예제 #1
0
class TransformationModule(PreprocessorModule):
    DEFAULT_SETTINGS = {
        'is_enabled': True,
        'method': 0,
    }

    PorterStemmer, SnowballStemmer, Lemmatizer = 0, 1, 2
    transformation_values = {
        PorterStemmer: PS,
        SnowballStemmer: SS,
        Lemmatizer: LM,
    }

    transformation_method = 0

    def __init__(self, data):
        data = data or self.DEFAULT_SETTINGS
        PreprocessorModule.__init__(
                self, 'Stemming', True,
                data.get('is_enabled')
        )

        self.group = QButtonGroup(self, exclusive=True)
        for method in [
            self.PorterStemmer,
            self.SnowballStemmer,
            self.Lemmatizer
        ]:
            rb = QRadioButton(
                    self,
                    text=self.transformation_values[method].name
            )
            self.add_to_content_area(rb)
            self.group.addButton(rb, method)
        self.group.buttonClicked.connect(self.group_button_clicked)

        # Restore the previous state, after starting off the layout.
        self.restore_data(data)

    def group_button_clicked(self):
        self.transformation_method = self.group.checkedId()
        self.notify_on_change()

    def restore_data(self, data):
        self.transformation_method = data.get('method')
        b = self.group.button(self.transformation_method)
        b.setChecked(True)

    def export_data(self):
        return {
            'is_enabled': self.enabled,
            'method': self.transformation_method,
        }

    def get_pp_setting(self):
        return {
            'transformation': self.transformation_values.get(
                    self.transformation_method
            )
        }
예제 #2
0
class RadioBooleanFilter(QWidget, Control):

    """ Boolean filter (Only/Exclude)
    """

    def __init__(self, tree, dataset, master, parent=None):
        QWidget.__init__(self, parent)
        Control.__init__(self, tree, dataset, master)

        self.setLayout(QVBoxLayout())
        self.buttonGroup = QButtonGroup(self)
        self.values = []
        for i, option in enumerate(tree.subelements_top("Option")):
            rb = QRadioButton(option.displayName, self)
            self.buttonGroup.addButton(rb)
            self.buttonGroup.setId(rb, i)
            self.layout().addWidget(rb)
            self.values.append(option.value)
        self.buttonGroup.button(0).setChecked(True)

    def value(self):
        return {"excluded": "%i" % self.buttonGroup.checkedId()}

    def get_filter(self):
        return self.tree.internalName, self.value()

    def query(self):
        return [("Filter", self.tree, self.value())]

    def setControlValue(self, name, value):
        for i, v in enumerate(self.values):
            if v == value:
                button = self.buttonGroup.button(i)
                button.setChecked(True)
                break
예제 #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
예제 #4
0
class RadioBooleanFilter(QWidget, Control):

    """ Boolean filter (Only/Exclude)
    """

    def __init__(self, tree, dataset, master, parent=None):
        QWidget.__init__(self, parent)
        Control.__init__(self, tree, dataset, master)

        self.setLayout(QVBoxLayout())
        self.buttonGroup = QButtonGroup(self)
        self.values = []
        for i, option in enumerate(tree.subelements_top("Option")):
            rb = QRadioButton(option.displayName, self)
            self.buttonGroup.addButton(rb)
            self.buttonGroup.setId(rb, i)
            self.layout().addWidget(rb)
            self.values.append(option.value)
        self.buttonGroup.button(0).setChecked(True)

    def value(self):
        return {"excluded": "%i" % self.buttonGroup.checkedId()}

    def get_filter(self):
        return self.tree.internalName, self.value()

    def query(self):
        return [("Filter", self.tree, self.value())]

    def setControlValue(self, name, value):
        for i, v in enumerate(self.values):
            if v == value:
                button = self.buttonGroup.button(i)
                button.setChecked(True)
                break
예제 #5
0
class TokenizerModule(PreprocessorModule):
    DEFAULT_SETTINGS = {
        'is_enabled': True,
        'method': 0,
    }

    NLTKTokenizer, NLTKPunctTokenizer, TwitterTokenizer = 0, 1, 2
    tokenizer_values = {
        NLTKTokenizer: 'default',
        NLTKPunctTokenizer: 'no_punct',
        TwitterTokenizer: 'twitter'
    }
    tokenizer_names = {
        NLTKTokenizer: 'NLTK tokenizer',
        NLTKPunctTokenizer: 'NLTK tokenizer (no punctuation)',
        TwitterTokenizer: 'Twitter tokenizer',
    }

    tokenizer_method = 0

    def __init__(self, data):
        data = data or self.DEFAULT_SETTINGS
        PreprocessorModule.__init__(
                self, 'Tokenizer', False,
                data.get('is_enabled')
        )

        self.group = QButtonGroup(self, exclusive=True)
        for method in [
            self.NLTKTokenizer,
            self.NLTKPunctTokenizer,
            self.TwitterTokenizer,
        ]:
            rb = QRadioButton(self, text=self.tokenizer_names[method])
            self.add_to_content_area(rb)
            self.group.addButton(rb, method)
        self.group.buttonClicked.connect(self.group_button_clicked)

        # Restore the previous state, after starting off the layout.
        self.restore_data(data)

    def group_button_clicked(self):
        self.tokenizer_method = self.group.checkedId()
        self.notify_on_change()

    def restore_data(self, data):
        self.tokenizer_method = data.get('method')
        b = self.group.button(self.tokenizer_method)
        b.setChecked(True)

    def export_data(self):
        return {
            'is_enabled': self.enabled,
            'method': self.tokenizer_method,
        }

    def get_pp_setting(self):
        return {
            'tokenizer': self.tokenizer_values.get(self.tokenizer_method)
        }
예제 #6
0
class ScopeBox(QGroupBox):
    title = None
    button_type = None

    def __init__(self):
        if self.title is None or self.button_type is None:
            raise Exception("Still too abstract!")

        super().__init__(title=self.title)

        self.populate_button_id()
        self.build_layout()
        self.populate_box()
        self.select_default()

        if self.button_type == 'check':
            self.group.setExclusive(False)

    def populate_button_id(self):
        pass

    def build_layout(self):
        self.group = QButtonGroup()
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

    def populate_box(self):
        keys = list(self.button_id.keys())
        keys.sort()

        BtnClass = None
        if self.button_type == 'check':
            BtnClass = QCheckBox
        elif self.button_type == 'radio':
            BtnClass = QRadioButton

        for key in keys:
            btn = BtnClass(key)
            self.layout.addWidget(btn)
            self.group.addButton(btn, self.button_id[key])

    def select_default(self):
        pass

    def getSelection(self):
        selection = None

        if self.button_type == 'radio':
            selection = self.group.checkedId()
        elif self.button_type == 'check':
            selection = []

            for btn in self.group.buttons():
                if btn.isChecked():
                    selection.append(btn.text())

        return selection
예제 #7
0
class TokenizerModule(PreprocessorModule):
    DEFAULT_SETTINGS = {
        'is_enabled': True,
        'method': 0,
    }

    NLTKTokenizer, NLTKPunctTokenizer, TwitterTokenizer = 0, 1, 2
    tokenizer_values = {
        NLTKTokenizer: 'default',
        NLTKPunctTokenizer: 'no_punct',
        TwitterTokenizer: 'twitter'
    }
    tokenizer_names = {
        NLTKTokenizer: 'NLTK tokenizer',
        NLTKPunctTokenizer: 'NLTK tokenizer (no punctuation)',
        TwitterTokenizer: 'Twitter tokenizer',
    }

    tokenizer_method = 0

    def __init__(self, data):
        data = data or self.DEFAULT_SETTINGS
        PreprocessorModule.__init__(self, 'Tokenizer', False,
                                    data.get('is_enabled'))

        self.group = QButtonGroup(self, exclusive=True)
        for method in [
                self.NLTKTokenizer,
                self.NLTKPunctTokenizer,
                self.TwitterTokenizer,
        ]:
            rb = QRadioButton(self, text=self.tokenizer_names[method])
            self.add_to_content_area(rb)
            self.group.addButton(rb, method)
        self.group.buttonClicked.connect(self.group_button_clicked)

        # Restore the previous state, after starting off the layout.
        self.restore_data(data)

    def group_button_clicked(self):
        self.tokenizer_method = self.group.checkedId()
        self.notify_on_change()

    def restore_data(self, data):
        self.tokenizer_method = data.get('method')
        b = self.group.button(self.tokenizer_method)
        b.setChecked(True)

    def export_data(self):
        return {
            'is_enabled': self.enabled,
            'method': self.tokenizer_method,
        }

    def get_pp_setting(self):
        return {'tokenizer': self.tokenizer_values.get(self.tokenizer_method)}
예제 #8
0
class TransformationModule(PreprocessorModule):
    DEFAULT_SETTINGS = {
        'is_enabled': True,
        'method': 0,
    }

    PorterStemmer, SnowballStemmer, Lemmatizer = 0, 1, 2
    transformation_values = {
        PorterStemmer: PS,
        SnowballStemmer: SS,
        Lemmatizer: LM,
    }

    transformation_method = 0

    def __init__(self, data):
        data = data or self.DEFAULT_SETTINGS
        PreprocessorModule.__init__(self, 'Stemming', True,
                                    data.get('is_enabled'))

        self.group = QButtonGroup(self, exclusive=True)
        for method in [
                self.PorterStemmer, self.SnowballStemmer, self.Lemmatizer
        ]:
            rb = QRadioButton(self,
                              text=self.transformation_values[method].name)
            self.add_to_content_area(rb)
            self.group.addButton(rb, method)
        self.group.buttonClicked.connect(self.group_button_clicked)

        # Restore the previous state, after starting off the layout.
        self.restore_data(data)

    def group_button_clicked(self):
        self.transformation_method = self.group.checkedId()
        self.notify_on_change()

    def restore_data(self, data):
        self.transformation_method = data.get('method')
        b = self.group.button(self.transformation_method)
        b.setChecked(True)

    def export_data(self):
        return {
            'is_enabled': self.enabled,
            'method': self.transformation_method,
        }

    def get_pp_setting(self):
        return {
            'transformation':
            self.transformation_values.get(self.transformation_method)
        }
예제 #9
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)
예제 #10
0
class SingleMethodModule(PreprocessorModule):
    method_index = settings.Setting(0)
    initialize_methods = True

    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)

    def get_value(self):
        self.method_index = self.group.checkedId()
        return self.methods[self.method_index]
예제 #11
0
class GroupSelectParameterWidget(GenericParameterWidget):
    """Widget class for Group Select Parameter."""
    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)

    def get_parameter(self):
        """Obtain list parameter object from the current widget state.

        :returns: A DefaultValueParameter from the current state of widget
        :rtype: DefaultValueParameter
        """
        # Set value for each key
        for key, value in self._parameter.options.items():
            if value.get('type') == STATIC:
                continue
            elif value.get('type') == SINGLE_DYNAMIC:
                new_value = self.spin_boxes.get(key).value()
                self._parameter.set_value_for_key(key, new_value)
            elif value.get('type') == MULTIPLE_DYNAMIC:
                # Need to iterate through all items
                items = []
                for index in xrange(self.list_widget.count()):
                    items.append(self.list_widget.item(index))
                new_value = [i.text() for i in items]
                self._parameter.set_value_for_key(key, new_value)

        # Get selected radio button
        radio_button_checked_id = self.input_button_group.checkedId()
        # No radio button checked, then default value = None
        if radio_button_checked_id == -1:
            self._parameter.selected = None
        else:
            self._parameter.selected = self._parameter.options.keys(
            )[radio_button_checked_id]

        return self._parameter

    def update_list_widget(self):
        """Update list widget when radio button is clicked."""
        # Get selected radio button
        radio_button_checked_id = self.input_button_group.checkedId()
        # No radio button checked, then default value = None
        if radio_button_checked_id > -1:
            selected_dict = self._parameter.options.values(
            )[radio_button_checked_id]
            if selected_dict.get('type') == MULTIPLE_DYNAMIC:
                for field in selected_dict.get('value'):
                    # Update list widget
                    field_item = QListWidgetItem(self.list_widget)
                    field_item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable
                                        | Qt.ItemIsDragEnabled)
                    field_item.setData(Qt.UserRole, field)
                    field_item.setText(field)
                    self.list_widget.addItem(field_item)

    def radio_buttons_clicked(self):
        """Handler when selected radio button changed."""
        # Disable all spin boxes
        for spin_box in self.spin_boxes.values():
            spin_box.setEnabled(False)
        # Disable list widget
        self.list_widget.setEnabled(False)

        # Get selected radio button
        radio_button_checked_id = self.input_button_group.checkedId()

        if radio_button_checked_id > -1:
            selected_value = self._parameter.options.values(
            )[radio_button_checked_id]
            if selected_value.get('type') == MULTIPLE_DYNAMIC:
                # Enable list widget
                self.list_widget.setEnabled(True)
            elif selected_value.get('type') == SINGLE_DYNAMIC:
                selected_key = self._parameter.options.keys(
                )[radio_button_checked_id]
                self.spin_boxes[selected_key].setEnabled(True)

    def select_radio_button(self, key):
        """Helper to select a radio button with key.

        :param key: The key of the radio button.
        :type key: str
        """
        key_index = self._parameter.options.keys().index(key)
        radio_button = self.input_button_group.button(key_index)
        radio_button.click()
예제 #12
0
class InterpolateConfirmDialog(QDialog):
    """
    Dialog class to confirm the interpolation
    """

    def __init__(self):
        """
        Constructor
        """
        QDialog.__init__(self)
        self.setWindowTitle(QCoreApplication.translate("VDLTools", "Edition Confirmation"))
        self.__layout = QGridLayout()

        self.__confirmLabel = QLabel(
            QCoreApplication.translate("VDLTools", "This LineString layer is not editable, what do you want to do ?"))

        self.__layout.addWidget(self.__confirmLabel, 0, 0, 1, 2)

        self.__radios = []

        self.__radios.append(QRadioButton(
            QCoreApplication.translate("VDLTools", "Create point, and edit line with new vertex")))
        self.__radios.append(QRadioButton(QCoreApplication.translate("VDLTools", "Create only the point")))
        self.__radios.append(QRadioButton(QCoreApplication.translate("VDLTools", "Just edit line with new vertex")))

        self.__scrollLayout = QGridLayout()

        self.__radios[0].setChecked(True)
        self.__radio_button_group = QButtonGroup()
        for i in range(len(self.__radios)):
            self.__scrollLayout.addWidget(self.__radios[i], i+1, 0, 1, 2)
            self.__radio_button_group.addButton(self.__radios[i], i)

        widget = QWidget()
        widget.setLayout(self.__scrollLayout)

        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        scroll.setWidget(widget)

        self.__layout.addWidget(scroll, 1, 0, 1, 2)

        self.__okButton = QPushButton(QCoreApplication.translate("VDLTools", "OK"))
        self.__okButton.setMinimumHeight(20)
        self.__okButton.setMinimumWidth(100)

        self.__layout.addWidget(self.__okButton, 4, 0)

        self.__cancelButton = QPushButton(QCoreApplication.translate("VDLTools", "Cancel"))
        self.__cancelButton.setMinimumHeight(20)
        self.__cancelButton.setMinimumWidth(100)

        self.__layout.addWidget(self.__cancelButton, 4, 1)

        self.setLayout(self.__layout)

    def setMainLabel(self, label):
        """
        To set the title
        :param label: title
        """
        self.__confirmLabel.setText(label)

    def setAllLabel(self, label):
        """
        To set the all button title
        :param label: title
        """
        self.__radios[0].setText(label)

    def setVtLabel(self, label):
        """
        To set the vertex button title
        :param label: title
        """
        self.__radios[2].setText(label)

    def getCheckedId(self):
        """
        To get the radio button checked id
        0 : all
        1 : point
        2 : vertex
        :return: id of radion button
        """
        return self.__radio_button_group.checkedId()

    def okButton(self):
        """
        To get the ok button instance
        :return: ok button instance
        """
        return self.__okButton

    def cancelButton(self):
        """
        To get the cancel button instance
        :return: cancel button instance
        """
        return self.__cancelButton
class DefaultSelectParameterWidget(SelectParameterWidget):

    """Widget class for Default Select Parameter."""

    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 raise_invalid_type_exception(self):
        message = 'Expecting element type of %s' % (
            self._parameter.element_type.__name__)
        err = ValueError(message)
        return err

    def get_parameter(self):
        """Obtain list parameter object from the current widget state.

        :returns: A DefaultSelectParameter from the current state of widget.
        """
        current_index = self.input.currentIndex()
        selected_value = self.input.itemData(current_index, Qt.UserRole)
        if hasattr(selected_value, 'toPyObject'):
            selected_value = selected_value.toPyObject()

        try:
            self._parameter.value = selected_value
        except ValueError:
            err = self.raise_invalid_type_exception()
            raise err

        radio_button_checked_id = self.default_input_button_group.checkedId()
        # No radio button checked, then default value = None
        if radio_button_checked_id == -1:
            self._parameter.default = None
        # The last radio button (custom) is checked, get the value from the
        # line edit
        elif (radio_button_checked_id ==
                len(self._parameter.default_values) - 1):
            self._parameter.default_values[radio_button_checked_id] \
                = self.custom_value.value()
            self._parameter.default = self.custom_value.value()
        else:
            self._parameter.default = self._parameter.default_values[
                radio_button_checked_id]

        return self._parameter

    def set_default(self, default):
        """Set default value by item's string.

        :param default: The default.
        :type default: str, int

        :returns: True if success, else False.
        :rtype: bool
        """
        # Find index of choice
        try:
            default_index = self._parameter.default_values.index(default)
            self.default_input_button_group.button(default_index).setChecked(
                True)
        except ValueError:
            last_index = len(self._parameter.default_values) - 1
            self.default_input_button_group.button(last_index).setChecked(
                True)
            self.custom_value.setValue(default)

        self.toggle_custom_value()

    def toggle_custom_value(self):
        radio_button_checked_id = self.default_input_button_group.checkedId()
        if (radio_button_checked_id ==
                len(self._parameter.default_values) - 1):
            self.custom_value.setDisabled(False)
        else:
            self.custom_value.setDisabled(True)

    def toggle_input(self):
        """Change behaviour of radio button based on input."""
        current_index = self.input.currentIndex()
        # If current input is not a radio button enabler, disable radio button.
        if self.input.itemData(current_index, Qt.UserRole) != (
                self.radio_button_enabler):
            self.disable_radio_button()
        # Otherwise, enable radio button.
        else:
            self.enable_radio_button()

    def set_selected_radio_button(self):
        """Set selected radio button to 'Do not report'."""
        dont_use_button = self.default_input_button_group.button(
            len(self._parameter.default_values) - 2)
        dont_use_button.setChecked(True)

    def disable_radio_button(self):
        """Disable radio button group and custom value input area."""
        checked = self.default_input_button_group.checkedButton()
        if checked:
            self.default_input_button_group.setExclusive(False)
            checked.setChecked(False)
            self.default_input_button_group.setExclusive(True)
        for button in self.default_input_button_group.buttons():
            button.setDisabled(True)
        self.custom_value.setDisabled(True)

    def enable_radio_button(self):
        """Enable radio button and custom value input area then set selected
        radio button to 'Do not report'.
        """
        for button in self.default_input_button_group.buttons():
            button.setEnabled(True)
        self.set_selected_radio_button()
        self.custom_value.setEnabled(True)
예제 #14
0
파일: dicom2fem.py 프로젝트: rc/dicom2fem
class MainWindow(QMainWindow):
    
    def __init__(self, dcmdir=None):
        QMainWindow.__init__(self)

        self.dcmdir = dcmdir
        self.dcm_3Ddata = None
        self.dcm_metadata = None
        self.dcm_zoom = None
        self.dcm_offsetmm = np.array([0,0,0])
        self.voxel_volume = 0.0
        self.voxel_sizemm = None
        self.segmentation_seeds = None
        self.segmentation_data = None
        self.mesh_data = None
        self.mesh_out_format = 'vtk'
        self.mesh_smooth_method = smooth_methods[0]
        self.initUI()
        
    def initUI(self):               

        cw = QWidget()
        self.setCentralWidget(cw)
        grid = QGridLayout()
        grid.setSpacing(15)
        
        # status bar
        self.statusBar().showMessage('Ready')

        font_label = QFont()
        font_label.setBold(True)

        ################ dicom reader
        rstart = 0
        text_dcm = QLabel('DICOM reader') 
        text_dcm.setFont(font_label)
        self.text_dcm_dir = QLabel('DICOM dir:')
        self.text_dcm_data = QLabel('DICOM data:')
        self.text_dcm_out = QLabel('output file:')
        grid.addWidget(text_dcm, rstart + 0, 1, 1, 4)
        grid.addWidget(self.text_dcm_dir, rstart + 1, 1, 1, 4)
        grid.addWidget(self.text_dcm_data, rstart + 2, 1, 1, 4)
        grid.addWidget(self.text_dcm_out, rstart + 3, 1, 1, 4)

        btn_dcmdir = QPushButton("Load DICOM", self)
        btn_dcmdir.clicked.connect(self.loadDcmDir)
        btn_dcmred = QPushButton("Reduce", self)
        btn_dcmred.clicked.connect(self.reduceDcm)
        btn_dcmcrop = QPushButton("Crop", self)
        btn_dcmcrop.clicked.connect(self.cropDcm)
        btn_dcmsave = QPushButton("Save DCM", self)
        btn_dcmsave.clicked.connect(self.saveDcm)
        grid.addWidget(btn_dcmdir, rstart + 4, 1)
        grid.addWidget(btn_dcmred, rstart + 4, 2)
        grid.addWidget(btn_dcmcrop, rstart + 4, 3)
        grid.addWidget(btn_dcmsave, rstart + 4, 4)

        hr = QFrame()
        hr.setFrameShape(QFrame.HLine)
        grid.addWidget(hr, rstart + 5, 0, 1, 6)

        ################ segmentation
        rstart = 6
        text_seg = QLabel('Segmentation') 
        text_seg.setFont(font_label)
        self.text_seg_in = QLabel('input data:')
        self.text_seg_data = QLabel('segment. data:')
        self.text_seg_out = QLabel('output file:')
        grid.addWidget(text_seg, rstart + 0, 1)
        grid.addWidget(self.text_seg_in, rstart + 1, 1, 1, 4)
        grid.addWidget(self.text_seg_data, rstart + 2, 1, 1, 4)
        grid.addWidget(self.text_seg_out, rstart + 3, 1, 1, 4)

        btn_segload = QPushButton("Load DCM", self)
        btn_segload.clicked.connect(self.loadDcm)
        btn_segauto = QPushButton("Automatic seg.", self)
        btn_segauto.clicked.connect(self.autoSeg)
        btn_segman = QPushButton("Manual seg.", self)
        btn_segman.clicked.connect(self.manualSeg)
        btn_segsave = QPushButton("Save SEG", self)
        btn_segsave.clicked.connect(self.saveSeg)
        grid.addWidget(btn_segload, rstart + 4, 1)
        grid.addWidget(btn_segauto, rstart + 4, 2)
        grid.addWidget(btn_segman, rstart + 4, 3)
        grid.addWidget(btn_segsave, rstart + 4, 4)

        hr = QFrame()
        hr.setFrameShape(QFrame.HLine)
        grid.addWidget(hr, rstart + 5, 0, 1, 6)

        ################ mesh gen.
        rstart = 12
        text_mesh = QLabel('Mesh generation') 
        text_mesh.setFont(font_label)
        self.text_mesh_in = QLabel('input data:')
        self.text_mesh_data = QLabel('mesh data:')
        self.text_mesh_out = QLabel('output file:')
        grid.addWidget(text_mesh, rstart + 0, 1)
        grid.addWidget(self.text_mesh_in, rstart + 1, 1, 1, 4)
        grid.addWidget(self.text_mesh_data, rstart + 2, 1, 1, 4)
        grid.addWidget(self.text_mesh_out, rstart + 3, 1, 1, 4)

        btn_meshload = QPushButton("Load SEG", self)
        btn_meshload.clicked.connect(self.loadSeg)
        btn_meshsave = QPushButton("Save MESH", self)
        btn_meshsave.clicked.connect(self.saveMesh)
        btn_meshgener = QPushButton("Generate", self)
        btn_meshgener.clicked.connect(self.generMesh)
        btn_meshsmooth = QPushButton("Smooth", self)
        btn_meshsmooth.clicked.connect(self.smoothMesh)
        btn_meshview = QPushButton("View", self)
        btn_meshview.clicked.connect(self.viewMesh)
        grid.addWidget(btn_meshload, rstart + 4, 1)
        grid.addWidget(btn_meshgener, rstart + 4, 2)
        grid.addWidget(btn_meshsmooth, rstart + 4, 3)
        grid.addWidget(btn_meshsave, rstart + 4, 4)
        grid.addWidget(btn_meshview, rstart + 8, 3, 1, 2)
        
        text_mesh_mesh = QLabel('mesh:')
        text_mesh_elements = QLabel('elements:')
        text_mesh_smooth = QLabel('smooth method:')
        text_mesh_output = QLabel('output format:')
        grid.addWidget(text_mesh_mesh, rstart + 6, 1)
        grid.addWidget(text_mesh_elements, rstart + 6, 2)
        grid.addWidget(text_mesh_smooth, rstart + 6, 3)
        grid.addWidget(text_mesh_output, rstart + 6, 4)
        
        rbtn_mesh_mesh_surf = QRadioButton('surface')
        rbtn_mesh_mesh_vol = QRadioButton('volume')
        grid.addWidget(rbtn_mesh_mesh_surf, rstart + 7, 1)
        grid.addWidget(rbtn_mesh_mesh_vol, rstart + 8, 1)
        self.rbtng_mesh_mesh = QButtonGroup(self)
        self.rbtng_mesh_mesh.addButton(rbtn_mesh_mesh_surf, 1)
        self.rbtng_mesh_mesh.addButton(rbtn_mesh_mesh_vol, 2)
        rbtn_mesh_mesh_vol.setChecked(True)

        rbtn_mesh_elements_3 = QRadioButton('tri/tetra')
        rbtn_mesh_elements_4 = QRadioButton('quad/hexa')
        grid.addWidget(rbtn_mesh_elements_3, rstart + 7, 2)
        grid.addWidget(rbtn_mesh_elements_4, rstart + 8, 2)
        self.rbtng_mesh_elements = QButtonGroup(self)
        self.rbtng_mesh_elements.addButton(rbtn_mesh_elements_3, 1)
        self.rbtng_mesh_elements.addButton(rbtn_mesh_elements_4, 2)
        rbtn_mesh_elements_4.setChecked(True)
        
        combo = QComboBox(self)
        combo.activated[str].connect(self.changeOut)
        
        supp_write = []
        for k, v in supported_capabilities.iteritems(): 
            if 'w' in v:
                supp_write.append(k)

        combo.addItems(supp_write)
        combo.setCurrentIndex(supp_write.index('vtk'))
        grid.addWidget(combo, rstart + 7, 4)

        combo2 = QComboBox(self)
        combo2.activated[str].connect(self.changeSmoothMethod)
        combo2.addItems(smooth_methods)
        combo2.setCurrentIndex(smooth_methods.index(self.mesh_smooth_method))
        grid.addWidget(combo2, rstart + 7, 3)

        hr = QFrame()
        hr.setFrameShape(QFrame.HLine)
        grid.addWidget(hr, rstart + 9, 0, 1, 6)
        
        # quit
        btn_quit = QPushButton("Quit", self)
        btn_quit.clicked.connect(self.quit)
        grid.addWidget(btn_quit, 24, 2, 1, 2)
        
        cw.setLayout(grid)
        self.setWindowTitle('DICOM2FEM')    
        self.show()

    def quit(self, event):
        self.close()

    def setLabelText(self, obj, text):
        dlab = str(obj.text())
        obj.setText(dlab[:dlab.find(':')] + ': %s' % text)
        
    def getDcmInfo(self):        
        vsize = tuple([float(ii) for ii in self.voxel_sizemm])
        ret = ' %dx%dx%d,  %fx%fx%f mm' % (self.dcm_3Ddata.shape + vsize)
        
        return ret
              
    def setVoxelVolume(self, vxs):
        self.voxel_volume = np.prod(vxs)

    def loadDcmDir(self):
        self.statusBar().showMessage('Reading DICOM directory...')
        QApplication.processEvents()

        if self.dcmdir is None:
            self.dcmdir = dcmreader.get_dcmdir_qt(app=True)

        if self.dcmdir is not None:
            dcr = dcmreader.DicomReader(os.path.abspath(self.dcmdir),
                                        qt_app=self)
        else:
            self.statusBar().showMessage('No DICOM directory specified!')
            return

        if dcr.validData():
            self.dcm_3Ddata = dcr.get_3Ddata()
            self.dcm_metadata = dcr.get_metaData()
            self.voxel_sizemm = np.array(self.dcm_metadata['voxelsizemm'])

            self.setVoxelVolume(self.voxel_sizemm)
            self.setLabelText(self.text_dcm_dir, self.dcmdir)
            self.setLabelText(self.text_dcm_data, self.getDcmInfo())
            self.statusBar().showMessage('Ready')
            self.setLabelText(self.text_seg_in, 'DICOM reader')
            
        else:
            self.statusBar().showMessage('No DICOM data in direcotry!')
            
    def reduceDcm(self, event=None, factor=None, default=0.25):
        if self.dcm_3Ddata is None:
            self.statusBar().showMessage('No DICOM data!')
            return

        self.statusBar().showMessage('Reducing DICOM data...')
        QApplication.processEvents()

        if factor is None:
            value, ok = QInputDialog.getText(self, 'Reduce DICOM data',
                                             'Reduce factor [0-1.0]:',
                                             text='%.2f' % default)
            if ok:
                vals = value.split(',')
                if len(vals) > 1:
                    factor = [float(ii) for ii in vals]

                else:
                    factor = float(value)

        if np.isscalar(factor):
            factor = [factor, factor, 1.0]

        self.dcm_zoom = np.array(factor[:3])
        for ii in factor:
           if ii < 0.0 or ii > 1.0:
               self.dcm_zoom = None
           
        if self.dcm_zoom is not None:
            self.dcm_3Ddata = ndimage.zoom(self.dcm_3Ddata, self.dcm_zoom,
                                           prefilter=False, mode='nearest')
            self.voxel_sizemm = self.voxel_sizemm / self.dcm_zoom
            self.setLabelText(self.text_dcm_data, self.getDcmInfo())

            self.statusBar().showMessage('Ready')

        else:
            self.statusBar().showMessage('No valid reduce factor!')

    def cropDcm(self):
        if self.dcm_3Ddata is None:
            self.statusBar().showMessage('No DICOM data!')
            return

        self.statusBar().showMessage('Cropping DICOM data...')
        QApplication.processEvents()

        is_reduced = False
        shape = self.dcm_3Ddata.shape
        max12 = np.max(shape[:2])
        if max12 > 128:
            is_reduced = True
            czoom = [128.0 / max12] * 2
            if shape[2] > 32:
                czoom.append(32.0 / shape[2])

            else:
                czoom.append(1.0)

            czoom = np.array(czoom)
            reduced_3Ddata = ndimage.zoom(self.dcm_3Ddata, czoom,
                                          prefilter=False, mode='nearest')
        else:
            reduced_3Ddata = self.dcm_3Ddata
             
        pyed = QTSeedEditor(reduced_3Ddata, mode='crop')
        pyed.exec_()
        nzs = pyed.getSeeds().nonzero()

        if nzs is not None:
            cri = []
            for ii in range(3):
                if nzs[ii].shape[0] == 0:
                    nzs = None
                    break
                smin, smax = np.min(nzs[ii]), np.max(nzs[ii])
                if smin == smax:
                    nzs = None
                    break

                cri.append((smin, smax))            
            cri = np.array(cri)

            if is_reduced and nzs is not None:
                aux = (cri.T * (1.0 / czoom)).T
                cri[:,0] = np.floor(aux[:,0])
                cri[:,1] = np.ceil(aux[:,1])

        if nzs is not None:
            crop = self.dcm_3Ddata[cri[0][0]:(cri[0][1] + 1),
                                   cri[1][0]:(cri[1][1] + 1),
                                   cri[2][0]:(cri[2][1] + 1)] 
            self.dcm_3Ddata = np.ascontiguousarray(crop)
            self.dcm_offsetmm = cri[:,0] * self.voxel_sizemm

            self.setLabelText(self.text_dcm_data, self.getDcmInfo())
            self.statusBar().showMessage('Ready')

        else:
            self.statusBar().showMessage('No crop information!')

    def saveDcm(self, event=None, filename=None):
        if self.dcm_3Ddata is not None:
            self.statusBar().showMessage('Saving DICOM data...')
            QApplication.processEvents()

            if filename is None:
                filename = str(QFileDialog.getSaveFileName(self, 'Save DCM file',
                                                           filter='Files (*.dcm)'))
            if len(filename) > 0:
                savemat(filename, {'data': self.dcm_3Ddata,
                                   'voxelsizemm': self.voxel_sizemm,
                                   'offsetmm': self.dcm_offsetmm},
                                   appendmat=False)

                self.setLabelText(self.text_dcm_out, filename)
                self.statusBar().showMessage('Ready')
            
            else:
                self.statusBar().showMessage('No output file specified!')

        else:
            self.statusBar().showMessage('No DICOM data!')      

    def loadDcm(self, event=None, filename=None):
        self.statusBar().showMessage('Loading DICOM data...')
        QApplication.processEvents()

        if filename is None:
            filename = str(QFileDialog.getOpenFileName(self, 'Load DCM file',
                                                       filter='Files (*.dcm)'))

        if len(filename) > 0:

            data = loadmat(filename,
                           variable_names=['data', 'voxelsizemm', 'offsetmm'],
                           appendmat=False)
            
            self.dcm_3Ddata = data['data']
            self.voxel_sizemm = data['voxelsizemm']
            self.dcm_offsetmm = data['offsetmm'] 
            self.setVoxelVolume(self.voxel_sizemm.reshape((3,)))
            self.setLabelText(self.text_seg_in, filename)
            self.statusBar().showMessage('Ready')
            
        else:
            self.statusBar().showMessage('No input file specified!')
            
    def checkSegData(self):
        if self.segmentation_data is None:
            self.statusBar().showMessage('No SEG data!')
            return

        nzs = self.segmentation_data.nonzero()
        nn = nzs[0].shape[0]
        if nn > 0:
            aux = ' voxels = %d, volume = %.2e mm3' % (nn, nn * self.voxel_volume)
            self.setLabelText(self.text_seg_data, aux)
            self.setLabelText(self.text_mesh_in, 'segmentation data')
            self.statusBar().showMessage('Ready')

        else:
            self.statusBar().showMessage('Zero SEG data!')

    def autoSeg(self):
        if self.dcm_3Ddata is None:
            self.statusBar().showMessage('No DICOM data!')
            return

        igc = pycat.ImageGraphCut(self.dcm_3Ddata,
                                  voxelsize=self.voxel_sizemm)

        pyed = QTSeedEditor(self.dcm_3Ddata,
                            seeds=self.segmentation_seeds,
                            modeFun=igc.interactivity_loop,
                            voxelVolume=self.voxel_volume)
        pyed.exec_()

        self.segmentation_data = pyed.getContours()
        self.segmentation_seeds = pyed.getSeeds()
        self.checkSegData()

    def manualSeg(self): 
        if self.dcm_3Ddata is None:
            self.statusBar().showMessage('No DICOM data!')
            return

        pyed = QTSeedEditor(self.dcm_3Ddata,
                            seeds=self.segmentation_data,
                            mode='draw',
                            voxelVolume=self.voxel_volume)
        pyed.exec_()

        self.segmentation_data = pyed.getSeeds()
        self.checkSegData()

    def saveSeg(self, event=None, filename=None):
        if self.segmentation_data is not None:
            self.statusBar().showMessage('Saving segmentation data...')
            QApplication.processEvents()

            if filename is None:
                filename = str(QFileDialog.getSaveFileName(self, 'Save SEG file',
                                                           filter='Files (*.seg)'))

            if len(filename) > 0:

                outdata = {'segdata': self.segmentation_data,
                            'voxelsizemm': self.voxel_sizemm,
                            'offsetmm': self.dcm_offsetmm}

                if self.segmentation_seeds is not None:
                    outdata['segseeds'] = self.segmentation_seeds

                savemat(filename, outdata, appendmat=False)
                self.setLabelText(self.text_seg_out, filename)
                self.statusBar().showMessage('Ready')

            else:
                self.statusBar().showMessage('No output file specified!')

        else:
            self.statusBar().showMessage('No segmentation data!')      

    def loadSeg(self, event=None, filename=None):
        if filename is None:
            filename = str(QFileDialog.getOpenFileName(self, 'Load SEG file',
                                                       filter='Files (*.seg)'))

        if len(filename) > 0:
            self.statusBar().showMessage('Loading segmentation data...')
            QApplication.processEvents()

            data = loadmat(filename,
                           variable_names=['segdata', 'segseeds',
                                           'voxelsizemm', 'offsetmm'],
                           appendmat=False)

            self.segmentation_data = data['segdata']
            if 'segseeds' in data:
                self.segmentation_seeds = data['segseeds']

            else:
                self.segmentation_seeds = None

            self.voxel_sizemm = data['voxelsizemm']
            self.dcm_offsetmm = data['offsetmm'] 
            self.setVoxelVolume(self.voxel_sizemm.reshape((3,)))
            self.setLabelText(self.text_mesh_in, filename)
            self.statusBar().showMessage('Ready')
            
        else:
            self.statusBar().showMessage('No input file specified!')

    def saveMesh(self, event=None, filename=None):
        if self.mesh_data is not None:
            self.statusBar().showMessage('Saving mesh...')
            QApplication.processEvents()

            if filename is None:
                file_ext = inv_supported_formats[self.mesh_out_format]
                filename = str(QFileDialog.getSaveFileName(self, 'Save MESH file',
                                                           filter='Files (*%s)' % file_ext))

            if len(filename) > 0:

                io = MeshIO.for_format(filename, format=self.mesh_out_format, writable=True)
                io.write(filename, self.mesh_data)

                self.setLabelText(self.text_mesh_out, filename)
                self.statusBar().showMessage('Ready')
            
            else:
                self.statusBar().showMessage('No output file specified!')

        else:
            self.statusBar().showMessage('No mesh data!')

    def generMesh(self):
        from seg2fem import gen_mesh_from_voxels

        etab = {1: 't', 2: 'q'}
        mtab = {1: 's', 2: 'v'}

        eid = self.rbtng_mesh_elements.checkedId()
        mid = self.rbtng_mesh_mesh.checkedId()
        self.statusBar().showMessage('Generating mesh...')
        QApplication.processEvents()
        
        self.mesh_data = gen_mesh_from_voxels(self.segmentation_data,
                                              self.voxel_sizemm * 1.0e-3,
                                              etype=etab[eid],
                                              mtype=mtab[mid])
        self.mesh_data.coors += self.dcm_offsetmm.reshape((1,3)) * 1.0e-3
        
        self.setLabelText(self.text_mesh_data, '%d %s'\
                          % (self.mesh_data.n_el,
                             elem_tab[self.mesh_data.descs[0]]))

        self.statusBar().showMessage('Ready')

    def smoothMesh(self):
        from seg2fem import gen_mesh_from_voxels_mc, smooth_mesh

        self.statusBar().showMessage('Smoothing mesh...')
        QApplication.processEvents()

        if self.mesh_smooth_method == 'marching cubes':
            self.mesh_data = gen_mesh_from_voxels_mc(self.segmentation_data,
                                                     self.voxel_sizemm * 1.0e-3)
            self.mesh_data.coors += self.dcm_offsetmm.reshape((1,3)) * 1.0e-3

        elif self.mesh_smooth_method == 'taubin':
            mid = self.rbtng_mesh_mesh.checkedId()
            if mid == 'v':
                 volume_corr=True

            else:
                volume_corr=False

            self.mesh_data.coors = smooth_mesh(self.mesh_data,
                                               n_iter=10, lam=0.6307, mu=-0.6347,
                                               volume_corr=volume_corr)
            
        self.setLabelText(self.text_mesh_data, '%d %s, smooth method - %s'\
                          % (self.mesh_data.n_el,
                             elem_tab[self.mesh_data.descs[0]],
                              self.mesh_smooth_method))

        self.statusBar().showMessage('Ready')
    
    def viewMesh(self):
        if self.mesh_data is not None:
            vtk_file = 'mesh_geom.vtk'
            self.mesh_data.write(vtk_file)
            view = QVTKViewer(vtk_file)
            view.exec_()

        else:
            self.statusBar().showMessage('No mesh data!')

    def changeOut(self, val):
        self.mesh_out_format = str(val)

    def changeSmoothMethod(self, val):
        self.mesh_smooth_method = str(val)
class GroupSelectParameterWidget(GenericParameterWidget):

    """Widget class for Group Select Parameter."""

    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)

    def get_parameter(self):
        """Obtain list parameter object from the current widget state.

        :returns: A DefaultValueParameter from the current state of widget
        :rtype: DefaultValueParameter
        """
        # Set value for each key
        for key, value in self._parameter.options.items():
            if value.get('type') == STATIC:
                continue
            elif value.get('type') == SINGLE_DYNAMIC:
                new_value = self.spin_boxes.get(key).value()
                self._parameter.set_value_for_key(key, new_value)
            elif value.get('type') == MULTIPLE_DYNAMIC:
                # Need to iterate through all items
                items = []
                for index in xrange(self.list_widget.count()):
                    items.append(self.list_widget.item(index))
                new_value = [i.text() for i in items]
                self._parameter.set_value_for_key(key, new_value)

        # Get selected radio button
        radio_button_checked_id = self.input_button_group.checkedId()
        # No radio button checked, then default value = None
        if radio_button_checked_id == -1:
            self._parameter.selected = None
        else:
            self._parameter.selected = self._parameter.options.keys()[
                radio_button_checked_id]

        return self._parameter

    def update_list_widget(self):
        """Update list widget when radio button is clicked."""
        # Get selected radio button
        radio_button_checked_id = self.input_button_group.checkedId()
        # No radio button checked, then default value = None
        if radio_button_checked_id > -1:
            selected_dict = self._parameter.options.values()[
                radio_button_checked_id]
            if selected_dict.get('type') == MULTIPLE_DYNAMIC:
                for field in selected_dict.get('value'):
                    # Update list widget
                    field_item = QListWidgetItem(self.list_widget)
                    field_item.setFlags(
                        Qt.ItemIsEnabled |
                        Qt.ItemIsSelectable |
                        Qt.ItemIsDragEnabled)
                    field_item.setData(Qt.UserRole, field)
                    field_item.setText(field)
                    self.list_widget.addItem(field_item)

    def radio_buttons_clicked(self):
        """Handler when selected radio button changed."""
        # Disable all spin boxes
        for spin_box in self.spin_boxes.values():
            spin_box.setEnabled(False)
        # Disable list widget
        self.list_widget.setEnabled(False)

        # Get selected radio button
        radio_button_checked_id = self.input_button_group.checkedId()

        if radio_button_checked_id > -1:
            selected_value = self._parameter.options.values()[
                radio_button_checked_id]
            if selected_value.get('type') == MULTIPLE_DYNAMIC:
                # Enable list widget
                self.list_widget.setEnabled(True)
            elif selected_value.get('type') == SINGLE_DYNAMIC:
                selected_key = self._parameter.options.keys()[
                    radio_button_checked_id]
                self.spin_boxes[selected_key].setEnabled(True)

    def select_radio_button(self, key):
        """Helper to select a radio button with key.

        :param key: The key of the radio button.
        :type key: str
        """
        key_index = self._parameter.options.keys().index(key)
        radio_button = self.input_button_group.button(key_index)
        radio_button.click()
예제 #16
0
    def restore_or_create(self):
        vbox = QVBoxLayout()

        main_label = QLabel(_("Electrum-VCN could not find an existing wallet."))
        vbox.addWidget(main_label)

        grid = QGridLayout()
        grid.setSpacing(5)

        gb1 = QGroupBox(_("What do you want to do?"))
        vbox.addWidget(gb1)
        vbox1 = QVBoxLayout()
        gb1.setLayout(vbox1)

        b1 = QRadioButton(gb1)
        b1.setText(_("Create new wallet"))
        b1.setChecked(True)

        b2 = QRadioButton(gb1)
        b2.setText(_("Restore a wallet or import keys"))

        group1 = QButtonGroup()
        group1.addButton(b1)
        group1.addButton(b2)
        vbox1.addWidget(b1)
        vbox1.addWidget(b2)

        gb2 = QGroupBox(_("Wallet type:"))
        vbox.addWidget(gb2)

        vbox2 = QVBoxLayout()
        gb2.setLayout(vbox2)

        group2 = QButtonGroup()

        self.wallet_types = [
            ('standard', _("Standard wallet")),
            ('twofactor', _("Wallet with two-factor authentication")),
            ('multisig', _("Multi-signature wallet")),
            ('hardware', _("Hardware wallet")),
        ]

        for i, (wtype, name) in enumerate(self.wallet_types):
            if not filter(lambda x: x[0] == wtype, electrum.wallet.wallet_types):
                continue
            button = QRadioButton(gb2)
            button.setText(name)
            vbox2.addWidget(button)
            group2.addButton(button)
            group2.setId(button, i)

            if i == 0:
                button.setChecked(True)

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

        if not self.exec_():
            return None, None

        action = 'create' if b1.isChecked() else 'restore'
        wallet_type = self.wallet_types[group2.checkedId()][0]
        return action, wallet_type
class DefaultValueParameterWidget(GenericParameterWidget):

    """Widget class for Default Value Parameter."""

    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)

    def raise_invalid_type_exception(self):
        """Raise invalid type."""
        message = 'Expecting element type of %s' % (
            self._parameter.element_type.__name__)
        err = ValueError(message)
        return err

    def get_parameter(self):
        """Obtain list parameter object from the current widget state.

        :returns: A DefaultValueParameter from the current state of widget
        :rtype: DefaultValueParameter
        """
        radio_button_checked_id = self.input_button_group.checkedId()
        # No radio button checked, then default value = None
        if radio_button_checked_id == -1:
            self._parameter.value = None
        # The last radio button (custom) is checked, get the value from the
        # line edit
        elif radio_button_checked_id == len(self._parameter.options) - 1:
            self._parameter.options[radio_button_checked_id] = \
                self.custom_value.value()
            self._parameter.value = self.custom_value.value()
        else:
            self._parameter.value = self._parameter.options[
                radio_button_checked_id]

        return self._parameter

    def set_value(self, value):
        """Set value by item's string.

        :param value: The value.
        :type value: str, int

        :returns: True if success, else False.
        :rtype: bool
        """
        # Find index of choice
        try:
            value_index = self._parameter.options.index(value)
            self.input_button_group.button(value_index).setChecked(True)
        except ValueError:
            last_index = len(self._parameter.options) - 1
            self.input_button_group.button(last_index).setChecked(
                True)
            self.custom_value.setValue(value)

        self.toggle_custom_value()

    def toggle_custom_value(self):
        """Enable or disable the custom value line edit."""
        radio_button_checked_id = self.input_button_group.checkedId()
        if (radio_button_checked_id ==
                len(self._parameter.options) - 1):
            self.custom_value.setDisabled(False)
        else:
            self.custom_value.setDisabled(True)
예제 #18
0
class DuplicateDistanceDialog(QDialog):
    """
    Dialog class to choose the duplicate distance
    """

    def __init__(self, isComplexPolygon):
        """
        Constructor
        :param isComplexPolygon: for a polygon, if it has interior ring(s)
        """
        QDialog.__init__(self)
        self.setWindowTitle(QCoreApplication.translate("VDLTools", "Duplicate"))
        self.resize(300, 100)
        self.__distanceLabel = QLabel(QCoreApplication.translate("VDLTools", "distance :"))
        self.__distanceLabel.setMinimumHeight(20)
        self.__distanceLabel.setMinimumWidth(50)

        self.__distanceEdit = QLineEdit("inputMask")
        self.__distanceEdit.setMinimumHeight(20)
        self.__distanceEdit.setMinimumWidth(120)
        self.__distanceEdit.setValidator(QDoubleValidator(-1000, 1000, 4, self))

        self.__distanceDirection = QCheckBox(QCoreApplication.translate("VDLTools", "invert direction"))

        self.__previewButton = QPushButton(QCoreApplication.translate("VDLTools", "Preview"))
        self.__previewButton.setMinimumHeight(20)
        self.__previewButton.setMinimumWidth(100)

        self.__okButton = QPushButton(QCoreApplication.translate("VDLTools", "OK"))
        self.__okButton.setMinimumHeight(20)
        self.__okButton.setMinimumWidth(100)

        self.__cancelButton = QPushButton(QCoreApplication.translate("VDLTools", "Cancel"))
        self.__cancelButton.setMinimumHeight(20)
        self.__cancelButton.setMinimumWidth(100)

        self.__layout = QGridLayout()
        self.__layout.addWidget(self.__distanceLabel, 0, 0)
        self.__layout.addWidget(self.__distanceEdit, 0, 1)
        self.__layout.addWidget(self.__distanceDirection, 0, 2)

        if isComplexPolygon:
            self.__polygonLabel = QLabel(
                QCoreApplication.translate("VDLTools", "In which direction the internal part has to be duplicated ?"))
            self.__polygonLabel.setMinimumHeight(20)
            self.__polygonLabel.setMinimumWidth(50)
            self.__layout.addWidget(self.__polygonLabel, 1, 0, 1, 3)

            self.__directions = [QRadioButton(QCoreApplication.translate("VDLTools", "same")),
                                 QRadioButton(QCoreApplication.translate("VDLTools", "opposite"))]
            self.__directions[0].setChecked(True)
            self.__direction_button_group = QButtonGroup()
            for i in range(len(self.__directions)):
                self.__layout.addWidget(self.__directions[i], 2, i+1)
                self.__direction_button_group.addButton(self.__directions[i], i)

        self.__layout.addWidget(self.__previewButton, 3, 0)
        self.__layout.addWidget(self.__okButton, 3, 1)
        self.__layout.addWidget(self.__cancelButton, 3, 2)
        self.setLayout(self.__layout)

    def previewButton(self):
        """
        To get the preview button instance
        :return: preview button instance
        """
        return self.__previewButton

    def okButton(self):
        """
        To get the ok button instance
        :return: ok button instance
        """
        return self.__okButton

    def cancelButton(self):
        """
        To get the cancel button instance
        :return: cancel button instance
        """
        return self.__cancelButton

    def distanceEdit(self):
        """
        To get the distance edit widget
        :return: distance edit widget
        """
        return self.__distanceEdit

    def directionCheck(self):
        """
        To get the direction check button
        :return: direction check button
        """
        return self.__distanceDirection

    def isInverted(self):
        """
        To get if the user want a complex polygon duplication inverted or not
        :return: true if inverted, false otherwise
        """
        return self.__direction_button_group.checkedId() == 1
예제 #19
0
class DuplicateDistanceDialog(QDialog):
    """
    Dialog class to choose the duplicate distance
    """
    def __init__(self, isComplexPolygon):
        """
        Constructor
        :param isComplexPolygon: for a polygon, if it has interior ring(s)
        """
        QDialog.__init__(self)
        self.setWindowTitle(QCoreApplication.translate("VDLTools",
                                                       "Duplicate"))
        self.resize(300, 100)
        self.__distanceLabel = QLabel(
            QCoreApplication.translate("VDLTools", "distance :"))
        self.__distanceLabel.setMinimumHeight(20)
        self.__distanceLabel.setMinimumWidth(50)

        self.__distanceEdit = QLineEdit("inputMask")
        self.__distanceEdit.setMinimumHeight(20)
        self.__distanceEdit.setMinimumWidth(120)
        self.__distanceEdit.setValidator(QDoubleValidator(
            -1000, 1000, 4, self))

        self.__distanceDirection = QCheckBox(
            QCoreApplication.translate("VDLTools", "invert direction"))

        self.__previewButton = QPushButton(
            QCoreApplication.translate("VDLTools", "Preview"))
        self.__previewButton.setMinimumHeight(20)
        self.__previewButton.setMinimumWidth(100)

        self.__okButton = QPushButton(
            QCoreApplication.translate("VDLTools", "OK"))
        self.__okButton.setMinimumHeight(20)
        self.__okButton.setMinimumWidth(100)

        self.__cancelButton = QPushButton(
            QCoreApplication.translate("VDLTools", "Cancel"))
        self.__cancelButton.setMinimumHeight(20)
        self.__cancelButton.setMinimumWidth(100)

        self.__layout = QGridLayout()
        self.__layout.addWidget(self.__distanceLabel, 0, 0)
        self.__layout.addWidget(self.__distanceEdit, 0, 1)
        self.__layout.addWidget(self.__distanceDirection, 0, 2)

        if isComplexPolygon:
            self.__polygonLabel = QLabel(
                QCoreApplication.translate(
                    "VDLTools",
                    "In which direction the internal part has to be duplicated ?"
                ))
            self.__polygonLabel.setMinimumHeight(20)
            self.__polygonLabel.setMinimumWidth(50)
            self.__layout.addWidget(self.__polygonLabel, 1, 0, 1, 3)

            self.__directions = [
                QRadioButton(QCoreApplication.translate("VDLTools", "same")),
                QRadioButton(QCoreApplication.translate(
                    "VDLTools", "opposite"))
            ]
            self.__directions[0].setChecked(True)
            self.__direction_button_group = QButtonGroup()
            for i in range(len(self.__directions)):
                self.__layout.addWidget(self.__directions[i], 2, i + 1)
                self.__direction_button_group.addButton(
                    self.__directions[i], i)

        self.__layout.addWidget(self.__previewButton, 3, 0)
        self.__layout.addWidget(self.__okButton, 3, 1)
        self.__layout.addWidget(self.__cancelButton, 3, 2)
        self.setLayout(self.__layout)

    def previewButton(self):
        """
        To get the preview button instance
        :return: preview button instance
        """
        return self.__previewButton

    def okButton(self):
        """
        To get the ok button instance
        :return: ok button instance
        """
        return self.__okButton

    def cancelButton(self):
        """
        To get the cancel button instance
        :return: cancel button instance
        """
        return self.__cancelButton

    def distanceEdit(self):
        """
        To get the distance edit widget
        :return: distance edit widget
        """
        return self.__distanceEdit

    def directionCheck(self):
        """
        To get the direction check button
        :return: direction check button
        """
        return self.__distanceDirection

    def isInverted(self):
        """
        To get if the user want a complex polygon duplication inverted or not
        :return: true if inverted, false otherwise
        """
        return self.__direction_button_group.checkedId() == 1
예제 #20
0
class DefaultSelectParameterWidget(SelectParameterWidget):
    """Widget class for Default Select Parameter."""
    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 raise_invalid_type_exception(self):
        message = 'Expecting element type of %s' % (
            self._parameter.element_type.__name__)
        err = ValueError(message)
        return err

    def get_parameter(self):
        """Obtain list parameter object from the current widget state.

        :returns: A DefaultSelectParameter from the current state of widget.
        """
        current_index = self.input.currentIndex()
        selected_value = self.input.itemData(current_index, Qt.UserRole)
        if hasattr(selected_value, 'toPyObject'):
            selected_value = selected_value.toPyObject()

        try:
            self._parameter.value = selected_value
        except ValueError:
            err = self.raise_invalid_type_exception()
            raise err

        radio_button_checked_id = self.default_input_button_group.checkedId()
        # No radio button checked, then default value = None
        if radio_button_checked_id == -1:
            self._parameter.default = None
        # The last radio button (custom) is checked, get the value from the
        # line edit
        elif (radio_button_checked_id == len(self._parameter.default_values) -
              1):
            self._parameter.default_values[radio_button_checked_id] \
                = self.custom_value.value()
            self._parameter.default = self.custom_value.value()
        else:
            self._parameter.default = self._parameter.default_values[
                radio_button_checked_id]

        return self._parameter

    def set_default(self, default):
        """Set default value by item's string.

        :param default: The default.
        :type default: str, int

        :returns: True if success, else False.
        :rtype: bool
        """
        # Find index of choice
        try:
            default_index = self._parameter.default_values.index(default)
            self.default_input_button_group.button(default_index).setChecked(
                True)
        except ValueError:
            last_index = len(self._parameter.default_values) - 1
            self.default_input_button_group.button(last_index).setChecked(True)
            self.custom_value.setValue(default)

        self.toggle_custom_value()

    def toggle_custom_value(self):
        radio_button_checked_id = self.default_input_button_group.checkedId()
        if (radio_button_checked_id == len(self._parameter.default_values) -
                1):
            self.custom_value.setDisabled(False)
        else:
            self.custom_value.setDisabled(True)

    def toggle_input(self):
        """Change behaviour of radio button based on input."""
        current_index = self.input.currentIndex()
        # If current input is not a radio button enabler, disable radio button.
        if self.input.itemData(current_index,
                               Qt.UserRole) != (self.radio_button_enabler):
            self.disable_radio_button()
        # Otherwise, enable radio button.
        else:
            self.enable_radio_button()

    def set_selected_radio_button(self):
        """Set selected radio button to 'Do not report'."""
        dont_use_button = self.default_input_button_group.button(
            len(self._parameter.default_values) - 2)
        dont_use_button.setChecked(True)

    def disable_radio_button(self):
        """Disable radio button group and custom value input area."""
        checked = self.default_input_button_group.checkedButton()
        if checked:
            self.default_input_button_group.setExclusive(False)
            checked.setChecked(False)
            self.default_input_button_group.setExclusive(True)
        for button in self.default_input_button_group.buttons():
            button.setDisabled(True)
        self.custom_value.setDisabled(True)

    def enable_radio_button(self):
        """Enable radio button and custom value input area then set selected
        radio button to 'Do not report'.
        """
        for button in self.default_input_button_group.buttons():
            button.setEnabled(True)
        self.set_selected_radio_button()
        self.custom_value.setEnabled(True)
예제 #21
0
class BoundingBoxBox(QGroupBox):

    def __init__(self, id):
        QGroupBox.__init__(self)
        self.id = id
        self.setTitle("Adjust bounding box")
        self.setToolTip("<p>Adjust plot bounding box (leave "
                            "unchecked to use default)</p>")
        self.setCheckable(True)
        self.setChecked(False)
        self.buttonGroup = QButtonGroup(self)
        self.buttonNames = []
        hbox = HBoxLayout()
        id = 0
        button = QToolButton()
        button.setToolTip("Outline")
        self.buttonNames.append("o")
        button.setIcon(QIcon(":custom-chart-outline.svg"))
        button.setCheckable(True)
        button.setChecked(True)
        self.buttonGroup.addButton(button, id)
        hbox.addWidget(button)
        id += 1
        button = QToolButton()
        button.setToolTip("L shape")
        self.buttonNames.append("l")
        button.setIcon(QIcon(":custom-chart-l-shape.svg"))
        button.setCheckable(True)
        self.buttonGroup.addButton(button, id)
        hbox.addWidget(button)
        id += 1
        button = QToolButton()
        button.setToolTip("7 shape")
        self.buttonNames.append("7")
        button.setIcon(QIcon(":custom-chart-7-shape.svg"))
        button.setCheckable(True)
        self.buttonGroup.addButton(button, id)
        hbox.addWidget(button)
        id += 1
        button = QToolButton()
        button.setToolTip("C shape")
        self.buttonNames.append("c")
        button.setIcon(QIcon(":custom-chart-c-shape.svg"))
        button.setCheckable(True)
        self.buttonGroup.addButton(button, id)
        hbox.addWidget(button)
        id += 1
        button = QToolButton()
        button.setToolTip("U shape")
        self.buttonNames.append("u")
        button.setCheckable(True)
        button.setIcon(QIcon(":custom-chart-u-shape.svg"))
        self.buttonGroup.addButton(button, id)
        hbox.addWidget(button)
        id += 1
        button = QToolButton()
        button.setToolTip("] shape")
        self.buttonNames.append("]")
        button.setIcon(QIcon(":custom-chart-]-shape.svg"))
        button.setCheckable(True)
        self.buttonGroup.addButton(button, id)
        hbox.addWidget(button)
        id += 1
        button = QToolButton()
        button.setToolTip("None")
        self.buttonNames.append("n")
        button.setIcon(QIcon())
        button.setCheckable(True)
        self.buttonGroup.addButton(button, id)
        hbox.addWidget(button)

        self.setLayout(hbox)

    def parameterValues(self):
        params = QString()
        if self.isChecked():
            params.append(", bty='%s'" % str(self.buttonNames[
                self.buttonGroup.checkedId()]))
        return {self.id:params}
예제 #22
0
class PlotTypeBox(QGroupBox):

    def __init__(self, id):
        QGroupBox.__init__(self)
        self.id = id
        self.setTitle("Adjust plot type")
        self.setToolTip("<p>Adjust plot type (leave "
                            "unchecked to use default)</p>")
        self.setCheckable(True)
        self.setChecked(False)
        self.buttonGroup = QButtonGroup(self)
        self.buttonNames = []
        hbox = HBoxLayout()
        id = 0
        button = QToolButton()
        button.setToolTip("Points")
        self.buttonNames.append("p")
        button.setIcon(QIcon(":custom-chart-point.svg"))
        button.setCheckable(True)
        button.setChecked(True)
        self.buttonGroup.addButton(button, id)
        hbox.addWidget(button)
        id += 1
        button = QToolButton()
        button.setToolTip("Lines")
        self.buttonNames.append("l")
        button.setIcon(QIcon(":custom-chart-line.svg"))
        button.setCheckable(True)
        self.buttonGroup.addButton(button, id)
        hbox.addWidget(button)
        id += 1
        button = QToolButton()
        button.setToolTip("Both")
        self.buttonNames.append("b")
        button.setIcon(QIcon(":custom-chart-both.svg"))
        button.setCheckable(True)
        self.buttonGroup.addButton(button, id)
        hbox.addWidget(button)
        id += 1
        button = QToolButton()
        button.setToolTip("Overplotted")
        self.buttonNames.append("o")
        button.setIcon(QIcon(":custom-chart-overplotted.svg"))
        button.setCheckable(True)
        self.buttonGroup.addButton(button, id)
        hbox.addWidget(button)
        id += 1
        button = QToolButton()
        button.setToolTip("Histogram")
        self.buttonNames.append("h")
        button.setIcon(QIcon(":custom-chart-hist.svg"))
        button.setCheckable(True)
        self.buttonGroup.addButton(button, id)
        hbox.addWidget(button)
        id += 1
        button = QToolButton()
        button.setToolTip("Stair steps")
        self.buttonNames.append("s")
        button.setIcon(QIcon(":custom-chart-stairs.svg"))
        button.setCheckable(True)
        self.buttonGroup.addButton(button, id)
        hbox.addWidget(button)
        id += 1
        button = QToolButton()
        button.setToolTip("No plotting")
        self.buttonNames.append("n")
        button.setIcon(QIcon())
        button.setCheckable(True)
        self.buttonGroup.addButton(button, id)
        hbox.addWidget(button)

        self.setLayout(hbox)

    def parameterValues(self):
        params = QString()
        if self.isChecked():
            params = "'%s'" % str(self.buttonNames[
                self.buttonGroup.checkedId()])
        return {self.id:params}
예제 #23
0
class DefaultValueParameterWidget(GenericParameterWidget):

    """Widget class for Default Value Parameter."""

    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)

    def raise_invalid_type_exception(self):
        """Raise invalid type."""
        message = 'Expecting element type of %s' % (
            self._parameter.element_type.__name__)
        err = ValueError(message)
        return err

    def get_parameter(self):
        """Obtain list parameter object from the current widget state.

        :returns: A DefaultValueParameter from the current state of widget
        :rtype: DefaultValueParameter
        """
        radio_button_checked_id = self.input_button_group.checkedId()
        # No radio button checked, then default value = None
        if radio_button_checked_id == -1:
            self._parameter.value = None
        # The last radio button (custom) is checked, get the value from the
        # line edit
        elif radio_button_checked_id == len(self._parameter.options) - 1:
            self._parameter.options[radio_button_checked_id] = \
                self.custom_value.value()
            self._parameter.value = self.custom_value.value()
        else:
            self._parameter.value = self._parameter.options[
                radio_button_checked_id]

        return self._parameter

    def set_value(self, value):
        """Set value by item's string.

        :param value: The value.
        :type value: str, int

        :returns: True if success, else False.
        :rtype: bool
        """
        # Find index of choice
        try:
            value_index = self._parameter.options.index(value)
            self.input_button_group.button(value_index).setChecked(True)
        except ValueError:
            last_index = len(self._parameter.options) - 1
            self.input_button_group.button(last_index).setChecked(
                True)
            self.custom_value.setValue(value)

        self.toggle_custom_value()

    def toggle_custom_value(self):
        """Enable or disable the custom value line edit."""
        radio_button_checked_id = self.input_button_group.checkedId()
        if (radio_button_checked_id ==
                len(self._parameter.options) - 1):
            self.custom_value.setDisabled(False)
        else:
            self.custom_value.setDisabled(True)
예제 #24
0
파일: authent.py 프로젝트: maximerobin/Ufwi
class AuthenticationFrontend(ScrollArea):
    COMPONENT = 'auth_cert'
    LABEL = tr('Authentication server')
    REQUIREMENTS = ('auth_cert',)
    ICON = ':/icons/auth_protocol.png'

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

        self.qauthcertobject = QAuthCertObject.getInstance()

        frame = QFrame(self)

        layout = QVBoxLayout(frame)

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

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

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

        self.mainwindow.writeAccessNeeded(self.strictCheckBox)

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


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

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

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

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

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


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

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

        self.resetConf()
        self.__loading = False

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

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

    def isModified(self):
        return self.modified

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

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

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

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

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

        if not auth_cert_loaded:
            return


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

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

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

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

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

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

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

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

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

    def onApplyFinished(self):
        self.pki_widget.feed()