Esempio n. 1
0
 def get_bgcolor(self, index):
     """Background color depending on value"""
     column = index.column()
     if column == 0:
         color = QColor(Qt.lightGray)
         color.setAlphaF(.8)
         return color
     if not self.bgcolor_enabled:
         return
     value = self.get_value(index.row(), column-1)
     if isinstance(value, _sup_com):
         color_func = abs
     else:
         color_func = float
     if isinstance(value, _sup_nr+_sup_com) and self.bgcolor_enabled:
         vmax, vmin = self.return_max(self.max_min_col, column-1)
         hue = self.hue0 + self.dhue*(vmax-color_func(value)) / (vmax-vmin)
         hue = float(abs(hue))
         color = QColor.fromHsvF(hue, self.sat, self.val, self.alp)
     elif is_text_string(value):
         color = QColor(Qt.lightGray)
         color.setAlphaF(.05)
     else:
         color = QColor(Qt.lightGray)
         color.setAlphaF(.3)
     return color
Esempio n. 2
0
def get_color(value, alpha):
    """Return color depending on value type"""
    color = QColor()
    for typ in COLORS:
        if isinstance(value, typ):
            color = QColor(COLORS[typ])
    color.setAlphaF(alpha)
    return color
Esempio n. 3
0
 def set_light_background(self, state):
     self.light_background = state
     if state:
         self.set_palette(background=QColor(Qt.white),
                          foreground=QColor(Qt.darkGray))
     else:
         self.set_palette(background=QColor(Qt.black),
                          foreground=QColor(Qt.lightGray))
     self.ansi_handler.set_light_background(state)
     self.set_pythonshell_font()
Esempio n. 4
0
 def data(self, index, role=Qt.DisplayRole):
     """Cell content"""
     if not index.isValid():
         return to_qvariant()
     value = self.get_value(index)
     if is_binary_string(value):
         try:
             value = to_text_string(value, 'utf8')
         except:
             pass
     if role == Qt.DisplayRole:
         if value is np.ma.masked:
             return ''
         else:
             return to_qvariant(self._format % value)
     elif role == Qt.TextAlignmentRole:
         return to_qvariant(int(Qt.AlignCenter|Qt.AlignVCenter))
     elif role == Qt.BackgroundColorRole and self.bgcolor_enabled \
       and value is not np.ma.masked:
         hue = self.hue0+\
               self.dhue*(self.vmax-self.color_func(value)) \
               /(self.vmax-self.vmin)
         hue = float(np.abs(hue))
         color = QColor.fromHsvF(hue, self.sat, self.val, self.alp)
         return to_qvariant(color)
     elif role == Qt.FontRole:
         return to_qvariant(get_font('arrayeditor'))
     return to_qvariant()
Esempio n. 5
0
 def data(self, index, role=Qt.DisplayRole):
     """Cell content"""
     if not index.isValid():
         return to_qvariant()
     value = self.get_value(index)
     if is_binary_string(value):
         try:
             value = to_text_string(value, 'utf8')
         except:
             pass
     if role == Qt.DisplayRole:
         if value is np.ma.masked:
             return ''
         else:
             return to_qvariant(self._format % value)
     elif role == Qt.TextAlignmentRole:
         return to_qvariant(int(Qt.AlignCenter|Qt.AlignVCenter))
     elif role == Qt.BackgroundColorRole and self.bgcolor_enabled \
       and value is not np.ma.masked:
         hue = self.hue0+\
               self.dhue*(self.vmax-self.color_func(value)) \
               /(self.vmax-self.vmin)
         hue = float(np.abs(hue))
         color = QColor.fromHsvF(hue, self.sat, self.val, self.alp)
         return to_qvariant(color)
     elif role == Qt.FontRole:
         return to_qvariant(get_font('arrayeditor'))
     return to_qvariant()
Esempio n. 6
0
 def create_scedit(self,
                   text,
                   option,
                   default=NoDefault,
                   tip=None,
                   without_layout=False):
     label = QLabel(text)
     clayout = ColorLayout(QColor(Qt.black), self)
     clayout.lineedit.setMaximumWidth(80)
     if tip is not None:
         clayout.setToolTip(tip)
     cb_bold = QCheckBox()
     cb_bold.setIcon(ima.icon('bold'))
     cb_bold.setToolTip(_("Bold"))
     cb_italic = QCheckBox()
     cb_italic.setIcon(ima.icon('italic'))
     cb_italic.setToolTip(_("Italic"))
     self.scedits[(clayout, cb_bold, cb_italic)] = (option, default)
     if without_layout:
         return label, clayout, cb_bold, cb_italic
     layout = QHBoxLayout()
     layout.addWidget(label)
     layout.addLayout(clayout)
     layout.addSpacing(10)
     layout.addWidget(cb_bold)
     layout.addWidget(cb_italic)
     layout.addStretch(1)
     layout.setContentsMargins(0, 0, 0, 0)
     widget = QWidget(self)
     widget.setLayout(layout)
     return widget
Esempio n. 7
0
class ColorButton(QPushButton):
    """
    Color choosing push button
    """
    __pyqtSignals__ = ("colorChanged(QColor)",)
    
    def __init__(self, parent=None):
        QPushButton.__init__(self, parent)
        self.setFixedSize(20, 20)
        self.setIconSize(QSize(12, 12))
        self.connect(self, SIGNAL("clicked()"), self.choose_color)
        self._color = QColor()
    
    def choose_color(self):
        rgba, valid = QColorDialog.getRgba(self._color.rgba(),
                                           self.parentWidget())
        if valid:
            color = QColor.fromRgba(rgba)
            self.set_color(color)
    
    def get_color(self):
        return self._color
    
    @Slot(QColor)
    def set_color(self, color):
        if color != self._color:
            self._color = color
            self.emit(SIGNAL("colorChanged(QColor)"), self._color)
            pixmap = QPixmap(self.iconSize())
            pixmap.fill(color)
            self.setIcon(QIcon(pixmap))
    
    color = Property("QColor", get_color, set_color)
Esempio n. 8
0
 def apply_style(self, font, light_background, is_default):
     self.format = QTextCharFormat()
     self.format.setFont(font)
     foreground = QColor(self.foregroundcolor)
     if not light_background and is_default:
         inverse_color(foreground)
     self.format.setForeground(foreground)
     background = QColor(self.backgroundcolor)
     if not light_background:
         inverse_color(background)
     self.format.setBackground(background)
     font = self.format.font()
     font.setBold(self.bold)
     font.setItalic(self.italic)
     font.setUnderline(self.underline)
     self.format.setFont(font)
Esempio n. 9
0
    def __init__(self, parent=None):
        QPlainTextEdit.__init__(self, parent)
        BaseEditMixin.__init__(self)
        self.setAttribute(Qt.WA_DeleteOnClose)

        self.extra_selections_dict = {}

        self.connect(self, SIGNAL('textChanged()'), self.changed)
        self.connect(self, SIGNAL('cursorPositionChanged()'),
                     self.cursor_position_changed)

        self.indent_chars = " " * 4

        # Code completion / calltips
        if parent is not None:
            mainwin = parent
            while not isinstance(mainwin, QMainWindow):
                mainwin = mainwin.parent()
                if mainwin is None:
                    break
            if mainwin is not None:
                parent = mainwin

        self.completion_widget = CompletionWidget(self, parent)
        self.codecompletion_auto = False
        self.codecompletion_case = True
        self.codecompletion_enter = False
        self.completion_text = ""

        self.calltip_widget = CallTipWidget(self, hide_timer_on=True)
        self.calltips = True
        self.calltip_position = None

        self.has_cell_separators = False
        self.highlight_current_cell_enabled = False

        # The color values may be overridden by the syntax highlighter
        # Highlight current line color
        self.currentline_color = QColor(Qt.red).lighter(190)
        self.currentcell_color = QColor(Qt.red).lighter(194)

        # Brace matching
        self.bracepos = None
        self.matched_p_color = QColor(Qt.green)
        self.unmatched_p_color = QColor(Qt.red)
Esempio n. 10
0
def text_to_qcolor(text):
    """
    Create a QColor from specified string
    Avoid warning from Qt when an invalid QColor is instantiated
    """
    color = QColor()
    text = str(text)
    if not isinstance(text, (unicode, str)):
        return color
    if text.startswith('#') and len(text)==7:
        correct = '#0123456789abcdef'
        for char in text:
            if char.lower() not in correct:
                return color
    elif text not in list(QColor.colorNames()):
        return color
    color.setNamedColor(text)
    return color
Esempio n. 11
0
def text_to_qcolor(text):
    """
    Create a QColor from specified string
    Avoid warning from Qt when an invalid QColor is instantiated
    """
    color = QColor()
    text = str(text)
    if not is_text_string(text):
        return color
    if text.startswith('#') and len(text)==7:
        correct = '#0123456789abcdef'
        for char in text:
            if char.lower() not in correct:
                return color
    elif text not in list(QColor.colorNames()):
        return color
    color.setNamedColor(text)
    return color
Esempio n. 12
0
    def set_style(self):
        """
        Set font style with the following attributes:
        'foreground_color', 'background_color', 'italic',
        'bold' and 'underline'
        """
        if self.current_format is None:
            assert self.base_format is not None
            self.current_format = QTextCharFormat(self.base_format)
        # Foreground color
        if self.foreground_color is None:
            qcolor = self.base_format.foreground()
        else:
            cstr = self.ANSI_COLORS[self.foreground_color - 30][self.intensity]
            qcolor = QColor(cstr)
        self.current_format.setForeground(qcolor)
        # Background color
        if self.background_color is None:
            qcolor = self.base_format.background()
        else:
            cstr = self.ANSI_COLORS[self.background_color - 40][self.intensity]
            qcolor = QColor(cstr)
        self.current_format.setBackground(qcolor)

        font = self.current_format.font()
        # Italic
        if self.italic is None:
            italic = self.base_format.fontItalic()
        else:
            italic = self.italic
        font.setItalic(italic)
        # Bold
        if self.bold is None:
            bold = self.base_format.font().bold()
        else:
            bold = self.bold
        font.setBold(bold)
        # Underline
        if self.underline is None:
            underline = self.base_format.font().underline()
        else:
            underline = self.underline
        font.setUnderline(underline)
        self.current_format.setFont(font)
Esempio n. 13
0
 def data(self, index, role=Qt.DisplayRole):
     """Return data at table index"""
     if not index.isValid():
         return to_qvariant()
     dep = self.dependencies[index.row()]
     if role == Qt.DisplayRole:
         if index.column() == 0:
             value = self.get_value(index)
             return to_qvariant(value)
         else:
             value = self.get_value(index)
             return to_qvariant(value)
     elif role == Qt.TextAlignmentRole:
         return to_qvariant(int(Qt.AlignLeft | Qt.AlignVCenter))
     elif role == Qt.BackgroundColorRole:
         from spyderlib.dependencies import Dependency
         status = dep.get_status()
         if status == Dependency.NOK:
             color = QColor(Qt.red)
             color.setAlphaF(.25)
             return to_qvariant(color)
Esempio n. 14
0
 def data(self, index, role=Qt.DisplayRole):
     """Return data at table index"""
     if not index.isValid():
         return to_qvariant()
     dep = self.dependencies[index.row()]
     if role == Qt.DisplayRole:
         if index.column() == 0:
             value = self.get_value(index)
             return to_qvariant(value)
         else:
             value = self.get_value(index)
             return to_qvariant(value)
     elif role == Qt.TextAlignmentRole:
         return to_qvariant(int(Qt.AlignLeft|Qt.AlignVCenter))
     elif role == Qt.BackgroundColorRole:
         from spyderlib.dependencies import Dependency
         status = dep.get_status()
         if status == Dependency.NOK:
             color = QColor(Qt.red)
             color.setAlphaF(.25)
             return to_qvariant(color)
Esempio n. 15
0
def get_color(value, alpha):
    """Return color depending on value type"""
    color = QColor()
    for typ in COLORS:
        if isinstance(value, typ):
            color = QColor(COLORS[typ])
    color.setAlphaF(alpha)
    return color
Esempio n. 16
0
 def create_coloredit(self, text, option, default=NoDefault, tip=None,
                      without_layout=False):
     label = QLabel(text)
     clayout = ColorLayout(QColor(Qt.black), self)
     clayout.lineedit.setMaximumWidth(80)
     if tip is not None:
         clayout.setToolTip(tip)
     self.coloredits[clayout] = (option, default)
     if without_layout:
         return label, clayout
     layout = QHBoxLayout()
     layout.addWidget(label)
     layout.addLayout(clayout)
     layout.addStretch(1)
     layout.setContentsMargins(0, 0, 0, 0)
     widget = QWidget(self)
     widget.setLayout(layout)
     return widget
Esempio n. 17
0
    def _paint_icon(self, iconic, painter, rect, mode, state, options):
        """Paint a single icon"""
        painter.save()
        color, char = options['color'], options['char']

        if mode == QIcon.Disabled:
            color = options.get('color_disabled', color)
            char = options.get('disabled', char)
        elif mode == QIcon.Active:
            color = options.get('color_active', color)
            char = options.get('active', char)
        elif mode == QIcon.Selected:
            color = options.get('color_selected', color)
            char = options.get('selected', char)

        painter.setPen(QColor(color))
        # A 16 pixel-high icon yields a font size of 14, which is pixel perfect
        # for font-awesome. 16 * 0.875 = 14
        # The reason for not using full-sized glyphs is the negative bearing of
        # fonts.
        draw_size = 0.875 * qRound(rect.height() * options['scale_factor'])
        prefix = options['prefix']

        # Animation setup hook
        animation = options.get('animation')
        if animation is not None:
            animation.setup(self, painter, rect)

        painter.setFont(iconic.font(prefix, draw_size))
        if 'offset' in options:
            rect = QRect(rect)
            rect.translate(options['offset'][0] * rect.width(),
                           options['offset'][1] * rect.height())

        painter.setOpacity(options.get('opacity', 1.0))

        painter.drawText(rect, Qt.AlignCenter | Qt.AlignVCenter, char)
        painter.restore()
Esempio n. 18
0
 def get_bgcolor(self, index):
     """Background color depending on value"""
     column = index.column()
     if column == 0:
         color = QColor(Qt.lightGray)
         color.setAlphaF(.8)
         return color
     if not self.bgcolor_enabled:
         return
     value = self.get_value(index.row(), column - 1)
     if isinstance(value, _sup_com):
         color_func = abs
     else:
         color_func = float
     if isinstance(value, _sup_nr + _sup_com) and self.bgcolor_enabled:
         vmax, vmin = self.return_max(self.max_min_col, column - 1)
         hue = self.hue0 + self.dhue * (vmax - color_func(value)) / (vmax -
                                                                     vmin)
         hue = float(abs(hue))
         color = QColor.fromHsvF(hue, self.sat, self.val, self.alp)
     elif is_text_string(value):
         color = QColor(Qt.lightGray)
         color.setAlphaF(.05)
     else:
         color = QColor(Qt.lightGray)
         color.setAlphaF(.3)
     return color
    def populate_tree(self):
        """Create each item (and associated data) in the tree"""
        if not self.stats:
            warn_item = QTreeWidgetItem(self)
            warn_item.setData(
                0, Qt.DisplayRole,
                _('No timings to display. '
                  'Did you forget to add @profile decorators ?').format(
                      url=WEBSITE_URL))
            warn_item.setFirstColumnSpanned(True)
            warn_item.setTextAlignment(0, Qt.AlignCenter)
            font = warn_item.font(0)
            font.setStyle(QFont.StyleItalic)
            warn_item.setFont(0, font)
            return

        try:
            monospace_font = self.window().editor.get_plugin_font()
        except AttributeError:  # If run standalone for testing
            monospace_font = QFont("Courier New")
            monospace_font.setPointSize(10)

        for func_info, func_data in self.stats.iteritems():
            # Function name and position
            filename, start_line_no, func_name = func_info
            func_stats, func_total_time = func_data
            func_item = QTreeWidgetItem(self)
            func_item.setData(
                0, Qt.DisplayRole,
                _('{func_name} ({time_ms:.3f}ms) in file "{filename}", '
                  'line {line_no}').format(filename=filename,
                                           line_no=start_line_no,
                                           func_name=func_name,
                                           time_ms=func_total_time * 1e3))
            func_item.setFirstColumnSpanned(True)
            func_item.setData(COL_POS, Qt.UserRole,
                              (osp.normpath(filename), start_line_no))

            # For sorting by time
            func_item.setData(COL_TIME, Qt.DisplayRole, func_total_time * 1e3)
            func_item.setData(COL_PERCENT, Qt.DisplayRole,
                              func_total_time * 1e3)

            if self.parent().use_colors:
                # Choose deteministic unique color for the function
                md5 = hashlib.md5(filename + func_name).hexdigest()
                hue = (int(md5[:2], 16) - 68) % 360  # avoid blue (unreadable)
                func_color = QColor.fromHsv(hue, 200, 255)
            else:
                # Red color only
                func_color = QColor.fromRgb(255, 0, 0)

            # Lines of code
            for line_info in func_stats:
                line_item = QTreeWidgetItem(func_item)
                (line_no, code_line, line_total_time, time_per_hit, hits,
                 percent) = line_info
                self.fill_item(line_item, filename, line_no, code_line,
                               line_total_time, percent, time_per_hit, hits)

                # Color background
                if line_total_time is not None:
                    alpha = percent
                    color = QColor(func_color)
                    color.setAlphaF(alpha)  # Returns None
                    color = QBrush(color)
                    for col in range(self.columnCount()):
                        line_item.setBackground(col, color)
                else:

                    for col in range(self.columnCount()):
                        line_item.setForeground(col, CODE_NOT_RUN_COLOR)

                # Monospace font for code
                line_item.setFont(COL_LINE, monospace_font)
Esempio n. 20
0
    def __init__(self, parent, opacity, duration, easing_curve):
        super(FadingTipBox, self).__init__(parent, opacity, duration,
                                           easing_curve)
        self.holder = self.anim  # needed for qt to work
        self.parent = parent

        self.frames = None
        self.color_top = QColor.fromRgb(230, 230, 230)
        self.color_back = QColor.fromRgb(255, 255, 255)
        self.offset_shadow = 0
        self.fixed_width = 300

        self.key_pressed = None

        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setWindowFlags(Qt.Dialog | Qt.FramelessWindowHint |
                            Qt.WindowStaysOnTopHint)
        self.setModal(False)

        # Widgets
        self.button_home = QPushButton("<<")
        self.button_close = QPushButton("X")
        self.button_previous = QPushButton(" < ")
        self.button_end = QPushButton(">>")
        self.button_next = QPushButton(" > ")
        self.button_run = QPushButton(_('Run code'))
        self.button_disable = None
        self.button_current = QToolButton()
        self.label_image = QLabel()

        self.label_title = QLabel()
        self.combo_title = QComboBox()
        self.label_current = QLabel()
        self.label_content = QLabel()

        self.label_content.setMinimumWidth(self.fixed_width)
        self.label_content.setMaximumWidth(self.fixed_width)

        self.label_current.setAlignment(Qt.AlignCenter)

        self.label_content.setWordWrap(True)

        self.widgets = [self.label_content, self.label_title,
                        self.label_current, self.combo_title,
                        self.button_close, self.button_run, self.button_next,
                        self.button_previous, self.button_end,
                        self.button_home, self.button_current]

        arrow = get_image_path('hide.png')

        self.stylesheet = '''QPushButton {
                             background-color: rgbs(200,200,200,100%);
                             color: rgbs(0,0,0,100%);
                             border-style: outset;
                             border-width: 1px;
                             border-radius: 3px;
                             border-color: rgbs(100,100,100,100%);
                             padding: 2px;
                             }

                             QPushButton:hover {
                             background-color: rgbs(150, 150, 150, 100%);
                             }

                             QPushButton:disabled {
                             background-color: rgbs(230,230,230,100%);
                             color: rgbs(200,200,200,100%);
                             border-color: rgbs(200,200,200,100%);
                             }

                             QComboBox {
                             padding-left: 5px;
                             background-color: rgbs(230,230,230,100%);
                             border-width: 0px;
                             border-radius: 0px;
                             min-height:20px;
                             max-height:20px;
                             }

                             QComboBox::drop-down  {
                             subcontrol-origin: padding;
                             subcontrol-position: top left;
                             border-width: 0px;
                             }
                             
                             QComboBox::down-arrow {
                             image: url(''' + arrow + ''');
                             }
                             
                             '''
        # Windows fix, slashes should be always in unix-style
        self.stylesheet = self.stylesheet.replace('\\', '/')

        for widget in self.widgets:
            widget.setFocusPolicy(Qt.NoFocus)
            widget.setStyleSheet(self.stylesheet)

        layout_top = QHBoxLayout()
        layout_top.addWidget(self.combo_title)
        layout_top.addStretch()
        layout_top.addWidget(self.button_close)
        layout_top.addSpacerItem(QSpacerItem(self.offset_shadow,
                                             self.offset_shadow))

        layout_content = QHBoxLayout()
        layout_content.addWidget(self.label_content)
        layout_content.addWidget(self.label_image)
        layout_content.addSpacerItem(QSpacerItem(5, 5))

        layout_run = QHBoxLayout()
        layout_run.addStretch()
        layout_run.addWidget(self.button_run)
        layout_run.addStretch()
        layout_run.addSpacerItem(QSpacerItem(self.offset_shadow,
                                             self.offset_shadow))

        layout_navigation = QHBoxLayout()
        layout_navigation.addWidget(self.button_home)
        layout_navigation.addWidget(self.button_previous)
        layout_navigation.addStretch()
        layout_navigation.addWidget(self.label_current)
        layout_navigation.addStretch()
        layout_navigation.addWidget(self.button_next)
        layout_navigation.addWidget(self.button_end)
        layout_navigation.addSpacerItem(QSpacerItem(self.offset_shadow,
                                                    self.offset_shadow))

        layout = QVBoxLayout()
        layout.addLayout(layout_top)
        layout.addStretch()
        layout.addSpacerItem(QSpacerItem(15, 15))
        layout.addLayout(layout_content)
        layout.addLayout(layout_run)
        layout.addStretch()
        layout.addSpacerItem(QSpacerItem(15, 15))
        layout.addLayout(layout_navigation)
        layout.addSpacerItem(QSpacerItem(self.offset_shadow,
                                         self.offset_shadow))

        layout.setSizeConstraint(QLayout.SetFixedSize)

        self.setLayout(layout)

        self.set_funcs_before_fade_in([self._disable_widgets])
        self.set_funcs_after_fade_in([self._enable_widgets])
        self.set_funcs_before_fade_out([self._disable_widgets])

        self.setContextMenuPolicy(Qt.CustomContextMenu)
Esempio n. 21
0
 def __init__(self, parent=None):
     QPushButton.__init__(self, parent)
     self.setFixedSize(20, 20)
     self.setIconSize(QSize(12, 12))
     self.connect(self, SIGNAL("clicked()"), self.choose_color)
     self._color = QColor()
Esempio n. 22
0
 def _show_message(self, text):
     """Show message on splash screen."""
     self.splash.showMessage(
         text, Qt.AlignBottom | Qt.AlignCenter | Qt.AlignAbsolute,
         QColor(Qt.white))
Esempio n. 23
0
"""Classes handling iconic fonts"""

from __future__ import print_function
from spyderlib.qt.QtCore import Qt, QObject, QPoint, QRect, qRound, QByteArray
from spyderlib.qt.QtGui import (QIcon, QColor, QIconEngine, QPainter, QPixmap,
                                QFontDatabase, QFont)
import json
import os
from six import unichr


_default_options = {
    'color': QColor(50, 50, 50),
    'color_disabled': QColor(150, 150, 150),
    'opacity': 1.0,
    'scale_factor': 1.0,
    }


def set_global_defaults(**kwargs):
    """Set global defaults for all icons"""
    valid_options = ['active', 'animation', 'color', 'color_active',
                     'color_disabled', 'color_selected', 'disabled', 'offset',
                     'scale_factor', 'selected']
    for kw in kwargs:
        if kw in valid_options:
            _default_options[kw] = kwargs[kw]
        else:
            error = "Invalid option '{0}'".format(kw)
            raise KeyError(error)
Esempio n. 24
0
 def choose_color(self):
     rgba, valid = QColorDialog.getRgba(self._color.rgba(),
                                        self.parentWidget())
     if valid:
         color = QColor.fromRgba(rgba)
         self.set_color(color)
try:
    from spyderlib.py3compat import to_text_string, getcwd
except ImportError:
    # python2
    to_text_string = unicode
    getcwd = os.getcwdu
_ = get_translation("p_memoryprofiler", dirname="spyderplugins")


COL_NO = 0
COL_USAGE = 1
COL_INCREMENT = 2
COL_LINE = 3
COL_POS = 0  # Position is not displayed but set as Qt.UserRole

CODE_NOT_RUN_COLOR = QBrush(QColor.fromRgb(128, 128, 128, 200))

WEBSITE_URL = 'https://pypi.python.org/pypi/memory_profiler/'


def is_memoryprofiler_installed():
    """Checks if the library for memory_profiler is installed
    """
    return programs.is_module_installed('memory_profiler')


class MemoryProfilerWidget(QWidget):
    """
    Memory profiler widget
    """
    DATAPATH = get_conf_path('memoryprofiler.results')
    def populate_tree(self):
        """Create each item (and associated data) in the tree"""
        if not self.stats:
            warn_item = QTreeWidgetItem(self)
            warn_item.setData(
                0, Qt.DisplayRole,
                _('No timings to display. '
                  'Did you forget to add @profile decorators ?')
                .format(url=WEBSITE_URL))
            warn_item.setFirstColumnSpanned(True)
            warn_item.setTextAlignment(0, Qt.AlignCenter)
            font = warn_item.font(0)
            font.setStyle(QFont.StyleItalic)
            warn_item.setFont(0, font)
            return

        try:
            monospace_font = self.window().editor.get_plugin_font()
        except AttributeError:  # If run standalone for testing
            monospace_font = QFont("Courier New")
            monospace_font.setPointSize(10)

        for func_info, func_data in self.stats.items():
            # Function name and position
            filename, start_line_no, func_name = func_info
            func_stats, func_peak_usage = func_data
            func_item = QTreeWidgetItem(self)
            func_item.setData(
                0, Qt.DisplayRole,
                _('{func_name} (peak {peak_usage:.3f} MiB) in file "{filename}", '
                  'line {line_no}').format(
                    filename=filename,
                    line_no=start_line_no,
                    func_name=func_name,
                    peak_usage=func_peak_usage))
            func_item.setFirstColumnSpanned(True)
            func_item.setData(COL_POS, Qt.UserRole,
                              (osp.normpath(filename), start_line_no))

            # For sorting by time
            func_item.setData(COL_USAGE, Qt.DisplayRole, func_peak_usage)
            func_item.setData(COL_INCREMENT, Qt.DisplayRole,
                              func_peak_usage)

            if self.parent().use_colors:
                # Choose deteministic unique color for the function
                md5 = hashlib.md5((filename + func_name).encode("utf8")).hexdigest()
                hue = (int(md5[:2], 16) - 68) % 360  # avoid blue (unreadable)
                func_color = QColor.fromHsv(hue, 200, 255)
            else:
                # Red color only
                func_color = QColor.fromRgb(255, 0, 0)

            # get max increment
            max_increment = 0
            for line_info in func_stats:
                (line_no, code_line, usage, increment) = line_info
                if increment is not None:
                    max_increment = max(max_increment, increment)

            # Lines of code
            for line_info in func_stats:
                line_item = QTreeWidgetItem(func_item)
                (line_no, code_line, usage, increment) = line_info
                self.fill_item(
                    line_item, filename, line_no, code_line,
                    usage, increment)

                # Color background
                if increment is not None:
                    alpha = increment / max_increment if max_increment != 0 else 0
                    color = QColor(func_color)
                    color.setAlphaF(alpha)  # Returns None
                    color = QBrush(color)
                    for col in range(self.columnCount()):
                        line_item.setBackground(col, color)
                else:

                    for col in range(self.columnCount()):
                        line_item.setForeground(col, CODE_NOT_RUN_COLOR)

                # Monospace font for code
                line_item.setFont(COL_LINE, monospace_font)
Esempio n. 27
0
    def __init__(self, parent, opacity, duration, easing_curve):
        super(FadingTipBox, self).__init__(parent, opacity, duration,
                                           easing_curve)
        self.holder = self.anim  # needed for qt to work
        self.parent = parent

        self.frames = None
        self.color_top = QColor.fromRgb(230, 230, 230)
        self.color_back = QColor.fromRgb(255, 255, 255)
        self.offset_shadow = 0
        self.fixed_width = 300

        self.key_pressed = None

        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setWindowFlags(Qt.Dialog | Qt.FramelessWindowHint
                            | Qt.WindowStaysOnTopHint)
        self.setModal(False)

        # Widgets
        self.button_home = QPushButton("<<")
        self.button_close = QPushButton("X")
        self.button_previous = QPushButton(" < ")
        self.button_end = QPushButton(">>")
        self.button_next = QPushButton(" > ")
        self.button_run = QPushButton(_('Run code'))
        self.button_disable = None
        self.button_current = QToolButton()
        self.label_image = QLabel()

        self.label_title = QLabel()
        self.combo_title = QComboBox()
        self.label_current = QLabel()
        self.label_content = QLabel()

        self.label_content.setMinimumWidth(self.fixed_width)
        self.label_content.setMaximumWidth(self.fixed_width)

        self.label_current.setAlignment(Qt.AlignCenter)

        self.label_content.setWordWrap(True)

        self.widgets = [
            self.label_content, self.label_title, self.label_current,
            self.combo_title, self.button_close, self.button_run,
            self.button_next, self.button_previous, self.button_end,
            self.button_home, self.button_current
        ]

        arrow = get_image_path('hide.png')

        self.stylesheet = '''QPushButton {
                             background-color: rgbs(200,200,200,100%);
                             color: rgbs(0,0,0,100%);
                             border-style: outset;
                             border-width: 1px;
                             border-radius: 3px;
                             border-color: rgbs(100,100,100,100%);
                             padding: 2px;
                             }

                             QPushButton:hover {
                             background-color: rgbs(150, 150, 150, 100%);
                             }

                             QPushButton:disabled {
                             background-color: rgbs(230,230,230,100%);
                             color: rgbs(200,200,200,100%);
                             border-color: rgbs(200,200,200,100%);
                             }

                             QComboBox {
                             padding-left: 5px;
                             background-color: rgbs(230,230,230,100%);
                             border-width: 0px;
                             border-radius: 0px;
                             min-height:20px;
                             max-height:20px;
                             }

                             QComboBox::drop-down  {
                             subcontrol-origin: padding;
                             subcontrol-position: top left;
                             border-width: 0px;
                             }
                             
                             QComboBox::down-arrow {
                             image: url(''' + arrow + ''');
                             }
                             
                             '''
        # Windows fix, slashes should be always in unix-style
        self.stylesheet = self.stylesheet.replace('\\', '/')

        for widget in self.widgets:
            widget.setFocusPolicy(Qt.NoFocus)
            widget.setStyleSheet(self.stylesheet)

        layout_top = QHBoxLayout()
        layout_top.addWidget(self.combo_title)
        layout_top.addStretch()
        layout_top.addWidget(self.button_close)
        layout_top.addSpacerItem(
            QSpacerItem(self.offset_shadow, self.offset_shadow))

        layout_content = QHBoxLayout()
        layout_content.addWidget(self.label_content)
        layout_content.addWidget(self.label_image)
        layout_content.addSpacerItem(QSpacerItem(5, 5))

        layout_run = QHBoxLayout()
        layout_run.addStretch()
        layout_run.addWidget(self.button_run)
        layout_run.addStretch()
        layout_run.addSpacerItem(
            QSpacerItem(self.offset_shadow, self.offset_shadow))

        layout_navigation = QHBoxLayout()
        layout_navigation.addWidget(self.button_home)
        layout_navigation.addWidget(self.button_previous)
        layout_navigation.addStretch()
        layout_navigation.addWidget(self.label_current)
        layout_navigation.addStretch()
        layout_navigation.addWidget(self.button_next)
        layout_navigation.addWidget(self.button_end)
        layout_navigation.addSpacerItem(
            QSpacerItem(self.offset_shadow, self.offset_shadow))

        layout = QVBoxLayout()
        layout.addLayout(layout_top)
        layout.addStretch()
        layout.addSpacerItem(QSpacerItem(15, 15))
        layout.addLayout(layout_content)
        layout.addLayout(layout_run)
        layout.addStretch()
        layout.addSpacerItem(QSpacerItem(15, 15))
        layout.addLayout(layout_navigation)
        layout.addSpacerItem(
            QSpacerItem(self.offset_shadow, self.offset_shadow))

        layout.setSizeConstraint(QLayout.SetFixedSize)

        self.setLayout(layout)

        self.set_funcs_before_fade_in([self._disable_widgets])
        self.set_funcs_after_fade_in([self._enable_widgets])
        self.set_funcs_before_fade_out([self._disable_widgets])

        self.setContextMenuPolicy(Qt.CustomContextMenu)
from spyderlib.baseconfig import get_conf_path, get_translation
from spyderlib.widgets.texteditor import TextEditor
from spyderlib.widgets.comboboxes import PythonModulesComboBox
from spyderlib.widgets.externalshell import baseshell
from spyderlib.py3compat import to_text_string, getcwd
_ = get_translation("p_lineprofiler", dirname="spyderplugins")

COL_NO = 0
COL_HITS = 1
COL_TIME = 2
COL_PERHIT = 3
COL_PERCENT = 4
COL_LINE = 5
COL_POS = 0  # Position is not displayed but set as Qt.UserRole

CODE_NOT_RUN_COLOR = QBrush(QColor.fromRgb(128, 128, 128, 200))

WEBSITE_URL = 'http://pythonhosted.org/line_profiler/'


def is_lineprofiler_installed():
    """Checks if the program and the library for line_profiler is installed
    """
    return (programs.is_module_installed('line_profiler')
            and programs.find_program('kernprof.py') is not None)


class LineProfilerWidget(QWidget):
    """
    Line profiler widget
    """
Esempio n. 29
0
    def populate_tree(self, parentItem, children_list):
        """Recursive method to create each item (and associated data) in the tree."""
        for child_key in children_list:
            self.item_depth += 1
            (filename, line_number, function_name, file_and_line,
             node_type) = self.function_info(child_key)

            ((total_calls, total_calls_dif), (loc_time, loc_time_dif),
             (cum_time, cum_time_dif)) = self.format_output(child_key)

            (primcalls, total_calls, loc_time, cum_time,
             callers) = self.stats[child_key]
            child_item = TreeWidgetItem(parentItem)
            self.item_list.append(child_item)
            self.set_item_data(child_item, filename, line_number)

            # FIXME: indexes to data should be defined by a dictionary on init
            child_item.setToolTip(0, 'Function or module name')
            child_item.setData(0, Qt.DisplayRole, function_name)
            child_item.setIcon(0, get_icon(self.icon_list[node_type]))

            child_item.setToolTip(1, _('Time in function '\
                                       '(including sub-functions)'))
            child_item.setData(1, Qt.DisplayRole, cum_time)
            child_item.setTextAlignment(1, Qt.AlignRight)

            child_item.setData(2, Qt.DisplayRole, cum_time_dif[0])
            child_item.setForeground(2, QColor(cum_time_dif[1]))
            child_item.setTextAlignment(2, Qt.AlignLeft)

            child_item.setToolTip(3, _('Local time in function '\
                                      '(not in sub-functions)'))

            child_item.setData(3, Qt.DisplayRole, loc_time)
            child_item.setTextAlignment(3, Qt.AlignRight)

            child_item.setData(4, Qt.DisplayRole, loc_time_dif[0])
            child_item.setForeground(4, QColor(loc_time_dif[1]))
            child_item.setTextAlignment(4, Qt.AlignLeft)

            child_item.setToolTip(5, _('Total number of calls '\
                                       '(including recursion)'))

            child_item.setData(5, Qt.DisplayRole, total_calls)
            child_item.setTextAlignment(5, Qt.AlignRight)

            child_item.setData(6, Qt.DisplayRole, total_calls_dif[0])
            child_item.setForeground(6, QColor(total_calls_dif[1]))
            child_item.setTextAlignment(6, Qt.AlignLeft)

            child_item.setToolTip(7, _('File:line '\
                                       'where function is defined'))
            child_item.setData(7, Qt.DisplayRole, file_and_line)
            #child_item.setExpanded(True)
            if self.is_recursive(child_item):
                child_item.setData(7, Qt.DisplayRole, '(%s)' % _('recursion'))
                child_item.setDisabled(True)
            else:
                callees = self.find_callees(child_key)
                if self.item_depth < 3:
                    self.populate_tree(child_item, callees)
                elif callees:
                    child_item.setChildIndicatorPolicy(
                        child_item.ShowIndicator)
                    self.items_to_be_shown[id(child_item)] = callees
            self.item_depth -= 1
Esempio n. 30
0
 def setup(self):
     for label, value in self.data:
         if DEBUG_FORMLAYOUT:
             print("value:", value)
         if label is None and value is None:
             # Separator: (None, None)
             self.formlayout.addRow(QLabel(" "), QLabel(" "))
             self.widgets.append(None)
             continue
         elif label is None:
             # Comment
             self.formlayout.addRow(QLabel(value))
             self.widgets.append(None)
             continue
         elif tuple_to_qfont(value) is not None:
             field = FontLayout(value, self)
         elif text_to_qcolor(value).isValid():
             field = ColorLayout(QColor(value), self)
         elif is_text_string(value):
             if '\n' in value:
                 for linesep in (os.linesep, '\n'):
                     if linesep in value:
                         value = value.replace(linesep, u("\u2029"))
                 field = QTextEdit(value, self)
             else:
                 field = QLineEdit(value, self)
         elif isinstance(value, (list, tuple)):
             value = list(value)  # in case this is a tuple
             selindex = value.pop(0)
             field = QComboBox(self)
             if isinstance(value[0], (list, tuple)):
                 keys = [ key for key, _val in value ]
                 value = [ val for _key, val in value ]
             else:
                 keys = value
             field.addItems(value)
             if selindex in value:
                 selindex = value.index(selindex)
             elif selindex in keys:
                 selindex = keys.index(selindex)
             elif not isinstance(selindex, int):
                 print("Warning: '%s' index is invalid (label: "\
                       "%s, value: %s)" % (selindex, label, value),
                       file=STDERR)
                 selindex = 0
             field.setCurrentIndex(selindex)
         elif isinstance(value, bool):
             field = QCheckBox(self)
             field.setCheckState(Qt.Checked if value else Qt.Unchecked)
         elif isinstance(value, float):
             field = QLineEdit(repr(value), self)
             field.setValidator(QDoubleValidator(field))
             dialog = self.get_dialog()
             dialog.register_float_field(field)
             field.textChanged.connect(lambda text: dialog.update_buttons())
         elif isinstance(value, int):
             field = QSpinBox(self)
             field.setRange(-1e9, 1e9)
             field.setValue(value)
         elif isinstance(value, datetime.datetime):
             field = QDateTimeEdit(self)
             field.setDateTime(value)
         elif isinstance(value, datetime.date):
             field = QDateEdit(self)
             field.setDate(value)
         else:
             field = QLineEdit(repr(value), self)
         self.formlayout.addRow(label, field)
         self.widgets.append(field)
Esempio n. 31
0
 def __init__(self, parent=None):
     QPushButton.__init__(self, parent)
     self.setFixedSize(20, 20)
     self.setIconSize(QSize(12, 12))
     self.clicked.connect(self.choose_color)
     self._color = QColor()