Beispiel #1
0
 def __init__(self, *args, **kwargs):
     QStyledItemDelegate.__init__(self, *args)
     self.is_half_star = kwargs.get('is_half_star', False)
     self.table_widget = args[0]
     self.rf = QFont(rating_font())
     self.em = Qt.TextElideMode.ElideMiddle
     delta = 0
     if iswindows and sys.getwindowsversion().major >= 6:
         delta = 2
     self.rf.setPointSize(
         QFontInfo(QApplication.font()).pointSize() + delta)
Beispiel #2
0
 def __init__(self, toc=None):
     QStandardItemModel.__init__(self)
     self.current_query = {'text': '', 'index': -1, 'items': ()}
     self.all_items = depth_first = []
     normal_font = QApplication.instance().font()
     emphasis_font = QFont(normal_font)
     emphasis_font.setBold(True), emphasis_font.setItalic(True)
     if toc:
         for t in toc['children']:
             self.appendRow(
                 TOCItem(t, 0, depth_first, normal_font, emphasis_font))
     self.node_id_map = {x.node_id: x for x in self.all_items}
Beispiel #3
0
def message_image(text, width=500, height=400, font_size=20):
    init_environment()
    img = QImage(width, height, QImage.Format.Format_ARGB32)
    img.fill(Qt.GlobalColor.white)
    p = QPainter(img)
    f = QFont()
    f.setPixelSize(font_size)
    p.setFont(f)
    r = img.rect().adjusted(10, 10, -10, -10)
    p.drawText(r, Qt.AlignmentFlag.AlignJustify | Qt.AlignmentFlag.AlignVCenter | Qt.TextFlag.TextWordWrap, text)
    p.end()
    return pixmap_to_data(img)
Beispiel #4
0
 def __init__(self, parent):
     super(CoverDelegate, self).__init__(parent)
     self._animated_size = 1.0
     self.animation = QPropertyAnimation(self, b'animated_size', self)
     self.animation.setEasingCurve(QEasingCurve.Type.OutInCirc)
     self.animation.setDuration(500)
     self.set_dimensions()
     self.cover_cache = CoverCache()
     self.render_queue = LifoQueue()
     self.animating = None
     self.highlight_color = QColor(Qt.GlobalColor.white)
     self.rating_font = QFont(rating_font())
Beispiel #5
0
    def do_paint(self, painter, option, index):
        text = str(index.data(Qt.ItemDataRole.DisplayRole) or '')
        font = QFont(option.font)
        font.setPointSizeF(QFontInfo(font).pointSize() * 1.5)
        font2 = QFont(font)
        font2.setFamily(text)

        system, has_latin = writing_system_for_font(font2)
        if has_latin:
            font = font2

        r = option.rect
        color = option.palette.text()

        if option.state & QStyle.StateFlag.State_Selected:
            color = option.palette.highlightedText()
        painter.setPen(QPen(color, 0))

        if (option.direction == Qt.LayoutDirection.RightToLeft):
            r.setRight(r.right() - 4)
        else:
            r.setLeft(r.left() + 4)

        painter.setFont(font)
        painter.drawText(
            r, Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeading
            | Qt.TextFlag.TextSingleLine, text)

        if (system != QFontDatabase.WritingSystem.Any):
            w = painter.fontMetrics().width(text + "  ")
            painter.setFont(font2)
            sample = QFontDatabase().writingSystemSample(system)
            if (option.direction == Qt.LayoutDirection.RightToLeft):
                r.setRight(r.right() - w)
            else:
                r.setLeft(r.left() + w)
            painter.drawText(
                r, Qt.AlignmentFlag.AlignVCenter
                | Qt.AlignmentFlag.AlignLeading | Qt.TextFlag.TextSingleLine,
                sample)
Beispiel #6
0
 def __init__(self, category, builtin, custom, scheduler_config, parent):
     NewsTreeItem.__init__(self, builtin, custom, scheduler_config, parent)
     self.category = category
     self.cdata = get_language(self.category)
     if self.category == _('Scheduled'):
         self.sortq = 0, ''
     elif self.category == _('Custom'):
         self.sortq = 1, ''
     else:
         self.sortq = 2, self.cdata
     self.bold_font = QFont()
     self.bold_font.setBold(True)
     self.bold_font = (self.bold_font)
Beispiel #7
0
 def data(self, index, role):
     try:
         widget = self.widgets[index.row()]
     except:
         return None
     if role == Qt.ItemDataRole.DisplayRole:
         return (widget.config_title())
     if role == Qt.ItemDataRole.DecorationRole:
         return (widget.config_icon())
     if role == Qt.ItemDataRole.FontRole:
         f = QFont()
         f.setBold(True)
         return (f)
     return None
Beispiel #8
0
 def __init__(self, parent=None):
     QTreeWidget.__init__(self, parent)
     self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
     self.customContextMenuRequested.connect(self.show_context_menu)
     self.default_decoration = QIcon(I('blank.png'))
     self.setHeaderHidden(True)
     self.num_of_items = 0
     self.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
     set_no_activate_on_click(self)
     self.itemActivated.connect(self.item_activated)
     self.currentItemChanged.connect(self.current_item_changed)
     self.uuid_map = {}
     self.section_font = QFont(self.font())
     self.section_font.setItalic(True)
Beispiel #9
0
 def __init__(self, parent):
     QTreeWidget.__init__(self, parent)
     self.setHeaderHidden(True)
     self.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
     self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
     self.customContextMenuRequested.connect(self.show_context_menu)
     self.delegate = AnnotsResultsDelegate(self)
     self.setItemDelegate(self.delegate)
     self.section_font = QFont(self.font())
     self.itemDoubleClicked.connect(self.item_activated)
     self.section_font.setItalic(True)
     self.currentItemChanged.connect(self.current_item_changed)
     self.number_of_results = 0
     self.item_map = []
Beispiel #10
0
 def paint(self, painter, option, index):
     QStyledItemDelegate.paint(self, painter, option, index)
     result = index.data(Qt.ItemDataRole.UserRole)
     is_hidden, result_before, result_text, result_after, show_leading_dot = self.result_data(result)
     if result_text is None:
         return
     painter.save()
     try:
         p = option.palette
         c = QPalette.ColorRole.HighlightedText if option.state & QStyle.StateFlag.State_Selected else QPalette.ColorRole.Text
         group = (QPalette.ColorGroup.Active if option.state & QStyle.StateFlag.State_Active else QPalette.ColorGroup.Inactive)
         c = p.color(group, c)
         painter.setPen(c)
         font = option.font
         if self.emphasize_text:
             emphasis_font = QFont(font)
             emphasis_font.setBold(True)
         else:
             emphasis_font = font
         flags = Qt.AlignmentFlag.AlignTop | Qt.TextFlag.TextSingleLine | Qt.TextFlag.TextIncludeTrailingSpaces
         rect = option.rect.adjusted(option.decorationSize.width() + 4 if is_hidden else 0, 0, 0, 0)
         painter.setClipRect(rect)
         before = re.sub(r'\s+', ' ', result_before)
         if show_leading_dot:
             before = '•' + before
         before_width = 0
         if before:
             before_width = painter.boundingRect(rect, flags, before).width()
         after = re.sub(r'\s+', ' ', result_after.rstrip())
         after_width = 0
         if after:
             after_width = painter.boundingRect(rect, flags, after).width()
         ellipsis_width = painter.boundingRect(rect, flags, '...').width()
         painter.setFont(emphasis_font)
         text = re.sub(r'\s+', ' ', result_text)
         match_width = painter.boundingRect(rect, flags, text).width()
         if match_width >= rect.width() - 3 * ellipsis_width:
             efm = QFontMetrics(emphasis_font)
             if show_leading_dot:
                 text = '•' + text
             text = efm.elidedText(text, Qt.TextElideMode.ElideRight, rect.width())
             painter.drawText(rect, flags, text)
         else:
             self.draw_match(
                 painter, flags, before, text, after, rect, before_width, match_width, after_width, ellipsis_width, emphasis_font, font)
     except Exception:
         import traceback
         traceback.print_exc()
     painter.restore()
Beispiel #11
0
 def __init__(self, parent=None):
     QTreeWidget.__init__(self, parent)
     self.setHeaderHidden(True)
     self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
     self.delegate = ResultsDelegate(self)
     self.setItemDelegate(self.delegate)
     self.itemClicked.connect(self.item_activated)
     self.blank_icon = QIcon(I('blank.png'))
     self.not_found_icon = QIcon(I('dialog_warning.png'))
     self.currentItemChanged.connect(self.current_item_changed)
     self.section_font = QFont(self.font())
     self.section_font.setItalic(True)
     self.section_map = {}
     self.search_results = []
     self.item_map = {}
Beispiel #12
0
    def populate(self, phrase, ts, process_space=True):
        phrase_pos = 0
        processed = False
        matches = self.__class__.whitespace.finditer(phrase)
        font = QFont(ts.font)
        if self.valign is not None:
            font.setPixelSize(font.pixelSize() / 1.5)
        fm = QFontMetrics(font)
        single_space_width = fm.width(' ')
        height, descent = fm.height(), fm.descent()
        for match in matches:
            processed = True
            left, right = match.span()
            if not process_space:
                right = left
            space_width = single_space_width * (right - left)
            word = phrase[phrase_pos:left]
            width = fm.width(word)
            if self.current_width + width < self.line_length:
                self.commit(word, width, height, descent, ts, font)
                if space_width > 0 and self.current_width + space_width < self.line_length:
                    self.add_space(space_width)
                phrase_pos = right
                continue

            # Word doesn't fit on line
            if self.hyphenate and len(word) > 3:
                tokens = hyphenate_word(word)
                for i in range(len(tokens) - 2, -1, -1):
                    word = ''.join(tokens[0:i + 1]) + '-'
                    width = fm.width(word)
                    if self.current_width + width < self.line_length:
                        self.commit(word, width, height, descent, ts, font)
                        return phrase_pos + len(word) - 1, True
            if self.current_width < 5:  # Force hyphenation as word is longer than line
                for i in range(len(word) - 5, 0, -5):
                    part = word[:i] + '-'
                    width = fm.width(part)
                    if self.current_width + width < self.line_length:
                        self.commit(part, width, height, descent, ts, font)
                        return phrase_pos + len(part) - 1, True
            # Failed to add word.
            return phrase_pos, True

        if not processed:
            return self.populate(phrase + ' ', ts, False)

        return phrase_pos, False
Beispiel #13
0
 def __init__(self, parent=None, is_half_star=False):
     QComboBox.__init__(self, parent)
     self.addItem(_('Not rated'))
     if is_half_star:
         [self.addItem(stars(x, True)) for x in range(1, 11)]
     else:
         [self.addItem(stars(x)) for x in (2, 4, 6, 8, 10)]
     self.rating_font = QFont(rating_font())
     self.undo_stack = QUndoStack(self)
     self.undo, self.redo = self.undo_stack.undo, self.undo_stack.redo
     self.allow_undo = False
     self.is_half_star = is_half_star
     self.delegate = RatingItemDelegate(self)
     self.view().setItemDelegate(self.delegate)
     self.view().setStyleSheet('QListView { background: palette(window) }\nQListView::item { padding: 6px }')
     self.setMaxVisibleItems(self.count())
     self.currentIndexChanged.connect(self.update_font)
Beispiel #14
0
 def __init__(self, parent=None):
     QTreeWidget.__init__(self, parent)
     self.setHeaderHidden(True)
     self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
     self.delegate = ResultsDelegate(self)
     self.setItemDelegate(self.delegate)
     self.itemClicked.connect(self.item_activated)
     self.blank_icon = QIcon(I('blank.png'))
     self.not_found_icon = QIcon(I('dialog_warning.png'))
     self.currentItemChanged.connect(self.current_item_changed)
     self.section_font = QFont(self.font())
     self.section_font.setItalic(True)
     self.section_map = {}
     self.search_results = []
     self.item_map = {}
     self.gesture_manager = GestureManager(self)
     self.setVerticalScrollMode(QAbstractItemView.ScrollMode.ScrollPerPixel)
Beispiel #15
0
 def apply_theme(self, theme):
     self.theme = theme
     pal = self.palette()
     pal.setColor(QPalette.ColorRole.Base,
                  theme_color(theme, 'Normal', 'bg'))
     pal.setColor(QPalette.ColorRole.AlternateBase,
                  theme_color(theme, 'CursorLine', 'bg'))
     pal.setColor(QPalette.ColorRole.Text,
                  theme_color(theme, 'Normal', 'fg'))
     pal.setColor(QPalette.ColorRole.Highlight,
                  theme_color(theme, 'Visual', 'bg'))
     pal.setColor(QPalette.ColorRole.HighlightedText,
                  theme_color(theme, 'Visual', 'fg'))
     self.setPalette(pal)
     self.tooltip_palette = pal = QPalette()
     pal.setColor(QPalette.ColorRole.ToolTipBase,
                  theme_color(theme, 'Tooltip', 'bg'))
     pal.setColor(QPalette.ColorRole.ToolTipText,
                  theme_color(theme, 'Tooltip', 'fg'))
     self.line_number_palette = pal = QPalette()
     pal.setColor(QPalette.ColorRole.Base,
                  theme_color(theme, 'LineNr', 'bg'))
     pal.setColor(QPalette.ColorRole.Text,
                  theme_color(theme, 'LineNr', 'fg'))
     pal.setColor(QPalette.ColorRole.BrightText,
                  theme_color(theme, 'LineNrC', 'fg'))
     self.match_paren_format = theme_format(theme, 'MatchParen')
     font = self.font()
     ff = tprefs['editor_font_family']
     if ff is None:
         ff = default_font_family()
     font.setFamily(ff)
     font.setPointSize(tprefs['editor_font_size'])
     self.tooltip_font = QFont(font)
     self.tooltip_font.setPointSize(font.pointSize() - 1)
     self.setFont(font)
     self.highlighter.apply_theme(theme)
     w = self.fontMetrics()
     self.number_width = max(
         map(lambda x: w.width(unicode_type(x)), range(10)))
     self.size_hint = QSize(
         self.expected_geometry[0] * w.averageCharWidth(),
         self.expected_geometry[1] * w.height())
     self.highlight_color = theme_color(theme, 'HighlightRegion', 'bg')
     self.highlight_cursor_line()
     self.completion_popup.clear_caches(), self.completion_popup.update()
Beispiel #16
0
    def __init__(self, msg, parent=None, window_title=_('Working')):
        QDialog.__init__(self, parent)

        self._layout = QVBoxLayout()
        self.setLayout(self._layout)
        self.msg = QLabel(msg)
        # self.msg.setWordWrap(True)
        self.font = QFont()
        self.font.setPointSize(self.font.pointSize() + 8)
        self.msg.setFont(self.font)
        self.pi = ProgressIndicator(self)
        self.pi.setDisplaySize(QSize(100, 100))
        self._layout.addWidget(self.pi, 0, Qt.AlignmentFlag.AlignHCenter)
        self._layout.addSpacing(15)
        self._layout.addWidget(self.msg, 0, Qt.AlignmentFlag.AlignHCenter)
        self.start()
        self.setWindowTitle(window_title)
        self.resize(self.sizeHint())
Beispiel #17
0
    def paint_line_numbers(self, ev):
        painter = QPainter(self.line_number_area)
        painter.fillRect(
            ev.rect(), self.line_number_palette.color(QPalette.ColorRole.Base))

        block = self.firstVisibleBlock()
        num = block.blockNumber()
        top = int(
            self.blockBoundingGeometry(block).translated(
                self.contentOffset()).top())
        bottom = top + int(self.blockBoundingRect(block).height())
        current = self.textCursor().block().blockNumber()
        painter.setPen(self.line_number_palette.color(QPalette.ColorRole.Text))

        while block.isValid() and top <= ev.rect().bottom():
            if block.isVisible() and bottom >= ev.rect().top():
                set_bold = False
                set_italic = False
                if current == num:
                    set_bold = True
                if num + 1 in self.clicked_line_numbers:
                    set_italic = True
                painter.save()
                if set_bold or set_italic:
                    f = QFont(self.font())
                    if set_bold:
                        f.setBold(set_bold)
                        painter.setPen(
                            self.line_number_palette.color(
                                QPalette.ColorRole.BrightText))
                    f.setItalic(set_italic)
                    painter.setFont(f)
                else:
                    painter.setFont(self.font())
                painter.drawText(0, top,
                                 self.line_number_area.width() - 5,
                                 self.fontMetrics().height(),
                                 Qt.AlignmentFlag.AlignRight,
                                 unicode_type(num + 1))
                painter.restore()
            block = block.next()
            top = bottom
            bottom = top + int(self.blockBoundingRect(block).height())
            num += 1
Beispiel #18
0
 def __init__(self, parent, icon_name, title):
     QHBoxLayout.__init__(self)
     title_font = QFont()
     title_font.setPointSize(16)
     title_image_label = QLabel(parent)
     pixmap = QPixmap()
     pixmap.load(I(icon_name))
     if pixmap is None:
         error_dialog(parent, _('Restart required'),
                      _('You must restart calibre before using this plugin!'), show=True)
     else:
         title_image_label.setPixmap(pixmap)
     title_image_label.setMaximumSize(32, 32)
     title_image_label.setScaledContents(True)
     self.addWidget(title_image_label)
     shelf_label = QLabel(title, parent)
     shelf_label.setFont(title_font)
     self.addWidget(shelf_label)
     self.insertStretch(-1)
Beispiel #19
0
def generate_masthead(title, output_path=None, width=600, height=60, as_qimage=False, font_family=None):
    init_environment()
    font_family = font_family or cprefs['title_font_family'] or 'Liberation Serif'
    img = QImage(width, height, QImage.Format.Format_ARGB32)
    img.fill(Qt.GlobalColor.white)
    p = QPainter(img)
    p.setRenderHints(QPainter.RenderHint.Antialiasing | QPainter.RenderHint.TextAntialiasing)
    f = QFont(font_family)
    f.setStyleStrategy(QFont.StyleStrategy.PreferAntialias)
    f.setPixelSize((height * 3) // 4), f.setBold(True)
    p.setFont(f)
    p.drawText(img.rect(), Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, sanitize(title))
    p.end()
    if as_qimage:
        return img
    data = pixmap_to_data(img)
    if output_path is None:
        return data
    with open(output_path, 'wb') as f:
        f.write(data)
 def set_value(self, g, val):
     from calibre.gui2.convert.xpath_wizard import XPathEdit
     from calibre.gui2.convert.regex_builder import RegexEdit
     from calibre.gui2.widgets import EncodingComboBox
     if self.set_value_handler(g, val):
         return
     if hasattr(g, 'set_value_for_config'):
         g.set_value_for_config = val
         return
     if isinstance(g, (QSpinBox, QDoubleSpinBox)):
         g.setValue(val)
     elif isinstance(g, (QLineEdit, QTextEdit, QPlainTextEdit)):
         if not val:
             val = ''
         getattr(g, 'setPlainText', getattr(g, 'setText', None))(val)
         getattr(g, 'setCursorPosition', lambda x: x)(0)
     elif isinstance(g, QFontComboBox):
         g.setCurrentFont(QFont(val or ''))
     elif isinstance(g, FontFamilyChooser):
         g.font_family = val
     elif isinstance(g, EncodingComboBox):
         if val:
             g.setEditText(val)
         else:
             g.setCurrentIndex(0)
     elif isinstance(g, QComboBox) and val:
         idx = g.findText(val, Qt.MatchFlag.MatchFixedString)
         if idx < 0:
             g.addItem(val)
             idx = g.findText(val, Qt.MatchFlag.MatchFixedString)
         g.setCurrentIndex(idx)
     elif isinstance(g, QCheckBox):
         g.setCheckState(Qt.CheckState.Checked if bool(val) else Qt.
                         CheckState.Unchecked)
     elif isinstance(g, (XPathEdit, RegexEdit)):
         g.edit.setText(val if val else '')
     else:
         raise Exception('Can\'t set value %s in %s' %
                         (repr(val), unicode_type(g.objectName())))
     self.post_set_value(g, val)
    def initialize_formats(self):
        font_name = gprefs.get('gpm_template_editor_font', None)
        size = gprefs['gpm_template_editor_font_size']
        if font_name is None:
            font = QFont()
            font.setFixedPitch(True)
            font.setPointSize(size)
            font_name = font.family()
        config = self.Config = {}
        config["fontfamily"] = font_name
        app_palette = QApplication.instance().palette()
        for name, color, bold, italic in (
            ("normal", None, False, False),
            ("keyword", app_palette.color(QPalette.ColorRole.Link).name(),
             True, False), ("builtin",
                            app_palette.color(QPalette.ColorRole.Link).name(),
                            False, False), ("identifier", None, False, True),
            ("comment", "#007F00", False, True), ("string", "#808000", False,
                                                  False), ("number", "#924900",
                                                           False, False),
            ("lparen", None, True, True), ("rparen", None, True, True)):
            config["%sfontcolor" % name] = color
            config["%sfontbold" % name] = bold
            config["%sfontitalic" % name] = italic
        base_format = QTextCharFormat()
        base_format.setFontFamily(config["fontfamily"])
        config["fontsize"] = size
        base_format.setFontPointSize(config["fontsize"])

        self.Formats = {}
        for name in ("normal", "keyword", "builtin", "comment", "identifier",
                     "string", "number", "lparen", "rparen"):
            format_ = QTextCharFormat(base_format)
            color = config["%sfontcolor" % name]
            if color:
                format_.setForeground(QColor(color))
            if config["%sfontbold" % name]:
                format_.setFontWeight(QFont.Weight.Bold)
            format_.setFontItalic(config["%sfontitalic" % name])
            self.Formats[name] = format_
Beispiel #22
0
 def data(self, index, role):
     row = index.row()
     try:
         tweak = self.tweaks[row]
     except:
         return None
     if role == Qt.ItemDataRole.DisplayRole:
         return textwrap.fill(tweak.name, 40)
     if role == Qt.ItemDataRole.FontRole and tweak.is_customized:
         ans = QFont()
         ans.setBold(True)
         return ans
     if role == Qt.ItemDataRole.ToolTipRole:
         tt = _('This tweak has its default value')
         if tweak.is_customized:
             tt = '<p>' + _('This tweak has been customized')
             tt += '<pre>'
             for varn, val in iteritems(tweak.custom_values):
                 tt += '%s = %r\n\n' % (varn, val)
         return textwrap.fill(tt)
     if role == Qt.ItemDataRole.UserRole:
         return tweak
     return None
Beispiel #23
0
    def __init__(self, name, plugins, gui_name, parent=None):
        QWidget.__init__(self, parent)
        self._layout = QVBoxLayout()
        self.setLayout(self._layout)
        self.label = QLabel(gui_name)
        self.sep = QFrame(self)
        self.bf = QFont()
        self.bf.setBold(True)
        self.label.setFont(self.bf)
        self.sep.setFrameShape(QFrame.Shape.HLine)
        self._layout.addWidget(self.label)
        self._layout.addWidget(self.sep)

        self.plugins = plugins

        self.bar = QToolBar(self)
        self.bar.setStyleSheet('QToolBar { border: none; background: none }')
        lh = QApplication.instance().line_height
        self.bar.setIconSize(QSize(2 * lh, 2 * lh))
        self.bar.setMovable(False)
        self.bar.setFloatable(False)
        self.bar.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextUnderIcon)
        self._layout.addWidget(self.bar)
        self.actions = []
        for p in plugins:
            target = partial(self.triggered, p)
            ac = self.bar.addAction(QIcon(p.icon),
                                    p.gui_name.replace('&', '&&'), target)
            ac.setToolTip(textwrap.fill(p.description))
            ac.setWhatsThis(textwrap.fill(p.description))
            ac.setStatusTip(p.description)
            self.actions.append(ac)
            w = self.bar.widgetForAction(ac)
            w.setCursor(Qt.CursorShape.PointingHandCursor)
            if hasattr(w, 'setAutoRaise'):
                w.setAutoRaise(True)
            w.setMinimumWidth(100)
Beispiel #24
0
    def paint_line_numbers(self, ev):
        painter = QPainter(self.line_number_area)
        painter.fillRect(ev.rect(), self.line_number_palette.color(QPalette.ColorRole.Base))

        block = self.firstVisibleBlock()
        num = block.blockNumber()
        top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top())
        bottom = top + int(self.blockBoundingRect(block).height())
        painter.setPen(self.line_number_palette.color(QPalette.ColorRole.Text))
        change_starts = {x[0] for x in self.changes}

        while block.isValid() and top <= ev.rect().bottom():
            r = ev.rect()
            if block.isVisible() and bottom >= r.top():
                text = unicode_type(self.line_number_map.get(num, ''))
                is_start = text != '-' and num in change_starts
                if is_start:
                    painter.save()
                    f = QFont(self.font())
                    f.setBold(True)
                    painter.setFont(f)
                    painter.setPen(self.line_number_palette.color(QPalette.ColorRole.BrightText))
                if text == '-':
                    painter.drawLine(r.left() + 2, (top + bottom)//2, r.right() - 2, (top + bottom)//2)
                else:
                    if self.right:
                        painter.drawText(r.left() + 3, top, r.right(), self.fontMetrics().height(),
                                Qt.AlignmentFlag.AlignLeft, text)
                    else:
                        painter.drawText(r.left() + 2, top, r.right() - 5, self.fontMetrics().height(),
                                Qt.AlignmentFlag.AlignRight, text)
                if is_start:
                    painter.restore()
            block = block.next()
            top = bottom
            bottom = top + int(self.blockBoundingRect(block).height())
            num += 1
Beispiel #25
0
 def __init__(self, accounts, subjects, aliases={}, tags={}):
     QAbstractTableModel.__init__(self)
     self.accounts = accounts
     self.subjects = subjects
     self.aliases = aliases
     self.tags = tags
     self.sorted_on = (0, True)
     self.account_order = list(self.accounts)
     self.do_sort()
     self.headers = [
         _('Email'),
         _('Formats'),
         _('Subject'),
         _('Auto send'),
         _('Alias'),
         _('Auto send only tags')
     ]
     self.default_font = QFont()
     self.default_font.setBold(True)
     self.default_font = (self.default_font)
     self.tooltips = [None] + list(
         map(textwrap.fill, [
             _('Formats to email. The first matching format will be sent.'),
             _('Subject of the email to use when sending. When left blank '
               'the title will be used for the subject. Also, the same '
               'templates used for "Save to disk" such as {title} and '
               '{author_sort} can be used here.'), '<p>' +
             _('If checked, downloaded news will be automatically '
               'mailed to this email address '
               '(provided it is in one of the listed formats and has not been filtered by tags).'
               ),
             _('Friendly name to use for this email address'),
             _('If specified, only news with one of these tags will be sent to'
               ' this email address. All news downloads have their title as a'
               ' tag, so you can use this to easily control which news downloads'
               ' are sent to this email address.')
         ]))
Beispiel #26
0
 def build_font_obj(self):
     font_info = qt_app.original_font if self.current_font is None else self.current_font
     font = QFont(*(font_info[:4]))
     font.setStretch(font_info[4])
     return font
Beispiel #27
0
 def family_setter(which, w, val):
     w.setCurrentFont(QFont(val or default_font(which)))
Beispiel #28
0
 def mark_item_as_current(self, item):
     font = QFont(self.font())
     font.setItalic(True)
     font.setBold(True)
     item.setData(0, Qt.ItemDataRole.FontRole, font)
Beispiel #29
0
    def __init__(self,
                 field_metadata,
                 parent=None,
                 revert_tooltip=None,
                 datetime_fmt='MMMM yyyy',
                 blank_as_equal=True,
                 fields=('title', 'authors', 'series', 'tags', 'rating',
                         'publisher', 'pubdate', 'identifiers', 'languages',
                         'comments', 'cover'),
                 db=None):
        QWidget.__init__(self, parent)
        self.l = l = QGridLayout()
        # l.setContentsMargins(0, 0, 0, 0)
        self.setLayout(l)
        revert_tooltip = revert_tooltip or _('Revert %s')
        self.current_mi = None
        self.changed_font = QFont(QApplication.font())
        self.changed_font.setBold(True)
        self.changed_font.setItalic(True)
        self.blank_as_equal = blank_as_equal

        self.widgets = OrderedDict()
        row = 0

        for field in fields:
            m = field_metadata[field]
            dt = m['datatype']
            extra = None
            if 'series' in {field, dt}:
                cls = SeriesEdit
            elif field == 'identifiers':
                cls = IdentifiersEdit
            elif field == 'languages':
                cls = LanguagesEdit
            elif 'comments' in {field, dt}:
                cls = CommentsEdit
            elif 'rating' in {field, dt}:
                cls = RatingsEdit
            elif dt == 'datetime':
                extra = datetime_fmt
                cls = DateEdit
            elif field == 'cover':
                cls = CoverView
            elif dt in {'text', 'enum'}:
                cls = LineEdit
            else:
                continue
            neww = cls(field, True, self, m, extra)
            neww.setObjectName(field)
            connect_lambda(
                neww.changed, self,
                lambda self: self.changed(self.sender().objectName()))
            if isinstance(neww, EditWithComplete):
                try:
                    neww.update_items_cache(db.new_api.all_field_names(field))
                except ValueError:
                    pass  # A one-one field like title
            if isinstance(neww, SeriesEdit):
                neww.set_db(db.new_api)
            oldw = cls(field, False, self, m, extra)
            newl = QLabel('&%s:' % m['name'])
            newl.setBuddy(neww)
            button = RightClickButton(self)
            button.setIcon(QIcon(I('back.png')))
            button.setObjectName(field)
            connect_lambda(
                button.clicked, self,
                lambda self: self.revert(self.sender().objectName()))
            button.setToolTip(revert_tooltip % m['name'])
            if field == 'identifiers':
                button.m = m = QMenu(button)
                button.setMenu(m)
                button.setPopupMode(
                    QToolButton.ToolButtonPopupMode.DelayedPopup)
                m.addAction(button.toolTip()).triggered.connect(button.click)
                m.actions()[0].setIcon(button.icon())
                m.addAction(_('Merge identifiers')).triggered.connect(
                    self.merge_identifiers)
                m.actions()[1].setIcon(QIcon(I('merge.png')))
            elif field == 'tags':
                button.m = m = QMenu(button)
                button.setMenu(m)
                button.setPopupMode(
                    QToolButton.ToolButtonPopupMode.DelayedPopup)
                m.addAction(button.toolTip()).triggered.connect(button.click)
                m.actions()[0].setIcon(button.icon())
                m.addAction(_('Merge tags')).triggered.connect(self.merge_tags)
                m.actions()[1].setIcon(QIcon(I('merge.png')))

            self.widgets[field] = Widgets(neww, oldw, newl, button)
            for i, w in enumerate((newl, neww, button, oldw)):
                c = i if i < 2 else i + 1
                if w is oldw:
                    c += 1
                l.addWidget(w, row, c)
            row += 1

        if 'comments' in self.widgets and not gprefs.get(
                'diff_widget_show_comments_controls', True):
            self.widgets['comments'].new.hide_toolbars()
Beispiel #30
0
 def set_subtitle_font(self, for_ratings=True):
     if for_ratings:
         self.setSubtitleFont(QFont(rating_font()))
     else:
         self.setSubtitleFont(self.font())