Exemple #1
0
def check_update(dlg: QProgressDialog) -> str:
    """Check for update."""
    ver_list = [int(v) for v in __version__.split('.') if v.isdigit()]
    logger.info(f"Getting update for \"{__version__}\":")
    m = len(ver_list)
    for i in range(m):
        if i == 0:
            text = "major"
        elif i == 1:
            text = "minor"
        else:
            text = "micro"
        dlg.setLabelText(f"Checking for {text}...")
        QCoreApplication.processEvents()
        if dlg.wasCanceled():
            return ""
        next_ver = ver_list[:m]
        next_ver[i] += 1
        for j in range(i + 1, m):
            next_ver[j] = 0
        if i == 0:
            next_ver[1] = 1
        elif i == 1:
            if next_ver[1] > 12:
                dlg.setValue(i + 1)
                continue
        url = (f"https://github.com/KmolYuan/Pyslvs-UI/releases/tag/"
               f"v{next_ver[0]}.{next_ver[1]:02}.{next_ver[2]}")
        request = get_url(url)
        dlg.setValue(i + 1)
        if request.status_code == 200:
            dlg.setValue(m)
            return url
    return ""
Exemple #2
0
 def __efd_path(self) -> None:
     """Elliptical Fourier Descriptors."""
     path = self.current_path()
     n, ok = QInputDialog.getInt(self, "Elliptical Fourier Descriptors",
                                 "The number of points:", len(path), 3)
     if not ok:
         return
     dlg = QProgressDialog("Path transform.", "Cancel", 0, 1, self)
     dlg.setWindowTitle("Elliptical Fourier Descriptors")
     dlg.show()
     self.set_path(efd_fitting(path, n))
     dlg.setValue(1)
     dlg.deleteLater()
 def __init__(self, parent):
     self._parent = parent
     self._progressDialog = QProgressDialog(self._parent)
     self._progressDialog.setMinimumWidth(300)
     self._progressDialog.setWindowModality(Qt.ApplicationModal)
     self._progressDialog.setMinimumDuration(0)
     self._progressDialog.hide()
Exemple #4
0
 def load_data(self, file_name: str, data: _Data) -> None:
     """Load file method."""
     self.main_clear()
     ver = data.get('pyslvs_ver', "")
     if ver:
         logger.info(f"Load data from version {ver}")
     del ver
     self.dlg = QProgressDialog("Loading project", "Cancel", 0, 7,
                                self._parent)
     self.dlg.show()
     try:
         mechanism_data = self.__load_mech(data)
         storage_data = self.__load_storage(data)
         input_data = self.__load_input(data)
         paths = self.__load_path(data)
         collection_data = self.__load_collection(data)
         config_data = self.__load_config(data)
         algorithm_data = self.__load_algorithm(data)
         self.__load_background(data)
     except Exception as e:
         QMessageBox.warning(self._parent, "Load error", f"Exception:\n{e}")
         self.dlg.deleteLater()
         self.dlg = None
         return
     # File type option align (ignore previous one)
     self.prefer.file_type_option = data.get('file_type', 0)
     # Show overview dialog
     self.dlg.deleteLater()
     self.dlg = OverviewDialog(
         self._parent,
         QFileInfo(file_name).baseName(),
         mechanism_data,
         storage_data,
         input_data,
         paths,
         collection_data,
         config_data,
         algorithm_data,
         self.get_background_path()
     )
     self.dlg.show()
     self.dlg.exec_()
     self.dlg.deleteLater()
     self.dlg = None
Exemple #5
0
 def _add_items(self):
     # Connect signals
     t = BuildTree(self)
     t.finished.connect(t.deleteLater)
     dlg = None
     if len(self.items) > 1500:
         dlg = QProgressDialog(
             labelText='Building Tree',
             minimum=0, maximum=len(self._items), parent=self)
         t.itemDone.connect(lambda: dlg.setValue(dlg.value() + 1))
         t.finished.connect(dlg.close)
     # Start
     t.start()
     if dlg:
         dlg.exec_()
     t.wait()
Exemple #6
0
 def __reload_atlas(self) -> None:
     """Reload atlas with the engine."""
     current_pos = self.collection_list.currentRow()
     self.collections_layouts.clear()
     self.collection_list.clear()
     self.__clear_selection()
     if not self.collections:
         return
     dlg = QProgressDialog("Drawing atlas...", "Cancel", 0,
                           len(self.collections), self)
     dlg.setWindowTitle("Type synthesis")
     dlg.resize(400, dlg.height())
     dlg.setModal(True)
     dlg.show()
     engine_str = self.graph_engine.currentText()
     for i, g in enumerate(self.collections):
         QCoreApplication.processEvents()
         if dlg.wasCanceled():
             dlg.deleteLater()
             return
         item = QListWidgetItem(f"No. {i + 1}")
         pos = engine_picker(g, engine_str,
                             self.graph_link_as_node.isChecked())
         item.setIcon(
             graph2icon(g,
                        self.collection_list.iconSize().width(),
                        self.graph_link_as_node.isChecked(),
                        self.graph_show_label.isChecked(),
                        self.prefer.monochrome_option,
                        pos=pos))
         self.collections_layouts.append(pos)
         item.setToolTip(f"{g.edges}")
         self.collection_list.addItem(item)
         dlg.setValue(i + 1)
     dlg.deleteLater()
     if current_pos > -1:
         self.collection_list.setCurrentRow(current_pos)
         self.__set_selection(self.collection_list.currentItem())
Exemple #7
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()
 def __check_update(self) -> None:
     """Check for update."""
     dlg = QProgressDialog("Checking update ...", "Cancel", 0, 3, self)
     dlg.setWindowTitle("Check for update")
     dlg.resize(400, dlg.height())
     dlg.setModal(True)
     dlg.show()
     url = check_update(dlg)
     dlg.deleteLater()
     if url:
         if QMessageBox.question(
                 self, "Pyslvs has update",
                 "Do you want to get it from Github?") == QMessageBox.Yes:
             self.__open_url(url)
     else:
         QMessageBox.information(
             self, "Pyslvs is up to date",
             "You are using the latest version of Pyslvs.")
Exemple #9
0
    def load_data(self, file_name: str, data: Dict[str, Any]) -> None:
        """Load file method."""
        self.main_clear()
        ver = data.get('pyslvs_ver', "")
        if ver:
            logger.info(f"Load data from Pyslvs {ver}")
        del ver
        dlg = QProgressDialog("Loading project", "Cancel", 0, 8, self.parent())
        dlg.setLabelText("Reading file ...")
        dlg.show()

        # Mechanism data
        dlg.setValue(1)
        dlg.setLabelText("Loading mechanism ...")
        if dlg.wasCanceled():
            dlg.deleteLater()
            return self.main_clear()
        self.__set_group("Add mechanism")
        links_data: Dict[str, str] = data.get('links', {})
        self.add_empty_links(links_data)
        mechanism_data: str = data.get('mechanism', "")
        self.parse_expression(mechanism_data)
        self.__end_group()

        # Input data
        dlg.setValue(2)
        dlg.setLabelText("Loading inputs data ...")
        if dlg.wasCanceled():
            dlg.deleteLater()
            return self.main_clear()
        self.__set_group("Add inputs data")
        input_data: List[Dict[str, int]] = data.get('input', [])
        i_attr = []
        for b, d in input_data:
            QCoreApplication.processEvents()
            i_attr.append((b, d))
        self.load_inputs(i_attr)
        self.__end_group()

        # Storage data
        dlg.setValue(3)
        dlg.setLabelText("Loading storage ...")
        if dlg.wasCanceled():
            dlg.deleteLater()
            return self.main_clear()
        self.__set_group("Add storage")
        storage_data: Dict[str, str] = data.get('storage', {})
        self.load_storage(storage_data)
        self.__end_group()

        # Path data
        dlg.setValue(4)
        dlg.setLabelText("Loading paths ...")
        if dlg.wasCanceled():
            dlg.deleteLater()
            return self.main_clear()
        self.__set_group("Add paths")
        path_data: Dict[str, Sequence[Tuple[float,
                                            float]]] = data.get('path', {})
        self.load_paths(path_data)
        self.__end_group()

        # Collection data
        dlg.setValue(5)
        dlg.setLabelText("Loading graph collections ...")
        if dlg.wasCanceled():
            dlg.deleteLater()
            return self.main_clear()
        self.__set_group("Add graph collections")
        collection_data: List[Tuple[Tuple[int, int],
                                    ...]] = data.get('collection', [])
        self.load_collections(collection_data)
        self.__end_group()

        # Configuration data
        dlg.setValue(6)
        dlg.setLabelText("Loading synthesis configurations ...")
        if dlg.wasCanceled():
            dlg.deleteLater()
            return self.main_clear()
        self.__set_group("Add synthesis configurations")
        config_data: Dict[str, Dict[str, Any]] = data.get('triangle', {})
        self.load_config(config_data)
        self.__end_group()

        # Algorithm data
        dlg.setValue(7)
        dlg.setLabelText("Loading synthesis results ...")
        if dlg.wasCanceled():
            dlg.deleteLater()
            return self.main_clear()
        self.__set_group("Add synthesis results")
        algorithm_data: List[Dict[str, Any]] = data.get('algorithm', [])
        self.load_algorithm(algorithm_data)
        self.__end_group()

        # Workbook loaded
        dlg.setValue(8)
        dlg.deleteLater()

        # File type option align (ignore previous one)
        self.prefer.file_type_option = data.get('file_type', 0)

        # Show overview dialog
        dlg = OverviewDialog(self.parent(),
                             QFileInfo(file_name).baseName(), storage_data,
                             i_attr, path_data, collection_data, config_data,
                             algorithm_data)
        dlg.show()
        dlg.exec_()
        dlg.deleteLater()
    def process_data(self):
        # get settings
        buffer_length = int(float(self.buffer_settings['buffer_length']) * self.SR)
        sample_length = int(float(self.buffer_settings['sample_length']) * self.SR)
        valid_thresh = [int(x['validity'] / 100 * sample_length)
                        for x in self.buffer_settings['electrode_settings'].values()]

        bar = QProgressDialog('Processing', 'Stop', 0, len(self.depths), None)
        bar.setWindowModality(Qt.WindowModal)
        bar.show()
        # loop through each comment time and check whether segment is long enough
        for idx, (time, depth) in enumerate(zip(self.depth_times[:-1], self.depths[:-1])):
            bar.setValue(idx)
            bar.setLabelText(self.f_name + "  " + str(depth))
            if bar.wasCanceled():
                break

            if self.depth_times[idx + 1] - time >= sample_length:
                # get sample first, if doesn't pass validation, move forward until it does
                # or until buffer_length is elapsed.
                data = self.reader.get_analogsignal_chunk(i_start=time, i_stop=time + sample_length).T
                valid = self.validate_data_sample(data)
                t_offset = 0
                while not all(np.sum(valid, axis=1) > valid_thresh) and \
                        t_offset + sample_length < buffer_length and \
                        time + t_offset + sample_length < self.depth_times[idx + 1]:
                    t_offset += 300  # roughly a 100 Hz update rate.
                    data = self.reader.get_analogsignal_chunk(i_start=time + t_offset,
                                                              i_stop=time + t_offset + sample_length).T
                    valid = self.validate_data_sample(data)

                # send to db
                self.db_wrapper.save_depth_datum(depth=depth,
                                                 data=data,
                                                 is_good=np.sum(valid, axis=1) > valid_thresh,
                                                 group_info=self.channels,
                                                 start_time=self.rec_start_time +
                                                 datetime.timedelta(seconds=(time + t_offset) / self.SR),
                                                 stop_time=self.rec_start_time +
                                                 datetime.timedelta(seconds=(time + t_offset +
                                                                             sample_length) /
                                                                    self.SR))
        bar.close()
class QtProgressInformation(object):
    def __init__(self, parent):
        self._parent = parent
        self._progressDialog = QProgressDialog(self._parent)
        self._progressDialog.setMinimumWidth(300)
        self._progressDialog.setWindowModality(Qt.ApplicationModal)
        self._progressDialog.setMinimumDuration(0)
        self._progressDialog.hide()
#        self.progress_iterator = lambda seq, text = "Working... Please wait", allow_cancel = True, self = self : self.QtProgressIterator(self, seq, text, allow_cancel)

    def progress_iterator(self, sequence, text="Working... Please wait", allow_cancel=True, always_refresh=True):
        return self.QtProgressIterator(self, sequence, text, allow_cancel)


    def __show(self, text, allow_cancel, max_value=0):
        if not hasattr(self, '_progressDialog'):
            raise Exception ("%s inheriting QtProgressInformation must call QtProgressInformation.__init__" % self.__class__.__name__)
        self._progressDialog.reset()  #reset cancel flag
        self._progressDialog.setWindowTitle(text)
        self._progressDialog.setMaximum(max_value)

        cancel_text = (None, "Cancel")[allow_cancel]
        self._progressDialog.setCancelButtonText(cancel_text)
        self._progressDialog
        self._progressDialog.show()
        QApplication.processEvents()

    def __hide(self):
        self._progressDialog.hide()
        self._progressDialog.close()
        QApplication.processEvents()

    def start_blocking_task(self, text):
        self.__show(text, False)

    def end_blocking_task(self):
        self.__hide()

    class QtProgressIterator(collections.Iterator):
        def __init__(self, QtProgressInformation, seq, text, allow_cancel=True):
            self.QtProgressInformation = QtProgressInformation
            self.generator = iter(list(seq))

            self.allow_cancel = allow_cancel
            self.n = 0

            max_value = self.generator.__length_hint__()
            self.update_every = max(1, max_value // 100)
            self.QtProgressInformation._QtProgressInformation__show(text, allow_cancel, max_value)


        def __del__(self):
                self.QtProgressInformation._QtProgressInformation__hide()
                pass

        def __iter__(self):
                return self

        def next(self):
            # required by python 2
            return self.__next__()

        def __next__(self):

            if self.n % self.update_every == 0:
                if self.allow_cancel and self.QtProgressInformation._progressDialog.wasCanceled():
                    raise CancelWarning()
                self.QtProgressInformation._progressDialog.setValue(self.n)
                QApplication.processEvents()
            self.n += 1
            return next(self.generator)
#             try:
#                 return self.generator.__next__()
#             except AttributeError:
#                 return self.generator.next()  #in python 2, iterators __next__ is named next


    def _callback(self, current, maximum):
        if self._progressDialog.maximum() != maximum:
            self._progressDialog.setMaximum(maximum)

        self._progressDialog.setValue(current)
        if self._progressDialog.wasCanceled():
            raise CancelWarning()



    def exec_long_task_with_callback(self, text, allow_cancel, task, *args, **kwargs):

        self.__show(text, allow_cancel)
        try:
            res = task(*args, **kwargs)
        except Exception as e:
            raise e
        finally:
#        self.taskThread = TaskThread(task, *args, **kwargs)
#        self.taskThread.cancel_event = threading.Event()
#        self.taskThread.start()
#        while self.taskThread.is_alive():
#            time.sleep(0.1)
#            if allow_cancel and self._progressDialog.wasCanceled():
#                self.taskThread.cancel_event.set()
#                self.taskThread.join()
#                #raise CancelWarning
#            QApplication.processEvents()
#        self.taskThread.join()
            self.__hide()
        return res

#    def progress_iterator(self, sequence, text="Working... Please wait", allow_cancel=True):
#        it = iter(sequence)
#        if it.__length_hint__() > 0:
#            self.__show(text, allow_cancel, it.__length_hint__())
#            for n, v in enumerate(it):
#                if allow_cancel and self._progressDialog.wasCanceled():
#                    raise CancelWarning()
#                self._progressDialog.setValue(n)
#                yield(v)
#            self._progressDialog.hide()
#            QApplication.processEvents()

    def exec_long_task(self, text, allow_cancel, task, *args, **kwargs):


#        class TaskQThread(QThread):
#            result = None
#            def __init__(self, _parent, task, *args, **kwargs):
#                QThread.__init__(self)
#                self.task = lambda: task(*args, **kwargs)
#
#            def run(self):
#                self.result = self.task()
#        t = TaskQThread(self, task, *args, **kwargs)
#        t.start()
#        while t.isRunning():
#            time.sleep(0.1)
#            QApplication.processEvents()


        self.__show(text, allow_cancel)
        if allow_cancel:
            self.taskThread = CancelableTaskThread(task, *args, **kwargs)
        else:
            self.taskThread = TaskThread(task, *args, **kwargs)

        self.taskThread.start()
        while self.taskThread.is_alive():
            time.sleep(0.1)
            if allow_cancel and self._progressDialog.wasCanceled():
                self.taskThread.cancel_event.set()
                self.taskThread.join()
                raise CancelWarning
            QApplication.processEvents()
        self.taskThread.join()
        self.__hide()
        if isinstance(self.taskThread.result, Exception):
            raise self.taskThread.result
        return self.taskThread.result

    def exec_long_guitask(self, text, task, *args, **kwargs):
        self.__show(text, False)
        QApplication.processEvents()
        task(*args, **kwargs)
        self.__hide()



        return self.taskThread.result