예제 #1
0
    def __init__(self, parent, **params):
        get_or_put(params, 'layout', QVBoxLayout())
        get_or_put(params, 'i18n_def', 'Miscellaneous')
        super(MiscellaneousWidget, self).__init__(parent, **params)

        LabelWidget(self, i18n_def='Data window shift: 1')
        self.params = Params(**params)
        self.params.data_accessor.addListener(self,
                                    __MiscellaneousVectorListener__(self))
        self.__window_size__ = __DataWindowSizeWidget__(self,
                                                self.params.data_accessor)

        self.__unitsWidget__ = TimeUnitsWidget(self, i18n_def='Units',
                        default_unit=self.params.data_accessor.signal_x_unit,
                        change_unit_handler=self.changeUnit,
                        layout=QHBoxLayout())
        self.__unitsWidget__.addUnit(OrderUnit)

        self.__use_parameters__ = CompositeWidget(self, layout=QHBoxLayout())
        self.__use_buffer__ = CheckBoxWidget(self.__use_parameters__,
                                             i18n_def='Use buffer',
                                             checked=True)
        self.__use_identity_line__ = CheckBoxWidget(self.__use_parameters__,
                                             i18n_def='Use identity line',
                                             checked=True)

        self.__sample_step__ = __SampleStepWidget__(self,
                                                self.params.data_accessor)

        self.__stepper_size__ = __StepperSizeWidget__(self,
                                                self.params.data_accessor)
예제 #2
0
    def __init__(self, parent, **params):
        get_or_put(params, 'layout', QHBoxLayout())
        self.params = Params(**params)
        self.data_accessor = self.params.data_accessor  # alias
        i18n_def = "Square filter " + self.data_accessor.signal_unit.display_label # @IgnorePep8
        super(SquareFilterWidget, self).__init__(parent, i18n_def=i18n_def,
                                                     **params)

        self.__filter__ = SquareFilter()

        LabelWidget(self, i18n_def="Min value")
        self.__min_value__ = NumberEditWidget(self,
                                    text_changed_handler=self.__min_handler__)
        LabelWidget(self, i18n_def="Max value")
        self.__max_value__ = NumberEditWidget(self,
                                    text_changed_handler=self.__max_handler__)

        if self.params.use_apply_button:
            self.__action_button__ = PushButtonWidget(self, i18n_def='Apply',
                                clicked_handler=self.__filter_handler__)
        else:
            self.__action_button__ = CheckBoxWidget(self,
                            i18n_def='Use filter',
                            clicked_handler=self.__use_handler__)
            self.data_accessor.addListener(self,
                                    __SquareFilterDataVectorListener__(self))
            self.__action_button__.setChecked(False)

        self.reset()
예제 #3
0
    def __init__(self, parent, **params):
        get_or_put(params, 'i18n', 'time.units.group.title')
        get_or_put(params, 'i18n_def', 'Time units')
        get_or_put(params, 'layout', QHBoxLayout())
        self.default_unit = params.get('default_unit', Millisecond)
        super(TimeUnitsWidget, self).__init__(parent, **params)
        self.__unitsButtonsGroup__ = ButtonGroupWidget(self)
        self.__change_unit_handler__ = params.get('change_unit_handler', None)

        for time_unit in get_units_for_type(TimeUnit):
            unitCheckBox = CheckBoxWidget(self,
                                          i18n_def="%s [%s]" %
                                          (time_unit.name, time_unit.label))

            #add artificially property unit for later use in getUnit method
            unitCheckBox.unit = time_unit

            if time_unit == self.default_unit:
                unitCheckBox.setChecked(True)
            self.__unitsButtonsGroup__.addButton(unitCheckBox)

        self.connect(self.__unitsButtonsGroup__,
                     SIGNAL("buttonClicked(QAbstractButton *)"),
                     self.__buttonClicked__)
        self.__old_button_unit__ = None
예제 #4
0
class ActivityWidget(CompositeWidget):
    """
    a widget used to input optional description text of activity
    """
    def __init__(self, parent, **params):
        super(ActivityWidget, self).__init__(parent, layout=QHBoxLayout(),
                                             **params)
        self.activityButton = CheckBoxWidget(self,
                            i18n="activity.button",
                            i18n_def="Save as activity",
                            clicked_handler=self.__clickedHandler__)

        LabelWidget(self,
                     i18n="activity.description.label",
                     i18n_def="Activity description (optional):")

        self.activityDescription = LineEditWidget(self, enabled=False)

    def activityOk(self):
        return self.activityButton.isChecked()

    def description(self):
        if self.activityButton.isChecked():
            return str(self.activityDescription.text())

    def __clickedHandler__(self):
        self.activityDescription.setEnabled(self.activityButton.isChecked())
예제 #5
0
class ActivityWidget(CompositeWidget):
    """
    a widget used to input optional description text of activity
    """
    def __init__(self, parent, **params):
        super(ActivityWidget, self).__init__(parent,
                                             layout=QHBoxLayout(),
                                             **params)
        self.activityButton = CheckBoxWidget(
            self,
            i18n="activity.button",
            i18n_def="Save as activity",
            clicked_handler=self.__clickedHandler__)

        LabelWidget(self,
                    i18n="activity.description.label",
                    i18n_def="Activity description (optional):")

        self.activityDescription = LineEditWidget(self, enabled=False)

    def activityOk(self):
        return self.activityButton.isChecked()

    def description(self):
        if self.activityButton.isChecked():
            return str(self.activityDescription.text())

    def __clickedHandler__(self):
        self.activityDescription.setEnabled(self.activityButton.isChecked())
예제 #6
0
    def __init__(self, parent, **params):
        get_or_put(params, 'layout', QHBoxLayout())
        self.params = Params(**params)
        self.data_accessor = self.params.data_accessor  # alias
        i18n_def = "Square filter " + self.data_accessor.signal_unit.display_label  # @IgnorePep8
        super(SquareFilterWidget, self).__init__(parent,
                                                 i18n_def=i18n_def,
                                                 **params)

        self.__filter__ = SquareFilter()

        LabelWidget(self, i18n_def="Min value")
        self.__min_value__ = NumberEditWidget(
            self, text_changed_handler=self.__min_handler__)
        LabelWidget(self, i18n_def="Max value")
        self.__max_value__ = NumberEditWidget(
            self, text_changed_handler=self.__max_handler__)

        if self.params.use_apply_button:
            self.__action_button__ = PushButtonWidget(
                self,
                i18n_def='Apply',
                clicked_handler=self.__filter_handler__)
        else:
            self.__action_button__ = CheckBoxWidget(
                self,
                i18n_def='Use filter',
                clicked_handler=self.__use_handler__)
            self.data_accessor.addListener(
                self, __SquareFilterDataVectorListener__(self))
            self.__action_button__.setChecked(False)

        self.reset()
예제 #7
0
파일: units.py 프로젝트: TEAM-HRA/hra_suite
 def addUnit(self, unit):
     unitCheckBox = CheckBoxWidget(self,
                 i18n_def="%s [%s]" % (unit.name, unit.label))
     unitCheckBox.unit = unit
     if unit == self.default_unit:
         unitCheckBox.setChecked(True)
     self.__unitsButtonsGroup__.addButton(unitCheckBox)
예제 #8
0
    def __init__(self, parent, **params):
        get_or_put(params, 'layout', QVBoxLayout())
        get_or_put(params, 'i18n_def', 'Miscellaneous')
        super(MiscellaneousWidget, self).__init__(parent, **params)

        LabelWidget(self, i18n_def='Data window shift: 1')
        self.params = Params(**params)
        self.params.data_accessor.addListener(
            self, __MiscellaneousVectorListener__(self))
        self.__window_size__ = __DataWindowSizeWidget__(
            self, self.params.data_accessor)

        self.__unitsWidget__ = TimeUnitsWidget(
            self,
            i18n_def='Units',
            default_unit=self.params.data_accessor.signal_x_unit,
            change_unit_handler=self.changeUnit,
            layout=QHBoxLayout())
        self.__unitsWidget__.addUnit(OrderUnit)

        self.__use_parameters__ = CompositeWidget(self, layout=QHBoxLayout())
        self.__use_buffer__ = CheckBoxWidget(self.__use_parameters__,
                                             i18n_def='Use buffer',
                                             checked=True)
        self.__use_identity_line__ = CheckBoxWidget(
            self.__use_parameters__,
            i18n_def='Use identity line',
            checked=True)

        self.__sample_step__ = __SampleStepWidget__(self,
                                                    self.params.data_accessor)

        self.__stepper_size__ = __StepperSizeWidget__(
            self, self.params.data_accessor)
예제 #9
0
class GlobalSeparatorWidget(SeparatorWidget):

    def __init__(self, parent, **params):
        super(GlobalSeparatorWidget, self).__init__(parent, **params)
        self.params = Params(**params)

        self.globalSettingsCheckBox = None
        if self.params.globalHandler:
            self.globalSettingsCheckBox = CheckBoxWidget(
                                        self.separatorsGroupBox,
                                        i18n="separator.global.separator",
                                        i18n_def="Global separator")
            self.separatorsGroupBox.connect(self.globalSettingsCheckBox,
                                        SIGNAL("clicked()"),
                                        self.globalSettingsButtonClicked)

    def globalSettingsButtonClicked(self, clicked=None):
        if clicked:
            self.globalSettingsCheckBox.setChecked(clicked)
        if self.globalSettingsCheckBox.isChecked():
            if not self.predefinedSeparatorsButtonsGroup.checkedButton() \
                == None \
              or not is_empty(self.customSeparatorEdit.text()):
                self.predefinedSeparatorsComposite.setEnabled(False)
                self.params.globalHandler(True, self.getSeparatorSign())
            else:
                self.globalSettingsCheckBox.setChecked(False)
                InformationWindow(message='A separator must be chosen !')
        else:
            self.predefinedSeparatorsComposite.setEnabled(True)
            self.params.globalHandler(False)

    def setGlobalSeparatorAsDefault(self):
        self.globalSettingsButtonClicked(True)
예제 #10
0
 def addUnit(self, unit):
     unitCheckBox = CheckBoxWidget(self,
                                   i18n_def="%s [%s]" %
                                   (unit.name, unit.label))
     unitCheckBox.unit = unit
     if unit == self.default_unit:
         unitCheckBox.setChecked(True)
     self.__unitsButtonsGroup__.addButton(unitCheckBox)
    def __init__(self, parent, model, **params):
        super(TachogramPlotDatasourceListWidget,
              self).__init__(parent,
                             add_widget_to_parent=True,
                             layout=QVBoxLayout())
        self.params = Params(**params)
        toolbars = ToolBarManager(
            self,
            CheckUncheckToolBarWidget,
            OperationalToolBarWidget,
            toolbar_close_handler=self.params.close_tachogram_plot_handler)
        self.layout().addWidget(toolbars)

        self.__showTachogramsButton__ = PushButtonWidget(
            self,
            i18n="poincare.plot.show.tachograms.button",
            i18n_def="Show tachograms",
            enabled=False,
            clicked_handler=self.__showTachogramsHandler__,
            enabled_precheck_handler=self.__enabledPrecheckHandler__)

        self.__allowTachogramsDuplicationButton__ = CheckBoxWidget(
            self,
            i18n="poincare.plot.allow.tachograms.duplications.button",
            i18n_def="Allow tachograms duplication",
            enabled=False,
            enabled_precheck_handler=self.__enabledPrecheckHandler__)

        self.__closeAllTachogramsButton__ = PushButtonWidget(
            self,
            i18n="poincare.plot.close.all.tachograms.button",
            i18n_def="Close all tachograms",
            enabled=False,
            clicked_handler=self.__closeTachogramsHandler__)

        self.__datasourceList__ = \
            ListWidgetWidget(self,
                list_item_clicked_handler=self.__datasourceItemClickedHandler__, # @IgnorePep8
                list_item_double_clicked_handler=self.__datasourceDoubleItemClickedHandler__, # @IgnorePep8
                selectionMode=QAbstractItemView.MultiSelection,
                selectionBehavior=QAbstractItemView.SelectRows)
        if len(model) > 0:
            for row in range(len(model)):
                fileSpecification = model[row]
                ListWidgetItemWidget(self.__datasourceList__,
                                     text=fileSpecification.filename,
                                     data=fileSpecification)
        else:
            ListWidgetItemWidget(self.__datasourceList__,
                                 text='model not specified or incorrect type')

        self.__filesPreviewButton__ = PushButtonWidget(
            self,
            i18n="poincare.plot.files.preview.button",
            i18n_def="Files preview",
            enabled=False,
            clicked_handler=self.__filesPreviewHandler__,
            enabled_precheck_handler=self.__enabledPrecheckHandler__)
예제 #12
0
    def __init__(self, parent, **params):
        super(GlobalSeparatorWidget, self).__init__(parent, **params)
        self.params = Params(**params)

        self.globalSettingsCheckBox = None
        if self.params.globalHandler:
            self.globalSettingsCheckBox = CheckBoxWidget(
                                        self.separatorsGroupBox,
                                        i18n="separator.global.separator",
                                        i18n_def="Global separator")
            self.separatorsGroupBox.connect(self.globalSettingsCheckBox,
                                        SIGNAL("clicked()"),
                                        self.globalSettingsButtonClicked)
예제 #13
0
class SlaveAnnotationFilterWidget(CommonAnnotationFilterWidget):
    def __init__(self, parent, **params):
        super(SlaveAnnotationFilterWidget, self).__init__(parent, **params)
        self.data_accessor.addListener(self,
                                __AnnotationFilterDataVectorListener__(self))
        self.setAnnotationsButtons(self.data_accessor.annotation)

    @property
    def action_button(self):
        return self.__action_button__

    def createActionButton(self):
        self.__action_button__ = CheckBoxWidget(self, i18n_def='Use filter')
        self.__action_button__.setChecked(False)
        self.__action_button__.setEnabled(False)

    def setAnnotationsButtons(self, _annotation):
        empty = is_empty(_annotation) or pl.sum(_annotation) == 0
        self.set_title(empty)
        if empty:
            self.reset()
        else:
            unique = list(pl.unique(_annotation))
            if len(unique) == self.buttons_count:
                self.setEnabledAnnotations(ALL_ANNOTATIONS)
            else:
                self.setEnabledAnnotations(unique)
                self.setUncheckNotAnnotations(unique)
            if self.isAllUnchecked():
                self.__action_button__.setChecked(False)
                self.__action_button__.setEnabled(False)
예제 #14
0
    def __createHeadersTablePreview__(self):

        self.__createHeaderPreviewGroup__()

        self.headersTablePreview = TableViewWidget(self.fileHeaderPreviewGroup,
                            selectionBehavior=QAbstractItemView.SelectRows,
                            selectionMode=QAbstractItemView.SingleSelection)

        self.__globalCheckBox__ = CheckBoxWidget(
                                    self.fileHeaderPreviewGroup,
                                    i18n="global.data.column.index",
                                    i18n_def="Global columns indexes",
                                    clicked_handler=self.__globalClicked__)
        if self.__globalIndex__.signal:
            self.__globalCheckBox__.setChecked(True)
예제 #15
0
    def __init__(self, parent, **params):
        super(ActivityWidget, self).__init__(parent,
                                             layout=QHBoxLayout(),
                                             **params)
        self.activityButton = CheckBoxWidget(
            self,
            i18n="activity.button",
            i18n_def="Save as activity",
            clicked_handler=self.__clickedHandler__)

        LabelWidget(self,
                    i18n="activity.description.label",
                    i18n_def="Activity description (optional):")

        self.activityDescription = LineEditWidget(self, enabled=False)
예제 #16
0
    def __createButtons__(self):
        buttons_composite = CompositeWidget(self, layout=QHBoxLayout())
        self.__calculate_button__ = PushButtonWidget(
            buttons_composite,
            i18n_def="Calculate statistics",
            clicked_handler=self.__calculate_statistics_handler__)
        self.__enabled_calculation_button__(False)

        self.__save_outcomes_button__ = CheckBoxWidget(
            buttons_composite, i18n_def="Save outcomes", enabled=False)

        #if parameter save_outcomes_fixed_state is not None
        #then it's equal to checked state of save outcomes button
        #and this state couldn't be change later by a user
        if self.params.save_outcomes_fixed_state:
            self.__save_outcomes_button__.setChecked(
                self.params.save_outcomes_fixed_state)
예제 #17
0
    def __createFileConstraintsComposite__(self, parent):
        fileConstraintsComposite = CompositeWidget(parent,
                                                   layout=QHBoxLayout())

        self.chooseRootDirButton = PushButtonWidget(
            fileConstraintsComposite,
            i18n="datasource.datasource.choose.root.dir.button",
            i18n_def="Choose root dir",
            clicked_handler=self.chooseRootDirAction)

        LabelWidget(fileConstraintsComposite,
                    i18n="datasource.root.dir.label",
                    i18n_def="Root dir:")
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.rootDirLabel = LabelWidget(fileConstraintsComposite,
                                        i18n="datasource.root.dir.label",
                                        i18n_def="[Not set]",
                                        sizePolicy=sizePolicy,
                                        stretch_after_widget=1)

        LabelWidget(fileConstraintsComposite,
                    i18n="datasource.file.name.filter.label",
                    i18n_def="Files name filter")

        self.filesExtension = LineEditWidget(
            fileConstraintsComposite,
            maxLength=15,
            width=get_width_of_n_letters(14),
            text="*",
            enabled_precheck_handler=self.enabledPrecheckHandler)

        self.recursively = CheckBoxWidget(
            fileConstraintsComposite,
            i18n="datasource.search.files.recursively.label",
            i18n_def="Search files recursively",
            clicked_handler=self.reload,
            enabled_precheck_handler=self.enabledPrecheckHandler)

        self.onlyKnownTypes = CheckBoxWidget(
            fileConstraintsComposite,
            i18n="datasource.only.known.types.checkbox",
            i18n_def="Only known types",
            checked=True,
            clicked_handler=self.reload,
            enabled_precheck_handler=self.enabledPrecheckHandler)
예제 #18
0
    def __init__(self, parent, **params):
        get_or_put(params, 'i18n_def', 'Separator')
        self.params = Params(**params)
        self.separatorsGroupBox = GroupBoxWidget(parent,
                            i18n="separator.widget.group.title",
                            i18n_def=nvl(self.params.i18n_def, "Separator"),
                            layout=QVBoxLayout())

        self.predefinedSeparatorsComposite = CompositeWidget(
                                                    self.separatorsGroupBox,
                                                    layout=QHBoxLayout())
        self.predefinedSeparatorsButtonsGroup = ButtonGroupWidget(
                                            self.predefinedSeparatorsComposite)

        self.predefinedSeparatorsSpecs = Separator.getSeparatorsSpec(
                                                    separator_label_handler)
        for separatorSpec in self.predefinedSeparatorsSpecs:
            label = separatorSpec.label
            if not label == Separator.CUSTOM.label:  # @UndefinedVariable
                predefinedSeparatorCheckBox = CheckBoxWidget(
                                            self.predefinedSeparatorsComposite)
                #attach artificially a separatorSpec object used later in
                #def setSeparator(self, _separator) method
                predefinedSeparatorCheckBox.separator_spec = separatorSpec
                predefinedSeparatorCheckBox.setText(label)
                predefinedSeparatorCheckBox.sep_spec = separatorSpec
                if self.params.default_separator and \
                    separatorSpec.id_ == self.params.default_separator.id_:
                    predefinedSeparatorCheckBox.setChecked(True)
                self.predefinedSeparatorsButtonsGroup.addButton(
                                                predefinedSeparatorCheckBox)

        self.separatorsGroupBox.connect(self.predefinedSeparatorsButtonsGroup,
                                    SIGNAL("buttonClicked(QAbstractButton *)"),
                                    self.predefinedSeparatorButtonClicked)

        if not self.params.no_custom_separator == True:
            self.customSeparatorCheckBox = CheckBoxWidget(
                                        self.predefinedSeparatorsComposite,
                                        i18n="separator.custom.checkbox",
                                        i18n_def="Custom")
            self.customSeparatorCheckBox.sep_spec = Separator.CUSTOM
            self.separatorsGroupBox.connect(self.customSeparatorCheckBox,
                                        SIGNAL("clicked()"),
                                        self.customSeparatorButtonClicked)

            self.customSeparatorEdit = LineEditWidget(
                        self.predefinedSeparatorsComposite,
                        maxLength=15,
                        width=get_width_of_n_letters(14),
                        text_changed_handler=self.customSeparatorButtonClicked,
                        enabled=False)

        self.setEnabled(self.params.enabled)
    def __createAnnotationButtons__(self):

        self.__button_group__ = ButtonGroupWidget(self)

        unique_annotations0 = get_unique_annotations(
            self.data_accessor.annotation0)
        empty = is_empty(unique_annotations0)
        self.set_title(empty)
        self.__all_button__ = CheckBoxWidget(
            self, i18n_def='ALL', clicked_handler=self.__all_button_handler__)
        self.__button_group__.addButton(self.__all_button__)
        for unique_annotation in unique_annotations0:
            annotationCheckBox = CheckBoxWidget(
                self, i18n_def=str(unique_annotation))
            self.__button_group__.addButton(annotationCheckBox)

        self.__button_group__.setExclusive(False)
        self.__button_group__.connect(self.__button_group__,
                                      BUTTON_CLICKED_SIGNAL,
                                      self.__button_handler__)
예제 #20
0
    def __createFileConstraintsComposite__(self, parent):
        fileConstraintsComposite = CompositeWidget(parent,
                                                   layout=QHBoxLayout())

        self.chooseRootDirButton = PushButtonWidget(fileConstraintsComposite,
                        i18n="datasource.datasource.choose.root.dir.button",
                        i18n_def="Choose root dir",
                        clicked_handler=self.chooseRootDirAction)

        LabelWidget(fileConstraintsComposite,
                     i18n="datasource.root.dir.label",
                     i18n_def="Root dir:")
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.rootDirLabel = LabelWidget(fileConstraintsComposite,
                                        i18n="datasource.root.dir.label",
                                        i18n_def="[Not set]",
                                        sizePolicy=sizePolicy,
                                        stretch_after_widget=1)

        LabelWidget(fileConstraintsComposite,
                    i18n="datasource.file.name.filter.label",
                    i18n_def="Files name filter")

        self.filesExtension = LineEditWidget(fileConstraintsComposite,
                        maxLength=15,
                        width=get_width_of_n_letters(14),
                        text="*",
                        enabled_precheck_handler=self.enabledPrecheckHandler)

        self.recursively = CheckBoxWidget(fileConstraintsComposite,
                        i18n="datasource.search.files.recursively.label",
                        i18n_def="Search files recursively",
                        clicked_handler=self.reload,
                        enabled_precheck_handler=self.enabledPrecheckHandler)

        self.onlyKnownTypes = CheckBoxWidget(fileConstraintsComposite,
                        i18n="datasource.only.known.types.checkbox",
                        i18n_def="Only known types",
                        checked=True,
                        clicked_handler=self.reload,
                        enabled_precheck_handler=self.enabledPrecheckHandler)
    def __init__(self, _parent, _header_label, _header_elements):
        QWidget.__init__(self, parent=_parent)
        layout = QVBoxLayout(self)
        self.setLayout(layout)

        LabelWidget(self, i18n_def=_header_label)

        self.__buttons__ = {}
        for header_element in _header_elements:
            handler = __Handler__(header_element.handler, self)
            self.__buttons__[header_element.name] = CheckBoxWidget(self,
                                        i18n_def=header_element.label,
                                        clicked_handler=handler)
예제 #22
0
    def __init__(self, parent, **params):
        super(ActivityWidget, self).__init__(parent, layout=QHBoxLayout(),
                                             **params)
        self.activityButton = CheckBoxWidget(self,
                            i18n="activity.button",
                            i18n_def="Save as activity",
                            clicked_handler=self.__clickedHandler__)

        LabelWidget(self,
                     i18n="activity.description.label",
                     i18n_def="Activity description (optional):")

        self.activityDescription = LineEditWidget(self, enabled=False)
    def __init__(self, parent, model, **params):
        super(TachogramPlotDatasourceListWidget, self).__init__(parent,
                                                    add_widget_to_parent=True,
                                                    layout=QVBoxLayout())
        self.params = Params(**params)
        toolbars = ToolBarManager(self, CheckUncheckToolBarWidget,
                OperationalToolBarWidget,
                toolbar_close_handler=self.params.close_tachogram_plot_handler)
        self.layout().addWidget(toolbars)

        self.__showTachogramsButton__ = PushButtonWidget(self,
                    i18n="poincare.plot.show.tachograms.button",
                    i18n_def="Show tachograms",
                    enabled=False,
                    clicked_handler=self.__showTachogramsHandler__,
                    enabled_precheck_handler=self.__enabledPrecheckHandler__)

        self.__allowTachogramsDuplicationButton__ = CheckBoxWidget(self,
                    i18n="poincare.plot.allow.tachograms.duplications.button",
                    i18n_def="Allow tachograms duplication",
                    enabled=False,
                    enabled_precheck_handler=self.__enabledPrecheckHandler__)

        self.__closeAllTachogramsButton__ = PushButtonWidget(self,
                    i18n="poincare.plot.close.all.tachograms.button",
                    i18n_def="Close all tachograms",
                    enabled=False,
                    clicked_handler=self.__closeTachogramsHandler__)

        self.__datasourceList__ = \
            ListWidgetWidget(self,
                list_item_clicked_handler=self.__datasourceItemClickedHandler__, # @IgnorePep8
                list_item_double_clicked_handler=self.__datasourceDoubleItemClickedHandler__, # @IgnorePep8
                selectionMode=QAbstractItemView.MultiSelection,
                selectionBehavior=QAbstractItemView.SelectRows)
        if len(model) > 0:
            for row in range(len(model)):
                fileSpecification = model[row]
                ListWidgetItemWidget(self.__datasourceList__,
                                     text=fileSpecification.filename,
                                     data=fileSpecification)
        else:
            ListWidgetItemWidget(self.__datasourceList__,
                                 text='model not specified or incorrect type')

        self.__filesPreviewButton__ = PushButtonWidget(self,
                    i18n="poincare.plot.files.preview.button",
                    i18n_def="Files preview",
                    enabled=False,
                    clicked_handler=self.__filesPreviewHandler__,
                    enabled_precheck_handler=self.__enabledPrecheckHandler__)
예제 #24
0
파일: units.py 프로젝트: TEAM-HRA/hra_suite
    def __init__(self, parent, **params):
        get_or_put(params, 'i18n', 'time.units.group.title')
        get_or_put(params, 'i18n_def', 'Time units')
        get_or_put(params, 'layout', QHBoxLayout())
        self.default_unit = params.get('default_unit', Millisecond)
        super(TimeUnitsWidget, self).__init__(parent, **params)
        self.__unitsButtonsGroup__ = ButtonGroupWidget(self)
        self.__change_unit_handler__ = params.get('change_unit_handler', None)

        for time_unit in get_units_for_type(TimeUnit):
            unitCheckBox = CheckBoxWidget(self,
                    i18n_def="%s [%s]" % (time_unit.name, time_unit.label))

            #add artificially property unit for later use in getUnit method
            unitCheckBox.unit = time_unit

            if time_unit == self.default_unit:
                unitCheckBox.setChecked(True)
            self.__unitsButtonsGroup__.addButton(unitCheckBox)

        self.connect(self.__unitsButtonsGroup__,
                    SIGNAL("buttonClicked(QAbstractButton *)"),
                    self.__buttonClicked__)
        self.__old_button_unit__ = None
예제 #25
0
    def __createButtons__(self):
        buttons_composite = CompositeWidget(self, layout=QHBoxLayout())
        self.__calculate_button__ = PushButtonWidget(buttons_composite,
                                            i18n_def="Calculate statistics",
                    clicked_handler=self.__calculate_statistics_handler__)
        self.__enabled_calculation_button__(False)

        self.__save_outcomes_button__ = CheckBoxWidget(buttons_composite,
                                    i18n_def="Save outcomes", enabled=False)

        #if parameter save_outcomes_fixed_state is not None
        #then it's equal to checked state of save outcomes button
        #and this state couldn't be change later by a user
        if self.params.save_outcomes_fixed_state:
            self.__save_outcomes_button__.setChecked(
                                        self.params.save_outcomes_fixed_state)
 def __init__(self, parent, **params):
     get_or_put(params, 'layout', QVBoxLayout())
     get_or_put(params, 'i18n_def', 'Output specification')
     super(OutputSpecificationWidget, self).__init__(parent, **params)
     self.params = Params(**params)
     if self.params.data_accessor:
         self.params.data_accessor.addListener(self,
                         __OutputSpecificationDataVectorListener__(self))
     self.__output_dir__ = DirWidget(self)
     precision = self.__get_output_precision__()
     self.__precision__ = DecimalPrecisionWidget(self,
                                                 precision=precision[0],
                                                 scale=precision[1])
     self.__separator__ = SeparatorWidget(self, i18n_def='Output separator',
             no_custom_separator=params.get('no_custom_separator', None),
             default_separator=Separator.WHITE_SPACE)
     self.__override_existing__ = CheckBoxWidget(self,
                                     i18n_def='Override existing outcomes',
                                     checked=False)
    def __createAnnotationButtons__(self):

        self.__button_group__ = ButtonGroupWidget(self)

        unique_annotations0 = get_unique_annotations(
                                                self.data_accessor.annotation0)
        empty = is_empty(unique_annotations0)
        self.set_title(empty)
        self.__all_button__ = CheckBoxWidget(self, i18n_def='ALL',
                                clicked_handler=self.__all_button_handler__)
        self.__button_group__.addButton(self.__all_button__)
        for unique_annotation in unique_annotations0:
            annotationCheckBox = CheckBoxWidget(self,
                                            i18n_def=str(unique_annotation))
            self.__button_group__.addButton(annotationCheckBox)

        self.__button_group__.setExclusive(False)
        self.__button_group__.connect(self.__button_group__,
                                      BUTTON_CLICKED_SIGNAL,
                                      self.__button_handler__)
class OutputSpecificationWidget(GroupBoxWidget):
    """
    widget used to specify output parameters like:
    output dir,
    output data precision,
    output data separator,
    whether skip existing outcomes
    """
    @temporarySettingsDecorator()
    def __init__(self, parent, **params):
        get_or_put(params, 'layout', QVBoxLayout())
        get_or_put(params, 'i18n_def', 'Output specification')
        super(OutputSpecificationWidget, self).__init__(parent, **params)
        self.params = Params(**params)
        if self.params.data_accessor:
            self.params.data_accessor.addListener(self,
                            __OutputSpecificationDataVectorListener__(self))
        self.__output_dir__ = DirWidget(self)
        precision = self.__get_output_precision__()
        self.__precision__ = DecimalPrecisionWidget(self,
                                                    precision=precision[0],
                                                    scale=precision[1])
        self.__separator__ = SeparatorWidget(self, i18n_def='Output separator',
                no_custom_separator=params.get('no_custom_separator', None),
                default_separator=Separator.WHITE_SPACE)
        self.__override_existing__ = CheckBoxWidget(self,
                                        i18n_def='Override existing outcomes',
                                        checked=False)

    def __get_output_precision__(self):
        """
        return precision defined in FileDataParameters object or a default one
        """
        if self.params.data_accessor:
            container = self.params.data_accessor.parameters_container
            #parameters = container.getParametersObject(
            #                    FileDataParameters.NAME, FileDataParameters)
            parameters = container.getParametersObject(
                        PoincarePlotParameters.NAME, PoincarePlotParameters)
            if not parameters.output_precision == None:
                return parameters.output_precision
        return DEFAULT_OUTPUT_PRECISION

    def __getSeparator__(self):
        return self.__separator__.getSeparatorSign()

    @temporarySetterDecorator(name='separator',
                              _conv=QVariant.toString,
                              _conv_2level=str,
                              _getter_handler=__getSeparator__)
    def __setSeparator__(self, separator):
        self.__separator__.setSeparator(separator)

    def __getDirectory__(self):
        return self.__output_dir__.directory

    @temporarySetterDecorator(name='output_dir',
                              _conv=QVariant.toString,
                              _getter_handler=__getDirectory__)
    def __setDirectory__(self, directory):
        self.__output_dir__.setDirectory(directory)

    def __getScale__(self):
        return self.__precision__.scale

    @temporarySetterDecorator(name='scale',
                              _conv=QVariant.toInt,
                              _getter_handler=__getScale__)
    def __setScale__(self, scale):
        self.__precision__.setScale(scale)

    def __getPrecision__(self):
        return self.__precision__.precision

    @temporarySetterDecorator(name='precision',
                              _conv=QVariant.toInt,
                              _getter_handler=__getPrecision__)
    def __setPrecision__(self, precision):
        self.__precision__.setPrecision(precision)

    def __getOverrideExisting__(self):
        return self.__override_existing__.isChecked()

    @temporarySetterDecorator(name='override_existing',
                              _conv=QVariant.toBool,
                              _getter_handler=__getOverrideExisting__)
    def __setOverrideExisting__(self, override_existing):
        self.__override_existing__.setChecked(override_existing)
예제 #29
0
class SquareFilterWidget(GroupBoxWidget):
    """
    graphical representation of a square filter
    """
    def __init__(self, parent, **params):
        get_or_put(params, 'layout', QHBoxLayout())
        self.params = Params(**params)
        self.data_accessor = self.params.data_accessor  # alias
        i18n_def = "Square filter " + self.data_accessor.signal_unit.display_label  # @IgnorePep8
        super(SquareFilterWidget, self).__init__(parent,
                                                 i18n_def=i18n_def,
                                                 **params)

        self.__filter__ = SquareFilter()

        LabelWidget(self, i18n_def="Min value")
        self.__min_value__ = NumberEditWidget(
            self, text_changed_handler=self.__min_handler__)
        LabelWidget(self, i18n_def="Max value")
        self.__max_value__ = NumberEditWidget(
            self, text_changed_handler=self.__max_handler__)

        if self.params.use_apply_button:
            self.__action_button__ = PushButtonWidget(
                self,
                i18n_def='Apply',
                clicked_handler=self.__filter_handler__)
        else:
            self.__action_button__ = CheckBoxWidget(
                self,
                i18n_def='Use filter',
                clicked_handler=self.__use_handler__)
            self.data_accessor.addListener(
                self, __SquareFilterDataVectorListener__(self))
            self.__action_button__.setChecked(False)

        self.reset()

    def __use_handler__(self):
        if not self.params.use_apply_button:
            if not self.isCorrectSignalRange(self.data_accessor.signal):
                self.__action_button__.setChecked(False)

    def __filter_handler__(self):
        if self.isCorrectSignalRange(self.data_accessor.signal):
            run_filter(self.parent(),
                       self.__filter__,
                       self.data_accessor,
                       filter_name='square')

    def isCorrectSignalRange(self, _signal):
        _min = pl.amin(_signal)
        if _min >= self.__filter__.min_value and \
            _min <= self.__filter__.max_value:
            return True
        _max = pl.amax(_signal)
        if _max >= self.__filter__.min_value and \
            _max <= self.__filter__.max_value:
            return True
        if _min <= self.__filter__.min_value and \
            _max >= self.__filter__.max_value:
            return True
        InformationWindow(message="Signal data out of range !")
        return False

    def __min_handler__(self, text):
        self.__filter__.min_value = text
        self.__check_range__(self.__min_value__)

    def __max_handler__(self, text):
        self.__filter__.max_value = text
        self.__check_range__(self.__max_value__)

    def __check_range__(self, _widget):
        message = self.__filter__.check()
        if message == None:
            self.__action_button__.setEnabled(True)
            _widget.setToolTip('')
            self.__action_button__.setToolTip('')
            return True
        else:
            _widget.setToolTip(message)
            self.__action_button__.setToolTip(message)
            self.__action_button__.setEnabled(False)
            if not self.params.use_apply_button:
                self.__action_button__.setChecked(False)
            return False

    def useFilter(self):
        return self.__action_button__.isChecked() \
            if not self.params.use_apply_button else False

    def getFilter(self):
        return self.__filter__

    def reset(self):
        self.setSquareFilterParams(
            SquareFilterParams(int(pl.amin(self.data_accessor.signal)),
                               int(pl.amax(self.data_accessor.signal)), True))

    def setEnabled(self, _enabled):
        self.__min_value__.setEnabled(_enabled)
        self.__max_value__.setEnabled(_enabled)

    def setSquareFilterParams(self, square_filter_params):
        """
        set up square filter widget parameters
        """
        self.__filter__.min_value = square_filter_params.min_value
        self.__min_value__.setText(self.__filter__.min_value)

        self.__filter__.max_value = square_filter_params.max_value
        self.__max_value__.setText(self.__filter__.max_value)

        if not self.params.use_apply_button:
            self.__action_button__.setChecked(square_filter_params.use_filter)

    def getSquareFilterParams(self):
        return SquareFilterParams(self.__filter__.min_value,
                                  self.__filter__.max_value, self.useFilter())
class TachogramPlotDatasourceListWidget(CommonWidget):
    def __init__(self, parent, model, **params):
        super(TachogramPlotDatasourceListWidget,
              self).__init__(parent,
                             add_widget_to_parent=True,
                             layout=QVBoxLayout())
        self.params = Params(**params)
        toolbars = ToolBarManager(
            self,
            CheckUncheckToolBarWidget,
            OperationalToolBarWidget,
            toolbar_close_handler=self.params.close_tachogram_plot_handler)
        self.layout().addWidget(toolbars)

        self.__showTachogramsButton__ = PushButtonWidget(
            self,
            i18n="poincare.plot.show.tachograms.button",
            i18n_def="Show tachograms",
            enabled=False,
            clicked_handler=self.__showTachogramsHandler__,
            enabled_precheck_handler=self.__enabledPrecheckHandler__)

        self.__allowTachogramsDuplicationButton__ = CheckBoxWidget(
            self,
            i18n="poincare.plot.allow.tachograms.duplications.button",
            i18n_def="Allow tachograms duplication",
            enabled=False,
            enabled_precheck_handler=self.__enabledPrecheckHandler__)

        self.__closeAllTachogramsButton__ = PushButtonWidget(
            self,
            i18n="poincare.plot.close.all.tachograms.button",
            i18n_def="Close all tachograms",
            enabled=False,
            clicked_handler=self.__closeTachogramsHandler__)

        self.__datasourceList__ = \
            ListWidgetWidget(self,
                list_item_clicked_handler=self.__datasourceItemClickedHandler__, # @IgnorePep8
                list_item_double_clicked_handler=self.__datasourceDoubleItemClickedHandler__, # @IgnorePep8
                selectionMode=QAbstractItemView.MultiSelection,
                selectionBehavior=QAbstractItemView.SelectRows)
        if len(model) > 0:
            for row in range(len(model)):
                fileSpecification = model[row]
                ListWidgetItemWidget(self.__datasourceList__,
                                     text=fileSpecification.filename,
                                     data=fileSpecification)
        else:
            ListWidgetItemWidget(self.__datasourceList__,
                                 text='model not specified or incorrect type')

        self.__filesPreviewButton__ = PushButtonWidget(
            self,
            i18n="poincare.plot.files.preview.button",
            i18n_def="Files preview",
            enabled=False,
            clicked_handler=self.__filesPreviewHandler__,
            enabled_precheck_handler=self.__enabledPrecheckHandler__)

    def __datasourceItemClickedHandler__(self, listItem):
        self.emit(ENABLEMEND_SIGNAL, listItem.isSelected())

    def __showTachogramsHandler__(self):
        self.__showTachograms__(self.__getFilesSpecifications__(selected=True))

    def __filesPreviewHandler__(self):
        showFilesPreviewDialog(self.__getFilesSpecifications__(selected=True))

    def __datasourceDoubleItemClickedHandler__(self, listItem):
        self.__showTachograms__(self.__getFilesSpecifications__([listItem]))

    def __showTachograms__(self, files_specifications):
        progressManager = ProgressDialogManager(
            self,
            label_text="Create tachograms",
            max_value=len(files_specifications))
        firstFocus = True
        checked = self.__allowTachogramsDuplicationButton__.isChecked()
        with progressManager as progress:
            for idx in range(progress.maximum()):
                if (progress.wasCanceled()):
                    break
                progress.increaseCounter()
                tachogram_plot = self.params.add_tachogram_plot_handler(
                    files_specifications[idx], checked, firstFocus)
                if firstFocus and tachogram_plot:
                    firstFocus = False

        self.__datasourceList__.clearSelection()

    def __enabledPrecheckHandler__(self, widget):
        """
        only interested widgets return bool value others return none value
        """
        if widget in (self.__showTachogramsButton__,
                      self.__allowTachogramsDuplicationButton__,
                      self.__filesPreviewButton__):
            return len(self.__datasourceList__.selectedIndexes()) > 0

    def __closeTachogramsHandler__(self):
        if self.params.close_tachograms_handler:
            if self.params.close_tachograms_handler():
                self.__closeAllTachogramsButton__.setEnabled(False)
        self.toolbar_uncheck_handler()

    def toolbar_uncheck_handler(self):
        self.__datasourceList__.clearSelection()
        self.emit(ENABLEMEND_SIGNAL, False)

    def toolbar_check_handler(self):
        self.__datasourceList__.selectAll()
        self.emit(ENABLEMEND_SIGNAL, True)

    def toolbar_maximum_handler(self):
        maximize_widget(self)

    def toolbar_restore_handler(self):
        restore_widget(self)

    def enabledCloseAllTachogramsButton(self, enabled):
        self.__closeAllTachogramsButton__.setEnabled(enabled)

    def __getFilesSpecifications__(self, list_items=None, selected=False):
        if selected:  # get files specifications from selected items
            list_items = self.__datasourceList__.selectedItems()
        #acquired from data buffer of list items file specification objects
        return [list_item.getData() for list_item in list_items]

    def getSelectedFilesSpecifications(self):
        """
        method returns selected files specifications in tachogram plot
        list widget
        """
        return self.__getFilesSpecifications__(selected=True)
class CommonAnnotationFilterWidget(GroupBoxWidget):
    def __init__(self, parent, **params):
        get_or_put(params, 'layout', QHBoxLayout())
        super(CommonAnnotationFilterWidget, self).__init__(parent, **params)
        self.params = Params(**params)
        self.data_accessor = self.params.data_accessor  # alias
        self.__filter__ = AnnotationFilter()
        self.__createAnnotationButtons__()
        self.createActionButton()
        self.__activateActionButton__(False)

    @property
    def action_button(self):
        pass

    @property
    def excluded_annotations(self):
        annotations = []
        for button in self.__button_group__.buttons():
            if button.isChecked():
                if button == self.__all_button__:
                    return ALL_ANNOTATIONS
                annotations.append(int(button.text()))
        return annotations

    def setEnabledAnnotations(self, _annotations):
        for button in self.__button_group__.buttons():
            if button == self.__all_button__:
                button.setEnabled(ALL_ANNOTATIONS == _annotations)
            elif ALL_ANNOTATIONS == _annotations or \
                int(button.text()) in _annotations:
                button.setEnabled(True)
            else:
                button.setEnabled(False)

    def setDisabledAnnotations(self, _annotations):
        for button in self.__button_group__.buttons():
            if button == self.__all_button__:
                button.setEnabled(not ALL_ANNOTATIONS == _annotations)
            elif ALL_ANNOTATIONS == _annotations or \
                int(button.text()) in _annotations:
                button.setEnabled(False)

    def disableIfAllChecked(self):
        for button in self.__button_group__.buttons():
            if not button == self.__all_button__ and not button.isChecked():
                return
        self.__all_button__.setEnabled(False)

    def reset(self):
        self.__button_group__.setEnabled(True)
        self.__button_group__.setAllChecked(False)
        self.__activateActionButton__(False)

    @property
    def use_filter(self):
        return self.__button_group__.isAnyChecked()

    @property
    def annotation_filter(self):
        return self.__filter__

    def set_title(self, empty):
        if empty:
            self.setTitle("Annotation filter [NOT ACTIVE - data already filtered]") # @IgnorePep8
            self.setEnabled(False)
        else:
            self.setTitle("Annotation filter")
            self.setEnabled(True)

    @property
    def buttons_count(self):
        return len(self.__button_group__.buttons())

    def setUncheckNotAnnotations(self, _annotations):
        for button in self.__button_group__.buttons():
            if button == self.__all_button__:
                button.setChecked(False)
            else:
                if int(button.text()) not in _annotations:
                    button.setChecked(False)

    def setCheckedAnnotations(self, _annotations):
        """
        check all buttons in accordance with annotations
        """
        for button in self.__button_group__.buttons():
            if not button == self.__all_button__:
                if int(button.text()) in _annotations:
                    button.setChecked(True)

    def isAllUnchecked(self):
        return self.__button_group__.isAllUnchecked()

    def __createAnnotationButtons__(self):

        self.__button_group__ = ButtonGroupWidget(self)

        unique_annotations0 = get_unique_annotations(
                                                self.data_accessor.annotation0)
        empty = is_empty(unique_annotations0)
        self.set_title(empty)
        self.__all_button__ = CheckBoxWidget(self, i18n_def='ALL',
                                clicked_handler=self.__all_button_handler__)
        self.__button_group__.addButton(self.__all_button__)
        for unique_annotation in unique_annotations0:
            annotationCheckBox = CheckBoxWidget(self,
                                            i18n_def=str(unique_annotation))
            self.__button_group__.addButton(annotationCheckBox)

        self.__button_group__.setExclusive(False)
        self.__button_group__.connect(self.__button_group__,
                                      BUTTON_CLICKED_SIGNAL,
                                      self.__button_handler__)

    def __button_handler__(self, button):
        if button.isChecked():
            if button == self.__all_button__:
                self.__setCheckedAnnotationsButtons__(False)
                self.__setEnabledAnnotationsButtons__(False)
            else:
                self.__all_button__.setChecked(False)
            self.__activateActionButton__(True)
        else:
            if button == self.__all_button__ or \
                self.__button_group__.isAllUnchecked():
                self.__activateActionButton__(False)
            if button == self.__all_button__:
                self.__setEnabledAnnotationsButtons__(True)

    def __all_button_handler__(self):
        self.__button_handler__(self.__all_button__)

    def __setCheckedAnnotationsButtons__(self, _checked):
        for button in self.__button_group__.buttons():
            if not button == self.__all_button__:
                button.setChecked(_checked)

    def __setEnabledAnnotationsButtons__(self, _enabled):
        for button in self.__button_group__.buttons():
            if not button == self.__all_button__:
                button.setEnabled(_enabled)

    def __activateActionButton__(self, _activate):
        self.action_button.setEnabled(_activate)
        if _activate == False and hasattr(self.action_button, 'setChecked'):
            self.action_button.setChecked(False)

    def useFilter(self):
        return self.action_button.isChecked() \
            if hasattr(self.action_button, 'isChecked') else False

    def getFilter(self):
        return self.__filter__

    def setAnnotationFilterParams(self, annotation_filter_params):
        """
        set up annotation filter widget parameters
        """
        if not annotation_filter_params.all_annotations:
            if not annotation_filter_params.annotations == None:
                self.setEnabledAnnotations(annotation_filter_params.annotations) # @IgnorePep8
                self.setCheckedAnnotations(annotation_filter_params.annotations) # @IgnorePep8

        self.__all_button__.setChecked(
                                    annotation_filter_params.all_annotations)
        self.__all_button__.setEnabled(True)

        self.__action_button__.setChecked(annotation_filter_params.use_filter)
        if annotation_filter_params.use_filter or \
            annotation_filter_params.all_annotations or \
            not annotation_filter_params.annotations == None:
            self.__action_button__.setEnabled(True)

    def getAnnotationFilterParams(self):
        all_annotations = False
        annotations = self.excluded_annotations
        if annotations == ALL_ANNOTATIONS \
            or self.__all_button__.isChecked():
            all_annotations = True
            annotations = None
        if not annotations == None and len(annotations) == 0:
            annotations = None
        return AnnotationFilterParams(annotations, all_annotations,
                                      self.useFilter())
예제 #32
0
 def createActionButton(self):
     self.__action_button__ = CheckBoxWidget(self, i18n_def='Use filter')
     self.__action_button__.setChecked(False)
     self.__action_button__.setEnabled(False)
예제 #33
0
class SquareFilterWidget(GroupBoxWidget):
    """
    graphical representation of a square filter
    """
    def __init__(self, parent, **params):
        get_or_put(params, 'layout', QHBoxLayout())
        self.params = Params(**params)
        self.data_accessor = self.params.data_accessor  # alias
        i18n_def = "Square filter " + self.data_accessor.signal_unit.display_label # @IgnorePep8
        super(SquareFilterWidget, self).__init__(parent, i18n_def=i18n_def,
                                                     **params)

        self.__filter__ = SquareFilter()

        LabelWidget(self, i18n_def="Min value")
        self.__min_value__ = NumberEditWidget(self,
                                    text_changed_handler=self.__min_handler__)
        LabelWidget(self, i18n_def="Max value")
        self.__max_value__ = NumberEditWidget(self,
                                    text_changed_handler=self.__max_handler__)

        if self.params.use_apply_button:
            self.__action_button__ = PushButtonWidget(self, i18n_def='Apply',
                                clicked_handler=self.__filter_handler__)
        else:
            self.__action_button__ = CheckBoxWidget(self,
                            i18n_def='Use filter',
                            clicked_handler=self.__use_handler__)
            self.data_accessor.addListener(self,
                                    __SquareFilterDataVectorListener__(self))
            self.__action_button__.setChecked(False)

        self.reset()

    def __use_handler__(self):
        if not self.params.use_apply_button:
            if not self.isCorrectSignalRange(self.data_accessor.signal):
                self.__action_button__.setChecked(False)

    def __filter_handler__(self):
        if self.isCorrectSignalRange(self.data_accessor.signal):
            run_filter(self.parent(), self.__filter__, self.data_accessor,
                       filter_name='square')

    def isCorrectSignalRange(self, _signal):
        _min = pl.amin(_signal)
        if _min >= self.__filter__.min_value and \
            _min <= self.__filter__.max_value:
            return True
        _max = pl.amax(_signal)
        if _max >= self.__filter__.min_value and \
            _max <= self.__filter__.max_value:
            return True
        if _min <= self.__filter__.min_value and \
            _max >= self.__filter__.max_value:
            return True
        InformationWindow(message="Signal data out of range !")
        return False

    def __min_handler__(self, text):
        self.__filter__.min_value = text
        self.__check_range__(self.__min_value__)

    def __max_handler__(self, text):
        self.__filter__.max_value = text
        self.__check_range__(self.__max_value__)

    def __check_range__(self, _widget):
        message = self.__filter__.check()
        if message == None:
            self.__action_button__.setEnabled(True)
            _widget.setToolTip('')
            self.__action_button__.setToolTip('')
            return True
        else:
            _widget.setToolTip(message)
            self.__action_button__.setToolTip(message)
            self.__action_button__.setEnabled(False)
            if not self.params.use_apply_button:
                self.__action_button__.setChecked(False)
            return False

    def useFilter(self):
        return self.__action_button__.isChecked() \
            if not self.params.use_apply_button else False

    def getFilter(self):
        return self.__filter__

    def reset(self):
        self.setSquareFilterParams(SquareFilterParams(
                                    int(pl.amin(self.data_accessor.signal)),
                                    int(pl.amax(self.data_accessor.signal)),
                                    True))

    def setEnabled(self, _enabled):
        self.__min_value__.setEnabled(_enabled)
        self.__max_value__.setEnabled(_enabled)

    def setSquareFilterParams(self, square_filter_params):
        """
        set up square filter widget parameters
        """
        self.__filter__.min_value = square_filter_params.min_value
        self.__min_value__.setText(self.__filter__.min_value)

        self.__filter__.max_value = square_filter_params.max_value
        self.__max_value__.setText(self.__filter__.max_value)

        if not self.params.use_apply_button:
            self.__action_button__.setChecked(square_filter_params.use_filter)

    def getSquareFilterParams(self):
        return SquareFilterParams(self.__filter__.min_value,
                                  self.__filter__.max_value,
                                  self.useFilter())
class TachogramPlotDatasourceListWidget(CommonWidget):
    def __init__(self, parent, model, **params):
        super(TachogramPlotDatasourceListWidget, self).__init__(parent,
                                                    add_widget_to_parent=True,
                                                    layout=QVBoxLayout())
        self.params = Params(**params)
        toolbars = ToolBarManager(self, CheckUncheckToolBarWidget,
                OperationalToolBarWidget,
                toolbar_close_handler=self.params.close_tachogram_plot_handler)
        self.layout().addWidget(toolbars)

        self.__showTachogramsButton__ = PushButtonWidget(self,
                    i18n="poincare.plot.show.tachograms.button",
                    i18n_def="Show tachograms",
                    enabled=False,
                    clicked_handler=self.__showTachogramsHandler__,
                    enabled_precheck_handler=self.__enabledPrecheckHandler__)

        self.__allowTachogramsDuplicationButton__ = CheckBoxWidget(self,
                    i18n="poincare.plot.allow.tachograms.duplications.button",
                    i18n_def="Allow tachograms duplication",
                    enabled=False,
                    enabled_precheck_handler=self.__enabledPrecheckHandler__)

        self.__closeAllTachogramsButton__ = PushButtonWidget(self,
                    i18n="poincare.plot.close.all.tachograms.button",
                    i18n_def="Close all tachograms",
                    enabled=False,
                    clicked_handler=self.__closeTachogramsHandler__)

        self.__datasourceList__ = \
            ListWidgetWidget(self,
                list_item_clicked_handler=self.__datasourceItemClickedHandler__, # @IgnorePep8
                list_item_double_clicked_handler=self.__datasourceDoubleItemClickedHandler__, # @IgnorePep8
                selectionMode=QAbstractItemView.MultiSelection,
                selectionBehavior=QAbstractItemView.SelectRows)
        if len(model) > 0:
            for row in range(len(model)):
                fileSpecification = model[row]
                ListWidgetItemWidget(self.__datasourceList__,
                                     text=fileSpecification.filename,
                                     data=fileSpecification)
        else:
            ListWidgetItemWidget(self.__datasourceList__,
                                 text='model not specified or incorrect type')

        self.__filesPreviewButton__ = PushButtonWidget(self,
                    i18n="poincare.plot.files.preview.button",
                    i18n_def="Files preview",
                    enabled=False,
                    clicked_handler=self.__filesPreviewHandler__,
                    enabled_precheck_handler=self.__enabledPrecheckHandler__)

    def __datasourceItemClickedHandler__(self, listItem):
        self.emit(ENABLEMEND_SIGNAL, listItem.isSelected())

    def __showTachogramsHandler__(self):
        self.__showTachograms__(self.__getFilesSpecifications__(selected=True))

    def __filesPreviewHandler__(self):
        showFilesPreviewDialog(self.__getFilesSpecifications__(selected=True))

    def __datasourceDoubleItemClickedHandler__(self, listItem):
        self.__showTachograms__(self.__getFilesSpecifications__([listItem]))

    def __showTachograms__(self, files_specifications):
        progressManager = ProgressDialogManager(self,
                                        label_text="Create tachograms",
                                        max_value=len(files_specifications))
        firstFocus = True
        checked = self.__allowTachogramsDuplicationButton__.isChecked()
        with progressManager as progress:
            for idx in range(progress.maximum()):
                if (progress.wasCanceled()):
                    break
                progress.increaseCounter()
                tachogram_plot = self.params.add_tachogram_plot_handler(
                                            files_specifications[idx],
                                            checked, firstFocus)
                if firstFocus and tachogram_plot:
                    firstFocus = False

        self.__datasourceList__.clearSelection()

    def __enabledPrecheckHandler__(self, widget):
        """
        only interested widgets return bool value others return none value
        """
        if widget in (self.__showTachogramsButton__,
                      self.__allowTachogramsDuplicationButton__,
                      self.__filesPreviewButton__):
            return len(self.__datasourceList__.selectedIndexes()) > 0

    def __closeTachogramsHandler__(self):
        if self.params.close_tachograms_handler:
            if self.params.close_tachograms_handler():
                self.__closeAllTachogramsButton__.setEnabled(False)
        self.toolbar_uncheck_handler()

    def toolbar_uncheck_handler(self):
        self.__datasourceList__.clearSelection()
        self.emit(ENABLEMEND_SIGNAL, False)

    def toolbar_check_handler(self):
        self.__datasourceList__.selectAll()
        self.emit(ENABLEMEND_SIGNAL, True)

    def toolbar_maximum_handler(self):
        maximize_widget(self)

    def toolbar_restore_handler(self):
        restore_widget(self)

    def enabledCloseAllTachogramsButton(self, enabled):
        self.__closeAllTachogramsButton__.setEnabled(enabled)

    def __getFilesSpecifications__(self, list_items=None, selected=False):
        if selected:  # get files specifications from selected items
            list_items = self.__datasourceList__.selectedItems()
        #acquired from data buffer of list items file specification objects
        return [list_item.getData() for list_item in list_items]

    def getSelectedFilesSpecifications(self):
        """
        method returns selected files specifications in tachogram plot
        list widget
        """
        return self.__getFilesSpecifications__(selected=True)
예제 #35
0
class MiscellaneousWidget(GroupBoxWidget):
    """
    widget used to set up some specific properties like:
    window size,
    using of internal buffer,
    use line of identity
    """
    @temporarySettingsDecorator()
    def __init__(self, parent, **params):
        get_or_put(params, 'layout', QVBoxLayout())
        get_or_put(params, 'i18n_def', 'Miscellaneous')
        super(MiscellaneousWidget, self).__init__(parent, **params)

        LabelWidget(self, i18n_def='Data window shift: 1')
        self.params = Params(**params)
        self.params.data_accessor.addListener(
            self, __MiscellaneousVectorListener__(self))
        self.__window_size__ = __DataWindowSizeWidget__(
            self, self.params.data_accessor)

        self.__unitsWidget__ = TimeUnitsWidget(
            self,
            i18n_def='Units',
            default_unit=self.params.data_accessor.signal_x_unit,
            change_unit_handler=self.changeUnit,
            layout=QHBoxLayout())
        self.__unitsWidget__.addUnit(OrderUnit)

        self.__use_parameters__ = CompositeWidget(self, layout=QHBoxLayout())
        self.__use_buffer__ = CheckBoxWidget(self.__use_parameters__,
                                             i18n_def='Use buffer',
                                             checked=True)
        self.__use_identity_line__ = CheckBoxWidget(
            self.__use_parameters__,
            i18n_def='Use identity line',
            checked=True)

        self.__sample_step__ = __SampleStepWidget__(self,
                                                    self.params.data_accessor)

        self.__stepper_size__ = __StepperSizeWidget__(
            self, self.params.data_accessor)

    def getUseBuffer(self):
        return self.__use_buffer__.isChecked()

    @temporarySetterDecorator(name='use_buffer',
                              _conv=QVariant.toBool,
                              _getter_handler=getUseBuffer)
    def setUseBuffer(self, use_buffer):
        return self.__use_buffer__.setChecked(use_buffer)

    def getUseIdentityLine(self):
        return self.__use_identity_line__.isChecked()

    @temporarySetterDecorator(name='use_identity_line',
                              _conv=QVariant.toBool,
                              _getter_handler=getUseIdentityLine)
    def setUseIdentityLine(self, use_identity_line):
        self.__use_identity_line__.setChecked(use_identity_line)

    def getWindowSize(self):
        return self.__window_size__.size

    @temporarySetterDecorator(name='window_size',
                              _conv=QVariant.toInt,
                              _getter_handler=getWindowSize)
    def setWindowSize(self, size):
        self.__window_size__.setSize(size)

    def changeUnit(self, _unit):
        self.__window_size__.setUnit(_unit)
        self.__window_size__.setValueInUnit(_unit)

    def getUnit(self):
        return self.__unitsWidget__.getUnit()

    @temporarySetterDecorator(name='window_size_unit',
                              _conv=QVariant.toPyObject,
                              _getter_handler=getUnit)
    def setUnit(self, unit):
        self.changeUnit(unit)
        self.__unitsWidget__.setUnit(unit)

    def getSampleStep(self):
        return self.__sample_step__.step

    @temporarySetterDecorator(name='sample_step',
                              _conv=QVariant.toInt,
                              _getter_handler=getSampleStep)
    def setSampleStep(self, step):
        self.__sample_step__.setStep(step)

    def getStepperSize(self):
        return self.__stepper_size__.size

    @temporarySetterDecorator(name='stepper_size',
                              _conv=QVariant.toInt,
                              _getter_handler=getStepperSize)
    def setStepperSize(self, size):
        self.__stepper_size__.setSize(size)

    def getStepperUnit(self):
        return self.__stepper_size__.unit

    @temporarySetterDecorator(name='stepper_unit',
                              _conv=QVariant.toPyObject,
                              _getter_handler=getStepperUnit,
                              before_name='stepper_size')
    def setStepperUnit(self, unit):
        self.__stepper_size__.changeUnit(unit)
class CommonAnnotationFilterWidget(GroupBoxWidget):
    def __init__(self, parent, **params):
        get_or_put(params, 'layout', QHBoxLayout())
        super(CommonAnnotationFilterWidget, self).__init__(parent, **params)
        self.params = Params(**params)
        self.data_accessor = self.params.data_accessor  # alias
        self.__filter__ = AnnotationFilter()
        self.__createAnnotationButtons__()
        self.createActionButton()
        self.__activateActionButton__(False)

    @property
    def action_button(self):
        pass

    @property
    def excluded_annotations(self):
        annotations = []
        for button in self.__button_group__.buttons():
            if button.isChecked():
                if button == self.__all_button__:
                    return ALL_ANNOTATIONS
                annotations.append(int(button.text()))
        return annotations

    def setEnabledAnnotations(self, _annotations):
        for button in self.__button_group__.buttons():
            if button == self.__all_button__:
                button.setEnabled(ALL_ANNOTATIONS == _annotations)
            elif ALL_ANNOTATIONS == _annotations or \
                int(button.text()) in _annotations:
                button.setEnabled(True)
            else:
                button.setEnabled(False)

    def setDisabledAnnotations(self, _annotations):
        for button in self.__button_group__.buttons():
            if button == self.__all_button__:
                button.setEnabled(not ALL_ANNOTATIONS == _annotations)
            elif ALL_ANNOTATIONS == _annotations or \
                int(button.text()) in _annotations:
                button.setEnabled(False)

    def disableIfAllChecked(self):
        for button in self.__button_group__.buttons():
            if not button == self.__all_button__ and not button.isChecked():
                return
        self.__all_button__.setEnabled(False)

    def reset(self):
        self.__button_group__.setEnabled(True)
        self.__button_group__.setAllChecked(False)
        self.__activateActionButton__(False)

    @property
    def use_filter(self):
        return self.__button_group__.isAnyChecked()

    @property
    def annotation_filter(self):
        return self.__filter__

    def set_title(self, empty):
        if empty:
            self.setTitle(
                "Annotation filter [NOT ACTIVE - data already filtered]"
            )  # @IgnorePep8
            self.setEnabled(False)
        else:
            self.setTitle("Annotation filter")
            self.setEnabled(True)

    @property
    def buttons_count(self):
        return len(self.__button_group__.buttons())

    def setUncheckNotAnnotations(self, _annotations):
        for button in self.__button_group__.buttons():
            if button == self.__all_button__:
                button.setChecked(False)
            else:
                if int(button.text()) not in _annotations:
                    button.setChecked(False)

    def setCheckedAnnotations(self, _annotations):
        """
        check all buttons in accordance with annotations
        """
        for button in self.__button_group__.buttons():
            if not button == self.__all_button__:
                if int(button.text()) in _annotations:
                    button.setChecked(True)

    def isAllUnchecked(self):
        return self.__button_group__.isAllUnchecked()

    def __createAnnotationButtons__(self):

        self.__button_group__ = ButtonGroupWidget(self)

        unique_annotations0 = get_unique_annotations(
            self.data_accessor.annotation0)
        empty = is_empty(unique_annotations0)
        self.set_title(empty)
        self.__all_button__ = CheckBoxWidget(
            self, i18n_def='ALL', clicked_handler=self.__all_button_handler__)
        self.__button_group__.addButton(self.__all_button__)
        for unique_annotation in unique_annotations0:
            annotationCheckBox = CheckBoxWidget(
                self, i18n_def=str(unique_annotation))
            self.__button_group__.addButton(annotationCheckBox)

        self.__button_group__.setExclusive(False)
        self.__button_group__.connect(self.__button_group__,
                                      BUTTON_CLICKED_SIGNAL,
                                      self.__button_handler__)

    def __button_handler__(self, button):
        if button.isChecked():
            if button == self.__all_button__:
                self.__setCheckedAnnotationsButtons__(False)
                self.__setEnabledAnnotationsButtons__(False)
            else:
                self.__all_button__.setChecked(False)
            self.__activateActionButton__(True)
        else:
            if button == self.__all_button__ or \
                self.__button_group__.isAllUnchecked():
                self.__activateActionButton__(False)
            if button == self.__all_button__:
                self.__setEnabledAnnotationsButtons__(True)

    def __all_button_handler__(self):
        self.__button_handler__(self.__all_button__)

    def __setCheckedAnnotationsButtons__(self, _checked):
        for button in self.__button_group__.buttons():
            if not button == self.__all_button__:
                button.setChecked(_checked)

    def __setEnabledAnnotationsButtons__(self, _enabled):
        for button in self.__button_group__.buttons():
            if not button == self.__all_button__:
                button.setEnabled(_enabled)

    def __activateActionButton__(self, _activate):
        self.action_button.setEnabled(_activate)
        if _activate == False and hasattr(self.action_button, 'setChecked'):
            self.action_button.setChecked(False)

    def useFilter(self):
        return self.action_button.isChecked() \
            if hasattr(self.action_button, 'isChecked') else False

    def getFilter(self):
        return self.__filter__

    def setAnnotationFilterParams(self, annotation_filter_params):
        """
        set up annotation filter widget parameters
        """
        if not annotation_filter_params.all_annotations:
            if not annotation_filter_params.annotations == None:
                self.setEnabledAnnotations(
                    annotation_filter_params.annotations)  # @IgnorePep8
                self.setCheckedAnnotations(
                    annotation_filter_params.annotations)  # @IgnorePep8

        self.__all_button__.setChecked(
            annotation_filter_params.all_annotations)
        self.__all_button__.setEnabled(True)

        self.__action_button__.setChecked(annotation_filter_params.use_filter)
        if annotation_filter_params.use_filter or \
            annotation_filter_params.all_annotations or \
            not annotation_filter_params.annotations == None:
            self.__action_button__.setEnabled(True)

    def getAnnotationFilterParams(self):
        all_annotations = False
        annotations = self.excluded_annotations
        if annotations == ALL_ANNOTATIONS \
            or self.__all_button__.isChecked():
            all_annotations = True
            annotations = None
        if not annotations == None and len(annotations) == 0:
            annotations = None
        return AnnotationFilterParams(annotations, all_annotations,
                                      self.useFilter())
예제 #37
0
class ChooseDatasourcePage(QWizardPage):
    def __init__(self, _parent):
        QWizardPage.__init__(self, parent=_parent)

    def initializePage(self):
        title_I18N(self, "datasource.page.title", "Datasource chooser")
        #self.setSubTitle('Setup frame specific data')
        pageLayout = QVBoxLayout()
        self.setLayout(pageLayout)
        self.__createFilesGroupBox(pageLayout)

        #to force call of isComplete(self) method by the Wizard framework
        #which causes state next button to be updated
        self.emit(WIZARD_COMPLETE_CHANGED_SIGNAL)
        self.rootDir = None

    def __createFilesGroupBox(self, pageLayout):
        self.filesGroupBox = GroupBoxWidget(
            self,
            i18n="datasource.files.group.title",
            i18n_def="Files",
            layout=QVBoxLayout())

        self.__createFileConstraintsComposite__(self.filesGroupBox)

        self.__createReloadButton__(self.filesGroupBox)

        self.__createTableView__(self.filesGroupBox)

        self.__createFilesOperationsComposite__(self.filesGroupBox)

        self.changeEnablemend(False)
        self.chooseRootDirButton.setEnabled(True)

    def __createFileConstraintsComposite__(self, parent):
        fileConstraintsComposite = CompositeWidget(parent,
                                                   layout=QHBoxLayout())

        self.chooseRootDirButton = PushButtonWidget(
            fileConstraintsComposite,
            i18n="datasource.datasource.choose.root.dir.button",
            i18n_def="Choose root dir",
            clicked_handler=self.chooseRootDirAction)

        LabelWidget(fileConstraintsComposite,
                    i18n="datasource.root.dir.label",
                    i18n_def="Root dir:")
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.rootDirLabel = LabelWidget(fileConstraintsComposite,
                                        i18n="datasource.root.dir.label",
                                        i18n_def="[Not set]",
                                        sizePolicy=sizePolicy,
                                        stretch_after_widget=1)

        LabelWidget(fileConstraintsComposite,
                    i18n="datasource.file.name.filter.label",
                    i18n_def="Files name filter")

        self.filesExtension = LineEditWidget(
            fileConstraintsComposite,
            maxLength=15,
            width=get_width_of_n_letters(14),
            text="*",
            enabled_precheck_handler=self.enabledPrecheckHandler)

        self.recursively = CheckBoxWidget(
            fileConstraintsComposite,
            i18n="datasource.search.files.recursively.label",
            i18n_def="Search files recursively",
            clicked_handler=self.reload,
            enabled_precheck_handler=self.enabledPrecheckHandler)

        self.onlyKnownTypes = CheckBoxWidget(
            fileConstraintsComposite,
            i18n="datasource.only.known.types.checkbox",
            i18n_def="Only known types",
            checked=True,
            clicked_handler=self.reload,
            enabled_precheck_handler=self.enabledPrecheckHandler)

    def __createReloadButton__(self, parent):
        self.reloadButton = PushButtonWidget(
            parent,
            i18n="datasource.reload.button",
            i18n_def="Reload",
            clicked_handler=self.reload,
            alignment=Qt.AlignRight,
            enabled_precheck_handler=self.enabledPrecheckHandler)

    def __createTableView__(self, parent):
        self.filesTableView = FilesTableView(
            parent,
            model=QStandardItemModel(self),
            onClickedAction=self.onClickedAction,
            wizardButtons=(QWizard.NextButton, ),
            wizard_handler=self.wizard,
            sorting=True,
            enabled_precheck_handler=self.enabledPrecheckHandler)

    def __createFilesOperationsComposite__(self, parent):
        filesOperations = CompositeWidget(parent, layout=QHBoxLayout())

        self.filePreviewButton = PushButtonWidget(
            filesOperations,
            i18n="datasource.file.preview.button",
            i18n_def="File preview",
            stretch_after_widget=1,
            clicked_handler=self.filePreviewAction,
            enabled_precheck_handler=self.enabledPrecheckHandler)

        self.selectAllButton = PushButtonWidget(
            filesOperations,
            i18n="datasource.accept.select.all.button",
            i18n_def="Select all",
            enabled=False,
            clicked_handler=self.__select_all_handler__,
            enabled_precheck_handler=self.enabledPrecheckHandler)

        self.unselectAllButton = PushButtonWidget(
            filesOperations,
            i18n="datasource.accept.unselect.all.button",
            i18n_def="Unselect all",
            enabled=False,
            clicked_handler=self.__unselect_all_handler__,
            enabled_precheck_handler=self.enabledPrecheckHandler)

    def chooseRootDirAction(self):
        SettingsFactory.loadSettings(self, Setter(rootDir=None))

        rootDir = QFileDialog.getExistingDirectory(
            self,
            caption=self.chooseRootDirButton.text(),
            directory=self.rootDir)
        if rootDir:
            self.rootDir = rootDir + os.path.sep
            SettingsFactory.saveSettings(self, Setter(rootDir=self.rootDir))
            self.rootDirLabel.setText(self.rootDir)
            self.reload()

    def __select_all_handler__(self):
        self.__change_selection__(True)

    def __unselect_all_handler__(self):
        self.__change_selection__(False)

    def __change_selection__(self, _select):
        self.changeEnablemend(False)
        count = self.filesTableView.getRowCount()
        progressManager = ProgressDialogManager(
            self,
            label_text=("Selecting..." if _select else "Unselecting..."),
            max_value=count)
        with progressManager as progress:
            for idx in range(count):
                if (progress.wasCanceled()):
                    break
                progress.increaseCounter()
                if _select:
                    self.filesTableView.setCheckedRowState(idx, Qt.Checked)
                else:
                    self.filesTableView.setCheckedRowState(idx, Qt.Unchecked)
        self.filesTableView.changeCompleteState()
        self.changeEnablemend(True)

    def filePreviewAction(self):
        showFilesPreviewDialog(
            self.filesTableView.getSelectedPathAndFilename())

    def reload(self):
        self.changeEnablemend(True)
        if self.rootDirLabel.text():

            self.filesTableView.clear()
            self.changeEnablemend(False)

            iteratorFlag = QDirIterator.Subdirectories \
                            if self.recursively.isChecked() \
                            else QDirIterator.NoIteratorFlags
            nameFilters = QStringList(
                    self.filesExtension.text()) \
                    if len(self.filesExtension.text()) > 0 \
                            and not self.filesExtension.text() \
                                in ("*", "*.*", "", None) \
                    else QStringList()
            self.iterator = QDirIterator(self.rootDirLabel.text(), nameFilters,
                                         QDir.Filters(QDir.Files),
                                         iteratorFlag)

            with ProgressDialogManager(self) as progress:
                while (self.iterator.next()):
                    if (progress.wasCanceled()):
                        break
                    fileInfo = self.iterator.fileInfo()
                    if fileInfo.size() == 0 or fileInfo.isFile() == False:
                        continue
                    if self.filesExtension.text() in ("*", "*.*", "", None):
                        if (sys.platform == 'win32' \
                            and fileInfo.isExecutable() == True) \
                            or is_text_file(fileInfo.filePath(),
                                    self.onlyKnownTypes.checkState()) == False:
                            continue
                    progress.increaseCounter()

                    checkable = QStandardItem("")
                    checkable.setCheckable(True)
                    filename = QStandardItem(fileInfo.fileName())
                    progress.setLabelText(fileInfo.fileName())
                    size = QStandardItem(str(fileInfo.size()))
                    path = QStandardItem(fileInfo.path())
                    self.filesTableView.addRow(
                        (checkable, filename, size, path))  # @IgnorePep8

            self.filesTableView.resizeColumnsToContents()
            self.filesExtension.setFocus()
            self.changeEnablemend(True)

    def onClickedAction(self, idx):
        self.filePreviewButton.setEnabled(True)
        self.filesTableView.onClickedAction(idx)

    def isComplete(self):
        """
        method used by QWizard to check if next/previous buttons have to
        be disabled/enabled (when False/True is returned)
        """
        return self.filesTableView.isCompletedCount()

    def changeEnablemend(self, enabled):
        self.emit(SIGNAL(ENABLED_SIGNAL_NAME), enabled)
        self.chooseRootDirButton.setEnabled(enabled)

    def enabledPrecheckHandler(self, widget):
        """
        only interested widgets return bool value others none value
        """
        if widget in (self.selectAllButton, self.unselectAllButton):
            return self.filesTableView.count() > 0
        elif widget == self.filePreviewButton:
            return self.filesTableView.getSelectedRowCount() > 0

    def getDatasourceModel(self):
        return self.filesTableView.getModel()
예제 #38
0
class ChooseColumnsDataPage(QWizardPage):

    def __init__(self, _parent, datasource_page_id):
        QWizardPage.__init__(self, parent=_parent)
        self.datasource_page_id = datasource_page_id
        self.pageLayout = None
        self.headersTablePreview = None

        self.__dataFilesHeaders__ = {}
        self.__signalColumnIndexes__ = {}  # includes selected signal column indexes @IgnorePep8
        self.__annotationColumnIndexes__ = {}  # includes selected annotation column indexes @IgnorePep8
        self.__timeColumnIndexes__ = {}  # includes selected [optional] time column indexes @IgnorePep8

        self.__globalSeparator__ = None
        self.__globalCheckBox__ = None
        self.__globalIndex__ = GlobalIndex(None, None, None)

        self.__headerWidgets__ = []
        self.__widgetsHorizontalHeader__ = None

        self.__signal_header_element__ = HeaderElement('signal', 'signal', self.__signalWidgetHandler__) # @IgnorePep8
        self.__annotation_header_element__ = HeaderElement('annotation', 'annotation', self.__annotationWidgetHandler__) # @IgnorePep8
        self.__time_header_element__ = HeaderElement('time', 'time', self.__timeWidgetHandler__) # @IgnorePep8

    def initializePage(self):
        self.setTitle('Choose column data')
        #self.setSubTitle('Choose column specific data')

        if self.pageLayout == None:
            self.pageLayout = QVBoxLayout()
            self.setLayout(self.pageLayout)
            self.__createTableView__(self.pageLayout)
        #select the first row
        self.filesTableView.selectRow(0)
        self.separatorWidget.setGlobalSeparatorAsDefault()

    def __createTableView__(self, pageLayout):
        self.tableViewComposite = CompositeWidget(self, layout=QVBoxLayout())

        datasource_page = self.wizard().page(self.datasource_page_id)
        model = CheckStateProxySortFilterModel(self)
        model.setSourceModel(datasource_page.getDatasourceModel())
        model.setDynamicSortFilter(True)

        self.filesTableView = FilesTableView(self.tableViewComposite,
                                        model=model,
                                        onClickedAction=self.onClickedAction,
                                        wizardButtons=(QWizard.NextButton,),
                                        wizard_handler=self.wizard,
                                        sorting=True)
        self.filesTableView.setColumnHidden(0, True)

        self.filePreviewButton = PushButtonWidget(self.tableViewComposite,
                            i18n="datasource.file.preview.button",
                            i18n_def="File preview",
                            enabled=False,
                            clicked_handler=self.filePreviewAction)

        self.separatorWidget = GlobalSeparatorWidget(self.tableViewComposite,
                                separatorHandler=self.__separatorHandler__,
                                globalHandler=self.__globalSeparatorHandler__,
                                enabled=False)

        self.__createHeaderPreviewGroup__()

        self.__activity__ = ActivityWidget(self)

        self.__timeUnitsGroup__ = self.__createTimeUnitsGroup__()

    def __createTimeUnitsGroup__(self):
        return TimeUnitsWidget(self.tableViewComposite,
                               i18n_def='Signal time unit')

    def onClickedAction(self, idx):
        self.filePreviewButton.setEnabled(True)
        self.filesTableView.onClickedAction(
                                self.filesTableView.model().mapToSource(idx))
        #global separator could be None
        self.__createFileHeadersPreview__(self.__globalSeparator__)
        if self.__globalSeparator__:
            self.separatorWidget.setSeparator(self.__globalSeparator__)
        else:
            self.separatorWidget.setSeparator(self.__getSelectedSeparator__())
        self.separatorWidget.setEnabled(True)

    def filePreviewAction(self):
        showFilesPreviewDialog(
                        self.filesTableView.getSelectedPathAndFilename())

    def __separatorHandler__(self, _separator):
        self.__createFileHeadersPreview__(_separator)

    def __globalSeparatorHandler__(self, _checked, _separator=None):
        self.__globalSeparator__ = _separator

    def __createFileHeadersPreview__(self, _separator=None):

        dataFileHeader = self.__getDataFileHeader__(_separator)
        if dataFileHeader == None:
            return

        self.__createHeadersTablePreview__()

        colCount = dataFileHeader.getHeadersCount()
        model = self.__createHeadersTablePreviewModel__(colCount)

        self.__widgetsHorizontalHeader__ = WidgetsHorizontalHeader(
                                                    self.headersTablePreview)

        # create header line
        pathFile = self.filesTableView.getSelectedPathAndFilename()
        self.__headerWidgets__ = []
        for headerLine in dataFileHeader.getHeadersLines(1):
            for num, header in enumerate(headerLine):
                widget = HeaderWidget(self.__widgetsHorizontalHeader__,
                                      header,
                                      [self.__signal_header_element__,
                                       self.__annotation_header_element__,
                                       self.__time_header_element__])
                self.__headerWidgets__.append(widget)
                # some value of global indicator have to be not None
                if not nvl(*self.__globalIndex__) == None:
                    widget.enabledAll(False)
                    if self.__globalIndex__.signal == num:  # signal index
                        widget.check(self.__signal_header_element__.name)
                    elif self.__globalIndex__.annotation == num:  # annotation index @IgnorePep8
                        widget.check(self.__annotation_header_element__.name)
                    if self.__globalIndex__.time == num:  # time index
                        widget.check(self.__time_header_element__.name)
                elif self.__signalColumnIndexes__.get(pathFile) == num:
                    widget.check(self.__signal_header_element__.name)
                elif self.__annotationColumnIndexes__.get(pathFile) == num:
                    widget.check(self.__annotation_header_element__.name)
                elif self.__timeColumnIndexes__.get(pathFile) == num:
                    widget.check(self.__time_header_element__.name)
        self.__widgetsHorizontalHeader__.setWidgets(self.__headerWidgets__)

        # create data lines
        for rowData in dataFileHeader.getDataLines():
            modelData = list()
            for idx in range(colCount):
                modelData.append(QStandardItem(rowData[idx]
                                        if colCount <= len(rowData) else ""))
            model.appendRow(modelData)

        self.fileHeaderPreviewGroup.setEnabled(True)
        self.fileHeaderPreviewGroup.show()

    def __getDataFileHeader__(self, _separator=None):
        pathFile = self.filesTableView.getSelectedPathAndFilename()
        if pathFile == None:
            ErrorWindow(message="The file must be selected !")
        else:
            return self.__createDataFileHeader__(pathFile, _separator)

    def __createHeadersTablePreviewModel__(self, colNumber):
        model = PreviewDataViewModel(self.headersTablePreview)
        labels = QStringList(create_list("", colNumber))
        model.setHorizontalHeaderLabels(labels)
        self.headersTablePreview.setModel(model)
        return model

    def __createHeadersTablePreview__(self):

        self.__createHeaderPreviewGroup__()

        self.headersTablePreview = TableViewWidget(self.fileHeaderPreviewGroup,
                            selectionBehavior=QAbstractItemView.SelectRows,
                            selectionMode=QAbstractItemView.SingleSelection)

        self.__globalCheckBox__ = CheckBoxWidget(
                                    self.fileHeaderPreviewGroup,
                                    i18n="global.data.column.index",
                                    i18n_def="Global columns indexes",
                                    clicked_handler=self.__globalClicked__)
        if self.__globalIndex__.signal:
            self.__globalCheckBox__.setChecked(True)

    def __createDataFileHeader__(self, pathFile, _separator):
        dataFileHeader = self.__dataFilesHeaders__.get(pathFile, None)
        if dataFileHeader == None:
            dataFileHeader = DataFileHeader(pathFile)
            self.__dataFilesHeaders__[pathFile] = dataFileHeader

        if _separator == None:
            _separator = dataFileHeader.getSeparator()

        if _separator == None:
            #try to discover a separator based on file data
            _separator = dataFileHeader.getSeparator(generate=True)

        dataFileHeader.setSeparator(_separator)
        return dataFileHeader

    def __getSelectedSeparator__(self):
        pathFile = self.filesTableView.getSelectedPathAndFilename()
        if pathFile:
            dataFileHeader = self.__dataFilesHeaders__.get(pathFile)
            if dataFileHeader:
                return dataFileHeader.getSeparator()

    # for future use
    def __setSeparatorForAll__(self, _separator=None):
        model = self.filesTableView.model()
        for row in range(model.rowCount()):
            #it's necessity to alter model index of QSortFilterProxyModel type
            #into source model index of QStandardItemModel type
            idx = model.mapToSource(model.index(row, 0))
            pathFile = self.filesTableView.getPathAndFilename(idx)
            if pathFile:
                self.__createDataFileHeader__(pathFile, _separator)

    def __signalWidgetHandler__(self, _widget):
        self.__widgetHandler__(_widget, self.__signal_header_element__.name)

    def __annotationWidgetHandler__(self, _widget):
        self.__widgetHandler__(_widget, self.__annotation_header_element__.name)  # @IgnorePep8

    def __timeWidgetHandler__(self, _widget):
        self.__widgetHandler__(_widget, self.__time_header_element__.name)

    def __widgetHandler__(self, _widget, _type):
        checked = _widget.isChecked(_type)
        pathFile = self.filesTableView.getSelectedPathAndFilename()
        if checked:
            for num, widget in enumerate(self.__headerWidgets__):
                if widget == _widget:
                    if _type == self.__signal_header_element__.name:
                        _widget.uncheck(self.__annotation_header_element__.name) # @IgnorePep8
                        self.__signalColumnIndexes__[pathFile] = num
                    elif _type == self.__annotation_header_element__.name:
                        _widget.uncheck(self.__signal_header_element__.name)
                        _widget.uncheck(self.__time_header_element__.name)
                        self.__annotationColumnIndexes__[pathFile] = num
                    elif _type == self.__time_header_element__.name:
                        _widget.uncheck(self.__annotation_header_element__.name) # @IgnorePep8
                        self.__timeColumnIndexes__[pathFile] = num
                else:
                    if _type == self.__signal_header_element__.name:
                        widget.uncheck(self.__signal_header_element__.name)
                    elif _type == self.__annotation_header_element__.name:
                        widget.uncheck(self.__annotation_header_element__.name)
                    elif _type == self.__time_header_element__.name:
                        widget.uncheck(self.__time_header_element__.name)

            self.__globalCheckBox__.setEnabled(True)
        else:
            if _type == self.__signal_header_element__.name:
                self.__signalColumnIndexes__[pathFile] = None
            elif _type == self.__annotation_header_element__.name:
                self.__annotationColumnIndexes__[pathFile] = None
            elif _type == self.__time_header_element__.name:
                self.__timeColumnIndexes__[pathFile] = None

    def __globalClicked__(self):

        _signal = None
        _annotation = None
        _time = None
        if self.__globalCheckBox__.isChecked():
            for num, widget in enumerate(self.__headerWidgets__):
                if widget.isChecked(self.__signal_header_element__.name):
                    _signal = num
                if widget.isChecked(self.__annotation_header_element__.name):
                    _annotation = num
                if widget.isChecked(self.__time_header_element__.name):
                    _time = num
            index = GlobalIndex(_signal, _annotation, _time)
            if index.signal == None:
                self.__globalCheckBox__.setChecked(False)
                InformationWindow(None,
                        message='At least signal column has to be selected !')
                return
            else:
                for num, widget in enumerate(self.__headerWidgets__):
                    widget.enabledAll(False)
                self.__globalIndex__ = index
                self.__setGlobalIndexForAll__(self.__globalIndex__)
        else:
            for widget in self.__headerWidgets__:
                widget.enabledAll(True)
            self.__globalIndex__ = GlobalIndex(None, None, None)

    def __setGlobalIndexForAll__(self, _globalIndex):
        model = self.filesTableView.model()
        for row in range(model.rowCount()):
            #it's necessity to alter model index of QSortFilterProxyModel type
            #into source model index of QStandardItemModel type
            idx = model.mapToSource(model.index(row, 0))
            pathFile = self.filesTableView.getPathAndFilename(idx)
            if pathFile:
                self.__signalColumnIndexes__[pathFile] = _globalIndex.signal

                if _globalIndex.annotation:  # annontation global index
                    self.__annotationColumnIndexes__[pathFile] = \
                                                    _globalIndex.annotation
                if _globalIndex.time:  # time global index
                    self.__timeColumnIndexes__[pathFile] = \
                                                    _globalIndex.time

    def __createHeaderPreviewGroup__(self):
        if hasattr(self, 'fileHeaderPreviewGroup'):
            self.fileHeaderPreviewGroup.deleteLater()
        self.fileHeaderPreviewGroup = GroupBoxWidget(self.tableViewComposite,
                                    i18n="datasource.file.header.preview",
                                    i18n_def="Header preview",
                                    layout=QVBoxLayout(),
                                    hidden=True,
                                    enabled=False)

    def validatePage(self):
        filesSpecificationModel = DatasourceFilesSpecificationModel()
        for (_path, _filename, _signalIndex, _annotationIndex, _timeIndex,
             _separator) in \
            self.__getFilesSpec__(indexes=True, separators=True):
                if _signalIndex == None:
                    ErrorWindow(message=("No signal column for the file %s !"
                                         % (_filename)))
                    return False
                if _separator == None:
                    ErrorWindow(message=("No separator for file %s !"
                                         % (_filename)))
                    return False
                filesSpecificationModel.appendRow(_path, _filename,
                    _signalIndex, _annotationIndex, _timeIndex, _separator,
                    self.__timeUnitsGroup__.getUnit())

        PluginsManager.invokePlugin(PluginsNames.TACHOGRAM_PLOT_PLUGIN_NAME,
                    inspect.stack(),
                    model=filesSpecificationModel.getAsFilesSpecifications(),
                    activity_description=self.__activity__.description(),
                    activity_params=['model'])
        return True

    def __getFilesSpec__(self, _pathfile=True,
                         indexes=False, use_global_index=True,
                         separators=False, use_global_separator=True):
        filesSpec = []
        model = self.filesTableView.model()
        for row in range(model.rowCount()):
            #it's necessity to alter model index of QSortFilterProxyModel type
            #into source model index of QStandardItemModel type
            idx = model.mapToSource(model.index(row, 0))
            pathFile = self.filesTableView.getPathAndFilename(idx)

            if pathFile:
                fileSpec = []
                if _pathfile == True:
                    fileSpec.extend(pathFile)

                if indexes == True:
                    signalIndex = self.__signalColumnIndexes__.get(pathFile)
                    if signalIndex == None and use_global_index == True and \
                        not self.__globalIndex__.signal == None:
                        signalIndex = self.__globalIndex__.signal
                    fileSpec.append(signalIndex)

                    annotationIndex = self.__annotationColumnIndexes__.get(
                                                                   pathFile)
                    if annotationIndex == None and use_global_index == True \
                        and not self.__globalIndex__.annotation == None:
                        annotationIndex = self.__globalIndex__.annotation
                    fileSpec.append(annotationIndex)

                    timeIndex = self.__timeColumnIndexes__.get(pathFile)
                    if timeIndex == None and use_global_index == True \
                        and not self.__globalIndex__.time == None:
                        timeIndex = self.__globalIndex__.time
                    fileSpec.append(timeIndex)

                if separators == True:
                    separator = None
                    dataFileHeader = self.__dataFilesHeaders__.get(pathFile)
                    if not dataFileHeader == None:
                        separator = dataFileHeader.getSeparator()
                    if separator == None and use_global_separator == True:
                        separator = self.__globalSeparator__
                    fileSpec.append(separator)
                filesSpec.append(tuple(fileSpec))
        return filesSpec
예제 #39
0
class StatisticsWidget(GroupBoxWidget):
    """
    widget adds an action of statistics calculations into statistics widget
    """
    def __init__(self, parent, **params):
        get_or_put(params, 'layout', QVBoxLayout())
        get_or_put(params, 'i18n_def', 'Statistics')
        super(StatisticsWidget, self).__init__(parent, **params)
        self.params = Params(**params)

        self.data_accessors = []
        self.main_data_accessor = None
        if not self.params.data_vectors_accessor_group == None:
            self.data_accessors = self.params.data_vectors_accessor_group.data_vectors_accessors # @IgnorePep8
            self.main_data_accessor = self.params.data_vectors_accessor_group.group_data_vector_accessor # @IgnorePep8
        elif not self.params.data_accessor == None:
            self.main_data_accessor = self.params.data_accessor
            self.data_accessors = [self.main_data_accessor]

        for data_accessor in self.data_accessors:
            data_accessor.addListener(self, __StatisticsVectorListener__(self))

        self.__createButtons__()
        self.__statistics_widget__ = StatisticsSelectionWidget(self,
                    layout=QVBoxLayout(), i18n_def='',
                    check_handler=self.__change_statistics_handler__)

        self.__summary_statistics_widget__ = SummaryStatisticsSelectionWidget(
                    self, layout=QVBoxLayout(), i18n_def='Summary statistics',
                    check_handler=self.__change_statistics_handler__)

    def __createButtons__(self):
        buttons_composite = CompositeWidget(self, layout=QHBoxLayout())
        self.__calculate_button__ = PushButtonWidget(buttons_composite,
                                            i18n_def="Calculate statistics",
                    clicked_handler=self.__calculate_statistics_handler__)
        self.__enabled_calculation_button__(False)

        self.__save_outcomes_button__ = CheckBoxWidget(buttons_composite,
                                    i18n_def="Save outcomes", enabled=False)

        #if parameter save_outcomes_fixed_state is not None
        #then it's equal to checked state of save outcomes button
        #and this state couldn't be change later by a user
        if self.params.save_outcomes_fixed_state:
            self.__save_outcomes_button__.setChecked(
                                        self.params.save_outcomes_fixed_state)

    def __calculate_statistics_handler__(self):
        if len(self.data_accessors) == 0:
            return

        self.main_data_accessor.prepareParametersContainer()
        #processing many data accessors objects:
        #self.data_accessors object contains many data_accessor objects which
        #have to be treated in the same way as self.main_data_accessor object,
        #that means they must have the same parameters
        for data_accessor in self.data_accessors:
            data_accessor.parameters_container = self.main_data_accessor.parameters_container # @IgnorePep8

        formatted_summary_statistics = []
        save_csv = self.__save_outcomes_button__.isChecked()
        check_level = CoreParameters.MEDIUM_CHECK_LEVEL if save_csv else CoreParameters.LOW_CHECK_LEVEL # @IgnorePep8

        pp_generator_progress_bar = PoincarePlotGeneratorProgressBar(self,
                self.data_accessors, label_text='Statistics calculation',
                check_level=check_level, save_csv=save_csv,
                formatted_summary_statistics=formatted_summary_statistics,
                output_file_listener=self.params.output_file_listener)
        pp_generator_progress_bar.start()
        if pp_generator_progress_bar.interrupted() == False and \
            len(formatted_summary_statistics) == 1:
            #summary statistics values are updated only in the case
            #of one data accessor object
            self.__summary_statistics_widget__.setStatisticsValues(
                                        formatted_summary_statistics[0])

    def __change_statistics_handler__(self, _statistic, _checked):
        """
        handler invoked when number of selected rows is changing
        """
        if not _checked:
            if len(self.getSelectedStatisticsClasses()) > 0 or \
                len(self.getSelectedSummaryStatisticsClasses()) > 0:
                _checked = True
        self.__enabled_calculation_button__(_checked)

        #only if this parameter is None save outcomes button's check state
        #could be changed
        if self.params.save_outcomes_fixed_state == None:
            self.__save_outcomes_button__.setEnabled(_checked)

    def getSelectedStatisticsClasses(self):
        return self.__statistics_widget__.getSelectedStatisticsClasses()

    def getSelectedSummaryStatisticsClasses(self):
        return self.__summary_statistics_widget__.getSelectedStatisticsClasses() # @IgnorePep8

    def __enabled_calculation_button__(self, _enabled):
        """
        method sets background color of 'Calculate statistics' button to red
        if the button is disabled foreground color is set up to brown
        otherwise to black
        """
        if _enabled == False:
            self.__calculate_button__.setStyleSheet("background-color: red; color: brown") # @IgnorePep8
        else:
            self.__calculate_button__.setStyleSheet("background-color: red; color: black") # @IgnorePep8
        self.__calculate_button__.setEnabled(_enabled)
예제 #40
0
class SeparatorWidget(object):
    """
    widget used to choose a separator sign
    """
    def __init__(self, parent, **params):
        get_or_put(params, 'i18n_def', 'Separator')
        self.params = Params(**params)
        self.separatorsGroupBox = GroupBoxWidget(parent,
                            i18n="separator.widget.group.title",
                            i18n_def=nvl(self.params.i18n_def, "Separator"),
                            layout=QVBoxLayout())

        self.predefinedSeparatorsComposite = CompositeWidget(
                                                    self.separatorsGroupBox,
                                                    layout=QHBoxLayout())
        self.predefinedSeparatorsButtonsGroup = ButtonGroupWidget(
                                            self.predefinedSeparatorsComposite)

        self.predefinedSeparatorsSpecs = Separator.getSeparatorsSpec(
                                                    separator_label_handler)
        for separatorSpec in self.predefinedSeparatorsSpecs:
            label = separatorSpec.label
            if not label == Separator.CUSTOM.label:  # @UndefinedVariable
                predefinedSeparatorCheckBox = CheckBoxWidget(
                                            self.predefinedSeparatorsComposite)
                #attach artificially a separatorSpec object used later in
                #def setSeparator(self, _separator) method
                predefinedSeparatorCheckBox.separator_spec = separatorSpec
                predefinedSeparatorCheckBox.setText(label)
                predefinedSeparatorCheckBox.sep_spec = separatorSpec
                if self.params.default_separator and \
                    separatorSpec.id_ == self.params.default_separator.id_:
                    predefinedSeparatorCheckBox.setChecked(True)
                self.predefinedSeparatorsButtonsGroup.addButton(
                                                predefinedSeparatorCheckBox)

        self.separatorsGroupBox.connect(self.predefinedSeparatorsButtonsGroup,
                                    SIGNAL("buttonClicked(QAbstractButton *)"),
                                    self.predefinedSeparatorButtonClicked)

        if not self.params.no_custom_separator == True:
            self.customSeparatorCheckBox = CheckBoxWidget(
                                        self.predefinedSeparatorsComposite,
                                        i18n="separator.custom.checkbox",
                                        i18n_def="Custom")
            self.customSeparatorCheckBox.sep_spec = Separator.CUSTOM
            self.separatorsGroupBox.connect(self.customSeparatorCheckBox,
                                        SIGNAL("clicked()"),
                                        self.customSeparatorButtonClicked)

            self.customSeparatorEdit = LineEditWidget(
                        self.predefinedSeparatorsComposite,
                        maxLength=15,
                        width=get_width_of_n_letters(14),
                        text_changed_handler=self.customSeparatorButtonClicked,
                        enabled=False)

        self.setEnabled(self.params.enabled)

    def getSeparatorSign(self):
        sign = self.__getPredefinedSeparatorSign__()
        if sign:
            return sign
        if not self.params.no_custom_separator == True:
            return self.__getCustomSeparatorSign__()

    def predefinedSeparatorButtonClicked(self, button):
        if not self.params.no_custom_separator == True:
            self.__customSeparatorClear__()
        if self.params.separatorHandler and \
            not self.predefinedSeparatorsButtonsGroup.checkedButton() == None:
            self.params.separatorHandler(self.__getPredefinedSeparatorSign__())

    def customSeparatorButtonClicked(self):
        checked = self.customSeparatorCheckBox.isChecked()
        separator = self.__getCustomSeparatorSign__()
        if checked and self.params.separatorHandler and separator:
            self.params.separatorHandler(separator)
        self.customSeparatorEdit.setEnabled(checked)
        if checked:
            self.__uncheckPredefinedButtons__()
            self.customSeparatorEdit.setFocus()

    def __getPredefinedSeparatorSign__(self):
        button = self.predefinedSeparatorsButtonsGroup.checkedButton()
        if not button == None:
            for (sign, _, label) in self.predefinedSeparatorsSpecs:
                if button.text() == label:
                    return sign

    def __getCustomSeparatorSign__(self):
        if self.customSeparatorCheckBox.isChecked():
            return str(self.customSeparatorEdit.text())

    def setEnabled(self, enabled):
        if not enabled == None:
            self.separatorsGroupBox.setEnabled(enabled)

    def setSeparator(self, _separator):
        if _separator:
            separatorSign = Separator.getSeparatorSign(_separator)
            if separatorSign == Separator.WHITE_SPACE:
                for button in self.predefinedSeparatorsButtonsGroup.buttons():
                    if button.separator_spec.id_ == Separator.WHITE_SPACE.id_:  # @UndefinedVariable @IgnorePep8
                        button.setChecked(True)
                        return
            elif separatorSign == Separator.CUSTOM:
                self.customSeparatorEdit.setText(_separator)
                self.__uncheckPredefinedButtons__()
            elif not separatorSign == Separator.NONE:
                for button in self.predefinedSeparatorsButtonsGroup.buttons():
                    if button.sep_spec.id_ == separatorSign.id_:
                        if not self.params.no_custom_separator == True:
                            self.__customSeparatorClear__()
                        button.setChecked(True)
                        return

    def __customSeparatorClear__(self):
        self.customSeparatorCheckBox.setChecked(False)
        self.customSeparatorEdit.setText("")
        self.customSeparatorEdit.setEnabled(False)

    def __uncheckPredefinedButtons__(self):
        #to uncheck button included in a button group one have to use a trick:
        #change to none exclusive state behaviour of the button group, then
        #uncheck checked button and reverse to previous exclusive state of
        #the button group
        if self.predefinedSeparatorsButtonsGroup.checkedButton():
            self.predefinedSeparatorsButtonsGroup.setExclusive(False)
            self.predefinedSeparatorsButtonsGroup.checkedButton().setChecked(
                                                                        False)
            self.predefinedSeparatorsButtonsGroup.setExclusive(True)
예제 #41
0
class StatisticsWidget(GroupBoxWidget):
    """
    widget adds an action of statistics calculations into statistics widget
    """
    def __init__(self, parent, **params):
        get_or_put(params, 'layout', QVBoxLayout())
        get_or_put(params, 'i18n_def', 'Statistics')
        super(StatisticsWidget, self).__init__(parent, **params)
        self.params = Params(**params)

        self.data_accessors = []
        self.main_data_accessor = None
        if not self.params.data_vectors_accessor_group == None:
            self.data_accessors = self.params.data_vectors_accessor_group.data_vectors_accessors  # @IgnorePep8
            self.main_data_accessor = self.params.data_vectors_accessor_group.group_data_vector_accessor  # @IgnorePep8
        elif not self.params.data_accessor == None:
            self.main_data_accessor = self.params.data_accessor
            self.data_accessors = [self.main_data_accessor]

        for data_accessor in self.data_accessors:
            data_accessor.addListener(self, __StatisticsVectorListener__(self))

        self.__createButtons__()
        self.__statistics_widget__ = StatisticsSelectionWidget(
            self,
            layout=QVBoxLayout(),
            i18n_def='',
            check_handler=self.__change_statistics_handler__)

        self.__summary_statistics_widget__ = SummaryStatisticsSelectionWidget(
            self,
            layout=QVBoxLayout(),
            i18n_def='Summary statistics',
            check_handler=self.__change_statistics_handler__)

    def __createButtons__(self):
        buttons_composite = CompositeWidget(self, layout=QHBoxLayout())
        self.__calculate_button__ = PushButtonWidget(
            buttons_composite,
            i18n_def="Calculate statistics",
            clicked_handler=self.__calculate_statistics_handler__)
        self.__enabled_calculation_button__(False)

        self.__save_outcomes_button__ = CheckBoxWidget(
            buttons_composite, i18n_def="Save outcomes", enabled=False)

        #if parameter save_outcomes_fixed_state is not None
        #then it's equal to checked state of save outcomes button
        #and this state couldn't be change later by a user
        if self.params.save_outcomes_fixed_state:
            self.__save_outcomes_button__.setChecked(
                self.params.save_outcomes_fixed_state)

    def __calculate_statistics_handler__(self):
        if len(self.data_accessors) == 0:
            return

        self.main_data_accessor.prepareParametersContainer()
        #processing many data accessors objects:
        #self.data_accessors object contains many data_accessor objects which
        #have to be treated in the same way as self.main_data_accessor object,
        #that means they must have the same parameters
        for data_accessor in self.data_accessors:
            data_accessor.parameters_container = self.main_data_accessor.parameters_container  # @IgnorePep8

        formatted_summary_statistics = []
        save_csv = self.__save_outcomes_button__.isChecked()
        check_level = CoreParameters.MEDIUM_CHECK_LEVEL if save_csv else CoreParameters.LOW_CHECK_LEVEL  # @IgnorePep8

        pp_generator_progress_bar = PoincarePlotGeneratorProgressBar(
            self,
            self.data_accessors,
            label_text='Statistics calculation',
            check_level=check_level,
            save_csv=save_csv,
            formatted_summary_statistics=formatted_summary_statistics,
            output_file_listener=self.params.output_file_listener)
        pp_generator_progress_bar.start()
        if pp_generator_progress_bar.interrupted() == False and \
            len(formatted_summary_statistics) == 1:
            #summary statistics values are updated only in the case
            #of one data accessor object
            self.__summary_statistics_widget__.setStatisticsValues(
                formatted_summary_statistics[0])

    def __change_statistics_handler__(self, _statistic, _checked):
        """
        handler invoked when number of selected rows is changing
        """
        if not _checked:
            if len(self.getSelectedStatisticsClasses()) > 0 or \
                len(self.getSelectedSummaryStatisticsClasses()) > 0:
                _checked = True
        self.__enabled_calculation_button__(_checked)

        #only if this parameter is None save outcomes button's check state
        #could be changed
        if self.params.save_outcomes_fixed_state == None:
            self.__save_outcomes_button__.setEnabled(_checked)

    def getSelectedStatisticsClasses(self):
        return self.__statistics_widget__.getSelectedStatisticsClasses()

    def getSelectedSummaryStatisticsClasses(self):
        return self.__summary_statistics_widget__.getSelectedStatisticsClasses(
        )  # @IgnorePep8

    def __enabled_calculation_button__(self, _enabled):
        """
        method sets background color of 'Calculate statistics' button to red
        if the button is disabled foreground color is set up to brown
        otherwise to black
        """
        if _enabled == False:
            self.__calculate_button__.setStyleSheet(
                "background-color: red; color: brown")  # @IgnorePep8
        else:
            self.__calculate_button__.setStyleSheet(
                "background-color: red; color: black")  # @IgnorePep8
        self.__calculate_button__.setEnabled(_enabled)
예제 #42
0
class ChooseDatasourcePage(QWizardPage):

    def __init__(self, _parent):
        QWizardPage.__init__(self, parent=_parent)

    def initializePage(self):
        title_I18N(self, "datasource.page.title", "Datasource chooser")
        #self.setSubTitle('Setup frame specific data')
        pageLayout = QVBoxLayout()
        self.setLayout(pageLayout)
        self.__createFilesGroupBox(pageLayout)

        #to force call of isComplete(self) method by the Wizard framework
        #which causes state next button to be updated
        self.emit(WIZARD_COMPLETE_CHANGED_SIGNAL)
        self.rootDir = None

    def __createFilesGroupBox(self, pageLayout):
        self.filesGroupBox = GroupBoxWidget(self,
                                    i18n="datasource.files.group.title",
                                    i18n_def="Files",
                                    layout=QVBoxLayout())

        self.__createFileConstraintsComposite__(self.filesGroupBox)

        self.__createReloadButton__(self.filesGroupBox)

        self.__createTableView__(self.filesGroupBox)

        self.__createFilesOperationsComposite__(self.filesGroupBox)

        self.changeEnablemend(False)
        self.chooseRootDirButton.setEnabled(True)

    def __createFileConstraintsComposite__(self, parent):
        fileConstraintsComposite = CompositeWidget(parent,
                                                   layout=QHBoxLayout())

        self.chooseRootDirButton = PushButtonWidget(fileConstraintsComposite,
                        i18n="datasource.datasource.choose.root.dir.button",
                        i18n_def="Choose root dir",
                        clicked_handler=self.chooseRootDirAction)

        LabelWidget(fileConstraintsComposite,
                     i18n="datasource.root.dir.label",
                     i18n_def="Root dir:")
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.rootDirLabel = LabelWidget(fileConstraintsComposite,
                                        i18n="datasource.root.dir.label",
                                        i18n_def="[Not set]",
                                        sizePolicy=sizePolicy,
                                        stretch_after_widget=1)

        LabelWidget(fileConstraintsComposite,
                    i18n="datasource.file.name.filter.label",
                    i18n_def="Files name filter")

        self.filesExtension = LineEditWidget(fileConstraintsComposite,
                        maxLength=15,
                        width=get_width_of_n_letters(14),
                        text="*",
                        enabled_precheck_handler=self.enabledPrecheckHandler)

        self.recursively = CheckBoxWidget(fileConstraintsComposite,
                        i18n="datasource.search.files.recursively.label",
                        i18n_def="Search files recursively",
                        clicked_handler=self.reload,
                        enabled_precheck_handler=self.enabledPrecheckHandler)

        self.onlyKnownTypes = CheckBoxWidget(fileConstraintsComposite,
                        i18n="datasource.only.known.types.checkbox",
                        i18n_def="Only known types",
                        checked=True,
                        clicked_handler=self.reload,
                        enabled_precheck_handler=self.enabledPrecheckHandler)

    def __createReloadButton__(self, parent):
        self.reloadButton = PushButtonWidget(parent,
                        i18n="datasource.reload.button",
                        i18n_def="Reload",
                        clicked_handler=self.reload,
                        alignment=Qt.AlignRight,
                        enabled_precheck_handler=self.enabledPrecheckHandler)

    def __createTableView__(self, parent):
        self.filesTableView = FilesTableView(parent,
                        model=QStandardItemModel(self),
                        onClickedAction=self.onClickedAction,
                        wizardButtons=(QWizard.NextButton,),
                        wizard_handler=self.wizard,
                        sorting=True,
                        enabled_precheck_handler=self.enabledPrecheckHandler)

    def __createFilesOperationsComposite__(self, parent):
        filesOperations = CompositeWidget(parent,
                                            layout=QHBoxLayout())

        self.filePreviewButton = PushButtonWidget(filesOperations,
                        i18n="datasource.file.preview.button",
                        i18n_def="File preview",
                        stretch_after_widget=1,
                        clicked_handler=self.filePreviewAction,
                        enabled_precheck_handler=self.enabledPrecheckHandler)

        self.selectAllButton = PushButtonWidget(filesOperations,
                        i18n="datasource.accept.select.all.button",
                        i18n_def="Select all",
                        enabled=False,
                        clicked_handler=self.__select_all_handler__,
                        enabled_precheck_handler=self.enabledPrecheckHandler)

        self.unselectAllButton = PushButtonWidget(filesOperations,
                        i18n="datasource.accept.unselect.all.button",
                        i18n_def="Unselect all",
                        enabled=False,
                        clicked_handler=self.__unselect_all_handler__,
                        enabled_precheck_handler=self.enabledPrecheckHandler)

    def chooseRootDirAction(self):
        SettingsFactory.loadSettings(self, Setter(rootDir=None))

        rootDir = QFileDialog.getExistingDirectory(self,
                                    caption=self.chooseRootDirButton.text(),
                                    directory=self.rootDir)
        if rootDir:
            self.rootDir = rootDir + os.path.sep
            SettingsFactory.saveSettings(self, Setter(rootDir=self.rootDir))
            self.rootDirLabel.setText(self.rootDir)
            self.reload()

    def __select_all_handler__(self):
        self.__change_selection__(True)

    def __unselect_all_handler__(self):
        self.__change_selection__(False)

    def __change_selection__(self, _select):
        self.changeEnablemend(False)
        count = self.filesTableView.getRowCount()
        progressManager = ProgressDialogManager(self,
                label_text=("Selecting..." if _select else "Unselecting..."),
                max_value=count)
        with progressManager as progress:
            for idx in range(count):
                if (progress.wasCanceled()):
                    break
                progress.increaseCounter()
                if _select:
                    self.filesTableView.setCheckedRowState(idx, Qt.Checked)
                else:
                    self.filesTableView.setCheckedRowState(idx, Qt.Unchecked)
        self.filesTableView.changeCompleteState()
        self.changeEnablemend(True)

    def filePreviewAction(self):
        showFilesPreviewDialog(
                    self.filesTableView.getSelectedPathAndFilename())

    def reload(self):
        self.changeEnablemend(True)
        if self.rootDirLabel.text():

            self.filesTableView.clear()
            self.changeEnablemend(False)

            iteratorFlag = QDirIterator.Subdirectories \
                            if self.recursively.isChecked() \
                            else QDirIterator.NoIteratorFlags
            nameFilters = QStringList(
                    self.filesExtension.text()) \
                    if len(self.filesExtension.text()) > 0 \
                            and not self.filesExtension.text() \
                                in ("*", "*.*", "", None) \
                    else QStringList()
            self.iterator = QDirIterator(
                                self.rootDirLabel.text(),
                                nameFilters,
                                QDir.Filters(QDir.Files),
                                iteratorFlag)

            with ProgressDialogManager(self) as progress:
                while(self.iterator.next()):
                    if (progress.wasCanceled()):
                        break
                    fileInfo = self.iterator.fileInfo()
                    if fileInfo.size() == 0 or fileInfo.isFile() == False:
                        continue
                    if self.filesExtension.text() in ("*", "*.*", "", None):
                        if (sys.platform == 'win32' \
                            and fileInfo.isExecutable() == True) \
                            or is_text_file(fileInfo.filePath(),
                                    self.onlyKnownTypes.checkState()) == False:
                            continue
                    progress.increaseCounter()

                    checkable = QStandardItem("")
                    checkable.setCheckable(True)
                    filename = QStandardItem(fileInfo.fileName())
                    progress.setLabelText(fileInfo.fileName())
                    size = QStandardItem(str(fileInfo.size()))
                    path = QStandardItem(fileInfo.path())
                    self.filesTableView.addRow((checkable, filename, size, path)) # @IgnorePep8

            self.filesTableView.resizeColumnsToContents()
            self.filesExtension.setFocus()
            self.changeEnablemend(True)

    def onClickedAction(self, idx):
        self.filePreviewButton.setEnabled(True)
        self.filesTableView.onClickedAction(idx)

    def isComplete(self):
        """
        method used by QWizard to check if next/previous buttons have to
        be disabled/enabled (when False/True is returned)
        """
        return self.filesTableView.isCompletedCount()

    def changeEnablemend(self, enabled):
        self.emit(SIGNAL(ENABLED_SIGNAL_NAME), enabled)
        self.chooseRootDirButton.setEnabled(enabled)

    def enabledPrecheckHandler(self, widget):
        """
        only interested widgets return bool value others none value
        """
        if widget in (self.selectAllButton, self.unselectAllButton):
            return self.filesTableView.count() > 0
        elif widget == self.filePreviewButton:
            return self.filesTableView.getSelectedRowCount() > 0

    def getDatasourceModel(self):
        return self.filesTableView.getModel()
예제 #43
0
class MiscellaneousWidget(GroupBoxWidget):
    """
    widget used to set up some specific properties like:
    window size,
    using of internal buffer,
    use line of identity
    """
    @temporarySettingsDecorator()
    def __init__(self, parent, **params):
        get_or_put(params, 'layout', QVBoxLayout())
        get_or_put(params, 'i18n_def', 'Miscellaneous')
        super(MiscellaneousWidget, self).__init__(parent, **params)

        LabelWidget(self, i18n_def='Data window shift: 1')
        self.params = Params(**params)
        self.params.data_accessor.addListener(self,
                                    __MiscellaneousVectorListener__(self))
        self.__window_size__ = __DataWindowSizeWidget__(self,
                                                self.params.data_accessor)

        self.__unitsWidget__ = TimeUnitsWidget(self, i18n_def='Units',
                        default_unit=self.params.data_accessor.signal_x_unit,
                        change_unit_handler=self.changeUnit,
                        layout=QHBoxLayout())
        self.__unitsWidget__.addUnit(OrderUnit)

        self.__use_parameters__ = CompositeWidget(self, layout=QHBoxLayout())
        self.__use_buffer__ = CheckBoxWidget(self.__use_parameters__,
                                             i18n_def='Use buffer',
                                             checked=True)
        self.__use_identity_line__ = CheckBoxWidget(self.__use_parameters__,
                                             i18n_def='Use identity line',
                                             checked=True)

        self.__sample_step__ = __SampleStepWidget__(self,
                                                self.params.data_accessor)

        self.__stepper_size__ = __StepperSizeWidget__(self,
                                                self.params.data_accessor)

    def getUseBuffer(self):
        return self.__use_buffer__.isChecked()

    @temporarySetterDecorator(name='use_buffer',
                              _conv=QVariant.toBool,
                              _getter_handler=getUseBuffer)
    def setUseBuffer(self, use_buffer):
        return self.__use_buffer__.setChecked(use_buffer)

    def getUseIdentityLine(self):
        return self.__use_identity_line__.isChecked()

    @temporarySetterDecorator(name='use_identity_line',
                              _conv=QVariant.toBool,
                              _getter_handler=getUseIdentityLine)
    def setUseIdentityLine(self, use_identity_line):
        self.__use_identity_line__.setChecked(use_identity_line)

    def getWindowSize(self):
        return self.__window_size__.size

    @temporarySetterDecorator(name='window_size',
                              _conv=QVariant.toInt,
                              _getter_handler=getWindowSize)
    def setWindowSize(self, size):
        self.__window_size__.setSize(size)

    def changeUnit(self, _unit):
        self.__window_size__.setUnit(_unit)
        self.__window_size__.setValueInUnit(_unit)

    def getUnit(self):
        return self.__unitsWidget__.getUnit()

    @temporarySetterDecorator(name='window_size_unit',
                              _conv=QVariant.toPyObject,
                              _getter_handler=getUnit)
    def setUnit(self, unit):
        self.changeUnit(unit)
        self.__unitsWidget__.setUnit(unit)

    def getSampleStep(self):
        return self.__sample_step__.step

    @temporarySetterDecorator(name='sample_step',
                              _conv=QVariant.toInt,
                              _getter_handler=getSampleStep)
    def setSampleStep(self, step):
        self.__sample_step__.setStep(step)

    def getStepperSize(self):
        return self.__stepper_size__.size

    @temporarySetterDecorator(name='stepper_size',
                              _conv=QVariant.toInt,
                              _getter_handler=getStepperSize)
    def setStepperSize(self, size):
        self.__stepper_size__.setSize(size)

    def getStepperUnit(self):
        return self.__stepper_size__.unit

    @temporarySetterDecorator(name='stepper_unit',
                              _conv=QVariant.toPyObject,
                              _getter_handler=getStepperUnit,
                              before_name='stepper_size')
    def setStepperUnit(self, unit):
        self.__stepper_size__.changeUnit(unit)