Exemple #1
0
    def add_level_to_table(self, level):
        row_count = self.levelsTable.rowCount()
        self.levelsTable.setRowCount(row_count + 1)

        checkbox_widget = QWidget(self.levelsTable)
        checkbox_widget.setStyleSheet("QWidget { background-color:none;}")

        checkbox = QCheckBox()
        checkbox.setStyleSheet(
            "QCheckBox::indicator { width: 15px; height: 15px;}")
        checkbox.setChecked(level.enabled)
        checkbox.clicked.connect(level.set_enabled)
        checkbox.clicked.connect(self.level_show_changed)
        checkbox.toggled.connect(level.set_enabled)

        checkbox_layout = QHBoxLayout()
        checkbox_layout.setAlignment(Qt.AlignCenter)
        checkbox_layout.setContentsMargins(0, 0, 0, 0)
        checkbox_layout.addWidget(checkbox)
        checkbox_widget.setLayout(checkbox_layout)

        self.levelsTable.setCellWidget(row_count, 0, checkbox_widget)
        self.levelsTable.setItem(row_count, 1,
                                 QTableWidgetItem(level.levelname))
        self.levelsTable.resizeColumnToContents(1)
    def add_new_row(self, _metadata, row=0):

        self.main_window.postprocessing_ui.table.insertRow(row)

        _layout = QHBoxLayout()
        _widget = QCheckBox()
        _widget.setEnabled(True)
        _layout.addWidget(_widget)
        _layout.addStretch()
        _new_widget = QWidget()
        _new_widget.setLayout(_layout)

        _widget.stateChanged.connect(lambda state=0, row=row:
                                     self.parent.table_select_state_changed(state, row))
        self.main_window_postprocessing_ui.table.setCellWidget(row, 0, _new_widget)

        _item = QTableWidgetItem(_metadata['name'])
        self.main_window_postprocessing_ui.table.setItem(row, 1, _item)

        _item = QTableWidgetItem(_metadata['runs'])
        self.main_window_postprocessing_ui.table.setItem(row, 2, _item)

        if not _metadata['sample_formula']:
            _item = QTableWidgetItem(_metadata['sample_formula'])
            self.main_window_postprocessing_ui.table.setItem(row, 3, _item)

        if not _metadata['mass_density']:
            _item = QTableWidgetItem(_metadata['mass_density'])
            self.main_window_postprocessing_ui.table.setItem(row, 4, _item)

        if not _metadata['radius']:
            _item = QTableWidgetItem(_metadata['radius'])
            self.main_window_postprocessing_ui.table.setItem(row, 5, _item)

        if not _metadata['packing_fraction']:
            _item = QTableWidgetItem(_metadata['packing_fraction'])
            self.main_window_postprocessing_ui.table.setItem(row, 6, _item)

        _widget = QComboBox()
        _widget.addItem("cylindrical")
        _widget.addItem("spherical")
        if _metadata['sample_shape'] == 'spherical':
            _widget.setCurrentIndex(1)
        self.main_window_postprocessing_ui.table.setCellWidget(row, 7, _widget)

        _layout = QHBoxLayout()
        _widget = QCheckBox()
        if _metadata['do_abs_correction'] == 'go':
            _widget.setCheckState(Qt.Checked)
        _widget.setStyleSheet("border:  2px; solid-black")
        _widget.setEnabled(True)
        _layout.addStretch()
        _layout.addWidget(_widget)
        _layout.addStretch()
        _new_widget = QWidget()
        _new_widget.setLayout(_layout)
        self.main_window_postprocessing_ui.table.setCellWidget(row, 8, _new_widget)
Exemple #3
0
    def add_new_row(self, _metadata, row=0):

        self.parent.ui.table.insertRow(row)

        _layout = QHBoxLayout()
        _widget = QCheckBox()
        _widget.setEnabled(True)
        _layout.addWidget(_widget)
        _layout.addStretch()
        _new_widget = QWidget()
        _new_widget.setLayout(_layout)

        _widget.stateChanged.connect(lambda state=0, row=row: self.parent.
                                     table_select_state_changed(state, row))
        self.parent.ui.table.setCellWidget(row, 0, _new_widget)

        _item = QTableWidgetItem(_metadata['name'])
        self.parent.ui.table.setItem(row, 1, _item)

        _item = QTableWidgetItem(_metadata['runs'])
        self.parent.ui.table.setItem(row, 2, _item)

        if not _metadata['sample_formula']:
            _item = QTableWidgetItem(_metadata['sample_formula'])
            self.parent.ui.table.setItem(row, 3, _item)

        if not _metadata['mass_density']:
            _item = QTableWidgetItem(_metadata['mass_density'])
            self.parent.ui.table.setItem(row, 4, _item)

        if not _metadata['radius']:
            _item = QTableWidgetItem(_metadata['radius'])
            self.parent.ui.table.setItem(row, 5, _item)

        if not _metadata['packing_fraction']:
            _item = QTableWidgetItem(_metadata['packing_fraction'])
            self.parent.ui.table.setItem(row, 6, _item)

        _widget = QComboBox()
        _widget.addItem("cylindrical")
        _widget.addItem("spherical")
        if _metadata['sample_shape'] == 'spherical':
            _widget.setCurrentIndex(1)
        self.parent.ui.table.setCellWidget(row, 7, _widget)

        _layout = QHBoxLayout()
        _widget = QCheckBox()
        if _metadata['do_abs_correction'] == 'go':
            _widget.setCheckState(Qt.Checked)
        _widget.setStyleSheet("border:  2px; solid-black")
        _widget.setEnabled(True)
        _layout.addStretch()
        _layout.addWidget(_widget)
        _layout.addStretch()
        _new_widget = QWidget()
        _new_widget.setLayout(_layout)
        self.parent.ui.table.setCellWidget(row, 8, _new_widget)
    def get_level_show_checkbox(self, level):
        checkbox_widget = QWidget(self.table)
        checkbox_widget.setStyleSheet("QWidget { background-color:none;}")

        checkbox = QCheckBox()
        checkbox.setStyleSheet(
            "QCheckBox::indicator { width: 15px; height: 15px;}")
        checkbox.setChecked(level.enabled)

        checkbox_layout = QHBoxLayout()
        checkbox_layout.setAlignment(Qt.AlignCenter)
        checkbox_layout.setContentsMargins(0, 0, 0, 0)
        checkbox_layout.addWidget(checkbox)
        checkbox_widget.setLayout(checkbox_layout)
        return checkbox_widget
Exemple #5
0
    def _create_scrn_summwidget(self, scrn_device, scrn_idx):
        """Create and return a screen detail widget."""
        cb_scrn = QCheckBox(scrn_device.get_nickname(dev=True), self)
        self._scrns_sel_bg.addButton(cb_scrn)
        self._scrns_sel_bg.setId(cb_scrn, scrn_idx)
        if scrn_idx == self._currScrn:
            cb_scrn.setChecked(True)
        cb_scrn.clicked.connect(self._setScrnWidget)
        cb_scrn.setStyleSheet("""
            min-width:6.5em; max-width:6.5em; font-weight:bold;""")

        led_camenbl = SiriusLedState(
            self,
            scrn_device.substitute(prefix=self.prefix, propty='CamEnbl-Sts'))
        led_camenbl.setStyleSheet("min-width:3.2em; max-width:3.2em;")

        cb_scrntype = PyDMEnumComboBox(
            self,
            scrn_device.substitute(prefix=self.prefix, propty='ScrnType-Sel'))
        cb_scrntype.setSizePolicy(QSzPlcy.Minimum, QSzPlcy.Fixed)
        cb_scrntype.setStyleSheet("min-width:4.5em;max-width:4.5em;")

        lb_scrntype = PyDMLabel(
            self,
            scrn_device.substitute(prefix=self.prefix, propty='ScrnType-Sts'))
        lb_scrntype.setStyleSheet("min-width:4.5em; max-width:4.5em;")
        lb_scrntype.setAlignment(Qt.AlignCenter)

        led_scrntype = PyDMLed(self,
                               scrn_device.substitute(prefix=self.prefix,
                                                      propty='ScrnType-Sts'),
                               color_list=[
                                   PyDMLed.LightGreen, PyDMLed.Red,
                                   PyDMLed.Red, PyDMLed.Yellow
                               ])
        led_scrntype.shape = 2
        led_scrntype.setStyleSheet("""min-width:4.5em; max-width:4.5em;""")

        wid = QWidget()
        lay = QGridLayout(wid)
        lay.setAlignment(Qt.AlignCenter)
        lay.addWidget(cb_scrn, 1, 1)
        lay.addWidget(led_camenbl, 1, 2)
        lay.addWidget(cb_scrntype, 1, 3)
        lay.addWidget(lb_scrntype, 1, 4)
        lay.addWidget(led_scrntype, 2, 4)
        return wid
Exemple #6
0
class SiriusScrnView(QWidget):
    """
    Class to read Sirius screen cameras image data.

    To allow saving a grid correctly, control calibrationgrid_flag, which
    indicates if the screen is in calibration grid position.
    You can control it by using the method/Slot updateCalibrationGridFlag.
    """

    save_files = Signal()

    def __init__(self, parent=None, prefix=_VACA_PREFIX, device=None):
        """Initialize object."""
        QWidget.__init__(self, parent=parent)
        self.prefix = prefix
        self.device = SiriusPVName(device)
        self.scrn_prefix = self.device.substitute(prefix=prefix)
        self._receivedData = False
        self.setObjectName(self.scrn_prefix.sec + 'App')

        self.screen_type_conn = SiriusConnectionSignal(
            self.scrn_prefix.substitute(propty='ScrnType-Sts'))
        self.screen_type_conn.new_value_signal.connect(
            self.updateCalibrationGridFlag)
        self._calibrationgrid_flag = self.screen_type_conn.getvalue()
        self.save_files.connect(self._saveGridLocalFiles)
        self.ch_ImgROIHeight = SiriusConnectionSignal(
            self.scrn_prefix.substitute(propty='ImgROIHeight-RB'))
        self.ch_ImgROIWidth = SiriusConnectionSignal(
            self.scrn_prefix.substitute(propty='ImgROIWidth-RB'))
        self.ch_ImgROIOffsetX = SiriusConnectionSignal(
            self.scrn_prefix.substitute(propty='ImgROIOffsetX-RB'))
        self.ch_ImgROIOffsetY = SiriusConnectionSignal(
            self.scrn_prefix.substitute(propty='ImgROIOffsetY-RB'))

        self._setupUi()
        self.setFocus(True)
        self.setFocusPolicy(Qt.StrongFocus)
        self._loadCalibrationGrid(default=True)

    @property
    def calibrationgrid_flag(self):
        """Indicate if the screen device is in calibration grid position."""
        return self._calibrationgrid_flag

    @Slot(int)
    def updateCalibrationGridFlag(self, new_state):
        """Update calibrationgrid_flag property."""
        self._calibrationgrid_flag = new_state
        if new_state == 1:
            self.pushbutton_savegrid.setEnabled(True)
        else:
            self.pushbutton_savegrid.setEnabled(False)

    def _setupUi(self):
        self.cameraview_widget = QWidget()
        self.cameraview_widget.setLayout(self._cameraviewLayout())

        self.settings_widget = QWidget(self)
        self.settings_widget.setLayout(self._settingsLayout())
        self.settings_widget.setStyleSheet("""
            .QLabel{
                min-width: 5em;}
            QLabel{
                qproperty-alignment: AlignCenter;}""")

        self.calibrationgrid_widget = QWidget(self)
        self.calibrationgrid_widget.setLayout(self._calibrationgridLayout())
        self.calibrationgrid_widget.setSizePolicy(QSzPlcy.Expanding,
                                                  QSzPlcy.Expanding)
        self.calibrationgrid_widget.layout().setAlignment(Qt.AlignHCenter)
        self.tab = QTabWidget(self)
        self.tab.setStyleSheet("""
            QTabWidget::pane {
                border-left: 2px solid gray;
                border-bottom: 2px solid gray;
                border-right: 2px solid gray;
            }""")
        self.tab.addTab(self.settings_widget, 'Camera Settings')
        self.tab.addTab(self.calibrationgrid_widget, 'Calibration')

        self.statistics_groupBox = QGroupBox('Statistics', self)
        self.statistics_groupBox.setLayout(self._statisticsLayout())
        self.statistics_groupBox.setSizePolicy(QSzPlcy.Expanding,
                                               QSzPlcy.Expanding)
        self.statistics_groupBox.setStyleSheet("""
            .QLabel{
                min-width:0.28em; max-width:0.28em;
                min-height:1.29em; max-height:1.29em;}
            QLabel{
                qproperty-alignment: AlignCenter;}
            PyDMWidget{
                min-width:4.84em; max-width:4.84em;
                min-height:1.29em; max-height:1.29em;}""")

        self.trigger_groupBox = QGroupBox('Trigger', self)
        if 'TB' in self.device or 'BO' in self.device:
            trg_prefix = 'AS-Fam:TI-Scrn-TBBO'
        elif 'TS' in self.device:
            trg_prefix = 'TS-Fam:TI-Scrn'
        hbl = QHBoxLayout(self.trigger_groupBox)
        hbl.addWidget(
            HLTriggerSimple(parent=self.trigger_groupBox,
                            device=trg_prefix,
                            prefix=self.prefix))
        self.trigger_groupBox.setLayout(hbl)
        self.trigger_groupBox.setStyleSheet("""
            PyDMWidget{
                min-width:4.84em; max-width:4.84em;
                min-height:1.29em; max-height:1.29em;}""")

        vlay = QVBoxLayout()
        vlay.addWidget(self.statistics_groupBox)
        vlay.addWidget(self.trigger_groupBox)
        vlay.setSpacing(10)

        lay = QGridLayout(self)
        lay.setHorizontalSpacing(10)
        lay.setVerticalSpacing(10)
        lay.addWidget(self.cameraview_widget, 0, 0, 1, 2)
        lay.addWidget(self.tab, 1, 0)
        lay.addLayout(vlay, 1, 1)
        lay.setRowStretch(0, 15)
        lay.setRowStretch(1, 7)

    def _cameraviewLayout(self):
        label = QLabel(self.device, self)
        label.setStyleSheet("""font-weight: bold;max-height:1.29em;""")
        label.setAlignment(Qt.AlignCenter)
        self.image_view = _SiriusImageView(
            parent=self,
            image_channel=self.scrn_prefix.substitute(propty='ImgData-Mon'),
            width_channel=self.scrn_prefix.substitute(propty='ImgROIWidth-RB'),
            offsetx_channel=self.scrn_prefix.substitute(
                propty='ImgROIOffsetX-RB'),
            offsety_channel=self.scrn_prefix.substitute(
                propty='ImgROIOffsetY-RB'),
            maxwidth_channel=self.scrn_prefix.substitute(
                propty='ImgMaxWidth-Cte'),
            maxheight_channel=self.scrn_prefix.substitute(
                propty='ImgMaxHeight-Cte'))
        self.image_view.setObjectName('ScrnView')
        self.image_view.normalizeData = True
        self.image_view.readingOrder = self.image_view.Clike
        self.image_view.maxRedrawRate = 15
        self.image_view.setStyleSheet("""
            #ScrnView{min-width:30em; min-height:24em;}""")
        self.image_view.failToSaveGrid.connect(self._showFailToSaveGridMsg)
        self.image_view.receivedData.connect(self._setReceivedDataFlag)

        lay = QGridLayout()
        lay.setContentsMargins(0, 0, 0, 0)
        lay.addWidget(label, 0, 1)
        lay.addItem(QSpacerItem(40, 2, QSzPlcy.Preferred, QSzPlcy.Fixed), 1, 1)
        lay.addWidget(self.image_view, 2, 1)
        return lay

    def _calibrationgridLayout(self):
        self.checkBox_showgrid = QCheckBox('Show', self)
        self.checkBox_showgrid.setEnabled(False)
        self.checkBox_showgrid.setStyleSheet("""
            min-width:4em; max-width:4em;
            min-height:1.29em; max-height:1.29em;""")
        self.checkBox_showgrid.toggled.connect(
            self.image_view.showCalibrationGrid)
        self.pushbutton_savegrid = QPushButton('Save', self)
        self.pushbutton_savegrid.setEnabled(False)
        self.pushbutton_savegrid.setStyleSheet("""
            min-width:4em; max-width:4em;
            min-height:1.29em; max-height:1.29em;""")
        self.pushbutton_savegrid.clicked.connect(self._saveCalibrationGrid)
        self.pushbutton_loadgrid = QPushButton('Load', self)
        self.pushbutton_loadgrid.setStyleSheet("""
            min-width:4em; max-width:4em;
            min-height:1.29em; max-height:1.29em;""")
        self.pushbutton_loadgrid.clicked.connect(self._loadCalibrationGrid)
        hbox_grid = QHBoxLayout()
        hbox_grid.addWidget(self.checkBox_showgrid)
        hbox_grid.addWidget(self.pushbutton_savegrid)
        hbox_grid.addWidget(self.pushbutton_loadgrid)

        lb = QLabel('Show levels <')
        lb.setStyleSheet("min-width:7em;max-width:7em;")
        self.spinbox_gridfilterfactor = QSpinBoxPlus()
        self.spinbox_gridfilterfactor.setMaximum(100)
        self.spinbox_gridfilterfactor.setMinimum(0)
        self.spinbox_gridfilterfactor.setValue(
            self.image_view.calibration_grid_filterfactor)
        self.spinbox_gridfilterfactor.editingFinished.connect(
            self._setCalibrationGridFilterFactor)
        self.spinbox_gridfilterfactor.setStyleSheet("""
            min-width:4em; max-width:4em;""")
        hbox_filter = QHBoxLayout()
        hbox_filter.setSpacing(0)
        hbox_filter.addWidget(lb)
        hbox_filter.addWidget(self.spinbox_gridfilterfactor)
        hbox_filter.addWidget(QLabel(' %'))

        lb = QLabel('Remove border: ')
        lb.setStyleSheet("min-width:7em;max-width:7em;")
        self.spinbox_removeborder = QSpinBoxPlus()
        self.spinbox_removeborder.setMaximum(512)
        self.spinbox_removeborder.setMinimum(0)
        self.spinbox_removeborder.setValue(
            self.image_view.calibration_grid_removeborder)
        self.spinbox_removeborder.editingFinished.connect(
            self._setCalibrationGridBorder2Remove)
        self.spinbox_removeborder.setStyleSheet("""
            min-width:4em; max-width:4em;""")
        hbox_remove = QHBoxLayout()
        hbox_remove.setSpacing(0)
        hbox_remove.addWidget(lb)
        hbox_remove.addWidget(self.spinbox_removeborder)
        hbox_remove.addWidget(QLabel(' px'))

        hbox_EnblLED = _create_propty_layout(parent=self,
                                             prefix=self.scrn_prefix,
                                             propty='EnblLED',
                                             propty_type='enbldisabl',
                                             width=4.68)

        lay = QFormLayout()
        lay.addItem(QSpacerItem(1, 10, QSzPlcy.Ignored, QSzPlcy.Preferred))
        lay.addRow('  Grid: ', hbox_grid)
        lay.addItem(QSpacerItem(1, 10, QSzPlcy.Ignored, QSzPlcy.Preferred))
        lay.addRow('  ', hbox_filter)
        lay.addRow('  ', hbox_remove)
        lay.addItem(QSpacerItem(1, 20, QSzPlcy.Ignored, QSzPlcy.Preferred))
        lay.addRow('  LED: ', hbox_EnblLED)
        lay.addItem(QSpacerItem(1, 10, QSzPlcy.Ignored, QSzPlcy.Preferred))
        lay.setLabelAlignment(Qt.AlignRight)
        lay.setFormAlignment(Qt.AlignCenter)
        return lay

    def _settingsLayout(self):
        label_CamEnbl = QLabel('Enable: ', self)
        hbox_CamEnbl = _create_propty_layout(parent=self,
                                             prefix=self.scrn_prefix,
                                             propty='CamEnbl',
                                             propty_type='enbldisabl')

        label_CamAcqPeriod = QLabel('Acquire\nPeriod [s]:', self)
        hbox_CamAcqPeriod = _create_propty_layout(parent=self,
                                                  prefix=self.scrn_prefix,
                                                  propty='CamAcqPeriod',
                                                  propty_type='sprb',
                                                  width=5.0)

        label_CamExposureTime = QLabel('Exposure\nTime [us]:', self)
        hbox_CamExposureTime = _create_propty_layout(parent=self,
                                                     prefix=self.scrn_prefix,
                                                     propty='CamExposureTime',
                                                     propty_type='sprb',
                                                     width=5.0)

        label_CamGain = QLabel('Gain[dB]:', self)
        hbox_CamGain = _create_propty_layout(parent=self,
                                             prefix=self.scrn_prefix,
                                             propty='CamGain',
                                             width=5.0,
                                             propty_type='sprb')

        label_AutoGain = QLabel('Auto Gain: ', self)
        self.pb_autogain = PyDMPushButton(
            label='',
            icon=qta.icon('mdi.auto-fix'),
            parent=self,
            pressValue=1,
            init_channel=self.scrn_prefix.substitute(propty='CamAutoGain-Cmd'))
        self.pb_autogain.setObjectName('autog')
        self.pb_autogain.setStyleSheet(
            "#autog{min-width:25px; max-width:25px; icon-size:20px;}")

        cam_prefix = SiriusPVName(self.scrn_prefix).substitute(dev='ScrnCam')
        label_Reset = QLabel('Reset: ', self)
        self.pb_dtl = PyDMPushButton(
            label='',
            icon=qta.icon('fa5s.sync'),
            parent=self,
            pressValue=1,
            init_channel=cam_prefix.substitute(propty='Rst-Cmd'))
        self.pb_dtl.setObjectName('reset')
        self.pb_dtl.setStyleSheet(
            "#reset{min-width:25px; max-width:25px; icon-size:20px;}")

        self.pb_details = QPushButton(qta.icon('fa5s.ellipsis-h'), '', self)
        self.pb_details.setToolTip('More settings')
        self.pb_details.setObjectName('detail')
        self.pb_details.setStyleSheet(
            "#detail{min-width:25px; max-width:25px; icon-size:20px;}")
        self.pb_details.setSizePolicy(QSzPlcy.Expanding, QSzPlcy.Preferred)
        util.connect_window(self.pb_details,
                            _ScrnSettingsDetails,
                            parent=self,
                            prefix=self.prefix,
                            device=self.device)

        hbox_aux = QHBoxLayout()
        hbox_aux.addWidget(self.pb_dtl, alignment=Qt.AlignLeft)
        hbox_aux.addWidget(self.pb_details, alignment=Qt.AlignRight)

        lay = QFormLayout()
        lay.setFormAlignment(Qt.AlignCenter)
        lay.addRow(label_CamEnbl, hbox_CamEnbl)
        lay.addRow(label_CamAcqPeriod, hbox_CamAcqPeriod)
        lay.addRow(label_CamExposureTime, hbox_CamExposureTime)
        lay.addRow(label_CamGain, hbox_CamGain)
        lay.addRow(label_AutoGain, self.pb_autogain)
        lay.addRow(label_Reset, hbox_aux)
        return lay

    def _statisticsLayout(self):
        # - Method
        label_Method = QLabel('CalcMethod:', self)
        label_Method.setStyleSheet("min-width:7em;")

        self.comboBox_Method = QComboBox(self)
        self.comboBox_Method.addItem('DimFei', 0)
        self.comboBox_Method.addItem('NDStats', 1)
        self.comboBox_Method.setCurrentIndex(0)
        self.comboBox_Method.setStyleSheet("""
            QComboBox::item {height: 1em;}
            QComboBox{min-width:6em;}""")
        self.comboBox_Method.currentIndexChanged.connect(
            self._handleShowStatistics)

        # - Centroid
        label_Centroid = QLabel('Centroid [mm]: ', self)
        label_Centroid.setStyleSheet("min-width:7em;")
        label_i_Center = QLabel('(', self)
        self.PyDMLabel_CenterXDimFei = PyDMLabel(
            parent=self,
            init_channel=self.scrn_prefix.substitute(
                propty='CenterXDimFei-Mon'))
        self.PyDMLabel_CenterXDimFei.setStyleSheet(
            'min-width:4em; max-width:4em;')
        self.PyDMLabel_CenterXNDStats = PyDMLabel(
            parent=self,
            init_channel=self.scrn_prefix.substitute(
                propty='CenterXNDStats-Mon'))
        self.PyDMLabel_CenterXNDStats.setStyleSheet(
            'min-width:4em; max-width:4em;')
        self.PyDMLabel_CenterXNDStats.setVisible(False)
        label_m_Center = QLabel(',', self)
        self.PyDMLabel_CenterYDimFei = PyDMLabel(
            parent=self,
            init_channel=self.scrn_prefix.substitute(
                propty='CenterYDimFei-Mon'))
        self.PyDMLabel_CenterYDimFei.setStyleSheet(
            'min-width:4em; max-width:4em;')
        self.PyDMLabel_CenterYNDStats = PyDMLabel(
            parent=self,
            init_channel=self.scrn_prefix.substitute(
                propty='CenterYNDStats-Mon'))
        self.PyDMLabel_CenterYNDStats.setStyleSheet(
            'min-width:4em; max-width:4em;')
        self.PyDMLabel_CenterYNDStats.setVisible(False)
        label_f_Center = QLabel(')', self)

        # - Sigma
        label_Sigma = QLabel('Sigma [mm]: ', self)
        label_Sigma.setStyleSheet("min-width:7em;")
        label_i_Sigma = QLabel('(', self)
        self.PyDMLabel_SigmaXDimFei = PyDMLabel(
            parent=self,
            init_channel=self.scrn_prefix.substitute(
                propty='SigmaXDimFei-Mon'))
        self.PyDMLabel_SigmaXDimFei.setStyleSheet(
            'min-width:4em; max-width:4em;')
        self.PyDMLabel_SigmaXNDStats = PyDMLabel(
            parent=self,
            init_channel=self.scrn_prefix.substitute(
                propty='SigmaXNDStats-Mon'))
        self.PyDMLabel_SigmaXNDStats.setStyleSheet(
            'min-width:4em; max-width:4em;')
        self.PyDMLabel_SigmaXNDStats.setVisible(False)
        label_m_Sigma = QLabel(',', self)
        self.PyDMLabel_SigmaYDimFei = PyDMLabel(
            parent=self,
            init_channel=self.scrn_prefix.substitute(
                propty='SigmaYDimFei-Mon'))
        self.PyDMLabel_SigmaYDimFei.setStyleSheet(
            'min-width:4em; max-width:4em;')
        self.PyDMLabel_SigmaYNDStats = PyDMLabel(
            parent=self,
            init_channel=self.scrn_prefix.substitute(
                propty='SigmaYNDStats-Mon'))
        self.PyDMLabel_SigmaYNDStats.setStyleSheet(
            'min-width:4em; max-width:4em;')
        self.PyDMLabel_SigmaYNDStats.setVisible(False)
        label_f_Sigma = QLabel(')', self)

        # - Theta
        label_Theta = QLabel('Theta [rad]: ')
        label_Theta.setStyleSheet("min-width:7em;")
        label_i_Theta = QLabel('(', self)
        self.PyDMLabel_ThetaDimFei = PyDMLabel(
            parent=self,
            init_channel=self.scrn_prefix.substitute(propty='ThetaDimFei-Mon'))
        self.PyDMLabel_ThetaDimFei.setStyleSheet("max-width:12em;")
        self.PyDMLabel_ThetaNDStats = PyDMLabel(
            parent=self,
            init_channel=self.scrn_prefix.substitute(
                propty='ThetaNDStats-Mon'))
        self.PyDMLabel_ThetaNDStats.setStyleSheet("max-width:12em;")
        self.PyDMLabel_ThetaNDStats.setVisible(False)
        label_f_Theta = QLabel(')', self)

        lay = QGridLayout()
        lay.addWidget(label_Method, 1, 1, 1, 3)
        lay.addWidget(self.comboBox_Method, 1, 3, 1, 3)
        lay.addWidget(label_Centroid, 3, 1, alignment=Qt.AlignCenter)
        lay.addWidget(label_i_Center, 3, 2)
        lay.addWidget(self.PyDMLabel_CenterXDimFei, 3, 3)
        lay.addWidget(self.PyDMLabel_CenterXNDStats, 3, 3)
        lay.addWidget(label_m_Center, 3, 4)
        lay.addWidget(self.PyDMLabel_CenterYDimFei, 3, 5)
        lay.addWidget(self.PyDMLabel_CenterYNDStats, 3, 5)
        lay.addWidget(label_f_Center, 3, 6)
        lay.addWidget(label_Sigma, 5, 1, alignment=Qt.AlignCenter)
        lay.addWidget(label_i_Sigma, 5, 2)
        lay.addWidget(self.PyDMLabel_SigmaXDimFei, 5, 3)
        lay.addWidget(self.PyDMLabel_SigmaXNDStats, 5, 3)
        lay.addWidget(label_m_Sigma, 5, 4)
        lay.addWidget(self.PyDMLabel_SigmaYDimFei, 5, 5)
        lay.addWidget(self.PyDMLabel_SigmaYNDStats, 5, 5)
        lay.addWidget(label_f_Sigma, 5, 6)
        lay.addWidget(label_Theta, 7, 1, alignment=Qt.AlignCenter)
        lay.addWidget(label_i_Theta, 7, 2)
        lay.addWidget(self.PyDMLabel_ThetaDimFei, 7, 3, 1, 3)
        lay.addWidget(self.PyDMLabel_ThetaNDStats, 7, 3, 1, 3)
        lay.addWidget(label_f_Theta, 7, 6)
        return lay

    def _handleShowStatistics(self, visible):
        self.PyDMLabel_CenterXDimFei.setVisible(not visible)
        self.PyDMLabel_CenterXNDStats.setVisible(visible)
        self.PyDMLabel_CenterYDimFei.setVisible(not visible)
        self.PyDMLabel_CenterYNDStats.setVisible(visible)
        self.PyDMLabel_ThetaDimFei.setVisible(not visible)
        self.PyDMLabel_ThetaNDStats.setVisible(visible)
        self.PyDMLabel_SigmaXDimFei.setVisible(not visible)
        self.PyDMLabel_SigmaXNDStats.setVisible(visible)
        self.PyDMLabel_SigmaYDimFei.setVisible(not visible)
        self.PyDMLabel_SigmaYNDStats.setVisible(visible)

    def _saveCalibrationGrid(self):
        t = Thread(target=self._saveCalibrationGrid_thread, daemon=True)
        t.start()

    def _saveCalibrationGrid_thread(self):
        roi_h = float(self.ch_ImgROIHeight.value)
        roi_w = float(self.ch_ImgROIWidth.value)
        roi_offsetx = float(self.ch_ImgROIOffsetX.value)
        roi_offsety = float(self.ch_ImgROIOffsetY.value)

        cond = roi_h != float(self.image_view.image_maxheight) or \
            roi_w != float(self.image_view.image_maxwidth) or \
            roi_offsetx != 0 or roi_offsety != 0
        if cond:
            # Disable camera acquisition and wait for disabling
            self.PyDMStateButton_CamEnbl.send_value_signal[int].emit(0)
            state = self.SiriusLedState_CamEnbl.state
            while state == 1:
                time.sleep(0.1)
                state = self.SiriusLedState_CamEnbl.state

            # Change ROI to get entire image
            self.ch_ImgROIHeight.send_value_signal[float].emit(
                float(self.image_view.image_maxheight))
            self.ch_ImgROIWidth.send_value_signal[float].emit(
                float(self.image_view.image_maxwidth))
            self.ch_ImgROIOffsetX.send_value_signal[float].emit(0)
            self.ch_ImgROIOffsetY.send_value_signal[float].emit(0)

        # Enable led and wait for status
        self.PyDMStateButton_EnblLED.send_value_signal[int].emit(1)
        while not self.SiriusLedState_EnblLED.state:
            time.sleep(0.1)

        # Enable camera acquisition and wait for receiveing first frame
        self._receivedData = False
        self.PyDMStateButton_CamEnbl.send_value_signal[int].emit(1)
        while not self._receivedData:
            time.sleep(0.1)

        # Save grid
        self.image_view.saveCalibrationGrid()

        if cond:
            # Disable camera acquisition and wait for disabling
            self.PyDMStateButton_CamEnbl.send_value_signal[int].emit(0)
            state = self.SiriusLedState_CamEnbl.state
            while state == 1:
                time.sleep(0.1)
                state = self.SiriusLedState_CamEnbl.state

            # Change ROI to original size
            self.ch_ImgROIHeight.send_value_signal[float].emit(roi_h)
            self.ch_ImgROIWidth.send_value_signal[float].emit(roi_w)
            self.ch_ImgROIOffsetX.send_value_signal[float].emit(roi_offsetx)
            self.ch_ImgROIOffsetY.send_value_signal[float].emit(roi_offsety)

            # Enable camera acquisition
            self.PyDMStateButton_CamEnbl.send_value_signal[int].emit(1)

        # Enable showing saved grid
        time.sleep(0.1)
        self.checkBox_showgrid.setEnabled(True)
        self.save_files.emit()

    def _saveGridLocalFiles(self):
        home = os.path.expanduser('~')
        folder_month = datetime.now().strftime('%Y-%m')
        folder_day = datetime.now().strftime('%Y-%m-%d')
        path = os.path.join(home, 'mounts', 'screens-iocs', folder_month,
                            folder_day)
        if not os.path.exists(path):
            os.makedirs(path)
        fn, _ = QFileDialog.getSaveFileName(
            self, 'Save Grid As...', path + '/' + self.device +
            datetime.now().strftime('_%Y-%m-%d_%Hh%Mmin'), '*.npy')
        if not fn:
            return False

        path_default = os.path.join(home, 'mounts', 'screens-iocs', 'default')
        if not os.path.exists(path_default):
            os.makedirs(path_default)
        fn_default = path_default + '/' + self.device

        grid = self.image_view.calibrationGrid
        width = self.image_view.imageWidth
        data = np.append(width, grid)
        np.save(fn, data)
        np.save(fn_default, data)

    def _loadCalibrationGrid(self, default=False):
        home = os.path.expanduser('~')
        if not default:
            folder_month = datetime.now().strftime('%Y-%m')
            path = os.path.join(home, 'mounts', 'screens-iocs', folder_month)
            fn, _ = QFileDialog.getOpenFileName(self, 'Load Grid...', path,
                                                '*.npy')
            if not fn:
                return
            if self.device not in fn:
                ans = QMessageBox.question(
                    self, 'Warning',
                    'The name of the selected file does not contain the name' +
                    ' of this screen. Are you sure you\'re loading this grid?',
                    QMessageBox.Yes, QMessageBox.Cancel)
                if ans == QMessageBox.Cancel:
                    return
        else:
            path = os.path.join(home, 'mounts', 'screens-iocs', 'default')
            fn = path + '/' + self.device + '.npy'

        try:
            data = np.load(fn)
            self.image_view.calibrationGrid = data
        except Exception as e:
            if not default:
                QMessageBox.critical(
                    self, 'Error',
                    'Could not load calibration grid from file ' + fn + '. ' +
                    '\nError message: ' + str(e), QMessageBox.Ok)
            return

        # Enable showing saved grid
        self.checkBox_showgrid.setEnabled(True)

    def _setReceivedDataFlag(self):
        self._receivedData = True

    def _setCalibrationGridFilterFactor(self):
        self.image_view.set_calibration_grid_filterfactor(
            self.spinbox_gridfilterfactor.value())

    def _setCalibrationGridBorder2Remove(self):
        self.image_view.set_calibration_grid_border2remove(
            self.spinbox_removeborder.value())

    @Slot()
    def _showFailToSaveGridMsg(self):
        QMessageBox.warning(self, 'Warning',
                            'Could not save calibration grid!', QMessageBox.Ok)
Exemple #7
0
class AboutView(QDialog):
    def __init__(self, parent, presenter, version_text, date_text = None):
        super(AboutView, self).__init__(parent)
        self.background_pixmap = QPixmap(':/images/First_use_Background.png')
        self.mantid_pixmap = QPixmap(':/images/mantid_smaller.png')
        self.lbl_version = QLabel()
        self.clb_release_notes = QCommandLinkButton()
        self.clb_sample_datasets = QCommandLinkButton()
        self.clb_mantid_introduction = QCommandLinkButton()
        self.clb_python_introduction = QCommandLinkButton()
        self.clb_python_in_mantid = QCommandLinkButton()
        self.clb_extending_mantid = QCommandLinkButton()
        self.cb_facility = QComboBox()
        self.cb_instrument = QComboBox()
        self.pb_manage_user_directories = QPushButton()
        self.chk_allow_usage_data = QCheckBox()
        self.lbl_privacy_policy = QLabel()
        self.chk_do_not_show_until_next_release = QCheckBox()
        self.pb_close = QPushButton()
        self.setupUI()
        self.customize_layout(version_text, date_text)
        self.presenter = presenter

    def paintEvent(self, event):
        scaled_background = self.background_pixmap.scaled(self.rescale_w(self.background_pixmap.width()),
                                                          self.rescale_h(self.background_pixmap.height()),
                                                          Qt.KeepAspectRatio,
                                                          Qt.SmoothTransformation)

        scaled_mantid = self.mantid_pixmap.scaled(self.rescale_w(self.mantid_pixmap.width()),
                                                  self.rescale_h(self.mantid_pixmap.height()),
                                                  Qt.KeepAspectRatio,
                                                  Qt.SmoothTransformation)
        qp = QPainter()
        qp.begin(self)
        qp.drawPixmap(0, 0, scaled_background)
        qp.drawPixmap(self.width() - scaled_mantid.width(), self.height()-scaled_mantid.height(), scaled_mantid)
        qp.end()

    def determine_dialog_dimensions(self):
        width = REFERENCE_WIDTH
        height = REFERENCE_HEIGHT

        screen = None
        try:
            if hasattr(QGuiApplication,"screenAt"):
                screen = QGuiApplication.screenAt(self.parent().geometry().center())
            else:
                # get the screen from the last top level window
                windows = QGuiApplication.topLevelWindows()
                screen = windows[-1].screen()
        except Exception:
            # something failed just take the primary screen
            screen = QGuiApplication.primaryScreen()

        if screen is not None:
            screen_width = screen.size().width()
            screen_height = screen.size().height()

            # the proportion of the whole window size for the about screen
            window_scaling = 0.4
            width = int(screen_width * window_scaling)

            # also calculate the intended width but using the hieght and a standard screen aspect ratio
            width_by_height= int(screen_height * WIDESCREEN_ASPECT_RATIO * window_scaling)
            # take the smaller of the width from the screen width and height
            if width_by_height < width:
                width = width_by_height

            # set a minimum size
            if width < REFERENCE_WIDTH:
                width = REFERENCE_WIDTH

            # calculate height from the width and aspect ratio
            height = int(width / REFERENCE_ASPECT_RATIO)

        return width, height

    def rescale_w(self, value):
        return int(value * (self.width() / REFERENCE_WIDTH))

    def rescale_h(self, value):
        return int(value * (self.height() / REFERENCE_HEIGHT))

    def setupUI(self):
        width, height  = self.determine_dialog_dimensions()

        self.setMinimumSize(width, height)
        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.setWindowTitle("About Mantid Workbench")
        self.setStyleSheet(f"""QDialog {{
    background-color: rgb(190, 230, 190);
}}
QLabel{{
    font: {self.rescale_w(14)}px;
}}
QPushButton{{
    font: {self.rescale_w(14)}px;
}}
QCommandLinkButton{{
    font: {self.rescale_w(22)}px;
    background-color: rgba(255, 255, 255, 0);
    border-radius: {self.rescale_w(15)}px;
}}
QCommandLinkButton:hover {{
    background-color: rgba(45, 105, 45, 40);
}}""")

        # version label section at th etop
        parent_layout = QVBoxLayout()
        parent_layout.addSpacerItem(QSpacerItem(self.rescale_w(20),self.rescale_h(70),vPolicy=QSizePolicy.Fixed))
        self.lbl_version.setText("version ")
        self.lbl_version.setIndent(self.rescale_w(115))
        self.lbl_version.setStyleSheet(f"""color: rgb(215, 215, 215);
font: {self.rescale_w(28)}pt;
font-weight: bold;
font-size: {self.rescale_w(28)}px""")
        parent_layout.addWidget(self.lbl_version)
        parent_layout.addSpacerItem(QSpacerItem(self.rescale_w(20),self.rescale_h(40),
                                                vPolicy=QSizePolicy.MinimumExpanding))

        # split into the two columns
        two_box_layout = QHBoxLayout()
        # left side Welcome and Tutorial
        left_layout = QVBoxLayout()
        left_layout.setContentsMargins(self.rescale_w(5), 0, self.rescale_w(10), 0)
        left_layout.setSpacing(0)
        # welcome label
        lbl_welcome = QLabel()
        lbl_welcome.setStyleSheet(f"color: rgb(45, 105, 45); font-size: {self.rescale_w(28)}px;")
        lbl_welcome.setText("Welcome")
        left_layout.addWidget(lbl_welcome)
        # release notes
        self.setup_command_link_button(self.clb_release_notes, "Release Notes",
                                       ':/images/Notepad-Bloc-notes-icon-48x48.png')
        left_layout.addWidget(self.clb_release_notes)
        # sample datasets
        self.setup_command_link_button(self.clb_sample_datasets, "Sample Datasets",
                                       ':/images/download-icon-48x48.png')
        left_layout.addWidget(self.clb_sample_datasets)
        # Tutorials Label
        lbl_tutorials = QLabel()
        lbl_tutorials.setStyleSheet(f"color: rgb(45, 105, 45); font-size: {self.rescale_w(28)}px;")
        lbl_tutorials.setText("Tutorials")
        left_layout.addWidget(lbl_tutorials)
        # Mantid Introduction
        self.setup_command_link_button(self.clb_mantid_introduction, "Mantid Introduction",
                                       ':/images/Misc-Tutorial-icon-48x48.png')
        left_layout.addWidget(self.clb_mantid_introduction)
        # Introduction to python
        self.setup_command_link_button(self.clb_python_introduction, "Introduction to Python",
                                       ':/images/Python-icon-48x48.png')
        left_layout.addWidget(self.clb_python_introduction)
        # Python in Mantid
        self.setup_command_link_button(self.clb_python_in_mantid, "Python In Mantid",
                                       ':/images/Circle_cog_48x48.png')
        left_layout.addWidget(self.clb_python_in_mantid)
        # Extending Mantid with python
        self.setup_command_link_button(self.clb_extending_mantid, "Extending Mantid with Python",
                                       ':/images/Plugin-Python-icon-48x48.png')
        left_layout.addWidget(self.clb_extending_mantid)

        # right hand side Setup and facility icons
        right_layout = QVBoxLayout()
        right_layout.setSpacing(0)
        # personal setup
        grp_personal_setup = QGroupBox()
        grp_personal_setup.setStyleSheet(f"""QGroupBox {{
     border: {self.rescale_w(3)}px solid  rgb(38, 128, 20);;
     border-radius: {self.rescale_w(10)}px;
     background-color: rgb(240, 240, 240);
}}
QGroupBox QLabel{{
    font: {self.rescale_w(12)}px;
    color: rgb(121, 121, 121);
}}
QGroupBox QComboBox{{
    font: {self.rescale_w(12)}px;
}}
font: {self.rescale_w(12)}px;
""")
        grp_personal_setup_layout = QVBoxLayout()
        grp_personal_setup_layout.setContentsMargins(self.rescale_w(9),
                                                     self.rescale_h(1),
                                                     self.rescale_w(9),
                                                     self.rescale_h(9))
        grp_personal_setup_layout.setSpacing(0)
        grp_personal_setup.setLayout(grp_personal_setup_layout)
        lbl_personal_setup = QLabel()
        lbl_personal_setup.setStyleSheet(f"color: rgb(38, 128, 20);\nfont-size: {self.rescale_w(18)}px;")
        lbl_personal_setup.setText("Personal Setup")
        lbl_personal_setup.setAlignment(Qt.AlignHCenter)
        grp_personal_setup_layout.addWidget(lbl_personal_setup)
        personal_setup_form_layout = QFormLayout()
        personal_setup_form_layout.setHorizontalSpacing(self.rescale_w(5))
        personal_setup_form_layout.setVerticalSpacing(self.rescale_h(5))
        personal_setup_form_layout.setLabelAlignment(Qt.AlignRight)
        # default Facility
        lbl_default_facilty = QLabel()
        lbl_default_facilty.setText("Default Facility")
        personal_setup_form_layout.addRow(lbl_default_facilty, self.cb_facility)
        # default instrument
        lbl_default_instrument = QLabel()
        lbl_default_instrument.setText("Default Instrument")
        personal_setup_form_layout.addRow(lbl_default_instrument, self.cb_instrument)
        # Set Data Directories
        lbl_mud = QLabel()
        lbl_mud.setText("Set data directories")
        self.pb_manage_user_directories.setText("Manage User Directories")
        personal_setup_form_layout.addRow(lbl_mud, self.pb_manage_user_directories)
        # Usage data
        lbl_allow_usage_data = QLabel()
        lbl_allow_usage_data.setText("Report Usage Data")
        usagelayout = QHBoxLayout()
        usagelayout.setContentsMargins(0, 0, 0, 0)
        self.chk_allow_usage_data.setChecked(True)
        self.chk_allow_usage_data.setStyleSheet(f"padding: {self.rescale_w(4)}px;")
        usagelayout.addWidget(self.chk_allow_usage_data)
        usagelayout.addSpacerItem(QSpacerItem(self.rescale_w(40), self.rescale_h(20), hPolicy=QSizePolicy.Expanding))
        self.lbl_privacy_policy.setText(r'<html><head/><body><p>'
                                        r'<a href="https://www.mantidproject.org/MantidProject:Privacy_policy'
                                        r'#Usage_Data_recorded_in_Mantid">'
                                        r'<span style=" text-decoration: underline; color:#0000ff;">'
                                        r'Privacy Policy</span></a></p></body></html>')
        self.lbl_privacy_policy.setOpenExternalLinks(False)
        usagelayout.addWidget(self.lbl_privacy_policy)
        personal_setup_form_layout.addRow(lbl_allow_usage_data,usagelayout)
        grp_personal_setup_layout.addLayout(personal_setup_form_layout)
        right_layout.addWidget(grp_personal_setup)
        right_layout.addSpacerItem(QSpacerItem(self.rescale_w(20), self.rescale_h(40), vPolicy=QSizePolicy.Expanding))

        # facility icons
        # Row one
        icon_layout_top = QHBoxLayout()
        icon_layout_top.setContentsMargins(0, self.rescale_h(10), 0, 0)
        icon_layout_top.setSpacing(0)
        icon_layout_top.addWidget(self.create_label_with_image(112, 50, ':/images/ISIS_Logo_Transparent.gif'))
        icon_layout_top.addSpacerItem(QSpacerItem(self.rescale_w(10), self.rescale_h(20), hPolicy=QSizePolicy.Fixed))
        icon_layout_top.addWidget(self.create_label_with_image(94, 50, ':/images/ess_logo_transparent_small.png'))
        icon_layout_top.addSpacerItem(QSpacerItem(self.rescale_w(40), 20,hPolicy=QSizePolicy.Expanding))
        right_layout.addLayout(icon_layout_top)
        # Row two
        icon_layout_middle = QHBoxLayout()
        icon_layout_middle.setContentsMargins(0, self.rescale_h(10), 0, 0)
        icon_layout_middle.setSpacing(0)
        icon_layout_middle.addWidget(self.create_label_with_image(200, 30, ':/images/Ornl_hfir_sns_logo_small.png'))
        icon_layout_middle.addSpacerItem(QSpacerItem(self.rescale_w(40), self.rescale_h(20),
                                                     hPolicy=QSizePolicy.Expanding))
        right_layout.addLayout(icon_layout_middle)
        # Row three
        icon_layout_bottom = QHBoxLayout()
        icon_layout_bottom.setContentsMargins(0, self.rescale_h(10), 0, 0)
        icon_layout_bottom.setSpacing(0)
        icon_layout_bottom.addWidget(self.create_label_with_image(110, 40, ':/images/Tessella_Logo_Transparent.gif'))
        icon_layout_bottom.addSpacerItem(QSpacerItem(self.rescale_w(10), self.rescale_h(20), hPolicy=QSizePolicy.Fixed))
        icon_layout_bottom.addWidget(self.create_label_with_image(50, 50, ':/images/ILL_logo.png'))
        icon_layout_bottom.addSpacerItem(QSpacerItem(self.rescale_w(10), self.rescale_h(20), hPolicy=QSizePolicy.Fixed))
        icon_layout_bottom.addWidget(self.create_label_with_image(92, 50, ':/images/CSNS_Logo_Short.png'))
        icon_layout_bottom.addSpacerItem(QSpacerItem(self.rescale_w(40), self.rescale_h(20),
                                                     hPolicy=QSizePolicy.Expanding))
        right_layout.addLayout(icon_layout_bottom)

        # end the two box layout
        two_box_layout.addLayout(left_layout)
        two_box_layout.addLayout(right_layout)
        parent_layout.addLayout(two_box_layout)

        # footer
        footer_layout = QHBoxLayout()
        # do not show again
        do_not_show_layout = QVBoxLayout()
        do_not_show_layout.setContentsMargins(self.rescale_w(15), 0, 0, 0)
        do_not_show_layout.setSpacing(self.rescale_w(2))
        do_not_show_layout.addSpacerItem(QSpacerItem(1,self.rescale_h(1), vPolicy=QSizePolicy.Expanding))
        lbl_update = QLabel()
        lbl_update.setMinimumSize(self.rescale_w(400),0)
        lbl_update.setStyleSheet("color: rgb(25,125,25);")
        lbl_update.setText('You can revisit this dialog by selecting "About" on the Help menu.')
        lbl_update.setAlignment(Qt.AlignBottom)
        do_not_show_layout.addWidget(lbl_update)

        do_not_show_checkbox_layout = QHBoxLayout()
        self.chk_do_not_show_until_next_release.setChecked(True)
        do_not_show_checkbox_layout.addWidget(self.chk_do_not_show_until_next_release)
        do_not_show_checkbox_layout.addSpacerItem(QSpacerItem(self.rescale_w(10), self.rescale_h(2),
                                                              hPolicy=QSizePolicy.Fixed))
        lbl_do_not_show = QLabel()
        lbl_do_not_show.setStyleSheet("color: rgb(25,125,25);")
        lbl_do_not_show.setText('Do not show again until next release')
        do_not_show_checkbox_layout.addWidget(lbl_do_not_show)
        do_not_show_checkbox_layout.addSpacerItem(QSpacerItem(self.rescale_w(40),10, hPolicy=QSizePolicy.Expanding))
        do_not_show_layout.addLayout(do_not_show_checkbox_layout)
        footer_layout.addLayout(do_not_show_layout)

        # Close button
        close_button_layout = QVBoxLayout()
        close_button_layout.addSpacerItem(QSpacerItem(20,self.rescale_h(15), vPolicy=QSizePolicy.Expanding))
        self.pb_close.setText("Close")
        self.pb_close.setDefault(True)
        close_button_layout.addWidget(self.pb_close)
        footer_layout.addLayout(close_button_layout)
        footer_layout.addSpacerItem(QSpacerItem(self.rescale_w(100), self.rescale_h(20), hPolicy=QSizePolicy.Fixed))
        parent_layout.addLayout(footer_layout)
        self.setLayout(parent_layout)

        self.setAttribute(Qt.WA_DeleteOnClose, True)

    def setup_command_link_button(self, link_button, text, image_location, width=40, height=40):
        link_button.setText(text)
        link_button.setIconSize(QSize(self.rescale_w(width), self.rescale_h(height)))
        link_button.setIcon(QIcon(QPixmap(image_location)))
        return link_button

    def create_label_with_image(self, width, height, image_location):
        label_with_image = QLabel()
        label_with_image.setMinimumSize(self.rescale_w(width), self.rescale_h(height))
        label_with_image.setMaximumSize(self.rescale_w(width), self.rescale_h(height))
        label_with_image.setPixmap(QPixmap(image_location))
        label_with_image.setScaledContents(True)
        return label_with_image

    def customize_layout(self, version_text, date_text):
        self.setWindowTitle(self.windowTitle() + " "
                            + version_text)
        version_label = version_text
        # add a date if it is an official release
        if date_text and len(version_text) < 10:
            # strip off the first few characters that will be "day, "
            version_label += " ({0})".format(date_text[5:])
        self.lbl_version.setText(self.lbl_version.text() + version_label)

    def closeEvent(self, event):
        self.presenter.save_on_closing()
        self.deleteLater()
        super(AboutView, self).closeEvent(event)
class MainWindowLightsOut(QMainWindow):
    """Main Window."""
    def __init__(self):
        """Init Main Window."""
        super().__init__()

        # Title and set icon
        self.setWindowTitle(f"LightsOut by ok97465 - {VER}")

        icon = QIcon()
        icon.addPixmap(QPixmap(r'ok_64x64.ico'), QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)

        # Setup toolbar
        self.toolbar = QToolBar()
        self.new_btn = None
        self.clear_btn = None
        self.n_lights_1axis_spinbox = None
        self.show_solution_chkbox = None
        self.setup_toolbar()

        # Setup Button
        self.btn_grid_table = QTableWidget(self)

        # Setup Status Bar
        self.n_clicked = 0
        self.clicked_label = QLabel("0", self)
        self.n_solution_1_label = QLabel("0", self)
        self.setup_status_bar()

        # Setup info  of lights out
        self.manage_puzzle = ManageLightsOutPuzzle()
        self.new_game()

        # Setup Main Layout
        self.setCentralWidget(self.btn_grid_table)
        self.resize_main_window()

        QTimer.singleShot(100, self.resize_main_window)

    def resize_main_window(self):
        """Resize mainwindow to fit table."""
        self.toolbar.adjustSize()
        self.statusBar().adjustSize()
        w = CELL_SIZE * self.manage_puzzle.n_lights_1axis
        w += self.btn_grid_table.frameWidth() * 2

        w = max([w, self.toolbar.width(), self.statusBar().width()])

        h = CELL_SIZE * self.manage_puzzle.n_lights_1axis
        h += self.btn_grid_table.frameWidth() * 2
        h += self.toolbar.frameSize().height()
        h += self.statusBar().height()

        self.resize(w, h)

    def new_game(self):
        """Create New Game."""
        self.manage_puzzle.new_puzzle(self.n_lights_1axis_spinbox.value())
        self.setup_btn_grid(self.manage_puzzle.n_lights_1axis)
        self.show_puzzle()
        self.n_solution_1_label.setText(
            f"{self.manage_puzzle.count_1_of_solution()}")
        self.resize_main_window()

    def setup_toolbar(self):
        """Set up toolbar."""
        self.addToolBar(self.toolbar)
        self.toolbar.setMovable(False)
        self.toolbar.setFloatable(False)

        self.toolbar.setStyleSheet(
            "QToolButton {{height:{30}px;width:{30}px;}}")

        self.new_btn = create_toolbutton(self,
                                         qta.icon("mdi.new-box",
                                                  color=ICON_COLOR),
                                         "Start new game.",
                                         triggered=self.new_game)
        self.toolbar.addWidget(self.new_btn)
        self.toolbar.addSeparator()

        self.clear_btn = create_toolbutton(self,
                                           qta.icon("fa5s.eraser",
                                                    color=ICON_COLOR),
                                           "Click을 초기화 한다.",
                                           triggered=self.show_puzzle)
        self.toolbar.addWidget(self.clear_btn)
        self.toolbar.addSeparator()

        self.n_lights_1axis_spinbox = QSpinBox(self)
        self.n_lights_1axis_spinbox.setValue(4)
        self.n_lights_1axis_spinbox.setRange(2, 10)
        self.n_lights_1axis_spinbox.setAlignment(Qt.AlignRight)
        self.n_lights_1axis_spinbox.setToolTip(
            "Set Number of light in 1 axis.")
        self.toolbar.addWidget(self.n_lights_1axis_spinbox)
        self.toolbar.addSeparator()

        self.show_solution_chkbox = QCheckBox("Solution", self)
        self.show_solution_chkbox.setStyleSheet(""" background : "#32414B" """)
        self.show_solution_chkbox.setToolTip("Show the solution.")
        self.show_solution_chkbox.stateChanged.connect(self.show_solution)
        self.toolbar.addWidget(self.show_solution_chkbox)
        self.toolbar.addSeparator()

        self.toolbar.adjustSize()

    def setup_status_bar(self):
        """Set up status bar."""
        status_bar = QStatusBar(self)
        status_bar.addPermanentWidget(QLabel("Clicked", self))
        status_bar.addPermanentWidget(self.clicked_label)
        status_bar.addPermanentWidget(QLabel("Solution", self))
        status_bar.addPermanentWidget(self.n_solution_1_label)

        self.setStatusBar(status_bar)

    def setup_btn_grid(self, n_lights_1axis):
        """Set up grid of buttons."""
        table = self.btn_grid_table
        if n_lights_1axis != table.rowCount():
            table.clear()
            table.setSelectionMode(QAbstractItemView.NoSelection)
            table.setColumnCount(n_lights_1axis)
            table.setRowCount(n_lights_1axis)
            table.horizontalHeader().setSectionResizeMode(QHeaderView.Fixed)
            table.verticalHeader().setSectionResizeMode(QHeaderView.Fixed)

            table.horizontalHeader().setDefaultSectionSize(CELL_SIZE)
            table.verticalHeader().setDefaultSectionSize(CELL_SIZE)

            table.horizontalHeader().hide()
            table.verticalHeader().hide()

            for idx_row in range(n_lights_1axis):
                for idx_col in range(n_lights_1axis):
                    btn = QPushButton(self)
                    btn.setStyleSheet(BTN_STYLE)
                    btn.setCheckable(True)
                    btn.setChecked(True)
                    btn.clicked.connect(
                        self.clicked_btn_of_grid_factory(idx_row, idx_col))
                    table.setCellWidget(idx_row, idx_col, btn)
        self.show_solution()

    def clicked_btn_of_grid_factory(self, idx_row, idx_col):
        """Generate lambda function of clicked_btn_of_grid."""
        return lambda: self.clicked_btn_of_grid(idx_row, idx_col)

    def clicked_btn_of_grid(self, idx_row, idx_col):
        """Change state of button around clicked button."""
        self.change_state_btn(idx_row - 1, idx_col + 0)
        self.change_state_btn(idx_row + 1, idx_col + 0)
        self.change_state_btn(idx_row + 0, idx_col - 1)
        self.change_state_btn(idx_row + 0, idx_col + 1)

        self.n_clicked += 1
        self.refresh_n_clicked()

        self.check_solve()

    def change_state_btn(self, idx_row, idx_col):
        """Change state of button."""
        btn = self.btn_grid_table.cellWidget(idx_row, idx_col)
        if btn is not None:
            btn.setChecked(not btn.isChecked())

    def show_solution(self):
        """Show the solution on the button."""
        n_lights = self.manage_puzzle.n_lights_1axis
        solution = self.manage_puzzle.mat_solution
        for idx_row in range(n_lights):
            for idx_col in range(n_lights):
                btn = self.btn_grid_table.cellWidget(idx_row, idx_col)
                if btn is not None:
                    if self.show_solution_chkbox.isChecked():
                        if solution[idx_row, idx_col] == 1:
                            btn.setText("◉")
                        else:
                            btn.setText("")
                    else:
                        btn.setText("")

    def refresh_n_clicked(self):
        """Refresh number of clicked."""
        self.clicked_label.setText(f"{self.n_clicked}")

    def show_puzzle(self):
        """Show puzzle."""
        n_lights = self.manage_puzzle.n_lights_1axis
        puzzle = self.manage_puzzle.mat_puzzle
        for idx_row in range(n_lights):
            for idx_col in range(n_lights):
                btn = self.btn_grid_table.cellWidget(idx_row, idx_col)
                if btn is not None:
                    if puzzle[idx_row, idx_col] == 1:
                        btn.setChecked(True)
                    else:
                        btn.setChecked(False)

        self.n_clicked = 0
        self.refresh_n_clicked()

    def check_solve(self):
        """Check if the problem is solved."""
        n_lights = self.manage_puzzle.n_lights_1axis
        for idx_row in range(n_lights):
            for idx_col in range(n_lights):
                btn = self.btn_grid_table.cellWidget(idx_row, idx_col)
                if btn is not None:
                    if btn.isChecked():
                        return

        n_solution = self.manage_puzzle.count_1_of_solution()
        QMessageBox.information(self, "Succeess",
                                ("Congratulation\n"
                                 f"clicked  : {self.n_clicked}\n"
                                 f"solution : {n_solution}"))
Exemple #9
0
class TuneSpectraControls(QWidget):
    """Tune Spectra Controls."""
    def __init__(self, parent=None, prefix='', section=''):
        """Init."""
        super().__init__(parent)
        self.prefix = prefix
        self.section = section
        self._setupUi()

    def _setupUi(self):
        self.spectra = TuneSpectraView(self, self.prefix, self.section)

        lb_show_trace = QLabel('Show')
        self.cb_show_x = QCheckBox('H', self)
        self.cb_show_x.setStyleSheet('color: blue;')
        self.cb_show_x.setChecked(True)
        self.cb_show_x.stateChanged.connect(self.spectra.showTuneH)
        self.cb_show_y = QCheckBox('V', self)
        self.cb_show_y.setStyleSheet('color: red;')
        self.cb_show_y.setChecked(True)
        self.cb_show_y.stateChanged.connect(self.spectra.showTuneV)

        self.cb_choose_x = QComboBox(self)
        self.cb_choose_x.addItem('Tune Frac.')
        self.cb_choose_x.addItem('Frequency')
        self.cb_choose_x.currentIndexChanged.connect(
            self.spectra.toggleXChannel)
        self.cb_choose_x.currentIndexChanged.connect(
            self._toggle_registers_axis)

        # Registers
        self.registers = {i: None for i in range(4)}
        self.spectra.curveReg = [None, None, None, None]
        self.cb_reg = {i: QCheckBox(self) for i in range(4)}
        self.bt_reg = {
            i: QPushButton('Register ' + str(i), self)
            for i in range(4)
        }
        self.lb_reg = {i: QLabel('Empty') for i in range(4)}
        self.bt_save = {
            i: QPushButton(qta.icon('fa5s.save'), '', self)
            for i in range(4)
        }
        self.colors = ['cyan', 'darkGreen', 'magenta', 'darkRed']
        self.registers_widget = QWidget()
        glay_reg = QGridLayout(self.registers_widget)
        shift = 2 if self.section == 'BO' else 18
        for i in range(4):
            # checks
            self.spectra.addChannel(y_channel='FAKE:Register' + str(i),
                                    name='Register ' + str(i),
                                    redraw_mode=2,
                                    color=self.colors[i],
                                    lineWidth=2,
                                    lineStyle=Qt.SolidLine)
            self.spectra.curveReg[i] = self.spectra.curveAtIndex(i + shift)
            self.spectra.curveReg[i].setVisible(False)
            self.cb_reg[i].setStyleSheet('min-width:1.2em; max-width:1.2em;'
                                         'min-height:1.29em; color:' +
                                         self.colors[i] + ';')
            self.cb_reg[i].stateChanged.connect(_part(self._show_curve, i))
            glay_reg.addWidget(self.cb_reg[i], i, 0, alignment=Qt.AlignLeft)
            # buttons
            self.bt_reg[i].setStyleSheet('min-width:5em; max-width:5em;')
            self.bt_reg[i].setMenu(QMenu())
            self.bt_reg[i].menu().addAction('Save Tune H',
                                            _part(self._registerData, i, 'H'))
            self.bt_reg[i].menu().addAction('Save Tune V',
                                            _part(self._registerData, i, 'V'))
            self.bt_reg[i].menu().addAction('Clear',
                                            _part(self._clear_register, i))
            glay_reg.addWidget(self.bt_reg[i], i, 1, alignment=Qt.AlignLeft)
            # label
            self.lb_reg[i].setMouseTracking(True)
            self.lb_reg[i].setTextInteractionFlags(Qt.TextEditorInteraction)
            self.lb_reg[i].setStyleSheet(
                'min-height:1.29em; min-width: 20em; max-width: 20em;')
            glay_reg.addWidget(self.lb_reg[i], i, 2, alignment=Qt.AlignLeft)
            glay_reg.addItem(
                QSpacerItem(i, 1, QSzPlcy.Expanding, QSzPlcy.Ignored), i, 3)
            # save button
            self.bt_save[i].clicked.connect(_part(self._export_data, i))
            glay_reg.addWidget(self.bt_save[i], i, 4, alignment=Qt.AlignRight)

        self.pb_showregs = QPushButton('^', self)
        self.pb_showregs.setObjectName('showregs')
        self.pb_showregs.setToolTip('Hide registers')
        self.pb_showregs.setStyleSheet(
            '#showregs{min-width:1em;max-width:1em;}')
        self.pb_showregs.released.connect(self._handle_registers_vis)

        hbox_ctrls = QHBoxLayout()
        hbox_ctrls.setContentsMargins(0, 0, 0, 0)
        hbox_ctrls.setSpacing(6)
        hbox_ctrls.addWidget(lb_show_trace, alignment=Qt.AlignLeft)
        hbox_ctrls.addWidget(self.cb_show_x, alignment=Qt.AlignLeft)
        hbox_ctrls.addWidget(self.cb_show_y, alignment=Qt.AlignLeft)
        hbox_ctrls.addStretch()
        hbox_ctrls.addWidget(QLabel('X Axis: '), alignment=Qt.AlignRight)
        hbox_ctrls.addWidget(self.cb_choose_x, alignment=Qt.AlignRight)
        hbox_ctrls.addItem(QSpacerItem(15, 1, QSzPlcy.Fixed, QSzPlcy.Ignored))
        hbox_ctrls.addWidget(self.pb_showregs, alignment=Qt.AlignLeft)

        lay = QVBoxLayout(self)
        lay.setSpacing(10)
        lay.setContentsMargins(10, 6, 6, 6)
        lay.addWidget(self.spectra)
        lay.addLayout(hbox_ctrls)
        lay.addWidget(self.registers_widget)

    def _registerData(self, idx, tune):
        curve = self.spectra.curveH if tune == 'H' else self.spectra.curveV
        latest_freq = curve.x_channels['Freq'].value
        latest_tune = curve.x_channels['Tune'].value
        self.registers[idx] = [latest_tune, latest_freq, curve.latest_y]
        self.lb_reg[idx].setText(
            'Tune ' + tune + ' at ' +
            time.strftime('%d/%m/%Y %H:%M:%S', time.localtime(time.time())))
        self._show_curve(idx, self.cb_reg[idx].checkState())

    def _clear_register(self, idx):
        self._show_curve(idx, False)
        self.lb_reg[idx].setText('Empty')
        self.registers[idx] = None

    def _show_curve(self, i, show):
        if not self.registers[i]:
            self.spectra.curveReg[i].receiveXWaveform([])
            self.spectra.curveReg[i].receiveYWaveform([])
            self.spectra.curveReg[i].redrawCurve()
            return
        if show:
            self.spectra.curveReg[i].receiveXWaveform(
                self.registers[i][self.cb_choose_x.currentIndex()])
            self.spectra.curveReg[i].receiveYWaveform(self.registers[i][2])
            self.spectra.curveReg[i].redrawCurve()
            self.spectra.curveReg[i].setVisible(True)
        else:
            self.spectra.curveReg[i].setVisible(False)

    def _toggle_registers_axis(self, idx):
        for i in range(4):
            if self.registers[i] is None:
                continue
            self.spectra.curveReg[i].receiveXWaveform(self.registers[i][idx])
            self.spectra.curveReg[i].receiveYWaveform(self.registers[i][2])
            self.spectra.curveReg[i].redrawCurve()

    def _export_data(self, idx):
        if not self.registers[idx]:
            return

        home = os.path.expanduser('~')
        folder_month = datetime.now().strftime('%Y-%m')
        folder_day = datetime.now().strftime('%Y-%m-%d')
        path = os.path.join(home, 'mounts', 'screens-iocs', folder_month,
                            folder_day)
        if not os.path.exists(path):
            os.makedirs(path)
        fn, _ = QFileDialog.getSaveFileName(self, 'Save as...', path, '*.txt')
        if not fn:
            return False
        if not fn.endswith('.txt'):
            fn += '.txt'

        data = np.array([self.registers[idx][0], self.registers[idx][1]]).T
        np.savetxt(fn, data)

    def _handle_registers_vis(self):
        vis = self.registers_widget.isVisible()
        text = 'v' if vis else '^'
        ttip = 'Show' if vis else 'Hide'
        self.pb_showregs.setText(text)
        self.pb_showregs.setToolTip(ttip + ' registers')
        self.registers_widget.setVisible(not vis)
        self.spectra.adjustSize()
        self.adjustSize()
Exemple #10
0
    def _setupUi(self):
        cw = QWidget(self)
        self.setCentralWidget(cw)
        self.setFocusPolicy(Qt.StrongFocus)

        label = QLabel('<h4>Booster Charge</h4>',
                       self,
                       alignment=Qt.AlignCenter)

        # timeplot
        self.timeplot = SiriusTimePlot(parent=self, background='w')
        timespan = 60 * 60 * 6
        colors = ['blue', 'red', 'green', 'magenta']
        self.timeplot.timeSpan = timespan  # [s]
        self.timeplot.bufferSize = 2 * timespan  # [2 samples/s]
        self.timeplot.autoRangeY = True
        self.timeplot.showXGrid = True
        self.timeplot.showYGrid = True
        self.timeplot.setLabel('left', text='Charge', units='nC')
        self.timeplot.setObjectName('timeplot')
        self.timeplot.setStyleSheet(
            '#timeplot{min-width:28em; min-height: 18em;}')
        t_end = Time.now()
        t_init = t_end - timespan

        self._channels = dict()
        self._curves = dict()
        self._cb_show = dict()
        self._pvs_labels = dict()
        self._cb_offsets = dict()
        glay_aux = QGridLayout()
        glay_aux.setHorizontalSpacing(20)
        glay_aux.setVerticalSpacing(10)
        glay_aux.addWidget(QLabel('Show curves: ', self),
                           0,
                           0,
                           alignment=Qt.AlignCenter)
        glay_aux.addWidget(QLabel('Offset [nC]: ', self),
                           2,
                           0,
                           alignment=Qt.AlignCenter)
        for i, e in enumerate(self._energies):
            pvname = self._ioc_prefix.substitute(propty='Charge' + e + '-Mon')
            self._channels[e] = SiriusConnectionSignal(address=pvname)
            self._channels[e].new_value_signal[float].connect(
                self._update_charges)

            self.timeplot.addYChannel('Charge' + e,
                                      color=colors[i],
                                      lineWidth=2)
            curve = self.timeplot.curveAtIndex(-1)
            self._curves[e] = curve
            self.timeplot.fill_curve_with_archdata(self._curves[e],
                                                   pvname,
                                                   t_init=t_init.get_iso8601(),
                                                   t_end=t_end.get_iso8601())

            cb = QCheckBox(e)
            cb.setChecked(True)
            cb.setStyleSheet('color:' + colors[i] + ';')
            cb.stateChanged.connect(curve.setVisible)
            self._cb_show[e] = cb

            lb = QLabel('', self, alignment=Qt.AlignCenter)
            self._pvs_labels[e] = lb

            sb = QDoubleSpinBoxPlus(self)
            sb.energy = e
            sb.setMinimum(0)
            sb.setMaximum(1e6)
            sb.setDecimals(4)
            sb.setStyleSheet('max-width: 5em;')
            sb.setValue(self._latest_offsets[e])
            sb.editingFinished.connect(self._update_offset)
            self._cb_offsets[e] = sb

            glay_aux.addWidget(cb, 0, i + 1, alignment=Qt.AlignCenter)
            glay_aux.addWidget(lb, 1, i + 1, alignment=Qt.AlignCenter)
            glay_aux.addWidget(sb, 2, i + 1, alignment=Qt.AlignCenter)

        self.pb_offset = QPushButton('Update offset', self)
        self.pb_offset.clicked.connect(self._set_current_values_2_offset)
        self.pb_offset.setToolTip('Set offsets to current charge values.')
        glay_aux.addWidget(self.pb_offset, 1, 0)

        lay = QVBoxLayout(cw)
        lay.addWidget(label)
        lay.addWidget(self.timeplot)
        lay.addLayout(glay_aux)
Exemple #11
0
    def populate_gui(self):
        _contain_parsed = self.contain_parsed
        for _row, _entry in enumerate(_contain_parsed):

            if _entry == ['']:
                continue

            self.parent.ui.table.insertRow(_row)

            # select
            _layout = QHBoxLayout()
            _widget = QCheckBox()
            _widget.setEnabled(True)
            _layout.addWidget(_widget)
            _layout.addStretch()
            _new_widget = QWidget()
            _new_widget.setLayout(_layout)

            _widget.stateChanged.connect(
                lambda state=0, row=_row: self.parent.
                table_select_state_changed(state, row))
            self.parent.ui.table.setCellWidget(_row, 0, _new_widget)

            # name
            _item = QTableWidgetItem(_entry[1])
            self.parent.ui.table.setItem(_row, 1, _item)

            # runs
            _item = QTableWidgetItem(_entry[2])
            self.parent.ui.table.setItem(_row, 2, _item)

            # Sample formula
            if _entry[3]:
                _item = QTableWidgetItem(_entry[3])
            else:
                _item = QTableWidgetItem("")
            self.parent.ui.table.setItem(_row, 3, _item)

            # mass density
            if _entry[4]:
                _item = QTableWidgetItem(_entry[4])
            else:
                _item = QTableWidgetItem("")
            self.parent.ui.table.setItem(_row, 4, _item)

            # radius
            if _entry[5]:
                _item = QTableWidgetItem(_entry[5])
            else:
                _item = QTableWidgetItem("")
            self.parent.ui.table.setItem(_row, 5, _item)

            # packing fraction
            if _entry[6]:
                _item = QTableWidgetItem(_entry[6])
            else:
                _item = QTableWidgetItem("")
            self.parent.ui.table.setItem(_row, 6, _item)

            # sample shape
            _widget = QComboBox()
            _widget.addItem("cylindrical")
            _widget.addItem("spherical")
            if _entry[7] == "spherical":
                _widget.setCurrentIndex(1)
            self.parent.ui.table.setCellWidget(_row, 7, _widget)

            # do abs corr
            _layout = QHBoxLayout()
            _widget = QCheckBox()
            if _entry[8] == "True":
                _widget.setCheckState(Qt.Checked)
            _widget.setStyleSheet("border:  2px; solid-black")
            _widget.setEnabled(True)
            _layout.addStretch()
            _layout.addWidget(_widget)
            _layout.addStretch()
            _new_widget = QWidget()
            _new_widget.setLayout(_layout)
            self.parent.ui.table.setCellWidget(_row, 8, _new_widget)

        for _row, _entry in enumerate(_contain_parsed):

            if _entry == ['']:
                continue

            # select
            _widget = self.parent.ui.table.cellWidget(_row, 0).children()[1]
            if _entry[0] == "True":
                _widget.setChecked(True)
Exemple #12
0
    def populate_gui(self):
        _contain_parsed = self.contain_parsed
        for _row, _entry in enumerate(_contain_parsed):

            if _entry == ['']:
                continue

            self.parent.ui.table.insertRow(_row)

            # select
            _layout = QHBoxLayout()
            _widget = QCheckBox()
            _widget.setEnabled(True)
            _layout.addWidget(_widget)
            _layout.addStretch()
            _new_widget = QWidget()
            _new_widget.setLayout(_layout)

            _widget.stateChanged.connect(lambda state=0, row=_row:
                                         self.parent.table_select_state_changed(state, row))
            self.parent.ui.table.setCellWidget(_row, 0, _new_widget)

            # name
            _item = QTableWidgetItem(_entry[1])
            self.parent.ui.table.setItem(_row, 1, _item)

            # runs
            _item = QTableWidgetItem(_entry[2])
            self.parent.ui.table.setItem(_row, 2, _item)

            # Sample formula
            if _entry[3]:
                _item = QTableWidgetItem(_entry[3])
            else:
                _item = QTableWidgetItem("")
            self.parent.ui.table.setItem(_row, 3, _item)

            # mass density
            if _entry[4]:
                _item = QTableWidgetItem(_entry[4])
            else:
                _item = QTableWidgetItem("")
            self.parent.ui.table.setItem(_row, 4, _item)

            # radius
            if _entry[5]:
                _item = QTableWidgetItem(_entry[5])
            else:
                _item = QTableWidgetItem("")
            self.parent.ui.table.setItem(_row, 5, _item)

            # packing fraction
            if _entry[6]:
                _item = QTableWidgetItem(_entry[6])
            else:
                _item = QTableWidgetItem("")
            self.parent.ui.table.setItem(_row, 6, _item)

            # sample shape
            _widget = QComboBox()
            _widget.addItem("cylindrical")
            _widget.addItem("spherical")
            if _entry[7] == "spherical":
                _widget.setCurrentIndex(1)
            self.parent.ui.table.setCellWidget(_row, 7, _widget)

            # do abs corr
            _layout = QHBoxLayout()
            _widget = QCheckBox()
            if _entry[8] == "True":
                _widget.setCheckState(Qt.Checked)
            _widget.setStyleSheet("border:  2px; solid-black")
            _widget.setEnabled(True)
            _layout.addStretch()
            _layout.addWidget(_widget)
            _layout.addStretch()
            _new_widget = QWidget()
            _new_widget.setLayout(_layout)
            self.parent.ui.table.setCellWidget(_row, 8, _new_widget)

        for _row, _entry in enumerate(_contain_parsed):

            if _entry == ['']:
                continue

            # select
            _widget = self.parent.ui.table.cellWidget(_row, 0).children()[1]
            if _entry[0] == "True":
                _widget.setChecked(True)
Exemple #13
0
    def _setupUi(self):
        cw = QWidget(self)
        self.setCentralWidget(cw)
        self.setFocusPolicy(Qt.StrongFocus)

        label = QLabel('<h3>Efficiency Monitor</h3>',
                       self,
                       alignment=Qt.AlignCenter)

        # timeplot
        timespan = 30 * 60  # [s]
        self.timeplot = SiriusTimePlot(parent=self, background='w')
        self.timeplot.timeSpan = timespan
        self.timeplot.autoRangeY = False
        self.timeplot.maxYRange = 150.0
        self.timeplot.minYRange = 0.0
        self.timeplot.showXGrid = True
        self.timeplot.showYGrid = True
        self.timeplot.setLabel('left', text='Efficiency', units='%')
        self.timeplot.setObjectName('timeplot')
        self.timeplot.setStyleSheet(
            '#timeplot{min-width:24em; min-height: 10em;}')
        t_end = Time.now()
        t_init = t_end - timespan

        self._channels = dict()
        self._curves = dict()
        self._cb_show = dict()
        self._pvs_labels = dict()

        lay_lbls = QVBoxLayout()
        lay_lbls.setSpacing(10)

        for i, data in enumerate(self._eff_list):
            text, pvn, color = data
            pvname = SiriusPVName(pvn).substitute(prefix=self._prefix)

            self.timeplot.addYChannel(pvname,
                                      name=pvname,
                                      color=color,
                                      lineWidth=2)
            curve = self.timeplot.curveAtIndex(-1)
            self._curves[pvn] = curve
            self.timeplot.fill_curve_with_archdata(self._curves[pvn],
                                                   pvname,
                                                   t_init=t_init.get_iso8601(),
                                                   t_end=t_end.get_iso8601())

            cb = QCheckBox(text, self)
            cb.setChecked(True)
            cb.setStyleSheet('color:' + color + ';')
            cb.stateChanged.connect(curve.setVisible)
            self._cb_show[pvn] = cb

            lb = PyDMLabel(self, pvname)
            lb.setStyleSheet("""
                QLabel{
                    font-weight: bold; min-width: 6em; max-width: 6em;
                    qproperty-alignment: AlignCenter;
                }""")
            lb.showUnits = True
            self._pvs_labels[pvn] = lb

            lay_lbls.addWidget(cb, alignment=Qt.AlignLeft)
            lay_lbls.addWidget(lb, alignment=Qt.AlignCenter)
            lay_lbls.addStretch()

        lay = QGridLayout(cw)
        lay.setSpacing(20)
        lay.addWidget(label, 0, 0, 1, 2)
        lay.addWidget(self.timeplot, 1, 0)
        lay.addLayout(lay_lbls, 1, 1)
Exemple #14
0
class _DiffStatus(SiriusDialog):
    def __init__(self, parent=None, desired=None, current=None):
        super().__init__(parent)
        self.setWindowTitle('Diff Status')
        self._desired = desired
        self._current = current
        self._setupUi()

    def _setupUi(self):
        self._text = 'It is all ok!'
        self._plot = None
        if isinstance(self._desired, type(self._current)):
            if isinstance(self._desired, (_np.ndarray, tuple, list)):
                if len(self._desired) != len(self._current):
                    self._text = \
                        'Implemented and desired values have different\n'\
                        'lenghts: {} and {}, respectively!'.format(
                            len(self._current), len(self._desired))
                else:
                    self._text = 'Difference: '
                    self._plot = PyDMWaveformPlot()
                    self._plot.autoRangeX = True
                    self._plot.autoRangeY = True
                    self._plot.plotItem.showButtons()
                    self._plot.setBackgroundColor(QColor(255, 255, 255))
                    self._plot.addChannel(y_channel='DES', color='blue')
                    self._plot.addChannel(y_channel='CURR', color='black')
                    self._plot.addChannel(y_channel='DIFF', color='magenta')
                    self._desired_curve = self._plot.curveAtIndex(0)
                    self._desired_curve.receiveYWaveform(self._desired)
                    self._desired_curve.redrawCurve()
                    self._current_curve = self._plot.curveAtIndex(1)
                    self._current_curve.receiveYWaveform(self._current)
                    self._current_curve.redrawCurve()
                    self._diff_curve = self._plot.curveAtIndex(2)
                    diff = self._current - self._desired
                    self._diff_curve.receiveYWaveform(diff)
                    self._diff_curve.redrawCurve()
            elif isinstance(self._desired, (int, float, str)):
                self._text = 'Implemented: {}\nDesired: {}'.format(
                    self._current, self._desired)
        elif self._current == 'UNDEF':
            self._text = 'PV is disconnected!'
        elif isinstance(self._desired, (tuple, list)):
            self._text = 'Implemented value ({}) is not within\n' \
                         'desired interval ({})!'.format(
                             self._current, self._desired)
        else:
            self._text = 'Implemented value (of type {}) has type\n' \
                         'different from desired ({})!'.format(
                             type(self._current), type(self._desired))

        lay = QGridLayout(self)
        self._label = QLabel(self._text, self, alignment=Qt.AlignCenter)
        self._label.setStyleSheet("min-width: 20em;")
        lay.addWidget(self._label, 0, 0, 1, 3)
        if self._plot:
            lay.addWidget(self._plot, 1, 0, 1, 3)
            self.show_des = QCheckBox('Desired')
            self.show_des.setChecked(True)
            self.show_des.setStyleSheet('color: blue;')
            self.show_des.stateChanged.connect(self._desired_curve.setVisible)
            lay.addWidget(self.show_des, 2, 0)
            self.show_cur = QCheckBox('Implemented')
            self.show_cur.setChecked(True)
            self.show_cur.setStyleSheet('color: black;')
            self.show_cur.stateChanged.connect(self._current_curve.setVisible)
            lay.addWidget(self.show_cur, 2, 1)
            self.show_dif = QCheckBox('Diff')
            self.show_dif.setChecked(True)
            self.show_dif.setStyleSheet('color: magenta;')
            self.show_dif.stateChanged.connect(self._diff_curve.setVisible)
            lay.addWidget(self.show_dif, 2, 2)
        self._ok_bt = QPushButton('Ok', self)
        self._ok_bt.clicked.connect(self.close)
        lay.addWidget(self._ok_bt, 3, 1)