Beispiel #1
0
class Background(QWidget):  # {{{

    def __init__(self, parent):
        QWidget.__init__(self, parent)
        self.bcol = QColor(*gprefs['cover_grid_color'])
        self.btex = gprefs['cover_grid_texture']
        self.update_brush()
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

    def update_brush(self):
        self.brush = QBrush(self.bcol)
        if self.btex:
            from calibre.gui2.preferences.texture_chooser import texture_path
            path = texture_path(self.btex)
            if path:
                self.brush.setTexture(QPixmap(path))
        self.update()

    def sizeHint(self):
        return QSize(200, 120)

    def paintEvent(self, ev):
        painter = QPainter(self)
        painter.fillRect(ev.rect(), self.brush)
        painter.end()
Beispiel #2
0
    def set_style(self, style):
        pf = PF(style=style)
        self.styles = {}
        self.normal = self.base_fmt()
        self.background_color = pf.style.background_color
        self.color = 'black'

        for ttype, ndef in pf.style:
            fmt = self.base_fmt()
            fmt.setProperty(fmt.UserProperty, str(ttype))
            if ndef['color']:
                fmt.setForeground(QBrush(QColor('#%s'%ndef['color'])))
                fmt.setUnderlineColor(QColor('#%s'%ndef['color']))
                if ttype == Generic.Output:
                    self.color = '#%s'%ndef['color']
            if ndef['bold']:
                fmt.setFontWeight(QFont.Bold)
            if ndef['italic']:
                fmt.setFontItalic(True)
            if ndef['underline']:
                fmt.setFontUnderline(True)
            if ndef['bgcolor']:
                fmt.setBackground(QBrush(QColor('#%s'%ndef['bgcolor'])))
            if ndef['border']:
                pass # No support for borders

            self.styles[ttype] = fmt
Beispiel #3
0
 def update_brush(self):
     self.brush = QBrush(self.bcol)
     if self.btex:
         from calibre.gui2.preferences.texture_chooser import texture_path
         path = texture_path(self.btex)
         if path:
             self.brush.setTexture(QPixmap(path))
     self.update()
Beispiel #4
0
 def data(self, index, role):
     if not index.isValid():
         return NONE
     row, col = index.row(), index.column()
     if row < 0 or row >= self.rowCount():
         return NONE
     display_plugin = self.display_plugins[row]
     if role in [Qt.DisplayRole, Qt.UserRole]:
         if col == 0:
             return QVariant(display_plugin.name)
         if col == 1:
             if display_plugin.donation_link:
                 return QVariant(_('PayPal'))
         if col == 2:
             return self._get_status(display_plugin)
         if col == 3:
             return QVariant(
                 self._get_display_version(
                     display_plugin.installed_version))
         if col == 4:
             return QVariant(
                 self._get_display_version(
                     display_plugin.available_version))
         if col == 5:
             if role == Qt.UserRole:
                 return self._get_display_release_date(
                     display_plugin.release_date, 'yyyyMMdd')
             else:
                 return self._get_display_release_date(
                     display_plugin.release_date)
         if col == 6:
             return QVariant(
                 self._get_display_version(
                     display_plugin.calibre_required_version))
         if col == 7:
             return QVariant(display_plugin.author)
     elif role == Qt.DecorationRole:
         if col == 0:
             return self._get_status_icon(display_plugin)
         if col == 1:
             if display_plugin.donation_link:
                 return QIcon(I('donate.png'))
     elif role == Qt.ToolTipRole:
         if col == 1 and display_plugin.donation_link:
             return QVariant(
                 _('This plugin is FREE but you can reward the developer for their effort\n'
                   'by donating to them via PayPal.\n\n'
                   'Right-click and choose Donate to reward: ') +
                 display_plugin.author)
         else:
             return self._get_status_tooltip(display_plugin)
     elif role == Qt.ForegroundRole:
         if col != 1:  # Never change colour of the donation column
             if display_plugin.is_deprecated:
                 return QVariant(QBrush(Qt.blue))
             if display_plugin.is_disabled():
                 return QVariant(QBrush(Qt.gray))
     return NONE
Beispiel #5
0
 def makeQPixmap(self, width, height):
     data = numpy.zeros((width, height), float)
     data[...] = (numpy.arange(width) / (width - 1.))[:, numpy.newaxis]
     # make brush image -- diag background, with colormap on top
     img = QPixmap(width, height)
     painter = QPainter(img)
     painter.fillRect(0, 0, width, height, QBrush(QColor("white")))
     painter.fillRect(0, 0, width, height, QBrush(Qt.BDiagPattern))
     painter.drawImage(0, 0, self.colorize(data))
     painter.end()
     return img
Beispiel #6
0
def read_color(col):
    if QColor.isValidColor(col):
        return QBrush(QColor(col))
    if col.startswith('rgb('):
        r, g, b = map(int, (x.strip() for x in col[4:-1].split(',')))
        return QBrush(QColor(r, g, b))
    try:
        r, g, b = col[0:2], col[2:4], col[4:6]
        r, g, b = int(r, 16), int(g, 16), int(b, 16)
        return QBrush(QColor(r, g, b))
    except Exception:
        pass
Beispiel #7
0
def full(p, xmax, ymax):
    p.drawRect(0, 0, xmax, ymax)
    p.drawPolyline(QPoint(0, 0), QPoint(xmax, 0), QPoint(xmax, ymax),
                    QPoint(0, ymax), QPoint(0, 0))
    pp = QPainterPath()
    pp.addRect(0, 0, xmax, ymax)
    p.drawPath(pp)
    p.save()
    for i in xrange(3):
        col = [0, 0, 0, 200]
        col[i] = 255
        p.setOpacity(0.3)
        p.fillRect(0, 0, xmax/10, xmax/10, QBrush(QColor(*col)))
        p.setOpacity(1)
        p.drawRect(0, 0, xmax/10, xmax/10)
        p.translate(xmax/10, xmax/10)
        p.scale(1, 1.5)
    p.restore()

    # p.scale(2, 2)
    # p.rotate(45)
    p.drawPixmap(0, 0, xmax/4, xmax/4, QPixmap(I('library.png')))
    p.drawRect(0, 0, xmax/4, xmax/4)

    f = p.font()
    f.setPointSize(20)
    # f.setLetterSpacing(f.PercentageSpacing, 200)
    f.setUnderline(True)
    # f.setOverline(True)
    # f.setStrikeOut(True)
    f.setFamily('Calibri')
    p.setFont(f)
    # p.setPen(QColor(0, 0, 255))
    # p.scale(2, 2)
    # p.rotate(45)
    p.drawText(QPoint(xmax/3.9, 30), 'Some—text not By’s ū --- Д AV ff ff')

    b = QBrush(Qt.HorPattern)
    b.setColor(QColor(Qt.blue))
    pix = QPixmap(I('console.png'))
    w = xmax/4
    p.fillRect(0, ymax/3, w, w, b)
    p.fillRect(xmax/3, ymax/3, w, w, QBrush(pix))
    x, y = 2*xmax/3, ymax/3
    p.drawTiledPixmap(QRectF(x, y, w, w), pix, QPointF(10, 10))

    x, y = 1, ymax/1.9
    g = QLinearGradient(QPointF(x, y), QPointF(x+w, y+w))
    g.setColorAt(0, QColor('#00f'))
    g.setColorAt(1, QColor('#fff'))
    p.fillRect(x, y, w, w, QBrush(g))
Beispiel #8
0
    def __init__(self, gui):
        QWidget.__init__(self, gui)
        self.setObjectName('jobs_pointer')
        self.setVisible(False)
        self.resize(100, 80)
        self.animation = QPropertyAnimation(self, "geometry", self)
        self.animation.setDuration(750)
        self.animation.setLoopCount(2)
        self.animation.setEasingCurve(QEasingCurve.Linear)
        self.animation.finished.connect(self.hide)

        taily, heady = 0, 55
        self.arrow_path = QPainterPath(QPointF(40, taily))
        self.arrow_path.lineTo(40, heady)
        self.arrow_path.lineTo(20, heady)
        self.arrow_path.lineTo(50, self.height())
        self.arrow_path.lineTo(80, heady)
        self.arrow_path.lineTo(60, heady)
        self.arrow_path.lineTo(60, taily)
        self.arrow_path.closeSubpath()

        c = self.palette().color(QPalette.Active, QPalette.WindowText)
        self.color = QColor(c)
        self.color.setAlpha(100)
        self.brush = QBrush(self.color, Qt.SolidPattern)
Beispiel #9
0
 def do_test(self):
     selections = []
     self.match_locs = []
     if self.regex_valid():
         text = unicode(self.preview.toPlainText())
         regex = unicode(self.regex.text())
         cursor = QTextCursor(self.preview.document())
         extsel = QTextEdit.ExtraSelection()
         extsel.cursor = cursor
         extsel.format.setBackground(QBrush(Qt.yellow))
         try:
             for match in re.finditer(regex, text):
                 es = QTextEdit.ExtraSelection(extsel)
                 es.cursor.setPosition(match.start(),
                                       QTextCursor.MoveAnchor)
                 es.cursor.setPosition(match.end(), QTextCursor.KeepAnchor)
                 selections.append(es)
                 self.match_locs.append((match.start(), match.end()))
         except:
             pass
     self.preview.setExtraSelections(selections)
     if self.match_locs:
         self.next.setEnabled(True)
         self.previous.setEnabled(True)
     self.occurrences.setText(str(len(self.match_locs)))
Beispiel #10
0
 def data(self, index, role):
     if not index.isValid():
         return NONE
     if index.internalId() == 0:
         if role == Qt.DisplayRole:
             category = self.categories[index.row()]
             return QVariant(_("%(plugin_type)s %(plugins)s")%
                     dict(plugin_type=category, plugins=_('plugins')))
     else:
         plugin = self.index_to_plugin(index)
         disabled = is_disabled(plugin)
         if role == Qt.DisplayRole:
             ver = '.'.join(map(str, plugin.version))
             desc = '\n'.join(textwrap.wrap(plugin.description, 100))
             ans='%s (%s) %s %s\n%s'%(plugin.name, ver, _('by'), plugin.author, desc)
             c = plugin_customization(plugin)
             if c and not disabled:
                 ans += _('\nCustomization: ')+c
             if disabled:
                 ans += _('\n\nThis plugin has been disabled')
             return QVariant(ans)
         if role == Qt.DecorationRole:
             return self.disabled_icon if disabled else self.icon
         if role == Qt.ForegroundRole and disabled:
             return QVariant(QBrush(Qt.gray))
         if role == Qt.UserRole:
             return plugin
     return NONE
Beispiel #11
0
 def copy(self):
     ans = GraphicsState()
     ans.fill = QBrush(self.fill)
     ans.stroke = QPen(self.stroke)
     ans.opacity = self.opacity
     ans.transform = self.transform * QTransform()
     ans.brush_origin = QPointF(self.brush_origin)
     ans.clip_updated = self.clip_updated
     ans.do_fill, ans.do_stroke = self.do_fill, self.do_stroke
     return ans
Beispiel #12
0
 def __init__(self):
     self.fill = QBrush(Qt.white)
     self.stroke = QPen()
     self.opacity = 1.0
     self.transform = QTransform()
     self.brush_origin = QPointF()
     self.clip_updated = False
     self.do_fill = False
     self.do_stroke = True
     self.qt_pattern_cache = {}
Beispiel #13
0
def brush(p, xmax, ymax):
    x = 0
    y = 0
    w = xmax / 2
    g = QLinearGradient(QPointF(x, y + w / 3), QPointF(x, y + (2 * w / 3)))
    g.setColorAt(0, QColor('#f00'))
    g.setColorAt(0.5, QColor('#fff'))
    g.setColorAt(1, QColor('#00f'))
    g.setSpread(g.ReflectSpread)
    p.fillRect(x, y, w, w, QBrush(g))
    p.drawRect(x, y, w, w)
Beispiel #14
0
 def drawTiledPixmap(self, rect, pixmap, point):
     self.apply_graphics_state()
     brush = QBrush(pixmap)
     bl = rect.topLeft()
     color, opacity, pattern, do_fill = self.graphics.convert_brush(
         brush, bl-point, 1.0, self.pdf_system,
         self.painter().transform())
     self.pdf.save_stack()
     self.pdf.apply_fill(color, pattern)
     self.pdf.draw_rect(bl.x(), bl.y(), rect.width(), rect.height(),
                         stroke=False, fill=True)
     self.pdf.restore_stack()
Beispiel #15
0
def background(painter, bkgimg):
    maxx = painter.device().width()
    maxy = painter.device().height()

    rimg = QRectF(0, 0, maxx, maxy * .9)
    #
    painter.fillRect(0, 0, maxx, maxy, QBrush(Qt.red, Qt.SolidPattern))
    painter.drawImage(rimg, bkgimg)

    wwh = QColor(255, 255, 255, 128)

    painter.fillRect(0, 2 * maxy / 10, maxx, 4 * maxy / 10,
                     QBrush(wwh, Qt.SolidPattern))

    u = QRectF(0, 9 * maxy / 10, maxx, maxy / 10)
    penHText = QPen(Qt.white)
    painter.setPen(penHText)
    painter.setFont(QFont("Arial", 16, italic=True))
    painter.drawText(
        u, Qt.AlignLeft | Qt.TextIncludeTrailingSpaces | Qt.AlignVCenter,
        " ekskursja.pl/flashcards")
Beispiel #16
0
 def set_color(self):
     r, g, b = gprefs['cover_grid_color']
     pal = QPalette()
     col = QColor(r, g, b)
     pal.setColor(pal.Base, col)
     tex = gprefs['cover_grid_texture']
     if tex:
         from calibre.gui2.preferences.texture_chooser import texture_path
         path = texture_path(tex)
         if path:
             pal.setBrush(pal.Base, QBrush(QPixmap(path)))
     dark = (r + g + b)/3.0 < 128
     pal.setColor(pal.Text, QColor(Qt.white if dark else Qt.black))
     self.setPalette(pal)
     self.delegate.highlight_color = pal.color(pal.Text)
Beispiel #17
0
def full(p, xmax, ymax):
    p.drawRect(0, 0, xmax, ymax)
    p.drawPolyline(QPoint(0, 0), QPoint(xmax, 0), QPoint(xmax, ymax),
                   QPoint(0, ymax), QPoint(0, 0))
    pp = QPainterPath()
    pp.addRect(0, 0, xmax, ymax)
    p.drawPath(pp)
    p.save()
    for i in xrange(3):
        col = [0, 0, 0, 200]
        col[i] = 255
        p.setOpacity(0.3)
        p.fillRect(0, 0, xmax / 10, xmax / 10, QBrush(QColor(*col)))
        p.setOpacity(1)
        p.drawRect(0, 0, xmax / 10, xmax / 10)
        p.translate(xmax / 10, xmax / 10)
        p.scale(1, 1.5)
    p.restore()

    # p.scale(2, 2)
    # p.rotate(45)
    p.drawPixmap(0, 0, xmax / 4, xmax / 4, QPixmap(I('library.png')))
    p.drawRect(0, 0, xmax / 4, xmax / 4)

    f = p.font()
    f.setPointSize(20)
    # f.setLetterSpacing(f.PercentageSpacing, 200)
    f.setUnderline(True)
    # f.setOverline(True)
    # f.setStrikeOut(True)
    f.setFamily('Calibri')
    p.setFont(f)
    # p.setPen(QColor(0, 0, 255))
    # p.scale(2, 2)
    # p.rotate(45)
    p.drawText(QPoint(xmax / 3.9, 30), 'Some—text not By’s ū --- Д AV ff ff')

    b = QBrush(Qt.HorPattern)
    b.setColor(QColor(Qt.blue))
    pix = QPixmap(I('console.png'))
    w = xmax / 4
    p.fillRect(0, ymax / 3, w, w, b)
    p.fillRect(xmax / 3, ymax / 3, w, w, QBrush(pix))
    x, y = 2 * xmax / 3, ymax / 3
    p.drawTiledPixmap(QRectF(x, y, w, w), pix, QPointF(10, 10))

    x, y = 1, ymax / 1.9
    g = QLinearGradient(QPointF(x, y), QPointF(x + w, y + w))
    g.setColorAt(0, QColor('#00f'))
    g.setColorAt(1, QColor('#fff'))
    p.fillRect(x, y, w, w, QBrush(g))
Beispiel #18
0
 def paintEvent(self, ev):
     br = ev.region().boundingRect()
     p = QPainter(self)
     p.setOpacity(0.2)
     p.fillRect(br, QBrush(self.palette().text()))
     p.end()
     QWidget.paintEvent(self, ev)
     p = QPainter(self)
     p.setClipRect(br)
     f = p.font()
     f.setBold(True)
     f.setPointSize(20)
     p.setFont(f)
     p.setPen(Qt.SolidLine)
     r = QRect(0, self.dummy.geometry().top() + 10, self.geometry().width(), 150)
     p.drawText(r, Qt.AlignHCenter | Qt.AlignTop | Qt.TextSingleLine, self.text)
     p.end()
Beispiel #19
0
 def set_color(self):
     r, g, b = gprefs['cover_grid_color']
     pal = QPalette()
     col = QColor(r, g, b)
     pal.setColor(pal.Base, col)
     tex = gprefs['cover_grid_texture']
     if tex:
         from calibre.gui2.preferences.texture_chooser import texture_path
         path = texture_path(tex)
         if path:
             pm = QPixmap(path)
             if not pm.isNull():
                 val = pm.scaled(1, 1).toImage().pixel(0, 0)
                 r, g, b = qRed(val), qGreen(val), qBlue(val)
                 pal.setBrush(pal.Base, QBrush(pm))
     dark = (r + g + b) / 3.0 < 128
     pal.setColor(pal.Text, QColor(Qt.white if dark else Qt.black))
     self.setPalette(pal)
     self.delegate.highlight_color = pal.color(pal.Text)
Beispiel #20
0
 def __init__(self, right=False, parent=None, show_open_in_editor=False):
     PlainTextEdit.__init__(self, parent)
     self.setFrameStyle(0)
     self.show_open_in_editor = show_open_in_editor
     self.side_margin = 0
     self.setContextMenuPolicy(Qt.CustomContextMenu)
     self.customContextMenuRequested.connect(self.show_context_menu)
     self.setFocusPolicy(Qt.NoFocus)
     self.right = right
     self.setReadOnly(True)
     w = self.fontMetrics()
     self.number_width = max(map(lambda x: w.width(str(x)), xrange(10)))
     self.space_width = w.width(' ')
     self.setLineWrapMode(self.WidgetWidth)
     self.setTabStopWidth(tprefs['editor_tab_stop_width'] *
                          self.space_width)
     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.setFont(font)
     font = self.heading_font = QFont(self.font())
     font.setPointSize(int(tprefs['editor_font_size'] * 1.5))
     font.setBold(True)
     theme = get_theme(tprefs['editor_theme'])
     pal = self.palette()
     pal.setColor(pal.Base, theme_color(theme, 'Normal', 'bg'))
     pal.setColor(pal.AlternateBase, theme_color(theme, 'CursorLine', 'bg'))
     pal.setColor(pal.Text, theme_color(theme, 'Normal', 'fg'))
     pal.setColor(pal.Highlight, theme_color(theme, 'Visual', 'bg'))
     pal.setColor(pal.HighlightedText, theme_color(theme, 'Visual', 'fg'))
     self.setPalette(pal)
     self.viewport().setCursor(Qt.ArrowCursor)
     self.line_number_area = LineNumbers(self)
     self.blockCountChanged[int].connect(self.update_line_number_area_width)
     self.updateRequest.connect(self.update_line_number_area)
     self.line_number_palette = pal = QPalette()
     pal.setColor(pal.Base, theme_color(theme, 'LineNr', 'bg'))
     pal.setColor(pal.Text, theme_color(theme, 'LineNr', 'fg'))
     pal.setColor(pal.BrightText, theme_color(theme, 'LineNrC', 'fg'))
     self.line_number_map = LineNumberMap()
     self.search_header_pos = 0
     self.changes, self.headers, self.images = [], [], OrderedDict()
     self.setVerticalScrollBarPolicy(
         Qt.ScrollBarAlwaysOff), self.setHorizontalScrollBarPolicy(
             Qt.ScrollBarAlwaysOff)
     self.diff_backgrounds = {
         'replace':
         theme_color(theme, 'DiffReplace', 'bg'),
         'insert':
         theme_color(theme, 'DiffInsert', 'bg'),
         'delete':
         theme_color(theme, 'DiffDelete', 'bg'),
         'replacereplace':
         theme_color(theme, 'DiffReplaceReplace', 'bg'),
         'boundary':
         QBrush(theme_color(theme, 'Normal', 'fg'), Qt.Dense7Pattern),
     }
     self.diff_foregrounds = {
         'replace': theme_color(theme, 'DiffReplace', 'fg'),
         'insert': theme_color(theme, 'DiffInsert', 'fg'),
         'delete': theme_color(theme, 'DiffDelete', 'fg'),
         'boundary': QColor(0, 0, 0, 0),
     }
     for x in ('replacereplace', 'insert', 'delete'):
         f = QTextCharFormat()
         f.setBackground(self.diff_backgrounds[x])
         setattr(self, '%s_format' % x, f)
Beispiel #21
0
    def __init__(self, parent, view, row, link_delegate):
        QDialog.__init__(self, parent)
        self.normal_brush = QBrush(Qt.white)
        self.marked_brush = QBrush(Qt.lightGray)
        self.marked = None
        self.gui = parent
        self.splitter = QSplitter(self)
        self._l = l = QVBoxLayout(self)
        self.setLayout(l)
        l.addWidget(self.splitter)

        self.cover = CoverView(self)
        self.cover.resizeEvent = self.cover_view_resized
        self.cover.cover_changed.connect(self.cover_changed)
        self.cover_pixmap = None
        self.cover.sizeHint = self.details_size_hint
        self.splitter.addWidget(self.cover)

        self.details = QWebView(self)
        self.details.sizeHint = self.details_size_hint
        self.details.page().setLinkDelegationPolicy(
            self.details.page().DelegateAllLinks)
        self.details.linkClicked.connect(self.link_clicked)
        self.css = css()
        self.link_delegate = link_delegate
        self.details.setAttribute(Qt.WA_OpaquePaintEvent, False)
        palette = self.details.palette()
        self.details.setAcceptDrops(False)
        palette.setBrush(QPalette.Base, Qt.transparent)
        self.details.page().setPalette(palette)

        self.c = QWidget(self)
        self.c.l = l2 = QGridLayout(self.c)
        self.c.setLayout(l2)
        l2.addWidget(self.details, 0, 0, 1, -1)
        self.splitter.addWidget(self.c)

        self.fit_cover = QCheckBox(_('Fit &cover within view'), self)
        self.fit_cover.setChecked(
            gprefs.get('book_info_dialog_fit_cover', True))
        l2.addWidget(self.fit_cover, l2.rowCount(), 0, 1, -1)
        self.previous_button = QPushButton(QIcon(I('previous.png')),
                                           _('&Previous'), self)
        self.previous_button.clicked.connect(self.previous)
        l2.addWidget(self.previous_button, l2.rowCount(), 0)
        self.next_button = QPushButton(QIcon(I('next.png')), _('&Next'), self)
        self.next_button.clicked.connect(self.next)
        l2.addWidget(self.next_button, l2.rowCount() - 1, 1)

        self.view = view
        self.current_row = None
        self.refresh(row)
        self.view.selectionModel().currentChanged.connect(self.slave)
        self.fit_cover.stateChanged.connect(self.toggle_cover_fit)
        self.ns = QShortcut(QKeySequence('Alt+Right'), self)
        self.ns.activated.connect(self.next)
        self.ps = QShortcut(QKeySequence('Alt+Left'), self)
        self.ps.activated.connect(self.previous)
        self.next_button.setToolTip(
            _('Next [%s]') %
            unicode(self.ns.key().toString(QKeySequence.NativeText)))
        self.previous_button.setToolTip(
            _('Previous [%s]') %
            unicode(self.ps.key().toString(QKeySequence.NativeText)))

        geom = QCoreApplication.instance().desktop().availableGeometry(self)
        screen_height = geom.height() - 100
        screen_width = geom.width() - 100
        self.resize(max(int(screen_width / 2), 700), screen_height)
        saved_layout = gprefs.get('book_info_dialog_layout', None)
        if saved_layout is not None:
            try:
                self.restoreGeometry(saved_layout[0])
                self.splitter.restoreState(saved_layout[1])
            except Exception:
                pass
Beispiel #22
0
 def paintEvent(self, ev):
     p = QPainter(self)
     p.fillRect(ev.region().boundingRect(), QBrush(QColor(200, 200, 200, 220), Qt.SolidPattern))
     p.end()
     QLabel.paintEvent(self, ev)
Beispiel #23
0
 def makeBrush(self, width, height):
     return QBrush(self.makeQImage(width, height))
Beispiel #24
0
def pen(p, xmax, ymax):
    pix = QPixmap(I('console.png'))
    pen = QPen(QBrush(pix), 60)
    p.setPen(pen)
    p.drawRect(0, xmax / 3, xmax / 3, xmax / 2)
Beispiel #25
0
class DocumentView(QWebView):  # {{{

    magnification_changed = pyqtSignal(object)
    DISABLED_BRUSH = QBrush(Qt.lightGray, Qt.Dense5Pattern)

    def initialize_view(self, debug_javascript=False):
        self.setRenderHints(QPainter.Antialiasing|QPainter.TextAntialiasing|QPainter.SmoothPixmapTransform)
        self.flipper = SlideFlip(self)
        self.is_auto_repeat_event = False
        self.debug_javascript = debug_javascript
        self.shortcuts =  Shortcuts(SHORTCUTS, 'shortcuts/viewer')
        self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding))
        self._size_hint = QSize(510, 680)
        self.initial_pos = 0.0
        self.to_bottom = False
        self.document = Document(self.shortcuts, parent=self,
                debug_javascript=debug_javascript)
        self.setPage(self.document)
        self.inspector = WebInspector(self, self.document)
        self.manager = None
        self._reference_mode = False
        self._ignore_scrollbar_signals = False
        self.loading_url = None
        self.loadFinished.connect(self.load_finished)
        self.connect(self.document, SIGNAL('linkClicked(QUrl)'), self.link_clicked)
        self.connect(self.document, SIGNAL('linkHovered(QString,QString,QString)'), self.link_hovered)
        self.connect(self.document, SIGNAL('selectionChanged()'), self.selection_changed)
        self.connect(self.document, SIGNAL('animated_scroll_done()'),
                self.animated_scroll_done, Qt.QueuedConnection)
        self.document.page_turn.connect(self.page_turn_requested)
        copy_action = self.pageAction(self.document.Copy)
        copy_action.setIcon(QIcon(I('convert.png')))
        d = self.document
        self.unimplemented_actions = list(map(self.pageAction,
            [d.DownloadImageToDisk, d.OpenLinkInNewWindow, d.DownloadLinkToDisk,
                d.OpenImageInNewWindow, d.OpenLink, d.Reload, d.InspectElement]))

        self.search_online_action = QAction(QIcon(I('search.png')), '', self)
        self.search_online_action.triggered.connect(self.search_online)
        self.addAction(self.search_online_action)
        self.dictionary_action = QAction(QIcon(I('dictionary.png')),
                _('&Lookup in dictionary'), self)
        self.dictionary_action.triggered.connect(self.lookup)
        self.addAction(self.dictionary_action)
        self.image_popup = ImagePopup(self)
        self.table_popup = TablePopup(self)
        self.view_image_action = QAction(QIcon(I('view-image.png')), _('View &image...'), self)
        self.view_image_action.triggered.connect(self.image_popup)
        self.view_table_action = QAction(QIcon(I('view.png')), _('View &table...'), self)
        self.view_table_action.triggered.connect(self.popup_table)
        self.search_action = QAction(QIcon(I('dictionary.png')),
                _('&Search for next occurrence'), self)
        self.search_action.triggered.connect(self.search_next)
        self.addAction(self.search_action)

        self.goto_location_action = QAction(_('Go to...'), self)
        self.goto_location_menu = m = QMenu(self)
        self.goto_location_actions = a = {
                'Next Page': self.next_page,
                'Previous Page': self.previous_page,
                'Section Top' : partial(self.scroll_to, 0),
                'Document Top': self.goto_document_start,
                'Section Bottom':partial(self.scroll_to, 1),
                'Document Bottom': self.goto_document_end,
                'Next Section': self.goto_next_section,
                'Previous Section': self.goto_previous_section,
        }
        for name, key in [(_('Next Section'), 'Next Section'),
                (_('Previous Section'), 'Previous Section'),
                (None, None),
                (_('Document Start'), 'Document Top'),
                (_('Document End'), 'Document Bottom'),
                (None, None),
                (_('Section Start'), 'Section Top'),
                (_('Section End'), 'Section Bottom'),
                (None, None),
                (_('Next Page'), 'Next Page'),
                (_('Previous Page'), 'Previous Page')]:
            if key is None:
                m.addSeparator()
            else:
                m.addAction(name, a[key], self.shortcuts.get_sequences(key)[0])
        self.goto_location_action.setMenu(self.goto_location_menu)
        self.grabGesture(Qt.SwipeGesture)

        self.restore_fonts_action = QAction(_('Default font size'), self)
        self.restore_fonts_action.setCheckable(True)
        self.restore_fonts_action.triggered.connect(self.restore_font_size)

    def goto_next_section(self, *args):
        if self.manager is not None:
            self.manager.goto_next_section()

    def goto_previous_section(self, *args):
        if self.manager is not None:
            self.manager.goto_previous_section()

    def goto_document_start(self, *args):
        if self.manager is not None:
            self.manager.goto_start()

    def goto_document_end(self, *args):
        if self.manager is not None:
            self.manager.goto_end()

    @property
    def copy_action(self):
        return self.pageAction(self.document.Copy)

    def animated_scroll_done(self):
        if self.manager is not None:
            self.manager.scrolled(self.document.scroll_fraction)

    def reference_mode(self, enable):
        self._reference_mode = enable
        self.document.reference_mode(enable)

    def goto(self, ref):
        self.document.goto(ref)

    def goto_bookmark(self, bm):
        self.document.goto_bookmark(bm)

    def config(self, parent=None):
        self.document.do_config(parent)
        if self.document.in_fullscreen_mode:
            self.document.switch_to_fullscreen_mode()
        self.setFocus(Qt.OtherFocusReason)

    def load_theme(self, theme_id):
        themes = load_themes()
        theme = themes[theme_id]
        opts = config(theme).parse()
        self.document.apply_settings(opts)
        if self.document.in_fullscreen_mode:
            self.document.switch_to_fullscreen_mode()
        self.setFocus(Qt.OtherFocusReason)

    def bookmark(self):
        return self.document.bookmark()

    def selection_changed(self):
        if self.manager is not None:
            self.manager.selection_changed(unicode(self.document.selectedText()))

    def _selectedText(self):
        t = unicode(self.selectedText()).strip()
        if not t:
            return u''
        if len(t) > 40:
            t = t[:40] + u'...'
        t = t.replace(u'&', u'&&')
        return _("S&earch Google for '%s'")%t

    def popup_table(self):
        html = self.document.extract_node()
        self.table_popup(html, QUrl.fromLocalFile(self.last_loaded_path),
                         self.document.font_magnification_step)

    def contextMenuEvent(self, ev):
        mf = self.document.mainFrame()
        r = mf.hitTestContent(ev.pos())
        img = r.pixmap()
        elem = r.element()
        if elem.isNull():
            elem = r.enclosingBlockElement()
        table = None
        parent = elem
        while not parent.isNull():
            if (unicode(parent.tagName()) == u'table' or
                unicode(parent.localName()) == u'table'):
                table = parent
                break
            parent = parent.parent()
        self.image_popup.current_img = img
        self.image_popup.current_url = r.imageUrl()
        menu = self.document.createStandardContextMenu()
        for action in self.unimplemented_actions:
            menu.removeAction(action)

        if not img.isNull():
            menu.addAction(self.view_image_action)
        if table is not None:
            self.document.mark_element.emit(table)
            menu.addAction(self.view_table_action)

        text = self._selectedText()
        if text and img.isNull():
            self.search_online_action.setText(text)
            for x, sc in (('search_online', 'Search online'), ('dictionary', 'Lookup word'), ('search', 'Next occurrence')):
                ac = getattr(self, '%s_action' % x)
                menu.addAction(ac.icon(), '%s [%s]' % (unicode(ac.text()), ','.join(self.shortcuts.get_shortcuts(sc))), ac.trigger)

        if not text and img.isNull():
            menu.addSeparator()
            if self.manager.action_back.isEnabled():
                menu.addAction(self.manager.action_back)
            if self.manager.action_forward.isEnabled():
                menu.addAction(self.manager.action_forward)
            menu.addAction(self.goto_location_action)

            if self.manager is not None:
                menu.addSeparator()
                menu.addAction(self.manager.action_table_of_contents)

                menu.addSeparator()
                menu.addAction(self.manager.action_font_size_larger)
                self.restore_fonts_action.setChecked(self.multiplier == 1)
                menu.addAction(self.restore_fonts_action)
                menu.addAction(self.manager.action_font_size_smaller)

        menu.addSeparator()
        menu.addAction(_('Inspect'), self.inspect)

        if not text and img.isNull() and self.manager is not None:
            menu.addSeparator()
            if (not self.document.show_controls or self.document.in_fullscreen_mode) and self.manager is not None:
                menu.addAction(self.manager.toggle_toolbar_action)
            menu.addAction(self.manager.action_full_screen)

            menu.addSeparator()
            menu.addAction(self.manager.action_quit)

        for plugin in self.document.all_viewer_plugins:
            plugin.customize_context_menu(menu, ev, r)
        menu.exec_(ev.globalPos())

    def inspect(self):
        self.inspector.show()
        self.inspector.raise_()
        self.pageAction(self.document.InspectElement).trigger()

    def lookup(self, *args):
        if self.manager is not None:
            t = unicode(self.selectedText()).strip()
            if t:
                self.manager.lookup(t.split()[0])

    def search_next(self):
        if self.manager is not None:
            t = unicode(self.selectedText()).strip()
            if t:
                self.manager.search.set_search_string(t)

    def search_online(self):
        t = unicode(self.selectedText()).strip()
        if t:
            url = 'https://www.google.com/search?q=' + QUrl().toPercentEncoding(t)
            open_url(QUrl.fromEncoded(url))

    def set_manager(self, manager):
        self.manager = manager
        self.scrollbar = manager.horizontal_scrollbar
        self.connect(self.scrollbar, SIGNAL('valueChanged(int)'), self.scroll_horizontally)

    def scroll_horizontally(self, amount):
        self.document.scroll_to(y=self.document.ypos, x=amount)

    @property
    def scroll_pos(self):
        return (self.document.ypos, self.document.ypos +
                self.document.window_height)

    @property
    def viewport_rect(self):
        # (left, top, right, bottom) of the viewport in document co-ordinates
        # When in paged mode, left and right are the numbers of the columns
        # at the left edge and *after* the right edge of the viewport
        d = self.document
        if d.in_paged_mode:
            try:
                l, r = d.column_boundaries
            except ValueError:
                l, r = (0, 1)
        else:
            l, r = d.xpos, d.xpos + d.window_width
        return (l, d.ypos, r, d.ypos + d.window_height)

    def link_hovered(self, link, text, context):
        link, text = unicode(link), unicode(text)
        if link:
            self.setCursor(Qt.PointingHandCursor)
        else:
            self.unsetCursor()

    def link_clicked(self, url):
        if self.manager is not None:
            self.manager.link_clicked(url)

    def sizeHint(self):
        return self._size_hint

    @dynamic_property
    def scroll_fraction(self):
        def fget(self):
            return self.document.scroll_fraction
        def fset(self, val):
            self.document.scroll_fraction = float(val)
        return property(fget=fget, fset=fset)

    @property
    def hscroll_fraction(self):
        return self.document.hscroll_fraction

    @property
    def content_size(self):
        return self.document.width, self.document.height

    @dynamic_property
    def current_language(self):
        def fget(self):
            return self.document.current_language
        def fset(self, val):
            self.document.current_language = val
        return property(fget=fget, fset=fset)

    def search(self, text, backwards=False):
        flags = self.document.FindBackward if backwards else self.document.FindFlags(0)
        found = self.document.findText(text, flags)
        if found and self.document.in_paged_mode:
            self.document.javascript('paged_display.snap_to_selection()')
        return found

    def path(self):
        return os.path.abspath(unicode(self.url().toLocalFile()))

    def load_path(self, path, pos=0.0):
        self.initial_pos = pos
        self.last_loaded_path = path

        def callback(lu):
            self.loading_url = lu
            if self.manager is not None:
                self.manager.load_started()

        load_html(path, self, codec=getattr(path, 'encoding', 'utf-8'), mime_type=getattr(path,
            'mime_type', 'text/html'), pre_load_callback=callback)
        entries = set()
        for ie in getattr(path, 'index_entries', []):
            if ie.start_anchor:
                entries.add(ie.start_anchor)
            if ie.end_anchor:
                entries.add(ie.end_anchor)
        self.document.index_anchors = entries

    def initialize_scrollbar(self):
        if getattr(self, 'scrollbar', None) is not None:
            if self.document.in_paged_mode:
                self.scrollbar.setVisible(False)
                return
            delta = self.document.width - self.size().width()
            if delta > 0:
                self._ignore_scrollbar_signals = True
                self.scrollbar.blockSignals(True)
                self.scrollbar.setRange(0, delta)
                self.scrollbar.setValue(0)
                self.scrollbar.setSingleStep(1)
                self.scrollbar.setPageStep(int(delta/10.))
            self.scrollbar.setVisible(delta > 0)
            self.scrollbar.blockSignals(False)
            self._ignore_scrollbar_signals = False

    def load_finished(self, ok):
        if self.loading_url is None:
            # An <iframe> finished loading
            return
        self.loading_url = None
        self.document.load_javascript_libraries()
        self.document.after_load(self.last_loaded_path)
        self._size_hint = self.document.mainFrame().contentsSize()
        scrolled = False
        if self.to_bottom:
            self.to_bottom = False
            self.initial_pos = 1.0
        if self.initial_pos > 0.0:
            scrolled = True
        self.scroll_to(self.initial_pos, notify=False)
        self.initial_pos = 0.0
        self.update()
        self.initialize_scrollbar()
        self.document.reference_mode(self._reference_mode)
        if self.manager is not None:
            spine_index = self.manager.load_finished(bool(ok))
            if spine_index > -1:
                self.document.set_reference_prefix('%d.'%(spine_index+1))
            if scrolled:
                self.manager.scrolled(self.document.scroll_fraction,
                        onload=True)

        if self.flipper.isVisible():
            if self.flipper.running:
                self.flipper.setVisible(False)
            else:
                self.flipper(self.current_page_image(),
                        duration=self.document.page_flip_duration)

    @classmethod
    def test_line(cls, img, y):
        'Test if line contains pixels of exactly the same color'
        start = img.pixel(0, y)
        for i in range(1, img.width()):
            if img.pixel(i, y) != start:
                return False
        return True

    def current_page_image(self, overlap=-1):
        if overlap < 0:
            overlap = self.height()
        img = QImage(self.width(), overlap, QImage.Format_ARGB32_Premultiplied)
        painter = QPainter(img)
        painter.setRenderHints(self.renderHints())
        self.document.mainFrame().render(painter, QRegion(0, 0, self.width(), overlap))
        painter.end()
        return img

    def find_next_blank_line(self, overlap):
        img = self.current_page_image(overlap)
        for i in range(overlap-1, -1, -1):
            if self.test_line(img, i):
                self.scroll_by(y=i, notify=False)
                return
        self.scroll_by(y=overlap)

    def previous_page(self):
        if self.flipper.running and not self.is_auto_repeat_event:
            return
        if self.loading_url is not None:
            return
        epf = self.document.enable_page_flip and not self.is_auto_repeat_event

        if self.document.in_paged_mode:
            loc = self.document.javascript(
                    'paged_display.previous_screen_location()', typ='int')
            if loc < 0:
                if self.manager is not None:
                    if epf:
                        self.flipper.initialize(self.current_page_image(),
                                forwards=False)
                    self.manager.previous_document()
            else:
                if epf:
                    self.flipper.initialize(self.current_page_image(),
                            forwards=False)
                self.document.scroll_to(x=loc, y=0)
                if epf:
                    self.flipper(self.current_page_image(),
                            duration=self.document.page_flip_duration)
                if self.manager is not None:
                    self.manager.scrolled(self.scroll_fraction)

            return

        delta_y = self.document.window_height - 25
        if self.document.at_top:
            if self.manager is not None:
                self.to_bottom = True
                if epf:
                    self.flipper.initialize(self.current_page_image(), False)
                self.manager.previous_document()
        else:
            opos = self.document.ypos
            upper_limit = opos - delta_y
            if upper_limit < 0:
                upper_limit = 0
            if upper_limit < opos:
                if epf:
                    self.flipper.initialize(self.current_page_image(),
                            forwards=False)
                self.document.scroll_to(self.document.xpos, upper_limit)
                if epf:
                    self.flipper(self.current_page_image(),
                            duration=self.document.page_flip_duration)
                if self.manager is not None:
                    self.manager.scrolled(self.scroll_fraction)

    def next_page(self):
        if self.flipper.running and not self.is_auto_repeat_event:
            return
        if self.loading_url is not None:
            return
        epf = self.document.enable_page_flip and not self.is_auto_repeat_event

        if self.document.in_paged_mode:
            loc = self.document.javascript(
                    'paged_display.next_screen_location()', typ='int')
            if loc < 0:
                if self.manager is not None:
                    if epf:
                        self.flipper.initialize(self.current_page_image())
                    self.manager.next_document()
            else:
                if epf:
                    self.flipper.initialize(self.current_page_image())
                self.document.scroll_to(x=loc, y=0)
                if epf:
                    self.flipper(self.current_page_image(),
                            duration=self.document.page_flip_duration)
                if self.manager is not None:
                    self.manager.scrolled(self.scroll_fraction)

            return

        window_height = self.document.window_height
        document_height = self.document.height
        ddelta = document_height - window_height
        # print '\nWindow height:', window_height
        # print 'Document height:', self.document.height

        delta_y = window_height - 25
        if self.document.at_bottom or ddelta <= 0:
            if self.manager is not None:
                if epf:
                    self.flipper.initialize(self.current_page_image())
                self.manager.next_document()
        elif ddelta < 25:
            self.scroll_by(y=ddelta)
            return
        else:
            oopos = self.document.ypos
            # print 'Original position:', oopos
            self.document.set_bottom_padding(0)
            opos = self.document.ypos
            # print 'After set padding=0:', self.document.ypos
            if opos < oopos:
                if self.manager is not None:
                    if epf:
                        self.flipper.initialize(self.current_page_image())
                    self.manager.next_document()
                return
            # oheight = self.document.height
            lower_limit = opos + delta_y  # Max value of top y co-ord after scrolling
            max_y = self.document.height - window_height  # The maximum possible top y co-ord
            if max_y < lower_limit:
                padding = lower_limit - max_y
                if padding == window_height:
                    if self.manager is not None:
                        if epf:
                            self.flipper.initialize(self.current_page_image())
                        self.manager.next_document()
                    return
                # print 'Setting padding to:', lower_limit - max_y
                self.document.set_bottom_padding(lower_limit - max_y)
            if epf:
                self.flipper.initialize(self.current_page_image())
            # print 'Document height:', self.document.height
            # print 'Height change:', (self.document.height - oheight)
            max_y = self.document.height - window_height
            lower_limit = min(max_y, lower_limit)
            # print 'Scroll to:', lower_limit
            if lower_limit > opos:
                self.document.scroll_to(self.document.xpos, lower_limit)
            actually_scrolled = self.document.ypos - opos
            # print 'After scroll pos:', self.document.ypos
            # print 'Scrolled by:', self.document.ypos - opos
            self.find_next_blank_line(window_height - actually_scrolled)
            # print 'After blank line pos:', self.document.ypos
            if epf:
                self.flipper(self.current_page_image(),
                        duration=self.document.page_flip_duration)
            if self.manager is not None:
                self.manager.scrolled(self.scroll_fraction)
            # print 'After all:', self.document.ypos

    def page_turn_requested(self, backwards):
        if backwards:
            self.previous_page()
        else:
            self.next_page()

    def scroll_by(self, x=0, y=0, notify=True):
        old_pos = (self.document.xpos if self.document.in_paged_mode else
                self.document.ypos)
        self.document.scroll_by(x, y)
        new_pos = (self.document.xpos if self.document.in_paged_mode else
                self.document.ypos)
        if notify and self.manager is not None and new_pos != old_pos:
            self.manager.scrolled(self.scroll_fraction)

    def scroll_to(self, pos, notify=True):
        if self._ignore_scrollbar_signals:
            return
        old_pos = (self.document.xpos if self.document.in_paged_mode else
                self.document.ypos)
        if self.document.in_paged_mode:
            if isinstance(pos, basestring):
                self.document.jump_to_anchor(pos)
            else:
                self.document.scroll_fraction = pos
        else:
            if isinstance(pos, basestring):
                self.document.jump_to_anchor(pos)
            else:
                if pos >= 1:
                    self.document.scroll_to(0, self.document.height)
                else:
                    y = int(math.ceil(
                            pos*(self.document.height-self.document.window_height)))
                    self.document.scroll_to(0, y)

        new_pos = (self.document.xpos if self.document.in_paged_mode else
                self.document.ypos)
        if notify and self.manager is not None and new_pos != old_pos:
            self.manager.scrolled(self.scroll_fraction)

    @dynamic_property
    def multiplier(self):
        def fget(self):
            return self.zoomFactor()
        def fset(self, val):
            self.setZoomFactor(val)
            self.magnification_changed.emit(val)
        return property(fget=fget, fset=fset)

    def magnify_fonts(self, amount=None):
        if amount is None:
            amount = self.document.font_magnification_step
        with self.document.page_position:
            self.multiplier += amount
        return self.document.scroll_fraction

    def shrink_fonts(self, amount=None):
        if amount is None:
            amount = self.document.font_magnification_step
        if self.multiplier >= amount:
            with self.document.page_position:
                self.multiplier -= amount
        return self.document.scroll_fraction

    def restore_font_size(self):
        with self.document.page_position:
            self.multiplier = 1
        return self.document.scroll_fraction

    def changeEvent(self, event):
        if event.type() == event.EnabledChange:
            self.update()
        return QWebView.changeEvent(self, event)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHints(self.renderHints())
        self.document.mainFrame().render(painter, event.region())
        if not self.isEnabled():
            painter.fillRect(event.region().boundingRect(), self.DISABLED_BRUSH)
        painter.end()

    def wheelEvent(self, event):
        mods = event.modifiers()
        if mods & Qt.CTRL:
            if self.manager is not None and event.delta() != 0:
                (self.manager.font_size_larger if event.delta() > 0 else
                        self.manager.font_size_smaller)()
                return

        if self.document.in_paged_mode:
            if abs(event.delta()) < 15:
                return
            typ = 'screen' if self.document.wheel_flips_pages else 'col'
            direction = 'next' if event.delta() < 0 else 'previous'
            loc = self.document.javascript('paged_display.%s_%s_location()'%(
                direction, typ), typ='int')
            if loc > -1:
                self.document.scroll_to(x=loc, y=0)
                if self.manager is not None:
                    self.manager.scrolled(self.scroll_fraction)
                event.accept()
            elif self.manager is not None:
                if direction == 'next':
                    self.manager.next_document()
                else:
                    self.manager.previous_document()
                event.accept()
            return

        if event.delta() < -14:
            if self.document.wheel_flips_pages:
                self.next_page()
                event.accept()
                return
            if self.document.at_bottom:
                self.scroll_by(y=15)  # at_bottom can lie on windows
                if self.manager is not None:
                    self.manager.next_document()
                    event.accept()
                    return
        elif event.delta() > 14:
            if self.document.wheel_flips_pages:
                self.previous_page()
                event.accept()
                return

            if self.document.at_top:
                if self.manager is not None:
                    self.manager.previous_document()
                    event.accept()
                    return

        ret = QWebView.wheelEvent(self, event)

        scroll_amount = (event.delta() / 120.0) * .2 * -1
        if event.orientation() == Qt.Vertical:
            self.scroll_by(0, self.document.viewportSize().height() * scroll_amount)
        else:
            self.scroll_by(self.document.viewportSize().width() * scroll_amount, 0)

        if self.manager is not None:
            self.manager.scrolled(self.scroll_fraction)
        return ret

    def keyPressEvent(self, event):
        if not self.handle_key_press(event):
            return QWebView.keyPressEvent(self, event)

    def paged_col_scroll(self, forward=True, scroll_past_end=True):
        dir = 'next' if forward else 'previous'
        loc = self.document.javascript(
                'paged_display.%s_col_location()'%dir, typ='int')
        if loc > -1:
            self.document.scroll_to(x=loc, y=0)
            self.manager.scrolled(self.document.scroll_fraction)
        elif scroll_past_end:
            (self.manager.next_document() if forward else
                    self.manager.previous_document())

    def handle_key_press(self, event):
        handled = True
        key = self.shortcuts.get_match(event)
        func = self.goto_location_actions.get(key, None)
        if func is not None:
            self.is_auto_repeat_event = event.isAutoRepeat()
            try:
                func()
            finally:
                self.is_auto_repeat_event = False
        elif key == 'Down':
            if self.document.in_paged_mode:
                self.paged_col_scroll(scroll_past_end=not
                        self.document.line_scrolling_stops_on_pagebreaks)
            else:
                if (not self.document.line_scrolling_stops_on_pagebreaks and
                        self.document.at_bottom):
                    self.manager.next_document()
                else:
                    self.scroll_by(y=15)
        elif key == 'Up':
            if self.document.in_paged_mode:
                self.paged_col_scroll(forward=False, scroll_past_end=not
                        self.document.line_scrolling_stops_on_pagebreaks)
            else:
                if (not self.document.line_scrolling_stops_on_pagebreaks and
                        self.document.at_top):
                    self.manager.previous_document()
                else:
                    self.scroll_by(y=-15)
        elif key == 'Left':
            if self.document.in_paged_mode:
                self.paged_col_scroll(forward=False)
            else:
                self.scroll_by(x=-15)
        elif key == 'Right':
            if self.document.in_paged_mode:
                self.paged_col_scroll()
            else:
                self.scroll_by(x=15)
        elif key == 'Back':
            if self.manager is not None:
                self.manager.back(None)
        elif key == 'Forward':
            if self.manager is not None:
                self.manager.forward(None)
        else:
            handled = False
        return handled

    def resizeEvent(self, event):
        if self.manager is not None:
            self.manager.viewport_resize_started(event)
        return QWebView.resizeEvent(self, event)

    def event(self, ev):
        if ev.type() == ev.Gesture:
            swipe = ev.gesture(Qt.SwipeGesture)
            if swipe is not None:
                self.handle_swipe(swipe)
                return True
        return QWebView.event(self, ev)

    def handle_swipe(self, swipe):
        if swipe.state() == Qt.GestureFinished:
            if swipe.horizontalDirection() == QSwipeGesture.Left:
                self.previous_page()
            elif swipe.horizontalDirection() == QSwipeGesture.Right:
                self.next_page()
            elif swipe.verticalDirection() == QSwipeGesture.Up:
                self.goto_previous_section()
            elif swipe.horizontalDirection() == QSwipeGesture.Down:
                self.goto_next_section()

    def mouseReleaseEvent(self, ev):
        opos = self.document.ypos
        ret = QWebView.mouseReleaseEvent(self, ev)
        if self.manager is not None and opos != self.document.ypos:
            self.manager.internal_link_clicked(opos)
            self.manager.scrolled(self.scroll_fraction)
        return ret
Beispiel #26
0
 def _setupHistogramPlot(self):
     self._histplot.setCanvasBackground(QColor("lightgray"))
     self._histplot.setAxisFont(QwtPlot.yLeft, QApplication.font())
     self._histplot.setAxisFont(QwtPlot.xBottom, QApplication.font())
     # add histogram curves
     self._histcurve1 = TiggerPlotCurve()
     self._histcurve2 = TiggerPlotCurve()
     self._histcurve1.setStyle(QwtPlotCurve.Steps)
     self._histcurve2.setStyle(QwtPlotCurve.Steps)
     self._histcurve1.setPen(QPen(Qt.NoPen))
     self._histcurve1.setBrush(QBrush(QColor("slategrey")))
     pen = QPen(QColor("red"))
     pen.setWidth(1)
     self._histcurve2.setPen(pen)
     self._histcurve1.setZ(0)
     self._histcurve2.setZ(100)
     #    self._histcurve1.attach(self._histplot)
     self._histcurve2.attach(self._histplot)
     # add maxbin and half-max curves
     self._line_0 = self.HistogramLineMarker(self._histplot, color="grey50", linestyle=Qt.SolidLine,
                                             align=Qt.AlignTop | Qt.AlignLeft, z=90)
     self._line_mean = self.HistogramLineMarker(self._histplot, color="black", linestyle=Qt.SolidLine,
                                                align=Qt.AlignBottom | Qt.AlignRight, z=91,
                                                label="mean", zlabel=151)
     self._line_std = self.HistogramLineMarker(self._histplot, color="black", linestyle=Qt.SolidLine,
                                               align=Qt.AlignTop | Qt.AlignRight, z=91,
                                               label="std", zlabel=151)
     sym = QwtSymbol()
     sym.setStyle(QwtSymbol.VLine)
     sym.setSize(8)
     self._line_std.line.setSymbol(sym)
     self._line_maxbin = self.HistogramLineMarker(self._histplot, color="green", linestyle=Qt.DotLine,
                                                  align=Qt.AlignTop | Qt.AlignRight, z=92,
                                                  label="max bin", zlabel=150)
     self._line_halfmax = self.HistogramLineMarker(self._histplot, color="green", linestyle=Qt.DotLine,
                                                   align=Qt.AlignBottom | Qt.AlignRight, z=90,
                                                   label="half-max", yaxis=QwtPlot.yLeft)
     # add current range
     self._rangebox = TiggerPlotCurve()
     self._rangebox.setStyle(QwtPlotCurve.Steps)
     self._rangebox.setYAxis(QwtPlot.yRight)
     self._rangebox.setPen(QPen(Qt.NoPen))
     self._rangebox.setBrush(QBrush(QColor("darkgray")))
     self._rangebox.setZ(50)
     self._rangebox.attach(self._histplot)
     self._rangebox2 = TiggerPlotCurve()
     self._rangebox2.setStyle(QwtPlotCurve.Sticks)
     self._rangebox2.setYAxis(QwtPlot.yRight)
     self._rangebox2.setZ(60)
     #  self._rangebox2.attach(self._histplot)
     # add intensity transfer function
     self._itfcurve = TiggerPlotCurve()
     self._itfcurve.setStyle(QwtPlotCurve.Lines)
     self._itfcurve.setPen(QPen(QColor("blue")))
     self._itfcurve.setYAxis(QwtPlot.yRight)
     self._itfcurve.setZ(120)
     self._itfcurve.attach(self._histplot)
     self._itfmarker = TiggerPlotMarker()
     label = QwtText("ITF")
     label.setColor(QColor("blue"))
     self._itfmarker.setLabel(label)
     try:
         self._itfmarker.setSpacing(0)
     except AttributeError:
         pass
     self._itfmarker.setLabelAlignment(Qt.AlignTop | Qt.AlignRight)
     self._itfmarker.setZ(120)
     self._itfmarker.attach(self._histplot)
     # add colorbar
     self._cb_item = self.ColorBarPlotItem(1, 1 + self.ColorBarHeight)
     self._cb_item.setYAxis(QwtPlot.yRight)
     self._cb_item.attach(self._histplot)
     # add pickers
     self._hist_minpicker = self.HistLimitPicker(self._histplot, "low: %(x).4g")
     self._hist_minpicker.setMousePattern(QwtEventPattern.MouseSelect1, Qt.LeftButton)
     QObject.connect(self._hist_minpicker, SIGNAL("selected(const QwtDoublePoint &)"), self._selectLowLimit)
     self._hist_maxpicker = self.HistLimitPicker(self._histplot, "high: %(x).4g")
     self._hist_maxpicker.setMousePattern(QwtEventPattern.MouseSelect1, Qt.RightButton)
     QObject.connect(self._hist_maxpicker, SIGNAL("selected(const QwtDoublePoint &)"), self._selectHighLimit)
     self._hist_maxpicker1 = self.HistLimitPicker(self._histplot, "high: %(x).4g")
     self._hist_maxpicker1.setMousePattern(QwtEventPattern.MouseSelect1, Qt.LeftButton, Qt.CTRL)
     QObject.connect(self._hist_maxpicker1, SIGNAL("selected(const QwtDoublePoint &)"), self._selectHighLimit)
     self._hist_zoompicker = self.HistLimitPicker(self._histplot, label="zoom",
                                                  tracker_mode=QwtPicker.AlwaysOn, track=self._trackHistCoordinates,
                                                  color="black",
                                                  mode=QwtPicker.RectSelection,
                                                  rubber_band=QwtPicker.RectRubberBand)
     self._hist_zoompicker.setMousePattern(QwtEventPattern.MouseSelect1, Qt.LeftButton, Qt.SHIFT)
     QObject.connect(self._hist_zoompicker, SIGNAL("selected(const QwtDoubleRect &)"), self._zoomHistogramIntoRect)