Esempio n. 1
0
    def update_message(self, show_no_update=False):
        parent = self.parent
        url = 'https://github.com/Argonne-National-Laboratory/Frhodo/releases'

        try:  # this would break without internet otherwise
            new_version_exists = self.newVersionExists(parent.version)
        except:
            return

        if new_version_exists:
            text = f'Frhodo update available at:<br><a href=\"{url}"\>Frhodo Github</a>'
            msgBox = self.msgBox = QMessageBox(parent)
            msgBox.setWindowTitle('Frhodo')
            msgBox.setText(text)
            msgBox.setTextFormat(QtCore.Qt.RichText)

            for child in msgBox.children():
                if type(child) == QLabel:
                    if child.text() == text:
                        child.setToolTip(url)
                        child.setOpenExternalLinks(False)
                        child.linkActivated.connect(lambda: self.openUrl(url))

            msgBox.show()
        elif show_no_update:
            msgBox = self.msgBox = QMessageBox(parent)
            msgBox.setWindowTitle('Frhodo')
            msgBox.setText('Frhodo is using the most current version')
            msgBox.show()
Esempio n. 2
0
    def _decrypt_mail(self, body, from_):
        cipher_key_pair = self._current_account.cipher_key_pairs.where(
            CipherKeyPair.address == from_)

        if cipher_key_pair.exists():
            try:
                body = cipher.decrypt(body.encode(),
                                      cipher_key_pair.get().private_key)
                body = body.decode()
            except DecryptionError:
                QMessageBox().warning(self._view, 'Ошибка',
                                      "Невозможно расшифровать")
                return body

        signature_key = self._current_account.signature_foreign_keys.where(
            SignatureForeignKey.address == from_)

        if signature_key.exists():
            body, correct = signature.decode_and_verify(
                body.encode(),
                signature_key.get().key)
            body = body.decode()
            if not correct:
                QMessageBox().warning(self._view, 'Ошибка', "Подпись не верна")

        return body
Esempio n. 3
0
    def set_segmentation_result(self, result: ROIExtractionResult):
        if (result.file_path is not None and result.file_path != "" and
                result.file_path != self.image.file_path):  # pragma: no cover
            if self._parent is not None:
                # TODO change to non disrupting popup
                QMessageBox().warning(
                    self._parent, "Result file bug",
                    "It looks like one try to set ROI form another file.")
            return
        if result.info_text and self._parent is not None:
            QMessageBox().information(self._parent, "Algorithm info",
                                      result.info_text)

        self._additional_layers = result.additional_layers
        self.last_executed_algorithm = result.parameters.algorithm
        self.set(f"algorithms.{result.parameters.algorithm}",
                 result.parameters.values)
        # Fixme not use EventedDict here
        try:
            roi_info = result.roi_info.fit_to_image(self.image)
        except ValueError:  # pragma: no cover
            raise ValueError(ROI_NOT_FIT)
        if result.points is not None:
            self.points = result.points
        self._roi_info = roi_info
        self.roi_changed.emit(self._roi_info)
Esempio n. 4
0
    def show_version_info(self):
        my_version = packaging.version.parse(self.base_release)
        remote_version = packaging.version.parse(self.release)
        if remote_version > my_version:
            if getattr(sys, "frozen", False):
                message = QMessageBox(
                    QMessageBox.Information,
                    "New release",
                    f"You use outdated version of PartSeg. "
                    f"Your version is {my_version} and current is {remote_version}. "
                    f"You can download next release form {self.url}",
                    QMessageBox.Ok | QMessageBox.Ignore,
                )
            else:
                message = QMessageBox(
                    QMessageBox.Information,
                    "New release",
                    f"You use outdated version of PartSeg. "
                    f"Your version is {my_version} and current is {remote_version}. "
                    "You can update it from pypi (pip install -U PartSeg)",
                    QMessageBox.Ok | QMessageBox.Ignore,
                )

            if message.exec_() == QMessageBox.Ignore:
                with open(os.path.join(state_store.save_folder, IGNORE_FILE),
                          "w",
                          encoding="utf-8") as f_p:
                    f_p.write(date.today().isoformat())
Esempio n. 5
0
    def _on_export_data(self):
        """
        Handler function that is called when the Export Data button is pressed
        """
        all_filters = ";;".join(['*.ecsv'])
        path, fmt = compat.getsavefilename(filters=all_filters)

        if path and fmt:
            try:
                plot_data_item = self.current_item
                self.export_data_item(plot_data_item, path, fmt)

                message_box = QMessageBox()
                message_box.setText("Data exported successfully.")
                message_box.setIcon(QMessageBox.Information)
                message_box.setInformativeText(
                    "Data set '{}' has been exported to '{}'".format(
                        plot_data_item.data_item.name, path))

                message_box.exec()
            except Exception as e:
                logging.error(e)

                message_box = QMessageBox()
                message_box.setText("Error exporting data set.")
                message_box.setIcon(QMessageBox.Critical)
                message_box.setInformativeText("{}\n{}".format(
                    sys.exc_info()[0],
                    sys.exc_info()[1].__repr__()[:100]))

                message_box.exec()
Esempio n. 6
0
    def show_error(self):
        """This class create error dialog and show it"""
        if self.error is None:
            return
        from PartSeg.common_gui.error_report import ErrorDialog

        if isinstance(self.error, TiffFileException):
            mess = QMessageBox()
            mess.setIcon(QMessageBox.Critical)
            mess.setText("During read file there is an error: " +
                         self.error.args[0])
            mess.setWindowTitle("Tiff error")
            mess.exec()
            return
        if isinstance(self.error, SegmentationLimitException):
            mess = QMessageBox()
            mess.setIcon(QMessageBox.Critical)
            mess.setText(
                "During segmentation process algorithm meet limitations:\n" +
                "\n".join(self.error.args))
            mess.setWindowTitle("Segmentation limitations")
            mess.exec()
            return
        dial = ErrorDialog(self.error, "Exception during program run")
        # TODO check
        # dial.moveToThread(QApplication.instance().thread())
        dial.exec()
Esempio n. 7
0
 def set_segmentation_result(self, result: ROIExtractionResult):
     if (result.file_path is not None and result.file_path != "" and
             result.file_path != self.image.file_path):  # pragma: no cover
         if self._parent is not None:
             # TODO change to non disrupting popup
             QMessageBox().warning(
                 self._parent, "Result file bug",
                 "It looks like one try to set ROI form another file.")
         return
     if self._parent and len(
             result.roi_info.bound_info) == 0:  # pragma: no cover
         QMessageBox.information(
             self._parent,
             "No result",
             "Segmentation contains no component, check parameters, especially chosen channel.",
         )
     if result.info_text and self._parent is not None:  # pragma: no cover
         QMessageBox().information(self._parent, "Algorithm info",
                                   result.info_text)
     parameters_dict = defaultdict(lambda: deepcopy(result.parameters))
     self._additional_layers = result.additional_layers
     self.additional_layers_changed.emit()
     self.last_executed_algorithm = result.parameters.algorithm
     self.set(f"algorithms.{result.parameters.algorithm}",
              result.parameters.values)
     self._set_roi_info(result.roi_info, True, [], parameters_dict)
     if result.points is not None:
         self.points = result.points
Esempio n. 8
0
 def __save_pixel_perfect(self):
     ''' saves an image based on passing the image through directly '''
     if len(self.image.text()) > 0:
         file_name = QFileDialog.getSaveFileName(parent=self, caption='Export Report',
                                                 filter='Report File (*.jpg *.png *.jpeg)')
         if file_name:
             output_file = str(file_name[0]).strip()
             if len(output_file) == 0:
                 return
             else:
                 format = os.path.splitext(output_file)[1][1:].strip()
                 if format in VALID_IMG_FORMATS:
                     from app import wait_cursor
                     with wait_cursor():
                         self.__status_bar.showMessage(f"Saving report to {output_file}", 5000)
                         self.preview.canvas.figure.savefig(output_file, format=format, dpi=self.__dpi)
                         if self.__concat_images(format, output_file):
                             self.__status_bar.showMessage(f"Saved report to {output_file}", 5000)
                 else:
                     msg_box = QMessageBox()
                     msg_box.setText(f"Invalid output file format - {output_file} is not one of {VALID_IMG_FORMATS}")
                     msg_box.setIcon(QMessageBox.Critical)
                     msg_box.setWindowTitle('Unexpected Error')
                     msg_box.exec()
     else:
         msg_box = QMessageBox()
         msg_box.setText('Unable to create report, no image selected')
         msg_box.setIcon(QMessageBox.Information)
         msg_box.setWindowTitle('No Image')
         msg_box.exec()
Esempio n. 9
0
    def pasteCellFromClipboard(self):
        """Paste text from clipboard into the table.

        :return: *True* in case of success, *False* if pasting data failed.
        """
        selected_idx = self.table.selectedIndexes()
        if len(selected_idx) != 1:
            msgBox = QMessageBox(parent=self.table)
            msgBox.setText(_PASTE1)
            msgBox.exec_()
            return False

        data_model = self.table.model()

        selected_row = selected_idx[0].row()
        selected_col = selected_idx[0].column()

        qapp = QApplication.instance()
        clipboard_text = qapp.clipboard().text()
        table_data = _parseTextAsTable(clipboard_text)

        protected_cells = 0
        out_of_range_cells = 0

        # paste table data into cells, using selected cell as origin
        for row_offset in range(len(table_data)):
            for col_offset in range(len(table_data[row_offset])):
                target_row = selected_row + row_offset
                target_col = selected_col + col_offset

                if target_row >= data_model.rowCount() or\
                   target_col >= data_model.columnCount():
                    out_of_range_cells += 1
                    continue

                index = data_model.index(target_row, target_col)
                flags = data_model.flags(index)

                # ignore empty strings
                if table_data[row_offset][col_offset] != "":
                    if not flags & Qt.ItemIsEditable:
                        protected_cells += 1
                        continue
                    data_model.setData(index,
                                       table_data[row_offset][col_offset])
                    # item.setText(table_data[row_offset][col_offset])

        if protected_cells or out_of_range_cells:
            msgBox = QMessageBox(parent=self.table)
            msgBox.setText(_PASTEFAIL)
            msgBox.exec_()
            return False
        return True
Esempio n. 10
0
    def _check_rows(self, rows, only_one=False):
        """Checks how many items are in ``rows`` and alerts user if not right.

        Checks the number of indices in ``rows``, alerts the user with a
        popup box if there are no items in ``rows``. Alternatively if the kwarg
        ``only_one`` is ``True`` also alerts users that too many rows are
        selected. Returns ``True`` if the right number(s) of items are in
        ``rows`` otherwise it returns ``False``.

        Parameters
        ----------
        rows : [row indices]
            A list of row indices to be checked.
        only_one : Bool, optional
            A boolean that indicates if more than one row is allowed, default
            is ``False``.
        Returns
        -------
        Ok : Bool
            A boolean to indicate if the number of items in row is Ok.

        """
        Ok = True

        if not rows:  # if no cell is selected
            Ok = False
            warning = QMessageBox()
            warning.setIcon(QMessageBox.Information)
            warning.setWindowTitle('Row(s) must be selected')
            warning.setText('Action not performed as no row is selected')
            warning.setDetailedText('This warning generally occurs '
                                    'because no row is selected, select a row'
                                    ' and try again')
            warning.setStandardButtons(QMessageBox.Ok)
            warning.exec_()

        elif len(rows) > 1 and only_one:
            Ok = False
            warning = QMessageBox()
            warning.setIcon(QMessageBox.Information)
            warning.setWindowTitle('More than one row is selected')
            warning.setText('Action not performed as more than one row is '
                            'selected')
            warning.setDetailedText('This warning generally occurs '
                                    'because there are more than one row '
                                    'selected, unselect some rows and try '
                                    'again')
            warning.setStandardButtons(QMessageBox.Ok)
            warning.exec_()

        return Ok
Esempio n. 11
0
    def save_attach(self):
        name = self.sender().text()

        path_to_save = save_dialog(self._view, name, "Сохранение файла")

        if not path_to_save:
            return

        original_path = list(self._current_mail.attachments.select().where(
            Attachment.name == name))[0].path

        encrypted = False
        content = None

        cipher_key_pair = self._current_account.cipher_key_pairs.where(
            CipherKeyPair.address == self._current_mail.sender)

        if cipher_key_pair.exists():
            encrypted = True

            with open(original_path, 'rb') as file:
                content = file.read()
            try:
                content = cipher.decrypt(content,
                                         cipher_key_pair.get().private_key)
            except DecryptionError:
                QMessageBox().warning(self._view, 'Ошибка',
                                      "Невозможно расшифровать")
                return

        signature_key = self._current_account.signature_foreign_keys.where(
            SignatureForeignKey.address == self._current_mail.sender)

        if signature_key.exists():
            if not encrypted:
                with open(original_path, 'rb') as file:
                    content = file.read()

            encrypted = True
            content, correct = signature.decode_and_verify(
                content,
                signature_key.get().key)
            if not correct:
                QMessageBox().warning(self._view, 'Ошибка', "Подпись не верна")
                return

        if encrypted:
            with open(path_to_save, 'wb') as file:
                file.write(content)
        else:
            shutil.copy(original_path, path_to_save)
Esempio n. 12
0
    def pb_export_to_tiff_and_txt_clicked(self):
        # TODO: Propagate full path to the saved file here
        dir_path = self.gpc.get_current_working_directory()
        dir_path = os.path.expanduser(dir_path)

        params = self.gpc.get_parameters_for_exporting_maps()

        dlg = DialogExportToTiffAndTxt(dir_path=dir_path)
        dlg.dset_list = params["dset_list"]
        dlg.dset_sel = params["dset_sel"]
        dlg.scaler_list = params["scaler_list"]
        dlg.scaler_sel = params["scaler_sel"]
        dlg.interpolate_on = params["interpolate_on"]
        dlg.quant_norm_on = params["quant_norm_on"]

        res = dlg.exec()
        if res:
            try:
                result_path = dlg.dir_path
                dataset_name = dlg.get_selected_dset_name()
                scaler_name = dlg.get_selected_scaler_name()
                interpolate_on = dlg.interpolate_on
                quant_norm_on = dlg.quant_norm_on
                file_formats = []
                if dlg.save_tiff:
                    file_formats.append("tiff")
                if dlg.save_txt:
                    file_formats.append("txt")
                self.gpc.export_xrf_maps(
                    results_path=result_path,
                    dataset_name=dataset_name,
                    scaler_name=scaler_name,
                    interpolate_on=interpolate_on,
                    quant_norm_on=quant_norm_on,
                    file_formats=file_formats,
                )
                if file_formats:
                    formats_text = " and ".join([_.upper() for _ in file_formats])
                else:
                    formats_text = "No"
                msg = f"{formats_text} files were saved to the directory '{result_path}'"
                logger.info(msg)

                msgbox = QMessageBox(QMessageBox.Information, "Files Saved", msg, QMessageBox.Ok, parent=self)
                msgbox.exec()

            except Exception as ex:
                msg = str(ex)
                msgbox = QMessageBox(QMessageBox.Critical, "Error", msg, QMessageBox.Ok, parent=self)
                msgbox.exec()
Esempio n. 13
0
def raise_to_operator(exc, execute=True):
    """
    Utility function to show a Python Exception in QMessageBox

    The type and representation of the Exception are shown in a pop-up
    QMessageBox. The entire traceback is available via a drop-down detailed
    text box in the QMessageBox

    Parameters
    ----------
    exc: Exception

    execute: bool, optional
        Whether to execute the QMessageBox
    """
    # Assemble QMessageBox with Exception details
    err_msg = QMessageBox()
    err_msg.setText(f'{exc.__class__.__name__}: {exc}')
    err_msg.setWindowTitle(type(exc).__name__)
    err_msg.setIcon(QMessageBox.Critical)
    # Format traceback as detailed text
    with io.StringIO() as handle:
        traceback.print_tb(exc.__traceback__, file=handle)
        handle.seek(0)
        err_msg.setDetailedText(handle.read())
    if execute:
        # Execute
        err_msg.exec_()
    return err_msg
Esempio n. 14
0
    def restart_failed_realizations(self):

        msg = QMessageBox(self)
        msg.setIcon(QMessageBox.Information)
        msg.setText(
            "Note that workflows will only be executed on the restarted realizations and that this might have unexpected consequences."
        )
        msg.setWindowTitle("Restart Failed Realizations")
        msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
        result = msg.exec_()

        if result == QMessageBox.Ok:
            self.restart_button.setVisible(False)
            self.kill_button.setVisible(True)
            self.done_button.setVisible(False)
            active_realizations = self.create_mask_from_failed_realizations()
            self._simulations_argments[
                'active_realizations'] = active_realizations
            self._simulations_argments[
                'prev_successful_realizations'] = self._simulations_argments.get(
                    'prev_successful_realizations', 0)
            self._simulations_argments[
                'prev_successful_realizations'] += self.count_successful_realizations(
                )
            self.startSimulation()
Esempio n. 15
0
    def validate_password(self):
        """
        If the widget is ```passwordProtected```, this method will propmt
        the user for the correct password.

        Returns
        -------
        bool
            True in case the password was correct of if the widget is not
            password protected.
        """
        if not self._password_protected:
            return True

        pwd, ok = QInputDialog().getText(None, "Authentication",
                                         "Please enter your password:"******"")
        pwd = str(pwd)
        if not ok or pwd == "":
            return False

        sha = hashlib.sha256()
        sha.update(pwd.encode())
        pwd_encrypted = sha.hexdigest()
        if pwd_encrypted != self._protected_password:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText("Invalid password.")
            msg.setWindowTitle("Error")
            msg.setStandardButtons(QMessageBox.Ok)
            msg.setDefaultButton(QMessageBox.Ok)
            msg.setEscapeButton(QMessageBox.Ok)
            msg.exec_()
            return False
        return True
Esempio n. 16
0
    def load_fod_input(self):
        _current_folder = self.parent.parent.current_folder
        [_table_file, _] = QFileDialog.getOpenFileName(
            parent=self.parent,
            caption="Input inp File",
            directory=_current_folder,
            filter=("inp files (*.inp);; All Files (*.*)"))

        if not _table_file:
            return

        try:
            fod_inputs = open(_table_file, "r")
        except IOError:
            self.err_messenger("Permission denied! Choose another input file!")
            return

        lines = fod_inputs.readlines()
        fod_inputs.close()

        for line in lines:
            try:
                if line.strip():
                    self.parameters[line.split('#')[1].strip()]=line.split('#')[0].strip()
            except IndexError:
                pass

        try:
            self.parent.ui.sample_1_title.setText(self.parameters['sample_1_title'])
            self.parent.ui.sample_2_title.setText(self.parameters['sample_2_title'])
            self.parent.ui.bkg_title.setText(self.parameters['background_title'])
            self.parent.ui.bkg_scans.setText(self.parameters['background scannrs'])
            self.parent.ui.sample_1_scans.setText(self.parameters['sample_1_scannrs'])
            self.parent.ui.sample_2_scans.setText(self.parameters['sample_2_scannrs'])
            self.parent.ui.secondary_scattering_ratio.setText(self.parameters['secondary_scattering_ratio'])
            self.parent.ui.plazcek_fit_range_min.setText(self.parameters['pla_range'].split(',')[0].strip())
            self.parent.ui.plazcek_fit_range_max.setText(self.parameters['pla_range'].split(',')[1].strip())
            if ',' in self.parameters['substitution_type']:
                self.parent.ui.subs_init.setText(self.parameters['substitution_type'].split(',')[0].strip())
                self.parent.ui.subs_rep.setText(self.parameters['substitution_type'].split(',')[1].strip())
            elif '/' in self.parameters['substitution_type']:
                self.parent.ui.subs_init.setText(self.parameters['substitution_type'].split('/')[0].strip())
                self.parent.ui.subs_rep.setText(self.parameters['substitution_type'].split('/')[1].strip())
            self.parent.ui.ft_qrange.setText(self.parameters['qrangeft'])
            self.parent.ui.ff_rrange.setText(self.parameters['fourier_range_r'])
            try:
                self.parent.ui.ff_qrange.setText(self.parameters['fourier_range_q'])
            except KeyError:
                self.parent.ui.ff_qrange.setText(self.parameters['fourier_range_Q'])

        except (IndexError, KeyError):
            msgBox = QMessageBox()
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.setText("Error in FOD input file!")
            msgBox.setWindowTitle("Error")
            msgBox.setStandardButtons(QMessageBox.Ok)
            msgBox.exec_()
            return

        return
Esempio n. 17
0
    def load_from_file(self, fname):
        try:
            self.I_meas, self.sigma = np.loadtxt(
                                        fname, skiprows=2, unpack=True)
        except (ValueError, TypeError):
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Warning)
            msg.setText("Could not Load File")
            msg.setInformativeText(
                "The chosen file does not match the formatting.")
            msg.setWindowTitle("Warning")
            msg.resize(900, 300)
            msg.exec_()
            return
        with open(fname, 'r') as f:
            self.plane_meas = f.readline().split()[-1]

        if self.plane_meas == 'x':
            self.line_sigmax.set_xdata(self.I_meas)
            self.line_sigmax.set_ydata(np.array(self.sigma)*1e3)
        else:
            self.line_sigmay.set_xdata(self.I_meas)
            self.line_sigmay.set_ydata(np.array(self.sigma)*1e3)
        self.fig_sigma.figure.axes[0].set_xlim(
                [min(self.I_meas)*(1-DT*10), max(self.I_meas)*(1+DT*10)])
        self.fig_sigma.figure.axes[0].set_ylim(
                [min(self.sigma)*(1-DT)*1e3, max(self.sigma)*(1+DT)*1e3])
        self.fig_sigma.figure.canvas.draw()
Esempio n. 18
0
    def load_data(self, file_path, file_loader, display=False):
        """
        Load spectral data given file path and loader.

        Parameters
        ----------
        file_path : str
            Path to location of the spectrum file.
        file_loader : str
            Format specified for the astropy io interface.
        display : bool
            Automatically add the loaded spectral data to the plot.

        Returns
        -------
        : :class:`~specviz.core.items.DataItem`
            The `DataItem` instance that has been added to the internal model.
        """
        try:
            spec = Spectrum1D.read(file_path, format=file_loader)
            name = file_path.split('/')[-1].split('.')[0]
            data_item = self.model.add_data(spec, name=name)

            return data_item
        except:
            message_box = QMessageBox()
            message_box.setText("Error loading data set.")
            message_box.setIcon(QMessageBox.Critical)
            message_box.setInformativeText("{}\n{}".format(
                sys.exc_info()[0],
                sys.exc_info()[1]))

            message_box.exec()
Esempio n. 19
0
    def _retrieve_configuration(self):
        type = QMessageBox.Question
        title = 'Retrieve configuration?'
        buttons = QMessageBox.Ok | QMessageBox.Cancel

        try:
            row = self._get_selected_rows(self.d_editor).pop()
        except KeyError:
            pass
        else:
            config_type, name = self._type_name(row, self.d_editor_model)
            name = name[:-37]
            message = \
                'Retrieve configuration {} ({})?'.format(config_type, name)
            msg = QMessageBox(type, title, message, buttons).exec_()
            if msg == QMessageBox.Ok:
                try:
                    self.d_editor_model.removeRows(row)
                except TypeError:
                    self._database_error(
                        'Exception',
                        'Configuration no longer is in the correct format',
                        'retrieve configuration')

        self.editor.selectionModel().clearSelection()
        self._fill_table(self.config_type.currentText())
Esempio n. 20
0
    def new_pydm_process(self, ui_file, macros=None, command_line_args=None):
        kwargs = copy.deepcopy(
            {
                "displayfile": ui_file,
                "macros": macros,
                "hide_nav_bar": self.hide_nav_bar,
                "hide_menu_bar": self.hide_menu_bar,
                "hide_status_bar": self.hide_status_bar,
                "read_only": pydm.data_plugins.is_read_only(),
            }
        )
        kwargs_str = json.dumps(kwargs)
        python_exe = sys.executable

        if not self._generic_launcher_file_path:
            msg = f"Failed to launch pydm process, '{self._generic_launcher_file_name}' not found in path. Using python '{python_exe}'"
            logger.error(msg)
            box = QMessageBox(QMessageBox.Critical, "New PyDM Process Error", msg)
            box.exec()
            return

        logger.info(f"Init New PyDM Processs - {ui_file}")
        logger.info(f"Params: {kwargs_str}")

        subprocess.Popen(
            [self._generic_launcher_file_path, kwargs_str],
            shell=False,
        )
Esempio n. 21
0
    def __init__(self,
                 file_name,
                 job_name,
                 job_number,
                 realization,
                 iteration,
                 parent=None):
        super(FileDialog, self).__init__(parent)

        self.setWindowTitle("{} # {} Realization: {} Iteration: {}" \
                            .format(job_name, job_number, realization, iteration))

        self._file_name = file_name
        try:
            self._file = open(file_name, "r")
        except OSError as error:
            self._mb = QMessageBox(QMessageBox.Critical, "Error opening file",
                                   error.strerror, QMessageBox.Ok, self)
            self._mb.finished.connect(self.accept)
            self._mb.show()
            return

        self._model = FileModel()
        self._view = FileView()
        self._view.setModel(self._model)

        self._init_layout()
        self._init_thread()

        self.show()
Esempio n. 22
0
 def display_warning(self):
     m = QMessageBox(self.parent())
     m.setText(
         'You need to restart the server for the changes to take effect')
     m.setWindowTitle('Warning')
     m.setIcon(QMessageBox.Information)
     m.show()
Esempio n. 23
0
def dialog(title, text, icon, setting=None, default=None):

    if not getattr(settings, setting.upper()):
        return True

    check = QCheckBox()
    check.setText(
        'Dont show this message again (can be reset via the preferences)')

    info = QMessageBox()
    info.setIcon(icon)
    info.setText(title)
    info.setInformativeText(text)
    info.setCheckBox(check)
    info.setStandardButtons(info.Cancel | info.Ok)
    if default == 'Cancel':
        info.setDefaultButton(info.Cancel)

    result = info.exec_()

    if result == info.Cancel:
        return False

    if check.isChecked():
        setattr(settings, setting.upper(), False)
        save_settings()

    return True
Esempio n. 24
0
def handle_capture(window, capture):
    email, ok = QInputDialog.getText(
        window, 'Email', 'Enter your employee ID or email:', flags=Qt.FramelessWindowHint | Qt.Popup)
    while ok and not get_email(email):
        email, ok = QInputDialog.getText(
            window, 'Email', 'Enter a valid employee ID or email:', flags=Qt.FramelessWindowHint | Qt.Popup)

    if ok:
        print('Send email to %s' % email)
        pb = None
        try:
            pb = QProgressDialog("Sending...", "", 0, 0, window, Qt.FramelessWindowHint | Qt.Popup)
            pb.setWindowModality(Qt.WindowModal)
            pb.setRange(0, 0)
            pb.setMinimumDuration(0)
            pb.setCancelButton(None)
            pb.show()

            nongui(send_image)(email, capture, cache_dir=IMAGE_CACHE_DIR)
        except Exception:
            import traceback
            traceback.print_exc()
            msg = QMessageBox(window)
            msg.setIcon(QMessageBox.Critical)
            msg.setText('Error sending email.')
            msg.setWindowFlags(Qt.FramelessWindowHint | Qt.Popup)
            msg.exec_()
        finally:
            if pb:
                pb.close()
Esempio n. 25
0
    def handle_timeout(self):
        """
        Handles the timeout event for the timer.
        Decreases the time remaining counter until 0 and when it is time,
        cleans up the event filter and closes the window.
        """
        if is_qt_designer():
            return
        # Decrease remaining time
        self._time_rem_ms -= self._timer.interval()
        # Update screen label with new remaining time
        self._update_label()

        if self._time_rem_ms > 0:
            self.start()
            return
        QApplication.instance().removeEventFilter(self)

        if self._window:
            logger.debug('Time to close the window')
            self._window.close()
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Warning)
            msg.setText(
                "Your window was closed due to inactivity for {}.".format(
                    self._get_time_text(self.timeout)))
            msg.setStandardButtons(QMessageBox.Ok)
            msg.setDefaultButton(QMessageBox.Ok)
            msg.exec_()
Esempio n. 26
0
    def _save_and_run_dialog(self):

        mb = QMessageBox(self.main_window)
        mb.setWindowTitle(_(u'Unsaved changes'))
        mb.setText(
            u'You have unsaved changes. What do you want to do?'
        )
        mb.addButton(
            QPushButton(
                self.theme.qicon(u'os-run'),
                _(u'Save and run')
            ),
            QMessageBox.AcceptRole
        )
        mb.addButton(
            QPushButton(
                self.theme.qicon(u'os-run'),
                _(u'Save, run, and don\'t ask again')
            ),
            QMessageBox.AcceptRole
        )

        mb.addButton(
            QPushButton(
                self.theme.qicon(u'dialog-cancel'),
                _(u'Cancel')
            ),
            QMessageBox.AcceptRole
        )
        return mb.exec_()
Esempio n. 27
0
 def report_error(self, text, error):
     heading = _('Error message:')
     msgbox = QMessageBox(
         QMessageBox.Critical, _('Restore'),
         _('<b>{}</b><br><br>{}<br>{}').format(text, heading, error),
         parent=self)
     msgbox.exec_()
Esempio n. 28
0
    def deleteSelectedTool(self):
        """Delete the currently selected item"""
        current_row = self.selectedRow()
        if current_row == -1:
            # no row selected
            return

        tdata = self.tool_model.toolDataFromRow(current_row)
        tnum = tdata['T']

        # should not delete tool if currently loaded in spindle. Warn user
        if tnum == self.tool_model.stat.tool_in_spindle:

            box = QMessageBox(
                QMessageBox.Warning,
                "Can't delete current tool!",
                "Tool #{} is currently loaded in the spindle.\n"
                "Please remove tool from spindle and try again.".format(tnum),
                QMessageBox.Ok,
                parent=self)
            box.show()
            return False

        if not self.confirmAction(
                'Are you sure you want to delete T{tdata[T]}?\n'
                '"{tdata[R]}"'.format(tdata=tdata)):
            return

        self.tool_model.removeTool(current_row)
Esempio n. 29
0
    def show_about(self):
        """Show About dialog."""
        msg_box = QMessageBox(self)
        text = (f"<img src='{image_path('mnelab_logo.png')}'>"
                f"<p>MNELAB {__version__}</p>")
        msg_box.setText(text)

        mnelab_url = "github.com/cbrnr/mnelab"
        mne_url = "github.com/mne-tools/mne-python"

        pkgs = []
        for key, value in have.items():
            if value:
                pkgs.append(f"{key}&nbsp;({value})")
            else:
                pkgs.append(f"{key}&nbsp;(not installed)")

        text = (f'<nobr><p>This program uses Python '
                f'{".".join(str(k) for k in version_info[:3])} and the '
                f'following packages:</p></nobr>'
                f'<p>{", ".join(pkgs)}</p>'
                f'<nobr><p>MNELAB repository: '
                f'<a href=https://{mnelab_url}>{mnelab_url}</a></p></nobr>'
                f'<nobr><p>MNE repository: '
                f'<a href=https://{mne_url}>{mne_url}</a></p></nobr>'
                f'<p>Licensed under the BSD 3-clause license.</p>'
                f'<p>Copyright 2017-2020 by Clemens Brunner.</p>')
        msg_box.setInformativeText(text)
        msg_box.exec_()
Esempio n. 30
0
 def __save_report(self):
     ''' writes the figure to the specified format '''
     formats = "Report Files (*.png *.jpg *.jpeg)"
     file_name = QFileDialog.getSaveFileName(parent=self,
                                             caption='Export Report',
                                             filter=formats)
     if file_name:
         output_file = str(file_name[0]).strip()
         if len(output_file) == 0:
             return
         else:
             format = os.path.splitext(output_file)[1][1:].strip()
             if format in VALID_IMG_FORMATS:
                 scale_factor = self.widthPixels.value() / self.__x
                 from app import wait_cursor
                 with wait_cursor():
                     self.__status_bar.showMessage(
                         f"Saving report to {output_file}", 5000)
                     self.preview.canvas.figure.savefig(output_file,
                                                        format=format,
                                                        dpi=self.__dpi *
                                                        scale_factor,
                                                        pad_inches=0,
                                                        bbox_inches='tight')
                     self.__status_bar.showMessage(
                         f"Saved report to {output_file}", 5000)
             else:
                 msg_box = QMessageBox()
                 msg_box.setText(
                     f"Invalid output file format - {output_file} is not one of {VALID_IMG_FORMATS}"
                 )
                 msg_box.setIcon(QMessageBox.Critical)
                 msg_box.setWindowTitle('Unexpected Error')
                 msg_box.exec()