Exemple #1
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
Exemple #2
0
    def change_format(self):
        """
        Ask user for display format for floats and use it.

        This function also checks whether the format is valid and emits
        `sig_option_changed`.
        """
        format, valid = QInputDialog.getText(self, _('Format'),
                                             _("Float formatting"),
                                             QLineEdit.Normal,
                                             self.dataModel.get_format())
        if valid:
            format = str(format)
            try:
                format % 1.1
            except:
                msg = _("Format ({}) is incorrect").format(format)
                QMessageBox.critical(self, _("Error"), msg)
                return
            if not format.startswith('%'):
                msg = _("Format ({}) should start with '%'").format(format)
                QMessageBox.critical(self, _("Error"), msg)
                return
            self.dataModel.set_format(format)
            self.sig_option_changed.emit('dataframe_format', format)
 def set_umr_namelist(self):
     """Set UMR excluded modules name list"""
     arguments, valid = QInputDialog.getText(self, _('UMR'),
                               _("Set the list of excluded modules as "
                                 "this: <i>numpy, scipy</i>"),
                               QLineEdit.Normal,
                               ", ".join(self.get_option('umr/namelist')))
     if valid:
         arguments = to_text_string(arguments)
         if arguments:
             namelist = arguments.replace(' ', '').split(',')
             fixed_namelist = [module_name for module_name in namelist
                               if programs.is_module_installed(module_name)]
             invalid = ", ".join(set(namelist)-set(fixed_namelist))
             if invalid:
                 QMessageBox.warning(self, _('UMR'),
                                     _("The following modules are not "
                                       "installed on your machine:\n%s"
                                       ) % invalid, QMessageBox.Ok)
             QMessageBox.information(self, _('UMR'),
                                 _("Please note that these changes will "
                                   "be applied only to new Python/IPython "
                                   "consoles"), QMessageBox.Ok)
         else:
             fixed_namelist = []
         self.set_option('umr/namelist', fixed_namelist)
Exemple #4
0
 def rename_file(self, fname):
     """Rename file"""
     path, valid = QInputDialog.getText(self, _('Rename'),
                           _('New name:'), QLineEdit.Normal,
                           osp.basename(fname))
     if valid:
         path = osp.join(osp.dirname(fname), to_text_string(path))
         if path == fname:
             return
         if osp.exists(path):
             if QMessageBox.warning(self, _("Rename"),
                      _("Do you really want to rename <b>%s</b> and "
                        "overwrite the existing file <b>%s</b>?"
                        ) % (osp.basename(fname), osp.basename(path)),
                      QMessageBox.Yes|QMessageBox.No) == QMessageBox.No:
                 return
         try:
             misc.rename_file(fname, path)
             self.parent_widget.renamed.emit(fname, path)
             return path
         except EnvironmentError as error:
             QMessageBox.critical(self, _("Rename"),
                         _("<b>Unable to rename file <i>%s</i></b>"
                           "<br><br>Error message:<br>%s"
                           ) % (osp.basename(fname), to_text_string(error)))
Exemple #5
0
 def create_new_folder(self, current_path, title, subtitle, is_package):
     """Create new folder"""
     if current_path is None:
         current_path = ''
     if osp.isfile(current_path):
         current_path = osp.dirname(current_path)
     name, valid = QInputDialog.getText(self, title, subtitle,
                                        QLineEdit.Normal, "")
     if valid:
         dirname = osp.join(current_path, to_text_string(name))
         try:
             os.mkdir(dirname)
         except EnvironmentError as error:
             QMessageBox.critical(self, title,
                                  _("<b>Unable "
                                    "to create folder <i>%s</i></b>"
                                    "<br><br>Error message:<br>%s"
                                    ) % (dirname, to_text_string(error)))
         finally:
             if is_package:
                 fname = osp.join(dirname, '__init__.py')
                 try:
                     with open(fname, 'wb') as f:
                         f.write(to_binary_string('#'))
                     return dirname
                 except EnvironmentError as error:
                     QMessageBox.critical(self, title,
                                          _("<b>Unable "
                                            "to create file <i>%s</i></b>"
                                            "<br><br>Error message:<br>%s"
                                            ) % (fname,
                                                 to_text_string(error)))
Exemple #6
0
 def change_history_depth(self):
     "Change history max entries" ""
     depth, valid = QInputDialog.getInt(
         self, _("History"), _("Maximum entries"), self.get_option("max_entries"), 10, 10000
     )
     if valid:
         self.set_option("max_entries", depth)
 def add_other_dialog(self):
     """
     A QAction callback. Start a dialog to choose a name of a function except a peak or a background. The new
     function is added to the browser.
     """
     selected_name = QInputDialog.getItem(self.canvas, 'Fit', 'Select function', self.other_names, 0, False)
     if selected_name[1]:
         self.add_other_requested.emit(selected_name[0])
Exemple #8
0
 def change_max_line_count(self):
     "Change maximum line count" ""
     mlc, valid = QInputDialog.getInteger(
         self, _("Buffer"), _("Maximum line count"), self.get_option("max_line_count"), 0, 1000000
     )
     if valid:
         self.shell.setMaximumBlockCount(mlc)
         self.set_option("max_line_count", mlc)
Exemple #9
0
 def change_history_depth(self):
     "Change history max entries"""
     depth, valid = QInputDialog.getInteger(self, _('History'),
                                    _('Maximum entries'),
                                    self.get_option('max_entries'),
                                    10, 10000)
     if valid:
         self.set_option('max_entries', depth)
Exemple #10
0
 def change_exteditor(self):
     """Change external editor path"""
     path, valid = QInputDialog.getText(self, _('External editor'),
                       _('External editor executable path:'),
                       QLineEdit.Normal,
                       self.get_option('external_editor/path'))
     if valid:
         self.set_option('external_editor/path', to_text_string(path))
Exemple #11
0
 def get_arguments(self):
     arguments, valid = QInputDialog.getText(self, _('Arguments'),
                                             _('Command line arguments:'),
                                             QLineEdit.Normal,
                                             self.arguments)
     if valid:
         self.arguments = to_text_string(arguments)
     return valid
Exemple #12
0
 def change_max_line_count(self):
     "Change maximum line count"""
     mlc, valid = QInputDialog.getInt(self, _('Buffer'),
                                        _('Maximum line count'),
                                        self.get_option('max_line_count'),
                                        0, 1000000)
     if valid:
         self.shell.setMaximumBlockCount(mlc)
         self.set_option('max_line_count', mlc)
 def add_peak_dialog(self):
     """
     A QAction callback. Start a dialog to choose a peak function name. After that the tool will expect the user
     to click on the canvas to where the peak should be placed.
     """
     selected_name = QInputDialog.getItem(self.canvas, 'Fit', 'Select peak function', self.peak_names,
                                          self.peak_names.index(self.current_peak_type), False)
     if selected_name[1]:
         self.peak_type_changed.emit(selected_name[0])
         self.mouse_state.transition_to('add_peak')
Exemple #14
0
 def edit_filter(self):
     """Edit name filters"""
     filters, valid = QInputDialog.getText(self, _('Edit filename filters'),
                                           _('Name filters:'),
                                           QLineEdit.Normal,
                                           ", ".join(self.name_filters))
     if valid:
         filters = [f.strip() for f in to_text_string(filters).split(',')]
         self.parent_widget.sig_option_changed.emit('name_filters', filters)
         self.set_name_filters(filters)
 def add_background_dialog(self):
     """
     A QAction callback. Start a dialog to choose a background function name. The new function is added to the
     browser.
     """
     current_index = self.background_names.index(self.default_background)
     if current_index < 0:
         current_index = 0
     selected_name = QInputDialog.getItem(self.canvas, 'Fit', 'Select background function', self.background_names,
                                          current_index, False)
     if selected_name[1]:
         self.add_background_requested.emit(selected_name[0])
Exemple #16
0
    def insert_node(self):
        index = self.currentIndex()
        parentnode = index.internalPointer() or self.model().root

        key, b = QInputDialog.getText(
            self, "Insert Json node", "Insert key for new node:")
        if not b:
            return
        node = JsonNode(key)
        parentnode.add(node)
        row = parentnode.index(node)
        self.model().beginInsertRows(index, row, row)
        self.model().endInsertRows()
Exemple #17
0
 def change_format(self):
     """Change display format"""
     format, valid = QInputDialog.getText(
         self, _("Format"), _("Float formatting"), QLineEdit.Normal, self.model.get_format()
     )
     if valid:
         format = str(format)
         try:
             format % 1.1
         except:
             QMessageBox.critical(self, _("Error"), _("Format (%s) is incorrect") % format)
             return
         self.model.set_format(format)
Exemple #18
0
    def edit_key(self):
        index = self.currentIndex()
        if index.isValid():
            node = index.internalPointer()
            key, b = QInputDialog.getText(
                self, "Edit Json item", "Insert new key for item:",
                text=node.key
            )

            if not b:
                return

            node.key = key

            try:  # PyQt5
                self.model().dataChanged.emit(index, index, [Qt.DisplayRole])
            except TypeError:  # PyQt4, PySide
                self.model().dataChanged.emit(index, index)
Exemple #19
0
    def insert_item(self):
        index = self.currentIndex()

        if index.isValid():
            node = index.internalPointer()
        else:
            node = self.model().root

        key, b = QInputDialog.getText(
            self, "Insert Json item", "Insert key for new item:")

        if not b:
            return

        item = JsonItem(key)
        node.add(item)
        row = node.index(item)
        self.model().beginInsertRows(index, row, row)
        self.model().endInsertRows()
Exemple #20
0
    def _add_fittable_model(self, model_type):
        if issubclass(model_type, models.Polynomial1D):
            text, ok = QInputDialog.getInt(self, 'Polynomial1D',
                                           'Enter Polynomial1D degree:')
            # User decided not to create a model after all
            if not ok:
                return

            model = model_type(int(text))
        else:
            model = model_type()

        # Grab any user-defined regions so we may initialize parameters only
        # for the selected data.
        mask = self.hub.region_mask
        spec = self._get_selected_plot_data_item().data_item.spectrum

        # Initialize the parameters
        model = initialize(model, spec.spectral_axis[mask], spec.flux[mask])

        self._add_model(model)
Exemple #21
0
 def set_umr_namelist(self):
     """Set UMR excluded modules name list"""
     arguments, valid = QInputDialog.getText(self, _('UMR'),
                               _("Set the list of excluded modules as "
                                 "this: <i>numpy, scipy</i>"),
                               QLineEdit.Normal,
                               ", ".join(self.get_option('umr/namelist')))
     if valid:
         arguments = to_text_string(arguments)
         if arguments:
             namelist = arguments.replace(' ', '').split(',')
             fixed_namelist = []
             non_ascii_namelist = []
             for module_name in namelist:
                 if PY2:
                     if all(ord(c) < 128 for c in module_name):
                         if programs.is_module_installed(module_name):
                             fixed_namelist.append(module_name)
                     else:
                         QMessageBox.warning(self, _('Warning'),
                         _("You are working with Python 2, this means that "
                           "you can not import a module that contains non-"
                           "ascii characters."), QMessageBox.Ok)
                         non_ascii_namelist.append(module_name)
                 elif programs.is_module_installed(module_name):
                     fixed_namelist.append(module_name)
             invalid = ", ".join(set(namelist)-set(fixed_namelist)-
                                 set(non_ascii_namelist))
             if invalid:
                 QMessageBox.warning(self, _('UMR'),
                                     _("The following modules are not "
                                       "installed on your machine:\n%s"
                                       ) % invalid, QMessageBox.Ok)
             QMessageBox.information(self, _('UMR'),
                                 _("Please note that these changes will "
                                   "be applied only to new Python/IPython "
                                   "consoles"), QMessageBox.Ok)
         else:
             fixed_namelist = []
         self.set_option('umr/namelist', fixed_namelist)
Exemple #22
0
    def config_node(self):
        """Opens configuration the selected BBB's configuration window"""
        current_tab = self.tabWidget.currentIndex()
        index = (getattr(self, TABLES[current_tab] +
                         "Table").selectionModel().selectedRows()[0])

        bbb_ip = index.sibling(index.row(),
                               0 if current_tab != 4 else 1).data()
        bbb_hostname = (index.sibling(
            index.row(),
            1 if current_tab != 4 else 2).data().replace(":", "--"))

        hashname = "BBB:{}:{}".format(bbb_ip, bbb_hostname)
        info = self.nodes_info[hashname]
        if info[b"state_string"].decode() == "Connected":
            if not self.sudo:
                text, confirmation = QInputDialog.getText(
                    self,
                    "Confirmation",
                    ("This interface is meant for advanced changes that could result in downtime,"
                     "\nfailures or worse.\n"
                     "\nIf you want to enter sudo mode, type in 'Beaglebone' (case sensitive)"
                     ),
                )
                if confirmation and text == "Beaglebone":
                    self.sudo = True

            if self.sudo:
                self.window = BBBConfig(hashname, info, self.server)
                self.window.show()
        else:
            QtWidgets.QMessageBox.warning(
                self,
                "Warning",
                "The node you are trying to configure isn't connected",
                QtWidgets.QMessageBox.Abort,
            )
Exemple #23
0
 def toogle_breakpoint(self,
                       line_number=None,
                       condition=None,
                       edit_condition=False):
     """Add/remove breakpoint."""
     if not self.editor.is_python_like():
         return
     if line_number is None:
         block = self.editor.textCursor().block()
     else:
         block = self.editor.document().findBlockByNumber(line_number - 1)
     data = block.userData()
     if not data:
         data = BlockUserData(self.editor)
         data.breakpoint = True
     elif not edit_condition:
         data.breakpoint = not data.breakpoint
         data.breakpoint_condition = None
     if condition is not None:
         data.breakpoint_condition = condition
     if edit_condition:
         condition = data.breakpoint_condition
         condition, valid = QInputDialog.getText(self, _('Breakpoint'),
                                                 _("Condition:"),
                                                 QLineEdit.Normal,
                                                 condition)
         if not valid:
             return
         data.breakpoint = True
         data.breakpoint_condition = str(condition) if condition else None
     if data.breakpoint:
         text = to_text_string(block.text()).strip()
         if len(text) == 0 or text.startswith(('#', '"', "'")):
             data.breakpoint = False
     block.setUserData(data)
     self.editor.sig_flags_changed.emit()
     self.editor.sig_breakpoints_changed.emit()
Exemple #24
0
    def _removeConfiguration(self):
        try:
            configs = self._model.getConfigurations()
        except Exception as e:
            self._showWarningBox(e, "Failed to retrieve configurations")
        else:
            if configs:
                # Show configs available
                options = [item["name"] for item in configs]
                config, ok = QInputDialog.getItem(self,
                                                  "Available Configurations",
                                                  "Select a configuration:",
                                                  options, 0, False)
                if ok and config:
                    # Ask for confirmation
                    if self._isConfigurationLoaded(config):
                        msg = ("Configuration is currenty loaded."
                               "Delete it anyway?")
                    else:
                        msg = ("This will permanently delete configuration {}."
                               "Proceed?").format(config)

                    if self._showDialogBox(msg) == QMessageBox.Cancel:
                        return
                    # Delete configuration
                    config = configs[options.index(config)]
                    try:
                        self._model.deleteConfiguration(config)
                    except Exception as e:
                        self._showWarningBox(e)
                    else:
                        self._showMessageBox(
                            "Configuration {} was deleted.".format(
                                config['name']))
            else:
                self._showMessageBox("No configuration found")
        return
Exemple #25
0
    def _add_fittable_model(self, model_type):
        if issubclass(model_type, models.Polynomial1D):
            text, ok = QInputDialog.getInt(self, 'Polynomial1D',
                                           'Enter Polynomial1D degree:')
            # User decided not to create a model after all
            if not ok:
                return

            model = model_type(int(text))
        else:
            model = model_type()

        # Grab any user-defined regions so we may initialize parameters only
        # for the selected data.
        inc_regs = self.hub.spectral_regions
        spec = self._get_selected_plot_data_item().data_item.spectrum

        if inc_regs is not None:
            spec = extract_region(spec, inc_regs)

        # Initialize the parameters
        model = initialize(model, spec.spectral_axis, spec.flux)

        self._add_model(model)
Exemple #26
0
    def set_max_results(self, value=None):
        """
        Set maximum amount of results to add to the result browser.

        Parameters
        ----------
        value: int, optional
            Number of results. If None an input dialog will be used.
            Default is None.
        """
        if value is None:
            value, valid = QInputDialog.getInt(
                self,
                self.get_name(),
                _('Set maximum number of results: '),
                value=self.get_option('max_results'),
                min=1,
                step=1,
            )
        else:
            valid = True

        if valid:
            self.set_option('max_results', value)
Exemple #27
0
    def addChoice(self):
        if len(self._possible_items) == 0:
            QMessageBox.information(self, "No items",
                                    "No items available for selection!")
        else:
            item, ok = QInputDialog.getItem(
                self,
                "Select a case",
                "Select a case to add to the case list:",
                self._possible_items,
            )

            if ok:
                item = str(item).strip()
                text = str(self._list_edit_line.text()).rstrip()

                if len(text) == 0:
                    text = item + ", "
                elif text.endswith(","):
                    text += " " + item
                else:
                    text += ", " + item

                self._list_edit_line.setText(text)
Exemple #28
0
 def __start_record(self, toggled: bool) -> None:
     """Save to file path data."""
     if toggled:
         self.main_canvas.record_start(int(
             self.dial_spinbox.maximum() / self.record_interval.value()
         ))
         return
     path = self.main_canvas.get_record_path()
     name, ok = QInputDialog.getText(
         self,
         "Recording completed!",
         "Please input name tag:"
     )
     i = 0
     name = name or f"Record_{i}"
     while name in self.__path_data:
         name = f"Record_{i}"
         i += 1
     QMessageBox.information(
         self,
         "Record",
         "The name tag is being used or empty."
     )
     self.add_path(name, path)
Exemple #29
0
 def toogle_breakpoint(self, line_number=None, condition=None,
                       edit_condition=False):
     """Add/remove breakpoint."""
     if not self.editor.is_python_like():
         return
     if line_number is None:
         block = self.editor.textCursor().block()
     else:
         block = self.editor.document().findBlockByNumber(line_number-1)
     data = block.userData()
     if not data:
         data = BlockUserData(self.editor)
         data.breakpoint = True
     elif not edit_condition:
         data.breakpoint = not data.breakpoint
         data.breakpoint_condition = None
     if condition is not None:
         data.breakpoint_condition = condition
     if edit_condition:
         condition = data.breakpoint_condition
         condition, valid = QInputDialog.getText(self.editor,
                                                 _('Breakpoint'),
                                                 _("Condition:"),
                                                 QLineEdit.Normal,
                                                 condition)
         if not valid:
             return
         data.breakpoint = True
         data.breakpoint_condition = str(condition) if condition else None
     if data.breakpoint:
         text = to_text_string(block.text()).strip()
         if len(text) == 0 or text.startswith(('#', '"', "'")):
             data.breakpoint = False
     block.setUserData(data)
     self.editor.sig_flags_changed.emit()
     self.editor.sig_breakpoints_changed.emit()
Exemple #30
0
 def _renameConfiguration(self, column):
     new_name, ok = QInputDialog.getText(self, "New name", "Rename to:")
     if ok and new_name:
         return self._model.renameConfiguration(column, new_name)
Exemple #31
0
def get_annotation_of_track_end(viewer):
    return QInputDialog.getText(viewer.window.qt_viewer, "Input dialog",
                                "Annotate the track end:")
Exemple #32
0
 def _open_overplotted_on(self):
     item, ok = QInputDialog.getItem(
         self, "Select Tab", "Tab", self._tab_titles, 0, False)
     if not ok:
         return
     self.open.emit(item, self.entries)
    def import_data(self, filenames=None):
        """Import data from text file"""
        title = _("Import data")
        if filenames is None:
            if self.filename is None:
                basedir = getcwd()
            else:
                basedir = osp.dirname(self.filename)
            filenames, _selfilter = getopenfilenames(self, title, basedir,
                                                     iofunctions.load_filters)
            if not filenames:
                return
        elif is_text_string(filenames):
            filenames = [filenames]

        for filename in filenames:
            self.filename = to_text_string(filename)
            ext = osp.splitext(self.filename)[1].lower()

            if ext not in iofunctions.load_funcs:
                buttons = QMessageBox.Yes | QMessageBox.Cancel
                answer = QMessageBox.question(self, title,
                            _("<b>Unsupported file extension '%s'</b><br><br>"
                              "Would you like to import it anyway "
                              "(by selecting a known file format)?"
                              ) % ext, buttons)
                if answer == QMessageBox.Cancel:
                    return
                formats = list(iofunctions.load_extensions.keys())
                item, ok = QInputDialog.getItem(self, title,
                                                _('Open file as:'),
                                                formats, 0, False)
                if ok:
                    ext = iofunctions.load_extensions[to_text_string(item)]
                else:
                    return

            load_func = iofunctions.load_funcs[ext]
                
            # 'import_wizard' (self.setup_io)
            if is_text_string(load_func):
                # Import data with import wizard
                error_message = None
                try:
                    text, _encoding = encoding.read(self.filename)
                    if self.is_internal_shell:
                        self.editor.import_from_string(text)
                    else:
                        base_name = osp.basename(self.filename)
                        editor = ImportWizard(self, text, title=base_name,
                                      varname=fix_reference_name(base_name))
                        if editor.exec_():
                            var_name, clip_data = editor.get_data()
                            monitor_set_global(self._get_sock(),
                                               var_name, clip_data)
                except Exception as error:
                    error_message = str(error)
            else:
                QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
                QApplication.processEvents()
                if self.is_internal_shell:
                    namespace, error_message = load_func(self.filename)
                    interpreter = self.shellwidget.interpreter
                    for key in list(namespace.keys()):
                        new_key = fix_reference_name(key,
                                     blacklist=list(interpreter.namespace.keys()))
                        if new_key != key:
                            namespace[new_key] = namespace.pop(key)
                    if error_message is None:
                        interpreter.namespace.update(namespace)
                else:
                    error_message = monitor_load_globals(self._get_sock(),
                                                         self.filename, ext)
                QApplication.restoreOverrideCursor()
                QApplication.processEvents()
    
            if error_message is not None:
                QMessageBox.critical(self, title,
                                     _("<b>Unable to load '%s'</b>"
                                       "<br><br>Error message:<br>%s"
                                       ) % (self.filename, error_message))
            self.refresh_table()
Exemple #34
0
 def addNewCollection(self):
     name, ok = QInputDialog.getText(self, 'Collection', 'Collection name:')
     if ok and len(name) > 0 and name != "All":
         config.bibleCollections[name] = {}
         self.showListOfCollections()
         self.biblesTable.setEnabled(False)