Exemplo n.º 1
0
 def initializePage(self):
     for choice in self.matrix.df.index[1:]:
         # Every choice gets a groupbox
         groupbox = QGroupBox(choice)
         QVBoxLayout(groupbox)
         for criterion in self.matrix.continuous_criteria:
             inner_grid = QHBoxLayout()
             self.add_row(inner_grid, choice, criterion)
             groupbox.layout().addLayout(inner_grid)
             self.grid.addWidget(groupbox)
Exemplo n.º 2
0
    def __init__(self, modules: dict, parent=None):
        super(CodeGenDialog, self).__init__(parent)

        self.modules = modules

        main_layout = QVBoxLayout()

        imports_group_box = QGroupBox('Imports')
        imports_group_box.setLayout(QVBoxLayout())

        info_text_edit = QPlainTextEdit(
            '''I found the following imports in the inspected components. Please unselect all imports whose source code you want me to include in the output. All checked modules remain imported using the import statements. Notice that import alias names (import ... as ...) of course won\'t work when including the module\'s source. Same goes for imports using 'from' (indicated in the list below). And for those, the whole (direct) source will be included if you unselect a module.'''
        )
        info_text_edit.setReadOnly(True)
        imports_group_box.layout().addWidget(info_text_edit)

        imports_scroll_area = QScrollArea()
        imports_scroll_area.setLayout(QVBoxLayout())

        self.import_widget_assignment = {'imports': {}, 'fromimports': {}}

        # imports
        imports_scroll_area.layout().addWidget(QLabel('imports:'))
        for i in modules['imports'].keys():
            import_check_box = QCheckBox(i)
            import_check_box.setChecked(True)
            imports_scroll_area.layout().addWidget(import_check_box)
            self.import_widget_assignment['imports'][import_check_box] = i

        # from-imports
        imports_scroll_area.layout().addWidget(QLabel('\'from\'-imports:'))
        for i in modules['fromimports'].keys():
            names = modules['fromimports'][i][2]
            from_names_list = ', '.join(names)
            import_check_box = QCheckBox(i + ': ' + from_names_list)
            import_check_box.setChecked(True)
            imports_scroll_area.layout().addWidget(import_check_box)
            self.import_widget_assignment['fromimports'][import_check_box] = i

        imports_group_box.layout().addWidget(imports_scroll_area)

        main_layout.addWidget(imports_group_box)

        button_box = QDialogButtonBox()
        button_box.setStandardButtons(QDialogButtonBox.Cancel
                                      | QDialogButtonBox.Ok)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)

        main_layout.addWidget(button_box)

        self.setLayout(main_layout)
        self.resize(500, 500)

        self.setWindowTitle('Source Code Gen Manager')
Exemplo n.º 3
0
    def create_label_and_spinbox_for_advanced_option(self, nexus_string: str,
                                                     group_box: QGroupBox):
        """
        Creates a SpinBox with a label and adds them to GroupBox then returns the SpinBox.
        :param nexus_string: The nexus string label for the SpinBox.
        :param group_box: The GroupBox that the label and SpinBox should be added to.
        :return: The newly created SpinBox.
        """
        label = QLabel(nexus_string)
        spinner = QSpinBox()
        spinner.setRange(self.minimum_spinbox_value,
                         self.maximum_spinbox_value)
        group_box.layout().addRow(label, spinner)

        return spinner
Exemplo n.º 4
0
class UiMainWindow:

    def __init__(self, window: QMainWindow, vscreen: VScreen):
        self.window = window
        self.vscreen = vscreen

        window.setWindowFlags(Qt.Window
                              | Qt.MSWindowsFixedSizeDialogHint
                              | Qt.WindowMinimizeButtonHint
                              | Qt.WindowCloseButtonHint
                              | Qt.CustomizeWindowHint)

        self.centralWidget = QWidget()
        self.centralWidget.setLayout(QVBoxLayout())
        self.centralWidget.layout().setContentsMargins(0, 0, 0, 0)
        window.setCentralWidget(self.centralWidget)

        self.monitor_overview_widget = VScreenOverview(vscreen, window)
        self.centralWidget.layout().addWidget(self.monitor_overview_widget)

        self.sub_widget = QWidget()
        self.sub_layout = QVBoxLayout()
        self.sub_widget.setLayout(self.sub_layout)
        self.centralWidget.layout().addWidget(self.sub_widget)

        self.monitor_info_group = QGroupBox()
        self.monitor_info_group.setLayout(QHBoxLayout())

        for monitor in self.vscreen.monitor_order:
            info_box = QGroupBox("Monitor Information")
            info_box.ui = UiMonitorInfoBox(info_box, monitor)
            self.monitor_info_group.layout().addWidget(info_box)
        self.sub_layout.addWidget(self.monitor_info_group)

        self.button_group = QDialogButtonBox(Qt.Horizontal)
        self.button_group.setStyleSheet('* { button-layout: 2 }')
        self.close_button = self.button_group.addButton("Close", QDialogButtonBox.RejectRole)
        self.adjust_button = self.button_group.addButton("Adjust", QDialogButtonBox.ActionRole)
        self.about_button = self.button_group.addButton("About", QDialogButtonBox.HelpRole)
        self.sub_layout.addWidget(self.button_group)

        self.translate_ui()

    def translate_ui(self):
        self.window.setWindowTitle("HwMonitorAlignment")
        self.monitor_info_group.setTitle("Monitor Setup Information")
        self.close_button.setText("Close")
        self.adjust_button.setText("Adjust")
Exemplo n.º 5
0
    def __draw(self):
        mainW = QWidget()
        mainW.setLayout(QVBoxLayout())

        settingsW = QWidget()
        settingsW.setLayout(QHBoxLayout())

        preCompileSettingsTable = QTableWidget()
        preCompileSettingsGPX = QGroupBox("Pre-Compile Settings")
        preCompileSettingsGPX.setLayout(QHBoxLayout())
        preCompileSettingsGPX.layout().addWidget(preCompileSettingsTable)
        self.loadPreBuildSettings(preCompileSettingsTable)

        postBuildSettingsGPX = QGroupBox("Post Build Settings")
        postBuildSettingsGPX.setLayout(QHBoxLayout())
        postBuildSettingsGPX.layout().addWidget(self.postBuildSettingsTab)
        self.postBuildSettingsTab.setTabsClosable(True)
        self.postBuildSettingsTab.tabBar().addTab(QIcon(), "+")
        self.postBuildSettingsTab.tabBar().setTabButton(
            0, QTabBar.RightSide, None)

        preCompileSettingsTable.verticalHeader().hide()
        preCompileSettingsTable.horizontalHeader().hide()
        header = preCompileSettingsTable.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.Stretch)
        header.setSectionResizeMode(1, QHeaderView.Stretch)

        def handler(index: int):
            self.__currentTabChangedHandler(index)

        self.postBuildSettingsTab.currentChanged.connect(handler)

        handler(0)

        settingsW.layout().addWidget(preCompileSettingsGPX)
        settingsW.layout().addWidget(postBuildSettingsGPX)

        btnW = QWidget()
        btnW.setLayout(QHBoxLayout())
        btnW.layout().addWidget(QLabel())
        btnW.layout().addWidget(QPushButton("Reset"))
        btnW.layout().addWidget(self.genBTN)

        mainW.layout().addWidget(settingsW)
        mainW.layout().addWidget(btnW)
        self.setCentralWidget(mainW)
Exemplo n.º 6
0
    def __init__(self, nodes, parent=None):
        super(PreviewAllCodes_Dialog, self).__init__(parent)

        self.code_update_assignments = {
        }  # {CodeEditor_Small : CodeEditor from NodeContentWidget}
        self.copy_buttons = []

        main_vertical_layout = QVBoxLayout()

        # nodes scroll area
        nodes_scroll_area = QScrollArea(self)
        nodes_scroll_area_widget = QWidget()
        nodes_scroll_area_widget.setLayout(QVBoxLayout())

        # nodes
        for n in nodes:
            c_w: NodeContentWidget = n.content_widget

            # node_scroll_area = QScrollArea(nodes_scroll_area_widget)
            node_group_box = QGroupBox(c_w.get_title(),
                                       nodes_scroll_area_widget)
            node_group_box.setLayout(QHBoxLayout())

            # src code
            src_code_group_box = QGroupBox(self)
            src_code_group_box.setLayout(QVBoxLayout())
            src_code_editor = CodeEditor_Small()
            src_code_editor.setText(c_w.edit_src_code_dialog.get_code())
            src_code_group_box.layout().addWidget(src_code_editor)

            self.code_update_assignments[
                src_code_editor] = c_w.edit_src_code_dialog

            # copy button
            copy_button = QPushButton('copy')
            self.copy_buttons.append(copy_button)
            copy_button.clicked.connect(self.copy_clicked)
            src_code_group_box.layout().addWidget(copy_button)

            # main widget
            main_widget_group_box = None
            if c_w.has_main_widget:
                main_widget_code_editor = CodeEditor_Small()
                main_widget_code_editor.setText(
                    c_w.edit_main_widget_dialog.get_code())
                main_widget_group_box = QGroupBox('main widget', self)
                main_widget_group_box.setLayout(QVBoxLayout())
                main_widget_group_box.layout().addWidget(
                    main_widget_code_editor)

                self.code_update_assignments[
                    main_widget_code_editor] = c_w.edit_main_widget_dialog

                # copy button
                copy_button = QPushButton('copy')
                self.copy_buttons.append(copy_button)
                copy_button.clicked.connect(self.copy_clicked)
                main_widget_group_box.layout().addWidget(copy_button)

            # inputs
            inputs_group_box = QGroupBox(self)
            inputs_group_box.setLayout(QHBoxLayout())

            for i_w in c_w.input_widgets:
                input_widget_code_editor = CodeEditor_Small()
                input_widget_code_editor.setText(
                    i_w.edit_widget_dialog.get_code())
                input_widget_group_box = QGroupBox(i_w.get_name(), self)
                input_widget_group_box.setLayout(QVBoxLayout())
                input_widget_group_box.layout().addWidget(
                    input_widget_code_editor)
                self.code_update_assignments[
                    input_widget_code_editor] = i_w.edit_widget_dialog

                inputs_group_box.layout().addWidget(input_widget_group_box)

                # copy button
                copy_button = QPushButton('copy')
                self.copy_buttons.append(copy_button)
                copy_button.clicked.connect(self.copy_clicked)
                input_widget_group_box.layout().addWidget(copy_button)

            node_group_box.layout().addWidget(src_code_group_box)
            if c_w.has_main_widget:
                node_group_box.layout().addWidget(main_widget_group_box)
            node_group_box.layout().addWidget(inputs_group_box)
            # node_scroll_area.setWidget(node_group_box)
            nodes_scroll_area_widget.layout().addWidget(node_group_box)

        nodes_scroll_area.setWidget(nodes_scroll_area_widget)

        # button box
        self.button_box = QDialogButtonBox(self)
        self.button_box.setStandardButtons(QDialogButtonBox.Ok)
        self.button_box.button(QDialogButtonBox.Ok).clicked.connect(
            self.accepting)

        # merge layouts
        main_vertical_layout.addWidget(nodes_scroll_area)
        main_vertical_layout.addWidget(self.button_box)

        self.setLayout(main_vertical_layout)
        self.resize(1200, 800)
Exemplo n.º 7
0
    def init_ui(self):
        self.vbox = QVBoxLayout()
        self.hbox = QHBoxLayout()

        # Set layout
        self.setLayout(self.vbox)

        # OBS Settings
        group_frame = QGroupBox("OBS")
        group_frame.setLayout(QVBoxLayout())

        label = QLabel("Hostname/IP")
        group_frame.layout().addWidget(label)
        self.obs_host = QLineEdit()
        group_frame.layout().addWidget(self.obs_host)

        label = QLabel("Port")
        group_frame.layout().addWidget(label)
        self.obs_port = QLineEdit()
        self.obs_port.setValidator(QIntValidator(1024, 65535))
        group_frame.layout().addWidget(self.obs_port)

        label = QLabel("Password")
        group_frame.layout().addWidget(label)
        self.auth_password = QLineEdit()
        group_frame.layout().addWidget(self.auth_password)

        self.hbox.addWidget(group_frame)

        # TouchOSC Settings
        group_frame = QGroupBox("TouchOSC")
        group_frame.setLayout(QVBoxLayout())

        label = QLabel("Hostname/IP")
        group_frame.layout().addWidget(label)
        self.touchosc_host = QLineEdit()
        group_frame.layout().addWidget(self.touchosc_host)

        label = QLabel("Port")
        group_frame.layout().addWidget(label)
        self.touchosc_port = QLineEdit()
        self.touchosc_port.setValidator(QIntValidator(1024, 65535))
        group_frame.layout().addWidget(self.touchosc_port)

        self.hbox.addWidget(group_frame)

        # OSC Settings
        group_frame = QGroupBox("OSC")
        group_frame.setLayout(QVBoxLayout())

        label = QLabel("Port")
        group_frame.layout().addWidget(label)
        self.osc_port = QLineEdit()
        self.osc_port.setValidator(QIntValidator(1024, 65535))
        group_frame.layout().addWidget(self.osc_port)

        self.hbox.addWidget(group_frame)

        # Add all to layout
        self.vbox.addLayout(self.hbox)

        # Start button
        icon = QIcon(resource_path('icons/play.png'))
        self.start_button = QPushButton(icon, "Start")
        self.start_button.pressed.connect(self.start_pressed)
        self.vbox.addWidget(self.start_button)

        self.setWindowTitle('OBS TouchOSC')
Exemplo n.º 8
0
class StreamFieldsWidget(QDialog):
    """
    A stream widget containing schema-specific properties.
    """
    def __init__(self, parent, show_only_f142_stream: bool = False):
        super().__init__()
        self.setParent(parent)
        self.setLayout(QGridLayout())
        self.setWindowModality(Qt.WindowModal)
        self.setModal(True)

        self._show_only_f142_stream = show_only_f142_stream
        self.minimum_spinbox_value = 0
        self.maximum_spinbox_value = 100_000_000
        self.advanced_options_enabled = False

        self.hs00_unimplemented_label = QLabel(
            "hs00 (Event histograms) has not yet been fully implemented.")

        self.schema_label = QLabel("Schema: ")
        self.schema_combo = DropDownList()
        self.schema_validator = SchemaSelectionValidator()
        self.schema_combo.setValidator(self.schema_validator)
        self.schema_validator.is_valid.connect(
            partial(validate_general_widget, self.schema_combo))

        self.topic_label = QLabel("Topic: ")
        self.topic_line_edit = QLineEdit()
        self.topic_validator = NoEmptyStringValidator()
        self.topic_line_edit.setValidator(self.topic_validator)
        self.topic_validator.is_valid.connect(
            partial(
                validate_line_edit,
                self.topic_line_edit,
                tooltip_on_reject="Topic name can not be empty.",
            ))
        validate_line_edit(self.topic_line_edit, False)

        self.source_label = QLabel("Source: ")
        self.source_line_edit = QLineEdit()
        self.source_validator = NoEmptyStringValidator()
        self.source_line_edit.setValidator(self.source_validator)
        self.source_validator.is_valid.connect(
            partial(
                validate_line_edit,
                self.source_line_edit,
                tooltip_on_reject="Source name can not be empty.",
            ))
        validate_line_edit(self.source_line_edit, False)

        self.array_size_label = QLabel("Array size: ")
        self.array_size_spinbox = QSpinBox()
        self.array_size_spinbox.setMaximum(np.iinfo(np.int32).max)

        self.array_size_table = QTableWidget(1, 3)
        self.array_size_table.setHorizontalHeaderLabels(["x", "y", "z"])
        self.array_size_table.setVerticalHeaderLabels([""])
        table_height = self.array_size_table.sizeHintForRow(
            0) + self.array_size_table.sizeHintForRow(1)
        self.array_size_table.setMaximumHeight(table_height)
        self.array_size_table.setFrameStyle(QFrame.NoFrame)
        self.array_size_table.horizontalHeader().setSectionResizeMode(
            QHeaderView.Stretch)
        self.array_size_table.resizeColumnsToContents()
        self.array_size_table.resizeRowsToContents()
        self.array_size_table.setItemDelegate(
            ValueDelegate(int, self.array_size_table))

        self.type_label = QLabel("Type: ")
        self.type_combo = QComboBox()
        self.type_combo.addItems(F142_TYPES)
        self.type_combo.setCurrentText("double")

        self.value_units_edit = QLineEdit()
        self.value_units_label = QLabel("Value Units:")

        self.show_advanced_options_button = QPushButton(
            text="Show/hide advanced options")
        self.show_advanced_options_button.setCheckable(True)
        self.show_advanced_options_button.clicked.connect(
            self.advanced_options_button_clicked)

        self._set_up_f142_group_box()
        self._set_up_ev42_group_box()

        self.scalar_radio = QRadioButton(text=SCALAR)
        self.scalar_radio.clicked.connect(partial(self._show_array_size,
                                                  False))
        self.scalar_radio.setChecked(True)
        self.scalar_radio.clicked.emit()

        self.array_radio = QRadioButton(text=ARRAY)
        self.array_radio.clicked.connect(partial(self._show_array_size, True))

        self.schema_combo.currentTextChanged.connect(self._schema_type_changed)
        if self._show_only_f142_stream:
            self.schema_combo.addItems([StreamModules.F142.value])
        else:
            self.schema_combo.addItems([e.value for e in StreamModules])

        self.ok_button = QPushButton("OK")
        self.ok_button.clicked.connect(self.parent().close)

        self.layout().addWidget(self.schema_label, 0, 0)
        self.layout().addWidget(self.schema_combo, 0, 1)

        self.layout().addWidget(self.topic_label, 1, 0)
        self.layout().addWidget(self.topic_line_edit, 1, 1)

        self.layout().addWidget(self.source_label, 2, 0)
        self.layout().addWidget(self.source_line_edit, 2, 1)

        self.layout().addWidget(self.value_units_label, 3, 0)
        self.layout().addWidget(self.value_units_edit, 3, 1)
        self.value_units_label.setVisible(False)
        self.value_units_edit.setVisible(False)

        self.layout().addWidget(self.type_label, 4, 0)
        self.layout().addWidget(self.type_combo, 4, 1)

        self.layout().addWidget(self.scalar_radio, 5, 0)
        self.layout().addWidget(self.array_radio, 5, 1)

        self.layout().addWidget(self.array_size_label, 6, 0)
        self.layout().addWidget(self.array_size_spinbox, 6, 1)
        self.layout().addWidget(self.array_size_table, 6, 1)

        self.layout().addWidget(self.hs00_unimplemented_label, 7, 0, 1, 2)

        # Spans both rows
        self.layout().addWidget(self.show_advanced_options_button, 8, 0, 1, 2)
        self.layout().addWidget(self.f142_advanced_group_box, 9, 0, 1, 2)

        self.layout().addWidget(self.ev42_advanced_group_box, 10, 0, 1, 2)

        self.layout().addWidget(self.ok_button, 11, 0, 1, 2)

        self._schema_type_changed(self.schema_combo.currentText())
        self.parent().parent().field_name_edit.setVisible(False)

    def advanced_options_button_clicked(self):
        self._show_advanced_options(
            show=self.show_advanced_options_button.isChecked())

    def _set_up_ev42_group_box(self):
        """
        Sets up the UI for ev42 advanced options.
        """
        self.ev42_advanced_group_box = QGroupBox(
            parent=self.show_advanced_options_button)
        self.ev42_advanced_group_box.setLayout(QFormLayout())

        self.ev42_adc_pulse_debug_label = QLabel(ADC_PULSE_DEBUG)
        self.ev42_adc_pulse_debug_checkbox = QCheckBox()
        self.ev42_advanced_group_box.layout().addRow(
            self.ev42_adc_pulse_debug_label,
            self.ev42_adc_pulse_debug_checkbox)

        self.ev42_chunk_size_spinner = (
            self.create_label_and_spinbox_for_advanced_option(
                CHUNK_SIZE, self.ev42_advanced_group_box))
        self.ev42_cue_interval_spinner = (
            self.create_label_and_spinbox_for_advanced_option(
                CUE_INTERVAL, self.ev42_advanced_group_box))

    def create_label_and_spinbox_for_advanced_option(self, nexus_string: str,
                                                     group_box: QGroupBox):
        """
        Creates a SpinBox with a label and adds them to GroupBox then returns the SpinBox.
        :param nexus_string: The nexus string label for the SpinBox.
        :param group_box: The GroupBox that the label and SpinBox should be added to.
        :return: The newly created SpinBox.
        """
        label = QLabel(nexus_string)
        spinner = QSpinBox()
        spinner.setRange(self.minimum_spinbox_value,
                         self.maximum_spinbox_value)
        group_box.layout().addRow(label, spinner)

        return spinner

    def _set_up_f142_group_box(self):
        """
        Sets up the UI for the f142 advanced options.
        """
        self.f142_advanced_group_box = QGroupBox(
            parent=self.show_advanced_options_button)
        self.f142_advanced_group_box.setLayout(QFormLayout())
        self.f142_chunk_size_spinner = (
            self.create_label_and_spinbox_for_advanced_option(
                CHUNK_SIZE, self.f142_advanced_group_box))
        self.f142_cue_interval_spinner = (
            self.create_label_and_spinbox_for_advanced_option(
                CUE_INTERVAL, self.f142_advanced_group_box))

    def _show_advanced_options(self, show):
        schema = self.schema_combo.currentText()
        if schema == WriterModules.F142.value:
            self.f142_advanced_group_box.setVisible(show)
        elif schema == WriterModules.EV42.value:
            self.ev42_advanced_group_box.setVisible(show)
        self.advanced_options_enabled = show

    def _show_array_size(self, show: bool):
        self.array_size_spinbox.setVisible(show)
        self.array_size_label.setVisible(show)

    def _schema_type_changed(self, schema: str):
        self.parent().setWindowTitle(f"Editing {schema} stream field")
        self.hs00_unimplemented_label.setVisible(False)
        self.f142_advanced_group_box.setVisible(False)
        self.ev42_advanced_group_box.setVisible(False)
        self.show_advanced_options_button.setVisible(False)
        self.show_advanced_options_button.setChecked(False)
        self.value_units_label.setVisible(False)
        self.value_units_edit.setVisible(False)
        self.array_size_table.setVisible(False)
        if schema == WriterModules.F142.value:
            self.value_units_label.setVisible(True)
            self.value_units_edit.setVisible(True)
            self._set_edits_visible(True, True)
            self.show_advanced_options_button.setVisible(True)
            self.f142_advanced_group_box.setVisible(False)
        elif schema == WriterModules.EV42.value:
            self._set_edits_visible(True, False)
            self.show_advanced_options_button.setVisible(True)
            self.ev42_advanced_group_box.setVisible(False)
        elif schema == WriterModules.ADAR.value:
            self._set_edits_visible(True, False)
            self._show_array_size_table(True)
        elif schema == WriterModules.HS00.value:
            self._set_edits_visible(True, False)
            self.hs00_unimplemented_label.setVisible(True)
        elif schema == WriterModules.NS10.value:
            self._set_edits_visible(True, False, "nicos/<device>/<parameter>")
        elif (schema == WriterModules.TDCTIME.value
              or schema == WriterModules.SENV.value):
            self._set_edits_visible(True, False)

    def _show_array_size_table(self, show: bool):
        self.array_size_label.setVisible(show)
        self.array_size_table.setVisible(show)

    def _set_edits_visible(self, source: bool, type: bool, source_hint=None):
        self.source_label.setVisible(source)
        self.source_line_edit.setVisible(source)
        self.type_label.setVisible(type)
        self.type_combo.setVisible(type)
        self.array_radio.setVisible(type)
        self.scalar_radio.setVisible(type)
        if source_hint:
            self.source_line_edit.setPlaceholderText(source_hint)
        else:
            self.source_line_edit.setPlaceholderText("")

    def get_stream_module(self, parent) -> StreamModule:
        """
        Create the stream module
        :return: The created stream module
        """

        source = self.source_line_edit.text()
        topic = self.topic_line_edit.text()
        stream: StreamModule = None
        type = self.type_combo.currentText()
        current_schema = self.schema_combo.currentText()
        if current_schema == WriterModules.F142.value:
            value_units = self.value_units_edit.text()
            array_size = self.array_size_spinbox.value()
            stream = F142Stream(
                parent_node=parent,
                source=source,
                topic=topic,
                type=type,
                value_units=value_units,
                array_size=array_size,
            )
            if array_size:
                stream.array_size = array_size
            if self.advanced_options_enabled:
                self.record_advanced_f142_values(stream)
        elif current_schema == WriterModules.ADAR.value:
            array_size = []
            for i in range(self.array_size_table.columnCount()):
                table_value = self.array_size_table.item(0, i)
                if table_value:
                    array_size.append(int(table_value.text()))
            stream = ADARStream(parent_node=parent, source=source, topic=topic)
            stream.array_size = array_size
        elif current_schema == WriterModules.EV42.value:
            stream = EV42Stream(parent_node=parent, source=source, topic=topic)
            if self.advanced_options_enabled:
                self.record_advanced_ev42_values(stream)
        elif current_schema == WriterModules.NS10.value:
            stream = NS10Stream(parent_node=parent, source=source, topic=topic)
        elif current_schema == WriterModules.SENV.value:
            stream = SENVStream(parent_node=parent, source=source, topic=topic)
        elif current_schema == WriterModules.HS00.value:
            stream = HS00Stream(  # type: ignore
                parent=parent,
                source=source,
                topic=topic,
                data_type=NotImplemented,
                edge_type=NotImplemented,
                error_type=NotImplemented,
                shape=[],
            )
        elif current_schema == WriterModules.TDCTIME.value:
            stream = TDCTStream(parent_node=parent, source=source, topic=topic)

        return stream

    def record_advanced_f142_values(self, stream: F142Stream):
        """
        Save the advanced f142 properties to the stream data object.
        :param stream: The stream data object to be modified.
        """
        stream.chunk_size = self.f142_chunk_size_spinner.value()
        stream.cue_interval = self.f142_cue_interval_spinner.value()

    def record_advanced_ev42_values(self, stream: EV42Stream):
        """
        Save the advanced ev42 properties to the stream data object.
        :param stream: The stream data object to be modified.
        """
        stream.adc_pulse_debug = self.ev42_adc_pulse_debug_checkbox.isChecked()
        stream.chunk_size = self.ev42_chunk_size_spinner.value()
        stream.cue_interval = self.ev42_cue_interval_spinner.value()

    def fill_in_existing_ev42_fields(self, field: EV42Stream):
        """
        Fill in specific existing ev42 fields into the new UI field.
        :param field: The stream group
        """
        if check_if_advanced_options_should_be_enabled(
            [field.adc_pulse_debug, field.chunk_size, field.cue_interval]):
            self._show_advanced_options(True)
            self._fill_existing_advanced_ev42_fields(field)

    def _fill_existing_advanced_ev42_fields(self, field: EV42Stream):
        """
        Fill the fields in the interface with the existing ev42 stream data.
        :param field: The ev42 stream data object.
        """
        self.ev42_adc_pulse_debug_checkbox.setChecked(field.adc_pulse_debug)
        self.ev42_chunk_size_spinner.setValue(field.chunk_size)
        self.ev42_cue_interval_spinner.setValue(field.cue_interval)

    def fill_in_existing_f142_fields(self, field: F142Stream):
        """
        Fill in specific existing f142 fields into the new UI field.
        :param field: The stream group
        """
        self.type_combo.setCurrentText(field.type)
        if field.array_size is not None:
            self.array_radio.setChecked(True)
            self.scalar_radio.setChecked(False)
            self.array_size_spinbox.setValue(field.array_size)
        else:
            self.array_radio.setChecked(False)
            self.scalar_radio.setChecked(True)
        if field.value_units is not None:
            self.value_units_edit.setText(field.value_units)

        if check_if_advanced_options_should_be_enabled(
            [field.chunk_size, field.cue_interval]):
            self._show_advanced_options(True)
            self._fill_existing_advanced_f142_fields(field)

    def _fill_existing_advanced_f142_fields(self, field: F142Stream):
        """
        Fill the advanced fields in the interface with the existing f142 stream data.
        :param field: The f412 stream data object.
        """
        self.f142_chunk_size_spinner.setValue(field.chunk_size)
        self.f142_cue_interval_spinner.setValue(field.cue_interval)

    def update_existing_stream_info(self, field):
        """
        Fill in stream fields and properties into the new UI field.
        :param field: The stream group
        """
        if isinstance(field, Group):
            field = field.children[0]
        if hasattr(field, "parent_node") and isinstance(
                field.parent_node, Group):
            self.schema_validator.set_group(field.parent_node)
        else:
            self.schema_validator.set_group(None)
        schema = field.writer_module
        self.schema_combo.setCurrentText(schema)
        self.schema_validator.validate(schema, 0)
        self.topic_line_edit.setText(field.topic)
        self.topic_validator.validate(field.topic, 0)
        self.source_line_edit.setText(field.source)
        self.source_validator.validate(field.source, 0)
        if schema == WriterModules.F142.value:
            self.fill_in_existing_f142_fields(field)
        elif schema == WriterModules.EV42.value:
            self.fill_in_existing_ev42_fields(field)
        elif schema == WriterModules.ADAR.value:
            for i, val in enumerate(field.array_size):
                self.array_size_table.setItem(0, i, QTableWidgetItem(str(val)))
Exemplo n.º 9
0
    def __init__(self, parent=None):
        super(SettingsDialog, self).__init__(parent, "Settings")

        mouse_box = QGroupBox("Mouse", self)
        mouse_box.setLayout(QVBoxLayout())

        scroll_layout = QHBoxLayout()

        label = QLabel("Scroll objects with mouse wheel:")
        label.setToolTip(
            "Select an object and scroll up and down to change its type.")
        self._scroll_check_box = QCheckBox("Enabled")
        self._scroll_check_box.setChecked(SETTINGS["object_scroll_enabled"])
        self._scroll_check_box.toggled.connect(self._update_settings)

        scroll_layout.addWidget(label)
        scroll_layout.addStretch(1)
        scroll_layout.addWidget(self._scroll_check_box)

        resize_layout = QHBoxLayout()

        self.lmb_radio = QRadioButton("Left Mouse Button")
        rmb_radio = QRadioButton("Right Mouse Button")

        self.lmb_radio.setChecked(SETTINGS["resize_mode"] == RESIZE_LEFT_CLICK)
        rmb_radio.setChecked(SETTINGS["resize_mode"] == RESIZE_RIGHT_CLICK)

        self.lmb_radio.toggled.connect(self._update_settings)

        radio_group = QButtonGroup()
        radio_group.addButton(self.lmb_radio)
        radio_group.addButton(rmb_radio)

        resize_layout.addWidget(QLabel("Object resize mode:"))
        resize_layout.addStretch(1)
        resize_layout.addWidget(self.lmb_radio)
        resize_layout.addWidget(rmb_radio)

        mouse_box.layout().addLayout(scroll_layout)
        mouse_box.layout().addLayout(resize_layout)

        # emulator command

        self.emulator_command_input = QLineEdit(self)
        self.emulator_command_input.setPlaceholderText("Path to emulator")
        self.emulator_command_input.setText(SETTINGS["instaplay_emulator"])

        self.emulator_command_input.textChanged.connect(self._update_settings)

        self.emulator_path_button = QPushButton(icon("folder.svg"), "", self)
        self.emulator_path_button.pressed.connect(self._get_emulator_path)

        self.command_arguments_input = QLineEdit(self)
        self.command_arguments_input.setPlaceholderText("%f")
        self.command_arguments_input.setText(SETTINGS["instaplay_arguments"])

        self.command_arguments_input.textEdited.connect(self._update_settings)

        self.command_label = QLabel()

        command_box = QGroupBox("Emulator", self)
        command_layout = QVBoxLayout(command_box)

        command_layout.addWidget(QLabel('Emulator command or "path to exe":'))

        command_input_layout = QHBoxLayout()
        command_input_layout.addWidget(self.emulator_command_input)
        command_input_layout.addWidget(self.emulator_path_button)

        command_layout.addLayout(command_input_layout)
        command_layout.addWidget(
            QLabel("Command arguments (%f will be replaced with rom path):"))
        command_layout.addWidget(self.command_arguments_input)
        command_layout.addWidget(QLabel("Command used to play the rom:"))
        command_layout.addWidget(self.command_label)

        command_layout.addWidget(HorizontalLine())

        command_layout.addWidget(
            QLabel("Power up of Mario when playing level:"))
        self.powerup_combo_box = QComboBox()

        for name, x, y, value, p_wing in POWERUPS:
            powerup_icon = self._load_from_png(x, y)

            self.powerup_combo_box.addItem(powerup_icon, name)

        self.powerup_combo_box.currentIndexChanged.connect(
            self._update_settings)

        self.powerup_combo_box.setCurrentIndex(SETTINGS["default_powerup"])

        command_layout.addWidget(self.powerup_combo_box)

        # ----------------------

        layout = QVBoxLayout(self)
        layout.addWidget(mouse_box)
        layout.addWidget(command_box)

        self.update()
Exemplo n.º 10
0
class SaveDialog(QDialog):
    def __init__(self, main_window, nodes_dict: dict, last_export_dir: str):
        super(SaveDialog, self).__init__(parent=main_window)

        self.create_UI()

        self.main_window = main_window
        self.nodes = nodes_dict
        self.export_nodes = []
        self.nodes_check_box_list = []
        self.export_dir = last_export_dir
        self.package_name = ''
        self.set_package_name(self.export_dir)

        # add node-checkboxes
        node_keys = list(self.nodes.keys())
        nodes_list_widget = self.nodes_scroll_area.takeWidget()
        for i in range(len(node_keys)):
            n = node_keys[i]
            node_check_box = QCheckBox(n.title)
            node_check_box.setObjectName('node_check_box_' + str(i))
            node_check_box.setChecked(self.nodes[n])
            nodes_list_widget.layout().addWidget(node_check_box)
            self.nodes_check_box_list.append(node_check_box)
        nodes_list_widget.adjustSize()
        self.nodes_scroll_area.setWidget(nodes_list_widget)

    def create_UI(self):

        # main layouts and widgets
        self.main_vertical_layout = QVBoxLayout(self)
        self.horizontal_layout = QHBoxLayout(self)
        self.nodes_vertical_layout = QVBoxLayout(self)
        self.nodes_vertical_layout.setAlignment(Qt.AlignTop)
        self.export_widget = QWidget(self)
        self.export_widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Expanding)
        self.export_layout = QVBoxLayout(self)
        self.export_layout.setAlignment(Qt.AlignTop)
        self.export_widget.setLayout(self.export_layout)

        # nodes selection section
        self.nodes_group_box = QGroupBox(self)

        self.nodes_group_box.setLayout(QVBoxLayout(self))
        self.nodes_group_box.setTitle('Select nodes to export')

        self.nodes_scroll_area = QScrollArea(self)
        self.nodes_list_widget = QWidget()
        self.nodes_list_widget.setLayout(self.nodes_vertical_layout)

        select_all_button = QPushButton('select all')
        select_all_button.clicked.connect(self.select_all)
        deselect_all_button = QPushButton('deselect all')
        deselect_all_button.clicked.connect(self.deselect_all)
        self.nodes_vertical_layout.addWidget(select_all_button)
        self.nodes_vertical_layout.addWidget(deselect_all_button)

        self.nodes_scroll_area.setWidget(self.nodes_list_widget)
        self.nodes_group_box.layout().addWidget(self.nodes_scroll_area)

        # export settings section
        self.select_package_dir_button = QPushButton('Select package dir',
                                                     self)
        self.select_package_dir_button.clicked.connect(self.select_package_dir)

        self.package_dir_label = QLabel()

        self.export_button = QPushButton('export', self)
        self.export_button.clicked.connect(self.export)

        self.export_layout.addWidget(self.select_package_dir_button)
        self.export_layout.addWidget(self.package_dir_label)
        self.export_layout.addWidget(self.export_button)

        # button box
        self.button_box = QDialogButtonBox(self)
        self.button_box.setStandardButtons(QDialogButtonBox.Ok)
        self.button_box.button(QDialogButtonBox.Ok).clicked.connect(
            self.close_)

        # merge layouts
        self.horizontal_layout.addWidget(self.nodes_group_box)
        self.horizontal_layout.addWidget(self.export_widget)
        self.main_vertical_layout.addLayout(self.horizontal_layout)
        self.main_vertical_layout.addWidget(self.button_box)

        self.setWindowTitle('Export Nodes')
        self.resize(500, 300)

    def select_all(self):
        for cb in self.nodes_check_box_list:
            cb.setChecked(True)

    def deselect_all(self):
        for cb in self.nodes_check_box_list:
            cb.setChecked(False)

    def select_package_dir(self):
        self.export_dir = QFileDialog.getExistingDirectory(
            self,
            'Select the package folder where your nodes shall be exported at',
            '../packages')
        self.set_package_name(self.export_dir)

    def set_package_name(self, path: str):
        self.package_name = os.path.basename(path)
        self.package_dir_label.setText('package dir: ' + path)

    def get_selected_nodes(self):
        nodes = []
        node_keys = list(self.nodes.keys())
        for i in range(len(self.nodes_check_box_list)):
            check_box: QCheckBox = self.nodes_check_box_list[i]
            if check_box.isChecked():
                nodes.append(node_keys[int(check_box.objectName()[15:])])

        return nodes

    def export(self):
        self.export_nodes = self.get_selected_nodes()

        nodes_dict = {}
        module_name_separator = '___'

        nodes_list = []
        node_titles_count = {}  # title (str) : number (int)
        for i in range(len(self.export_nodes)):
            n: Node = self.export_nodes[i]

            c_w: NodeContentWidget = n.content_widget

            node_number = 0
            title = c_w.get_node_title()
            if title in node_titles_count.values():
                node_number = node_titles_count[title]  # index
                node_titles_count[title] += 1
            else:
                node_titles_count[title] = 1

            node_data = c_w.get_json_data(
                package_name=self.package_name,
                module_name_separator=module_name_separator,
                number=node_number)

            nodes_list.append(node_data)

        nodes_dict['nodes'] = nodes_list

        info_dict = {'type': 'Ryven nodes package'}

        whole_dict = {
            **info_dict,
            **nodes_dict
        }  # merges single two dictionaries to one

        json_data = json.dumps(whole_dict)
        print(json_data)

        # create dirs and save files
        if not os.path.isdir(self.export_dir + '/nodes'):
            os.mkdir(self.export_dir + '/nodes')

        save_file(self.export_dir + '/' + self.package_name + '.rpc',
                  json_data)

        for i in range(len(self.export_nodes)):
            n = self.export_nodes[i]
            module_name = nodes_list[i]['module name']

            # create node folder
            node_dir = self.export_dir + '/nodes/' + module_name
            if not os.path.isdir(node_dir):
                os.mkdir(node_dir)

            # create widgets folder
            widgets_dir = node_dir + '/widgets'
            if not os.path.isdir(widgets_dir):
                os.mkdir(widgets_dir)

            n.content_widget.save_metacode_files(
                node_dir=node_dir,
                widgets_dir=widgets_dir,
                module_name_separator=module_name_separator,
                module_name=module_name)

    def close_(self):
        self.main_window.last_exported_nodes = self.get_selected_nodes()
        self.main_window.last_export_path = self.export_dir
        self.close()
Exemplo n.º 11
0
class NodeInput(QWidget):
    def __init__(self, content_widget):
        super(NodeInput, self).__init__()

        self.content_widget = content_widget
        self.widget_type = ''  # gets specified automatically when creating ui below (see self.widget_combo_box_changed)

        # create UI

        # create all layouts
        self.grid_layout = QGridLayout(self)

        # move buttons
        self.up_button = QPushButton('   <   ')
        self.down_button = QPushButton('   >   ')

        # type and label
        self.type_combo_box = QComboBox(self)
        self.type_combo_box.addItem('exec')
        self.type_combo_box.addItem('data')
        self.type_combo_box.currentTextChanged.connect(
            self.type_combo_box_changed)
        self.label_text_edit = QPlainTextEdit(self)
        self.label_text_edit.setPlaceholderText('Label')
        self.label_text_edit.setFixedWidth(self.type_combo_box.width())
        # self.label_text_edit.setMinimumHeight(20)
        self.label_text_edit.setMaximumHeight(56)

        # widget
        self.widget_grid_layout = QGridLayout()
        self.widget_yes_no_group_box = QGroupBox(self)
        self.widget_yes_no_group_box.setLayout(QVBoxLayout())
        self.widget_yes_radio_button = QRadioButton('Yes', self)
        self.widget_yes_radio_button.setChecked(True)
        self.widget_yes_radio_button.toggled.connect(self.widget_yes_set)
        self.widget_no_radio_button = QRadioButton('No', self)
        self.widget_yes_no_group_box.layout().addWidget(
            self.widget_yes_radio_button)
        self.widget_yes_no_group_box.layout().addWidget(
            self.widget_no_radio_button)
        self.widget_grid_layout.addWidget(self.widget_yes_no_group_box, 0, 0,
                                          4, 1)

        self.widget_group_box = QGroupBox(self)
        self.widget_group_box.setLayout(QVBoxLayout())
        self.widget_type_combo_box = QComboBox(self)
        self.widget_type_combo_box.addItem('std line edit')
        self.widget_type_combo_box.addItem('std spin box')
        self.widget_type_combo_box.addItem('custom widget')
        self.widget_type_combo_box.currentTextChanged.connect(
            self.widget_type_combo_box_changed)
        self.custom_widget_line_edit = QLineEdit()
        self.custom_widget_line_edit.setPlaceholderText('input widget name')
        self.custom_widget_line_edit.editingFinished.connect(
            self.widget_name_line_edit_edited)
        self.custom_widget_line_edit.setEnabled(False)

        self.widget_under_label_radio_button = QRadioButton(
            'widget under label')
        self.widget_under_label_radio_button.setChecked(True)
        self.widget_besides_label_radio_button = QRadioButton(
            'widget besides label')

        self.widget_group_box.layout().addWidget(self.widget_type_combo_box)
        self.widget_group_box.layout().addWidget(self.custom_widget_line_edit)
        self.widget_group_box.layout().addWidget(
            self.widget_under_label_radio_button)
        self.widget_group_box.layout().addWidget(
            self.widget_besides_label_radio_button)

        self.widget_grid_layout.addWidget(self.widget_group_box, 0, 3, 4, 1)

        # del button
        self.del_button = QPushButton(self)
        self.del_button.setText(' Del ')
        self.del_button.clicked.connect(self.delete_clicked)

        # create layout
        self.grid_layout.addWidget(self.up_button, 0, 0, 1, 1)
        self.grid_layout.addWidget(self.down_button, 3, 0, 1, 1)
        self.grid_layout.addWidget(self.type_combo_box, 0, 1)
        self.grid_layout.addWidget(self.label_text_edit, 1, 1, 3, 1)
        self.grid_layout.addLayout(self.widget_grid_layout, 0, 2, 4, 1)
        self.grid_layout.addWidget(self.del_button, 0, 4, 4, 1)

    def get_type(self):
        return self.type_combo_box.currentText()

    def get_label(self):
        return self.label_text_edit.toPlainText()

    def has_widget(self):
        return self.widget_yes_radio_button.isChecked()

    def set_has_widget(self, has_widget):
        if has_widget:
            self.widget_yes_radio_button.setChecked(True)
            self.widget_no_radio_button.setChecked(False)
        else:
            self.widget_yes_radio_button.setChecked(False)
            self.widget_no_radio_button.setChecked(True)

    def get_widget_type(self):
        return self.widget_type_combo_box.currentText()

    def set_widget_type(self, new_widget_type):
        self.widget_type_combo_box.setCurrentText(new_widget_type)

    def get_widget_name(self):
        return self.content_widget.prepare_class_name(
            self.custom_widget_line_edit.text())

    def set_widget_name(self, name):
        self.custom_widget_line_edit.setText(name)

    def get_widget_pos(self):
        under = self.widget_under_label_radio_button
        # besides = self.widget_besides_label_radio_button
        return 'under' if under.isChecked() else 'besides'

    def set_widget_pos(self, pos):
        if pos == 'under':
            self.widget_under_label_radio_button.setChecked(True)
            self.widget_besides_label_radio_button.setChecked(False)
        elif pos == 'besides':
            self.widget_under_label_radio_button.setChecked(False)
            self.widget_besides_label_radio_button.setChecked(True)

    def widget_yes_set(self):
        if self.widget_yes_radio_button.isChecked():
            self.widget_group_box.setEnabled(True)
        else:
            self.widget_group_box.setEnabled(False)

    def widget_name_line_edit_edited(self):
        self.custom_widget_line_edit.setText(
            self.content_widget.prepare_class_name(
                self.custom_widget_line_edit.text()))

    def widget_type_combo_box_changed(self, new_text):
        self.widget_type = new_text
        if new_text == 'custom widget':
            self.custom_widget_line_edit.setEnabled(True)
        else:
            self.custom_widget_line_edit.setEnabled(False)

    def set_type(self, new_type):
        self.type_combo_box.setCurrentText(new_type)

    def type_combo_box_changed(self, new_type):
        if new_type == 'data':
            self.widget_grid_layout.setEnabled(True)
        elif new_type == 'exec':
            self.widget_grid_layout.setEnabled(False)

    def set_label(self, new_label):
        self.label_text_edit.setPlainText(new_label)

    def delete_clicked(self):
        ret = QMessageBox.warning(
            self, 'Input',
            'Do you really want to delete this input? All changes'
            'will be lost.', QMessageBox.Yes, QMessageBox.No)
        if ret == QMessageBox.Yes:
            self.content_widget.delete_input(self)
Exemplo n.º 12
0
class SettingsDialog(CustomDialog):
    def __init__(self, parent=None):
        super(SettingsDialog, self).__init__(parent, "Settings")

        mouse_box = QGroupBox("Mouse", self)
        mouse_box.setLayout(QVBoxLayout())

        label = QLabel("Scroll objects with mouse wheel:")
        label.setToolTip(
            "Select an object and scroll up and down to change its type.")
        self._scroll_check_box = QCheckBox("Enabled")
        self._scroll_check_box.setChecked(SETTINGS["object_scroll_enabled"])
        self._scroll_check_box.toggled.connect(self._update_settings)

        scroll_layout = QHBoxLayout()
        scroll_layout.addWidget(label)
        scroll_layout.addStretch(1)
        scroll_layout.addWidget(self._scroll_check_box)

        label = QLabel("Show object names on hover:")
        label.setToolTip(
            "When hovering your cursor over an object in a level, its name and position is shown in a tooltip."
        )
        self._tooltip_check_box = QCheckBox("Enabled")
        self._tooltip_check_box.setChecked(SETTINGS["object_tooltip_enabled"])
        self._tooltip_check_box.toggled.connect(self._update_settings)

        tooltip_layout = QHBoxLayout()
        tooltip_layout.addWidget(label)
        tooltip_layout.addStretch(1)
        tooltip_layout.addWidget(self._tooltip_check_box)

        self.lmb_radio = QRadioButton("Left Mouse Button")
        rmb_radio = QRadioButton("Right Mouse Button")

        self.lmb_radio.setChecked(SETTINGS["resize_mode"] == RESIZE_LEFT_CLICK)
        rmb_radio.setChecked(SETTINGS["resize_mode"] == RESIZE_RIGHT_CLICK)

        self.lmb_radio.toggled.connect(self._update_settings)

        radio_group = QButtonGroup()
        radio_group.addButton(self.lmb_radio)
        radio_group.addButton(rmb_radio)

        resize_layout = QHBoxLayout()
        resize_layout.addWidget(QLabel("Object resize mode:"))
        resize_layout.addStretch(1)
        resize_layout.addWidget(self.lmb_radio)
        resize_layout.addWidget(rmb_radio)

        mouse_box.layout().addLayout(scroll_layout)
        mouse_box.layout().addLayout(tooltip_layout)
        mouse_box.layout().addLayout(resize_layout)

        # -----------------------------------------------
        # GUI theme section

        self.gui_style_box = QGroupBox("GUI", self)
        QHBoxLayout(self.gui_style_box)

        self.gui_style_box.layout().addWidget(QLabel("Style:"))

        for gui_style in GUI_STYLE.keys():
            gui_style = gui_style.capitalize()

            style_radio_button = QRadioButton(gui_style)
            style_radio_button.setChecked(
                SETTINGS["gui_style"] == GUI_STYLE[gui_style.upper()]())
            style_radio_button.toggled.connect(self._update_settings)

            self.gui_style_box.layout().addWidget(style_radio_button)

        # -----------------------------------------------
        # emulator command

        self.emulator_command_input = QLineEdit(self)
        self.emulator_command_input.setPlaceholderText("Path to emulator")
        self.emulator_command_input.setText(SETTINGS["instaplay_emulator"])

        self.emulator_command_input.textChanged.connect(self._update_settings)

        self.emulator_path_button = QPushButton(icon("folder.svg"), "", self)
        self.emulator_path_button.pressed.connect(self._get_emulator_path)

        self.command_arguments_input = QLineEdit(self)
        self.command_arguments_input.setPlaceholderText("%f")
        self.command_arguments_input.setText(SETTINGS["instaplay_arguments"])

        self.command_arguments_input.textEdited.connect(self._update_settings)

        self.command_label = QLabel()

        command_box = QGroupBox("Emulator", self)
        command_layout = QVBoxLayout(command_box)

        command_layout.addWidget(QLabel('Emulator command or "path to exe":'))

        command_input_layout = QHBoxLayout()
        command_input_layout.addWidget(self.emulator_command_input)
        command_input_layout.addWidget(self.emulator_path_button)

        command_layout.addLayout(command_input_layout)
        command_layout.addWidget(
            QLabel("Command arguments (%f will be replaced with rom path):"))
        command_layout.addWidget(self.command_arguments_input)
        command_layout.addWidget(QLabel("Command used to play the rom:"))
        command_layout.addWidget(self.command_label)

        command_layout.addWidget(HorizontalLine())

        command_layout.addWidget(
            QLabel("Power up of Mario when playing level:"))
        self.powerup_combo_box = QComboBox()

        for name, x, y, value, p_wing in POWERUPS:
            powerup_icon = self._load_from_png(x, y)

            self.powerup_combo_box.addItem(powerup_icon, name)

        self.powerup_combo_box.currentIndexChanged.connect(
            self._update_settings)

        self.powerup_combo_box.setCurrentIndex(SETTINGS["default_powerup"])

        command_layout.addWidget(self.powerup_combo_box)

        # ----------------------

        layout = QVBoxLayout(self)
        layout.addWidget(mouse_box)
        layout.addWidget(self.gui_style_box)
        layout.addWidget(command_box)

        self.update()

    def update(self):
        self.command_label.setText(
            f" > {SETTINGS['instaplay_emulator']} {SETTINGS['instaplay_arguments']}"
        )

    def _update_settings(self, _):
        SETTINGS["instaplay_emulator"] = self.emulator_command_input.text()
        SETTINGS["instaplay_arguments"] = self.command_arguments_input.text()

        if self.lmb_radio.isChecked():
            SETTINGS["resize_mode"] = RESIZE_LEFT_CLICK
        else:
            SETTINGS["resize_mode"] = RESIZE_RIGHT_CLICK

        # setup style sheets
        for child_widget in self.gui_style_box.children():
            if isinstance(child_widget, QRadioButton):
                if child_widget.isChecked():
                    selected_gui_style = child_widget.text().upper()

                    loaded_style_sheet = GUI_STYLE[selected_gui_style]()
                    SETTINGS["gui_style"] = loaded_style_sheet

                    self.parent().setStyleSheet(SETTINGS["gui_style"])
                    break

        SETTINGS["object_scroll_enabled"] = self._scroll_check_box.isChecked()
        SETTINGS["object_tooltip_enabled"] = self._tooltip_check_box.isChecked(
        )

        SETTINGS["default_powerup"] = self.powerup_combo_box.currentIndex()

        self.update()

    def _get_emulator_path(self):
        path_to_emulator, _ = QFileDialog.getOpenFileName(
            self, caption="Select emulator executable")

        if not path_to_emulator:
            return

        self.emulator_command_input.setText(path_to_emulator)

    @staticmethod
    def _load_from_png(x: int, y: int) -> QIcon:
        image = png.copy(
            QRect(x * Block.SIDE_LENGTH, y * Block.SIDE_LENGTH,
                  Block.SIDE_LENGTH, Block.SIDE_LENGTH))
        mask = image.createMaskFromColor(
            QColor(*MASK_COLOR).rgb(), Qt.MaskOutColor)
        image.setAlphaChannel(mask)

        pixmap = QPixmap.fromImage(image)
        icon_from_png = QIcon(pixmap)

        return icon_from_png

    def on_exit(self):
        save_settings()

        super(SettingsDialog, self).on_exit()
Exemplo n.º 13
0
class Card(QWidget):
    def __init__(self, parent: QWidget, card_details: Dict[str, Any]):
        super().__init__()
        if parent is not None:
            self.setParent(parent)
        self.model = create_card(card_details)
        self.setupUi()

    def get_card_background_colour(self):
        if isinstance(self.model, SpellCard):
            return QColor(CardColours[CardType.SPELL])
        elif isinstance(self.model, TrapCard):
            return QColor(CardColours[CardType.TRAP])
        else:
            pass

    def setupUi(self):
        self.main_layout = QVBoxLayout()

        self.name_attr_layout = QHBoxLayout()
        self.name_label = QLabel(self.model.name)
        font = self.name_label.font()
        font.setBold(True)
        font.setCapitalization(QFont.AllUppercase)
        font.setPointSize(12)
        self.name_label.setFont(font)
        self.name_label.setMargin(5)
        pixmap = get_attr_icon(self.model.attribute)
        self.attr_icon = QLabel()
        self.attr_icon.setPixmap(pixmap)
        self.attr_icon.setAlignment(Qt.AlignRight)
        self.name_attr_layout.addWidget(self.name_label)
        self.name_attr_layout.addWidget(self.attr_icon)
        self.main_layout.addLayout(self.name_attr_layout)

        self.level_layout = QHBoxLayout()
        self.main_layout.addLayout(self.level_layout)

        self.picture_frame = QFrame()
        self.picture_frame.setFixedSize(250, 250)
        self.picture_frame.setFrameStyle(QFrame.Box | QFrame.Plain)
        self.picture_frame.setFrameShadow(QFrame.Shadow.Raised)
        self.picture_frame.setLineWidth(1)
        self.picture_frame.setContentsMargins(0, 0, 0, 0)
        self.picture_frame.setLayout(QGridLayout())
        self.image_holder = QLabel()

        pixmap = self._get_card_image()
        self.image_holder.setPixmap(
            pixmap.scaled(
                self.picture_frame.width(),
                self.picture_frame.height(),
                Qt.KeepAspectRatio,
            ))

        self.picture_frame.layout().addWidget(self.image_holder)

        self.main_layout.addWidget(self.picture_frame)

        # Card sets here?

        self.desc_group_box = QGroupBox()
        self.desc_group_box.setMaximumWidth(250)
        self.set_up_group_box()
        self.main_layout.addWidget(self.desc_group_box)

        self.id_label = QLabel(self.model.id)
        self.id_label.setAlignment(Qt.AlignLeft)
        self.id_label.setMargin(5)
        self.main_layout.addWidget(self.id_label)

        self.setLayout(self.main_layout)

        pal = QPalette()
        pal.setColor(QPalette.Background, self.get_card_background_colour())
        self.setAutoFillBackground(True)
        self.setPalette(pal)

    def _get_card_image(self):
        image_name = self.model.img_url.split("/")[-1]

        if os.path.exists(self.get_image_path(image_name)):
            image = Image.open(self.get_image_path(image_name))
        else:
            image_data = requests.get(self.model.img_url).content
            image = Image.open(BytesIO(image_data))
            image.save(self.get_image_path(image_name))
        image = image.crop((44, 106, 380, 438))  # this is about correct
        data = image.tobytes("raw", "RGB")
        qimage = QImage(data, image.size[0], image.size[1],
                        QImage.Format_RGB888)
        pixmap = QPixmap.fromImage(qimage)
        return pixmap

    def get_image_path(self, image_name):
        return os.path.join(os.getcwd(), "images", image_name)

    def set_up_group_box(self):
        self.desc_group_box.setLayout(QVBoxLayout())
        self.desc_label = QLabel(self.model.desc)
        self.desc_label.setWordWrap(True)
        self.desc_group_box.layout().addWidget(self.desc_label)
        if isinstance(self.model, (MonsterCard)):
            self.desc_group_box.setTitle(self.get_group_box_title())
            line = QFrame()
            line.setFrameShape((QFrame.HLine))
            line.setFrameShadow(QFrame.Sunken)
            self.desc_group_box.layout().addWidget(line)
            label = QLabel(
                f"ATK/{self.model.attack}  DEF/{self.model.defence}")
            label.setAlignment(Qt.AlignRight)
            self.desc_group_box.layout().addWidget(label)

    def get_group_box_title(self):
        return "[TEST/TEST]"
Exemplo n.º 14
0
class SaveDialog(QDialog):
    def __init__(self, parent, nodes):
        super(SaveDialog, self).__init__(parent)

        self.all_nodes = nodes
        self.export_nodes = []
        self.nodes_check_box_list = []
        self.export_dir = ''
        self.package_name = ''

        # create UI

        # main layouts and widgets
        self.main_vertical_layout = QVBoxLayout(self)
        self.horizontal_layout = QHBoxLayout(self)
        self.nodes_vertical_layout = QVBoxLayout(self)
        self.nodes_vertical_layout.setAlignment(Qt.AlignTop)
        self.export_widget = QWidget(self)
        self.export_widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Expanding)
        self.export_layout = QVBoxLayout(self)
        self.export_layout.setAlignment(Qt.AlignTop)
        self.export_widget.setLayout(self.export_layout)

        # nodes selection section
        self.nodes_group_box = QGroupBox(self)

        self.nodes_group_box.setLayout(QVBoxLayout(self))
        self.nodes_group_box.setTitle('Select nodes to export')

        self.nodes_scroll_area = QScrollArea(self)
        nodes_list_widget = QWidget()
        nodes_list_widget.setLayout(self.nodes_vertical_layout)

        for i in range(len(nodes)):
            n = nodes[i]
            node_check_box = QCheckBox(n.title)
            node_check_box.setObjectName('node_check_box_' + str(i))
            node_check_box.setChecked(True)
            self.nodes_vertical_layout.addWidget(node_check_box)
            self.nodes_check_box_list.append(node_check_box)

        self.nodes_scroll_area.setWidget(nodes_list_widget)
        self.nodes_group_box.layout().addWidget(self.nodes_scroll_area)

        # preview codes dialog
        self.preview_codes_button = QPushButton('preview codes')
        self.preview_codes_button.clicked.connect(self.preview_codes_clicked)

        # export settings section
        self.select_package_dir_button = QPushButton('Select package dir',
                                                     self)
        self.select_package_dir_button.clicked.connect(self.select_package_dir)

        self.package_dir_label = QLabel('package dir: -')

        self.export_button = QPushButton('export', self)
        self.export_button.clicked.connect(self.export)

        self.export_layout.addWidget(self.preview_codes_button)
        self.export_layout.addWidget(self.select_package_dir_button)
        self.export_layout.addWidget(self.package_dir_label)
        self.export_layout.addWidget(self.export_button)

        # button box
        self.button_box = QDialogButtonBox(self)
        self.button_box.setStandardButtons(QDialogButtonBox.Ok)
        self.button_box.button(QDialogButtonBox.Ok).clicked.connect(self.close)

        # merge layouts
        self.horizontal_layout.addWidget(self.nodes_group_box)
        self.horizontal_layout.addWidget(self.export_widget)
        self.main_vertical_layout.addLayout(self.horizontal_layout)
        self.main_vertical_layout.addWidget(self.button_box)

        self.setWindowTitle('Export Nodes')
        self.resize(500, 300)

    def preview_codes_clicked(self):
        accepted = PreviewAllCodes_Dialog(self.all_nodes, self).exec_()

    def select_package_dir(self):
        self.export_dir = QFileDialog.getExistingDirectory(
            self,
            'Select the package folder where your nodes shall be exported at',
            '../packages')
        self.package_name = os.path.basename(self.export_dir)
        self.package_dir_label.setText('package dir: ' + self.export_dir)

    def update_export_nodes(self):
        self.export_nodes.clear()

        for i in range(len(self.nodes_check_box_list)):
            check_box: QCheckBox = self.nodes_check_box_list[i]
            if check_box.isChecked():
                self.export_nodes.append(self.all_nodes[int(
                    check_box.objectName()[15:])])

    def export(self):
        self.update_export_nodes()

        # prevent duplicates
        # EXPLANATION: different Nodes should be able to have same names inside a package. Also two different nodes
        # should both be able to have a custom input widget f.ex. 'InputWidget1' (same name again) although these are
        # different widgets. There is a problem when importing the modules (the python files) in the editor - if an
        # earlier imported module has the same name, then the old one will be used to import f.ex. a widget class which
        # leads of course to errors. In fact, all my modules I use in the editor have to have individual names. That's
        # what I do here. The only convention that has to be followed by the user now would be not to create multiple
        # packages with same name -> which isn't possible!! (two folders with the same name are impossible)
        node_module_names = {}  # Node : Name
        module_name_separator = '___'
        for n in self.export_nodes:
            module_node_title = n.content_widget.get_intern_title()
            pattern = self.package_name + module_name_separator + module_node_title + '\\d+'
            node_module_names[n] = self.package_name + module_name_separator + \
                                   module_node_title + \
                                   str(len([x for x in node_module_names.values() if re.match(pattern, x)]))

        nodes_dict = {}

        nodes_list = []
        for i in range(len(self.export_nodes)):
            n: Node = self.export_nodes[i]

            c_w: NodeContentWidget = n.content_widget

            # save general node info
            node_data = {
                'title': c_w.get_title(),
                'description': c_w.get_description(),
                'type': c_w.get_type(),
                'module name': node_module_names[n],
                'class name': c_w.get_intern_title(),
                'design style': c_w.get_design_style(),
                'color': c_w.node_color.name(),
                'has main widget': c_w.has_main_widget
            }
            if c_w.has_main_widget:
                node_data['widget position'] = c_w.get_main_widget_pos()
                # 'DSL code': c_w.get_dsl_code() if c_w.programming_type == 'DSL' else None}

            input_widgets_list = []
            for i_w in c_w.input_widgets:
                input_widgets_list.append(i_w.get_name())
            node_data['custom input widgets'] = input_widgets_list

            inputs = []  # save inputs
            for inp in c_w.inputs:
                input_data = {'type': inp.get_type(), 'label': inp.get_label()}
                if inp.get_type() == 'data':
                    input_data['has widget'] = inp.has_widget()
                    if inp.has_widget():
                        input_data['widget type'] = inp.get_widget_type()
                        if inp.get_widget_type() == 'custom widget':
                            input_data['widget name'] = inp.get_widget_name()
                        input_data['widget position'] = inp.get_widget_pos()
                inputs.append(input_data)

            outputs = []  # save outputs
            for out in c_w.outputs:
                output_data = {
                    'type': out.get_type(),
                    'label': out.get_label()
                }
                outputs.append(output_data)

            node_data['inputs'] = inputs
            node_data['outputs'] = outputs

            nodes_list.append(node_data)

        nodes_dict['nodes'] = nodes_list

        info_dict = {'type': 'vyScriptFP nodes package'}

        whole_dict = {
            **info_dict,
            **nodes_dict
        }  # merges single two dictionaries to one

        json_data = json.dumps(whole_dict)
        print(json_data)

        # try:
        #     # create main package folder
        #     self.export_dir = self.export_dir+'/'+self.get_package_name()
        #     os.mkdir(self.export_dir)
        #
        #     f = open(self.export_dir+'/'+self.get_package_name()+'.txt', 'w')
        #     f.write(json_data)
        #     f.close()
        # except FileExistsError:
        #     print('File already exists! Please select another location')

        # # clear directory if it already exitsts
        # if len(self.export_dir) > 12 and self.export_dir.find('packages') != -1:
        #     if len(os.listdir(self.export_dir)) > 0:
        #         shutil.rmtree(self.export_dir + '/', ignore_errors=True)
        #         time.sleep(0.001)
        #         os.mkdir(self.export_dir)

        # create dirs and save files
        if not os.path.isdir(self.export_dir + '/nodes'):
            os.mkdir(self.export_dir + '/nodes')

        self.save_file(self.export_dir + '/' + self.package_name + '.pypac',
                       json_data)

        for n in self.export_nodes:
            c_w: NodeContentWidget = n.content_widget
            module_name = node_module_names[n]
            module_node_title = c_w.get_title()
            node_class_name = c_w.get_intern_title()

            # create node folder
            node_dir = self.export_dir + '/nodes/' + module_name
            if not os.path.isdir(node_dir):
                os.mkdir(node_dir)

            # create widgets folder
            widgets_dir = node_dir + '/widgets'
            if not os.path.isdir(widgets_dir):
                os.mkdir(widgets_dir)

            # save source files
            src_code_file_path = node_dir + '/' + module_name + module_name_separator + 'METACODE.py'
            if not os.path.isfile(src_code_file_path):
                meta_code = c_w.get_src_code()
                self.save_file(
                    node_dir + '/' + module_name + module_name_separator +
                    'METACODE.py',
                    meta_code)  # the NI file's name is just the 'module name'

            if c_w.has_main_widget:
                main_widget_src_code_file_path = widgets_dir + '/' + module_name + module_name_separator + 'main_widget' + module_name_separator + 'METACODE.py'
                if not os.path.isfile(main_widget_src_code_file_path):
                    meta_code = c_w.get_main_widget_code()
                    self.save_file(
                        widgets_dir + '/' + module_name +
                        module_name_separator + 'main_widget' +
                        module_name_separator + 'METACODE.py', meta_code)

            for iw in c_w.input_widgets:
                iw: InputWidget = iw
                iw_file_path = widgets_dir + '/' + module_name + module_name_separator + iw.get_name(
                ) + module_name_separator + 'METACODE.py'
                if not os.path.isfile(iw_file_path):
                    meta_code = iw.get_code()
                    self.save_file(
                        widgets_dir + '/' + module_name +
                        module_name_separator + iw.get_name() +
                        module_name_separator + 'METACODE.py', meta_code)

    def save_file(self, file_path, content):
        try:
            os.remove(file_path)
        except OSError:
            pass

        f = open(file_path, 'w')
        f.write(content)
        f.close()
Exemplo n.º 15
0
combo = QComboBox()
combo.addItem("Left to Right")
combo.addItem("Right to Left")
combo.addItem("Random")
combo.addItem("Top down")
combo.addItem("Bottom up")
combo.currentIndexChanged.connect(set_trx_mode)

#update_led_button = QPushButton("Update LEDs")
#update_led_button.clicked.connect(value_update)

image_button = QPushButton("Load image")
image_button.clicked.connect(load_image)

group_interactive.setLayout(QVBoxLayout())
group_interactive.layout().addWidget(FlipdotWidget(pixel_queue))

group_display.setLayout(QVBoxLayout())
box1 = QWidget()
box1.setLayout(QHBoxLayout())
group_display.layout().addWidget(box1)
box1.layout().addWidget(clear_button)
box1.layout().addWidget(light_button)
box1.layout().addWidget(inc_button)
box1.layout().addWidget(ovr_button)

box1.layout().addWidget(test_button)
#box1.layout().addWidget(update_led_button)
box1.layout().addWidget(image_button)
box1.layout().addWidget(combo)
box1.layout().addWidget(set_speed_button)
Exemplo n.º 16
0
class StreamFieldsWidget(QDialog):
    """
    A stream widget containing schema-specific properties.
    """
    def __init__(self, parent):
        super().__init__()
        self.setParent(parent)
        self.setLayout(QGridLayout())
        self.setWindowModality(Qt.WindowModal)
        self.setModal(True)
        self.minimum_spinbox_value = 0
        self.maximum_spinbox_value = 100_000_000
        self.advanced_options_enabled = False

        self.hs00_unimplemented_label = QLabel(
            "hs00 (Event histograms) has not yet been fully implemented.")

        self.schema_label = QLabel("Schema: ")
        self.schema_combo = QComboBox()

        self.topic_label = QLabel("Topic: ")
        self.topic_line_edit = QLineEdit()
        self.topic_line_edit.setPlaceholderText(
            "[broker][:port, default=9092]/topic")

        self.source_label = QLabel("Source: ")
        self.source_line_edit = QLineEdit()

        self.array_size_label = QLabel("Array size")
        self.array_size_spinbox = QSpinBox()
        self.array_size_spinbox.setMaximum(np.iinfo(np.int32).max)

        self.type_label = QLabel("Type: ")
        self.type_combo = QComboBox()
        self.type_combo.addItems(F142_TYPES)
        self.type_combo.setCurrentText("double")

        self.value_units_edit = QLineEdit()
        self.value_units_label = QLabel("Value Units:")

        self.show_advanced_options_button = QPushButton(
            text="Show/hide advanced options")
        self.show_advanced_options_button.setCheckable(True)
        self.show_advanced_options_button.clicked.connect(
            self.advanced_options_button_clicked)

        self._set_up_f142_group_box()
        self._set_up_ev42_group_box()

        self.scalar_radio = QRadioButton(text="Scalar")
        self.scalar_radio.clicked.connect(partial(self._show_array_size,
                                                  False))
        self.scalar_radio.setChecked(True)
        self.scalar_radio.clicked.emit()

        self.array_radio = QRadioButton(text="Array")
        self.array_radio.clicked.connect(partial(self._show_array_size, True))

        self.schema_combo.currentTextChanged.connect(self._schema_type_changed)
        self.schema_combo.addItems([e.value for e in WriterModules])

        self.ok_button = QPushButton("OK")
        self.ok_button.clicked.connect(self.parent().close)

        self.layout().addWidget(self.schema_label, 0, 0)
        self.layout().addWidget(self.schema_combo, 0, 1)

        self.layout().addWidget(self.topic_label, 1, 0)
        self.layout().addWidget(self.topic_line_edit, 1, 1)

        self.layout().addWidget(self.source_label, 2, 0)
        self.layout().addWidget(self.source_line_edit, 2, 1)

        self.layout().addWidget(self.value_units_label, 3, 0)
        self.layout().addWidget(self.value_units_edit, 3, 1)
        self.value_units_label.setVisible(False)
        self.value_units_edit.setVisible(False)

        self.layout().addWidget(self.type_label, 4, 0)
        self.layout().addWidget(self.type_combo, 4, 1)

        self.layout().addWidget(self.scalar_radio, 5, 0)
        self.layout().addWidget(self.array_radio, 5, 1)

        self.layout().addWidget(self.array_size_label, 6, 0)
        self.layout().addWidget(self.array_size_spinbox, 6, 1)

        self.layout().addWidget(self.hs00_unimplemented_label, 7, 0, 1, 2)

        # Spans both rows
        self.layout().addWidget(self.show_advanced_options_button, 8, 0, 1, 2)
        self.layout().addWidget(self.f142_advanced_group_box, 9, 0, 1, 2)

        self.layout().addWidget(self.ev42_advanced_group_box, 10, 0, 1, 2)

        self.layout().addWidget(self.ok_button, 11, 0, 1, 2)

        self._schema_type_changed(self.schema_combo.currentText())

    def advanced_options_button_clicked(self):
        self._show_advanced_options(
            show=self.show_advanced_options_button.isChecked())

    def _set_up_ev42_group_box(self):
        """
        Sets up the UI for ev42 advanced options.
        """
        self.ev42_nexus_elements = [
            NEXUS_INDICES_INDEX_EVERY_MB,
            NEXUS_INDICES_INDEX_EVERY_KB,
            NEXUS_CHUNK_CHUNK_MB,
            NEXUS_CHUNK_CHUNK_KB,
        ]

        self.ev42_nexus_to_spinner_ui_element = {}

        self.ev42_advanced_group_box = QGroupBox(
            parent=self.show_advanced_options_button)
        self.ev42_advanced_group_box.setLayout(QFormLayout())

        self.ev42_adc_pulse_debug_label = QLabel(ADC_PULSE_DEBUG)
        self.ev42_adc_pulse_debug_checkbox = QCheckBox()

        self.ev42_advanced_group_box.layout().addRow(
            self.ev42_adc_pulse_debug_label,
            self.ev42_adc_pulse_debug_checkbox)

        self.add_labels_and_spinboxes_for_advanced_options(
            self.ev42_nexus_elements,
            self.ev42_advanced_group_box,
            self.ev42_nexus_to_spinner_ui_element,
        )

    def add_labels_and_spinboxes_for_advanced_options(self, elements,
                                                      group_box,
                                                      nexus_to_spinner):
        for nexus_string in elements:
            label = QLabel(nexus_string)
            spinner = QSpinBox()
            spinner.setRange(self.minimum_spinbox_value,
                             self.maximum_spinbox_value)

            group_box.layout().addRow(label, spinner)

            nexus_to_spinner[nexus_string] = spinner

    def _set_up_f142_group_box(self):
        """
        Sets up the UI for the f142 advanced options.
        """
        self.f142_advanced_group_box = QGroupBox(
            parent=self.show_advanced_options_button)
        self.f142_advanced_group_box.setLayout(QFormLayout())
        self.f142_nexus_to_spinner_ui_element = {}

        self.f142_nexus_elements = [
            NEXUS_INDICES_INDEX_EVERY_MB,
            NEXUS_INDICES_INDEX_EVERY_KB,
            STORE_LATEST_INTO,
        ]

        self.add_labels_and_spinboxes_for_advanced_options(
            self.f142_nexus_elements,
            self.f142_advanced_group_box,
            self.f142_nexus_to_spinner_ui_element,
        )

    def _show_advanced_options(self, show):
        schema = self.schema_combo.currentText()
        if schema == WriterModules.F142.value:
            self.f142_advanced_group_box.setVisible(show)
        elif schema == WriterModules.EV42.value:
            self.ev42_advanced_group_box.setVisible(show)
        self.advanced_options_enabled = show

    def _show_array_size(self, show: bool):
        self.array_size_spinbox.setVisible(show)
        self.array_size_label.setVisible(show)

    def _schema_type_changed(self, schema: str):
        self.parent().setWindowTitle(f"Editing {schema} stream field")
        self.hs00_unimplemented_label.setVisible(False)
        self.f142_advanced_group_box.setVisible(False)
        self.ev42_advanced_group_box.setVisible(False)
        self.show_advanced_options_button.setVisible(False)
        self.show_advanced_options_button.setChecked(False)
        self.value_units_label.setVisible(False)
        self.value_units_edit.setVisible(False)
        if schema == WriterModules.F142.value:
            self.value_units_label.setVisible(True)
            self.value_units_edit.setVisible(True)
            self._set_edits_visible(True, True)
            self.show_advanced_options_button.setVisible(True)
            self.f142_advanced_group_box.setVisible(False)
        elif schema == WriterModules.EV42.value:
            self._set_edits_visible(True, False)
            self.show_advanced_options_button.setVisible(True)
            self.ev42_advanced_group_box.setVisible(False)
        elif schema == WriterModules.HS00.value:
            self._set_edits_visible(True, False)
            self.hs00_unimplemented_label.setVisible(True)
        elif schema == WriterModules.NS10.value:
            self._set_edits_visible(True, False, "nicos/<device>/<parameter>")
        elif (schema == WriterModules.TDCTIME.value
              or schema == WriterModules.SENV.value):
            self._set_edits_visible(True, False)

    def _set_edits_visible(self, source: bool, type: bool, source_hint=None):
        self.source_label.setVisible(source)
        self.source_line_edit.setVisible(source)
        self.type_label.setVisible(type)
        self.type_combo.setVisible(type)
        self.array_radio.setVisible(type)
        self.scalar_radio.setVisible(type)
        if source_hint:
            self.source_line_edit.setPlaceholderText(source_hint)
        else:
            self.source_line_edit.setPlaceholderText("")

    def get_stream_group(self) -> h5py.Group:
        """
        Create the stream group with a temporary in-memory HDF5 file.
        :return: The created HDF group.
        """

        temp_file = create_temporary_in_memory_file()
        group = temp_file.create_group("children")
        group.create_dataset(name="type", dtype=STRING_DTYPE, data="stream")
        stream_group = group.create_group(
            self.parent().parent().field_name_edit.text())
        stream_group.attrs[CommonAttrs.NX_CLASS] = CommonAttrs.NC_STREAM
        stream_group.create_dataset(name="topic",
                                    dtype=STRING_DTYPE,
                                    data=self.topic_line_edit.text())
        stream_group.create_dataset(
            name="writer_module",
            dtype=STRING_DTYPE,
            data=self.schema_combo.currentText(),
        )

        schema = self.schema_combo.currentText()
        stream_group.create_dataset("source",
                                    dtype=STRING_DTYPE,
                                    data=self.source_line_edit.text())

        if schema == WriterModules.F142.value:
            self._create_f142_fields(stream_group)
        elif schema == WriterModules.EV42.value:
            self._create_ev42_fields(stream_group)
        return stream_group

    def _create_ev42_fields(self, stream_group: h5py.Group):
        """
        Create ev42 fields in the given group if advanced options are specified.
        :param stream_group: The group to apply fields to.
        """
        if self.advanced_options_enabled:
            if self.ev42_adc_pulse_debug_checkbox.isChecked():
                stream_group.create_dataset(
                    ADC_PULSE_DEBUG,
                    dtype=bool,
                    data=self.ev42_adc_pulse_debug_checkbox.isChecked(),
                )
            self._create_dataset_from_spinner(
                stream_group, self.ev42_nexus_to_spinner_ui_element)

    def _create_f142_fields(self, stream_group: h5py.Group):
        """
        Create f142 fields in the given group if advanced options are specified.
        :param stream_group: The group to apply fields to.
        """
        stream_group.create_dataset("type",
                                    dtype=STRING_DTYPE,
                                    data=self.type_combo.currentText())
        if self.array_radio.isChecked():
            stream_group.create_dataset("array_size",
                                        data=self.array_size_spinbox.value())
        if self.value_units_edit.text():
            stream_group.create_dataset("value_units",
                                        data=self.value_units_edit.text())
        if self.advanced_options_enabled:
            self._create_dataset_from_spinner(
                stream_group, self.f142_nexus_to_spinner_ui_element)

    @staticmethod
    def _create_dataset_from_spinner(stream_group: h5py.Group,
                                     nexus_to_spinner_dict: Dict[str,
                                                                 QSpinBox]):
        for (nexus_string, ui_element) in nexus_to_spinner_dict.items():
            if ui_element.value() > 0:
                stream_group.create_dataset(nexus_string,
                                            dtype=int,
                                            data=ui_element.value())

    def fill_in_existing_ev42_fields(self, field: h5py.Group):
        """
        Fill in specific existing ev42 fields into the new UI field.
        :param field: The stream group
        :param new_ui_field: The new UI field to be filled in
        """
        all_ev42_elements = list(self.ev42_nexus_elements)
        all_ev42_elements.append(ADC_PULSE_DEBUG)

        if check_if_advanced_options_should_be_enabled(all_ev42_elements,
                                                       field):
            self._show_advanced_options(True)
            if ADC_PULSE_DEBUG in field.keys():
                self.ev42_adc_pulse_debug_checkbox.setChecked(
                    bool(field[ADC_PULSE_DEBUG][()]))

            fill_in_advanced_options(
                self.ev42_nexus_to_spinner_ui_element.items(), field)

    def fill_in_existing_f142_fields(self, field: h5py.Group):
        """
        Fill in specific existing f142 fields into the new UI field.
        :param field: The stream group
        :param new_ui_field: The new UI field to be filled in
        """
        self.type_combo.setCurrentText(field["type"][()])
        if "array_size" in field.keys():
            self.array_radio.setChecked(True)
            self.scalar_radio.setChecked(False)
            self.array_size_spinbox.setValue(field["array_size"][()])
        else:
            self.array_radio.setChecked(False)
            self.scalar_radio.setChecked(True)

        if check_if_advanced_options_should_be_enabled(
                self.f142_nexus_elements, field):
            self._show_advanced_options(True)
            fill_in_advanced_options(
                self.f142_nexus_to_spinner_ui_element.items(), field)

    def update_existing_stream_info(self, field: h5py.Group):
        """
        Fill in stream fields and properties into the new UI field.
        :param field: The stream group
        :param new_ui_field: The new UI field to be filled in
        """
        schema = field["writer_module"][()]
        self.schema_combo.setCurrentText(str(schema))
        self.topic_line_edit.setText(str(field["topic"][()]))
        self.source_line_edit.setText(str(field["source"][()]))
        if schema == WriterModules.F142.value:
            self.fill_in_existing_f142_fields(field)
        elif schema == WriterModules.EV42.value:
            self.fill_in_existing_ev42_fields(field)
Exemplo n.º 17
0
    def init_ui(self):
        self.vbox = QVBoxLayout()
        self.hbox = QHBoxLayout()

        # Set layout
        self.setLayout(self.vbox)

        # Group list
        vbox3 = QVBoxLayout()
        group_frame = QGroupBox("Device Groups")
        group_frame.setLayout(QVBoxLayout())
        self.group_list = QListWidget()
        self.group_list.itemPressed.connect(self.group_selected)
        group_frame.layout().addWidget(self.group_list)
        vbox3.addWidget(group_frame)

        # Sliders
        self.group_toggle = QCheckBox("Power")
        self.group_toggle.setEnabled(False)
        vbox3.addWidget(self.group_toggle)
        vbox3.addWidget(QLabel("Brightness"))
        self.group_brightness_slider = QSlider(Qt.Orientation.Horizontal)
        self.group_brightness_slider.setEnabled(False)
        self.group_brightness_slider.sliderMoved.connect(
            self.group_brightness_changed)
        vbox3.addWidget(self.group_brightness_slider)
        vbox3.addWidget(QLabel("Color Temperature"))
        self.group_color_slider = QSlider(Qt.Orientation.Horizontal)
        self.group_color_slider.setEnabled(False)
        self.group_color_slider.sliderMoved.connect(self.group_color_changed)
        vbox3.addWidget(self.group_color_slider)

        self.hbox.addLayout(vbox3)

        # moods
        mood_frame = QGroupBox("Moods")
        mood_frame.setLayout(QVBoxLayout())
        self.mood_list = QListWidget()
        self.mood_list.itemPressed.connect(self.mood_selected)
        mood_frame.layout().addWidget(self.mood_list)

        self.hbox.addWidget(mood_frame)

        # Devices in group
        vbox2 = QVBoxLayout()

        device_frame = QGroupBox("Devices in Group")
        device_frame.setLayout(QVBoxLayout())
        self.device_list = QListWidget()
        self.device_list.setEnabled(False)
        self.device_list.itemPressed.connect(self.device_selected)
        device_frame.layout().addWidget(self.device_list)
        vbox2.addWidget(device_frame)

        # Sliders
        self.device_toggle = QCheckBox("Power")
        self.device_toggle.setEnabled(False)
        vbox2.addWidget(self.device_toggle)
        vbox2.addWidget(QLabel("Brightness"))
        self.brightness_slider = QSlider(Qt.Orientation.Horizontal)
        self.brightness_slider.setEnabled(False)
        self.brightness_slider.sliderMoved.connect(self.brightness_changed)
        vbox2.addWidget(self.brightness_slider)
        vbox2.addWidget(QLabel("Color Temperature"))
        self.color_slider = QSlider(Qt.Orientation.Horizontal)
        self.color_slider.setEnabled(False)
        self.color_slider.sliderMoved.connect(self.color_changed)
        vbox2.addWidget(self.color_slider)

        self.hbox.addLayout(vbox2)
        self.vbox.addLayout(self.hbox)

        # Settings button
        icon = QIcon(resource_path('icons/settings.png'))
        self.settings_button = QPushButton(icon, "Settings")
        self.settings_button.pressed.connect(self.settings_pressed)
        self.vbox.addWidget(self.settings_button)

        self.setWindowTitle('TradfriGUI')
        self.re_init()