本文整理汇总了Python中pyqode.core.api.DelayJobRunner.request_job方法的典型用法代码示例。如果您正苦于以下问题:Python DelayJobRunner.request_job方法的具体用法?Python DelayJobRunner.request_job怎么用?Python DelayJobRunner.request_job使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyqode.core.api.DelayJobRunner
的用法示例。
在下文中一共展示了DelayJobRunner.request_job方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: HtmlPreviewWidget
# 需要导入模块: from pyqode.core.api import DelayJobRunner [as 别名]
# 或者: from pyqode.core.api.DelayJobRunner import request_job [as 别名]
class HtmlPreviewWidget(QtWebWidgets.QWebView):
hide_requested = QtCore.Signal()
show_requested = QtCore.Signal()
def __init__(self, parent=None):
super(HtmlPreviewWidget, self).__init__(parent)
self._editor = None
self._timer = DelayJobRunner(delay=1000)
try:
# prevent opening internal links when using QtWebKit
self.page().setLinkDelegationPolicy(
QtWebWidgets.QWebPage.DelegateAllLinks)
except (TypeError, AttributeError):
# no needed with QtWebEngine, internal links are properly handled
# by the default implementation
pass
def set_editor(self, editor):
url = QtCore.QUrl('')
if editor is not None:
url = QtCore.QUrl.fromLocalFile(editor.file.path)
try:
self.setHtml(editor.to_html(), url)
except (TypeError, AttributeError):
self.setHtml('<center>No preview available...</center>', url)
self._editor = None
self.hide_requested.emit()
else:
if self._editor is not None and editor != self._editor:
try:
self._editor.textChanged.disconnect(self._on_text_changed)
except TypeError:
pass
editor.textChanged.connect(self._on_text_changed)
self._editor = proxy(editor)
self.show_requested.emit()
def _on_text_changed(self, *_):
self._timer.request_job(self._update_preview)
def _update_preview(self):
url = QtCore.QUrl('')
if self._editor is not None:
url = QtCore.QUrl.fromLocalFile(self._editor.file.path)
try:
try:
pos = self.page().mainFrame().scrollBarValue(QtCore.Qt.Vertical)
self.setHtml(self._editor.to_html(), url)
self.page().mainFrame().setScrollBarValue(QtCore.Qt.Vertical, pos)
except AttributeError:
# Not possible with QtWebEngine???
# self._scroll_pos = self.page().mainFrame().scrollBarValue(
# QtCore.Qt.Vertical)
self.setHtml(self._editor.to_html(), url)
except (TypeError, AttributeError):
self.setHtml('<center>No preview available...</center>', url)
self.hide_requested.emit()
示例2: HtmlPreviewWidget
# 需要导入模块: from pyqode.core.api import DelayJobRunner [as 别名]
# 或者: from pyqode.core.api.DelayJobRunner import request_job [as 别名]
class HtmlPreviewWidget(QtWidgets.QTextEdit):
"""
Display html preview of a document as rich text in a QTextEdit.
"""
hide_requested = QtCore.Signal()
show_requested = QtCore.Signal()
def __init__(self, parent=None):
super(HtmlPreviewWidget, self).__init__(parent)
self._editor = None
self._timer = DelayJobRunner(delay=1000)
def set_editor(self, editor):
try:
self.setHtml(editor.to_html())
except (TypeError, AttributeError):
self.setHtml('<center>No preview available...</center>')
self._editor = None
self.hide_requested.emit()
else:
if self._editor is not None and editor != self._editor:
try:
self._editor.textChanged.disconnect(self._on_text_changed)
except TypeError:
pass
editor.textChanged.connect(self._on_text_changed)
self._editor = proxy(editor)
self.show_requested.emit()
def _on_text_changed(self, *_):
self._timer.request_job(self._update_preview)
def _update_preview(self):
try:
# remember cursor/scrollbar position
p = self.textCursor().position()
v = self.verticalScrollBar().value()
# display new html
self.setHtml(self._editor.to_html())
# restore cursor/scrollbar position
c = self.textCursor()
c.setPosition(p)
self.setTextCursor(c)
self.verticalScrollBar().setValue(v)
except (TypeError, AttributeError):
self.setHtml('<center>No preview available...</center>')
self.hide_requested.emit()
示例3: TabBar
# 需要导入模块: from pyqode.core.api import DelayJobRunner [as 别名]
# 或者: from pyqode.core.api.DelayJobRunner import request_job [as 别名]
class TabBar(QtWidgets.QTabBar):
"""
Tab bar specialized to allow the user to close a tab using mouse middle
click. Also exposes a double clicked signal.
"""
double_clicked = QtCore.Signal()
def __init__(self, parent):
QtWidgets.QTabBar.__init__(self, parent)
self.setTabsClosable(True)
self._timer = DelayJobRunner(delay=1)
def mousePressEvent(self, event):
QtWidgets.QTabBar.mousePressEvent(self, event)
if event.button() == QtCore.Qt.MiddleButton:
tab = self.tabAt(event.pos())
self._timer.request_job(
self.parentWidget().tabCloseRequested.emit, tab)
def mouseDoubleClickEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self.double_clicked.emit()
示例4: DocumentAnalyserMode
# 需要导入模块: from pyqode.core.api import DelayJobRunner [as 别名]
# 或者: from pyqode.core.api.DelayJobRunner import request_job [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)
#.........这里部分代码省略.........
示例5: GoToDefinitionMode
# 需要导入模块: from pyqode.core.api import DelayJobRunner [as 别名]
# 或者: from pyqode.core.api.DelayJobRunner import request_job [as 别名]
class GoToDefinitionMode(Mode, QObject):
"""
Go to the definition of the symbol under the word cursor.
"""
#: Signal emitted when a word is clicked. The parameter is a
#: QTextCursor with the clicked word set as the selected text.
word_clicked = Signal(QTextCursor)
def __init__(self):
QObject.__init__(self)
Mode.__init__(self)
self._previous_cursor_start = -1
self._previous_cursor_end = -1
self._definition = None
self._deco = None
self._pending = False
self.action_goto = QAction(_("Go to assignments"), self)
self.action_goto.setShortcut('F7')
self.action_goto.triggered.connect(self.request_goto)
self.word_clicked.connect(self.request_goto)
self._timer = DelayJobRunner(delay=200)
def on_state_changed(self, state):
"""
Connects/disconnects slots to/from signals when the mode state
changed.
"""
super(GoToDefinitionMode, self).on_state_changed(state)
if state:
self.editor.mouse_moved.connect(self._on_mouse_moved)
self.editor.mouse_pressed.connect(self._on_mouse_pressed)
self.editor.add_action(self.action_goto, sub_menu='COBOL')
self.editor.mouse_double_clicked.connect(
self._timer.cancel_requests)
else:
self.editor.mouse_moved.disconnect(self._on_mouse_moved)
self.editor.mouse_pressed.disconnect(self._on_mouse_pressed)
self.editor.remove_action(self.action_goto, sub_menu='Python')
self.editor.mouse_double_clicked.disconnect(
self._timer.cancel_requests)
def _select_word_under_mouse_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 _on_mouse_moved(self, event):
""" mouse moved callback """
if event.modifiers() & Qt.ControlModifier:
self._select_word_under_mouse_cursor()
else:
self._remove_decoration()
self.editor.set_mouse_cursor(Qt.IBeamCursor)
self._previous_cursor_start = -1
self._previous_cursor_end = -1
def _on_mouse_pressed(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 find_definition(self, symbol, definition):
if symbol in TextHelper(self.editor).line_text(definition.line):
return definition
for ch in definition.children:
d = self.find_definition(symbol, ch)
if d is not None:
return d
return None
def select_word(self, cursor):
symbol = cursor.selectedText()
analyser = self.editor.outline_mode
for definition in analyser.definitions:
node = self.find_definition(symbol, definition)
if node is not None:
break
else:
node = None
self._definition = None
if node and node.line != cursor.block().blockNumber():
self._definition = node
if self._deco is None:
if cursor.selectedText():
self._deco = TextDecoration(cursor)
self._deco.set_foreground(Qt.blue)
self._deco.set_as_underlined()
self.editor.decorations.append(self._deco)
return True
return False
def _add_decoration(self, cursor):
"""
#.........这里部分代码省略.........
示例6: GoToAssignmentsMode
# 需要导入模块: from pyqode.core.api import DelayJobRunner [as 别名]
# 或者: from pyqode.core.api.DelayJobRunner import request_job [as 别名]
class GoToAssignmentsMode(WordClickMode):
"""
Goes to the assignments (using jedi.Script.goto_assignments) when the user
execute the shortcut or click word. If there are more than one assignments,
an input dialog is used to ask the user to choose the desired assignment.
This mode will emit the :attr:`out_of_doc` signal if the definition can
not be reached in the current document. IDE will typically connects a slot
that open a new editor tab and goes to the definition position.
"""
#: Signal emitted when the definition cannot be reached in the current
#: document
out_of_doc = QtCore.Signal(Assignment)
#: Signal emitted when no results could be found.
no_results_found = QtCore.Signal()
shortcut = 'Alt+F2'
def __init__(self):
super(GoToAssignmentsMode, self).__init__()
self._definitions = []
self._goto_requested = False
self.action_goto = QtWidgets.QAction("Go to assignments", self)
self.action_goto.setShortcut(self.shortcut)
self.action_goto.triggered.connect(self.request_goto)
self.word_clicked.connect(self._on_word_clicked)
self._runner = DelayJobRunner(delay=1)
def on_state_changed(self, state):
super(GoToAssignmentsMode, self).on_state_changed(state)
if state:
self.editor.add_action(self.action_goto)
else:
self.editor.remove_action(self.action_goto)
def request_goto(self):
"""
Request a goto action for the word under the text cursor.
"""
self._goto_requested = True
self._check_word_cursor()
def _check_word_cursor(self, tc=None):
"""
Request a go to assignment.
:param tc: Text cursor which contains the text that we must look for
its assignment. Can be None to go to the text that is under
the text cursor.
:type tc: QtGui.QTextCursor
"""
if not tc:
tc = TextHelper(self.editor).word_under_cursor()
request_data = {
'code': self.editor.toPlainText(),
'line': tc.blockNumber(),
'column': tc.columnNumber(),
'path': self.editor.file.path,
'encoding': self.editor.file.encoding
}
try:
self.editor.backend.send_request(
workers.goto_assignments, request_data,
on_receive=self._on_results_available)
except NotRunning:
pass
def _goto(self, definition):
fp = ''
if self.editor.file.path:
fp = os.path.normpath(self.editor.file.path.replace(".pyc", ".py"))
if definition.module_path == fp:
line = definition.line
col = definition.column
_logger().debug("Go to %s" % definition)
self._runner.request_job(
TextHelper(self.editor).goto_line,
line, move=True, column=col)
else:
_logger().debug("Out of doc: %s" % definition)
self.out_of_doc.emit(definition)
def _unique(self, seq):
"""
Not performant but works.
"""
# order preserving
checked = []
for e in seq:
present = False
for c in checked:
if str(c) == str(e):
present = True
break
if not present:
checked.append(e)
return checked
#.........这里部分代码省略.........
示例7: OutlineMode
# 需要导入模块: from pyqode.core.api import DelayJobRunner [as 别名]
# 或者: from pyqode.core.api.DelayJobRunner import request_job [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()
示例8: FoldingPanel
# 需要导入模块: from pyqode.core.api import DelayJobRunner [as 别名]
# 或者: from pyqode.core.api.DelayJobRunner import request_job [as 别名]
#.........这里部分代码省略.........
# highlight surrounding parent scopes with a darker color
start, end = scope.get_range()
if not TextBlockHelper.get_fold_trigger_state(block):
self._add_scope_decorations(block, start, end)
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).
示例9: WordClickMode
# 需要导入模块: from pyqode.core.api import DelayJobRunner [as 别名]
# 或者: from pyqode.core.api.DelayJobRunner import request_job [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'))
#.........这里部分代码省略.........
示例10: CheckerPanel
# 需要导入模块: from pyqode.core.api import DelayJobRunner [as 别名]
# 或者: from pyqode.core.api.DelayJobRunner import request_job [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):
"""
#.........这里部分代码省略.........
示例11: OccurrencesHighlighterMode
# 需要导入模块: from pyqode.core.api import DelayJobRunner [as 别名]
# 或者: from pyqode.core.api.DelayJobRunner import request_job [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
示例12: DocumentOutlineMode
# 需要导入模块: from pyqode.core.api import DelayJobRunner [as 别名]
# 或者: from pyqode.core.api.DelayJobRunner import request_job [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)
示例13: DocumentAnalyserMode
# 需要导入模块: from pyqode.core.api import DelayJobRunner [as 别名]
# 或者: from pyqode.core.api.DelayJobRunner import request_job [as 别名]
class DocumentAnalyserMode(Mode, QtCore.QObject):
"""
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.blockCountChanged.connect(self._on_line_count_changed)
self.editor.new_text_set.connect(self._run_analysis)
else:
self.editor.blockCountChanged.disconnect(
self._on_line_count_changed)
self.editor.new_text_set.disconnect(self._run_analysis)
def _on_line_count_changed(self, e):
self._jobRunner.request_job(self._run_analysis)
def _run_analysis(self):
if 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 NotConnected:
QtCore.QTimer.singleShot(100, self._run_analysis)
else:
self.results = []
self.document_changed.emit()
def _on_results_available(self, status, 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