当前位置: 首页>>代码示例>>Python>>正文


Python DelayJobRunner.cancel_requests方法代码示例

本文整理汇总了Python中pyqode.core.api.DelayJobRunner.cancel_requests方法的典型用法代码示例。如果您正苦于以下问题:Python DelayJobRunner.cancel_requests方法的具体用法?Python DelayJobRunner.cancel_requests怎么用?Python DelayJobRunner.cancel_requests使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pyqode.core.api.DelayJobRunner的用法示例。


在下文中一共展示了DelayJobRunner.cancel_requests方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: OutlineMode

# 需要导入模块: from pyqode.core.api import DelayJobRunner [as 别名]
# 或者: from pyqode.core.api.DelayJobRunner import cancel_requests [as 别名]
class OutlineMode(Mode, QtCore.QObject):
    """
    Generic mode that provides outline information through the
    document_changed signal and a specialised worker function.

    To use this mode, you need to write a worker function that returns a list
    of pyqode.core.share.Definition (see
    pyqode.python.backend.workers.defined_names() for an example of how to
    implement the worker function).
    """

    #: Signal emitted when the document structure changed.
    document_changed = QtCore.Signal()

    @property
    def definitions(self):
        """
        Gets the list of top level definitions.
        """
        return self._results

    def __init__(self, worker, delay=1000):
        Mode.__init__(self)
        QtCore.QObject.__init__(self)
        self._worker = worker
        self._jobRunner = DelayJobRunner(delay=delay)
        #: The list of definitions found in the file, each item is a
        #: pyqode.core.share.Definition.
        self._results = []

    def on_state_changed(self, state):
        if state:
            self.editor.new_text_set.connect(self._run_analysis)
            self.editor.textChanged.connect(self._request_analysis)
        else:
            self.editor.textChanged.disconnect(self._request_analysis)
            self.editor.new_text_set.disconnect(self._run_analysis)
            self._jobRunner.cancel_requests()

    def _request_analysis(self):
        self._jobRunner.request_job(self._run_analysis)

    def _run_analysis(self):
        try:
            self.editor.file
            self.editor.toPlainText()
        except (RuntimeError, AttributeError):
            # called by the timer after the editor got deleted
            return
        if self.enabled:
            request_data = {
                'code': self.editor.toPlainText(),
                'path': self.editor.file.path,
                'encoding': self.editor.file.encoding
            }
            try:
                self.editor.backend.send_request(
                    self._worker, request_data,
                    on_receive=self._on_results_available)
            except NotRunning:
                QtCore.QTimer.singleShot(100, self._run_analysis)
        else:
            self._results = []
            self.document_changed.emit()

    def _on_results_available(self, results):
        if results:
            results = [Definition.from_dict(ddict) for ddict in results]
        self._results = results
        if self._results is not None:
            _logger().debug("Document structure changed")
            self.document_changed.emit()
开发者ID:abdullahtahiriyo,项目名称:cadquery-freecad-module,代码行数:74,代码来源:outline.py

示例2: DocumentAnalyserMode

# 需要导入模块: from pyqode.core.api import DelayJobRunner [as 别名]
# 或者: from pyqode.core.api.DelayJobRunner import cancel_requests [as 别名]
class DocumentAnalyserMode(Mode, QtCore.QObject):
    """ Analyses the document outline as a tree of statements.

    This mode analyses the structure of a document (a tree of
    :class:`pyqode.python.backend.workers.Definition`.

    :attr:`pyqode.python.modes.DocumentAnalyserMode.document_changed`
    is emitted whenever the document structure changed.

    To keep good performances, the analysis task is run when the application is
    idle for more than 1 second (by default).
    """
    #: Signal emitted when the document structure changed.
    document_changed = QtCore.Signal()

    def __init__(self, delay=1000):
        Mode.__init__(self)
        QtCore.QObject.__init__(self)
        self._jobRunner = DelayJobRunner(delay=delay)
        #: The list of results (elements might have children; this is actually
        #: a tree).
        self.results = []

    def on_state_changed(self, state):
        if state:
            self.editor.new_text_set.connect(self._run_analysis)
            self.editor.textChanged.connect(self._request_analysis)
        else:
            self.editor.textChanged.disconnect(self._request_analysis)
            self.editor.new_text_set.disconnect(self._run_analysis)
            self._jobRunner.cancel_requests()

    def _request_analysis(self):
        self._jobRunner.request_job(self._run_analysis)

    def _run_analysis(self):
        if self.enabled and self.editor and self.editor.toPlainText() and \
                self.editor.file:
            request_data = {
                'code': self.editor.toPlainText(),
                'path': self.editor.file.path,
                'encoding': self.editor.file.encoding
            }
            try:
                self.editor.backend.send_request(
                    defined_names, request_data,
                    on_receive=self._on_results_available)
            except NotRunning:
                QtCore.QTimer.singleShot(100, self._run_analysis)
        else:
            self.results = []
            self.document_changed.emit()

    def _on_results_available(self, results):
        if results:
            results = [Definition().from_dict(ddict) for ddict in results]
        self.results = results
        if self.results is not None:
            _logger().debug("Document structure changed")
            self.document_changed.emit()

    @property
    def flattened_results(self):
        """
        Flattens the document structure tree as a simple sequential list.
        """
        ret_val = []
        for d in self.results:
            ret_val.append(d)
            for sub_d in d.children:
                nd = Definition(sub_d.name, sub_d.icon, sub_d.line,
                                sub_d.column, sub_d.full_name)
                nd.name = "  " + nd.name
                nd.full_name = "  " + nd.full_name
                ret_val.append(nd)
        return ret_val

    def to_tree_widget_items(self, to_collapse=None):
        """
        Returns the results as a list of top level QTreeWidgetItem.

        This is a convenience function that you can use to update a document
        tree widget wheneve the document changed.
        """
        def convert(name, editor, to_collapse):
            ti = QtWidgets.QTreeWidgetItem()
            ti.setText(0, name.name)
            ti.setIcon(0, QtGui.QIcon(name.icon))
            name.block = editor.document().findBlockByNumber(name.line)
            ti.setData(0, QtCore.Qt.UserRole, name)
            block_data = name.block.userData()
            if block_data is None:
                block_data = TextBlockUserData()
                name.block.setUserData(block_data)
            block_data.tree_item = ti

            if to_collapse is not None and \
                    TextBlockHelper.get_fold_trigger_state(name.block):
                to_collapse.append(ti)

#.........这里部分代码省略.........
开发者ID:AlexLee,项目名称:cadquery-freecad-module,代码行数:103,代码来源:document_analyser.py

示例3: FoldingPanel

# 需要导入模块: from pyqode.core.api import DelayJobRunner [as 别名]
# 或者: from pyqode.core.api.DelayJobRunner import cancel_requests [as 别名]

#.........这里部分代码省略.........
    def mouseMoveEvent(self, event):
        """
        Detect mouser over indicator and highlight the current scope in the
        editor (up and down decoration arround the foldable text when the mouse
        is over an indicator).

        :param event: event
        """
        super(FoldingPanel, self).mouseMoveEvent(event)
        th = TextHelper(self.editor)
        line = th.line_nbr_from_position(event.pos().y())
        if line >= 0:
            block = FoldScope.find_parent_scope(
                self.editor.document().findBlockByNumber(line))
            if TextBlockHelper.is_fold_trigger(block):
                if self._mouse_over_line is None:
                    # mouse enter fold scope
                    QtWidgets.QApplication.setOverrideCursor(
                        QtGui.QCursor(QtCore.Qt.PointingHandCursor))
                if self._mouse_over_line != block.blockNumber() and \
                        self._mouse_over_line is not None:
                    # fold scope changed, a previous block was highlighter so
                    # we quickly update our highlighting
                    self._mouse_over_line = block.blockNumber()
                    self._highlight_surrounding_scopes(block)
                else:
                    # same fold scope, request highlight
                    self._mouse_over_line = block.blockNumber()
                    self._highlight_runner.request_job(
                        self._highlight_surrounding_scopes, block)
                self._highight_block = block
            else:
                # no fold scope to highlight, cancel any pending requests
                self._highlight_runner.cancel_requests()
                self._mouse_over_line = None
                QtWidgets.QApplication.restoreOverrideCursor()
            self.repaint()

    def leaveEvent(self, event):
        """
        Removes scope decorations and background from the editor and the panel
        if highlight_caret_scope, else simply update the scope decorations to
        match the caret scope.

        """
        super(FoldingPanel, self).leaveEvent(event)
        QtWidgets.QApplication.restoreOverrideCursor()
        self._highlight_runner.cancel_requests()
        if not self.highlight_caret_scope:
            self._clear_scope_decos()
            self._mouse_over_line = None
            self._current_scope = None
        else:
            self._block_nbr = -1
            self._highlight_caret_scope()
        self.editor.repaint()

    def _add_fold_decoration(self, block, region):
        """
        Add fold decorations (boxes arround a folded block in the editor
        widget).
        """
        _logger().debug('add fold deco %r', block)
        deco = TextDecoration(block)
        deco.signals.clicked.connect(self._on_fold_deco_clicked)
        deco.tooltip = region.text(max_lines=25)
开发者ID:sopak,项目名称:cadquery-freecad-module,代码行数:70,代码来源:folding.py

示例4: WordClickMode

# 需要导入模块: from pyqode.core.api import DelayJobRunner [as 别名]
# 或者: from pyqode.core.api.DelayJobRunner import cancel_requests [as 别名]
class WordClickMode(Mode, QtCore.QObject):
    """ Adds support for word click events.

    It will highlight the click-able word when the user press control and move
    the mouse over a word.

    Detecting whether a word is click-able is the responsability of the
    subclasses. You must override ``_check_word_cursor`` and call
    ``_select_word_cursor`` if this is a click-able word (this
    process might be asynchrone) otherwise _clear_selection.

    :attr:`pyqode.core.modes.WordClickMode.word_clicked` is emitted
    when the word is clicked by the user (while keeping control pressed).
    """
    #: Signal emitted when a word is clicked. The parameter is a
    #: QTextCursor with the clicked word set as the selected text.
    word_clicked = QtCore.Signal(QtGui.QTextCursor)

    def __init__(self):
        QtCore.QObject.__init__(self)
        Mode.__init__(self)
        self._previous_cursor_start = -1
        self._previous_cursor_end = -1
        self._deco = None
        self._cursor = None
        self._timer = DelayJobRunner(delay=200)

    def on_state_changed(self, state):
        if state:
            self.editor.mouse_moved.connect(self._on_mouse_moved)
            self.editor.mouse_released.connect(self._on_mouse_released)
            self.editor.key_released.connect(self._on_key_released)
            self.editor.mouse_double_clicked.connect(
                self._on_mouse_double_clicked)
        else:
            self.editor.mouse_moved.disconnect(self._on_mouse_moved)
            self.editor.mouse_released.disconnect(self._on_mouse_released)
            self.editor.key_released.disconnect(self._on_key_released)
            self.editor.mouse_double_clicked.disconnect(
                self._on_mouse_double_clicked)

    def _on_mouse_double_clicked(self):
        self._timer.cancel_requests()

    def _on_key_released(self, event):
        if event.key() == QtCore.Qt.Key_Control:
            self._clear_selection()
            self._cursor = None

    def _select_word_cursor(self):
        """ Selects the word under the mouse cursor. """
        cursor = TextHelper(self.editor).word_under_mouse_cursor()
        if (self._previous_cursor_start != cursor.selectionStart() and
                self._previous_cursor_end != cursor.selectionEnd()):
            self._remove_decoration()
            self._add_decoration(cursor)
        self._previous_cursor_start = cursor.selectionStart()
        self._previous_cursor_end = cursor.selectionEnd()

    def _clear_selection(self):
        try:
            self._remove_decoration()
        except ValueError:
            pass
        self.editor.set_mouse_cursor(QtCore.Qt.IBeamCursor)
        self._previous_cursor_start = -1
        self._previous_cursor_end = -1

    def _on_mouse_moved(self, event):
        """ mouse moved callback """
        if event.modifiers() & QtCore.Qt.ControlModifier:
            cursor = TextHelper(self.editor).word_under_mouse_cursor()
            if (not self._cursor or
                    cursor.position() != self._cursor.position()):
                self._check_word_cursor(cursor)
            self._cursor = cursor
        else:
            self._cursor = None
            self._clear_selection()

    def _check_word_cursor(self, cursor):
        pass

    def _on_mouse_released(self, event):
        """ mouse pressed callback """
        if event.button() == 1 and self._deco:
            cursor = TextHelper(self.editor).word_under_mouse_cursor()
            if cursor and cursor.selectedText():
                self._timer.request_job(
                    self.word_clicked.emit, cursor)

    def _add_decoration(self, cursor):
        """
        Adds a decoration for the word under ``cursor``.
        """
        if self._deco is None:
            if cursor.selectedText():
                self._deco = TextDecoration(cursor)
                if self.editor.background.lightness() < 128:
                    self._deco.set_foreground(QtGui.QColor('#0681e0'))
#.........这里部分代码省略.........
开发者ID:OpenCobolIDE,项目名称:OpenCobolIDE,代码行数:103,代码来源:wordclick.py

示例5: CheckerPanel

# 需要导入模块: from pyqode.core.api import DelayJobRunner [as 别名]
# 或者: from pyqode.core.api.DelayJobRunner import cancel_requests [as 别名]
class CheckerPanel(Panel):
    """ Shows messages collected by one or more checker modes """
    def __init__(self):
        super(CheckerPanel, self).__init__()
        self._previous_line = -1
        self.scrollable = True
        self._job_runner = DelayJobRunner(delay=100)
        self.setMouseTracking(True)
        #: Info icon
        self.info_icon = icons.icon(
            'dialog-info', ':pyqode-icons/rc/dialog-info.png',
            'fa.info-circle', qta_options={'color': '#4040DD'})
        self.warning_icon = icons.icon(
            'dialog-warning', ':pyqode-icons/rc/dialog-warning.png',
            'fa.exclamation-triangle', qta_options={'color': '#DDDD40'})
        self.error_icon = icons.icon(
            'dialog-error', ':pyqode-icons/rc/dialog-error.png',
            'fa.exclamation-circle', qta_options={'color': '#DD4040'})

    def marker_for_line(self, line):
        """
        Returns the marker that is displayed at the specified line number if
        any.

        :param line: The marker line.

        :return: Marker of None
        :rtype: pyqode.core.Marker
        """
        block = self.editor.document().findBlockByNumber(line)
        try:
            return block.userData().messages
        except AttributeError:
            return []

    def sizeHint(self):
        """
        Returns the panel size hint. (fixed with of 16px)
        """
        metrics = QtGui.QFontMetricsF(self.editor.font())
        size_hint = QtCore.QSize(metrics.height(), metrics.height())
        if size_hint.width() > 16:
            size_hint.setWidth(16)
        return size_hint

    def on_uninstall(self):
        self._job_runner.cancel_requests()
        super(CheckerPanel, self).on_uninstall()

    def paintEvent(self, event):
        super(CheckerPanel, self).paintEvent(event)
        painter = QtGui.QPainter(self)
        for top, block_nbr, block in self.editor.visible_blocks:
            user_data = block.userData()
            if user_data and user_data.messages:
                for msg in user_data.messages:
                    icon = self._icon_from_message(msg)
                    if icon:
                        rect = QtCore.QRect()
                        rect.setX(0)
                        rect.setY(top)
                        rect.setWidth(self.sizeHint().width())
                        rect.setHeight(self.sizeHint().height())
                        icon.paint(painter, rect)

    def _icon_from_message(self, message):
        icons = {
            CheckerMessages.INFO: self.info_icon,
            CheckerMessages.WARNING: self.warning_icon,
            CheckerMessages.ERROR: self.error_icon
        }
        return icons[message.status]

    def mouseMoveEvent(self, event):
        # Requests a tooltip if the cursor is currently over a marker.
        line = TextHelper(self.editor).line_nbr_from_position(event.pos().y())
        if line:
            markers = self.marker_for_line(line)
            text = '\n'.join([marker.description for marker in markers if
                              marker.description])
            if len(markers):
                if self._previous_line != line:
                    top = TextHelper(self.editor).line_pos_from_number(
                        markers[0].line)
                    if top:
                        self._job_runner.request_job(self._display_tooltip,
                                                     text, top)
            else:
                self._job_runner.cancel_requests()
            self._previous_line = line

    def leaveEvent(self, *args):
        """
        Hide tooltip when leaving the panel region.
        """
        QtWidgets.QToolTip.hideText()
        self._previous_line = -1

    def _display_tooltip(self, tooltip, top):
        """
#.........这里部分代码省略.........
开发者ID:OpenCobolIDE,项目名称:OpenCobolIDE,代码行数:103,代码来源:checker.py

示例6: OccurrencesHighlighterMode

# 需要导入模块: from pyqode.core.api import DelayJobRunner [as 别名]
# 或者: from pyqode.core.api.DelayJobRunner import cancel_requests [as 别名]

#.........这里部分代码省略.........
        self._underlined = value
        if self.editor:
            for clone in self.editor.clones:
                try:
                    clone.modes.get(self.__class__).underlined = value
                except KeyError:
                    # this should never happen since we're working with clones
                    pass

    @property
    def case_sensitive(self):
        return self._case_sensitive

    @case_sensitive.setter
    def case_sensitive(self, value):
        self._case_sensitive = value
        self._request_highlight()

    def __init__(self):
        super(OccurrencesHighlighterMode, self).__init__()
        self._decorations = []
        #: Timer used to run the search request with a specific delay
        self.timer = DelayJobRunner(delay=1000)
        self._sub = None
        self._background = QtGui.QColor('#CCFFCC')
        self._foreground = None
        self._underlined = False
        self._case_sensitive = False

    def on_state_changed(self, state):
        if state:
            self.editor.cursorPositionChanged.connect(self._request_highlight)
        else:
            self.editor.cursorPositionChanged.disconnect(
                self._request_highlight)
            self.timer.cancel_requests()

    def _clear_decos(self):
        for d in self._decorations:
            self.editor.decorations.remove(d)
        self._decorations[:] = []

    def _request_highlight(self):
        if self.editor is not None:
            sub = TextHelper(self.editor).word_under_cursor(
                select_whole_word=True).selectedText()
            if sub != self._sub:
                self._clear_decos()
                if len(sub) > 1:
                    self.timer.request_job(self._send_request)

    def _send_request(self):
        if self.editor is None:
            return
        cursor = self.editor.textCursor()
        self._sub = TextHelper(self.editor).word_under_cursor(
            select_whole_word=True).selectedText()
        if not cursor.hasSelection() or cursor.selectedText() == self._sub:
            request_data = {
                'string': self.editor.toPlainText(),
                'sub': self._sub,
                'regex': False,
                'whole_word': True,
                'case_sensitive': self.case_sensitive
            }
            try:
                self.editor.backend.send_request(findall, request_data,
                                                 self._on_results_available)
            except NotRunning:
                self._request_highlight()

    def _on_results_available(self, results):
        if len(results) > 500:
            # limit number of results (on very big file where a lots of
            # occurrences can be found, this would totally freeze the editor
            # during a few seconds, with a limit of 500 we can make sure
            # the editor will always remain responsive).
            results = results[:500]
        current = self.editor.textCursor().position()
        if len(results) > 1:
            for start, end in results:
                if start <= current <= end:
                    continue
                deco = TextDecoration(self.editor.textCursor(),
                                      start_pos=start, end_pos=end)
                if self.underlined:
                    deco.set_as_underlined(self._background)
                else:
                    deco.set_background(QtGui.QBrush(self._background))
                    if self._foreground is not None:
                        deco.set_foreground(self._foreground)
                deco.draw_order = 3
                self.editor.decorations.append(deco)
                self._decorations.append(deco)

    def clone_settings(self, original):
        self.delay = original.delay
        self.background = original.background
        self.foreground = original.foreground
        self.underlined = original.underlined
开发者ID:OpenCobolIDE,项目名称:OpenCobolIDE,代码行数:104,代码来源:occurences.py

示例7: DocumentOutlineMode

# 需要导入模块: from pyqode.core.api import DelayJobRunner [as 别名]
# 或者: from pyqode.core.api.DelayJobRunner import cancel_requests [as 别名]
class DocumentOutlineMode(QObject, Mode):
    """
    Parses the current cobol document when the text changed and emit the
    changed event if any properties of any document node has changed.

    This mode can be used to implement a document outline widget.

    """
    #: Signal emitted when the document layout changed
    changed = Signal(Name, list, list)

    @property
    def root_node(self):
        """
        Returns the document root node.
        """
        return self._root_node

    @property
    def variables(self):
        """
        Returns the list of variable document nodes
        """
        return self._vars

    @property
    def paragraphs(self):
        """
        Returns the list of paragraphs document nodes
        """
        return self._paragraphs

    def __init__(self):
        QObject.__init__(self)
        Mode.__init__(self)
        self._root_node = None
        self._vars = []
        self._paragraphs = []
        self._runner = DelayJobRunner()

    def on_state_changed(self, state):
        """
        Called when the mode is activated/deactivated
        """
        if state:
            self.editor.new_text_set.connect(self.parse)
            self.editor.textChanged.connect(self._parse)
        else:
            self.editor.new_text_set.disconnect(self.parse)
            self.editor.textChanged.disconnect(self._parse)
            self._runner.cancel_requests()

    def _parse(self):
        self._runner.request_job(self.parse)

    def parse(self):
        """ Parse the document layout.

        To get the results, use the following properties:
            - root_node
            - variables
            - paragraphs
        """
        # preview in preferences dialog have no file path
        if not self.editor.file.path:
            return
        txt = self.editor.toPlainText()
        fmt = self.editor.free_format
        try:
            root_node, variables, paragraphs = defined_names(txt, fmt)
        except AttributeError:
            # this should never happen but we must exit gracefully
            _logger().exception("Failed to parse document, probably due to "
                                "a malformed syntax.")
        else:
            changed = False
            if self._root_node is None or cmp_name(root_node, self._root_node):
                changed = True
            self._root_node = root_node
            self._vars = variables
            self._paragraphs = paragraphs
            if changed:
                _logger().debug('changed')
                self.changed.emit(
                    self.root_node, self.variables, self.paragraphs)
开发者ID:dtonal,项目名称:pyqode.cobol,代码行数:87,代码来源:doc_outline.py


注:本文中的pyqode.core.api.DelayJobRunner.cancel_requests方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。