def run(self): while True: ac = async_call_queue.get() if not ac.func_to_call: continue result = None try: if ac.parameter == None: result = ac.func_to_call() elif isinstance(ac.parameter, tuple): result = ac.func_to_call(*ac.parameter) else: result = ac.func_to_call(ac.parameter) except Exception as e: with async_session_lock: if ac.session_id != async_session_id: continue if ac.error_callback != None: if ac.log_exception: logging.exception('Error while doing async call') if ac.report_exception: async_event_queue.put( functools.partial(ac.error_callback, e)) else: async_event_queue.put(ac.error_callback) if isinstance(e, ip_connection.Error): # clear the async call queue if an IPConnection # error occurred. in this case we assume that the # next calls will also fail with async_call_queue.mutex: async_call_queue.queue.clear() QApplication.postEvent(self, QEvent(ASYNC_EVENT)) continue if ac.result_callback != None: with async_session_lock: if ac.session_id != async_session_id: continue if result == None: async_event_queue.put(ac.result_callback) else: async_event_queue.put( functools.partial(ac.result_callback, result)) QApplication.postEvent(self, QEvent(ASYNC_EVENT))
def __set_update_loop(self, loop): """ Set the update `loop` coroutine. The `loop` is a generator yielding `(embedding, stress, progress)` tuples where `embedding` is a `(N, 2) ndarray` of current updated MDS points, `stress` is the current stress and `progress` a float ratio (0 <= progress <= 1) If an existing update loop is already in palace it is interrupted (closed). .. note:: The `loop` must not explicitly yield control flow to the event loop (i.e. call `QApplication.processEvents`) """ if self.__update_loop is not None: self.__update_loop.close() self.__update_loop = None self.progressBarFinished(processEvents=None) self.__update_loop = loop if loop is not None: self.progressBarInit(processEvents=None) self.setStatusMessage("Running") self.runbutton.setText("Stop") self.__state = OWMDS.Running QtGui.QApplication.postEvent(self, QEvent(QEvent.User)) else: self.setStatusMessage("") self.runbutton.setText("Start") self.__state = OWMDS.Finished
def _invalidate_plot(self): """ Schedule a delayed replot. """ if not self.__replot_requested: self.__replot_requested = True QApplication.postEvent(self, QEvent(self.ReplotRequest), Qt.LowEventPriority - 10)
def write(self, str): """ Emulate write function """ if self.guistream.thread() != QThread.currentThread(): sys_stdout.write(str) e = QEvent(QEvent.Type(RedirectionEventId)) e.txt = str QApplication.postEvent(self.guistream, e) pass else: self.guistream.write(str)
def customEvent(self, event): if event.type() == QEvent.User and self.__update_loop is not None: if not self.__in_next_step: self.__in_next_step = True try: self.__next_step() finally: self.__in_next_step = False else: warnings.warn( "Re-entry in update loop detected. " "A rogue `proccessEvents` is on the loose.", RuntimeWarning) # re-schedule the update iteration. QtGui.QApplication.postEvent(self, QEvent(QEvent.User)) return super().customEvent(event)
def __next_step(self): if self.__update_loop is None: return loop = self.__update_loop try: embedding, stress, progress = next(self.__update_loop) assert self.__update_loop is loop except StopIteration: self.__set_update_loop(None) self.unconditional_commit() else: self.progressBarSet(100.0 * progress, processEvents=None) self.embedding = embedding self._update_plot() # schedule next update QtGui.QApplication.postEvent(self, QEvent(QEvent.User), Qt.LowEventPriority)
def closeSecondaryEvent(self, event): """Close the main window. """ document = self.current_document() if document.isModifiedStrict(): if self.ask_save_changes() == QDialog.Rejected: # Reject the event event.ignore() return old_scheme = document.scheme() # Set an empty scheme to clear the document document.setScheme(config.workflow_constructor(parent=self)) QApplication.sendEvent(old_scheme, QEvent(QEvent.Close)) old_scheme.deleteLater() config.save_config() geometry = self.saveGeometry() state = self.saveState(version=self.SETTINGS_VERSION) settings = QSettings() settings.beginGroup("mainwindow") settings.setValue("geometry", geometry) settings.setValue("state", state) settings.setValue("canvasdock/expanded", self.dock_widget.expanded()) settings.setValue("scheme-margins-enabled", self.scheme_margins_enabled) settings.setValue("last-scheme-dir", self.last_scheme_dir) settings.setValue("widgettoolbox/state", self.widgets_tool_box.saveState()) settings.setValue("quick-help/visible", self.canvas_tool_dock.quickHelpVisible()) settings.endGroup() event.accept()
def test_outputs(self): self.send_signal(self.signal_name, self.signal_data) # only needed in TestOWMDS if type(self).__name__ == "TestOWMDS": from PyQt4.QtCore import QEvent self.widget.customEvent(QEvent(QEvent.User)) self.widget.commit() # check selected data output self.assertIsNone(self.get_output("Selected Data")) # check annotated data output feature_name = ANNOTATED_DATA_FEATURE_NAME annotated = self.get_output(ANNOTATED_DATA_SIGNAL_NAME) self.assertEqual(0, np.sum([i[feature_name] for i in annotated])) # select data instances self._select_data() # check selected data output selected = self.get_output("Selected Data") n_sel, n_attr = len(selected), len(self.data.domain.attributes) self.assertGreater(n_sel, 0) self.assertEqual(selected.domain == self.data.domain, self.same_input_output_domain) np.testing.assert_array_equal(selected.X[:, :n_attr], self.data.X[self.selected_indices]) # check annotated data output annotated = self.get_output(ANNOTATED_DATA_SIGNAL_NAME) self.assertEqual(n_sel, np.sum([i[feature_name] for i in annotated])) # compare selected and annotated data domains self._compare_selected_annotated_domains(selected, annotated) # check output when data is removed self.send_signal(self.signal_name, None) self.assertIsNone(self.get_output("Selected Data")) self.assertIsNone(self.get_output(ANNOTATED_DATA_SIGNAL_NAME))
def __next_step(self): if self.__update_loop is None: return loop = self.__update_loop try: embedding, stress, progress = next(self.__update_loop) assert self.__update_loop is loop except StopIteration: self.__set_update_loop(None) self.unconditional_commit() self.__draw_similar_pairs = True self._update_plot() self.plot.autoRange(padding=0.1, items=[self._scatter_item]) else: self.progressBarSet(100.0 * progress, processEvents=None) self.embedding = embedding self._update_plot() self.plot.autoRange(padding=0.1, items=[self._scatter_item]) # schedule next update QtGui.QApplication.postEvent( self, QEvent(QEvent.User), Qt.LowEventPriority)
def _invalidate(self): if not self._invalidated: self._invalidated = True QApplication.postEvent(self, QEvent(QEvent.User))
def _invalidate_preview(self): if not self.__update_pending: self.__update_pending = True QApplication.postEvent(self, QEvent(QEvent.User))
def __scheduleLayout(self): if not self.__reflowPending: self.__reflowPending = True QApplication.postEvent(self, QEvent(QEvent.LayoutRequest), Qt.HighEventPriority)
def _invalidate(self): self.__invalidated = True QApplication.postEvent(self, QEvent(self.Invalidate))
def __init__(self): super().__init__() #: widget's runtime state self.__state = State.NoState self._imageMeta = [] self._imageCategories = {} self.__invalidated = False self.__pendingTask = None vbox = gui.vBox(self.controlArea) hbox = gui.hBox(vbox) self.recent_cb = QComboBox( sizeAdjustPolicy=QComboBox.AdjustToMinimumContentsLengthWithIcon, minimumContentsLength=16, ) self.recent_cb.activated[int].connect(self.__onRecentActivated) icons = standard_icons(self) browseaction = QAction( "Open/Load Images", self, iconText="\N{HORIZONTAL ELLIPSIS}", icon=icons.dir_open_icon, toolTip="Select a directory from which to load the images") browseaction.triggered.connect(self.__runOpenDialog) reloadaction = QAction("Reload", self, icon=icons.reload_icon, toolTip="Reload current image set") reloadaction.triggered.connect(self.reload) self.__actions = namespace( browse=browseaction, reload=reloadaction, ) browsebutton = QPushButton(browseaction.iconText(), icon=browseaction.icon(), toolTip=browseaction.toolTip(), clicked=browseaction.trigger) reloadbutton = QPushButton( reloadaction.iconText(), icon=reloadaction.icon(), clicked=reloadaction.trigger, default=True, ) hbox.layout().addWidget(self.recent_cb) hbox.layout().addWidget(browsebutton) hbox.layout().addWidget(reloadbutton) self.addActions([browseaction, reloadaction]) reloadaction.changed.connect( lambda: reloadbutton.setEnabled(reloadaction.isEnabled())) box = gui.vBox(vbox, "Info") self.infostack = QStackedWidget() self.info_area = QLabel(text="No image set selected", wordWrap=True) self.progress_widget = QProgressBar(minimum=0, maximum=0) self.cancel_button = QPushButton( "Cancel", icon=icons.cancel_icon, ) self.cancel_button.clicked.connect(self.cancel) w = QWidget() vlayout = QVBoxLayout() vlayout.setContentsMargins(0, 0, 0, 0) hlayout = QHBoxLayout() hlayout.setContentsMargins(0, 0, 0, 0) hlayout.addWidget(self.progress_widget) hlayout.addWidget(self.cancel_button) vlayout.addLayout(hlayout) self.pathlabel = TextLabel() self.pathlabel.setTextElideMode(Qt.ElideMiddle) self.pathlabel.setAttribute(Qt.WA_MacSmallSize) vlayout.addWidget(self.pathlabel) w.setLayout(vlayout) self.infostack.addWidget(self.info_area) self.infostack.addWidget(w) box.layout().addWidget(self.infostack) self.__initRecentItemsModel() self.__invalidated = True self.__executor = ThreadExecutor(self) QApplication.postEvent(self, QEvent(RuntimeEvent.Init))
def shutdown_request(): QCoreApplication.postEvent(mainwindow, QEvent(Updater.QUIT_EVENT_TYPE))
def _update(self): """ Schedule processing at a later time. """ QCoreApplication.postEvent(self, QEvent(QEvent.UpdateRequest))
def scheduleDelayedActivate(self): if self.isEnabled() and not self.__layoutPending: self.__layoutPending = True QApplication.postEvent(self, QEvent(QEvent.LayoutRequest))
def postEventWithCallback(self, callback, *args): self.queue.put((callback, args)) app = KApplication.kApplication() app.postEvent(self, QEvent(QEvent.User))