class SettingChangedEvent(QEvent): """ A settings has changed. This event is sent by Settings instance to itself when a setting for a key has changed. """ SettingChanged = QEvent.registerEventType() """Setting was changed""" SettingAdded = QEvent.registerEventType() """A setting was added""" SettingRemoved = QEvent.registerEventType() """A setting was removed""" def __init__(self, etype, key, value=None, oldValue=None): """ Initialize the event instance """ QEvent.__init__(self, etype) self.__key = key self.__value = value self.__oldValue = oldValue def key(self): return self.__key def value(self): return self.__value def oldValue(self): return self.__oldValue
class EventFlusher(QObject): SetEvent = QEvent.Type(QEvent.registerEventType()) def __init__(self, parent=None): QObject.__init__(self, parent) self._state = threading.Event() def event(self, e): if e.type() == EventFlusher.SetEvent: assert threading.current_thread().name == "MainThread" self.set() return True return False def eventFilter(self, watched, event): return self.event(event) def set(self): QApplication.sendPostedEvents() QApplication.processEvents() QApplication.flush() assert not self._state.is_set() self._state.set() def clear(self): self._state.clear() def wait(self): assert threading.current_thread().name != "MainThread" self._state.wait()
class ThunkEvent( QEvent ): """ A QEvent subclass that holds a callable which can be executed by its listeners. Sort of like a "queued connection" signal. """ EventType = QEvent.Type(QEvent.registerEventType()) def __init__(self, func, *args): QEvent.__init__(self, self.EventType) if len(args) > 0: self.thunk = partial(func, *args) else: self.thunk = func def __call__(self): self.thunk() @classmethod def post(cls, handlerObject, func, *args): e = ThunkEvent( func, *args ) QApplication.postEvent(handlerObject, e) @classmethod def send(cls, handlerObject, func, *args): e = ThunkEvent( func, *args ) QApplication.sendEvent(handlerObject, e)
def __init__(self, function, args, kwargs): QEvent.__init__(self, QueuedCallEvent.QueuedCall) self.function = function self.args = args self.kwargs = kwargs self._result = None self._exc_info = None self._state = 0
class CallbackEvent(QEvent): _evtype = QEvent.Type(QEvent.registerEventType()) def __init__(self, callback, *args): super(CallbackEvent, self).__init__(self._evtype) self.callback = callback self.args = args
def __init__(self, etype, key, value=None, oldValue=None): """ Initialize the event instance """ QEvent.__init__(self, etype) self.__key = key self.__value = value self.__oldValue = oldValue
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 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 set(self, rms, peak, decay): """ This is the main function, call this from any thread. 0.0 <= rms, peak, decay <= 1.0 """ t = time.time() * 0.1 if t - self._last_time > self.gov_sec: self._last_time = t e = QEvent(QEvent.User) e.rms = rms e.peak = peak e.decay = decay QCoreApplication.instance().postEvent(self, e)
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))
class Updater(): QUIT_EVENT_TYPE = QEvent.Type(QEvent.registerEventType()) def __init__(self, window): pass def checkForUpdates(self): pass def close(self): pass
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 timerEvent(self, e): if self.percent == 100: self.killTimer(self.tid) event = QEvent(QEvent.User) data = {} data['tracknum'] = 0 data['state'] = 'enc' data['percent'] = self.percent data['track'] = 'Banco de Patricio' data['genre'] = 'Christmas' data['album'] = 'Patricio Nino' data['artist'] = 'AAAorthman' event.data = data self.emit(SIGNAL('status(QEvent *)'), event) self.percent += 10
class QueuedCallEvent(QEvent): QueuedCall = QEvent.registerEventType() def __init__(self, function, args, kwargs): QEvent.__init__(self, QueuedCallEvent.QueuedCall) self.function = function self.args = args self.kwargs = kwargs self._result = None self._exc_info = None self._state = 0 def call(self): try: self._result = self.function(*self.args, **self.kwargs) self._state = 1 except Exception as ex: self._exc_info = (type(ex), ex.args, None) raise def result(self): if self._state == 1: return self._result elif self._exc_info: raise self._exc_info[0](self._exc_info[1]) else: # Should this block, add timeout? raise RuntimeError("Result not yet ready") def isready(self): return self._state == 1 or self._exc_info
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)
class WidgetInitEvent(QEvent): DelayedInit = QEvent.registerEventType() def __init__(self, initstate): super().__init__(WidgetManager.WidgetInitEvent.DelayedInit) self._initstate = initstate def initstate(self): return self._initstate
class ExecuteCallEvent(QEvent): """ Represents an function call from the event loop (used by :class:`Task` to schedule the :func:`Task.run` method to be invoked) """ ExecuteCall = QEvent.registerEventType() def __init__(self): QEvent.__init__(self, ExecuteCallEvent.ExecuteCall)
class Updater(): QUIT_EVENT_TYPE = QEvent.Type(QEvent.registerEventType()) # https://github.com/vslavik/winsparkle/wiki/Basic-Setup def __init__(self, window): try: sys.frozen # don't want to try updating python.exe self.updater = ctypes.cdll.WinSparkle self.updater.win_sparkle_set_appcast_url( 'http://eliteocr.sourceforge.net/appcast.xml' ) # py2exe won't let us embed this in resources self.updater.win_sparkle_set_automatic_check_for_updates(1) self.updater.win_sparkle_set_update_check_interval(47 * 60 * 60) # set up shutdown callback global mainwindow mainwindow = window self.callback_t = ctypes.CFUNCTYPE(None) # keep reference self.callback_fn = self.callback_t(shutdown_request) self.updater.win_sparkle_set_shutdown_request_callback( self.callback_fn) self.updater.win_sparkle_init() except: from traceback import print_exc print_exc() self.updater = None def checkForUpdates(self): if self.updater: self.updater.win_sparkle_check_update_with_ui() def close(self): if self.updater: self.updater.win_sparkle_cleanup() self.updater = None
class Updater(): QUIT_EVENT_TYPE = QEvent.Type(QEvent.registerEventType()) # http://sparkle-project.org/documentation/customization/ def __init__(self, window): try: objc.loadBundle( 'Sparkle', globals(), join(dirname(sys.executable), os.pardir, 'Frameworks', 'Sparkle.framework')) self.updater = SUUpdater.sharedUpdater() except: # can't load framework - not frozen or not included in app bundle? self.updater = None def checkForUpdates(self): if self.updater: self.updater.checkForUpdates_(None) def close(self): self.updater = None
class StateChangedEvent(QEvent): """ Represents a change in the internal state of a :class:`Future`. """ StateChanged = QEvent.registerEventType() def __init__(self, state): QEvent.__init__(self, StateChangedEvent.StateChanged) self._state = state def state(self): """ Return the new state (Future.Pending, Future.Cancelled, ...). """ return self._state
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)
class QueuedCallEvent(QEvent): QueuedCall = QEvent.registerEventType() def __init__(self, function, args, kwargs): QEvent.__init__(self, QueuedCallEvent.QueuedCall) self.function = function self.args = args self.kwargs = kwargs self._result = None self._exc_info = None self._state = 0 def call(self): try: self._result = self.function(*self.args, **self.kwargs) self._state = 1 except Exception, ex: self._exc_info = (type(ex), ex.args, None) raise
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)
class QueuedCallEvent(QEvent): QueuedCall = QEvent.registerEventType() def __init__(self, function, args, kwargs, semaphore=None): QEvent.__init__(self, QueuedCallEvent.QueuedCall) self.function = function self.args = args self.kwargs = kwargs self.semaphore = semaphore self._result = None self._exc_info = None self._state = 0 def call(self): try: self._result = self.function(*self.args, **self.kwargs) self._state = 1 if self.semaphore is not None: self.semaphore.release() except BaseException, ex: self._exc_info = (type(ex), ex.args, None) if self.semaphore is not None: self.semaphore.release() raise
def __init__(self, navdb): super(Gui, self).__init__([]) self.acdata = ACDataEvent() self.navdb = navdb self.radarwidget = [] self.command_history = [] self.cmdargs = [] self.history_pos = 0 self.command_mem = '' self.command_line = '' self.prev_cmdline = '' self.simevent_target = 0 self.mousepos = (0, 0) self.prevmousepos = (0, 0) self.panzoomchanged = False # Register our custom pan/zoom event for etype in [PanZoomEventType, ACDataEventType, SimInfoEventType, StackTextEventType, ShowDialogEventType, DisplayFlagEventType, RouteDataEventType, DisplayShapeEventType]: reg_etype = QEvent.registerEventType(etype) if reg_etype != etype: print('Warning: Registered event type differs from requested type id (%d != %d)' % (reg_etype, etype)) self.splash = Splash() self.splash.show() self.splash.showMessage('Constructing main window') self.processEvents() # Install error message handler handler = QErrorMessage.qtHandler() handler.setWindowFlags(Qt.WindowStaysOnTopHint) # Check and set OpenGL capabilities if not QGLFormat.hasOpenGL(): raise RuntimeError('No OpenGL support detected for this system!') else: f = QGLFormat() f.setVersion(3, 3) f.setProfile(QGLFormat.CoreProfile) f.setDoubleBuffer(True) QGLFormat.setDefaultFormat(f) print('QGLWidget initialized for OpenGL version %d.%d' % (f.majorVersion(), f.minorVersion())) # Create the main window and related widgets self.radarwidget = RadarWidget(navdb) self.win = MainWindow(self, self.radarwidget) self.nd = ND(shareWidget=self.radarwidget) # Enable HiDPI support (Qt5 only) if QT_VERSION == 5: self.setAttribute(Qt.AA_UseHighDpiPixmaps) timer = QTimer(self) timer.timeout.connect(self.radarwidget.updateGL) timer.timeout.connect(self.nd.updateGL) timer.start(50) # Load geo data if False: pb = QProgressDialog('Binary buffer file not found, or file out of date: Constructing vertex buffers from geo data.', 'Cancel', 0, 100) pb.setWindowFlags(Qt.WindowStaysOnTopHint) pb.show() for i in range(101): pb.setValue(i) self.processEvents() QThread.msleep(100) pb.close()
def __init__(self, initstate): QEvent.__init__(self, WidgetManager.WidgetInitEvent.DelayedInit) self._initstate = initstate
def __init__(self, nb): QEvent.__init__(self, self.event_type) self.nb = nb
class AsyncUpdateLoop(QObject): """ Run/drive an coroutine from the event loop. This is a utility class which can be used for implementing asynchronous update loops. I.e. coroutines which periodically yield control back to the Qt event loop. """ Next = QEvent.registerEventType() #: State flags Idle, Running, Cancelled, Finished = 0, 1, 2, 3 #: The coroutine has yielded control to the caller (with `object`) yielded = Signal(object) #: The coroutine has finished/exited (either with an exception #: or with a return statement) finished = Signal() #: The coroutine has returned (normal return statement / StopIteration) returned = Signal(object) #: The coroutine has exited with with an exception. raised = Signal(object) #: The coroutine was cancelled/closed. cancelled = Signal() def __init__(self, parent=None, **kwargs): super().__init__(parent, **kwargs) self.__coroutine = None self.__next_pending = False # Flag for compressing scheduled events self.__in_next = False self.__state = AsyncUpdateLoop.Idle @Slot(object) def setCoroutine(self, loop): """ Set the coroutine. The coroutine will be resumed (repeatedly) from the event queue. If there is an existing coroutine set it is first closed/cancelled. Raises an RuntimeError if the current coroutine is running. """ if self.__coroutine is not None: self.__coroutine.close() self.__coroutine = None self.__state = AsyncUpdateLoop.Cancelled self.cancelled.emit() self.finished.emit() if loop is not None: self.__coroutine = loop self.__state = AsyncUpdateLoop.Running self.__schedule_next() @Slot() def cancel(self): """ Cancel/close the current coroutine. Raises an RuntimeError if the current coroutine is running. """ self.setCoroutine(None) def state(self): """ Return the current state. """ return self.__state def isRunning(self): return self.__state == AsyncUpdateLoop.Running def __schedule_next(self): if not self.__next_pending: self.__next_pending = True QtCore.QTimer.singleShot(10, self.__on_timeout) def __next(self): if self.__coroutine is not None: try: rval = next(self.__coroutine) except StopIteration as stop: self.__state = AsyncUpdateLoop.Finished self.returned.emit(stop.value) self.finished.emit() self.__coroutine = None except BaseException as er: self.__state = AsyncUpdateLoop.Finished self.raised.emit(er) self.finished.emit() self.__coroutine = None else: self.yielded.emit(rval) self.__schedule_next() @Slot() def __on_timeout(self): assert self.__next_pending self.__next_pending = False if not self.__in_next: self.__in_next = True try: self.__next() finally: self.__in_next = False else: # warn self.__schedule_next() def customEvent(self, event): if event.type() == AsyncUpdateLoop.Next: self.__on_timeout() else: super().customEvent(event)
def __init__(self): QEvent.__init__(self, QEvent.User)
def __init__(self, fn, *args, **kwargs): QEvent.__init__(self, InvokeEvent.EVENT_TYPE) self.fn = fn self.args = args self.kwargs = kwargs
def _invalidate_preview(self): if not self.__update_pending: self.__update_pending = True QApplication.postEvent(self, QEvent(QEvent.User))
def __init__(self, func, *args, **kwargs): QEvent.__init__(self, QEvent.User) self.func = func self.args = args self.kwargs = kwargs
def __init__(self, config): QEvent.__init__(self, 11003) self.config = config
def __init__(self, cur_img, nb_pts): QEvent.__init__(self, QEvent.User) self.currentImage = cur_img self.nbPoints = nb_pts
def __init__(self, func, *args): QEvent.__init__(self, self.EventType) if len(args) > 0: self.thunk = partial(func, *args) else: self.thunk = func
def __init__(self, cur_pt): QEvent.__init__(self, QEvent.User) self.currentPoint = cur_pt
def __init__(self): QEvent.__init__(self, ExecuteCallEvent.ExecuteCall)
def __init__(self, state): QEvent.__init__(self, StateChangedEvent.StateChanged) self._state = state
def scheduleDelayedActivate(self): if self.isEnabled() and not self.__layoutPending: self.__layoutPending = True QApplication.postEvent(self, QEvent(QEvent.LayoutRequest))
def _invalidate(self): if not self._invalidated: self._invalidated = True QApplication.postEvent(self, QEvent(QEvent.User))
def __init__(self): QEvent.__init__(self, FinishImageGrowthEvent.event_type)
def __init__(self, msg): QEvent.__init__(self, QEvent.User) self.msg = msg self.src = msg.src self._type = msg.type
def ripper_event(self, e): """ """ event = QEvent(event_type(e.type)) event.data = e.__dict__ QApplication.instance().postEvent(self, event)
def __init__(self, etype): QEvent.__init__(self, etype)
def __init__(cls, name, bases, dct): super(EventMeta, cls).__init__(name, bases, dct) cls.id = QEvent.registerEventType() if name != 'EventBase' else None
def _update(self): """ Schedule processing at a later time. """ QCoreApplication.postEvent(self, QEvent(QEvent.UpdateRequest))
def __init__(self, reason): QEvent.__init__(self, self.event_type) self.reason = reason
def __init__(self, _, event): QEvent.__init__(self, _) self.event = event
def __init__(self): QEvent.__init__(self, self.event_type)
def __init__(self): QEvent.__init__(self, self.ActivateParent)
def __init__(self): QEvent.__init__(self, AbortImageGrowthEvent.event_type)