class AcquisitionWidgetSimple(QtImport.QWidget):

    acqParametersChangedSignal = QtImport.pyqtSignal(list)
    madEnergySelectedSignal = QtImport.pyqtSignal(str, float, bool)

    def __init__(
        self,
        parent=None,
        name=None,
        fl=0,
        acq_params=None,
        path_template=None,
        layout=None,
    ):

        QtImport.QWidget.__init__(self, parent, QtImport.Qt.WindowFlags(fl))
        if name is not None:
            self.setObjectName(name)

        # Internal variables --------------------------------------------------
        self.value_changed_list = []

        # Properties ----------------------------------------------------------

        # Signals -------------------------------------------------------------

        # Slots ---------------------------------------------------------------

        # Graphic elements ----------------------------------------------------
        if acq_params is None:
            self._acquisition_parameters = queue_model_objects.AcquisitionParameters(
            )
        else:
            self._acquisition_parameters = acq_params
        if path_template is None:
            self._path_template = queue_model_objects.PathTemplate()
        else:
            self._path_template = path_template

        self._acquisition_mib = DataModelInputBinder(
            self._acquisition_parameters)
        self.acq_widget_layout = QtImport.load_ui_file(
            "acquisition_widget_vertical_simple_layout.ui")

        # Layout --------------------------------------------------------------
        main_layout = QtImport.QVBoxLayout(self)
        main_layout.addWidget(self.acq_widget_layout)
        main_layout.setSpacing(0)
        main_layout.setContentsMargins(0, 0, 0, 0)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------
        self.acq_widget_layout.osc_start_cbox.stateChanged.connect(
            self.use_osc_start)
        self.acq_widget_layout.num_images_cbox.activated.connect(
            self.update_num_images)
        self.acq_widget_layout.detector_roi_mode_combo.activated.connect(
            self.detector_roi_mode_changed)

        # Other ---------------------------------------------------------------
        self.osc_start_validator = QtImport.QDoubleValidator(
            -10000, 10000, 4, self.acq_widget_layout.osc_start_ledit)
        self.osc_range_validator = QtImport.QDoubleValidator(
            -10000, 10000, 4, self.acq_widget_layout.osc_range_ledit)
        self.kappa_validator = QtImport.QDoubleValidator(
            0, 360, 4, self.acq_widget_layout.kappa_ledit)
        self.kappa_phi_validator = QtImport.QDoubleValidator(
            0, 360, 4, self.acq_widget_layout.kappa_phi_ledit)
        self.energy_validator = QtImport.QDoubleValidator(
            0, 25, 5, self.acq_widget_layout.energy_ledit)
        self.resolution_validator = QtImport.QDoubleValidator(
            0, 15, 3, self.acq_widget_layout.resolution_ledit)
        self.transmission_validator = QtImport.QDoubleValidator(
            0, 100, 3, self.acq_widget_layout.transmission_ledit)
        self.exp_time_validator = QtImport.QDoubleValidator(
            0, 10000, 6, self.acq_widget_layout.exp_time_ledit)
        self.acq_widget_layout.num_images_cbox.setCurrentIndex(1)

        self.acq_widget_layout.detector_roi_mode_label.setEnabled(False)
        self.acq_widget_layout.detector_roi_mode_combo.setEnabled(False)

        self.set_tunable_energy(HWR.beamline.tunable_wavelength)

        if HWR.beamline.diffractometer.in_plate_mode():
            self.acq_widget_layout.num_images_cbox.clear()
            self.acq_widget_layout.num_images_cbox.addItem("1")
            self.acq_widget_layout.num_images_cbox.setCurrentIndex(0)

        self.init_detector_roi_modes()
        self.init_limits()

    def update_osc_total_range(self):
        pass

    def set_osc_start_limits(self, limits):
        if not None in limits:
            self.osc_start_validator.setRange(limits[0], limits[1], 4)

    def update_osc_start(self, new_value):
        if not self.acq_widget_layout.osc_start_cbox.hasFocus():
            self.acq_widget_layout.osc_start_ledit.setText(str(new_value))

    def update_kappa(self, new_value):
        if not self.acq_widget_layout.kappa_ledit.hasFocus():
            self.acq_widget_layout.kappa_ledit.setText(str(new_value))

    def update_kappa_phi(self, new_value):
        if not self.acq_widget_layout.kappa_phi_ledit.hasFocus():
            self.acq_widget_layout.kappa_phi_ledit.setText(str(new_value))

    def use_kappa(self, state):
        if HWR.beamline.diffractometer.in_plate_mode():
            state = False
        self.acq_widget_layout.kappa_label.setEnabled(state)
        self.acq_widget_layout.kappa_ledit.setEnabled(state)
        self.acq_widget_layout.kappa_phi_label.setEnabled(state)
        self.acq_widget_layout.kappa_phi_ledit.setEnabled(state)

    def use_max_osc_range(self, state):
        pass

    def update_num_images(self, index=None, num_images=None):
        if index is not None:
            if index is 0:
                self._acquisition_parameters.num_images = 1
                self._path_template.num_files = 1
            elif index is 1:
                self._acquisition_parameters.num_images = 2
                self._path_template.num_files = 2
            elif index is 2:
                self._acquisition_parameters.num_images = 4
                self._path_template.num_files = 4

        if num_images:
            if self.acq_widget_layout.num_images_cbox.count() > 3:
                self.acq_widget_layout.num_images_cbox.removeItem(4)

            if num_images is 1:
                self.acq_widget_layout.num_images_cbox.setCurrentIndex(0)
            elif num_images is 2:
                self.acq_widget_layout.num_images_cbox.setCurrentIndex(1)
            elif num_images is 4:
                self.acq_widget_layout.num_images_cbox.setCurrentIndex(2)
            else:
                self.acq_widget_layout.num_images_cbox.addItem(str(num_images))
                self.acq_widget_layout.num_images_cbox.setCurrenIndex(3)

            self._path_template.num_files = num_images

    def use_mad(self, state):
        pass

    def get_mad_energy(self):
        pass

    def set_energies(self, energy_scan_result):
        pass

    def energy_selected(self, index):
        pass

    def init_limits(self):
        limits_dict = HWR.beamline.acquisition_limit_values

        tpl = limits_dict.get("osc_range")
        if tpl:
            self.osc_start_validator.setRange(tpl[0], tpl[1], 4)
            self.osc_range_validator.setRange(tpl[0], tpl[1], 4)

        self._acquisition_mib.bind_value_update(
            "osc_start",
            self.acq_widget_layout.osc_start_ledit,
            float,
            self.osc_start_validator,
        )

        self._acquisition_mib.bind_value_update(
            "osc_range",
            self.acq_widget_layout.osc_range_ledit,
            float,
            self.osc_range_validator,
        )

        tpl = limits_dict.get("kappa")
        if tpl:
            self.kappa_validator.setRange(tpl[0], tpl[1], 4)
        self._acquisition_mib.bind_value_update(
            "kappa", self.acq_widget_layout.kappa_ledit, float,
            self.kappa_validator)

        tpl = limits_dict.get("kappa_phi")
        if tpl:
            self.kappa_phi_validator.setRange(tpl[0], tpl[1], 4)
        self._acquisition_mib.bind_value_update(
            "kappa_phi",
            self.acq_widget_layout.kappa_phi_ledit,
            float,
            self.kappa_phi_validator,
        )

        tpl = limits_dict.get("exposure_time")
        if tpl:
            self.exp_time_validator.setRange(tpl[0], tpl[1], 6)
        self._acquisition_mib.bind_value_update(
            "exp_time",
            self.acq_widget_layout.exp_time_ledit,
            float,
            self.exp_time_validator,
        )

        self._acquisition_mib.bind_value_update(
            "energy", self.acq_widget_layout.energy_ledit, float,
            self.energy_validator)
        self.acq_widget_layout.energy_ledit.setToolTip(
            "Energy limits %0.3f : %0.3f" %
            (self.energy_validator.bottom(), self.energy_validator.top()))

        self._acquisition_mib.bind_value_update(
            "transmission",
            self.acq_widget_layout.transmission_ledit,
            float,
            self.transmission_validator,
        )

        self._acquisition_mib.bind_value_update(
            "resolution",
            self.acq_widget_layout.resolution_ledit,
            float,
            self.resolution_validator,
        )

    def set_energy(self, energy, wav):
        if not self.acq_widget_layout.energy_ledit.hasFocus():
            self.acq_widget_layout.energy_ledit.setText(str(energy))

    def update_transmission(self, transmission):
        if self.acq_widget_layout.transmission_ledit.hasFocus():
            self.acq_widget_layout.transmission_ledit.setText(
                str(transmission))

    def update_resolution(self, resolution):
        if not self.acq_widget_layout.resolution_ledit.hasFocus():
            self.acq_widget_layout.resolution_ledit.setText(str(resolution))

    def update_energy_limits(self, limits):
        if limits:
            self.energy_validator.setBottom(limits[0])
            self.energy_validator.setTop(limits[1])
            self.acq_widget_layout.energy_ledit.setToolTip(
                "Energy limits %0.3f : %0.3f" % (limits[0], limits[1]))
            self._acquisition_mib.validate_all()

    def update_transmission_limits(self, limits):
        if limits:
            self.transmission_validator.setBottom(limits[0])
            self.transmission_validator.setTop(limits[1])
            self.acq_widget_layout.transmission_ledit.setToolTip(
                "Transmission limits %0.3f : %0.3f" % (limits[0], limits[1]))
            self._acquisition_mib.validate_all()

    def update_resolution_limits(self, limits):
        if limits:
            self.resolution_validator.setBottom(limits[0])
            self.resolution_validator.setTop(limits[1])
            self.acq_widget_layout.resolution_ledit.setToolTip(
                "Resolution limits %0.3f : %0.3f" % (limits[0], limits[1]))
            self._acquisition_mib.validate_all()

    def update_detector_exp_time_limits(self, limits):
        if limits:
            self.exp_time_validator.setBottom(limits[0])
            self.exp_time_validator.setTop(limits[1])
            self.acq_widget_layout.exp_time_ledit.setToolTip(
                "Exposure time limits %0.3f : %0.3f" % (limits[0], limits[1]))
            self._acquisition_mib.validate_all()

    def update_energy(self, energy):
        if ("energy" not in self.value_changed_list
                and not self.acq_widget_layout.energy_ledit.hasFocus()):
            self.acq_widget_layout.energy_ledit.setText("%.4f" % float(energy))

    def init_detector_roi_modes(self):
        roi_modes = HWR.beamline.detector.get_roi_modes()
        if (len(roi_modes) > 0 and
                self.acq_widget_layout.detector_roi_mode_combo.count() == 0):
            for roi_mode in roi_modes:
                self.acq_widget_layout.detector_roi_mode_combo.addItem(
                    roi_mode)
            self.acq_widget_layout.detector_roi_mode_label.setEnabled(True)
            self.acq_widget_layout.detector_roi_mode_combo.setEnabled(True)

    def update_exp_time_limits(self):
        try:
            exp_time_limits = (
                HWR.beamline.detector.get_exposure_time_limits())
            max_osc_speed = HWR.beamline.diffractometer.get_osc_max_speed()
            top_limit = (float(self.acq_widget_layout.osc_range_ledit.text()) /
                         max_osc_speed)
            limits = (max(exp_time_limits[0], top_limit), exp_time_limits[1])
            self.update_detector_exp_time_limits(limits)
        except BaseException:
            pass

    def update_detector_roi_mode(self, roi_mode_index):
        if (roi_mode_index is not None and
                self.acq_widget_layout.detector_roi_mode_combo.count() > 0):
            self.acq_widget_layout.detector_roi_mode_combo.setCurrentIndex(
                roi_mode_index)

    def update_osc_range_limits(self, limits=None):
        pass

    def detector_roi_mode_changed(self, roi_mode_index):
        HWR.beamline.detector.set_roi_mode(roi_mode_index)

    def update_data_model(self, acquisition_parameters, path_template):
        self._acquisition_parameters = acquisition_parameters
        self._acquisition_mib.set_model(acquisition_parameters)
        self._path_template = path_template
        self.update_num_images(None, acquisition_parameters.num_images)

    def set_tunable_energy(self, state):
        self.acq_widget_layout.energy_ledit.setEnabled(state)

    def use_osc_start(self, state):
        self.acq_widget_layout.osc_start_ledit.setEnabled(state)

    def check_parameter_conflict(self):
        return self._acquisition_mib.validate_all()
class AcquisitionWidget(QtImport.QWidget):

    acqParametersChangedSignal = QtImport.pyqtSignal(list)
    madEnergySelectedSignal = QtImport.pyqtSignal(str, float, bool)

    def __init__(
        self,
        parent=None,
        name=None,
        fl=0,
        acq_params=None,
        path_template=None,
        layout="horizontal",
    ):

        QtImport.QWidget.__init__(self, parent, QtImport.Qt.WindowFlags(fl))

        if name is not None:
            self.setObjectName(name)

        # Hardware objects ----------------------------------------------------

        # Internal variables --------------------------------------------------
        self.previous_energy = 0

        # If the acq. widget is used with grids then total osc range is not
        # equal to num_images * osc_range, but num_images_per_line * osc_range
        # For grids the osc total range is updated when a grid is selected

        self.grid_mode = False

        # Properties ----------------------------------------------------------

        # Signals -------------------------------------------------------------

        # Slots ---------------------------------------------------------------

        # Graphic elements ----------------------------------------------------
        if acq_params is None:
            self._acquisition_parameters = queue_model_objects.AcquisitionParameters()
        else:
            self._acquisition_parameters = acq_params

        if path_template is None:
            self._path_template = queue_model_objects.PathTemplate()
        else:
            self._path_template = path_template

        self._acquisition_mib = DataModelInputBinder(self._acquisition_parameters)

        if layout == "horizontal":
            self.acq_widget_layout = QtImport.load_ui_file(
                "acquisition_widget_horizontal_layout.ui"
            )
            self.use_osc_start(False)
        else:
            self.acq_widget_layout = QtImport.load_ui_file(
                "acquisition_widget_vertical_layout.ui"
            )

        # Layout --------------------------------------------------------------
        __main_vlayout = QtImport.QVBoxLayout(self)
        __main_vlayout.addWidget(self.acq_widget_layout)
        __main_vlayout.setSpacing(0)
        __main_vlayout.setContentsMargins(0, 0, 0, 0)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------
        self.acq_widget_layout.osc_start_cbox.stateChanged.connect(self.fix_osc_start)
        self.acq_widget_layout.exp_time_ledit.textChanged.connect(
            self.exposure_time_ledit_changed
        )
        self.acq_widget_layout.exp_time_total_ledit.textEdited.connect(
            self.exp_time_total_ledit_changed
        )
        self.acq_widget_layout.first_image_ledit.textChanged.connect(
            self.first_image_ledit_change
        )
        self.acq_widget_layout.num_images_ledit.textChanged.connect(
            self.num_images_ledit_change
        )
        self.acq_widget_layout.detector_roi_mode_combo.activated.connect(
            self.detector_roi_mode_changed
        )
        self.acq_widget_layout.energies_combo.activated.connect(self.energy_selected)
        self.acq_widget_layout.mad_cbox.toggled.connect(self.use_mad)
        self.acq_widget_layout.osc_start_ledit.textEdited.connect(
            self.osc_start_ledit_changed
        )
        self.acq_widget_layout.osc_range_ledit.textEdited.connect(
            self.osc_range_per_frame_ledit_changed
        )
        self.acq_widget_layout.osc_total_range_ledit.textEdited.connect(
            self.osc_total_range_ledit_changed
        )
        self.acq_widget_layout.energy_ledit.textEdited.connect(
            self.energy_ledit_changed
        )
        self.acq_widget_layout.transmission_ledit.textEdited.connect(
            self.transmission_ledit_changed
        )
        self.acq_widget_layout.resolution_ledit.textEdited.connect(
            self.resolution_ledit_changed
        )
        self.acq_widget_layout.kappa_ledit.textEdited.connect(self.kappa_ledit_changed)
        self.acq_widget_layout.kappa_phi_ledit.textEdited.connect(
            self.kappa_phi_ledit_changed
        )

        if self.acq_widget_layout.findChild(QtImport.QLineEdit, "overlap_ledit"):
            self.acq_widget_layout.overlap_ledit.textChanged.connect(
                self.overlap_changed
            )
        if self.acq_widget_layout.findChild(QtImport.QCheckBox, "max_osc_range_cbx"):
            self.acq_widget_layout.max_osc_range_cbx.toggled.connect(
                self.max_osc_range_toggled
            )

        # Other ---------------------------------------------------------------
        self.value_changed_list = []

        self.acq_widget_layout.energies_combo.setDisabled(True)
        self.acq_widget_layout.energies_combo.addItems(
            ["ip: -", "pk: -", "rm1: -", "rm2: -"]
        )

        self.osc_start_validator = QtImport.QDoubleValidator(
            -10000, 10000, 4, self.acq_widget_layout.osc_start_ledit
        )
        self.osc_range_per_frame_validator = QtImport.QDoubleValidator(
            0, 10000, 4, self.acq_widget_layout.osc_range_ledit
        )
        self.osc_total_range_validator = QtImport.QDoubleValidator(
            0, 10000, 4, self.acq_widget_layout.osc_total_range_ledit
        )
        self.kappa_validator = QtImport.QDoubleValidator(
            -0.01, 360, 4, self.acq_widget_layout.kappa_ledit
        )
        self.kappa_phi_validator = QtImport.QDoubleValidator(
            -360, 360, 4, self.acq_widget_layout.kappa_phi_ledit
        )
        self.energy_validator = QtImport.QDoubleValidator(
            4, 25, 4, self.acq_widget_layout.energy_ledit
        )
        self.resolution_validator = QtImport.QDoubleValidator(
            0, 15, 3, self.acq_widget_layout.resolution_ledit
        )
        self.transmission_validator = QtImport.QDoubleValidator(
            0, 100, 3, self.acq_widget_layout.transmission_ledit
        )
        self.exp_time_validator = QtImport.QDoubleValidator(
            0.0001, 10000, 7, self.acq_widget_layout.exp_time_ledit
        )
        self.first_img_validator = QtImport.QIntValidator(
            0, 99999, self.acq_widget_layout.first_image_ledit
        )
        self.num_img_validator = QtImport.QIntValidator(
            1, 9999999, self.acq_widget_layout.num_images_ledit
        )
        self.acq_widget_layout.detector_roi_mode_label.setEnabled(False)
        self.acq_widget_layout.detector_roi_mode_combo.setEnabled(False)

    def use_max_osc_range(self, state):
        self.acq_widget_layout.max_osc_range_cbx.setEnabled(state)

    def fix_osc_start(self, state):
        """
        Fix osc start, so the lineEdit do not change when osc is changed
        """
        self.acq_widget_layout.osc_start_ledit.setEnabled(state)

    def update_osc_start(self, new_value):
        """
        Updates osc line edit
        """
        if (
            "osc_start" not in self.value_changed_list
            and not self.acq_widget_layout.osc_start_ledit.hasFocus()
            and not self.acq_widget_layout.osc_start_cbox.isChecked()
        ):
            osc_start_value = 0
            try:
                osc_start_value = round(float(new_value), 2)
            except TypeError:
                pass

            self.acq_widget_layout.osc_start_ledit.setText(str(osc_start_value))
            self._acquisition_parameters.osc_start = osc_start_value

            # self.update_osc_total_range_limits()
            # self.update_num_images_limits()

    def osc_start_ledit_changed(self, osc_start):
        """Fixes osc start edit"""
        if "osc_start" not in self.value_changed_list:
            self.value_changed_list.append("osc_start")
        self.update_osc_total_range_limits()
        self.update_num_images_limits()
        self.emit_acq_parameters_changed()

    def update_osc_start_limits(self):
        """In the plate mode sets osc start limits"""
        self.update_osc_total_range_limits()
        self.update_num_images_limits()

    def osc_range_per_frame_ledit_changed(self, new_value):
        self.update_osc_total_range()
        self.update_num_images_limits()
        self.update_exp_time_limits()
        self.emit_acq_parameters_changed()

    def update_osc_range_per_frame_limits(self):
        try:
            max_osc_speed = api.diffractometer.get_osc_max_speed()
            top_limit = max_osc_speed * float(
                self.acq_widget_layout.exp_time_ledit.text()
            )

            self.osc_range_per_frame_validator.setTop(top_limit)
            tool_tip = (
                "Oscillation range per frame limits 0 : "
                + "%0.4f\n4 digits precision." % top_limit
            )

            self.acq_widget_layout.osc_range_ledit.setToolTip(tool_tip)
            self._acquisition_mib.validate_all()
        except BaseException:
            pass

    def update_osc_total_range(self):
        self.acq_widget_layout.osc_total_range_ledit.blockSignals(True)

        if not self.grid_mode:
            try:
                self.acq_widget_layout.osc_total_range_ledit.setText(
                    "%0.2f" %
                    (
                        float(self.acq_widget_layout.osc_range_ledit.text())
                        * int(self.acq_widget_layout.num_images_ledit.text())
                    )
                )
            except BaseException:
                pass
        self.acq_widget_layout.osc_total_range_ledit.blockSignals(False)

    def update_total_exp_time(self):
        try:
            self.acq_widget_layout.exp_time_total_ledit.setText(
                "%.2f"
                % (
                    float(self.acq_widget_layout.exp_time_ledit.text())
                    * float(self.acq_widget_layout.num_images_ledit.text())
                )
            )
        except BaseException:
            pass

    def osc_total_range_ledit_changed(self, new_value):
        if not self.grid_mode:
            try:
                num_images = int(
                    float(new_value)
                    / float(self.acq_widget_layout.osc_range_ledit.text())
                )
                self.acq_widget_layout.num_images_ledit.blockSignals(True)
                self.acq_widget_layout.num_images_ledit.setText("%d" % num_images)
                self._acquisition_parameters.num_images = num_images
                self.acq_widget_layout.num_images_ledit.blockSignals(False)
            except BaseException:
                pass
            self.emit_acq_parameters_changed()

    def exp_time_total_ledit_changed(self, new_value):
        try:
            exp_time = float(new_value)  / float(self.acq_widget_layout.num_images_ledit.text())
            self.acq_widget_layout.exp_time_ledit.blockSignals(True)
            self.acq_widget_layout.exp_time_ledit.setText("%.4f" % exp_time)
            self._acquisition_parameters.exp_time = exp_time
            self.acq_widget_layout.exp_time_ledit.blockSignals(False)
        except BaseException:
            pass
        self.emit_acq_parameters_changed()

    def update_osc_total_range_limits(self, num_images=None):
        """Updates osc totol range. Limits are changed if a plate is used.
           - For simple oscillation osc_range is defined by osc_start and
             osc_start top limit.
           - For mesh osc_range is defined by number of images per line
             and osc in the middle of mesh
        """
        if api.diffractometer.in_plate_mode():
            if hasattr(self.parent(), "set_osc_total_range"):
                self.parent().set_osc_total_range(num_images)
                self._acquisition_mib.validate_all()

    def update_exp_time_limits(self):
        try:
            exp_time_limits = (
                api.detector.get_exposure_time_limits()
            )
            max_osc_speed = api.diffractometer.get_osc_max_speed()
            top_limit = (
                float(self.acq_widget_layout.osc_range_ledit.text()) / max_osc_speed
            )
            limits = (max(exp_time_limits[0], top_limit), exp_time_limits[1])

            self.update_detector_exp_time_limits(limits)
        except BaseException:
            pass

    def update_kappa(self, new_value):
        if not self.acq_widget_layout.kappa_ledit.hasFocus() and new_value is not None:
            self.acq_widget_layout.kappa_ledit.setText(str(new_value))
            self.emit_acq_parameters_changed()

    def update_kappa_phi(self, new_value):
        if not self.acq_widget_layout.kappa_phi_ledit.hasFocus() and new_value:
            self.acq_widget_layout.kappa_phi_ledit.setText(str(new_value))
            self.emit_acq_parameters_changed()

    def use_osc_start(self, state):
        self.acq_widget_layout.osc_start_cbox.setVisible(state)
        self.acq_widget_layout.osc_start_label.setVisible(not state)
        self.acq_widget_layout.osc_start_ledit.setEnabled(not state)

    def use_kappa(self, state):
        if api.diffractometer is not None:
            if api.diffractometer.in_plate_mode():
                state = False
        self.acq_widget_layout.kappa_label.setEnabled(state)
        self.acq_widget_layout.kappa_ledit.setEnabled(state)
        self.acq_widget_layout.kappa_phi_label.setEnabled(state)
        self.acq_widget_layout.kappa_phi_ledit.setEnabled(state)

    def init_api(self):
        limits_dict = api.beamline_setup.get_acquisition_limit_values()

        if "osc_range" in limits_dict:
            limits = tuple(map(float, limits_dict["osc_range"].split(",")))
            (lower, upper) = limits
            self.osc_start_validator.setRange(lower, upper, 4)
            self.osc_range_per_frame_validator.setRange(lower, upper, 4)
            self.osc_total_range_validator.setRange(lower, upper, 4)

        self._acquisition_mib.bind_value_update(
            "osc_start",
            self.acq_widget_layout.osc_start_ledit,
            float,
            self.osc_start_validator,
        )

        self._acquisition_mib.bind_value_update(
            "osc_range",
            self.acq_widget_layout.osc_range_ledit,
            float,
            self.osc_range_per_frame_validator,
        )

        self._acquisition_mib.bind_value_update(
            "osc_total_range",
            self.acq_widget_layout.osc_total_range_ledit,
            float,
            self.osc_total_range_validator,
        )

        if "kappa" in limits_dict:
            limits = tuple(map(float, limits_dict["kappa"].split(",")))
            (lower, upper) = limits
            self.kappa_validator.setRange(lower, upper, 4)
        self._acquisition_mib.bind_value_update(
            "kappa", self.acq_widget_layout.kappa_ledit, float, self.kappa_validator
        )

        if "kappa_phi" in limits_dict:
            limits = tuple(map(float, limits_dict["kappa_phi"].split(",")))
            (lower, upper) = limits
            self.kappa_phi_validator.setRange(lower, upper, 4)
        self._acquisition_mib.bind_value_update(
            "kappa_phi",
            self.acq_widget_layout.kappa_phi_ledit,
            float,
            self.kappa_phi_validator,
        )

        if "exposure_time" in limits_dict:
            limits = tuple(map(float, limits_dict["exposure_time"].split(",")))
            (lower, upper) = limits
            self.exp_time_validator.setRange(lower, upper, 6)

        self._acquisition_mib.bind_value_update(
            "exp_time",
            self.acq_widget_layout.exp_time_ledit,
            float,
            self.exp_time_validator,
        )

        if "number_of_images" in limits_dict:
            limits = tuple(map(float, limits_dict["number_of_images"].split(",")))
            (lower, upper) = limits
            self.num_img_validator.setRange(lower, upper)
            self.first_img_validator.setRange(lower, upper)

        self._acquisition_mib.bind_value_update(
            "first_image",
            self.acq_widget_layout.first_image_ledit,
            int,
            self.first_img_validator,
        )

        self._acquisition_mib.bind_value_update(
            "num_images",
            self.acq_widget_layout.num_images_ledit,
            int,
            self.num_img_validator,
        )

        num_passes = self.acq_widget_layout.findChild(
            QtImport.QLineEdit, "num_passes_ledit"
        )

        if num_passes:
            self._acquisition_mib.bind_value_update(
                "num_passes", num_passes, int, QtImport.QIntValidator(1, 1000, self)
            )

        overlap_ledit = self.acq_widget_layout.findChild(
            QtImport.QLineEdit, "overlap_ledit"
        )

        if overlap_ledit:
            self._acquisition_mib.bind_value_update(
                "overlap",
                overlap_ledit,
                float,
                QtImport.QDoubleValidator(-1000, 1000, 2, self),
            )

        self._acquisition_mib.bind_value_update(
            "energy", self.acq_widget_layout.energy_ledit, float, self.energy_validator
        )
        self.update_energy_limits(
            (self.energy_validator.bottom(), self.energy_validator.top())
        )

        self._acquisition_mib.bind_value_update(
            "transmission",
            self.acq_widget_layout.transmission_ledit,
            float,
            self.transmission_validator,
        )
        self.update_transmission_limits(
            (self.transmission_validator.bottom(), self.transmission_validator.top())
        )

        self._acquisition_mib.bind_value_update(
            "resolution",
            self.acq_widget_layout.resolution_ledit,
            float,
            self.resolution_validator,
        )
        # self.update_resolution_limits((self.resolution_validator.bottom(),
        #                               self.resolution_validator.top()))

        self._acquisition_mib.bind_value_update(
            "shutterless", self.acq_widget_layout.shutterless_cbx, bool, None
        )

        self.set_tunable_energy(api.beamline_setup.tunable_wavelength())

        has_shutter_less = api.beamline_setup.detector_has_shutterless()
        self.acq_widget_layout.shutterless_cbx.setEnabled(has_shutter_less)
        self.acq_widget_layout.shutterless_cbx.setChecked(has_shutter_less)

        if api.beamline_setup.disable_num_passes():
            num_passes = self.acq_widget_layout.findChild(
                QtImport.QLineEdit, "num_passes_ledit"
            )
            if num_passes:
                num_passes.setDisabled(True)

        self.init_detector_roi_modes()

    def first_image_ledit_change(self, new_value):
        self.emit_acq_parameters_changed()

    def exposure_time_ledit_changed(self, new_value):
        """If the exposure time changes we have to check the osc speed
           and if necessary update osc range per frame
        """
        self.update_osc_range_per_frame_limits()
        self.update_osc_total_range_limits()
        self.update_total_exp_time()
        self.emit_acq_parameters_changed()

    def num_images_ledit_change(self, new_value):
        if str(new_value).isdigit():
            # self._path_template.num_files = int(new_value)
            self.update_osc_range_per_frame_limits()
            self.update_osc_total_range_limits()
            self.update_osc_total_range()
            self.update_total_exp_time()
        self.emit_acq_parameters_changed()

    def overlap_changed(self, new_value):
        if api.beamline_setup:
            has_shutter_less = api.beamline_setup.detector_has_shutterless()
        else:
            has_shutter_less = True

        if has_shutter_less:
            try:
                new_value = float(new_value)
            except ValueError:
                pass

            if new_value != 0:
                self.acq_widget_layout.shutterless_cbx.setEnabled(False)
                self.acq_widget_layout.shutterless_cbx.setChecked(False)
                self._acquisition_parameters.shutterless = False
            else:
                self.acq_widget_layout.shutterless_cbx.setEnabled(True)
                self.acq_widget_layout.shutterless_cbx.setChecked(True)
                self._acquisition_parameters.shutterless = True

    def use_mad(self, state):
        self.acq_widget_layout.energies_combo.setEnabled(state)
        if state:
            (name, energy) = self.get_mad_energy()

            if energy != 0:
                self.update_energy(energy)
            self.madEnergySelectedSignal.emit(name, energy, state)
        else:
            self.update_energy(self.previous_energy)
            energy = api.energy.get_current_energy()
            self.madEnergySelectedSignal.emit("", self.previous_energy, state)

    def max_osc_range_toggled(self, state):
        self.update_osc_total_range_limits()

    def get_mad_energy(self):
        energy_str = str(self.acq_widget_layout.energies_combo.currentText())
        (name, value) = energy_str.split(":")

        name = name.strip()
        value = value.strip()
        value = 0 if (value == "-") else float(value)

        return (name, value)

    def set_energies(self, energy_scan_result):
        self.acq_widget_layout.energies_combo.clear()

        inflection = (
            ("ip: %.4f" % energy_scan_result.inflection)
            if energy_scan_result.inflection
            else "ip: -"
        )

        peak = (
            ("pk: %.4f" % energy_scan_result.peak)
            if energy_scan_result.peak
            else "pk: -"
        )

        first_remote = (
            ("rm1: %.4f" % energy_scan_result.first_remote)
            if energy_scan_result.first_remote
            else "rm1: -"
        )

        second_remote = (
            ("rm2: %.4f" % energy_scan_result.second_remote)
            if energy_scan_result.second_remote
            else "rm2: -"
        )

        self.acq_widget_layout.energies_combo.addItems(
            [inflection, peak, first_remote, second_remote]
        )

    def energy_selected(self, index):
        if self.acq_widget_layout.mad_cbox.isChecked():
            (name, energy) = self.get_mad_energy()
            if energy != 0:
                self.update_energy(energy)

            self.madEnergySelectedSignal.emit(name, energy, True)

    def energy_ledit_changed(self, new_value):
        if "energy" not in self.value_changed_list:
            self.value_changed_list.append("energy")
        self.emit_acq_parameters_changed()

    def update_energy(self, energy, wav=None):
        if (
            "energy" not in self.value_changed_list
            and not self.acq_widget_layout.energy_ledit.hasFocus()
        ):
            self.acq_widget_layout.energy_ledit.setText(str(energy))
        self.emit_acq_parameters_changed()

    def transmission_ledit_changed(self, transmission):
        if "transmission" not in self.value_changed_list:
            self.value_changed_list.append("transmission")
        self.emit_acq_parameters_changed()

    def update_transmission(self, transmission):
        if "transmission" not in self.value_changed_list:
            self.acq_widget_layout.transmission_ledit.setText(str(transmission))
        self.emit_acq_parameters_changed()

    def resolution_ledit_changed(self, resolution):
        if "resolution" not in self.value_changed_list:
            self.value_changed_list.append("resolution")
        self.emit_acq_parameters_changed()

    def update_resolution(self, resolution):
        if (
            "resolution" not in self.value_changed_list
            and not self.acq_widget_layout.resolution_ledit.hasFocus()
        ):
            self.acq_widget_layout.resolution_ledit.setText(str(resolution))
        self.emit_acq_parameters_changed()

    def update_energy_limits(self, limits):
        if limits:
            self.energy_validator.setBottom(limits[0])
            self.energy_validator.setTop(limits[1])
            self.acq_widget_layout.energy_ledit.setToolTip(
                "Energy limits %0.4f : %0.4f keV\n" % (limits[0], limits[1])
                + "4 digits precision."
            )
            self._acquisition_mib.validate_all()

    def update_transmission_limits(self, limits):
        if limits:
            self.transmission_validator.setBottom(limits[0])
            self.transmission_validator.setTop(limits[1])
            self.acq_widget_layout.transmission_ledit.setToolTip(
                "Transmission limits %0.2f : %0.2f %%\n" % (limits[0], limits[1])
                + "2 digits precision."
            )
            self._acquisition_mib.validate_all()

    def update_resolution_limits(self, limits):
        if limits:
            self.resolution_validator.setBottom(limits[0])
            self.resolution_validator.setTop(limits[1])
            self.acq_widget_layout.resolution_ledit.setToolTip(
                "Resolution limits %0.4f : %0.4f %s\n"
                % (limits[0], limits[1], chr(197))
                + "4 digits precision."
            )
            self._acquisition_mib.validate_all()

    def update_detector_exp_time_limits(self, limits):
        if limits:
            self.exp_time_validator.setRange(limits[0], limits[1], 6)
            self.acq_widget_layout.exp_time_ledit.setToolTip(
                "Exposure time limits %0.6f s : %0.1f s\n" % (limits[0], limits[1])
                + "6 digits precision."
            )
            self._acquisition_mib.validate_all()

    def update_num_images_limits(self, num_images_limits=None):
        """Updates number of images limit. Method used if plate mode.
        """

        self._acquisition_mib.validate_all()

        return
        if api.diffractometer.in_plate_mode():
            if num_images_limits is None:
                try:
                    osc_start = float(self.acq_widget_layout.osc_start_ledit.text())
                    osc_range = float(self.acq_widget_layout.osc_range_ledit.text())
                except ValueError:
                    return

                if osc_range == 0:
                    return

                num_images_limits = int(
                    (self.osc_start_validator.top() - osc_start) / osc_range
                )

            self.num_img_validator.setTop(num_images_limits)
            self.acq_widget_layout.num_images_ledit.setToolTip(
                "Number of images limits : %d" % num_images_limits
            )
            self._acquisition_mib.validate_all()

    def init_detector_roi_modes(self):
        roi_modes = api.detector.get_roi_modes()
        if (
            len(roi_modes) > 0
            and self.acq_widget_layout.detector_roi_mode_combo.count() == 0
        ):
            for roi_mode in roi_modes:
                self.acq_widget_layout.detector_roi_mode_combo.addItem(roi_mode)
            self.acq_widget_layout.detector_roi_mode_label.setEnabled(True)
            self.acq_widget_layout.detector_roi_mode_combo.setEnabled(True)

    def update_detector_roi_mode(self, roi_mode_index):
        if (
            roi_mode_index is not None
            and self.acq_widget_layout.detector_roi_mode_combo.count() > 0
        ):
            self.acq_widget_layout.detector_roi_mode_combo.setCurrentIndex(
                roi_mode_index
            )

    def detector_roi_mode_changed(self, roi_mode_index):
        api.detector.set_roi_mode(roi_mode_index)

    def kappa_ledit_changed(self, new_value):
        if "kappa" not in self.value_changed_list:
            self.value_changed_list.append("kappa")
        self.emit_acq_parameters_changed()

    def kappa_phi_ledit_changed(self, new_value):
        if "kappa_phi" not in self.value_changed_list:
            self.value_changed_list.append("kappa_phi")
        self.emit_acq_parameters_changed()

    def update_data_model(self, acquisition_parameters, path_template):
        self._acquisition_parameters = acquisition_parameters
        self._path_template = path_template
        self._acquisition_mib.set_model(acquisition_parameters)

        # Update mad widgets
        mad = True if self._path_template.mad_prefix != "" else False
        if mad:
            mad_prefix = str(self._path_template.mad_prefix)
            index = MAD_ENERGY_COMBO_NAMES[str(mad_prefix)]
            self.acq_widget_layout.energies_combo.setCurrentIndex(index)
            self.acq_widget_layout.mad_cbox.setChecked(True)
            self.acq_widget_layout.energies_combo.setEnabled(True)
        else:
            self.acq_widget_layout.mad_cbox.setChecked(False)
            self.acq_widget_layout.energies_combo.setEnabled(False)
            self.acq_widget_layout.energies_combo.setCurrentIndex(0)

        self.update_osc_total_range()
        self.update_total_exp_time()

        self.emit_acq_parameters_changed()

    def set_tunable_energy(self, state):
        self.acq_widget_layout.energy_ledit.setEnabled(state)
        self.acq_widget_layout.mad_cbox.setEnabled(state)
        self.acq_widget_layout.energies_combo.setEnabled(state)

    def check_parameter_conflict(self):
        return self._acquisition_mib.validate_all()

    def emit_acq_parameters_changed(self):
        self.acqParametersChangedSignal.emit(self._acquisition_mib.validate_all())
class AdvancedParametersWidget(QtImport.QWidget):
    def __init__(self, parent=None, name="advanced_parameters_widget"):
        QtImport.QWidget.__init__(self, parent)

        # Internal values -----------------------------------------------------
        self._data_collection = None
        self._tree_view_item = None
        self._acquisition_mib = None

        # Properties ----------------------------------------------------------

        # Signals -------------------------------------------------------------

        # Slots ---------------------------------------------------------------

        # Graphic elements ----------------------------------------------------
        _dc_parameters_widget = QtImport.QWidget(self)
        self._data_path_widget = DataPathWidget(_dc_parameters_widget)
        self._acq_widget = AcquisitionWidget(_dc_parameters_widget, layout="horizontal")

        # Layout --------------------------------------------------------------
        _dc_parameters_widget_layout = QtImport.QVBoxLayout(_dc_parameters_widget)
        _dc_parameters_widget_layout.addWidget(self._data_path_widget)
        _dc_parameters_widget_layout.addWidget(self._acq_widget)
        _dc_parameters_widget_layout.setSpacing(2)
        _dc_parameters_widget_layout.addStretch(10)
        _dc_parameters_widget_layout.setContentsMargins(0, 0, 0, 0)

        _main_hlayout = QtImport.QHBoxLayout(self)
        _main_hlayout.addWidget(_dc_parameters_widget)
        _main_hlayout.setSpacing(2)
        _main_hlayout.setContentsMargins(2, 2, 2, 2)
        _main_hlayout.addStretch(0)

        # Qt signal/slot connections ------------------------------------------
        # self._acq_widget.acqParametersChangedSignal.\
        #     connect(self.acq_parameters_changed)
        # self._data_path_widget.pathTemplateChangedSignal.\
        #     connect(self.acq_parameters_changed)
        self._acq_widget.madEnergySelectedSignal.connect(self.mad_energy_selected)

        # Ohter ---------------------------------------------------------------
        self._acq_widget.use_osc_start(False)
        self._acq_widget.acq_widget_layout.mad_cbox.hide()
        self._acq_widget.acq_widget_layout.energies_combo.hide()
        self._acq_widget.acq_widget_layout.shutterless_cbx.hide()

    def init_api(self):
        self._acq_widget.init_api()

    def mad_energy_selected(self, name, energy, state):
        path_template = self._data_collection.acquisitions[0].path_template

        if state:
            path_template.mad_prefix = name
        else:
            path_template.mad_prefix = ""

        run_number = api.queue_model.get_next_run_number(
            path_template
        )

        self._data_path_widget.set_run_number(run_number)
        self._data_path_widget.set_prefix(path_template.base_prefix)
        model = self._tree_view_item.get_model()
        model.set_name(path_template.get_prefix())
        self._tree_view_item.setText(0, model.get_name())

    def tab_changed(self):
        if self._tree_view_item:
            self.populate_widget(self._tree_view_item, None)

    def populate_widget(self, tree_view_item, data_collection):
        self._tree_view_item = tree_view_item
        self._data_collection = data_collection

        # if isinstance(tree_view_item, queue_item.XrayCenteringQueueItem):
        #    self._data_collection = tree_view_item.get_model().reference_image_collection
        # else:
        #    self._data_collection = tree_view_item.get_model()
        executed = self._data_collection.is_executed()

        self._acq_widget.setEnabled(not executed)
        self._data_path_widget.setEnabled(not executed)

        self._acquisition_mib = DataModelInputBinder(
            self._data_collection.acquisitions[0].acquisition_parameters
        )

        # The acq_widget sends a signal to the path_widget, and it relies
        # on that both models upto date, we need to refactor this part
        # so that both models are set before taking ceratin actions.
        # This workaround, works for the time beeing.
        self._data_path_widget._data_model = self._data_collection.acquisitions[
            0
        ].path_template
        self._data_path_widget.update_data_model(
            self._data_collection.acquisitions[0].path_template
        )

        self._acq_widget.update_data_model(
            self._data_collection.acquisitions[0].acquisition_parameters,
            self._data_collection.acquisitions[0].path_template,
        )
        # self._acq_widget.use_osc_start(False)

        self._acq_widget.acq_widget_layout.num_images_ledit.setDisabled(
            data_collection.is_mesh()
        )
        invalid = self._acquisition_mib.validate_all()
        if invalid:
            msg = (
                "This data collection has one or more incorrect parameters,"
                + " correct the fields marked in red to solve the problem."
            )
            logging.getLogger("GUI").warning(msg)
Exemple #4
0
class AcquisitionStillWidget(QtImport.QWidget):

    acqParametersChangedSignal = QtImport.pyqtSignal(list)

    def __init__(
        self,
        parent=None,
        name=None,
        fl=0,
        acq_params=None,
        path_template=None,
        layout="vertical",
    ):
        """
        Loads ui file that defines the gui layout.
        Initiates QLineEdits by adding limits, precision
        Connects to qt signals to update acquisition parameters
        :param parent:
        :param name:
        :param fl:
        :param acq_params:
        :param path_template:
        :param layout:
        """

        QtImport.QWidget.__init__(self, parent, QtImport.Qt.WindowFlags(fl))

        if name is not None:
            self.setObjectName(name)

        # Internal variables --------------------------------------------------
        self.value_changed_list = []

        # Properties ----------------------------------------------------------

        # Signals -------------------------------------------------------------

        # Slots ---------------------------------------------------------------

        # Graphic elements ----------------------------------------------------
        if acq_params is None:
            self._acquisition_parameters = queue_model_objects.AcquisitionParameters(
            )
        else:
            self._acquisition_parameters = acq_params

        if path_template is None:
            self._path_template = queue_model_objects.PathTemplate()
        else:
            self._path_template = path_template

        self._acquisition_mib = DataModelInputBinder(
            self._acquisition_parameters)

        self.acq_widget_layout = QtImport.load_ui_file(
            "acquisition_widget_vertical_still_layout.ui")
        # Layout --------------------------------------------------------------
        __main_vlayout = QtImport.QVBoxLayout(self)
        __main_vlayout.addWidget(self.acq_widget_layout)
        __main_vlayout.setSpacing(0)
        __main_vlayout.setContentsMargins(0, 0, 0, 0)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------
        self.acq_widget_layout.num_triggers_ledit.textChanged.connect(
            self.num_triggers_ledit_changed)
        self.acq_widget_layout.num_images_per_trigger_ledit.textChanged.connect(
            self.num_images_per_trigger_ledit_changed)

        self.acq_widget_layout.exp_time_ledit.textChanged.connect(
            self.exposure_time_ledit_changed)
        self.acq_widget_layout.detector_roi_mode_combo.activated.connect(
            self.detector_roi_mode_changed)
        self.acq_widget_layout.energy_ledit.textEdited.connect(
            self.energy_ledit_changed)
        self.acq_widget_layout.transmission_ledit.textEdited.connect(
            self.transmission_ledit_changed)
        self.acq_widget_layout.resolution_ledit.textEdited.connect(
            self.resolution_ledit_changed)

        # Other ---------------------------------------------------------------
        self.energy_validator = QtImport.QDoubleValidator(
            4, 25, 4, self.acq_widget_layout.energy_ledit)
        self.resolution_validator = QtImport.QDoubleValidator(
            0, 15, 3, self.acq_widget_layout.resolution_ledit)
        self.transmission_validator = QtImport.QDoubleValidator(
            0, 100, 3, self.acq_widget_layout.transmission_ledit)
        self.exp_time_validator = QtImport.QDoubleValidator(
            0.0001, 10000, 7, self.acq_widget_layout.exp_time_ledit)
        self.num_triggers_validator = QtImport.QIntValidator(
            1, 9999999, self.acq_widget_layout.num_triggers_ledit)
        self.num_images_per_trigger_validator = QtImport.QIntValidator(
            1, 9999999, self.acq_widget_layout.num_images_per_trigger_ledit)
        self.num_img_validator = QtImport.QIntValidator(
            1, 9999999, self.acq_widget_layout.num_images_ledit)
        self.hare_num_validator = QtImport.QIntValidator(
            1, 9999999, self.acq_widget_layout.hare_num_ledit)

        limits_dict = HWR.beamline.acquisition_limit_values

        tpl = limits_dict.get("exposure_time")
        if tpl:
            self.exp_time_validator.setRange(tpl[0], tpl[1], 6)

        self._acquisition_mib.bind_value_update(
            "exp_time",
            self.acq_widget_layout.exp_time_ledit,
            float,
            self.exp_time_validator,
        )

        self._acquisition_mib.bind_value_update(
            "num_triggers",
            self.acq_widget_layout.num_triggers_ledit,
            int,
            self.num_triggers_validator,
        )

        self._acquisition_mib.bind_value_update(
            "num_images_per_trigger",
            self.acq_widget_layout.num_images_per_trigger_ledit,
            int,
            self.num_images_per_trigger_validator,
        )

        self._acquisition_mib.bind_value_update(
            "hare_num",
            self.acq_widget_layout.hare_num_ledit,
            int,
            self.hare_num_validator,
        )

        tpl = limits_dict.get("number_of_images")
        if tpl:
            self.num_img_validator.setRange(tpl[0], tpl[1])

        self._acquisition_mib.bind_value_update(
            "num_images",
            self.acq_widget_layout.num_images_ledit,
            int,
            self.num_img_validator,
        )

        self._acquisition_mib.bind_value_update(
            "energy", self.acq_widget_layout.energy_ledit, float,
            self.energy_validator)
        self.update_energy_limits(
            (self.energy_validator.bottom(), self.energy_validator.top()))

        self._acquisition_mib.bind_value_update(
            "transmission",
            self.acq_widget_layout.transmission_ledit,
            float,
            self.transmission_validator,
        )
        self.update_transmission_limits((self.transmission_validator.bottom(),
                                         self.transmission_validator.top()))

        self._acquisition_mib.bind_value_update(
            "resolution",
            self.acq_widget_layout.resolution_ledit,
            float,
            self.resolution_validator,
        )

        self.init_detector_roi_modes()
        self.acq_widget_layout.detector_roi_mode_label.setEnabled(False)
        self.acq_widget_layout.detector_roi_mode_combo.setEnabled(False)
        self.update_exp_time_limits()

    def update_osc_total_range(self):
        """
        :return: None
        """
        return

    def use_osc_start(self, status):
        """
        :param status: boolean
        :return: None
        """
        return

    def use_max_osc_range(self, status):
        """
        :param status: boolean
        :return: None
        """
        return

    def use_kappa(self, status):
        """
        :param status: boolean
        :return: None
        """
        return

    def exposure_time_ledit_changed(self, value):
        """
        Updates exposure time QLineEdit
        :param value: str
        :return: None
        """
        self.update_total_exp_time()
        self.emit_acq_parameters_changed()

    def energy_ledit_changed(self, value):
        """
        Fixes energy value. Energy change will not rewrite the typed energy value
        :param value: str
        :return: None
        """
        if "energy" not in self.value_changed_list:
            self.value_changed_list.append("energy")
        self.emit_acq_parameters_changed()

    def update_energy(self, energy, wav=None):
        """
        Updates energy QLineEdit
        :param energy: energy in keV (float)
        :param wav: wavelength in A (float)
        :return: None
        """
        if ("energy" not in self.value_changed_list
                and not self.acq_widget_layout.energy_ledit.hasFocus()):
            self.acq_widget_layout.energy_ledit.setText(str(energy))
        self.emit_acq_parameters_changed()

    def transmission_ledit_changed(self, transmission):
        """
        Event when a value in the transmission QLineEdit is changed
        :param transmission: in perc. (str)
        :return: None
        """
        if "transmission" not in self.value_changed_list:
            self.value_changed_list.append("transmission")
        self.emit_acq_parameters_changed()

    def update_transmission(self, transmission):
        """
        Updates transmission QLineEdit
        :param transmission: in perc. (float)
        :return: None
        """
        if "transmission" not in self.value_changed_list:
            self.acq_widget_layout.transmission_ledit.setText(
                str(transmission))
        self.emit_acq_parameters_changed()

    def resolution_ledit_changed(self, resolution):
        """
        Method called when user changes resolution
        :param resolution: in A (float)
        :return: None
        """
        if "resolution" not in self.value_changed_list:
            self.value_changed_list.append("resolution")
        self.emit_acq_parameters_changed()

    def update_resolution(self, resolution):
        """
        Updates resolution QLineEdit
        :param resolution: A (float)
        :return: None
        """
        if ("resolution" not in self.value_changed_list
                and not self.acq_widget_layout.resolution_ledit.hasFocus()):
            self.acq_widget_layout.resolution_ledit.setText(str(resolution))
        self.emit_acq_parameters_changed()

    def update_energy_limits(self, limits):
        """
        Updates energy limits
        :param limits: list of two floats
        :return: None
        """
        if limits:
            self.energy_validator.setBottom(limits[0])
            self.energy_validator.setTop(limits[1])
            self.acq_widget_layout.energy_ledit.setToolTip(
                "Energy limits %0.4f : %0.4f keV\n" % (limits[0], limits[1]) +
                "4 digits precision.")
            self._acquisition_mib.validate_all()

    def update_transmission_limits(self, limits):
        """
        Updates transmission limits
        :param limits: list of two floats
        :return: None
        """
        if limits:
            self.transmission_validator.setBottom(limits[0])
            self.transmission_validator.setTop(limits[1])
            self.acq_widget_layout.transmission_ledit.setToolTip(
                "Transmission limits %0.2f : %0.2f %%\n" %
                (limits[0], limits[1]) + "2 digits precision.")
            self._acquisition_mib.validate_all()

    def update_resolution_limits(self, limits):
        """
        Updates resolution limits
        :param limits: list of two floats
        :return: None
        """
        if limits:
            self.resolution_validator.setBottom(limits[0])
            self.resolution_validator.setTop(limits[1])
            self.acq_widget_layout.resolution_ledit.setToolTip(
                "Resolution limits %0.4f : %0.4f %s\n" %
                (limits[0], limits[1], chr(197)) + "4 digits precision.")
            self._acquisition_mib.validate_all()

    def update_detector_exp_time_limits(self, limits):
        """
        Updates exposure time limits
        :param limits: list of two floats
        :return: None
        """
        if limits:
            self.exp_time_validator.setRange(limits[0], limits[1], 6)
            self.acq_widget_layout.exp_time_ledit.setToolTip(
                "Exposure time limits %0.6f s : %0.1f s\n" %
                (limits[0], limits[1]) + "6 digits precision.")
            self._acquisition_mib.validate_all()

    def init_detector_roi_modes(self):
        """
        Initiates detetor ROI modes. Available modes are added to the combobox
        :return: None
        """
        roi_modes = HWR.beamline.detector.get_roi_modes()
        if (len(roi_modes) > 0 and
                self.acq_widget_layout.detector_roi_mode_combo.count() == 0):
            for roi_mode in roi_modes:
                self.acq_widget_layout.detector_roi_mode_combo.addItem(
                    roi_mode)
        self.acq_widget_layout.detector_roi_mode_label.setEnabled(
            len(roi_modes) > 1)
        self.acq_widget_layout.detector_roi_mode_combo.setEnabled(
            len(roi_modes) > 1)

    def update_detector_roi_mode(self, roi_mode_index):
        """
        Method called when roi mode has been chaned
        :param roi_mode_index: int
        :return: None
        """
        if (roi_mode_index is not None and
                self.acq_widget_layout.detector_roi_mode_combo.count() > 0):
            self.acq_widget_layout.detector_roi_mode_combo.setCurrentIndex(
                roi_mode_index)

    def detector_roi_mode_changed(self, roi_mode_index):
        """
        Method called when user selects a detector roi mode
        :param roi_mode_index: int
        :return:
        """
        HWR.beamline.detector.set_roi_mode(roi_mode_index)

    def update_osc_range_per_frame_limits(self):
        """
        Updates osc range per frame limits
        :return: None
        """
        return

    def update_exp_time_limits(self):
        self.update_detector_exp_time_limits(
            HWR.beamline.detector.get_exposure_time_limits())

    def update_osc_start(self, value):
        """
        Updates osc start
        :param value: float
        :return: None
        """
        return

    def update_kappa(self, value):
        """
        Updates kappa value
        :param value: float
        :return:
        """
        return

    def update_kappa_phi(self, value):
        """
        Updates kappa phi value
        :param value: float
        :return: None
        """
        return

    def update_data_model(self, acquisition_parameters, path_template):
        """
        Updates data model
        :param acquisition_parameters: AcquisitionParameters
        :param path_template: PathTemplate
        :return: None
        """
        self._acquisition_parameters = acquisition_parameters
        self._path_template = path_template
        self._acquisition_mib.set_model(acquisition_parameters)
        self.emit_acq_parameters_changed()

    def check_parameter_conflict(self):
        """
        Checks for parameter conflicts
        :return: list of conflicts
        """
        return self._acquisition_mib.validate_all()

    def emit_acq_parameters_changed(self):
        """
        Emits acqParametersChangedSignal
        :return: None
        """
        self.acqParametersChangedSignal.emit(
            self._acquisition_mib.validate_all())

    def set_energies(self, energies):
        """
        Sets energies
        :param energies:
        :return: None
        """
        return

    def num_triggers_ledit_changed(self, value):
        """
        Updates num images and total exp time
        :param value: QString
        :return: None
        """
        if "num_triggers" not in self.value_changed_list:
            self.value_changed_list.append("num_triggers")
        self.update_num_images()
        self.update_total_exp_time()
        self.emit_acq_parameters_changed()

    def num_images_per_trigger_ledit_changed(self, value):
        """
                Updates num images and total exp time
                :param value: QString
                :return: None
                """
        if "num_images_per_trigger" not in self.value_changed_list:
            self.value_changed_list.append("num_images_per_trigger")
        self.update_num_images()
        self.update_total_exp_time()
        self.emit_acq_parameters_changed()

    def update_num_images(self):
        """
        Updates num images
        :return: None
        """
        self.acq_widget_layout.num_images_ledit.setText(
            str(self._acquisition_parameters.num_triggers *
                self._acquisition_parameters.num_images_per_trigger))

    def update_total_exp_time(self):
        """Updates total exposure time
        :return: None
        """
        try:
            self.acq_widget_layout.exp_time_total_ledit.setText(
                "%.2f" %
                (float(self.acq_widget_layout.exp_time_ledit.text()) *
                 float(self.acq_widget_layout.num_images_ledit.text())))
        except BaseException:
            pass
class DCParametersWidget(QtImport.QWidget):
    def __init__(self, parent=None, name="parameter_widget"):

        QtImport.QWidget.__init__(self, parent)
        if name is not None:
            self.setObjectName(name)

        # Properties ----------------------------------------------------------

        # Signals ------------------------------------------------------------

        # Slots ---------------------------------------------------------------

        # Internal variables --------------------------------------------------
        self._data_collection = None
        self._tree_view_item = None
        self._acquisition_mib = None

        # Graphic elements ----------------------------------------------------
        _dc_parameters_widget = QtImport.QWidget(self)
        self._data_path_widget = DataPathWidget(_dc_parameters_widget)
        self._acq_widget = AcquisitionWidget(_dc_parameters_widget, layout="horizontal")
        self._processing_widget = ProcessingWidget(_dc_parameters_widget)

        # Layout --------------------------------------------------------------
        _dc_parameters_widget_layout = QtImport.QVBoxLayout(_dc_parameters_widget)
        _dc_parameters_widget_layout.addWidget(self._data_path_widget)
        _dc_parameters_widget_layout.addWidget(self._acq_widget)
        _dc_parameters_widget_layout.addWidget(self._processing_widget)
        _dc_parameters_widget_layout.setContentsMargins(0, 0, 0, 0)
        _dc_parameters_widget_layout.setSpacing(2)
        _dc_parameters_widget_layout.addStretch(10)

        _main_hlayout = QtImport.QHBoxLayout(self)
        _main_hlayout.addWidget(_dc_parameters_widget)
        _main_hlayout.setContentsMargins(0, 0, 0, 0)
        _main_hlayout.setSpacing(2)
        _main_hlayout.addStretch(0)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------
        self._data_path_widget.data_path_layout.prefix_ledit.textChanged.connect(
            self._prefix_ledit_change
        )
        self._data_path_widget.data_path_layout.run_number_ledit.textChanged.connect(
            self._run_number_ledit_change
        )
        self._acq_widget.madEnergySelectedSignal.connect(self.mad_energy_selected)
        self._acq_widget.acqParametersChangedSignal.connect(self.acq_parameters_changed)

        # Other ---------------------------------------------------------------

    def _prefix_ledit_change(self, new_value):
        prefix = self._data_collection.acquisitions[0].path_template.get_prefix()
        self._data_collection.set_name(prefix)
        self._tree_view_item.setText(0, self._data_collection.get_name())

    def _run_number_ledit_change(self, new_value):
        if str(new_value).isdigit():
            self._data_collection.set_number(int(new_value))
            self._tree_view_item.setText(0, self._data_collection.get_name())

    def acq_parameters_changed(self):
        if self._tree_view_item is None:
            # TODO fix this
            return

        # TODO  get tree view in another way
        dc_tree_widget = self._tree_view_item.listView().parent().parent()
        dc_tree_widget.check_for_path_collisions()
        path_template = self._data_collection.acquisitions[0].path_template
        path_conflict = api.queue_model.check_for_path_collisions(path_template)

    def mad_energy_selected(self, name, energy, state):
        path_template = self._data_collection.acquisitions[0].path_template

        if state:
            path_template.mad_prefix = str(name)
        else:
            path_template.mad_prefix = ""

        run_number = api.queue_model.get_next_run_number(
            path_template
        )

        self._data_path_widget.set_run_number(run_number)
        self._data_path_widget.set_prefix(path_template.base_prefix)
        model = self._tree_view_item.get_model()
        model.set_name(path_template.get_prefix())
        self._tree_view_item.setText(0, model.get_name())

    def tab_changed(self):
        if self._tree_view_item:
            self.populate_parameter_widget(self._tree_view_item)

    def set_enabled(self, state):
        self._acq_widget.setEnabled(state)
        self._data_path_widget.setEnabled(state)
        self._processing_widget.setEnabled(state)

    def populate_widget(self, item):
        data_collection = item.get_model()
        self._tree_view_item = item
        self._data_collection = data_collection
        self._acquisition_mib = DataModelInputBinder(
            self._data_collection.acquisitions[0].acquisition_parameters
        )

        # The acq_widget sends a signal to the path_widget, and it relies
        # on that both models upto date, we need to refactor this part
        # so that both models are set before taking ceratin actions.
        # This workaround, works for the time beeing.
        self._data_path_widget._data_model = data_collection.acquisitions[
            0
        ].path_template

        self._acq_widget.set_energies(data_collection.crystal.energy_scan_result)
        self._acq_widget.update_data_model(
            data_collection.acquisitions[0].acquisition_parameters,
            data_collection.acquisitions[0].path_template,
        )
        self._data_path_widget.update_data_model(
            data_collection.acquisitions[0].path_template
        )
        self._processing_widget.update_data_model(data_collection.processing_parameters)

        invalid = self._acquisition_mib.validate_all()
        if invalid:
            msg = (
                "This data collection has one or more incorrect parameters,"
                + " correct the fields marked in red to solve the problem."
            )

            logging.getLogger("GUI").warning(msg)
class AcquisitionWidgetSimple(QtImport.QWidget):

    acqParametersChangedSignal = QtImport.pyqtSignal(list)
    madEnergySelectedSignal = QtImport.pyqtSignal(str, float, bool)

    def __init__(
        self,
        parent=None,
        name=None,
        fl=0,
        acq_params=None,
        path_template=None,
        layout=None,
    ):

        QtImport.QWidget.__init__(self, parent, QtImport.Qt.WindowFlags(fl))
        if name is not None:
            self.setObjectName(name)

        # Internal variables --------------------------------------------------
        self.value_changed_list = []

        # Properties ----------------------------------------------------------

        # Signals -------------------------------------------------------------

        # Slots ---------------------------------------------------------------

        # Graphic elements ----------------------------------------------------
        if acq_params is None:
            self._acquisition_parameters = queue_model_objects.AcquisitionParameters()
        else:
            self._acquisition_parameters = acq_params
        if path_template is None:
            self._path_template = queue_model_objects.PathTemplate()
        else:
            self._path_template = path_template

        self._acquisition_mib = DataModelInputBinder(self._acquisition_parameters)
        self.acq_widget_layout = QtImport.load_ui_file(
            "acquisition_widget_vertical_simple_layout.ui"
        )

        # Layout --------------------------------------------------------------
        main_layout = QtImport.QVBoxLayout(self)
        main_layout.addWidget(self.acq_widget_layout)
        main_layout.setSpacing(0)
        main_layout.setContentsMargins(0, 0, 0, 0)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------
        self.acq_widget_layout.osc_start_cbox.stateChanged.connect(self.use_osc_start)
        self.acq_widget_layout.num_images_cbox.activated.connect(self.update_num_images)
        self.acq_widget_layout.detector_roi_mode_combo.activated.connect(
            self.detector_roi_mode_changed
        )

        # Other ---------------------------------------------------------------
        self.osc_start_validator = QtImport.QDoubleValidator(
            -10000, 10000, 4, self.acq_widget_layout.osc_start_ledit
        )
        self.osc_range_validator = QtImport.QDoubleValidator(
            -10000, 10000, 4, self.acq_widget_layout.osc_range_ledit
        )
        self.kappa_validator = QtImport.QDoubleValidator(
            0, 360, 4, self.acq_widget_layout.kappa_ledit
        )
        self.kappa_phi_validator = QtImport.QDoubleValidator(
            0, 360, 4, self.acq_widget_layout.kappa_phi_ledit
        )
        self.energy_validator = QtImport.QDoubleValidator(
            0, 25, 5, self.acq_widget_layout.energy_ledit
        )
        self.resolution_validator = QtImport.QDoubleValidator(
            0, 15, 3, self.acq_widget_layout.resolution_ledit
        )
        self.transmission_validator = QtImport.QDoubleValidator(
            0, 100, 3, self.acq_widget_layout.transmission_ledit
        )
        self.exp_time_validator = QtImport.QDoubleValidator(
            0, 10000, 6, self.acq_widget_layout.exp_time_ledit
        )
        self.acq_widget_layout.num_images_cbox.setCurrentIndex(1)

        self.acq_widget_layout.detector_roi_mode_label.setEnabled(False)
        self.acq_widget_layout.detector_roi_mode_combo.setEnabled(False)

    def update_osc_total_range(self):
        pass

    def set_osc_start_limits(self, limits):
        if not None in limits:
            self.osc_start_validator.setRange(limits[0], limits[1], 4)

    def update_osc_start(self, new_value):
        if not self.acq_widget_layout.osc_start_cbox.hasFocus():
            self.acq_widget_layout.osc_start_ledit.setText(str(new_value))

    def update_kappa(self, new_value):
        if not self.acq_widget_layout.kappa_ledit.hasFocus():
            self.acq_widget_layout.kappa_ledit.setText(str(new_value))

    def update_kappa_phi(self, new_value):
        if not self.acq_widget_layout.kappa_phi_ledit.hasFocus():
            self.acq_widget_layout.kappa_phi_ledit.setText(str(new_value))

    def use_kappa(self, state):
        if api.beamline_setup is not None:
            if api.diffractometer.in_plate_mode():
                state = False
        self.acq_widget_layout.kappa_label.setEnabled(state)
        self.acq_widget_layout.kappa_ledit.setEnabled(state)
        self.acq_widget_layout.kappa_phi_label.setEnabled(state)
        self.acq_widget_layout.kappa_phi_ledit.setEnabled(state)

    def use_max_osc_range(self, state):
        pass

    def update_num_images(self, index=None, num_images=None):
        if index is not None:
            if index is 0:
                self._acquisition_parameters.num_images = 1
                self._path_template.num_files = 1
            elif index is 1:
                self._acquisition_parameters.num_images = 2
                self._path_template.num_files = 2
            elif index is 2:
                self._acquisition_parameters.num_images = 4
                self._path_template.num_files = 4

        if num_images:
            if self.acq_widget_layout.num_images_cbox.count() > 3:
                self.acq_widget_layout.num_images_cbox.removeItem(4)

            if num_images is 1:
                self.acq_widget_layout.num_images_cbox.setCurrentIndex(0)
            elif num_images is 2:
                self.acq_widget_layout.num_images_cbox.setCurrentIndex(1)
            elif num_images is 4:
                self.acq_widget_layout.num_images_cbox.setCurrentIndex(2)
            else:
                self.acq_widget_layout.num_images_cbox.addItem(str(num_images))
                self.acq_widget_layout.num_images_cbox.setCurrenIndex(3)

            self._path_template.num_files = num_images

    def use_mad(self, state):
        pass

    def get_mad_energy(self):
        pass

    def set_energies(self, energy_scan_result):
        pass

    def energy_selected(self, index):
        pass

    def init_api(self):
        limits_dict = api.beamline_setup.get_acquisition_limit_values()

        if "osc_range" in limits_dict:
            limits = tuple(map(float, limits_dict["osc_range"].split(",")))
            (lower, upper) = limits
            self.osc_start_validator.setRange(lower, upper, 4)
            self.osc_range_validator.setRange(lower, upper, 4)

        self._acquisition_mib.bind_value_update(
            "osc_start",
            self.acq_widget_layout.osc_start_ledit,
            float,
            self.osc_start_validator,
        )

        self._acquisition_mib.bind_value_update(
            "osc_range",
            self.acq_widget_layout.osc_range_ledit,
            float,
            self.osc_range_validator,
        )

        if "kappa" in limits_dict:
            limits = tuple(map(float, limits_dict["kappa"].split(",")))
            (lower, upper) = limits
            self.kappa_validator.setRange(lower, upper, 4)
        self._acquisition_mib.bind_value_update(
            "kappa", self.acq_widget_layout.kappa_ledit, float, self.kappa_validator
        )

        if "kappa_phi" in limits_dict:
            limits = tuple(map(float, limits_dict["kappa_phi"].split(",")))
            (lower, upper) = limits
            self.kappa_phi_validator.setRange(lower, upper, 4)
        self._acquisition_mib.bind_value_update(
            "kappa_phi",
            self.acq_widget_layout.kappa_phi_ledit,
            float,
            self.kappa_phi_validator,
        )

        if "exposure_time" in limits_dict:
            limits = tuple(map(float, limits_dict["exposure_time"].split(",")))
            (lower, upper) = limits
            self.exp_time_validator.setRange(lower, upper, 6)

        self._acquisition_mib.bind_value_update(
            "exp_time",
            self.acq_widget_layout.exp_time_ledit,
            float,
            self.exp_time_validator,
        )

        self._acquisition_mib.bind_value_update(
            "energy", self.acq_widget_layout.energy_ledit, float, self.energy_validator
        )
        self.acq_widget_layout.energy_ledit.setToolTip(
            "Energy limits %0.3f : %0.3f"
            % (self.energy_validator.bottom(), self.energy_validator.top())
        )

        self._acquisition_mib.bind_value_update(
            "transmission",
            self.acq_widget_layout.transmission_ledit,
            float,
            self.transmission_validator,
        )

        self._acquisition_mib.bind_value_update(
            "resolution",
            self.acq_widget_layout.resolution_ledit,
            float,
            self.resolution_validator,
        )

        self.set_tunable_energy(api.beamline_setup.tunable_wavelength())

        if api.diffractometer.in_plate_mode():
            self.acq_widget_layout.num_images_cbox.clear()
            self.acq_widget_layout.num_images_cbox.addItem("1")
            self.acq_widget_layout.num_images_cbox.setCurrentIndex(0)

        self.init_detector_roi_modes()

    def set_energy(self, energy, wav):
        if not self.acq_widget_layout.energy_ledit.hasFocus():
            self.acq_widget_layout.energy_ledit.setText(str(energy))

    def update_transmission(self, transmission):
        if self.acq_widget_layout.transmission_ledit.hasFocus():
            self.acq_widget_layout.transmission_ledit.setText(str(transmission))

    def update_resolution(self, resolution):
        if not self.acq_widget_layout.resolution_ledit.hasFocus():
            self.acq_widget_layout.resolution_ledit.setText(str(resolution))

    def update_energy_limits(self, limits):
        if limits:
            self.energy_validator.setBottom(limits[0])
            self.energy_validator.setTop(limits[1])
            self.acq_widget_layout.energy_ledit.setToolTip(
                "Energy limits %0.3f : %0.3f" % (limits[0], limits[1])
            )
            self._acquisition_mib.validate_all()

    def update_transmission_limits(self, limits):
        if limits:
            self.transmission_validator.setBottom(limits[0])
            self.transmission_validator.setTop(limits[1])
            self.acq_widget_layout.transmission_ledit.setToolTip(
                "Transmission limits %0.3f : %0.3f" % (limits[0], limits[1])
            )
            self._acquisition_mib.validate_all()

    def update_resolution_limits(self, limits):
        if limits:
            self.resolution_validator.setBottom(limits[0])
            self.resolution_validator.setTop(limits[1])
            self.acq_widget_layout.resolution_ledit.setToolTip(
                "Resolution limits %0.3f : %0.3f" % (limits[0], limits[1])
            )
            self._acquisition_mib.validate_all()

    def update_detector_exp_time_limits(self, limits):
        if limits:
            self.exp_time_validator.setBottom(limits[0])
            self.exp_time_validator.setTop(limits[1])
            self.acq_widget_layout.exp_time_ledit.setToolTip(
                "Exposure time limits %0.3f : %0.3f" % (limits[0], limits[1])
            )
            self._acquisition_mib.validate_all()

    def update_energy(self, energy, wav):
        if (
            "energy" not in self.value_changed_list
            and not self.acq_widget_layout.energy_ledit.hasFocus()
        ):
            self.acq_widget_layout.energy_ledit.setText("%.4f" % float(energy))

    def init_detector_roi_modes(self):
        roi_modes = api.detector.get_roi_modes()
        if (
            len(roi_modes) > 0
            and self.acq_widget_layout.detector_roi_mode_combo.count() == 0
        ):
            for roi_mode in roi_modes:
                self.acq_widget_layout.detector_roi_mode_combo.addItem(roi_mode)
            self.acq_widget_layout.detector_roi_mode_label.setEnabled(True)
            self.acq_widget_layout.detector_roi_mode_combo.setEnabled(True)

    def update_exp_time_limits(self):
        try:
            exp_time_limits = (
                api.detector.get_exposure_time_limits()
            )
            max_osc_speed = api.diffractometer.get_osc_max_speed()
            top_limit = (
                float(self.acq_widget_layout.osc_range_ledit.text()) / max_osc_speed
            )
            limits = (max(exp_time_limits[0], top_limit), exp_time_limits[1])
            self.update_detector_exp_time_limits(limits)
        except BaseException:
            pass

    def update_detector_roi_mode(self, roi_mode_index):
        if (
            roi_mode_index is not None
            and self.acq_widget_layout.detector_roi_mode_combo.count() > 0
        ):
            self.acq_widget_layout.detector_roi_mode_combo.setCurrentIndex(
                roi_mode_index
            )

    def update_osc_range_limits(self, limits=None):
        pass

    def detector_roi_mode_changed(self, roi_mode_index):
        api.detector.set_roi_mode(roi_mode_index)

    def update_data_model(self, acquisition_parameters, path_template):
        self._acquisition_parameters = acquisition_parameters
        self._acquisition_mib.set_model(acquisition_parameters)
        self._path_template = path_template
        self.update_num_images(None, acquisition_parameters.num_images)

    def set_tunable_energy(self, state):
        self.acq_widget_layout.energy_ledit.setEnabled(state)

    def use_osc_start(self, state):
        self.acq_widget_layout.osc_start_ledit.setEnabled(state)

    def check_parameter_conflict(self):
        return self._acquisition_mib.validate_all()
Exemple #7
0
class AcquisitionWidget(QtImport.QWidget):

    acqParametersChangedSignal = QtImport.pyqtSignal(list)
    madEnergySelectedSignal = QtImport.pyqtSignal(str, float, bool)

    def __init__(
        self,
        parent=None,
        name=None,
        fl=0,
        acq_params=None,
        path_template=None,
        layout="horizontal",
    ):

        QtImport.QWidget.__init__(self, parent, QtImport.Qt.WindowFlags(fl))

        if name is not None:
            self.setObjectName(name)

        # Hardware objects ----------------------------------------------------

        # Internal variables --------------------------------------------------
        self.previous_energy = 0

        # If the acq. widget is used with grids then total osc range is not
        # equal to num_images * osc_range, but num_images_per_line * osc_range
        # For grids the osc total range is updated when a grid is selected

        self.grid_mode = False

        # Properties ----------------------------------------------------------

        # Signals -------------------------------------------------------------

        # Slots ---------------------------------------------------------------

        # Graphic elements ----------------------------------------------------
        if acq_params is None:
            self._acquisition_parameters = queue_model_objects.AcquisitionParameters()
        else:
            self._acquisition_parameters = acq_params

        if path_template is None:
            self._path_template = queue_model_objects.PathTemplate()
        else:
            self._path_template = path_template

        self._acquisition_mib = DataModelInputBinder(self._acquisition_parameters)

        if layout == "horizontal":
            self.acq_widget_layout = QtImport.load_ui_file(
                "acquisition_widget_horizontal_layout.ui"
            )
            self.use_osc_start(False)
        else:
            self.acq_widget_layout = QtImport.load_ui_file(
                "acquisition_widget_vertical_layout.ui"
            )

        # Layout --------------------------------------------------------------
        __main_vlayout = QtImport.QVBoxLayout(self)
        __main_vlayout.addWidget(self.acq_widget_layout)
        __main_vlayout.setSpacing(0)
        __main_vlayout.setContentsMargins(0, 0, 0, 0)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------
        self.acq_widget_layout.osc_start_cbox.stateChanged.connect(self.fix_osc_start)
        self.acq_widget_layout.exp_time_ledit.textChanged.connect(
            self.exposure_time_ledit_changed
        )
        self.acq_widget_layout.exp_time_total_ledit.textEdited.connect(
            self.exp_time_total_ledit_changed
        )
        self.acq_widget_layout.first_image_ledit.textChanged.connect(
            self.first_image_ledit_change
        )
        self.acq_widget_layout.num_images_ledit.textChanged.connect(
            self.num_images_ledit_change
        )
        self.acq_widget_layout.detector_roi_mode_combo.activated.connect(
            self.detector_roi_mode_changed
        )
        self.acq_widget_layout.energies_combo.activated.connect(self.energy_selected)
        self.acq_widget_layout.mad_cbox.toggled.connect(self.use_mad)
        self.acq_widget_layout.osc_start_ledit.textEdited.connect(
            self.osc_start_ledit_changed
        )
        self.acq_widget_layout.osc_range_ledit.textEdited.connect(
            self.osc_range_per_frame_ledit_changed
        )
        self.acq_widget_layout.osc_total_range_ledit.textEdited.connect(
            self.osc_total_range_ledit_changed
        )
        self.acq_widget_layout.energy_ledit.textEdited.connect(
            self.energy_ledit_changed
        )
        self.acq_widget_layout.transmission_ledit.textEdited.connect(
            self.transmission_ledit_changed
        )
        self.acq_widget_layout.resolution_ledit.textEdited.connect(
            self.resolution_ledit_changed
        )
        self.acq_widget_layout.kappa_ledit.textEdited.connect(self.kappa_ledit_changed)
        self.acq_widget_layout.kappa_phi_ledit.textEdited.connect(
            self.kappa_phi_ledit_changed
        )

        if self.acq_widget_layout.findChild(QtImport.QLineEdit, "overlap_ledit"):
            self.acq_widget_layout.overlap_ledit.textChanged.connect(
                self.overlap_changed
            )
        if self.acq_widget_layout.findChild(QtImport.QCheckBox, "max_osc_range_cbx"):
            self.acq_widget_layout.max_osc_range_cbx.toggled.connect(
                self.max_osc_range_toggled
            )

        # Other ---------------------------------------------------------------
        self.value_changed_list = []

        self.acq_widget_layout.energies_combo.setDisabled(True)
        self.acq_widget_layout.energies_combo.addItems(
            ["ip: -", "pk: -", "rm1: -", "rm2: -"]
        )

        self.osc_start_validator = QtImport.QDoubleValidator(
            -10000, 10000, 4, self.acq_widget_layout.osc_start_ledit
        )
        self.osc_range_per_frame_validator = QtImport.QDoubleValidator(
            0, 10000, 4, self.acq_widget_layout.osc_range_ledit
        )
        self.osc_total_range_validator = QtImport.QDoubleValidator(
            0, 10000, 4, self.acq_widget_layout.osc_total_range_ledit
        )
        self.kappa_validator = QtImport.QDoubleValidator(
            -0.01, 360, 4, self.acq_widget_layout.kappa_ledit
        )
        self.kappa_phi_validator = QtImport.QDoubleValidator(
            -360, 360, 4, self.acq_widget_layout.kappa_phi_ledit
        )
        self.energy_validator = QtImport.QDoubleValidator(
            4, 25, 5, self.acq_widget_layout.energy_ledit
        )
        self.resolution_validator = QtImport.QDoubleValidator(
            0, 15, 3, self.acq_widget_layout.resolution_ledit
        )
        self.transmission_validator = QtImport.QDoubleValidator(
            0, 100, 3, self.acq_widget_layout.transmission_ledit
        )
        self.exp_time_validator = QtImport.QDoubleValidator(
            0.0001, 10000, 7, self.acq_widget_layout.exp_time_ledit
        )
        self.first_img_validator = QtImport.QIntValidator(
            0, 99999, self.acq_widget_layout.first_image_ledit
        )
        self.num_img_validator = QtImport.QIntValidator(
            1, 9999999, self.acq_widget_layout.num_images_ledit
        )
        self.acq_widget_layout.detector_roi_mode_label.setEnabled(False)
        self.acq_widget_layout.detector_roi_mode_combo.setEnabled(False)

        self.init_limits()

    def use_max_osc_range(self, state):
        self.acq_widget_layout.max_osc_range_cbx.setEnabled(state)

    def fix_osc_start(self, state):
        """
        Fix osc start, so the lineEdit do not change when osc is changed
        """
        self.acq_widget_layout.osc_start_ledit.setEnabled(state)

    def update_osc_start(self, new_value):
        """
        Updates osc line edit
        """
        if (
            "osc_start" not in self.value_changed_list
            and not self.acq_widget_layout.osc_start_ledit.hasFocus()
            and not self.acq_widget_layout.osc_start_cbox.isChecked()
        ):
            osc_start_value = 0
            try:
                osc_start_value = round(float(new_value), 2)
            except TypeError:
                pass

            self.acq_widget_layout.osc_start_ledit.setText(str(osc_start_value))
            self._acquisition_parameters.osc_start = osc_start_value

            # self.update_osc_total_range_limits()
            # self.update_num_images_limits()

    def osc_start_ledit_changed(self, osc_start):
        """Fixes osc start edit"""
        if "osc_start" not in self.value_changed_list:
            self.value_changed_list.append("osc_start")
        self.update_osc_total_range_limits()
        self.update_num_images_limits()
        self.emit_acq_parameters_changed()

    def update_osc_start_limits(self):
        """In the plate mode sets osc start limits"""
        self.update_osc_total_range_limits()
        self.update_num_images_limits()

    def osc_range_per_frame_ledit_changed(self, new_value):
        self.update_osc_total_range()
        self.update_num_images_limits()
        self.update_exp_time_limits()
        self.emit_acq_parameters_changed()

    def update_osc_range_per_frame_limits(self):
        try:
            max_osc_speed = HWR.beamline.diffractometer.get_osc_max_speed()
            top_limit = max_osc_speed * float(
                self.acq_widget_layout.exp_time_ledit.text()
            )
            self.osc_range_per_frame_validator.setTop(top_limit)
            tool_tip = (
                "Oscillation range per frame limits 0 : "
                + "%0.4f\n4 digits precision." % top_limit
            )

            self.acq_widget_layout.osc_range_ledit.setToolTip(tool_tip)
            self._acquisition_mib.validate_all()
        except BaseException:
            pass

    def update_osc_total_range(self):
        self.acq_widget_layout.osc_total_range_ledit.blockSignals(True)

        if not self.grid_mode:
            try:
                self.acq_widget_layout.osc_total_range_ledit.setText(
                    "%0.2f" %
                    (
                        float(self.acq_widget_layout.osc_range_ledit.text())
                        * int(self.acq_widget_layout.num_images_ledit.text())
                    )
                )
            except BaseException:
                pass
        self.acq_widget_layout.osc_total_range_ledit.blockSignals(False)

    def update_total_exp_time(self):
        try:
            self.acq_widget_layout.exp_time_total_ledit.setText(
                "%.2f"
                % (
                    float(self.acq_widget_layout.exp_time_ledit.text())
                    * float(self.acq_widget_layout.num_images_ledit.text())
                )
            )
        except BaseException:
            pass

    def osc_total_range_ledit_changed(self, new_value):
        if not self.grid_mode:
            try:
                num_images = int(
                    float(new_value)
                    / float(self.acq_widget_layout.osc_range_ledit.text())
                )
                self.acq_widget_layout.num_images_ledit.blockSignals(True)
                self.acq_widget_layout.num_images_ledit.setText("%d" % num_images)
                self._acquisition_parameters.num_images = num_images
                self.acq_widget_layout.num_images_ledit.blockSignals(False)
            except BaseException:
                pass
            self.emit_acq_parameters_changed()

    def exp_time_total_ledit_changed(self, new_value):
        try:
            exp_time = float(new_value)  / float(self.acq_widget_layout.num_images_ledit.text())
            self.acq_widget_layout.exp_time_ledit.blockSignals(True)
            self.acq_widget_layout.exp_time_ledit.setText("%.4f" % exp_time)
            self._acquisition_parameters.exp_time = exp_time
            self.acq_widget_layout.exp_time_ledit.blockSignals(False)
        except BaseException:
            pass
        self.emit_acq_parameters_changed()

    def update_osc_total_range_limits(self, num_images=None):
        """Updates osc totol range. Limits are changed if a plate is used.
           - For simple oscillation osc_range is defined by osc_start and
             osc_start top limit.
           - For mesh osc_range is defined by number of images per line
             and osc in the middle of mesh
        """
        if HWR.beamline.diffractometer.in_plate_mode():
            if hasattr(self.parent(), "set_osc_total_range"):
                self.parent().set_osc_total_range(num_images)
                self._acquisition_mib.validate_all()

    def update_exp_time_limits(self):
        try:
            exp_time_limits = (
                HWR.beamline.detector.get_exposure_time_limits()
            )
            max_osc_speed = HWR.beamline.diffractometer.get_osc_max_speed()
            top_limit = (
                float(self.acq_widget_layout.osc_range_ledit.text()) / max_osc_speed
            )
            limits = (max(exp_time_limits[0], top_limit), exp_time_limits[1])

            self.update_detector_exp_time_limits(limits)
        except BaseException:
            pass

    def update_kappa(self, new_value):
        if not self.acq_widget_layout.kappa_ledit.hasFocus() and new_value is not None:
            self.acq_widget_layout.kappa_ledit.setText(str(new_value))
            self.emit_acq_parameters_changed()

    def update_kappa_phi(self, new_value):
        if not self.acq_widget_layout.kappa_phi_ledit.hasFocus() and new_value:
            self.acq_widget_layout.kappa_phi_ledit.setText(str(new_value))
            self.emit_acq_parameters_changed()

    def use_osc_start(self, state):
        self.acq_widget_layout.osc_start_cbox.setVisible(state)
        self.acq_widget_layout.osc_start_label.setVisible(not state)
        self.acq_widget_layout.osc_start_ledit.setEnabled(not state)

    def use_kappa(self, state):
        if HWR.beamline.diffractometer is not None:
            if HWR.beamline.diffractometer.in_plate_mode():
                state = False
        self.acq_widget_layout.kappa_label.setEnabled(state)
        self.acq_widget_layout.kappa_ledit.setEnabled(state)
        self.acq_widget_layout.kappa_phi_label.setEnabled(state)
        self.acq_widget_layout.kappa_phi_ledit.setEnabled(state)

    def init_limits(self):
        limits_dict = HWR.beamline.acquisition_limit_values

        tpl = limits_dict.get("osc_range")
        if tpl:
            self.osc_start_validator.setRange(tpl[0], tpl[1], 4)
            self.osc_range_per_frame_validator.setRange(tpl[0], tpl[1], 4)
            self.osc_total_range_validator.setRange(tpl[0], tpl[1], 4)

        self._acquisition_mib.bind_value_update(
            "osc_start",
            self.acq_widget_layout.osc_start_ledit,
            float,
            self.osc_start_validator,
        )

        self._acquisition_mib.bind_value_update(
            "osc_range",
            self.acq_widget_layout.osc_range_ledit,
            float,
            self.osc_range_per_frame_validator,
        )

        self._acquisition_mib.bind_value_update(
            "osc_total_range",
            self.acq_widget_layout.osc_total_range_ledit,
            float,
            self.osc_total_range_validator,
        )

        tpl = limits_dict.get("kappa")
        if tpl:
            self.kappa_validator.setRange(tpl[0], tpl[1], 4)
        self._acquisition_mib.bind_value_update(
            "kappa", self.acq_widget_layout.kappa_ledit, float, self.kappa_validator
        )

        tpl = limits_dict.get("kappa_phi")
        if tpl:
            self.kappa_phi_validator.setRange(tpl[0], tpl[1], 4)
        self._acquisition_mib.bind_value_update(
            "kappa_phi",
            self.acq_widget_layout.kappa_phi_ledit,
            float,
            self.kappa_phi_validator,
        )

        tpl = limits_dict.get("exposure_time")
        if tpl:
            self.exp_time_validator.setRange(tpl[0], tpl[1], 6)

        self._acquisition_mib.bind_value_update(
            "exp_time",
            self.acq_widget_layout.exp_time_ledit,
            float,
            self.exp_time_validator,
        )

        tpl = limits_dict.get("number_of_images")
        if tpl:
            self.num_img_validator.setRange(tpl[0], tpl[1])
            self.first_img_validator.setRange(tpl[0], tpl[1])

        self._acquisition_mib.bind_value_update(
            "first_image",
            self.acq_widget_layout.first_image_ledit,
            int,
            self.first_img_validator,
        )

        self._acquisition_mib.bind_value_update(
            "num_images",
            self.acq_widget_layout.num_images_ledit,
            int,
            self.num_img_validator,
        )

        num_passes = self.acq_widget_layout.findChild(
            QtImport.QLineEdit, "num_passes_ledit"
        )

        if num_passes:
            self._acquisition_mib.bind_value_update(
                "num_passes", num_passes, int, QtImport.QIntValidator(1, 1000, self)
            )

        overlap_ledit = self.acq_widget_layout.findChild(
            QtImport.QLineEdit, "overlap_ledit"
        )

        if overlap_ledit:
            self._acquisition_mib.bind_value_update(
                "overlap",
                overlap_ledit,
                float,
                QtImport.QDoubleValidator(-1000, 1000, 2, self),
            )

        self._acquisition_mib.bind_value_update(
            "energy", self.acq_widget_layout.energy_ledit, float, self.energy_validator
        )
        self.update_energy_limits(
            (self.energy_validator.bottom(), self.energy_validator.top())
        )

        self._acquisition_mib.bind_value_update(
            "transmission",
            self.acq_widget_layout.transmission_ledit,
            float,
            self.transmission_validator,
        )
        self.update_transmission_limits(
            (self.transmission_validator.bottom(), self.transmission_validator.top())
        )

        self._acquisition_mib.bind_value_update(
            "resolution",
            self.acq_widget_layout.resolution_ledit,
            float,
            self.resolution_validator,
        )
        # self.update_resolution_limits((self.resolution_validator.bottom(),
        #                               self.resolution_validator.top()))

        self._acquisition_mib.bind_value_update(
            "shutterless", self.acq_widget_layout.shutterless_cbx, bool, None
        )

        self.set_tunable_energy(HWR.beamline.tunable_wavelength)

        has_shutter_less = HWR.beamline.detector.has_shutterless()
        self.acq_widget_layout.shutterless_cbx.setEnabled(has_shutter_less)
        self.acq_widget_layout.shutterless_cbx.setChecked(has_shutter_less)

        if HWR.beamline.disable_num_passes:
            num_passes = self.acq_widget_layout.findChild(
                QtImport.QLineEdit, "num_passes_ledit"
            )
            if num_passes:
                num_passes.setDisabled(True)

        self.init_detector_roi_modes()

    def first_image_ledit_change(self, new_value):
        self.emit_acq_parameters_changed()

    def exposure_time_ledit_changed(self, new_value):
        """If the exposure time changes we have to check the osc speed
           and if necessary update osc range per frame
        """
        self.update_osc_range_per_frame_limits()
        self.update_osc_total_range_limits()
        self.update_total_exp_time()
        self.emit_acq_parameters_changed()

    def num_images_ledit_change(self, new_value):
        if str(new_value).isdigit():
            # self._path_template.num_files = int(new_value)
            self.update_osc_range_per_frame_limits()
            self.update_osc_total_range_limits()
            self.update_osc_total_range()
            self.update_total_exp_time()
        self.emit_acq_parameters_changed()

    def overlap_changed(self, new_value):

        if HWR.beamline.detector.has_shutterless():
            try:
                new_value = float(new_value)
            except ValueError:
                pass

            if new_value != 0:
                self.acq_widget_layout.shutterless_cbx.setEnabled(False)
                self.acq_widget_layout.shutterless_cbx.setChecked(False)
                self._acquisition_parameters.shutterless = False
            else:
                self.acq_widget_layout.shutterless_cbx.setEnabled(True)
                self.acq_widget_layout.shutterless_cbx.setChecked(True)
                self._acquisition_parameters.shutterless = True

    def use_mad(self, state):
        self.acq_widget_layout.energies_combo.setEnabled(state)
        if state:
            (name, energy) = self.get_mad_energy()

            if energy != 0:
                self.update_energy(energy)
            self.madEnergySelectedSignal.emit(name, energy, state)
        else:
            self.update_energy(self.previous_energy)
            # energy = HWR.beamline.energy.get_current_energy()
            self.madEnergySelectedSignal.emit("", self.previous_energy, state)

    def max_osc_range_toggled(self, state):
        self.update_osc_total_range_limits()

    def get_mad_energy(self):
        energy_str = str(self.acq_widget_layout.energies_combo.currentText())
        (name, value) = energy_str.split(":")

        name = name.strip()
        value = value.strip()
        value = 0 if (value == "-") else float(value)

        return (name, value)

    def set_energies(self, energy_scan_result):
        self.acq_widget_layout.energies_combo.clear()

        inflection = (
            ("ip: %.4f" % energy_scan_result.inflection)
            if energy_scan_result.inflection
            else "ip: -"
        )

        peak = (
            ("pk: %.4f" % energy_scan_result.peak)
            if energy_scan_result.peak
            else "pk: -"
        )

        first_remote = (
            ("rm1: %.4f" % energy_scan_result.first_remote)
            if energy_scan_result.first_remote
            else "rm1: -"
        )

        second_remote = (
            ("rm2: %.4f" % energy_scan_result.second_remote)
            if energy_scan_result.second_remote
            else "rm2: -"
        )

        self.acq_widget_layout.energies_combo.addItems(
            [inflection, peak, first_remote, second_remote]
        )

    def energy_selected(self, index):
        if self.acq_widget_layout.mad_cbox.isChecked():
            (name, energy) = self.get_mad_energy()
            if energy != 0:
                self.update_energy(energy)

            self.madEnergySelectedSignal.emit(name, energy, True)

    def energy_ledit_changed(self, new_value):
        if "energy" not in self.value_changed_list:
            self.value_changed_list.append("energy")
        self.emit_acq_parameters_changed()

    def update_energy(self, energy):
        if (
            "energy" not in self.value_changed_list
            and not self.acq_widget_layout.energy_ledit.hasFocus()
        ):
            self.acq_widget_layout.energy_ledit.setText(str(energy))
        self.emit_acq_parameters_changed()

    def transmission_ledit_changed(self, transmission):
        if "transmission" not in self.value_changed_list:
            self.value_changed_list.append("transmission")
        self.emit_acq_parameters_changed()

    def update_transmission(self, transmission):
        if "transmission" not in self.value_changed_list:
            self.acq_widget_layout.transmission_ledit.setText(str(transmission))
        self.emit_acq_parameters_changed()

    def resolution_ledit_changed(self, resolution):
        if "resolution" not in self.value_changed_list:
            self.value_changed_list.append("resolution")
        self.emit_acq_parameters_changed()

    def update_resolution(self, resolution):
        if (
            "resolution" not in self.value_changed_list
            and not self.acq_widget_layout.resolution_ledit.hasFocus()
        ):
            self.acq_widget_layout.resolution_ledit.setText(str(resolution))
        self.emit_acq_parameters_changed()

    def update_energy_limits(self, limits):
        if limits:
            self.energy_validator.setBottom(limits[0])
            self.energy_validator.setTop(limits[1])
            self.acq_widget_layout.energy_ledit.setToolTip(
                "Energy limits %0.4f : %0.4f keV\n" % (limits[0], limits[1])
                + "4 digits precision."
            )
            self._acquisition_mib.validate_all()

    def update_transmission_limits(self, limits):
        if limits:
            self.transmission_validator.setBottom(limits[0])
            self.transmission_validator.setTop(limits[1])
            self.acq_widget_layout.transmission_ledit.setToolTip(
                "Transmission limits %0.2f : %0.2f %%\n" % (limits[0], limits[1])
                + "2 digits precision."
            )
            self._acquisition_mib.validate_all()

    def update_resolution_limits(self, limits):
        if limits:
            self.resolution_validator.setBottom(limits[0])
            self.resolution_validator.setTop(limits[1])
            self.acq_widget_layout.resolution_ledit.setToolTip(
                "Resolution limits %0.4f : %0.4f %s\n"
                % (limits[0], limits[1], chr(197))
                + "4 digits precision."
            )
            self._acquisition_mib.validate_all()

    def update_detector_exp_time_limits(self, limits):
        if limits:
            self.exp_time_validator.setRange(limits[0], limits[1], 6)
            self.acq_widget_layout.exp_time_ledit.setToolTip(
                "Exposure time limits %0.6f s : %0.1f s\n" % (limits[0], limits[1])
                + "6 digits precision."
            )
            self._acquisition_mib.validate_all()

    def update_num_images_limits(self, num_images_limits=None):
        """Updates number of images limit. Method used if plate mode.
        """

        self._acquisition_mib.validate_all()

        return
        if HWR.beamline.diffractometer.in_plate_mode():
            if num_images_limits is None:
                try:
                    osc_start = float(self.acq_widget_layout.osc_start_ledit.text())
                    osc_range = float(self.acq_widget_layout.osc_range_ledit.text())
                except ValueError:
                    return

                if osc_range == 0:
                    return

                num_images_limits = int(
                    (self.osc_start_validator.top() - osc_start) / osc_range
                )

            self.num_img_validator.setTop(num_images_limits)
            self.acq_widget_layout.num_images_ledit.setToolTip(
                "Number of images limits : %d" % num_images_limits
            )
            self._acquisition_mib.validate_all()

    def init_detector_roi_modes(self):
        roi_modes = HWR.beamline.detector.get_roi_modes()
        if (
            len(roi_modes) > 0
            and self.acq_widget_layout.detector_roi_mode_combo.count() == 0
        ):
            for roi_mode in roi_modes:
                self.acq_widget_layout.detector_roi_mode_combo.addItem(roi_mode)
            self.acq_widget_layout.detector_roi_mode_label.setEnabled(True)
            self.acq_widget_layout.detector_roi_mode_combo.setEnabled(True)

    def update_detector_roi_mode(self, roi_mode_index):
        if (
            roi_mode_index is not None
            and self.acq_widget_layout.detector_roi_mode_combo.count() > 0
        ):
            self.acq_widget_layout.detector_roi_mode_combo.setCurrentIndex(
                roi_mode_index
            )

    def detector_roi_mode_changed(self, roi_mode_index):
        HWR.beamline.detector.set_roi_mode(roi_mode_index)

    def kappa_ledit_changed(self, new_value):
        if "kappa" not in self.value_changed_list:
            self.value_changed_list.append("kappa")
        self.emit_acq_parameters_changed()

    def kappa_phi_ledit_changed(self, new_value):
        if "kappa_phi" not in self.value_changed_list:
            self.value_changed_list.append("kappa_phi")
        self.emit_acq_parameters_changed()

    def update_data_model(self, acquisition_parameters, path_template):
        self._acquisition_parameters = acquisition_parameters
        self._path_template = path_template
        self._acquisition_mib.set_model(acquisition_parameters)

        # Update mad widgets
        mad = True if self._path_template.mad_prefix != "" else False
        if mad:
            mad_prefix = str(self._path_template.mad_prefix)
            index = MAD_ENERGY_COMBO_NAMES[str(mad_prefix)]
            self.acq_widget_layout.energies_combo.setCurrentIndex(index)
            self.acq_widget_layout.mad_cbox.setChecked(True)
            self.acq_widget_layout.energies_combo.setEnabled(True)
        else:
            self.acq_widget_layout.mad_cbox.setChecked(False)
            self.acq_widget_layout.energies_combo.setEnabled(False)
            self.acq_widget_layout.energies_combo.setCurrentIndex(0)

        self.update_osc_total_range()
        self.update_total_exp_time()

        self.emit_acq_parameters_changed()

    def set_tunable_energy(self, state):
        self.acq_widget_layout.energy_ledit.setEnabled(state)
        self.acq_widget_layout.mad_cbox.setEnabled(state)
        self.acq_widget_layout.energies_combo.setEnabled(state)

    def check_parameter_conflict(self):
        return self._acquisition_mib.validate_all()

    def emit_acq_parameters_changed(self):
        self.acqParametersChangedSignal.emit(self._acquisition_mib.validate_all())
Exemple #8
0
class DCParametersWidget(QtImport.QWidget):
    def __init__(self, parent=None, name="parameter_widget"):

        QtImport.QWidget.__init__(self, parent)
        if name is not None:
            self.setObjectName(name)

        # Properties ----------------------------------------------------------

        # Signals ------------------------------------------------------------

        # Slots ---------------------------------------------------------------

        # Internal variables --------------------------------------------------
        self._data_collection = None
        self._tree_view_item = None
        self._acquisition_mib = None

        # Graphic elements ----------------------------------------------------
        _dc_parameters_widget = QtImport.QWidget(self)
        self._data_path_widget = DataPathWidget(_dc_parameters_widget)
        self._acq_widget = AcquisitionWidget(_dc_parameters_widget,
                                             layout="horizontal")
        self._processing_widget = ProcessingWidget(_dc_parameters_widget)

        # Layout --------------------------------------------------------------
        _dc_parameters_widget_layout = QtImport.QVBoxLayout(
            _dc_parameters_widget)
        _dc_parameters_widget_layout.addWidget(self._data_path_widget)
        _dc_parameters_widget_layout.addWidget(self._acq_widget)
        _dc_parameters_widget_layout.addWidget(self._processing_widget)
        _dc_parameters_widget_layout.setContentsMargins(0, 0, 0, 0)
        _dc_parameters_widget_layout.setSpacing(2)
        _dc_parameters_widget_layout.addStretch(10)

        _main_hlayout = QtImport.QHBoxLayout(self)
        _main_hlayout.addWidget(_dc_parameters_widget)
        _main_hlayout.setContentsMargins(0, 0, 0, 0)
        _main_hlayout.setSpacing(2)
        _main_hlayout.addStretch(0)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------
        self._data_path_widget.data_path_layout.prefix_ledit.textChanged.connect(
            self._prefix_ledit_change)
        self._data_path_widget.data_path_layout.run_number_ledit.textChanged.connect(
            self._run_number_ledit_change)
        self._acq_widget.madEnergySelectedSignal.connect(
            self.mad_energy_selected)
        self._acq_widget.acqParametersChangedSignal.connect(
            self.acq_parameters_changed)

        # Other ---------------------------------------------------------------

    def _prefix_ledit_change(self, new_value):
        prefix = self._data_collection.acquisitions[
            0].path_template.get_prefix()
        self._data_collection.set_name(prefix)
        self._tree_view_item.setText(0, self._data_collection.get_name())

    def _run_number_ledit_change(self, new_value):
        if str(new_value).isdigit():
            self._data_collection.set_number(int(new_value))
            self._tree_view_item.setText(0, self._data_collection.get_name())

    def acq_parameters_changed(self):
        if self._tree_view_item is None:
            return

        # TODO  get tree view in another way
        dc_tree_widget = self._tree_view_item.listView().parent().parent()
        dc_tree_widget.check_for_path_collisions()
        path_template = self._data_collection.acquisitions[0].path_template
        HWR.beamline.queue_model.check_for_path_collisions(path_template)

    def mad_energy_selected(self, name, energy, state):
        path_template = self._data_collection.acquisitions[0].path_template

        if state:
            path_template.mad_prefix = str(name)
        else:
            path_template.mad_prefix = ""

        run_number = HWR.beamline.queue_model.get_next_run_number(
            path_template)

        self._data_path_widget.set_run_number(run_number)
        self._data_path_widget.set_prefix(path_template.base_prefix)
        model = self._tree_view_item.get_model()
        model.set_name(path_template.get_prefix())
        self._tree_view_item.setText(0, model.get_name())

    def set_enabled(self, state):
        self._acq_widget.setEnabled(state)
        self._data_path_widget.setEnabled(state)
        self._processing_widget.setEnabled(state)

    def populate_widget(self, item):
        data_collection = item.get_model()
        self._tree_view_item = item
        self._data_collection = data_collection
        self._acquisition_mib = DataModelInputBinder(
            self._data_collection.acquisitions[0].acquisition_parameters)

        # The acq_widget sends a signal to the path_widget, and it relies
        # on that both models upto date, we need to refactor this part
        # so that both models are set before taking ceratin actions.
        # This workaround, works for the time beeing.
        self._data_path_widget._data_model = data_collection.acquisitions[
            0].path_template

        self._acq_widget.set_energies(
            data_collection.crystal.energy_scan_result)
        self._acq_widget.update_data_model(
            data_collection.acquisitions[0].acquisition_parameters,
            data_collection.acquisitions[0].path_template,
        )
        self._data_path_widget.update_data_model(
            data_collection.acquisitions[0].path_template)
        self._processing_widget.update_data_model(
            data_collection.processing_parameters)

        invalid = self._acquisition_mib.validate_all()
        if invalid:
            msg = (
                "This data collection has one or more incorrect parameters," +
                " correct the fields marked in red to solve the problem.")

            logging.getLogger("GUI").warning(msg)
Exemple #9
0
class AdvancedParametersWidget(QtImport.QWidget):
    def __init__(self, parent=None, name="advanced_parameters_widget"):
        QtImport.QWidget.__init__(self, parent)

        # Internal values -----------------------------------------------------
        self._data_collection = None
        self._tree_view_item = None
        self._acquisition_mib = None

        # Properties ----------------------------------------------------------

        # Signals -------------------------------------------------------------

        # Slots ---------------------------------------------------------------

        # Graphic elements ----------------------------------------------------
        _dc_parameters_widget = QtImport.QWidget(self)
        self._data_path_widget = DataPathWidget(_dc_parameters_widget)
        self._acq_widget = AcquisitionWidget(_dc_parameters_widget,
                                             layout="horizontal")

        # Layout --------------------------------------------------------------
        _dc_parameters_widget_layout = QtImport.QVBoxLayout(
            _dc_parameters_widget)
        _dc_parameters_widget_layout.addWidget(self._data_path_widget)
        _dc_parameters_widget_layout.addWidget(self._acq_widget)
        _dc_parameters_widget_layout.setSpacing(2)
        _dc_parameters_widget_layout.addStretch(10)
        _dc_parameters_widget_layout.setContentsMargins(0, 0, 0, 0)

        _main_hlayout = QtImport.QHBoxLayout(self)
        _main_hlayout.addWidget(_dc_parameters_widget)
        _main_hlayout.setSpacing(2)
        _main_hlayout.setContentsMargins(2, 2, 2, 2)
        _main_hlayout.addStretch(0)

        # Qt signal/slot connections ------------------------------------------
        # self._acq_widget.acqParametersChangedSignal.\
        #     connect(self.acq_parameters_changed)
        # self._data_path_widget.pathTemplateChangedSignal.\
        #     connect(self.acq_parameters_changed)
        self._acq_widget.madEnergySelectedSignal.connect(
            self.mad_energy_selected)

        # Ohter ---------------------------------------------------------------
        self._acq_widget.use_osc_start(False)
        self._acq_widget.acq_widget_layout.mad_cbox.hide()
        self._acq_widget.acq_widget_layout.energies_combo.hide()
        self._acq_widget.acq_widget_layout.shutterless_cbx.hide()

    def mad_energy_selected(self, name, energy, state):
        path_template = self._data_collection.acquisitions[0].path_template

        if state:
            path_template.mad_prefix = name
        else:
            path_template.mad_prefix = ""

        run_number = HWR.beamline.queue_model.get_next_run_number(
            path_template)

        self._data_path_widget.set_run_number(run_number)
        self._data_path_widget.set_prefix(path_template.base_prefix)
        model = self._tree_view_item.get_model()
        model.set_name(path_template.get_prefix())
        self._tree_view_item.setText(0, model.get_name())

    def populate_widget(self, tree_view_item, data_collection):
        self._tree_view_item = tree_view_item
        self._data_collection = data_collection

        # if isinstance(tree_view_item, queue_item.XrayCenteringQueueItem):
        #    self._data_collection = tree_view_item.get_model().reference_image_collection
        # else:
        #    self._data_collection = tree_view_item.get_model()
        executed = self._data_collection.is_executed()

        self._acq_widget.setEnabled(not executed)
        self._data_path_widget.setEnabled(not executed)

        self._acquisition_mib = DataModelInputBinder(
            self._data_collection.acquisitions[0].acquisition_parameters)

        # The acq_widget sends a signal to the path_widget, and it relies
        # on that both models upto date, we need to refactor this part
        # so that both models are set before taking ceratin actions.
        # This workaround, works for the time beeing.
        self._data_path_widget.update_data_model(
            self._data_collection.acquisitions[0].path_template)

        self._acq_widget.update_data_model(
            self._data_collection.acquisitions[0].acquisition_parameters,
            self._data_collection.acquisitions[0].path_template,
        )
        # self._acq_widget.use_osc_start(False)

        self._acq_widget.acq_widget_layout.num_images_ledit.setDisabled(
            data_collection.is_mesh())
        invalid = self._acquisition_mib.validate_all()
        if invalid:
            msg = (
                "This data collection has one or more incorrect parameters," +
                " correct the fields marked in red to solve the problem.")
            logging.getLogger("GUI").warning(msg)
class AcquisitionStillWidget(QtImport.QWidget):

    acqParametersChangedSignal = QtImport.pyqtSignal(list)

    def __init__(
            self,
            parent=None,
            name=None,
            fl=0,
            acq_params=None,
            path_template=None,
            layout="vertical",
    ):
        """
        Loads ui file that defines the gui layout.
        Initiates QLineEdits by adding limits, precision
        Connects to qt signals to update acquisition parameters
        :param parent:
        :param name:
        :param fl:
        :param acq_params:
        :param path_template:
        :param layout:
        """

        QtImport.QWidget.__init__(self, parent, QtImport.Qt.WindowFlags(fl))

        if name is not None:
            self.setObjectName(name)

        # Internal variables --------------------------------------------------
        self.value_changed_list = []

        # Properties ----------------------------------------------------------

        # Signals -------------------------------------------------------------

        # Slots ---------------------------------------------------------------

        # Graphic elements ----------------------------------------------------
        if acq_params is None:
            self._acquisition_parameters = queue_model_objects.AcquisitionParameters()
        else:
            self._acquisition_parameters = acq_params

        if path_template is None:
            self._path_template = queue_model_objects.PathTemplate()
        else:
            self._path_template = path_template

        self._acquisition_mib = DataModelInputBinder(self._acquisition_parameters)

        self.acq_widget_layout = QtImport.load_ui_file(
            "acquisition_widget_vertical_still_layout.ui"
        )
        # Layout --------------------------------------------------------------
        __main_vlayout = QtImport.QVBoxLayout(self)
        __main_vlayout.addWidget(self.acq_widget_layout)
        __main_vlayout.setSpacing(0)
        __main_vlayout.setContentsMargins(0, 0, 0, 0)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------
        self.acq_widget_layout.num_triggers_ledit.textChanged.connect(
            self.num_triggers_ledit_changed
        )
        self.acq_widget_layout.num_images_per_trigger_ledit.textChanged.connect(
            self.num_images_per_trigger_ledit_changed
        )

        self.acq_widget_layout.exp_time_ledit.textChanged.connect(
            self.exposure_time_ledit_changed
        )
        self.acq_widget_layout.detector_roi_mode_combo.activated.connect(
            self.detector_roi_mode_changed
        )
        self.acq_widget_layout.energy_ledit.textEdited.connect(
            self.energy_ledit_changed
        )
        self.acq_widget_layout.transmission_ledit.textEdited.connect(
            self.transmission_ledit_changed
        )
        self.acq_widget_layout.resolution_ledit.textEdited.connect(
            self.resolution_ledit_changed
        )

        # Other ---------------------------------------------------------------
        self.energy_validator = QtImport.QDoubleValidator(
            4, 25, 4, self.acq_widget_layout.energy_ledit
        )
        self.resolution_validator = QtImport.QDoubleValidator(
            0, 15, 3, self.acq_widget_layout.resolution_ledit
        )
        self.transmission_validator = QtImport.QDoubleValidator(
            0, 100, 3, self.acq_widget_layout.transmission_ledit
        )
        self.exp_time_validator = QtImport.QDoubleValidator(
            0.0001, 10000, 7, self.acq_widget_layout.exp_time_ledit
        )
        self.num_triggers_validator = QtImport.QIntValidator(
            1, 9999999, self.acq_widget_layout.num_triggers_ledit
        )
        self.num_images_per_trigger_validator = QtImport.QIntValidator(
            1, 9999999, self.acq_widget_layout.num_images_per_trigger_ledit
        )
        self.num_img_validator = QtImport.QIntValidator(
            1, 9999999, self.acq_widget_layout.num_images_ledit
        )

        limits_dict = api.beamline_setup.get_acquisition_limit_values()

        if "exposure_time" in limits_dict:
            limits = tuple(map(float, limits_dict["exposure_time"].split(",")))
            (lower, upper) = limits
            self.exp_time_validator.setRange(lower, upper, 6)

        self._acquisition_mib.bind_value_update(
            "exp_time",
            self.acq_widget_layout.exp_time_ledit,
            float,
            self.exp_time_validator,
        )

        self._acquisition_mib.bind_value_update(
            "num_triggers",
            self.acq_widget_layout.num_triggers_ledit,
            int,
            self.num_triggers_validator,
        )

        self._acquisition_mib.bind_value_update(
            "num_images_per_trigger",
            self.acq_widget_layout.num_images_per_trigger_ledit,
            int,
            self.num_images_per_trigger_validator,
        )

        if "number_of_images" in limits_dict:
            limits = tuple(map(float, limits_dict["number_of_images"].split(",")))
            (lower, upper) = limits
            self.num_img_validator.setRange(lower, upper)

        self._acquisition_mib.bind_value_update(
            "num_images",
            self.acq_widget_layout.num_images_ledit,
            int,
            self.num_img_validator,
        )

        self._acquisition_mib.bind_value_update(
            "energy", self.acq_widget_layout.energy_ledit, float, self.energy_validator
        )
        self.update_energy_limits(
            (self.energy_validator.bottom(), self.energy_validator.top())
        )

        self._acquisition_mib.bind_value_update(
            "transmission",
            self.acq_widget_layout.transmission_ledit,
            float,
            self.transmission_validator,
        )
        self.update_transmission_limits(
            (self.transmission_validator.bottom(), self.transmission_validator.top())
        )

        self._acquisition_mib.bind_value_update(
            "resolution",
            self.acq_widget_layout.resolution_ledit,
            float,
            self.resolution_validator,
        )

        self.init_detector_roi_modes()
        self.acq_widget_layout.detector_roi_mode_label.setEnabled(False)
        self.acq_widget_layout.detector_roi_mode_combo.setEnabled(False)

    def update_osc_total_range(self):
        """
        :return: None
        """
        return

    def use_osc_start(self, status):
        """
        :param status: boolean
        :return: None
        """
        return

    def use_max_osc_range(self, status):
        """
        :param status: boolean
        :return: None
        """
        return

    def use_kappa(self, status):
        """
        :param status: boolean
        :return: None
        """
        return

    def exposure_time_ledit_changed(self, value):
        """
        Updates exposure time QLineEdit
        :param value: str
        :return: None
        """
        self.update_total_exp_time()
        self.emit_acq_parameters_changed()

    def energy_ledit_changed(self, value):
        """
        Fixes energy value. Energy change will not rewrite the typed energy value
        :param value: str
        :return: None
        """
        if "energy" not in self.value_changed_list:
            self.value_changed_list.append("energy")
        self.emit_acq_parameters_changed()

    def update_energy(self, energy, wav=None):
        """
        Updates energy QLineEdit
        :param energy: energy in keV (float)
        :param wav: wavelength in A (float)
        :return: None
        """
        if (
            "energy" not in self.value_changed_list
            and not self.acq_widget_layout.energy_ledit.hasFocus()
        ):
            self.acq_widget_layout.energy_ledit.setText(str(energy))
        self.emit_acq_parameters_changed()

    def transmission_ledit_changed(self, transmission):
        """
        Event when a value in the transmission QLineEdit is changed
        :param transmission: in perc. (str)
        :return: None
        """
        if "transmission" not in self.value_changed_list:
            self.value_changed_list.append("transmission")
        self.emit_acq_parameters_changed()

    def update_transmission(self, transmission):
        """
        Updates transmission QLineEdit
        :param transmission: in perc. (float)
        :return: None
        """
        if "transmission" not in self.value_changed_list:
            self.acq_widget_layout.transmission_ledit.setText(str(transmission))
        self.emit_acq_parameters_changed()

    def resolution_ledit_changed(self, resolution):
        """
        Method called when user changes resolution
        :param resolution: in A (float)
        :return: None
        """
        if "resolution" not in self.value_changed_list:
            self.value_changed_list.append("resolution")
        self.emit_acq_parameters_changed()

    def update_resolution(self, resolution):
        """
        Updates resolution QLineEdit
        :param resolution: A (float)
        :return: None
        """
        if (
            "resolution" not in self.value_changed_list
            and not self.acq_widget_layout.resolution_ledit.hasFocus()
        ):
            self.acq_widget_layout.resolution_ledit.setText(str(resolution))
        self.emit_acq_parameters_changed()

    def update_energy_limits(self, limits):
        """
        Updates energy limits
        :param limits: list of two floats
        :return: None
        """
        if limits:
            self.energy_validator.setBottom(limits[0])
            self.energy_validator.setTop(limits[1])
            self.acq_widget_layout.energy_ledit.setToolTip(
                "Energy limits %0.4f : %0.4f keV\n" % (limits[0], limits[1])
                + "4 digits precision."
            )
            self._acquisition_mib.validate_all()

    def update_transmission_limits(self, limits):
        """
        Updates transmission limits
        :param limits: list of two floats
        :return: None
        """
        if limits:
            self.transmission_validator.setBottom(limits[0])
            self.transmission_validator.setTop(limits[1])
            self.acq_widget_layout.transmission_ledit.setToolTip(
                "Transmission limits %0.2f : %0.2f %%\n" % (limits[0], limits[1])
                + "2 digits precision."
            )
            self._acquisition_mib.validate_all()

    def update_resolution_limits(self, limits):
        """
        Updates resolution limits
        :param limits: list of two floats
        :return: None
        """
        if limits:
            self.resolution_validator.setBottom(limits[0])
            self.resolution_validator.setTop(limits[1])
            self.acq_widget_layout.resolution_ledit.setToolTip(
                "Resolution limits %0.4f : %0.4f %s\n"
                % (limits[0], limits[1], chr(197))
                + "4 digits precision."
            )
            self._acquisition_mib.validate_all()

    def update_detector_exp_time_limits(self, limits):
        """
        Updates exposure time limits
        :param limits: list of two floats
        :return: None
        """
        if limits:
            self.exp_time_validator.setRange(limits[0], limits[1], 6)
            self.acq_widget_layout.exp_time_ledit.setToolTip(
                "Exposure time limits %0.6f s : %0.1f s\n" % (limits[0], limits[1])
                + "6 digits precision."
            )
            self._acquisition_mib.validate_all()

    def init_detector_roi_modes(self):
        """
        Initiates detetor ROI modes. Available modes are added to the combobox
        :return: None
        """
        roi_modes = api.detector.get_roi_modes()
        if (
            len(roi_modes) > 0
            and self.acq_widget_layout.detector_roi_mode_combo.count() == 0
        ):
            for roi_mode in roi_modes:
                self.acq_widget_layout.detector_roi_mode_combo.addItem(roi_mode)
        self.acq_widget_layout.detector_roi_mode_label.setEnabled(
            len(roi_modes) > 1
        )
        self.acq_widget_layout.detector_roi_mode_combo.setEnabled(
            len(roi_modes) > 1
        )

    def update_detector_roi_mode(self, roi_mode_index):
        """
        Method called when roi mode has been chaned
        :param roi_mode_index: int
        :return: None
        """
        if (
            roi_mode_index is not None
            and self.acq_widget_layout.detector_roi_mode_combo.count() > 0
        ):
            self.acq_widget_layout.detector_roi_mode_combo.setCurrentIndex(
                roi_mode_index
            )

    def detector_roi_mode_changed(self, roi_mode_index):
        """
        Method called when user selects a detector roi mode
        :param roi_mode_index: int
        :return:
        """
        api.detector.set_roi_mode(roi_mode_index)

    def update_osc_range_per_frame_limits(self):
        """
        Updates osc range per frame limits
        :return: None
        """
        return

    def update_exp_time_limits(self):
        """
        Updates exposure time limits
        :return: None
        """
        return

    def update_osc_start(self, value):
        """
        Updates osc start
        :param value: float
        :return: None
        """
        return

    def update_kappa(self, value):
        """
        Updates kappa value
        :param value: float
        :return:
        """
        return

    def update_kappa_phi(self, value):
        """
        Updates kappa phi value
        :param value: float
        :return: None
        """
        return

    def update_data_model(self, acquisition_parameters, path_template):
        """
        Updates data model
        :param acquisition_parameters: AcquisitionParameters
        :param path_template: PathTemplate
        :return: None
        """
        self._acquisition_parameters = acquisition_parameters
        self._path_template = path_template
        self._acquisition_mib.set_model(acquisition_parameters)
        self.emit_acq_parameters_changed()

    def check_parameter_conflict(self):
        """
        Checks for parameter conflicts
        :return: list of conflicts
        """
        return self._acquisition_mib.validate_all()

    def emit_acq_parameters_changed(self):
        """
        Emits acqParametersChangedSignal
        :return: None
        """
        self.acqParametersChangedSignal.emit(self._acquisition_mib.validate_all())

    def set_energies(self, energies):
        """
        Sets energies
        :param energies:
        :return: None
        """
        return

    def num_triggers_ledit_changed(self, value):
        """
        Updates num images and total exp time
        :param value: QString
        :return: None
        """
        if "num_triggers" not in self.value_changed_list:
            self.value_changed_list.append("num_triggers")
        self.update_num_images()
        self.update_total_exp_time()
        self.emit_acq_parameters_changed()

    def num_images_per_trigger_ledit_changed(self, value):
        """
                Updates num images and total exp time
                :param value: QString
                :return: None
                """
        if "num_images_per_trigger" not in self.value_changed_list:
            self.value_changed_list.append("num_images_per_trigger")
        self.update_num_images()
        self.update_total_exp_time()
        self.emit_acq_parameters_changed()

    def update_num_images(self):
        """
        Updates num images
        :return: None
        """
        self.acq_widget_layout.num_images_ledit.setText(
            str(
                self._acquisition_parameters.num_triggers
                * self._acquisition_parameters.num_images_per_trigger
            )
        )

    def update_total_exp_time(self):
        """Updates total exposure time
        :return: None
        """
        try:
            self.acq_widget_layout.exp_time_total_ledit.setText(
                "%.2f"
                % (
                    float(self.acq_widget_layout.exp_time_ledit.text())
                    * float(self.acq_widget_layout.num_images_ledit.text())
                )
            )
        except BaseException:
            pass
class AcquisitionStillWidget(QtImport.QWidget):

    acqParametersChangedSignal = QtImport.pyqtSignal(list)

    def __init__(
        self,
        parent=None,
        name=None,
        fl=0,
        acq_params=None,
        path_template=None,
        layout="vertical",
    ):

        QtImport.QWidget.__init__(self, parent, QtImport.Qt.WindowFlags(fl))

        if name is not None:
            self.setObjectName(name)

        # Internal variables --------------------------------------------------

        # Properties ----------------------------------------------------------

        # Signals -------------------------------------------------------------

        # Slots ---------------------------------------------------------------

        # Graphic elements ----------------------------------------------------
        if acq_params is None:
            self._acquisition_parameters = queue_model_objects.AcquisitionParameters()
        else:
            self._acquisition_parameters = acq_params

        if path_template is None:
            self._path_template = queue_model_objects.PathTemplate()
        else:
            self._path_template = path_template

        self._acquisition_mib = DataModelInputBinder(self._acquisition_parameters)

        self.acq_widget_layout = QtImport.load_ui_file(
            "acquisition_widget_vertical_still_layout.ui"
        )
        # Layout --------------------------------------------------------------
        __main_vlayout = QtImport.QVBoxLayout(self)
        __main_vlayout.addWidget(self.acq_widget_layout)
        __main_vlayout.setSpacing(0)
        __main_vlayout.setContentsMargins(0, 0, 0, 0)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------
        self.acq_widget_layout.num_triggers_ledit.textChanged.connect(
            self.num_triggers_ledit_changed
        )
        self.acq_widget_layout.num_images_per_trigger_ledit.textChanged.connect(
            self.num_images_per_trigger_ledit_changed
        )

        self.acq_widget_layout.exp_time_ledit.textChanged.connect(
            self.exposure_time_ledit_changed
        )
        self.acq_widget_layout.detector_roi_mode_combo.activated.connect(
            self.detector_roi_mode_changed
        )
        self.acq_widget_layout.energy_ledit.textEdited.connect(
            self.energy_ledit_changed
        )
        self.acq_widget_layout.transmission_ledit.textEdited.connect(
            self.transmission_ledit_changed
        )
        self.acq_widget_layout.resolution_ledit.textEdited.connect(
            self.resolution_ledit_changed
        )

        # Other ---------------------------------------------------------------
        self.value_changed_list = []

        self.energy_validator = QtImport.QDoubleValidator(
            4, 25, 4, self.acq_widget_layout.energy_ledit
        )
        self.resolution_validator = QtImport.QDoubleValidator(
            0, 15, 3, self.acq_widget_layout.resolution_ledit
        )
        self.transmission_validator = QtImport.QDoubleValidator(
            0, 100, 3, self.acq_widget_layout.transmission_ledit
        )
        self.exp_time_validator = QtImport.QDoubleValidator(
            0.0001, 10000, 7, self.acq_widget_layout.exp_time_ledit
        )
        self.num_triggers_validator = QtImport.QIntValidator(
            1, 9999999, self.acq_widget_layout.num_triggers_ledit
        )
        self.num_images_per_trigger_validator = QtImport.QIntValidator(
            1, 9999999, self.acq_widget_layout.num_images_per_trigger_ledit
        )
        self.num_img_validator = QtImport.QIntValidator(
            1, 9999999, self.acq_widget_layout.num_images_ledit
        )
        self.acq_widget_layout.detector_roi_mode_label.setEnabled(False)
        self.acq_widget_layout.detector_roi_mode_combo.setEnabled(False)

    def update_osc_total_range(self):
        pass

    def use_osc_start(self, status):
        pass

    def use_max_osc_range(self, status):
        pass

    def use_kappa(self, status):
        pass

    def init_api(self):
        limits_dict = api.beamline_setup.get_acquisition_limit_values()

        if "exposure_time" in limits_dict:
            limits = tuple(map(float, limits_dict["exposure_time"].split(",")))
            (lower, upper) = limits
            self.exp_time_validator.setRange(lower, upper, 6)

        self._acquisition_mib.bind_value_update(
            "exp_time",
            self.acq_widget_layout.exp_time_ledit,
            float,
            self.exp_time_validator,
        )

        self._acquisition_mib.bind_value_update(
            "num_triggers",
            self.acq_widget_layout.num_triggers_ledit,
            int,
            self.num_triggers_validator,
        )

        self._acquisition_mib.bind_value_update(
            "num_images_per_trigger",
            self.acq_widget_layout.num_images_per_trigger_ledit,
            int,
            self.num_images_per_trigger_validator,
        )

        if "number_of_images" in limits_dict:
            limits = tuple(map(float, limits_dict["number_of_images"].split(",")))
            (lower, upper) = limits
            self.num_img_validator.setRange(lower, upper)

        self._acquisition_mib.bind_value_update(
            "num_images",
            self.acq_widget_layout.num_images_ledit,
            int,
            self.num_img_validator,
        )

        self._acquisition_mib.bind_value_update(
            "energy", self.acq_widget_layout.energy_ledit, float, self.energy_validator
        )
        self.update_energy_limits(
            (self.energy_validator.bottom(), self.energy_validator.top())
        )

        self._acquisition_mib.bind_value_update(
            "transmission",
            self.acq_widget_layout.transmission_ledit,
            float,
            self.transmission_validator,
        )
        self.update_transmission_limits(
            (self.transmission_validator.bottom(), self.transmission_validator.top())
        )

        self._acquisition_mib.bind_value_update(
            "resolution",
            self.acq_widget_layout.resolution_ledit,
            float,
            self.resolution_validator,
        )

        self.init_detector_roi_modes()

    def exposure_time_ledit_changed(self, new_values):
        self.emit_acq_parameters_changed()

    def energy_ledit_changed(self, new_value):
        if "energy" not in self.value_changed_list:
            self.value_changed_list.append("energy")
        self.emit_acq_parameters_changed()

    def update_energy(self, energy, wav=None):
        if (
            "energy" not in self.value_changed_list
            and not self.acq_widget_layout.energy_ledit.hasFocus()
        ):
            self.acq_widget_layout.energy_ledit.setText(str(energy))
        self.emit_acq_parameters_changed()

    def transmission_ledit_changed(self, transmission):
        if "transmission" not in self.value_changed_list:
            self.value_changed_list.append("transmission")
        self.emit_acq_parameters_changed()

    def update_transmission(self, transmission):
        if "transmission" not in self.value_changed_list:
            self.acq_widget_layout.transmission_ledit.setText(str(transmission))
        self.emit_acq_parameters_changed()

    def resolution_ledit_changed(self, resolution):
        if "resolution" not in self.value_changed_list:
            self.value_changed_list.append("resolution")
        self.emit_acq_parameters_changed()

    def update_resolution(self, resolution):
        if (
            "resolution" not in self.value_changed_list
            and not self.acq_widget_layout.resolution_ledit.hasFocus()
        ):
            self.acq_widget_layout.resolution_ledit.setText(str(resolution))
        self.emit_acq_parameters_changed()

    def update_energy_limits(self, limits):
        if limits:
            self.energy_validator.setBottom(limits[0])
            self.energy_validator.setTop(limits[1])
            self.acq_widget_layout.energy_ledit.setToolTip(
                "Energy limits %0.4f : %0.4f keV\n" % (limits[0], limits[1])
                + "4 digits precision."
            )
            self._acquisition_mib.validate_all()

    def update_transmission_limits(self, limits):
        if limits:
            self.transmission_validator.setBottom(limits[0])
            self.transmission_validator.setTop(limits[1])
            self.acq_widget_layout.transmission_ledit.setToolTip(
                "Transmission limits %0.2f : %0.2f %%\n" % (limits[0], limits[1])
                + "2 digits precision."
            )
            self._acquisition_mib.validate_all()

    def update_resolution_limits(self, limits):
        if limits:
            self.resolution_validator.setBottom(limits[0])
            self.resolution_validator.setTop(limits[1])
            self.acq_widget_layout.resolution_ledit.setToolTip(
                "Resolution limits %0.4f : %0.4f %s\n"
                % (limits[0], limits[1], chr(197))
                + "4 digits precision."
            )
            self._acquisition_mib.validate_all()

    def update_detector_exp_time_limits(self, limits):
        if limits:
            self.exp_time_validator.setRange(limits[0], limits[1], 6)
            self.acq_widget_layout.exp_time_ledit.setToolTip(
                "Exposure time limits %0.6f s : %0.1f s\n" % (limits[0], limits[1])
                + "6 digits precision."
            )
            self._acquisition_mib.validate_all()

    def init_detector_roi_modes(self):
        roi_modes = api.detector.get_roi_modes()
        if (
            len(roi_modes) > 0
            and self.acq_widget_layout.detector_roi_mode_combo.count() == 0
        ):
            for roi_mode in roi_modes:
                self.acq_widget_layout.detector_roi_mode_combo.addItem(roi_mode)
        self.acq_widget_layout.detector_roi_mode_label.setEnabled(
            len(roi_modes) > 1
        )
        self.acq_widget_layout.detector_roi_mode_combo.setEnabled(
            len(roi_modes) > 1
        )

    def update_detector_roi_mode(self, roi_mode_index):
        if (
            roi_mode_index is not None
            and self.acq_widget_layout.detector_roi_mode_combo.count() > 0
        ):
            self.acq_widget_layout.detector_roi_mode_combo.setCurrentIndex(
                roi_mode_index
            )

    def detector_roi_mode_changed(self, roi_mode_index):
        api.detector.set_roi_mode(roi_mode_index)

    def update_osc_range_per_frame_limits(self):
        pass

    def update_exp_time_limits(self):
        pass

    def update_osc_start(self, value):
        pass

    def update_kappa(self, value):
        pass

    def update_kappa_phi(self, value):
        pass

    def update_data_model(self, acquisition_parameters, path_template):
        self._acquisition_parameters = acquisition_parameters
        self._path_template = path_template
        self._acquisition_mib.set_model(acquisition_parameters)
        self.emit_acq_parameters_changed()

    def check_parameter_conflict(self):
        return self._acquisition_mib.validate_all()

    def emit_acq_parameters_changed(self):
        self.acqParametersChangedSignal.emit(self._acquisition_mib.validate_all())

    def set_energies(self, energies):
        pass

    def num_triggers_ledit_changed(self, value):
        if "num_triggers" not in self.value_changed_list:
            self.value_changed_list.append("num_triggers")
        self.update_num_images()
        self.emit_acq_parameters_changed()

    def num_images_per_trigger_ledit_changed(self, values):
        if "num_images_per_trigger" not in self.value_changed_list:
            self.value_changed_list.append("num_images_per_trigger")
        self.update_num_images()
        self.emit_acq_parameters_changed()

    def update_num_images(self):
        self.acq_widget_layout.num_images_ledit.setText(
            str(
                self._acquisition_parameters.num_triggers
                * self._acquisition_parameters.num_images_per_trigger
            )
        )