def set_graphics_item_brush(item, fill_color=None, alpha=255): ''' :param alpha: 255 means opaque, 0 means transparent. ''' if fill_color is None: fill_color = QColor(Qt.white) fill_color.setAlpha(alpha) brush = QBrush(fill_color) item.setBrush(brush)
def _update_widgets(self): _BaseColorsWidget._update_widgets(self) if self.update_colors_in_slider: color = self._model.color h, s, v = self._get_color_params(color) self._widget_1.set_gradient_stops( [(x / 100, QColor.fromHsvF(h, x / 100., v)) for x in range(101)]) self._widget_2.set_gradient_stops( [(x / 100, QColor.fromHsvF(h, s, x / 100.)) for x in range(101)])
def test_qgradient_slider(qtapi, qgradient_slider, capsys): import logging from pyvmmonitor_core.log_utils import logger_level from pyvmmonitor_qt.qt.QtGui import QColor from pyvmmonitor_qt.qt.QtCore import Qt qgradient_slider.show() assert qgradient_slider.value == 0 assert qgradient_slider.min_value == 0 assert qgradient_slider.max_value == 100 qgradient_slider.set_gradient_stops([ (0, QColor(Qt.red)), (0.5, QColor(Qt.yellow)), (1.0, QColor(Qt.blue)), ]) values = [] def on_value_changed(slider, new_val): assert slider is qgradient_slider values.append(new_val) qgradient_slider.on_value.register(on_value_changed) try: qgradient_slider.value = 40 assert values == [40] assert qgradient_slider.normalized_value == 0.4 assert qgradient_slider.value == 40 qgradient_slider.resize(100, 100) # Force the creation without waiting for a draw event. qgradient_slider.force_create_pixmap() # It's lower because the pixmap width < widget width assert qgradient_slider.value_from_point(30, 30) in (27, 33) logger = logging.getLogger() with logger_level(logger, logging.CRITICAL): # Trying to set > max or < min changes to the max or min value qgradient_slider.value = 999 assert values == [40, 100] assert qgradient_slider.value == 100 qgradient_slider.value = -1 assert qgradient_slider.value == 0 assert values == [40, 100, 0] with pytest.raises(ValueError): qgradient_slider.min_value = 1000 with pytest.raises(ValueError): qgradient_slider.max_value = -1000 assert (qgradient_slider.min_value, qgradient_slider.max_value) == (0, 100) # unchanged finally: qgradient_slider.on_value.unregister(on_value_changed)
def _update_widgets(self): _BaseColorsWidget._update_widgets(self) if self.update_colors_in_slider: color = self._model.color h, s, v = self._get_color_params(color) self._widget_1.set_gradient_stops([ (x / 100, QColor.fromHsvF(h, x / 100., v)) for x in range(101) ]) self._widget_2.set_gradient_stops([ (x / 100, QColor.fromHsvF(h, s, x / 100.)) for x in range(101) ])
def test_hsv_widget(qtapi, hsv_widget): from pyvmmonitor_qt.qt.QtGui import QColor assert hsv_widget.model is not None hsv_widget.model.color = QColor.fromHsvF(0.5, 0.5, 0.5) assert hsv_widget._hue_widget._slider.value == 360 * .5 hsv_widget.model.color = QColor.fromHsvF(0.1, 0.5, 0.5) assert hsv_widget._hue_widget._slider.value == 360 * .1 hsv_widget._hue_widget._slider.value = 360 * .4 assert hsv_widget.model.color == QColor.fromHsvF(0.4, 0.5, 0.5)
def _update_widgets(self): _BaseColorsWidget._update_widgets(self) color = self._model.color r, g, b = self._get_color_params(color) self._widget_0.set_gradient_stops( [(x / 255, QColor.fromRgbF(x / 255., g, b)) for x in range(256)]) self._widget_1.set_gradient_stops( [(x / 255, QColor.fromRgbF(r, x / 255., b)) for x in range(256)]) self._widget_2.set_gradient_stops( [(x / 255, QColor.fromRgbF(r, g, x / 255.)) for x in range(256)])
def test_color(qtapi, tree): tree.tree.show() tree['a'] = [10, 20] from pyvmmonitor_qt.qt.QtGui import QBrush from pyvmmonitor_qt.qt.QtGui import QColor from pyvmmonitor_qt.qt.QtCore import Qt tree['a'].set_foreground_brush(QBrush(QColor(Qt.red))) assert tree['a'].get_foreground_brush(0).color() == QColor(Qt.red) tree['a'].set_background_brush(QBrush(QColor(Qt.gray))) assert tree['a'].get_background_brush(0).color() == QColor(Qt.gray)
def test_rgb_widget(qtapi, rgb_widget): from pyvmmonitor_qt.qt.QtGui import QColor assert rgb_widget.model is not None color = rgb_widget.model.color = QColor.fromRgbF(0.5, 0.5, 0.5) # Note: qt doesn't really store the original float for the later redF (it's re-normalized # based on 0-255. assert rgb_widget._r_widget._slider.value == 255 * color.redF() color = rgb_widget.model.color = QColor.fromRgbF(0.1, 0.5, 0.5) assert rgb_widget._r_widget._slider.value == 255 * color.redF() rgb_widget._r_widget._slider.value = 255 * .4 assert rgb_widget.model.color == QColor.fromRgbF(0.4, 0.5, 0.5)
def _update_widgets(self): _BaseColorsWidget._update_widgets(self) color = self._model.color r, g, b = self._get_color_params(color) self._widget_0.set_gradient_stops([ (x / 255, QColor.fromRgbF(x / 255., g, b)) for x in range(256) ]) self._widget_1.set_gradient_stops([ (x / 255, QColor.fromRgbF(r, x / 255., b)) for x in range(256) ]) self._widget_2.set_gradient_stops([ (x / 255, QColor.fromRgbF(r, g, x / 255.)) for x in range(256) ])
def _update_widgets(self): _BaseColorsWidget._update_widgets(self) color = self._model.color c, m, y, k = self._get_color_params(color) self._widget_0.set_gradient_stops( [(x / 100, QColor.fromCmykF(x / 100., m, y, k)) for x in range(101)]) self._widget_1.set_gradient_stops( [(x / 100, QColor.fromCmykF(c, x / 100., y, k)) for x in range(101)]) self._widget_2.set_gradient_stops( [(x / 100, QColor.fromCmykF(c, m, x / 100., k)) for x in range(101)]) self._widget_3.set_gradient_stops( [(x / 100, QColor.fromCmykF(c, m, y, x / 100)) for x in range(101)])
def __init__(self, parent): super(PythonHighlighter, self).__init__(parent) self.rules = [] brush = QBrush(QtCore.Qt.darkGreen, QtCore.Qt.SolidPattern) builtin = QTextCharFormat() builtin.setForeground(brush) builtin.setFontWeight(QFont.Bold) builtins = dir(__builtin__) for word in builtins: pattern = QtCore.QRegExp("\\b{w}\\b".format(w=word)) rule = HighlightRule(pattern, builtin) self.rules.append(rule) brush = QBrush(QtCore.Qt.darkBlue, QtCore.Qt.SolidPattern) keyword = QTextCharFormat() keyword.setForeground(brush) keyword.setFontWeight(QFont.Bold) keywords = pythonkeyword.kwlist for word in keywords: pattern = QtCore.QRegExp("\\b{w}\\b".format(w=word)) rule = HighlightRule(pattern, keyword) self.rules.append(rule) brush = QBrush(QColor.fromRgb(255, 140, 0), QtCore.Qt.SolidPattern) pattern = QtCore.QRegExp("#[^\n]*") comment = QTextCharFormat() comment.setForeground(brush) comment.setFontWeight(QFont.Light) rule = HighlightRule(pattern, comment) self.rules.append(rule) self.setDocument(parent.document())
def test_choose_color_widget(qtapi, choose_color_widget): from pyvmmonitor_qt.qt_event_loop import process_events from pyvmmonitor_qt.qt.QtGui import QColor process_events() color_wheel_widget = choose_color_widget.color_wheel_widget choose_color_widget.color_wheel_widget.repaint() pixmap_size = choose_color_widget.color_wheel_widget._pixmap.size() # Just checking that the color wheel was built on paint assert pixmap_size.width() > 30 assert pixmap_size.height() > 30 assert color_wheel_widget.width() > pixmap_size.width() assert color_wheel_widget.height() > pixmap_size.height() center = color_wheel_widget._center assert color_wheel_widget.saturation_from_point(center[0], center[1]) == 0.0 assert color_wheel_widget.saturation_from_point(pixmap_size.width(), 0.0) == 1.0 choose_color_widget.model.color = QColor.fromCmykF(0.000000, 0.000000, 0.000000, 0.000000, 1.000000)
def test_opacity_widget(qtapi, opacity_widget): from pyvmmonitor_qt.qt.QtGui import QColor assert opacity_widget.model is not None color = opacity_widget.model.color = QColor.fromRgb(100, 90, 80) assert opacity_widget.model.opacity == 255 opacity_widget.model.opacity = 150 assert opacity_widget._widget_0._slider.value == 150
def paintEvent(self, ev): from pyvmmonitor_qt.qt_utils import painter_on from pyvmmonitor_qt.qt.QtGui import QColor from pyvmmonitor_qt.qt.QtCore import Qt from pyvmmonitor_qt.qt.QtGui import QBrush QPixmapWidget.paintEvent(self, ev) pixmap = self._pixmap triangle_path = self._triangle_path pixmap_offset = self._pixmap_offset if pixmap is None or triangle_path is None or pixmap_offset is None: return # After painting, also show the value selected. with painter_on(self, True) as painter: painter.setPen(Qt.lightGray) translation = [pixmap_offset[0], pixmap_offset[1]] translation[1] += (pixmap.height() + 2) translation[0] += (self.normalized_value * pixmap.width() ) # calculate the position translation[0] -= (self._triangle_size / 2) path = triangle_path.translated(translation[0], translation[1]) painter.fillPath(path, QBrush(QColor(30, 30, 30))) painter.drawPath(path)
def _lighten_with_alpha(self, hue_pixmap): from pyvmmonitor_qt.qt.QtGui import QPixmap from pyvmmonitor_qt.qt_utils import painter_on from pyvmmonitor_qt.qt.QtGui import QRadialGradient from pyvmmonitor_qt.qt.QtGui import QBrush size = self._wheel_size # Create a gradient to lighten up the center alpha_channel_pixmap = QPixmap(size, size) alpha_channel_pixmap.fill(Qt.transparent) radius = (size / 2) - 4 rg = QRadialGradient(size / 2, size / 2, radius, size / 2, size / 2) delta = 0.1 v = 0.0 for _ in range(10): v += delta rg.setColorAt(v, QColor.fromHsvF(0, 0, 1.0, 1.0 - v)) with painter_on(alpha_channel_pixmap, True) as painter: painter.setPen(Qt.NoPen) painter.setBrush(QBrush(rg)) painter.drawEllipse(0, 0, size, size) with painter_on(hue_pixmap, True) as painter: # Draw the alpha channel pixmap on top of the hue. painter.drawPixmap(0, 0, alpha_channel_pixmap) return hue_pixmap
def _create_hue_pixmap(self): ''' Create a simple hue pixmap where we change the hue in a conical gradient. ''' from pyvmmonitor_qt.qt.QtGui import QPixmap from pyvmmonitor_qt.qt.QtGui import QBrush from pyvmmonitor_qt.qt_utils import painter_on from pyvmmonitor_qt.qt.QtGui import QConicalGradient stops = 360 delta = 1.0 / stops v = 0.0 size = self._wheel_size pixmap = QPixmap(size, size) pixmap.fill(Qt.transparent) degrees = 360 gradient = QConicalGradient(size / 2, size / 2, degrees) for _stop in range(stops): v += delta # we do 1.0 - v to have blue on top (just a matter of taste really). color = QColor.fromHsvF(1.0 - v, 1.0, 1.0) gradient.setColorAt(v, color) with painter_on(pixmap, True) as painter: painter.setPen(Qt.NoPen) painter.setBrush(QBrush(gradient)) painter.drawEllipse(0, 0, size, size) return pixmap
def _update_widgets(self): color = self._model.color r, g, b = color.redF(), color.greenF(), color.blueF() self._widget_0.set_gradient_stops([ (a / 255, QColor.fromRgbF(r, g, b, a / 255)) for a in range(256) ]) self._widget_0.set_normalized_value(self._model.opacity / 255.)
def _on_mouse_pos(self, pos): saturation = self.saturation_from_point(*pos) hue = self.hue_from_point(*pos) # Update the model for the new saturation / hue. value = self._model.color.valueF() color = QColor.fromHsvF(hue, saturation, value) self._model.color = color
def __init__(self, *args, **kwargs): from pyvmmonitor_core.callback import Callback from pyvmmonitor_qt.qt.QtGui import QColor from pyvmmonitor_qt.qt.QtCore import Qt QPixmapWidget.__init__(self, *args, **kwargs) self._props = _QGradientSliderProps() self._props.register_modified(self._on_modified) self._triangle_path = None self._triangle_size = None # Called with on_value(self, value) self.on_value = Callback() gradient_stops = [ (0, QColor(Qt.black)), (1, QColor(Qt.red)), ] self.set_gradient_stops(gradient_stops)
def test_zoom_on_wheel(qtapi, view): from pyvmmonitor_qt.qt.QtWidgets import QGraphicsLineItem from pyvmmonitor_qt.qt.QtGui import QColor from pyvmmonitor_qt.qt.QtGui import QPen from pyvmmonitor_qt.qt.QtCore import Qt item = QGraphicsLineItem(0, 0, 10, 10) item.setPen(QPen(QColor(Qt.red))) view.scene().addItem(item)
def _on_line_edit_changed(self, value): color = QColor() color.setNamedColor(value) if not color.isValid(): color.setNamedColor('#' + value) if color.isValid(): self._model.color = color self._line_edit.setStyleSheet("") else: self._line_edit.setStyleSheet( "QLineEdit { background: #D30000; color: white;}")
def _update_widgets(self): _BaseColorsWidget._update_widgets(self) color = self._model.color c, m, y, k = self._get_color_params(color) self._widget_0.set_gradient_stops([ (x / 100, QColor.fromCmykF(x / 100., m, y, k)) for x in range(101) ]) self._widget_1.set_gradient_stops([ (x / 100, QColor.fromCmykF(c, x / 100., y, k)) for x in range(101) ]) self._widget_2.set_gradient_stops([ (x / 100, QColor.fromCmykF(c, m, x / 100., k)) for x in range(101) ]) self._widget_3.set_gradient_stops([ (x / 100, QColor.fromCmykF(c, m, y, x / 100)) for x in range(101) ])
def highlightCurrentLine(self): sel = QTextEdit.ExtraSelection() lineColor = QColor(QtCore.Qt.gray).lighter(150) sel.format.setBackground(QBrush(lineColor, QtCore.Qt.DiagCrossPattern)) sel.format.setProperty(QTextFormat.FullWidthSelection, True) sel.cursor = self.textCursor() sel.cursor.clearSelection() extraSelections = [sel] self.setExtraSelections(extraSelections)
def _create_label_widgets(self): hue_colors = [ (hue / 360., QColor.fromHsvF(hue / 360., 1.0, 1.0)) for hue in range(361)] self._widget_0 = _LabelGradientAndInt(self, 'H', hue_colors, (0, 360)) self._widget_0.slider.setObjectName('Hue') self._widget_1 = _LabelGradientAndInt(self, 'S', limits=self._saturation_limits) self._widget_1.slider.setObjectName('Saturation') self._widget_2 = _LabelGradientAndInt(self, 'V', limits=self._value_limits) self._widget_2.slider.setObjectName('Value') self.update_colors_in_slider = True
def _on_line_edit_changed(self, value): color = QColor() color.setNamedColor(value) if not color.isValid(): color.setNamedColor('#' + value) if color.isValid(): self._model.color = color self._line_edit.setStyleSheet("") else: self._line_edit.setStyleSheet("QLineEdit { background: #D30000; color: white;}")
def displaySyntaxError(self, line): sel = QTextEdit.ExtraSelection() lineColor = QColor(QtCore.Qt.red).lighter(150) sel.format.setBackground(QBrush(lineColor, QtCore.Qt.SolidPattern)) sel.format.setProperty(QTextFormat.FullWidthSelection, True) sel.cursor = QTextCursor(self.document()) sel.cursor.movePosition(sel.cursor.NextBlock, QTextCursor.MoveAnchor, line - 1) sel.cursor.clearSelection() extraSelections = [sel] self.setExtraSelections(extraSelections)
def _create_label_widgets(self): hue_colors = [(hue / 360., QColor.fromHsvF(hue / 360., 1.0, 1.0)) for hue in range(361)] self._widget_0 = _LabelGradientAndInt(self, 'H', hue_colors, (0, 360)) self._widget_0.slider.setObjectName('Hue') self._widget_1 = _LabelGradientAndInt(self, 'S', limits=self._saturation_limits) self._widget_1.slider.setObjectName('Saturation') self._widget_2 = _LabelGradientAndInt(self, 'V', limits=self._value_limits) self._widget_2.slider.setObjectName('Value') self.update_colors_in_slider = True
def test_python_code_text_edit(qtapi): from pyvmmonitor_qt.pyface_based.pygments_highlighter import PygmentsHighlighter from pyvmmonitor_qt.qt_utils import assert_focus_within_timeout from pyvmmonitor_qt.pyface_based.code_widget import CodeWidget PygmentsHighlighter.style = MonokaiStyle edit = CodeWidget(parent=None) edit.show() qtapi.add_widget(edit) edit.line_highlight_color = QColor(90, 90, 90) initial_code = '''class Error(object): pass''' edit.set_code(initial_code) cursor = edit.textCursor() assert_focus_within_timeout(edit) cursor.setPosition(len(initial_code)) edit.setTextCursor(cursor) # We must set it for it to be applied! assert edit.get_line_until_cursor() == ' pass' assert edit.get_current_line() == ' pass' QTest.sendKeyEvent(QTest.Click, edit, Qt.Key_Home, '', Qt.NoModifier) cursor = edit.textCursor() assert cursor.position(), len(initial_code) - len('pass') assert edit.get_line_until_cursor() == ' ' assert edit.get_current_line() == ' pass' QTest.sendKeyEvent(QTest.Click, edit, Qt.Key_Home, '', Qt.NoModifier) cursor = edit.textCursor() assert cursor.position(), len(initial_code) - len(' pass') assert edit.get_line_until_cursor() == '' assert edit.get_current_line() == ' pass' edit.set_code("""class Foo(object): def Method(self): ''' Docstring ''' a = 10 b += 20 c = 'single line string' self.a = 10 #Some comment """)
def test_choose_color_widget(qtapi, choose_color_widget): from pyvmmonitor_qt.qt_event_loop import process_events from pyvmmonitor_qt.qt.QtGui import QColor process_events() color_wheel_widget = choose_color_widget.color_wheel_widget choose_color_widget.color_wheel_widget.repaint() pixmap_size = choose_color_widget.color_wheel_widget._pixmap.size() # Just checking that the color wheel was built on paint assert pixmap_size.width() > 30 assert pixmap_size.height() > 30 assert color_wheel_widget.width() > pixmap_size.width() assert color_wheel_widget.height() > pixmap_size.height() center = color_wheel_widget._center assert color_wheel_widget.saturation_from_point(center[0], center[1]) == 0.0 assert color_wheel_widget.saturation_from_point(pixmap_size.width(), 0.0) == 1.0 choose_color_widget.model.color = QColor.fromCmykF( 0.000000, 0.000000, 0.000000, 0.000000, 1.000000)
def lineNumberAreaPaintEvent(self, event): painter = QPainter(self._lineNumber) painter.fillRect(event.rect(), QColor.fromRgb(200, 200, 200)) block = self.firstVisibleBlock() blockNumber = block.blockNumber() top = int( self.blockBoundingGeometry(block).translated( self.contentOffset()).top()) bottom = top + int(self.blockBoundingRect(block).height()) while block.isValid() and top <= event.rect().bottom(): if block.isVisible() and bottom >= event.rect().top(): number = str(blockNumber + 1) painter.setPen(QtCore.Qt.black) painter.drawText(0, top, self._lineNumber.width(), self.fontMetrics().height(), QtCore.Qt.AlignRight, number) block = block.next() top = bottom bottom = top + int(self.blockBoundingRect(block).height()) blockNumber += 1
def test_python_code_text_edit_current_line(qtapi): from pyvmmonitor_qt.pyface_based.pygments_highlighter import PygmentsHighlighter from pyvmmonitor_qt.qt_utils import assert_focus_within_timeout from pyvmmonitor_qt.pyface_based.code_widget import CodeWidget PygmentsHighlighter.style = MonokaiStyle edit = CodeWidget(parent=None) edit.line_highlight_color = QColor(90, 90, 90) initial_code = '''a = 10 b = 20 c = 30''' edit.set_code(initial_code) edit.show() cursor = edit.textCursor() assert_focus_within_timeout(edit) cursor.setPosition(0) edit.setTextCursor(cursor) # We must set it for it to be applied! assert edit.get_current_line_number() == 1 # 1-based edit.set_line_column(2, 1) assert edit.get_current_line_number() == 2
def test_python_code_text_edit_dirty(qtapi, tmpdir): from pyvmmonitor_qt.pyface_based.saveable_code_widget import SaveableAdvancedCodeWidget from pyvmmonitor_qt.pyface_based.pygments_highlighter import PygmentsHighlighter p = tmpdir.mkdir("sub").join("hello.py") initial_code = '''class Error(object): pass''' p.write(initial_code) PygmentsHighlighter.style = MonokaiStyle edit = SaveableAdvancedCodeWidget(parent=None) qtapi.add_widget(edit) edit.code.line_highlight_color = QColor(90, 90, 90) new_code = 'a = 10' dirty = [True] def on_dirty_changed(is_dirty): dirty[0] = is_dirty edit.on_dirty_changed.register(on_dirty_changed) edit.code.set_code(new_code) assert not dirty[0] edit.code.autoindent_newline() assert new_code + '\n' == edit.code.get_code() assert dirty[0] edit.filename = compat.unicode(p) edit.save() assert not dirty[0] edit.code.autoindent_newline() assert dirty[0] edit.code.undo() assert not dirty[0]
def _update_widgets(self): color = self._model.color r, g, b = color.redF(), color.greenF(), color.blueF() self._widget_0.set_gradient_stops( [(a / 255, QColor.fromRgbF(r, g, b, a / 255)) for a in range(256)]) self._widget_0.set_normalized_value(self._model.opacity / 255.)
def get_cpu_plot_fill_brush_color(self): color = QColor('#99B7FF') color.setAlpha(30) return color
def _create_color_from_params(self, params): return QColor.fromCmykF(*params)
def __init__(self, parent, should_highlight_current_line=True, font=None, lexer=None): from pyvmmonitor_qt.qt.QtGui import QColor from pyvmmonitor_qt.qt.QtGui import QFont super(CodeWidget, self).__init__(parent) self.highlighter = PygmentsHighlighter(self.document(), lexer) self.line_number_widget = LineNumberWidget(self) self.status_widget = StatusGutterWidget(self) if font is None: # Set a decent fixed width font for this platform. font = QFont() if sys.platform == 'win32': # Prefer Consolas, but fall back to Courier if necessary. font.setFamily('Consolas') if not font.exactMatch(): font.setFamily('Courier') elif sys.platform == 'darwin': font.setFamily('Monaco') else: font.setFamily('Monospace') font.setStyleHint(QFont.TypeWriter) self.set_font(font) # Whether we should highlight the current line or not. self.should_highlight_current_line = should_highlight_current_line # What that highlight color should be. self.line_highlight_color = QColor(QtCore.Qt.yellow).lighter(160) # Auto-indentation behavior self.auto_indent = True self.smart_backspace = True # Tab settings self.tabs_as_spaces = True self.tab_width = 4 self.indent_character = ':' self.comment_character = '#' # Set up gutter widget and current line highlighting self.blockCountChanged.connect(self.update_line_number_width) self.updateRequest.connect(self.update_line_numbers) self.cursorPositionChanged.connect(self.highlight_current_line) self.update_line_number_width() self.highlight_current_line() # Don't wrap text self.setLineWrapMode(QPlainTextEdit.NoWrap) # Key bindings from pyvmmonitor_qt.qt.QtGui import QKeySequence self.indent_key = QKeySequence(QtCore.Qt.Key_Tab) self.unindent_key = QKeySequence(QtCore.Qt.SHIFT + QtCore.Qt.Key_Backtab) self.comment_key = QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_Slash) self.backspace_key = QKeySequence(QtCore.Qt.Key_Backspace) self.goto_line_key = QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_G) self.home_key = QKeySequence(QtCore.Qt.Key_Home)
class ChooseColorModel(PropsObject): PropsObject.declare_props( color=QColor(Qt.red), opacity=255, )
def test_python_code_text_edit_save(qtapi, tmpdir): from pyvmmonitor_qt.pyface_based.saveable_code_widget import SaveableAdvancedCodeWidget from pyvmmonitor_qt.pyface_based.pygments_highlighter import PygmentsHighlighter try: # Python 3 has mock builtin from unittest.mock import patch except ImportError: # Python 2: use mock module from mock import patch p = tmpdir.mkdir("sub").join("hello.py") initial_code = '''class Error(object): pass''' p.write(initial_code) PygmentsHighlighter.style = MonokaiStyle edit = SaveableAdvancedCodeWidget(parent=None) qtapi.add_widget(edit) edit.code.line_highlight_color = QColor(90, 90, 90) new_code = 'a = 10' dirty = [True] def on_dirty_changed(is_dirty): dirty[0] = is_dirty edit.on_dirty_changed.register(on_dirty_changed) edit.code.set_code(new_code) assert not dirty[0] edit.filename = compat.unicode(p) edit.save() assert p.read() == new_code if sys.platform == 'win32': time.sleep(.001) # pass some millis before changing else: time.sleep(1) # Timeout must be higher for linux/mac. p.write(initial_code) from pyvmmonitor_qt.qt import QtWidgets with patch('pyvmmonitor_qt.qt.QtWidgets.QMessageBox.exec_') as m: m.return_value = QtWidgets.QMessageBox.AcceptRole edit.save() # I.e.: reloaded assert p.read() == initial_code assert edit.code.get_code() == initial_code p.write(new_code) with patch('pyvmmonitor_qt.qt.QtWidgets.QMessageBox.exec_') as m: m.return_value = QtWidgets.QMessageBox.RejectRole edit.save() # I.e.: not reloaded (overwrite) assert p.read() == initial_code assert edit.code.get_code() == initial_code p.write('foo') with patch.object(qt_utils, 'ask_save_filename') as m: m.return_value = compat.unicode(p), '' edit.filename = '' edit.save() assert edit.filename == compat.unicode(p) assert p.read() == initial_code assert edit.code.get_code() == initial_code p.write('foo') with patch.object(qt_utils, 'ask_save_filename') as m: m.return_value = '', '' edit.filename = '' edit.save() assert not edit.filename assert p.read() == 'foo' assert edit.code.get_code() == initial_code edit.filename = compat.unicode(p) edit.reload() assert p.read() == 'foo' assert edit.code.get_code() == 'foo'