def mouseReleaseEvent(self, ev):
        """Handle mouse release events for kinetic dragging end/auto mode."""
        if self._dragging:
            self._dragging = False
            self.unsetCursor()
            if self._kineticScrollingEnabled:
                # kinetic scrolling
                if self._kineticData.ignoreEvent(ev):
                    return
                
                if self._kineticData._state == KineticData.Pressed:
                    self._kineticData._state = KineticData.Steady
                    event1 = QMouseEvent(QEvent.MouseButtonPress,
                                         self._kineticData._pressPos, Qt.LeftButton,
                                         Qt.LeftButton, Qt.NoModifier)
                    event2 = QMouseEvent(ev)
                    self._kineticData._ignored.append(event1)
                    self._kineticData._ignored.append(event2)
                    QApplication.postEvent(self, event1)
                    QApplication.postEvent(self, event2)
                    
                elif self._kineticData._state == KineticData.ManualScroll:
                    self._kineticData._state = KineticData.AutoScroll
    
                elif self._kineticData._state == KineticData.AutoScroll:
                    self._kineticData._state = KineticData.Stop
                    self._kineticData._speed = QPoint(0, 0)
                    
                elif self._kineticData._state == KineticData.Stop:
                    self._kineticData._state = KineticData.Steady

        if self._kineticData._state == KineticData.Steady:
            self.cursorNeedUpdate.emit(ev.globalPos())
        
        super(KineticScrollArea, self).mouseReleaseEvent(ev)
Example #2
0
 def run(self):
     """ Spawns child process and passes a WorkerEvent to the main event loop when finished """
     try:
         output_file = str(self.path)
     except UnicodeEncodeError:
         output_file = self.path.encode(
             'utf-8')  # assume uft8 encoding for shell - see worker
     # oflag=excl -> fail if the output file already exists
     cmd = [
         'dd', 'if=/dev/random', 'of=' + output_file, 'bs=1', 'count=1024',
         'conv=excl'
     ]
     with open(os.devnull) as DEVNULL:
         self.process = subprocess.Popen(cmd,
                                         stderr=subprocess.PIPE,
                                         stdout=DEVNULL,
                                         universal_newlines=True,
                                         close_fds=True)
         __, errors = self.process.communicate()
     if self.process.returncode != 0:
         QApplication.postEvent(
             self.parent.parent(),
             WorkerEvent(
                 callback=lambda msg: self.parent.display_create_failed(
                     msg, stop_timer=True),
                 response=_('Error while creating key file:\n{error}'
                            ).format(error=errors)))
     else:
         QApplication.postEvent(
             self.parent.parent(),
             WorkerEvent(
                 callback=lambda msg: self.parent.on_keyfile_created(msg),
                 response=self.path))
     return
Example #3
0
 def _set_settings(self, settings):
     old_settings = self.__dict__.get('settings', None)
     if settings == old_settings:
         return
     self.__dict__['settings'] = settings
     if self.thread.isRunning():
         QApplication.postEvent(self, RFBConfigureClientEvent())
Example #4
0
 def execute(self, command, success_callback, error_callback):
     """ Writes command to workers stdin and sets callbacks for listener thread
         :param command: The function to be done by the worker is in command[`msg`] the arguments are passed as named properties command[`device_name`] etc.
         :type command: dict
         :param success_callback: The function to be called if the worker finished successfully
         :type success_callback: function
         :param error_callback: The function to be called if the worker returns an error
         :type error_callback: function
     """
     try:
         assert ('type' in command
                 and 'msg' in command)  # valid command obj?
         assert (
             self.success_callback is None and self.error_callback is None
         )  # channel clear? (no qeue neccessary for the backend process)
         self.success_callback = success_callback
         self.error_callback = error_callback
         self.worker.stdin.write(json.dumps(command) + '\n')
         self.worker.stdin.flush()
     except (IOError, AssertionError) as communication_error:
         QApplication.postEvent(
             self.parent,
             WorkerEvent(
                 callback=lambda msg: show_alert(
                     self.parent, msg, critical=True),
                 response=_('Error in communication:\n{error}').format(
                     error=format_exception(communication_error))))
Example #5
0
 def _on_hint_mouse_event(self, evt):
     """Post a new mouse event from a hintmanager."""
     # FIXME:qtwebengine Will this implementation work for QtWebEngine?
     #                   We probably need to send the event to the
     #                   focusProxy()?
     log.modes.debug("Hint triggered, focusing {!r}".format(self))
     self._widget.setFocus()
     QApplication.postEvent(self._widget, evt)
Example #6
0
 def ThreadBackTest(self):
     try:
         self.OnBackTest(self.analys.symbol_list, self.analys.trading_day_list, self.analys.trade_fees)
     except Exception as e:
         traceback.print_exc() #
         QApplication.postEvent(self.analysis_panel, QEvent(define.DEF_EVENT_SET_ANALYSIS_PROGRESS_ERROR))
         self.log_text = "回测 %s %s 计算发生异常!%s" % (self.analysis, self.analysis_name, e)
         self.logger.SendMessage("E", 4, self.log_cate, self.log_text, "S")
Example #7
0
    def run(self):
        while True:
            ac = async_call_queue.get()

            if ac == None:
                break

            if ac.function == None:
                continue

            with async_session_lock:
                if ac.session_id != async_session_id:
                    continue

            result = None

            try:
                retry_on_exception = ac.retry_on_exception

                for _ in range(2):
                    try:
                        if ac.arguments == None:
                            result = ac.function()
                        elif isinstance(ac.arguments, tuple):
                            result = ac.function(*ac.arguments)
                        else:
                            result = ac.function(ac.arguments)
                    except:
                        if not retry_on_exception:
                            raise

                        retry_on_exception = False
                        continue

                    break
            except Exception as e:
                with async_session_lock:
                    if ac.session_id != async_session_id:
                        continue

                if ac.debug_exception:
                    logging.exception('Error while doing async call')

                if ac.error_callback != None:
                    async_event_queue.put((ac, False, e))

                    QApplication.postEvent(self, QEvent(ASYNC_EVENT))

                continue

            if ac.result_callback != None:
                with async_session_lock:
                    if ac.session_id != async_session_id:
                        continue

                async_event_queue.put((ac, True, result))

                QApplication.postEvent(self, QEvent(ASYNC_EVENT))
Example #8
0
    def run(self):
        while True:
            ac = async_call_queue.get()

            if ac == None:
                break

            if ac.function == None:
                continue

            with async_session_lock:
                if ac.session_id != async_session_id:
                    continue

            result = None

            try:
                retry_on_exception = ac.retry_on_exception

                for _ in range(2):
                    try:
                        if ac.arguments == None:
                            result = ac.function()
                        elif isinstance(ac.arguments, tuple):
                            result = ac.function(*ac.arguments)
                        else:
                            result = ac.function(ac.arguments)
                    except:
                        if not retry_on_exception:
                            raise

                        retry_on_exception = False
                        continue

                    break
            except Exception as e:
                with async_session_lock:
                    if ac.session_id != async_session_id:
                        continue

                if ac.debug_exception:
                    logging.exception('Error while doing async call')

                if ac.error_callback != None:
                    async_event_queue.put((ac, False, e))

                    QApplication.postEvent(self, QEvent(ASYNC_EVENT))

                continue

            if ac.result_callback != None:
                with async_session_lock:
                    if ac.session_id != async_session_id:
                        continue

                async_event_queue.put((ac, True, result))

                QApplication.postEvent(self, QEvent(ASYNC_EVENT))
Example #9
0
    def hideShipList(self):
        self.__ratio = self.RATIO_WITHOUT_SHIPLIST
        self.__scene.removeItem(self.__shipListItem)
        for _, ship in self.__shipList.items():
            self.__scene.removeItem(ship.shipItem)

        self.__adjustedToSize = None
        resize = QResizeEvent(self.size(), self.size())
        QApplication.postEvent(self, resize)
Example #10
0
    def onRemoveClicked(self):
        if not self._listWidget.currentItem():
            return

        item = self._listWidget.currentItem()
        #print(item.text())
        self._listWidget.takeItem(self._listWidget.row(item))
        QApplication.postEvent(
            self, QKeyEvent(QEvent.KeyPress, Qt.Key_Enter, Qt.NoModifier))
Example #11
0
 def mouseReleaseEvent(self, event):
     p1 = event.pos()
     p2 = self.mapToScene(p1)
     p3 = self.chart().mapFromScene(p2)
     p4 = self.chart().mapToValue(p3)
     if self.chart():
         for serie in self.chart().series():
             QApplication.postEvent(serie, ReleasePosEvent(p4))
     QChartView.mouseReleaseEvent(self, event)
Example #12
0
 def OnQuoteFuture(self, msg): # 行情触发
     try:
         str_code = msg.data[0].decode()
         if str_code == self.contract:
             self.quote_data = msg.data
             QApplication.postEvent(self, QEvent(define.DEF_EVENT_TRADER_FUE_CTP_UPDATE_QUOTE)) # postEvent异步,sendEvent同步
     except Exception as e:
         self.log_text = "%s:函数 OnQuoteFuture 异常!%s" % (self.strategy, e)
         self.logger.SendMessage("E", 4, self.log_cate, self.log_text, "M")
Example #13
0
 def mouseReleaseEvent(self, ev):
     """End a self-initiated drag; if the right button was used; send a context menu event."""
     if self._dragging and ev.button() == self._dragbutton:
         self.stopDrag()
     if ev.button() == Qt.RightButton:
         QApplication.postEvent(
             self.parent(),
             QContextMenuEvent(QContextMenuEvent.Mouse,
                               ev.pos() + self.pos()))
Example #14
0
 def clickHandler(self, ch):
     # Getting current focus
     recipient = self.webView.focusProxy()
     modifiers = QtCore.Qt.NoModifier
     qt_key = getattr(QtCore.Qt, ch)
     self.event = QKeyEvent(QEvent.KeyPress, qt_key, modifiers,
                            QKeySequence(qt_key).toString())
     QApplication.postEvent(recipient, self.event)
     # Reset timer when operate with keyboard
     self.resetTimer(self.timer_scr_set, self.scr_set_delay)
Example #15
0
    def sendKey(self,key):
        recipient = self.browser.focusProxy()
        if( self.curKey is not None and key!=self.curKey):
            event_key_up = QKeyEvent(QEvent.KeyRelease, self.curKey, Qt.NoModifier)
            QApplication.postEvent(recipient, event_key_up)

        event_key_press = QKeyEvent(QEvent.KeyPress, key, Qt.NoModifier)
        QApplication.postEvent(recipient, event_key_press)
        if(key != Qt.Key_Up):
            self.curKey = key
Example #16
0
 def _key_press(self, key, count=1):
     # FIXME:qtwebengine Abort scrolling if the minimum/maximum was reached.
     press_evt = QKeyEvent(QEvent.KeyPress, key, Qt.NoModifier, 0, 0, 0)
     release_evt = QKeyEvent(QEvent.KeyRelease, key, Qt.NoModifier, 0, 0, 0)
     recipient = self._widget.focusProxy()
     for _ in range(count):
         # If we get a segfault here, we might want to try sendEvent
         # instead.
         QApplication.postEvent(recipient, press_evt)
         QApplication.postEvent(recipient, release_evt)
Example #17
0
    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Tab or e.key() == Qt.Key_Backtab:
            e.accept()
            ev = QKeyEvent(QEvent.KeyPress, e.key(), e.modifiers(), e.text(),
                           e.isAutoRepeat(), e.count())
            QApplication.postEvent(self.parent().parent(), ev)

            return

        QListView.keyPressEvent(self, e)
Example #18
0
    def clearHover(self):
        """Post a mouse move event to clear the mouse hover indication.

        Needed to avoid crash when deleting nodes with hovered child nodes.
        """
        event = QMouseEvent(QEvent.MouseMove,
                            QPointF(0.0, self.viewport().width()),
                            Qt.NoButton, Qt.NoButton, Qt.NoModifier)
        QApplication.postEvent(self.viewport(), event)
        QApplication.processEvents()
Example #19
0
    def test_detector_create_delete_gui(self, qtbot):
        detector_name = 'test_detector'
        w = Rase([])
        qtbot.addWidget(w)
        w.show()
        qtbot.waitForWindowShown(w)

        def add_detector():
            qtbot.keyClicks(w.d_dialog.txtDetector, detector_name)
            qtbot.mouseClick(w.d_dialog.buttonBox.button(QDialogButtonBox.Ok),
                             Qt.LeftButton)

        QTimer.singleShot(100, add_detector)
        qtbot.mouseClick(w.btnAddDetector, Qt.LeftButton)

        helper = Helper()

        def handle_timeout():
            menu = None
            for tl in QApplication.topLevelWidgets():
                if isinstance(tl,
                              QMenu) and len(tl.actions()) > 0 and tl.actions(
                              )[0].text() == "Delete Instrument":
                    menu = tl
                    break

            assert menu is not None
            delete_action = None

            for action in menu.actions():
                if action.text() == 'Delete Instrument':
                    delete_action = action
                    break
            assert delete_action is not None
            rect = menu.actionGeometry(delete_action)
            QTimer.singleShot(100, helper.finished.emit)
            qtbot.mouseClick(menu, Qt.LeftButton, pos=rect.center())

        with qtbot.waitSignal(helper.finished, timeout=5 * 1000):
            QTimer.singleShot(1000, handle_timeout)
            item = None
            for row in range(w.tblDetectorReplay.rowCount()):
                if w.tblDetectorReplay.item(row, 0).text() == detector_name:
                    item = w.tblDetectorReplay.item(row, 0)
                    break
            assert item is not None
            rect = w.tblDetectorReplay.visualItemRect(item)
            event = QContextMenuEvent(QContextMenuEvent.Mouse, rect.center())
            QApplication.postEvent(w.tblDetectorReplay.viewport(), event)

        # make sure the detector is not in the database or the instrument table
        assert w.tblDetectorReplay.rowCount() == 0
        session = Session()
        assert not session.query(Detector).filter_by(
            name=detector_name).first()
Example #20
0
 def _post_mouse_event(self, type, button, x, y):
     q_button = {
         # TODO perhaps add right button here
         "left": Qt.LeftButton,
         "nobutton": Qt.NoButton,
     }.get(button)
     point = QPointF(x, y)
     buttons = QApplication.mouseButtons()
     modifiers = QApplication.keyboardModifiers()
     event = QMouseEvent(type, point, q_button, buttons, modifiers)
     QApplication.postEvent(self.web_page, event)
Example #21
0
 def rightClick(self, pos):
     """Called when the right mouse button is released.
     
     (Use this instead of the contextMenuEvent as that one also
     fires when starting a right-button selection.)
     The default implementation emits the rightClicked(pos) signal and also
     sends a ContextMenu event to the View widget.
     
     """
     self.rightClicked.emit(pos)
     QApplication.postEvent(self.view().viewport(), QContextMenuEvent(QContextMenuEvent.Mouse, pos + self.pos()))
Example #22
0
 def _post_mouse_event(self, type, button, x, y):
     q_button = {
         # TODO perhaps add right button here
         "left": Qt.LeftButton,
         "nobutton": Qt.NoButton,
     }.get(button)
     point = QPointF(x, y)
     buttons = QApplication.mouseButtons()
     modifiers = QApplication.keyboardModifiers()
     event = QMouseEvent(type, point, q_button, buttons, modifiers)
     QApplication.postEvent(self.web_page, event)
Example #23
0
    def onAddClicked(self):
        text = self._newItem.text().strip()
        if not len(text): return
        items = self._listWidget.findItems(text, Qt.MatchExactly)
        if (len(items) > 0):
            print('already exists actor name!')
            return

        self._listWidget.addItem(text)
        self._newItem.clear()
        QApplication.postEvent(
            self, QKeyEvent(QEvent.KeyPress, Qt.Key_Enter, Qt.NoModifier))
Example #24
0
 def getFrameAndDrive_bkp(self):
     image = self.getBrowserScreenshot()
     action=get_action_for_image(image, self.model)
     key=get_key_for_action(action)
     print(action+" --> "+str(key))
     event_key_press = QKeyEvent(QEvent.KeyPress, key, Qt.NoModifier)
     event_key_up = QKeyEvent(QEvent.KeyRelease, key, Qt.NoModifier)
     recipient = self.browser.focusProxy()
     QApplication.postEvent(recipient, event_key_press)
     #time.sleep(0.0025)
     QApplication.postEvent(recipient, event_key_up)
     return
Example #25
0
    def send_event(self, evt, *, postpone=False):
        """Send the given event to the underlying widget.

        Args:
            postpone: Postpone the event to be handled later instead of
                      immediately. Using this might cause crashes in Qt.
        """
        recipient = self._event_target()
        if postpone:
            QApplication.postEvent(recipient, evt)
        else:
            QApplication.sendEvent(recipient, evt)
Example #26
0
    def send_event(self, evt, *, postpone=False):
        """Send the given event to the underlying widget.

        Args:
            postpone: Postpone the event to be handled later instead of
                      immediately. Using this might cause crashes in Qt.
        """
        recipient = self._event_target()
        if postpone:
            QApplication.postEvent(recipient, evt)
        else:
            QApplication.sendEvent(recipient, evt)
Example #27
0
 def rightClick(self, pos):
     """Called when the right mouse button is released.
     
     (Use this instead of the contextMenuEvent as that one also
     fires when starting a right-button selection.)
     The default implementation emits the rightClicked(pos) signal and also
     sends a ContextMenu event to the View widget.
     
     """
     self.rightClicked.emit(pos)
     QApplication.postEvent(
         self.view().viewport(),
         QContextMenuEvent(QContextMenuEvent.Mouse, pos + self.pos()))
Example #28
0
    def send_event(self, evt):
        """Send the given event to the underlying widget.

        The event will be sent via QApplication.postEvent.
        Note that a posted event may not be re-used in any way!
        """
        # This only gives us some mild protection against re-using events, but
        # it's certainly better than a segfault.
        if getattr(evt, 'posted', False):
            raise AssertionError("Can't re-use an event which was already "
                                 "posted!")
        recipient = self.event_target()
        evt.posted = True
        QApplication.postEvent(recipient, evt)
Example #29
0
    def run(self):
        """ Listens on workers stdout and executes callbacks when answers arrive """
        while True:
            try:
                buf = self.worker.stdout.readline()  # blocks
                if buf:  # check if worker output pipe closed
                    response = json.loads(buf.strip(), encoding='utf-8')
                else:
                    return
                assert('type' in response and 'msg' in response)
                assert(self.success_callback is not None and self.error_callback is not None)  # there should be somebody waiting for an answer!
                # valid response received
                if response['type'] == 'error':
                    QApplication.postEvent(self.parent, WorkerEvent(self.error_callback, response['msg']))
                else:
                    QApplication.postEvent(self.parent, WorkerEvent(self.success_callback, response['msg']))
                # reset callbacks
                self.success_callback, self.error_callback = None, None

            except ValueError:
                # worker didn't return json -> probably crashed, show everything printed to stdout
                buf += self.worker.stdout.read()
                QApplication.postEvent(self.parent, WorkerEvent(callback=lambda msg: show_alert(self.parent, msg, critical=True),
                                                                response=_('Error in communication:\n{error}').format(error=_(buf))))
                return

            except (IOError, AssertionError) as communication_error:
                QApplication.postEvent(self.parent, WorkerEvent(callback=lambda msg: show_alert(self.parent, msg, critical=True),
                                                                response=_('Error in communication:\n{error}').format(error=format_exception(communication_error))))
                return
Example #30
0
    def eventFilter(self, viewport, ev):
        """Act on events in the viewport:

        * keep on the same place when the viewport resizes
        * start dragging the selection if showbutton clicked (preventing the
          contextmenu if the showbutton is the right button)
        * end a drag on mousebutton release, if that button would have shown
          the context menu, show it on button release.

        """
        if ev.type() == QEvent.Resize and self.isVisible():
            view = self.parent().parent()
            if not view.viewMode():
                # fixed scale, try to keep ourselves in the same position on resize
                self.move(self._getLayoutOffset())
        elif (self.showbutton == Qt.RightButton
              and isinstance(ev, QContextMenuEvent)
              and ev.reason() == QContextMenuEvent.Mouse):
            # suppress context menu event if that would coincide with start selection
            if not self._dragging or (self.geometry()
                                      and self.edge(ev.pos()) == _INSIDE):
                return False
            return True
        elif not self._dragging:
            if ev.type() == QEvent.MouseButtonPress and ev.button(
            ) == self.showbutton:
                if self.isVisible():
                    # this cancels a previous selection if we were visible
                    self._setSelectionFromGeometry(QRect())
                self.setGeometry(QRect(ev.pos(), QSize(0, 0)))
                self._setLayoutOffset(ev.pos())
                self._oldZoom = viewport.parent().zoomFactor()
                self.startDrag(ev.pos(), ev.button())
                self._dragedge = _RIGHT | _BOTTOM
                self.adjustCursor(self._dragedge)
                self.show()
                return True
        elif self._dragging:
            if ev.type() == QEvent.MouseMove:
                self.drag(ev.pos())
                return True
            elif ev.type() == QEvent.MouseButtonRelease and ev.button(
            ) == self._dragbutton:
                self.stopDrag()
                if ev.button() == Qt.RightButton:
                    QApplication.postEvent(
                        viewport,
                        QContextMenuEvent(QContextMenuEvent.Mouse, ev.pos()))
                return True
        return False
Example #31
0
    def send_event(self, evt):
        """Send the given event to the underlying widget.

        The event will be sent via QApplication.postEvent.
        Note that a posted event may not be re-used in any way!
        """
        # This only gives us some mild protection against re-using events, but
        # it's certainly better than a segfault.
        if getattr(evt, 'posted', False):
            raise utils.Unreachable("Can't re-use an event which was already "
                                    "posted!")
        recipient = self.event_target()
        evt.posted = True
        QApplication.postEvent(recipient, evt)
    def test_spectrum(self):
        port = self.get_free_port()
        spectrum_dialog = self.__get_spectrum_dialog()
        spectrum_dialog.device.set_server_port(port)
        spectrum_dialog.ui.btnStart.click()
        self.assertEqual(len(spectrum_dialog.scene_manager.peak), 0)

        data = np.array([complex(
            1, 1), complex(2, 2), complex(3, 3)],
                        dtype=np.complex64)

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        sock.connect(("127.0.0.1", port))
        sock.sendall(data.tostring())
        sock.shutdown(socket.SHUT_RDWR)
        sock.close()

        QApplication.instance().processEvents()
        QTest.qWait(5 * self.SEND_RECV_TIMEOUT)

        self.assertGreater(len(spectrum_dialog.scene_manager.peak), 0)
        self.assertIsNone(
            spectrum_dialog.ui.graphicsViewFFT.scene().frequency_marker)
        w = spectrum_dialog.ui.graphicsViewFFT.viewport()

        # this actually gets the click to the view
        # QTest.mouseMove(w, QPoint(80,80))
        event = QMouseEvent(QEvent.MouseMove, QPoint(80, 80),
                            w.mapToGlobal(QPoint(80, 80)), Qt.LeftButton,
                            Qt.LeftButton, Qt.NoModifier)
        QApplication.postEvent(w, event)
        QApplication.instance().processEvents()
        QTest.qWait(500)
        QApplication.instance().processEvents()

        self.assertIsNotNone(
            spectrum_dialog.ui.graphicsViewFFT.scene().frequency_marker)

        spectrum_dialog.ui.btnStop.click()

        self.assertGreater(
            len(spectrum_dialog.ui.graphicsViewSpectrogram.items()), 0)
        spectrum_dialog.ui.btnClear.click()
        self.assertEqual(
            len(spectrum_dialog.ui.graphicsViewSpectrogram.items()), 0)

        spectrum_dialog.close()
Example #33
0
 def OnQuoteStock(self, msg):  # 行情触发
     try:
         str_code = msg.data[0].decode()
         if str_code == self.symbol:
             if "60" == str_code[0:2] or "000" == str_code[
                     0:3] or "001" == str_code[0:3] or "002" == str_code[
                         0:3] or "300" == str_code[0:3]:
                 self.quote_data = msg.data
                 QApplication.postEvent(
                     self,
                     QEvent(define.DEF_EVENT_TRADER_STK_APE_UPDATE_QUOTE
                            ))  # postEvent异步,sendEvent同步
     except Exception as e:
         self.log_text = "%s:函数 OnQuoteStock 异常!%s" % (self.strategy, e)
         self.logger.SendMessage("E", 4, self.log_cate, self.log_text, "M")
Example #34
0
def qt_send_text(text, target, key_type=0):
    """
    Send text as key input event to target qt object, as if generated by
    `key_type`. Key type defaults to 0, meaning "the event is not a result of a
    known key; for example, it may be the result of a compose sequence or
    keyboard macro."
    """
    modifiers = QApplication.keyboardModifiers()
    text = list(text) or ['']
    for x in text:
        event = QKeyEvent(QEvent.KeyPress, key_type, modifiers, x)
        QApplication.postEvent(target, event)
        # Key release does not generate any input
        event = QKeyEvent(QEvent.KeyRelease, key_type, modifiers, '')
        QApplication.postEvent(target, event)
Example #35
0
def qt_send_text(text, target, key_type=0):
    """
    Send text as key input event to target qt object, as if generated by
    `key_type`. Key type defaults to 0, meaning "the event is not a result of a
    known key; for example, it may be the result of a compose sequence or
    keyboard macro."
    """
    modifiers = QApplication.keyboardModifiers()
    text = list(text) or ['']
    for x in text:
        event = QKeyEvent(QEvent.KeyPress, key_type, modifiers, x)
        QApplication.postEvent(target, event)
        # Key release does not generate any input
        event = QKeyEvent(QEvent.KeyRelease, key_type, modifiers, '')
        QApplication.postEvent(target, event)
Example #36
0
 def keyPressEvent(self, event):
     # https://doc.qt.io/qt-5/qt.html#Key-enum
     if event.key() == Qt.Key_Tab:
         event.ignore()
         event.accept = True
         for x in range(0, 4):
             newevent = QKeyEvent(QEvent.KeyPress,
                                  Qt.Key_Space,
                                  Qt.NoModifier,
                                  text=" ",
                                  autorep=False,
                                  count=1)
             QApplication.postEvent(self, newevent)
     else:
         super(TextEdit, self).keyPressEvent(event)
         event.accept = True
     self.setFocus()
Example #37
0
    def post_to(cls, receiver, func, *args, **kwargs):
        """
        Post a callable to be delivered to a specific
        receiver as a CallbackEvent.

        It is the responsibility of this receiver to
        handle the event and choose to call the callback.
        """
        # We can create a weak proxy reference to the
        # callback so that if the object associated with
        # a bound method is deleted, it won't call a dead method
        if not isinstance(func, proxy):
            reference = proxy(func, quiet=True)
        else:
            reference = func
        event = cls(reference, *args, **kwargs)

        # post the event to the given receiver
        QApplication.postEvent(receiver, event)
Example #38
0
 def execute(self, command, success_callback, error_callback):
     """ Writes command to workers stdin and sets callbacks for listener thread
         :param command: The function to be done by the worker is in command[`msg`] the arguments are passed as named properties command[`device_name`] etc.
         :type command: dict
         :param success_callback: The function to be called if the worker finished successfully
         :type success_callback: function
         :param error_callback: The function to be called if the worker returns an error
         :type error_callback: function
     """
     try:
         assert('type' in command and 'msg' in command)  # valid command obj?
         assert(self.success_callback is None and self.error_callback is None)  # channel clear? (no qeue neccessary for the backend process)
         self.success_callback = success_callback
         self.error_callback = error_callback
         self.worker.stdin.write(json.dumps(command) + '\n')
         self.worker.stdin.flush()
     except (IOError, AssertionError) as communication_error:
         QApplication.postEvent(self.parent, WorkerEvent(callback=lambda msg: show_alert(self.parent, msg, critical=True),
                                                         response=_('Error in communication:\n{error}').format(error=format_exception(communication_error))))
Example #39
0
    def test_spectrum(self):
        port = self.get_free_port()
        spectrum_dialog = self.__get_spectrum_dialog()
        spectrum_dialog.device.set_server_port(port)
        spectrum_dialog.ui.btnStart.click()
        self.assertEqual(len(spectrum_dialog.scene_manager.peak), 0)

        data = np.array([complex(1, 1), complex(2, 2), complex(3, 3)], dtype=np.complex64)

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        sock.connect(("127.0.0.1", port))
        sock.sendall(data.tostring())
        sock.shutdown(socket.SHUT_RDWR)
        sock.close()

        QApplication.instance().processEvents()
        QTest.qWait(5*self.SEND_RECV_TIMEOUT)

        self.assertGreater(len(spectrum_dialog.scene_manager.peak), 0)
        self.assertIsNone(spectrum_dialog.ui.graphicsViewFFT.scene().frequency_marker)
        w = spectrum_dialog.ui.graphicsViewFFT.viewport()

        # this actually gets the click to the view
        # QTest.mouseMove(w, QPoint(80,80))
        event = QMouseEvent(QEvent.MouseMove, QPoint(80, 80), w.mapToGlobal(QPoint(80, 80)), Qt.LeftButton,
                            Qt.LeftButton, Qt.NoModifier)
        QApplication.postEvent(w, event)
        QApplication.instance().processEvents()
        QTest.qWait(500)
        QApplication.instance().processEvents()

        self.assertIsNotNone(spectrum_dialog.ui.graphicsViewFFT.scene().frequency_marker)

        spectrum_dialog.ui.btnStop.click()

        self.assertGreater(len(spectrum_dialog.ui.graphicsViewSpectrogram.items()), 0)
        spectrum_dialog.ui.btnClear.click()
        self.assertEqual(len(spectrum_dialog.ui.graphicsViewSpectrogram.items()), 0)

        spectrum_dialog.close()
Example #40
0
    def select(self, start: int, end: int, bufferIdx=0, scrollIntoView=False):
        #TODO ensure that start, end are in valid range
        self.selStart = self.clipPosition(bufferIdx, start)
        self.selEnd = self.clipPosition(bufferIdx, end)
        self.selBuffer = bufferIdx
        if scrollIntoView:
            self.scrollIntoView(self.selEnd)
            self.scrollIntoView(self.selStart)

        self.redrawSelection()
        print("selection changed", self.selStart, self.selEnd, self.lastHit)
        r = self.selRange()
        self.fiTreeWidget.hilightFormatInfoTree(r)
        GlobalEvents.on_select_bytes.emit(self.buffers[bufferIdx], r)
        QApplication.postEvent(
            self,
            QStatusTipEvent(
                "Selection %d-%d (%d bytes)   0x%X - 0x%X (0x%X bytes)" %
                (self.selStart, self.selEnd, self.selLength(), self.selStart,
                 self.selEnd, self.selLength())))
Example #41
0
 def run(self):
     """ Spawns child process and passes a WorkerEvent to the main event loop when finished """
     try:
         output_file = str(self.path)
     except UnicodeEncodeError:
         output_file = self.path.encode('utf-8')  # assume uft8 encoding for shell - see worker
     # oflag=excl -> fail if the output file already exists
     cmd = ['dd', 'if=/dev/random', 'of=' + output_file, 'bs=1', 'count=1024', 'conv=excl']
     with open(os.devnull) as DEVNULL:
         self.process = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=DEVNULL, universal_newlines=True, close_fds=True)
         __, errors = self.process.communicate()
     if self.process.returncode != 0:
         QApplication.postEvent(self.parent.parent(),
                                WorkerEvent(callback=lambda msg: self.parent.display_create_failed(msg, stop_timer=True),
                                            response=_('Error while creating key file:\n{error}').format(error=errors))
                                )
     else:
         QApplication.postEvent(self.parent.parent(), WorkerEvent(callback=lambda msg: self.parent.on_keyfile_created(msg),
                                                                  response=self.path))
     return
Example #42
0
    def send_event(self, evt: QEvent) -> None:
        """Send the given event to the underlying widget.

        The event will be sent via QApplication.postEvent.
        Note that a posted event must not be re-used in any way!
        """
        # This only gives us some mild protection against re-using events, but
        # it's certainly better than a segfault.
        if getattr(evt, 'posted', False):
            raise utils.Unreachable("Can't re-use an event which was already "
                                    "posted!")

        recipient = self.private_api.event_target()
        if recipient is None:
            # https://github.com/qutebrowser/qutebrowser/issues/3888
            log.webview.warning("Unable to find event target!")
            return

        evt.posted = True
        QApplication.postEvent(recipient, evt)
Example #43
0
    def send_event(self, evt: QEvent) -> None:
        """Send the given event to the underlying widget.

        The event will be sent via QApplication.postEvent.
        Note that a posted event must not be re-used in any way!
        """
        # This only gives us some mild protection against re-using events, but
        # it's certainly better than a segfault.
        if getattr(evt, 'posted', False):
            raise utils.Unreachable("Can't re-use an event which was already "
                                    "posted!")

        recipient = self.private_api.event_target()
        if recipient is None:
            # https://github.com/qutebrowser/qutebrowser/issues/3888
            log.webview.warning("Unable to find event target!")
            return

        evt.posted = True  # type: ignore[attr-defined]
        QApplication.postEvent(recipient, evt)
Example #44
0
 def SendMessage(self, log_kind, log_class, log_cate, log_info, log_show = ""): # 自身的日志就不保存到数据库了
     if log_kind == "D" or log_kind == "I" or log_kind == "H" or log_kind == "W":
         self.logger.debug("%s %d <%s> - %s" % (log_kind, log_class, log_cate, log_info))
     elif log_kind == "S" or log_kind == "E" or log_kind == "F":
         self.logger.error("%s %d <%s> - %s" % (log_kind, log_class, log_cate, log_info))
     log_item = LogInfo(log_kind, log_class, log_cate, log_info)
     self.AddTbData_Logger(log_item)
     if log_show == define.DEF_LOG_SHOW_TYPE_S and self.log_info_panel_s != None:
         self.log_info_panel_s.AddLogInfo(log_item)
         QApplication.postEvent(self.log_info_panel_s, QEvent(define.DEF_EVENT_LOG_INFO_PRINT))
     elif log_show == define.DEF_LOG_SHOW_TYPE_T and self.log_info_panel_t != None:
         self.log_info_panel_t.AddLogInfo(log_item)
         QApplication.postEvent(self.log_info_panel_t, QEvent(define.DEF_EVENT_LOG_INFO_PRINT))
     elif log_show == define.DEF_LOG_SHOW_TYPE_M and self.log_info_panel_m != None:
         self.log_info_panel_m.AddLogInfo(log_item)
         QApplication.postEvent(self.log_info_panel_m, QEvent(define.DEF_EVENT_LOG_INFO_PRINT))
     elif log_show == define.DEF_LOG_SHOW_TYPE_A and self.log_info_panel_a != None:
         self.log_info_panel_a.AddLogInfo(log_item)
         QApplication.postEvent(self.log_info_panel_a, QEvent(define.DEF_EVENT_LOG_INFO_PRINT))
     elif log_show == define.DEF_LOG_SHOW_TYPE_SPBSA and self.log_info_panel_spbsa != None:
         self.log_info_panel_spbsa.AddLogInfo(log_item)
         QApplication.postEvent(self.log_info_panel_spbsa, QEvent(define.DEF_EVENT_LOG_INFO_PRINT))
Example #45
0
 def post(cls, handlerObject, func, *args):
     e = ThunkEvent( func, *args )
     QApplication.postEvent(handlerObject, e)
Example #46
0
 def on_mouse_event(self, evt):
     """Post a new mouseevent from a hintmanager."""
     log.modes.debug("Hint triggered, focusing {!r}".format(self))
     self.setFocus()
     QApplication.postEvent(self, evt)
Example #47
0
    def on_update(self, status, line_number, step):
        self.current_job_status = status
        self.current_job_line = line_number
        self.current_job_step = step

        QApplication.postEvent(self, JobUpdateEvent())
Example #48
0
    def on_resume(self, job_outcomes=list()):
        print('Received ' + str(len(job_outcomes)) + ' from Jobs thread')

        self.current_job_outcomes = job_outcomes

        QApplication.postEvent(self, JobDoneEvent())
Example #49
0
 def finished_adding_plots(self):
     QApplication.postEvent(self, PlotReadyEvent())
Example #50
0
 def mute_callback(self, mute):
     QApplication.postEvent(self, MuteEvent(mute))
Example #51
0
 def on_mouse_event(self, evt):
     """Post a new mouseevent from a hintmanager."""
     self.setFocus()
     QApplication.postEvent(self, evt)
Example #52
0
 def close_busy_dlg(*args):
     QApplication.postEvent(busy_dlg, QCloseEvent())