def screen_pos_size(): ###e this copies code in main.py -- main.py should call this
    """
    Return (x,y),(w,h), where the main screen area
    (not including menubar, for Mac) is in a rect of size w,h,
    topleft at x,y. Note that x,y is 0,0 except for Mac.
    Current implementation guesses Mac menubar size since it doesn't
    know how to measure it.
    """
    # Create desktop widget to obtain screen resolution
    dtop = QDesktopWidget()
    screensize = QRect (dtop.screenGeometry (0))

    if is_macintosh():
        # menubar_height = 44 was measured (approximately) on an iMac G5 20 inch
        # screen; I don't know if it's the same on all Macs (or whether it can
        # vary with OS or user settings). (Is there any way of getting this info
        # from Qt? #e)
        menubar_height = 44
    else:
        menubar_height = 0

    screen_w = screensize.width()
    screen_h = screensize.height() # of which menubar_height is in use at the top

    x,y = 0,0
    w,h = screen_w, screen_h

    y += menubar_height
    h -= menubar_height

    return (x,y), (w,h)
Exemplo n.º 2
0
 def paintEvent(self, event):
     QWidget.paintEvent(self, event)
     pmap = self._pixmap
     if pmap.isNull():
         return
     w, h = pmap.width(), pmap.height()
     ow, oh = w, h
     cw, ch = self.rect().width(), self.rect().height()
     scaled, nw, nh = fit_image(w, h, cw, ch)
     if scaled:
         pmap = pmap.scaled(nw, nh, Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
     w, h = pmap.width(), pmap.height()
     x = int(abs(cw - w) / 2.0)
     y = int(abs(ch - h) / 2.0)
     target = QRect(x, y, w, h)
     p = QPainter(self)
     p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
     p.drawPixmap(target, pmap)
     if self.draw_border:
         pen = QPen()
         pen.setWidth(self.BORDER_WIDTH)
         p.setPen(pen)
         p.drawRect(target)
     if self.show_size:
         sztgt = target.adjusted(0, 0, 0, -4)
         f = p.font()
         f.setBold(True)
         p.setFont(f)
         sz = u"\u00a0%d x %d\u00a0" % (ow, oh)
         flags = Qt.AlignBottom | Qt.AlignRight | Qt.TextSingleLine
         szrect = p.boundingRect(sztgt, flags, sz)
         p.fillRect(szrect.adjusted(0, 0, 0, 4), QColor(0, 0, 0, 200))
         p.setPen(QPen(QColor(255, 255, 255)))
         p.drawText(sztgt, flags, sz)
     p.end()
Exemplo n.º 3
0
def drag_icon(self, cover, multiple):
    cover = cover.scaledToHeight(120, Qt.SmoothTransformation)
    if multiple:
        base_width = cover.width()
        base_height = cover.height()
        base = QImage(base_width+21, base_height+21,
                QImage.Format_ARGB32_Premultiplied)
        base.fill(QColor(255, 255, 255, 0).rgba())
        p = QPainter(base)
        rect = QRect(20, 0, base_width, base_height)
        p.fillRect(rect, QColor('white'))
        p.drawRect(rect)
        rect.moveLeft(10)
        rect.moveTop(10)
        p.fillRect(rect, QColor('white'))
        p.drawRect(rect)
        rect.moveLeft(0)
        rect.moveTop(20)
        p.fillRect(rect, QColor('white'))
        p.save()
        p.setCompositionMode(p.CompositionMode_SourceAtop)
        p.drawImage(rect.topLeft(), cover)
        p.restore()
        p.drawRect(rect)
        p.end()
        cover = base
    return QPixmap.fromImage(cover)
Exemplo n.º 4
0
 def paintEvent(self, event):
     canvas_size = self.rect()
     width = self.current_pixmap_size.width()
     extrax = canvas_size.width() - width
     if extrax < 0:
         extrax = 0
     x = int(extrax/2.)
     height = self.current_pixmap_size.height()
     extray = canvas_size.height() - height
     if extray < 0:
         extray = 0
     y = int(extray/2.)
     target = QRect(x, y, width, height)
     p = QPainter(self)
     p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
     p.drawPixmap(target, self.pixmap.scaled(target.size(),
         Qt.KeepAspectRatio, Qt.SmoothTransformation))
     if gprefs['bd_overlay_cover_size']:
         sztgt = target.adjusted(0, 0, 0, -4)
         f = p.font()
         f.setBold(True)
         p.setFont(f)
         sz = u'\u00a0%d x %d\u00a0'%(self.pixmap.width(), self.pixmap.height())
         flags = Qt.AlignBottom|Qt.AlignRight|Qt.TextSingleLine
         szrect = p.boundingRect(sztgt, flags, sz)
         p.fillRect(szrect.adjusted(0, 0, 0, 4), QColor(0, 0, 0, 200))
         p.setPen(QPen(QColor(255,255,255)))
         p.drawText(sztgt, flags, sz)
     p.end()
Exemplo n.º 5
0
 def draw(self, painter, width, palette):
     flags = self.FLAGS | (Qt.AlignRight if self.right_align else Qt.AlignLeft)
     rect = QRect(self.rect)
     if self.right_align:
         rect.setRight(width - self.SIDE_MARGIN)
     painter.setPen(palette.color(self.color_role) if self.override_color is None else self.override_color)
     br = painter.drawText(rect, flags, self.text)
     if self.swatch is not None:
         r = QRect(br.right() + self.SIDE_MARGIN // 2, br.top() + 2, br.height() - 4, br.height() - 4)
         painter.fillRect(r, self.swatch)
Exemplo n.º 6
0
 def paint(self, painter, option, index):
     QStyledItemDelegate.paint(self, painter, option, index)
     style = QApplication.style()
     waiting = self.timer.isActive() and index.data(Qt.UserRole).toBool()
     if waiting:
         rect = QRect(0, 0, self.spinner_width, self.spinner_width)
         rect.moveCenter(option.rect.center())
         self.draw_spinner(painter, rect)
     else:
         # Ensure the cover is rendered over any selection rect
         style.drawItemPixmap(painter, option.rect, Qt.AlignTop|Qt.AlignHCenter,
             QPixmap(index.data(Qt.DecorationRole)))
Exemplo n.º 7
0
 def paintEvent(self, event):
     canvas_size = self.rect()
     width = self.current_pixmap_size.width()
     extrax = canvas_size.width() - width
     if extrax < 0: extrax = 0
     x = int(extrax/2.)
     height = self.current_pixmap_size.height()
     extray = canvas_size.height() - height
     if extray < 0: extray = 0
     y = int(extray/2.)
     target = QRect(x, y, width, height)
     p = QPainter(self)
     p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
     p.drawPixmap(target, self.pixmap.scaled(target.size(),
         Qt.KeepAspectRatio, Qt.SmoothTransformation))
     p.end()
Exemplo n.º 8
0
    def do_layout(self):
        fm = self.fontMetrics()
        bounding_rect = lambda text: fm.boundingRect(0, 0, 10000, 10000, Cell.FLAGS, text)
        line_spacing = 2
        side_margin = Cell.SIDE_MARGIN
        self.rows = []
        ypos = line_spacing + (1 if self.is_first else 0)
        if 'href' in self.data:
            name = self.data['href']
            if isinstance(name, list):
                name = self.html_name
            br1 = bounding_rect(name)
            sel = self.data['selector'] or ''
            if self.data['type'] == 'inline':
                sel = 'style=""'
            br2 = bounding_rect(sel)
            self.hyperlink_rect = QRect(side_margin, ypos, br1.width(), br1.height())
            self.rows.append([
                Cell(name, self.hyperlink_rect, color_role=QPalette.Link),
                Cell(sel, QRect(br1.right() + side_margin, ypos, br2.width(), br2.height()), right_align=True)
            ])
            ypos += max(br1.height(), br2.height()) + 2 * line_spacing

        for prop in self.data['properties']:
            text = prop.name + ':\xa0'
            br1 = bounding_rect(text)
            vtext = prop.value + '\xa0' + ('!' if prop.important else '') + prop.important
            br2 = bounding_rect(vtext)
            self.rows.append([
                Cell(text, QRect(side_margin, ypos, br1.width(), br1.height()), color_role=QPalette.LinkVisited, is_overriden=prop.is_overriden),
                Cell(vtext, QRect(br1.right() + side_margin, ypos, br2.width(), br2.height()), swatch=prop.color, is_overriden=prop.is_overriden)
            ])
            ypos += max(br1.height(), br2.height()) + line_spacing

        self.height_hint = ypos + line_spacing
        self.width_hint = max(row[-1].rect.right() + side_margin for row in self.rows) if self.rows else 0
Exemplo n.º 9
0
 def rect_at(self, frac):
     return QRect(self.point_at(frac), self.size())
Exemplo n.º 10
0
 def boundingBox(self):
     r = QRect()
     for i in self.indicators:
         r = r.united( i.s.geometry())
     return r
Exemplo n.º 11
0
class Declaration(QWidget):

    hyperlink_activated = pyqtSignal(object)

    def __init__(self, html_name, data, is_first=False, parent=None):
        QWidget.__init__(self, parent)
        self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum)
        self.data = data
        self.is_first = is_first
        self.html_name = html_name
        self.do_layout()
        self.setMouseTracking(True)

    def do_layout(self):
        fm = self.fontMetrics()
        bounding_rect = lambda text: fm.boundingRect(0, 0, 10000, 10000, Cell.FLAGS, text)
        line_spacing = 2
        side_margin = Cell.SIDE_MARGIN
        self.rows = []
        ypos = line_spacing + (1 if self.is_first else 0)
        if 'href' in self.data:
            name = self.data['href']
            if isinstance(name, list):
                name = self.html_name
            br1 = bounding_rect(name)
            sel = self.data['selector'] or ''
            if self.data['type'] == 'inline':
                sel = 'style=""'
            br2 = bounding_rect(sel)
            self.hyperlink_rect = QRect(side_margin, ypos, br1.width(), br1.height())
            self.rows.append([
                Cell(name, self.hyperlink_rect, color_role=QPalette.Link),
                Cell(sel, QRect(br1.right() + side_margin, ypos, br2.width(), br2.height()), right_align=True)
            ])
            ypos += max(br1.height(), br2.height()) + 2 * line_spacing

        for prop in self.data['properties']:
            text = prop.name + ':\xa0'
            br1 = bounding_rect(text)
            vtext = prop.value + '\xa0' + ('!' if prop.important else '') + prop.important
            br2 = bounding_rect(vtext)
            self.rows.append([
                Cell(text, QRect(side_margin, ypos, br1.width(), br1.height()), color_role=QPalette.LinkVisited, is_overriden=prop.is_overriden),
                Cell(vtext, QRect(br1.right() + side_margin, ypos, br2.width(), br2.height()), swatch=prop.color, is_overriden=prop.is_overriden)
            ])
            ypos += max(br1.height(), br2.height()) + line_spacing

        self.height_hint = ypos + line_spacing
        self.width_hint = max(row[-1].rect.right() + side_margin for row in self.rows) if self.rows else 0

    def sizeHint(self):
        return QSize(self.width_hint, self.height_hint)

    def paintEvent(self, ev):
        p = QPainter(self)
        p.setClipRect(ev.rect())
        palette = self.palette()
        p.setPen(palette.color(QPalette.WindowText))
        if not self.is_first:
            p.drawLine(0, 0, self.width(), 0)
        try:
            for row in self.rows:
                for cell in row:
                    p.save()
                    try:
                        cell.draw(p, self.width(), palette)
                    finally:
                        p.restore()

        finally:
            p.end()

    def mouseMoveEvent(self, ev):
        if hasattr(self, 'hyperlink_rect'):
            pos = ev.pos()
            hovering = self.hyperlink_rect.contains(pos)
            self.update_hover(hovering)
            cursor = Qt.ArrowCursor
            for r, row in enumerate(self.rows):
                for cell in row:
                    if cell.rect.contains(pos):
                        cursor = Qt.PointingHandCursor if cell.rect is self.hyperlink_rect else Qt.IBeamCursor
                    if r == 0:
                        break
                if cursor != Qt.ArrowCursor:
                    break
            self.setCursor(cursor)
        return QWidget.mouseMoveEvent(self, ev)

    def mousePressEvent(self, ev):
        if hasattr(self, 'hyperlink_rect'):
            pos = ev.pos()
            if self.hyperlink_rect.contains(pos):
                self.emit_hyperlink_activated()
        return QWidget.mousePressEvent(self, ev)

    def emit_hyperlink_activated(self):
        dt = self.data['type']
        data = {'type':dt, 'name':self.html_name, 'syntax':'html'}
        if dt == 'inline':  # style attribute
            data['sourceline_address'] = self.data['href']
        elif dt == 'elem':  # <style> tag
            data['sourceline_address'] = self.data['href']
            data['rule_address'] = self.data['rule_address']
        else:  # stylesheet
            data['name'] = self.data['href']
            data['rule_address'] = self.data['rule_address']
            data['syntax'] = 'css'
        self.hyperlink_activated.emit(data)

    def leaveEvent(self, ev):
        self.update_hover(False)
        self.setCursor(Qt.ArrowCursor)
        return QWidget.leaveEvent(self, ev)

    def update_hover(self, hovering):
        cell = self.rows[0][0]
        if (hovering and cell.override_color is None) or (
                not hovering and cell.override_color is not None):
            cell.override_color = QColor(Qt.red) if hovering else None
            self.update()
Exemplo n.º 12
0
        def numberbarPaint(self, number_bar, event):
            font_metrics = self.fontMetrics()
            # edit_font = self.font()
            current_line = self.document().findBlock(
                self.textCursor().position()).blockNumber() + 1

            block = self.firstVisibleBlock()
            # block = self.document().findBlock(2)
            # block = self.document().firstBlock()
            line_count = block.blockNumber()
            painter = QPainter(number_bar)

            # baseBrush=self.palette().light()
            # baseBrush.setColor(Qt.darkGray)
            painter.fillRect(event.rect(), self.palette().light())

            # Iterate over all visible text blocks in the document.
            while block.isValid():
                line_count += 1
                block_bounding_rect = self.blockBoundingGeometry(
                    block).translated(self.contentOffset())

                block_top = block_bounding_rect.top()
                # block_top_middle=block_top + font_metrics.height()/2

                # f.write('line_count: %s , %s' % (line_count,block_top))
                # Check if the position of the block is out side of the visible
                # area.
                if not block.isVisible() or block_top >= event.rect().bottom():
                    break
                    # pass

                # We want the line number for the selected line to be bold.
                if line_count == current_line:
                    font = painter.font()
                    font.setBold(True)
                    # font.setPointSize(font.pointSize() * 2)
                    # painter.setFont(font)
                else:
                    font = painter.font()
                    font.setBold(False)
                    # font.setPointSize(font.pointSize() * 2)

                # print 'painter font size',font.pointSize(),
                # '--->',font.pointSize()*2
                edit_font_size = self.font().pointSize()
                if edit_font_size > 0:
                    font.setPointSize(edit_font_size)

                painter.setFont(font)

                # font.setPointSize(20)

                # Draw the line number right justified at the position of the
                # line.
                paint_rect = QRect(
                    0, block_top, number_bar.width(),
                    font_metrics.height())  # edit_font.pixelSize())
                painter.drawText(paint_rect, Qt.AlignRight,
                                 unicode(line_count))

                block = block.next()

            painter.end()
Exemplo n.º 13
0
 def paint(self, painter, option, index):
     QStyledItemDelegate.paint(self, painter, option, QModelIndex())  # draw the hover and selection highlights
     m = index.model()
     db = m.db
     try:
         book_id = db.id(index.row())
     except (ValueError, IndexError, KeyError):
         return
     if book_id in m.ids_to_highlight_set:
         painter.save()
         try:
             painter.setPen(self.highlight_color)
             painter.setRenderHint(QPainter.Antialiasing, True)
             painter.drawRoundedRect(option.rect, 10, 10, Qt.RelativeSize)
         finally:
             painter.restore()
     marked = db.data.get_marked(book_id)
     db = db.new_api
     cdata = self.cover_cache[book_id]
     device_connected = self.parent().gui.device_connected is not None
     on_device = device_connected and db.field_for('ondevice', book_id)
     painter.save()
     right_adjust = 0
     try:
         rect = option.rect
         rect.adjust(self.MARGIN, self.MARGIN, -self.MARGIN, -self.MARGIN)
         orect = QRect(rect)
         if cdata is None or cdata is False:
             title = db.field_for('title', book_id, default_value='')
             authors = ' & '.join(db.field_for('authors', book_id, default_value=()))
             painter.setRenderHint(QPainter.TextAntialiasing, True)
             painter.drawText(rect, Qt.AlignCenter|Qt.TextWordWrap, '%s\n\n%s' % (title, authors))
             if cdata is False:
                 self.render_queue.put(book_id)
         else:
             if self.title_height != 0:
                 trect = QRect(rect)
                 rect.setBottom(rect.bottom() - self.title_height)
             if self.animating is not None and self.animating.row() == index.row():
                 cdata = cdata.scaled(cdata.size() * self._animated_size)
             dx = max(0, int((rect.width() - cdata.width())/2.0))
             dy = max(0, rect.height() - cdata.height())
             right_adjust = dx
             rect.adjust(dx, dy, -dx, 0)
             painter.drawPixmap(rect, cdata)
             if self.title_height != 0:
                 rect = trect
                 rect.setTop(rect.bottom() - self.title_height + 5)
                 painter.setRenderHint(QPainter.TextAntialiasing, True)
                 title = db.field_for('title', book_id, default_value='')
                 metrics = painter.fontMetrics()
                 painter.drawText(rect, Qt.AlignCenter|Qt.TextSingleLine,
                                  metrics.elidedText(title, Qt.ElideRight, rect.width()))
         if marked:
             try:
                 p = self.marked_emblem
             except AttributeError:
                 p = self.marked_emblem = QPixmap(I('rating.png')).scaled(48, 48, transformMode=Qt.SmoothTransformation)
             drect = QRect(orect)
             drect.setLeft(drect.left() + right_adjust)
             drect.setRight(drect.left() + p.width())
             drect.setBottom(drect.bottom() - self.title_height)
             drect.setTop(drect.bottom() - p.height())
             painter.drawPixmap(drect, p)
         if on_device:
             try:
                 p = self.on_device_emblem
             except AttributeError:
                 p = self.on_device_emblem = QPixmap(I('ok.png')).scaled(48, 48, transformMode=Qt.SmoothTransformation)
             drect = QRect(orect)
             drect.setRight(drect.right() - right_adjust)
             drect.setBottom(drect.bottom() - self.title_height)
             drect.setTop(drect.bottom() - p.height() + 1)
             drect.setLeft(drect.right() - p.width() + 1)
             painter.drawPixmap(drect, p)
     finally:
         painter.restore()
Exemplo n.º 14
0
    def dump(self, items, out_stream, pdf_metadata):
        opts = self.opts
        page_size = get_page_size(self.opts)
        xdpi, ydpi = self.view.logicalDpiX(), self.view.logicalDpiY()
        # We cannot set the side margins in the webview as there is no right
        # margin for the last page (the margins are implemented with
        # -webkit-column-gap)
        ml, mr = opts.margin_left, opts.margin_right
        self.doc = PdfDevice(out_stream, page_size=page_size, left_margin=ml,
                             top_margin=0, right_margin=mr, bottom_margin=0,
                             xdpi=xdpi, ydpi=ydpi, errors=self.log.error,
                             debug=self.log.debug, compress=not
                             opts.uncompressed_pdf,
                             mark_links=opts.pdf_mark_links)
        self.footer = opts.pdf_footer_template
        if self.footer:
            self.footer = self.footer.strip()
        if not self.footer and opts.pdf_page_numbers:
            self.footer = '<p style="text-align:center; text-indent: 0">_PAGENUM_</p>'
        self.header = opts.pdf_header_template
        if self.header:
            self.header = self.header.strip()
        min_margin = 36
        if self.footer and opts.margin_bottom < min_margin:
            self.log.warn('Bottom margin is too small for footer, increasing it.')
            opts.margin_bottom = min_margin
        if self.header and opts.margin_top < min_margin:
            self.log.warn('Top margin is too small for header, increasing it.')
            opts.margin_top = min_margin

        self.page.setViewportSize(QSize(self.doc.width(), self.doc.height()))
        self.render_queue = items
        self.total_items = len(items)

        mt, mb = map(self.doc.to_px, (opts.margin_top, opts.margin_bottom))
        self.margin_top, self.margin_bottom = map(lambda x:int(floor(x)), (mt, mb))

        self.painter = QPainter(self.doc)
        self.doc.set_metadata(title=pdf_metadata.title,
                              author=pdf_metadata.author,
                              tags=pdf_metadata.tags, mi=pdf_metadata.mi)
        self.doc_title = pdf_metadata.title
        self.doc_author = pdf_metadata.author
        self.painter.save()
        try:
            if self.cover_data is not None:
                p = QPixmap()
                try:
                    p.loadFromData(self.cover_data)
                except TypeError:
                    self.log.warn('This ebook does not have a raster cover, cannot generate cover for PDF'
                                  '. Cover type: %s' % type(self.cover_data))
                if not p.isNull():
                    self.doc.init_page()
                    draw_image_page(QRect(*self.doc.full_page_rect),
                            self.painter, p,
                            preserve_aspect_ratio=self.opts.preserve_cover_aspect_ratio)
                    self.doc.end_page()
        finally:
            self.painter.restore()

        QTimer.singleShot(0, self.render_book)
        if self.loop.exec_() == 1:
            raise Exception('PDF Output failed, see log for details')

        if self.toc is not None and len(self.toc) > 0:
            self.doc.add_outline(self.toc)

        self.painter.end()

        if self.doc.errors_occurred:
            raise Exception('PDF Output failed, see log for details')
Exemplo n.º 15
0
 def resizeEvent(self, ev):
     QPlainTextEdit.resizeEvent(self, ev)
     cr = self.contentsRect()
     self.line_number_area.setGeometry(
         QRect(cr.left(), cr.top(), self.line_number_area_width(),
               cr.height()))
Exemplo n.º 16
0
 def drag_icon(self, cover, multiple):
     cover = cover.scaledToHeight(120, Qt.SmoothTransformation)
     if multiple:
         base_width = cover.width()
         base_height = cover.height()
         base = QImage(base_width+21, base_height+21,
                 QImage.Format_ARGB32_Premultiplied)
         base.fill(QColor(255, 255, 255, 0).rgba())
         p = QPainter(base)
         rect = QRect(20, 0, base_width, base_height)
         p.fillRect(rect, QColor('white'))
         p.drawRect(rect)
         rect.moveLeft(10)
         rect.moveTop(10)
         p.fillRect(rect, QColor('white'))
         p.drawRect(rect)
         rect.moveLeft(0)
         rect.moveTop(20)
         p.fillRect(rect, QColor('white'))
         p.save()
         p.setCompositionMode(p.CompositionMode_SourceAtop)
         p.drawImage(rect.topLeft(), cover)
         p.restore()
         p.drawRect(rect)
         p.end()
         cover = base
     return QPixmap.fromImage(cover)
Exemplo n.º 17
0
def pre_main_show(win):
    """
    Do whatever should be done after the main window is created
    but before it's first shown.
    """

    # Determine the screen resolution and compute the normal window size for NE-1
    # [bruce 041230 corrected this for Macintosh, and made sure it never exceeds
    #  screen size even on a very small screen.]
    # [bruce 050118 further modified this and removed some older comments
    #  (see cvs for those); also split out some code into platform.py.]
    from platform_dependent.PlatformDependent import screen_pos_size
    ((x0, y0), (screen_w, screen_h)) = screen_pos_size()
    # note: y0 is nonzero on mac, due to menubar at top of screen.

    # use 85% of screen width and 90% of screen height, or more if that would be
    # less than 780 by 560 pixels, but never more than the available space.
    norm_w = int(min(screen_w - 2, max(780, screen_w * 0.85)))
    norm_h = int(min(screen_h - 2, max(560, screen_h * 0.90)))
    #bruce 050118 reduced max norm_h to never overlap mac menubar (bugfix?)

    # determine normal window origin
    # [bruce 041230 changed this to center it, but feel free to change this back
    #  by changing the next line to center_it = 0]
    center_it = 1
    if center_it:
        # centered in available area
        norm_x = (screen_w - norm_w) / 2 + x0
        norm_y = (screen_h - norm_h) / 2 + y0
    else:
        # at the given absolute position within the available area
        # (but moved towards (0,0) from that, if necessary to keep it all on-screen)
        want_x = 4  # Left (4 pixels)
        want_y = 36  # Top (36 pixels)
        norm_x = min(want_x, (screen_w - norm_w)) + x0
        norm_y = min(want_y, (screen_h - norm_h)) + y0

    # Set the main window geometry, hopefully before the caller shows the window
    from PyQt4.Qt import QRect
    win.setGeometry(QRect(norm_x, norm_y, norm_w, norm_h))

    ###e it might be good to register this as the default geom. in the prefs system, and use that to implement "restore defaults"

    # After the above (whose side effects on main window geom. are used as defaults by the following code),
    # load any mainwindow geometry present in prefs db. [bruce 051218 new feature; see also new "save" features in UserPrefs.py]
    from utilities.debug import print_compact_stack
    try:
        # this code is similar to debug.py's _debug_load_window_layout
        from ne1_ui.prefs.Preferences import load_window_pos_size
        from utilities.prefs_constants import mainwindow_geometry_prefs_key_prefix
        keyprefix = mainwindow_geometry_prefs_key_prefix
        load_window_pos_size(win, keyprefix)
        win._ok_to_autosave_geometry_changes = True
    except:
        print_compact_stack(
            "exception while loading/setting main window pos/size from prefs db: "
        )
        win.setGeometry(QRect(norm_x, norm_y, norm_w, norm_h))

    _initialize_custom_display_modes(win)

    ### TODO: this would be a good place to add miscellaneous commands to the UI,
    # provided they are fully supported (not experimental, unlikely to cause bugs when added)
    # and won't take a lot of runtime to add. Otherwise they can be added after the
    # main window is shown. [bruce 071005 comment] ###@@@

    return  # from pre_main_show
Exemplo n.º 18
0
# Global imports
from __future__ import print_function
import sys
from PyQt4.QtGui import QApplication

# Local imports
from screenCaptureModifier import mainWindow
from screenCaptureModifier.screenCapture import ScreenCapture
from PyQt4.Qt import QRect
import argparse

if __name__ == '__main__':
    app = QApplication(sys.argv)
    p = argparse.ArgumentParser()
    p.add_argument("--coords", default="200,200,800,600")
    p.add_argument("--fps", default=15)
    args = p.parse_args()
    
    window = mainWindow.MainWindow()
    window.show()
    
       
    # Tu si vyberas coordinaty na grabovanie plochy a fps
    x,y,width,height = args.coords.split(",")
    capture = ScreenCapture(coords=QRect(int(x), int(y), int(width), int(height)), fps=int(args.fps))
    
    capture.newScreen.connect(window.originalPictureWidget.updateImage)
    capture.newTransformedScreen.connect(window.transofrmedPictureWidget.updateImage)
    
    
    app.exec_()
Exemplo n.º 19
0
    def setupUi(self, orientationWidget):

        win = self.win
        MainWindow = self.win

        # Set the default width and height.
        _width = 150
        _height = 280
        _maxWidth = 400  # 400 should be more than enough. --mark

        # "View > Orientation" Dock Widget
        orientationWidget.setEnabled(True)
        orientationWidget.setFloating(True)
        orientationWidget.setVisible(False)
        orientationWidget.setWindowTitle("Orientation")
        orientationWidget.setWindowIcon(
            geticon("ui/actions/View/Modify/Orientation.png"))
        orientationWidget.setGeometry(QRect(0, 0, _width, _height))
        orientationWidget.setMaximumWidth(400)

        x = max(0, win.geometry().x())
        y = max(0, win.geometry().y())

        orientationWidget.move(x, y)

        self.orientationWindowContents = QtGui.QWidget(orientationWidget)

        gridlayout = QtGui.QGridLayout(self.orientationWindowContents)

        gridlayout.setMargin(4)
        gridlayout.setSpacing(4)

        hboxlayout = QtGui.QHBoxLayout()
        hboxlayout.setMargin(0)
        hboxlayout.setSpacing(6)

        self.pinOrientationWindowToolButton = QtGui.QToolButton(
            self.orientationWindowContents)
        self.pinOrientationWindowToolButton.setCheckable(True)

        self.pinOrientationWindowToolButton.setIcon(
            geticon("ui/dialogs/unpinned.png"))
        hboxlayout.addWidget(self.pinOrientationWindowToolButton)

        self.saveNamedViewToolButton = QtGui.QToolButton(
            self.orientationWindowContents)
        self.saveNamedViewToolButton.setIcon(
            geticon("ui/actions/View/Modify/Save_Named_View.png")
        )  #@@ ninad 061115 dir path will be modified
        hboxlayout.addWidget(self.saveNamedViewToolButton)
        gridlayout.addLayout(hboxlayout, 0, 0, 1, 1)

        self.orientationViewList = QtGui.QListWidget(orientationWidget)
        self.orientationViewList.setFlow(QtGui.QListWidget.TopToBottom)
        self.orientationViewList.setWindowIcon(
            geticon("ui/actions/View/Modify/Orientation.png"))

        gridlayout.addWidget(self.orientationViewList, 1, 0, 1, 1)

        orientationWidget.setWidget(self.orientationWindowContents)

        MainWindow.addDockWidget(Qt.BottomDockWidgetArea, orientationWidget)
Exemplo n.º 20
0
 def paint(self, painter, option, index):
     QStyledItemDelegate.paint(
         self, painter, option,
         QModelIndex())  # draw the hover and selection highlights
     m = index.model()
     db = m.db
     try:
         book_id = db.id(index.row())
     except (ValueError, IndexError, KeyError):
         return
     if book_id in m.ids_to_highlight_set:
         painter.save()
         try:
             painter.setPen(self.highlight_color)
             painter.setRenderHint(QPainter.Antialiasing, True)
             painter.drawRoundedRect(option.rect, 10, 10, Qt.RelativeSize)
         finally:
             painter.restore()
     marked = db.data.get_marked(book_id)
     db = db.new_api
     cdata = self.cover_cache[book_id]
     device_connected = self.parent().gui.device_connected is not None
     on_device = device_connected and db.field_for('ondevice', book_id)
     painter.save()
     right_adjust = 0
     try:
         rect = option.rect
         rect.adjust(self.MARGIN, self.MARGIN, -self.MARGIN, -self.MARGIN)
         orect = QRect(rect)
         if cdata is None or cdata is False:
             title = db.field_for('title', book_id, default_value='')
             authors = ' & '.join(
                 db.field_for('authors', book_id, default_value=()))
             painter.setRenderHint(QPainter.TextAntialiasing, True)
             painter.drawText(rect, Qt.AlignCenter | Qt.TextWordWrap,
                              '%s\n\n%s' % (title, authors))
             if cdata is False:
                 self.render_queue.put(book_id)
         else:
             if self.title_height != 0:
                 trect = QRect(rect)
                 rect.setBottom(rect.bottom() - self.title_height)
             if self.animating is not None and self.animating.row(
             ) == index.row():
                 cdata = cdata.scaled(cdata.size() * self._animated_size)
             dx = max(0, int((rect.width() - cdata.width()) / 2.0))
             dy = max(0, rect.height() - cdata.height())
             right_adjust = dx
             rect.adjust(dx, dy, -dx, 0)
             painter.drawPixmap(rect, cdata)
             if self.title_height != 0:
                 rect = trect
                 rect.setTop(rect.bottom() - self.title_height + 5)
                 painter.setRenderHint(QPainter.TextAntialiasing, True)
                 title = db.field_for('title', book_id, default_value='')
                 metrics = painter.fontMetrics()
                 painter.drawText(
                     rect, Qt.AlignCenter | Qt.TextSingleLine,
                     metrics.elidedText(title, Qt.ElideRight, rect.width()))
         if marked:
             try:
                 p = self.marked_emblem
             except AttributeError:
                 p = self.marked_emblem = QPixmap(I('rating.png')).scaled(
                     48, 48, transformMode=Qt.SmoothTransformation)
             drect = QRect(orect)
             drect.setLeft(drect.left() + right_adjust)
             drect.setRight(drect.left() + p.width())
             drect.setBottom(drect.bottom() - self.title_height)
             drect.setTop(drect.bottom() - p.height())
             painter.drawPixmap(drect, p)
         if on_device:
             try:
                 p = self.on_device_emblem
             except AttributeError:
                 p = self.on_device_emblem = QPixmap(I('ok.png')).scaled(
                     48, 48, transformMode=Qt.SmoothTransformation)
             drect = QRect(orect)
             drect.setRight(drect.right() - right_adjust)
             drect.setBottom(drect.bottom() - self.title_height)
             drect.setTop(drect.bottom() - p.height() + 1)
             drect.setLeft(drect.right() - p.width() + 1)
             painter.drawPixmap(drect, p)
     finally:
         painter.restore()
Exemplo n.º 21
0
    p = argparse.ArgumentParser()
    p.add_argument("--zmqHost", default="127.0.0.1")
    p.add_argument("--zmqPort", default=8889)
    p.add_argument("--coords", default="200,200,800,600")
    p.add_argument("--sendModified", default=False)
    p.add_argument("--fps", default=15)
    args = p.parse_args()

    window = mainWindow.MainWindow()
    window.setWindowTitle("Server version of viewer")
    window.show()

    # Tu si vyberas coordinaty na grabovanie plochy a fps
    x, y, width, height = args.coords.split(",")
    capture = ScreenCapture(coords=QRect(int(x), int(y), int(width),
                                         int(height)),
                            fps=int(args.fps))

    server = zmqPublisher(args.zmqHost, args.zmqPort)

    def sendOriginalPicture(frameBuffer):
        server.send(b"original", frameBuffer[-1].copy())

    def sendModifiedPicture(frameBuffer):
        server.send(b"modified", frameBuffer[-1].copy())

    def onClose():
        capture.newScreen.disconnect(sendOriginalPicture)
        capture.newTransformedScreen.disconnect(sendModifiedPicture)
        server.close()
Exemplo n.º 22
0
    def draw(self, painter, xmap, ymap, rect):
        """Implements QwtPlotItem.draw(), to render the image on the given painter."""
        xp1, xp2, xdp, xs1, xs2, xds = xinfo = xmap.p1(), xmap.p2(
        ), xmap.pDist(), xmap.s1(), xmap.s2(), xmap.sDist()
        yp1, yp2, ydp, ys1, ys2, yds = yinfo = ymap.p1(), ymap.p2(
        ), ymap.pDist(), ymap.s1(), ymap.s2(), ymap.sDist()
        dprint(5, "draw:", rect, xinfo, yinfo)
        self._current_rect = QRectF(QPointF(xs2, ys1), QSizeF(xds, yds))
        self._current_rect_pix = QRect(
            QPoint(*self.lmToPix(xs1, ys1)),
            QPoint(*self.lmToPix(xs2, ys2))).intersected(
                self._bounding_rect_pix)
        dprint(5, "draw:", self._current_rect_pix)
        # put together tuple describing current mapping
        mapping = xinfo, yinfo
        # if mapping has changed w.r.t. cache (i.e. zoom has changed), discard all cached QImages
        if mapping != self._cache_mapping:
            dprint(2, "does not match cached mapping, cache is:",
                   self._cache_mapping)
            dprint(2, "and we have:", mapping)
            self.clearDisplayCache()
            self._cache_mapping = mapping
        t0 = time.time()
        # check cached QImage for current image key.
        qimg = self._cache_qimage.get(self._image_key)
        if qimg:
            dprint(5, "QImage found in cache, reusing")
        # else regenerate image
        else:
            # check for cached intensity-mapped data
            if self._cache_imap is not None:
                dprint(5, "intensity-mapped data found in cache, reusing")
            else:
                if self._cache_interp is not None:
                    dprint(5, "interpolated data found in cache, reusing")
                else:
                    image = self._image.transpose(
                    ) if self._data_fortran_order else self._image
                    spline_order = 2
                    xsamp = abs(xmap.sDist() / xmap.pDist()) / abs(self._dl)
                    ysamp = abs(ymap.sDist() / ymap.pDist()) / abs(self._dm)
                    if max(xsamp, ysamp) < .33 or min(xsamp, ysamp) > 2:
                        spline_order = 1
                    dprint(2,
                           "regenerating drawing cache, sampling factors are",
                           xsamp, ysamp, "spline order is", spline_order)
                    self._cache_imap = None
                    if self._prefilter is None and spline_order > 1:
                        self._prefilter = interpolation.spline_filter(
                            image, order=spline_order)
                        dprint(2, "spline prefiltering took",
                               time.time() - t0, "secs")
                        t0 = time.time()
                    # make arrays of plot coordinates
                    # xp[0],yp[0] corresponds to pixel 0,0, where 0,0 is the upper-left corner of the plot
                    # the maps are in a funny order (w.r.t. meaning of p1/p2/s1/s2), so the indices here are determined empirically
                    # We also adjust by half-pixel, to get the world coordinate of the pixel _center_
                    xp = xmap.s1() - (xmap.sDist() / xmap.pDist()) * (
                        0.5 + numpy.arange(int(xmap.pDist())))
                    yp = ymap.s2() - (ymap.sDist() / ymap.pDist()) * (
                        0.5 + numpy.arange(int(ymap.pDist())))
                    # now convert plot coordinates into fractional image pixel coordinates
                    xi = self._x0 + (xp - self._l0) / self._dl
                    yi = self._y0 + (yp - self._m0) / self._dm
                    # interpolate image data
                    ###        # old code for nearest-neighbour interpolation
                    ###        # superceded by interpolation below (we simply round pixel coordinates to go to NN when oversampling)
                    ###        xi = xi.round().astype(int)
                    ###        oob_x = (xi<0)|(xi>=self._nx)
                    ###        xi[oob_x] = 0
                    ###        yi = yi.round().astype(int)
                    ###        oob_y = (yi<0)|(yi>=self._ny)
                    ###        yi[oob_y] = 0
                    ###        idx = (xi[:,numpy.newaxis]*self._ny + yi[numpy.newaxis,:]).ravel()
                    ###        interp_image = self._image.ravel()[idx].reshape((len(xi),len(yi)))
                    ###        interp_image[oob_x,:] = 0
                    ###        interp_image[:,oob_y] = 0
                    ###        self._qimage_cache = self.colormap.colorize(interp_image,self._img_range)
                    ###        self._qimage_cache_attrs = (rect,xinfo,yinfo)

                    # if either axis is oversampled by a factor of 3 or more, switch to nearest-neighbour interpolation by rounding pixel values
                    if xsamp < .33:
                        xi = xi.round()
                    if ysamp < .33:
                        yi = yi.round()
                    # make [2,nx,ny] array of interpolation coordinates
                    xy = numpy.zeros((2, len(xi), len(yi)))
                    xy[0, :, :] = xi[:, numpy.newaxis]
                    xy[1, :, :] = yi[numpy.newaxis, :]
                    # interpolate. Use NAN for out of range pixels...
                    # for fortran order, tranpose axes for extra speed (flip XY around then)
                    if self._data_fortran_order:
                        xy = xy[-1::-1, ...]
                    if spline_order > 1:
                        interp_image = interpolation.map_coordinates(
                            self._prefilter,
                            xy,
                            order=spline_order,
                            cval=numpy.nan,
                            prefilter=False)
                    else:
                        interp_image = interpolation.map_coordinates(
                            image, xy, order=spline_order, cval=numpy.nan)
                    # ...and put a mask on them (Colormap.colorize() will make these transparent).
                    mask = ~numpy.isfinite(interp_image)
                    self._cache_interp = numpy.ma.masked_array(
                        interp_image, mask)
                    dprint(2, "interpolation took", time.time() - t0, "secs")
                    t0 = time.time()
                # ok, we have interpolated data in _cache_interp
                self._cache_imap = self.imap.remap(self._cache_interp)
                dprint(2, "intensity mapping took", time.time() - t0, "secs")
                t0 = time.time()
            # ok, we have intensity-mapped data in _cache_imap
            qimg = self.colormap.colorize(self._cache_imap)
            dprint(2, "colorizing took", time.time() - t0, "secs")
            t0 = time.time()
            # cache the qimage
            self._cache_qimage[self._image_key] = qimg.copy()
        # now draw the image
        t0 = time.time()
        painter.drawImage(xp1, yp2, qimg)
        dprint(2, "drawing took", time.time() - t0, "secs")
Exemplo n.º 23
0
    def paintEvent(self, event):
        w = self.viewport().rect().width()
        painter = QPainter(self.viewport())
        painter.setClipRect(event.rect())
        floor = event.rect().bottom()
        ceiling = event.rect().top()
        fv = self.firstVisibleBlock().blockNumber()
        origin = self.contentOffset()
        doc = self.document()
        lines = []

        for num, text in self.headers:
            top, bot = num, num + 3
            if bot < fv:
                continue
            y_top = self.blockBoundingGeometry(
                doc.findBlockByNumber(top)).translated(origin).y()
            y_bot = self.blockBoundingGeometry(
                doc.findBlockByNumber(bot)).translated(origin).y()
            if max(y_top, y_bot) < ceiling:
                continue
            if min(y_top, y_bot) > floor:
                break
            painter.setFont(self.heading_font)
            br = painter.drawText(3, y_top, w, y_bot - y_top - 5,
                                  Qt.TextSingleLine, text)
            painter.setPen(QPen(self.palette().text(), 2))
            painter.drawLine(0, br.bottom() + 3, w, br.bottom() + 3)

        for top, bot, kind in self.changes:
            if bot < fv:
                continue
            y_top = self.blockBoundingGeometry(
                doc.findBlockByNumber(top)).translated(origin).y()
            y_bot = self.blockBoundingGeometry(
                doc.findBlockByNumber(bot)).translated(origin).y()
            if max(y_top, y_bot) < ceiling:
                continue
            if min(y_top, y_bot) > floor:
                break
            if y_top != y_bot:
                painter.fillRect(0, y_top, w, y_bot - y_top,
                                 self.diff_backgrounds[kind])
            lines.append((y_top, y_bot, kind))
            if top in self.images:
                img, maxw = self.images[top][:2]
                if bot > top + 1 and not img.isNull():
                    y_top = self.blockBoundingGeometry(
                        doc.findBlockByNumber(top +
                                              1)).translated(origin).y() + 3
                    y_bot -= 3
                    scaled, imgw, imgh = fit_image(img.width(), img.height(),
                                                   w - 3, y_bot - y_top)
                    painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
                    painter.drawPixmap(QRect(3, y_top, imgw, imgh), img)

        painter.end()
        PlainTextEdit.paintEvent(self, event)
        painter = QPainter(self.viewport())
        painter.setClipRect(event.rect())
        for top, bottom, kind in sorted(lines,
                                        key=lambda
                                        (t, b, k): {'replace': 0}.get(k, 1)):
            painter.setPen(QPen(self.diff_foregrounds[kind], 1))
            painter.drawLine(0, top, w, top)
            painter.drawLine(0, bottom - 1, w, bottom - 1)
Exemplo n.º 24
0
class Declaration(QWidget):

    hyperlink_activated = pyqtSignal(object)

    def __init__(self, html_name, data, is_first=False, parent=None):
        QWidget.__init__(self, parent)
        self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum)
        self.data = data
        self.is_first = is_first
        self.html_name = html_name
        self.do_layout()
        self.setMouseTracking(True)

    def do_layout(self):
        fm = self.fontMetrics()
        bounding_rect = lambda text: fm.boundingRect(0, 0, 10000, 10000, Cell.
                                                     FLAGS, text)
        line_spacing = 2
        side_margin = Cell.SIDE_MARGIN
        self.rows = []
        ypos = line_spacing + (1 if self.is_first else 0)
        if 'href' in self.data:
            name = self.data['href']
            if isinstance(name, list):
                name = self.html_name
            br1 = bounding_rect(name)
            sel = self.data['selector'] or ''
            if self.data['type'] == 'inline':
                sel = 'style=""'
            br2 = bounding_rect(sel)
            self.hyperlink_rect = QRect(side_margin, ypos, br1.width(),
                                        br1.height())
            self.rows.append([
                Cell(name, self.hyperlink_rect, color_role=QPalette.Link),
                Cell(sel,
                     QRect(br1.right() + side_margin, ypos, br2.width(),
                           br2.height()),
                     right_align=True)
            ])
            ypos += max(br1.height(), br2.height()) + 2 * line_spacing

        for prop in self.data['properties']:
            text = prop.name + ':\xa0'
            br1 = bounding_rect(text)
            vtext = prop.value + '\xa0' + ('!' if prop.important else
                                           '') + prop.important
            br2 = bounding_rect(vtext)
            self.rows.append([
                Cell(text,
                     QRect(side_margin, ypos, br1.width(), br1.height()),
                     color_role=QPalette.LinkVisited,
                     is_overriden=prop.is_overriden),
                Cell(vtext,
                     QRect(br1.right() + side_margin, ypos, br2.width(),
                           br2.height()),
                     swatch=prop.color,
                     is_overriden=prop.is_overriden)
            ])
            ypos += max(br1.height(), br2.height()) + line_spacing

        self.height_hint = ypos + line_spacing
        self.width_hint = max(row[-1].rect.right() + side_margin
                              for row in self.rows) if self.rows else 0

    def sizeHint(self):
        return QSize(self.width_hint, self.height_hint)

    def paintEvent(self, ev):
        p = QPainter(self)
        p.setClipRect(ev.rect())
        palette = self.palette()
        p.setPen(palette.color(QPalette.WindowText))
        if not self.is_first:
            p.drawLine(0, 0, self.width(), 0)
        try:
            for row in self.rows:
                for cell in row:
                    p.save()
                    try:
                        cell.draw(p, self.width(), palette)
                    finally:
                        p.restore()

        finally:
            p.end()

    def mouseMoveEvent(self, ev):
        if hasattr(self, 'hyperlink_rect'):
            pos = ev.pos()
            hovering = self.hyperlink_rect.contains(pos)
            self.update_hover(hovering)
            cursor = Qt.ArrowCursor
            for r, row in enumerate(self.rows):
                for cell in row:
                    if cell.rect.contains(pos):
                        cursor = Qt.PointingHandCursor if cell.rect is self.hyperlink_rect else Qt.IBeamCursor
                    if r == 0:
                        break
                if cursor != Qt.ArrowCursor:
                    break
            self.setCursor(cursor)
        return QWidget.mouseMoveEvent(self, ev)

    def mousePressEvent(self, ev):
        if hasattr(self, 'hyperlink_rect'):
            pos = ev.pos()
            if self.hyperlink_rect.contains(pos):
                self.emit_hyperlink_activated()
        return QWidget.mousePressEvent(self, ev)

    def emit_hyperlink_activated(self):
        dt = self.data['type']
        data = {'type': dt, 'name': self.html_name, 'syntax': 'html'}
        if dt == 'inline':  # style attribute
            data['sourceline_address'] = self.data['href']
        elif dt == 'elem':  # <style> tag
            data['sourceline_address'] = self.data['href']
            data['rule_address'] = self.data['rule_address']
        else:  # stylesheet
            data['name'] = self.data['href']
            data['rule_address'] = self.data['rule_address']
            data['syntax'] = 'css'
        self.hyperlink_activated.emit(data)

    def leaveEvent(self, ev):
        self.update_hover(False)
        self.setCursor(Qt.ArrowCursor)
        return QWidget.leaveEvent(self, ev)

    def update_hover(self, hovering):
        cell = self.rows[0][0]
        if (hovering and cell.override_color is None) or (
                not hovering and cell.override_color is not None):
            cell.override_color = QColor(Qt.red) if hovering else None
            self.update()