예제 #1
0
 def render_emblems(item, emblems):
     emblems = tuple(emblems)
     if not emblems:
         return
     icon = self.rendered_emblem_cache.get(emblems, None)
     if icon is None:
         pixmaps = []
         for emblem in emblems:
             pm = self.emblem_cache.get(emblem, None)
             if pm is None:
                 pm = self.emblem_cache[emblem] = QPixmap(
                     I(emblem)).scaled(self.iconSize(), transformMode=Qt.SmoothTransformation)
             pixmaps.append(pm)
         num = len(pixmaps)
         w, h = pixmaps[0].width(), pixmaps[0].height()
         if num == 1:
             icon = self.rendered_emblem_cache[emblems] = QIcon(pixmaps[0])
         else:
             canvas = QPixmap((num * w) + ((num-1)*2), h)
             canvas.fill(Qt.transparent)
             painter = QPainter(canvas)
             for i, pm in enumerate(pixmaps):
                 painter.drawPixmap(i * (w + 2), 0, pm)
             painter.end()
             icon = self.rendered_emblem_cache[emblems] = canvas
     item.setData(0, Qt.DecorationRole, icon)
예제 #2
0
파일: Controller.py 프로젝트: ska-sa/tigger
 def _exportImageToPNG(self, filename=None):
     if not filename:
         if not self._export_png_dialog:
             dialog = self._export_png_dialog = QFileDialog(self, "Export image to PNG", ".", "*.png")
             dialog.setDefaultSuffix("png")
             dialog.setFileMode(QFileDialog.AnyFile)
             dialog.setAcceptMode(QFileDialog.AcceptSave)
             dialog.setModal(True)
             QObject.connect(dialog, SIGNAL("filesSelected(const QStringList &)"), self._exportImageToPNG)
         return self._export_png_dialog.exec_() == QDialog.Accepted
     busy = BusyIndicator()
     if isinstance(filename, QStringList):
         filename = filename[0]
     filename = str(filename)
     # make QPixmap
     nx, ny = self.image.imageDims()
     (l0, l1), (m0, m1) = self.image.getExtents()
     pixmap = QPixmap(nx, ny)
     painter = QPainter(pixmap)
     # use QwtPlot implementation of draw canvas, since we want to avoid caching
     xmap = QwtScaleMap()
     xmap.setPaintInterval(0, nx)
     xmap.setScaleInterval(l1, l0)
     ymap = QwtScaleMap()
     ymap.setPaintInterval(ny, 0)
     ymap.setScaleInterval(m0, m1)
     self.image.draw(painter, xmap, ymap, pixmap.rect())
     painter.end()
     # save to file
     try:
         pixmap.save(filename, "PNG")
     except Exception as exc:
         self.emit(SIGNAL("showErrorMessage"), "Error writing %s: %s" % (filename, str(exc)))
         return
     self.emit(SIGNAL("showMessage"), "Exported image to file %s" % filename)
예제 #3
0
        def paintEvent(self, event):
            contents_y = self.edit.verticalScrollBar().value()
            page_bottom = contents_y + self.edit.viewport().height()
            font_metrics = self.fontMetrics()

            painter = QPainter(self)

            line_count = 0

            block = self.edit.document().begin()

            while block.isValid():
                line_count += 1

                # The top left position of the block in the document
                position = self.edit.document().documentLayout().blockBoundingRect(block).topLeft()

                # Check if the position of the block is out side of the visible
                # area.
                if position.y() > page_bottom:
                    break

                # Draw the line number right justified at the y position of the
                # line. 3 is a magic padding number. drawText(x, y, text).
                painter.drawText(-5 + self.width() - font_metrics.width(str(line_count)) - 3,
                                round(position.y()) - contents_y + font_metrics.ascent(),
                                str(line_count))

                block = block.next()

            self.highest_line = line_count
            painter.end()

            QWidget.paintEvent(self, event)
예제 #4
0
 def __call__(self, ok):
     from PyQt4.Qt import QImage, QPainter, QByteArray, QBuffer
     try:
         if not ok:
             raise RuntimeError('Rendering of HTML failed.')
         de = self.page.mainFrame().documentElement()
         pe = de.findFirst('parsererror')
         if not pe.isNull():
             raise ParserError(pe.toPlainText())
         image = QImage(self.page.viewportSize(), QImage.Format_ARGB32)
         image.setDotsPerMeterX(96*(100/2.54))
         image.setDotsPerMeterY(96*(100/2.54))
         painter = QPainter(image)
         self.page.mainFrame().render(painter)
         painter.end()
         ba = QByteArray()
         buf = QBuffer(ba)
         buf.open(QBuffer.WriteOnly)
         image.save(buf, 'JPEG')
         self.data = str(ba.data())
     except Exception as e:
         self.exception = e
         self.traceback = traceback.format_exc()
     finally:
         self.loop.exit(0)
예제 #5
0
파일: writer.py 프로젝트: Eksmo/calibre
    def do_paged_render(self, outpath):
        from PyQt4.Qt import QSize, QPainter
        if self.paged_js is None:
            from calibre.utils.resources import compiled_coffeescript
            self.paged_js = compiled_coffeescript('ebooks.oeb.display.utils')
            self.paged_js += compiled_coffeescript('ebooks.oeb.display.paged')
        printer = get_pdf_printer(self.opts, output_file_name=outpath)
        painter = QPainter(printer)
        zoomx = printer.logicalDpiX()/self.view.logicalDpiX()
        zoomy = printer.logicalDpiY()/self.view.logicalDpiY()
        painter.scale(zoomx, zoomy)

        pr = printer.pageRect()
        evaljs = self.view.page().mainFrame().evaluateJavaScript
        evaljs(self.paged_js)
        self.view.page().setViewportSize(QSize(pr.width()/zoomx,
            pr.height()/zoomy))
        evaljs('''
        document.body.style.backgroundColor = "white";
        paged_display.set_geometry(1, 0, 0, 0);
        paged_display.layout();
        paged_display.fit_images();
        ''')
        mf = self.view.page().mainFrame()
        while True:
            mf.render(painter)
            nsl = evaljs('paged_display.next_screen_location()').toInt()
            if not nsl[1] or nsl[0] <= 0: break
            evaljs('window.scrollTo(%d, 0)'%nsl[0])
            printer.newPage()

        painter.end()
        printer.abort()
예제 #6
0
 def render_html(self, ok):
     try:
         if not ok:
             return
         cwidth, cheight = self.page.mainFrame().contentsSize().width(), self.page.mainFrame().contentsSize().height()
         self.page.setViewportSize(QSize(cwidth, cheight))
         factor = float(self.width)/cwidth if cwidth > self.width else 1
         cutoff_height = int(self.height/factor)-3
         image = QImage(self.page.viewportSize(), QImage.Format_ARGB32)
         image.setDotsPerMeterX(self.dpi*(100/2.54))
         image.setDotsPerMeterY(self.dpi*(100/2.54))
         painter = QPainter(image)
         self.page.mainFrame().render(painter)
         painter.end()
         cheight = image.height()
         cwidth = image.width()
         pos = 0
         while pos < cheight:
             img = image.copy(0, pos, cwidth, min(cheight-pos, cutoff_height))
             pos += cutoff_height-20
             if cwidth > self.width:
                 img = img.scaledToWidth(self.width, Qt.SmoothTransform)
             f = os.path.join(self.tdir, '%d.png'%pos)
             img.save(f)
             self.images.append((f, img.width(), img.height()))
     finally:
         QApplication.quit()
예제 #7
0
 def event(self, e):
     if e.type() == e.Paint:
         p = QPainter(self)
         # Without this the viewport margin is rendered in QPalette::Window
         # instead of QPalette::Base
         p.fillRect(0, 0, self.padding_left+2, self.height(), self.palette().color(QPalette.Base))
         p.end()
     return QListView.event(self, e)
예제 #8
0
 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
예제 #9
0
    def add_image(self, img, cache_key):
        ref = self.get_image(cache_key)
        if ref is not None:
            return ref

        fmt = img.format()
        image = QImage(img)
        if (image.depth() == 1 and img.colorTable().size() == 2 and
            img.colorTable().at(0) == QColor(Qt.black).rgba() and
            img.colorTable().at(1) == QColor(Qt.white).rgba()):
            if fmt == QImage.Format_MonoLSB:
                image = image.convertToFormat(QImage.Format_Mono)
            fmt = QImage.Format_Mono
        else:
            if (fmt != QImage.Format_RGB32 and fmt != QImage.Format_ARGB32):
                image = image.convertToFormat(QImage.Format_ARGB32)
                fmt = QImage.Format_ARGB32

        w = image.width()
        h = image.height()
        d = image.depth()

        if fmt == QImage.Format_Mono:
            bytes_per_line = (w + 7) >> 3
            data = image.constBits().asstring(bytes_per_line * h)
            return self.write_image(data, w, h, d, cache_key=cache_key)

        has_alpha = False
        soft_mask = None

        if fmt == QImage.Format_ARGB32:
            tmask = image.constBits().asstring(4*w*h)[self.alpha_bit::4]
            sdata = bytearray(tmask)
            vals = set(sdata)
            vals.discard(255)  # discard opaque pixels
            has_alpha = bool(vals)
            if has_alpha:
                # Blend image onto a white background as otherwise Qt will render
                # transparent pixels as black
                background = QImage(image.size(), QImage.Format_ARGB32_Premultiplied)
                background.fill(Qt.white)
                painter = QPainter(background)
                painter.drawImage(0, 0, image)
                painter.end()
                image = background

        ba = QByteArray()
        buf = QBuffer(ba)
        image.save(buf, 'jpeg', 94)
        data = bytes(ba.data())

        if has_alpha:
            soft_mask = self.write_image(tmask, w, h, 8)

        return self.write_image(data, w, h, 32, dct=True,
                                soft_mask=soft_mask, cache_key=cache_key)
예제 #10
0
파일: writer.py 프로젝트: hashken/calibre
 def setup_printer(self, outpath):
     self.printer = self.painter = None
     printer = get_pdf_printer(self.opts, output_file_name=outpath)
     painter = QPainter(printer)
     zoomx = printer.logicalDpiX() / self.view.logicalDpiX()
     zoomy = printer.logicalDpiY() / self.view.logicalDpiY()
     painter.scale(zoomx, zoomy)
     pr = printer.pageRect()
     self.printer, self.painter = printer, painter
     self.viewport_size = QSize(pr.width() / zoomx, pr.height() / zoomy)
     self.page.setViewportSize(self.viewport_size)
예제 #11
0
파일: test.py 프로젝트: 089git/calibre
def run(dev, func):
    p = QPainter(dev)
    if isinstance(dev, PdfDevice):
        dev.init_page()
    xmax, ymax = p.viewport().width(), p.viewport().height()
    try:
        func(p, xmax, ymax)
    finally:
        p.end()
    if isinstance(dev, PdfDevice):
        if dev.engine.errors_occurred:
            raise SystemExit(1)
예제 #12
0
파일: writer.py 프로젝트: Eksmo/calibre
 def insert_cover(self):
     if self.cover_data is None:
         return
     item_path = os.path.join(self.tmp_path, 'cover.pdf')
     printer = get_pdf_printer(self.opts, output_file_name=item_path)
     self.combine_queue.insert(0, item_path)
     p = QPixmap()
     p.loadFromData(self.cover_data)
     if not p.isNull():
         painter = QPainter(printer)
         draw_image_page(printer, painter, p,
                 preserve_aspect_ratio=self.opts.preserve_cover_aspect_ratio)
         painter.end()
     printer.abort()
예제 #13
0
파일: writer.py 프로젝트: hashken/calibre
 def insert_cover(self):
     if not isinstance(self.cover_data, bytes):
         return
     item_path = os.path.join(self.tmp_path, "cover.pdf")
     printer = get_pdf_printer(self.opts, output_file_name=item_path, for_comic=True)
     self.combine_queue.insert(0, item_path)
     p = QPixmap()
     p.loadFromData(self.cover_data)
     if not p.isNull():
         painter = QPainter(printer)
         draw_image_page(printer, painter, p, preserve_aspect_ratio=self.opts.preserve_cover_aspect_ratio)
         painter.end()
         self.append_doc(item_path)
     printer.abort()
예제 #14
0
파일: live_css.py 프로젝트: dusual/calibre
 def paintEvent(self, ev):
     p = QPainter(self)
     p.setClipRect(ev.rect())
     bg = self.palette().color(QPalette.AlternateBase)
     if self.hovering:
         bg = bg.lighter(115)
     p.fillRect(self.rect(), bg)
     try:
         p.drawText(self.rect(), Qt.AlignLeft|Qt.AlignVCenter|Qt.TextSingleLine, self.rendered_text)
     finally:
         p.end()
예제 #15
0
파일: canvas.py 프로젝트: pwasiewi/calibre
 def paintEvent(self, event):
     QWidget.paintEvent(self, event)
     p = QPainter(self)
     p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
     try:
         self.draw_background(p)
         if self.original_image_data is None:
             return
         if not self.is_valid:
             return self.draw_image_error(p)
         self.load_pixmap()
         self.draw_pixmap(p)
         if self.selection_state.rect is not None:
             self.draw_selection_rect(p)
     finally:
         p.end()
예제 #16
0
 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()
예제 #17
0
 def paintEvent(self, event):
     res = QToolButton.paintEvent(self, event)
     if _enable_hacked_QToolButton_paintEvent and self.isChecked():
         r = event.rect()
         x,y = r.left(), r.top()
         w,h = r.width(), r.height()
         # There are at least three rect sizes: 30x35, 30x36, 32x33 (see debug-print below).
         # Not sure if this sometimes includes some padding around the icon.
         ## print r.top(),r.bottom(),r.height(), r.left(),r.right(),r.width()
         ## 0 29 30 0 34 35
         ## 0 29 30 0 35 36
         ## 0 31 32 0 32 33
         p = QPainter(self, True) # True claims to mean un-clipped -- not sure if this is good.
             ## Qt4 error: TypeError: too many arguments to QPainter(), 1 at most expected
         color = toolbutton_highlight_color
         p.setPen(QPen(color, 3)) # try 3 and 2
         p.drawRect(x+2,y+2,w-4,h-4) #e could also try drawRoundRect(r, xroundedness, yroundedness)
     return res
예제 #18
0
파일: writer.py 프로젝트: hashken/calibre
    def render_images(self, outpath, mi, items):
        printer = get_pdf_printer(self.opts, for_comic=True, output_file_name=outpath)
        printer.setDocName(mi.title)

        painter = QPainter(printer)
        painter.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)

        for i, imgpath in enumerate(items):
            self.log("Rendering image:", i)
            p = QPixmap()
            p.load(imgpath)
            if not p.isNull():
                if i > 0:
                    printer.newPage()
                draw_image_page(printer, painter, p)
            else:
                self.log.warn("Failed to load image", i)
        painter.end()
예제 #19
0
파일: printing.py 프로젝트: 089git/calibre
    def do_print(self, printer):
        painter = QPainter(printer)
        zoomx = printer.logicalDpiX()/self.view.logicalDpiX()
        zoomy = printer.logicalDpiY()/self.view.logicalDpiY()
        painter.scale(zoomx, zoomy)
        pr = printer.pageRect()
        self.view.page().setViewportSize(QSize(pr.width()/zoomx,
            pr.height()/zoomy))
        evaljs = self.mf.evaluateJavaScript
        loop = QEventLoop(self)
        pagenum = 0
        from_, to = printer.fromPage(), printer.toPage()
        first = True

        for path in self.iterator.spine:
            self.loaded_ok = None
            load_html(path, self.view, codec=getattr(path, 'encoding', 'utf-8'),
                    mime_type=getattr(path, 'mime_type', None))
            while self.loaded_ok is None:
                loop.processEvents(loop.ExcludeUserInputEvents)
            if not self.loaded_ok:
                return error_dialog(self.parent(), _('Failed to render'),
                        _('Failed to render document %s')%path, show=True)
            evaljs(self.paged_js)
            evaljs('''
                document.body.style.backgroundColor = "white";
                paged_display.set_geometry(1, 0, 0, 0);
                paged_display.layout();
                paged_display.fit_images();
            ''')

            while True:
                pagenum += 1
                if (pagenum >= from_ and (to == 0 or pagenum <= to)):
                    if not first:
                        printer.newPage()
                    first = False
                    self.mf.render(painter)
                nsl = evaljs('paged_display.next_screen_location()').toInt()
                if not nsl[1] or nsl[0] <= 0: break
                evaljs('window.scrollTo(%d, 0)'%nsl[0])

        painter.end()
예제 #20
0
파일: canvas.py 프로젝트: pwasiewi/calibre
 def __call__(self, canvas):
     if canvas.has_selection and canvas.selection_state.rect is not None:
         pimg = self.after_image
         img = self.after_image = QImage(canvas.current_image)
         rect = QRectF(*get_selection_rect(img, canvas.selection_state.rect, canvas.target))
         p = QPainter(img)
         p.setRenderHint(p.SmoothPixmapTransform, True)
         p.drawImage(rect, pimg, QRectF(pimg.rect()))
         p.end()
     return self.after_image
예제 #21
0
파일: writer.py 프로젝트: Eksmo/calibre
    def render_images(self, outpath, mi, items):
        printer = get_pdf_printer(self.opts, for_comic=True,
                output_file_name=outpath)
        printer.setDocName(mi.title)
        printer.setCreator(u'%s [%s]'%(__appname__, __version__))
        # Seems to be no way to set author

        painter = QPainter(printer)
        painter.setRenderHints(QPainter.Antialiasing|QPainter.SmoothPixmapTransform)

        for i, imgpath in enumerate(items):
            self.log('Rendering image:', i)
            p = QPixmap()
            p.load(imgpath)
            if not p.isNull():
                if i > 0:
                    printer.newPage()
                draw_image_page(printer, painter, p)
            else:
                self.log.warn('Failed to load image', i)
        painter.end()
예제 #22
0
파일: Colormaps.py 프로젝트: ska-sa/tigger
 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
예제 #23
0
    def dump(self, items, out_stream, pdf_metadata):
        opts = self.opts
        self.outline = Outline(self.toc, items)
        page_size = get_page_size(self.opts)
        xdpi, ydpi = self.view.logicalDpiX(), self.view.logicalDpiY()
        ml, mr = opts.margin_left, opts.margin_right
        margin_side = min(ml, mr)
        ml, mr = ml - margin_side, mr - margin_side
        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)

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

        # TODO: Test margins
        mt, mb = map(self.doc.to_px, (opts.margin_top, opts.margin_bottom))
        ms = self.doc.to_px(margin_side, vertical=False)
        self.margin_top, self.margin_size, self.margin_bottom = map(
            lambda x:int(floor(x)), (mt, ms, mb))

        self.painter = QPainter(self.doc)
        self.doc.set_metadata(title=pdf_metadata.title,
                              author=pdf_metadata.author,
                              tags=pdf_metadata.tags)
        self.painter.save()
        try:
            if self.cover_data is not None:
                p = QPixmap()
                p.loadFromData(self.cover_data)
                if not p.isNull():
                    draw_image_page(QRect(0, 0, self.doc.width(), self.doc.height()),
                            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)
        self.loop.exec_()

        # TODO: Outline and links
        self.painter.end()

        if self.doc.errors_occurred:
            raise Exception('PDF Output failed, see log for details')
예제 #24
0
파일: icons.py 프로젝트: dodo/blain
def magnify_icons(a, b):
    a = a.pixmap(16,16)
    b = b.pixmap(16,16)
    img = [QPixmap(16,16), QPixmap(16,16)]
    for i in img:
        i.fill(QColor(0, 0, 0, 0))
        g = a.toImage()
        for n in range(256):
            x, y = n%16, n//16
            c = QColor(g.pixel(x, y))
            s = (c.redF() + c.greenF() + c.blueF()) / 3.0
            l = s * 4.2
            if l > 1.0: l = 1.0
            c.setRgbF(s, s, s, l)
            g.setPixel(x, y, c.rgba())
        p = QPainter()
        p.begin(i)
        p.drawImage( QRectF(6, 0,  8, 16), g, QRectF(0, 0, 10, 16))
        p.drawPixmap(QRectF(0, 0, 10, 16), b, QRectF(6, 1,  10, 15))
        p.end()
        a, b = b, a
    return tuple(map(QIcon, img))
예제 #25
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()
예제 #26
0
    def do_print(self, printer):
        painter = QPainter(printer)
        zoomx = printer.logicalDpiX() / self.view.logicalDpiX()
        zoomy = printer.logicalDpiY() / self.view.logicalDpiY()
        painter.scale(zoomx, zoomy)
        pr = printer.pageRect()
        self.view.page().setViewportSize(
            QSize(pr.width() / zoomx,
                  pr.height() / zoomy))
        evaljs = self.mf.evaluateJavaScript
        loop = QEventLoop(self)
        first = True

        for path in self.iterator.spine:
            self.loaded_ok = None
            load_html(path,
                      self.view,
                      codec=getattr(path, 'encoding', 'utf-8'),
                      mime_type=getattr(path, 'mime_type', None))
            while self.loaded_ok is None:
                loop.processEvents(loop.ExcludeUserInputEvents)
            if not self.loaded_ok:
                return error_dialog(self.parent(),
                                    _('Failed to render'),
                                    _('Failed to render document %s') % path,
                                    show=True)
            evaljs(self.paged_js)
            evaljs('''
                document.body.style.backgroundColor = "white";
                paged_display.set_geometry(1, 0, 0, 0);
                paged_display.layout();
                paged_display.fit_images();
            ''')

            while True:
                if not first:
                    printer.newPage()
                first = False
                self.mf.render(painter)
                nsl = evaljs('paged_display.next_screen_location()').toInt()
                if not nsl[1] or nsl[0] <= 0: break
                evaljs('window.scrollTo(%d, 0)' % nsl[0])

        painter.end()
예제 #27
0
파일: writer.py 프로젝트: sss/calibre
    def render_images(self, outpath, mi, items):
        printer = get_pdf_printer(self.opts,
                                  for_comic=True,
                                  output_file_name=outpath)
        printer.setDocName(mi.title)

        painter = QPainter(printer)
        painter.setRenderHints(QPainter.Antialiasing
                               | QPainter.SmoothPixmapTransform)

        for i, imgpath in enumerate(items):
            self.log('Rendering image:', i)
            p = QPixmap()
            p.load(imgpath)
            if not p.isNull():
                if i > 0:
                    printer.newPage()
                draw_image_page(printer, painter, p)
            else:
                self.log.warn('Failed to load image', i)
        painter.end()
예제 #28
0
 def paintEvent(self, event):
     res = QToolButton.paintEvent(self, event)
     if _enable_hacked_QToolButton_paintEvent and self.isChecked():
         r = event.rect()
         x, y = r.left(), r.top()
         w, h = r.width(), r.height()
         # There are at least three rect sizes: 30x35, 30x36, 32x33 (see debug-print below).
         # Not sure if this sometimes includes some padding around the icon.
         ## print r.top(),r.bottom(),r.height(), r.left(),r.right(),r.width()
         ## 0 29 30 0 34 35
         ## 0 29 30 0 35 36
         ## 0 31 32 0 32 33
         p = QPainter(
             self, True
         )  # True claims to mean un-clipped -- not sure if this is good.
         ## Qt4 error: TypeError: too many arguments to QPainter(), 1 at most expected
         color = toolbutton_highlight_color
         p.setPen(QPen(color, 3))  # try 3 and 2
         p.drawRect(
             x + 2, y + 2, w - 4, h - 4
         )  #e could also try drawRoundRect(r, xroundedness, yroundedness)
     return res
예제 #29
0
        def paintEvent(self, event):
            contents_y = self.edit.verticalScrollBar().value()
            page_bottom = contents_y + self.edit.viewport().height()
            font_metrics = self.fontMetrics()

            painter = QPainter(self)

            line_count = 0

            block = self.edit.document().begin()

            while block.isValid():
                line_count += 1

                # The top left position of the block in the document
                position = self.edit.document().documentLayout(
                ).blockBoundingRect(block).topLeft()

                # Check if the position of the block is out side of the visible
                # area.
                if position.y() > page_bottom:
                    break

                # Draw the line number right justified at the y position of the
                # line. 3 is a magic padding number. drawText(x, y, text).
                painter.drawText(
                    -5 + self.width() - font_metrics.width(str(line_count)) -
                    3,
                    round(position.y()) - contents_y + font_metrics.ascent(),
                    str(line_count))

                block = block.next()

            self.highest_line = line_count
            painter.end()

            QWidget.paintEvent(self, event)
예제 #30
0
 def paintEvent(self, ev):
     painter = QPainter(self)
     painter.fillRect(ev.rect(), self.brush)
     painter.end()
예제 #31
0
파일: diff.py 프로젝트: sss/calibre
    def paintEvent(self, event):
        pmap = self.blank if self.pixmap is None or self.pixmap.isNull(
        ) else self.pixmap
        target = self.rect()
        scaled, width, height = fit_image(pmap.width(), pmap.height(),
                                          target.width(), target.height())
        target.setRect(target.x(), target.y(), width, height)
        p = QPainter(self)
        p.setRenderHints(QPainter.Antialiasing
                         | QPainter.SmoothPixmapTransform)
        p.drawPixmap(target, pmap)

        if self.pixmap is not None and not self.pixmap.isNull():
            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()
예제 #32
0
def create_icon(text, palette=None, sz=32, divider=2):
    if palette is None:
        palette = QApplication.palette()
    img = QImage(sz, sz, QImage.Format_ARGB32)
    img.fill(Qt.transparent)
    p = QPainter(img)
    p.setRenderHints(p.TextAntialiasing | p.Antialiasing)
    qDrawShadeRect(p, img.rect(), palette, fill=QColor('#ffffff'), lineWidth=1, midLineWidth=1)
    f = p.font()
    f.setFamily('Liberation Sans'), f.setPixelSize(sz // divider), f.setBold(True)
    p.setFont(f), p.setPen(Qt.black)
    p.drawText(img.rect().adjusted(2, 2, -2, -2), Qt.AlignCenter, text)
    p.end()
    return QIcon(QPixmap.fromImage(img))
예제 #33
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)
예제 #34
0
파일: view.py 프로젝트: mrmac123/calibre
 def failed_img(self):
     if self._failed_img is None:
         i = QImage(200, 150, QImage.Format_ARGB32)
         i.fill(Qt.white)
         p = QPainter(i)
         r = i.rect().adjusted(10, 10, -10, -10)
         n = QPen(Qt.DashLine)
         n.setColor(Qt.black)
         p.setPen(n)
         p.drawRect(r)
         p.setPen(Qt.black)
         f = self.font()
         f.setPixelSize(20)
         p.setFont(f)
         p.drawText(r.adjusted(10, 0, -10, 0),
                    Qt.AlignCenter | Qt.TextWordWrap,
                    _('Image could not be rendered'))
         p.end()
         self._failed_img = QPixmap.fromImage(i)
     return self._failed_img
예제 #35
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()
예제 #36
0
    def paint_line_numbers(self, ev):
        painter = QPainter(self.line_number_area)
        painter.fillRect(ev.rect(), self.line_number_palette.color(QPalette.Base))

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

        while block.isValid() and top <= ev.rect().bottom():
            if block.isVisible() and bottom >= ev.rect().top():
                if current == num:
                    painter.save()
                    painter.setPen(self.line_number_palette.color(QPalette.BrightText))
                    f = QFont(self.font())
                    f.setBold(True)
                    painter.setFont(f)
                    self.last_current_lnum = (top, bottom - top)
                painter.drawText(0, top, self.line_number_area.width() - 5, self.fontMetrics().height(),
                              Qt.AlignRight, str(num + 1))
                if current == num:
                    painter.restore()
            block = block.next()
            top = bottom
            bottom = top + int(self.blockBoundingRect(block).height())
            num += 1
예제 #37
0
def createCompositeCursor(cursor,
                          overlayCursor,
                          hotX=None,
                          hotY=None,
                          offsetX=0,
                          offsetY=0):
    """
    Returns a composite 32x32 cursor using two other cursors.

    This is useful for creating composite cursor images from two (or more)
    cursors.
    
    For example, the pencil cursor includes a horizontal and vertical 
    symbol when drawing a horizontal or vertical line. This function can
    be used to create these cursors without having to create each one by hand.
    The payoff is when the developer/artist wants to change the base cursor 
    image (i.e. the pencil cursor) without having to redraw and save all the 
    other versions of the cursor in the set.
    
    @param cursor: The main cursor.
    @type  cursor: QCursor
    
    @param overlayCursor: The cursor to overlay on top of I{cursor}.
    @type  overlayCursor: QCursor
    
    @param hotX: The X coordinate of the hotspot. If none is given, the
                 hotspot of I{cursor} is used.
    @type  hotX: int
    
    @param hotY: The Y coordinate of the hotspot. If none is given, the
                 hotspot of I{cursor} is used.
    @type  hotY: int
    
    @param offsetX: The X offset in which to draw the overlay cursor onto
                    I{cursor}. The default is 0.
    @type  offsetX: int
    
    @param offsetY: The Y offset in which to draw the overlay cursor onto
                    I{cursor}. The default is 0.
    @type  offsetY: int
    
    @return: The composite cursor.
    @rtype:  QCursor
    
    @note: It would be easy and useful to allow overlayCursor to be a QPixmap.
           I'll add this when it becomes helpful. --Mark 2008-03-06.
    """
    # Method:
    # 1. Get cursor's pixmap and create a painter from it.
    # 2. Get the pixmap from the overlay cursor and draw it onto the
    #    cursor pixmap to create the composite pixmap.
    # 3. Create and return a new QCursor from the composite pixmap.
    # Mark 2008-03-05

    assert isinstance(cursor, QCursor)
    assert isinstance(overlayCursor, QCursor)

    if hotX is None:
        hotX = cursor.hotSpot().x()
    if hotY is None:
        hotY = cursor.hotSpot().y()
    pixmap = cursor.pixmap()
    overlayPixmap = overlayCursor.pixmap()
    painter = QPainter(pixmap)
    painter.drawPixmap(offsetX, offsetY, overlayPixmap)
    painter.end()
    return QCursor(pixmap, hotX, hotY)
예제 #38
0
 def paintEvent(self, ev):
     p = QPainter(self)
     p.setRenderHints(p.Antialiasing)
     p.setBrush(self.brush)
     p.setPen(Qt.NoPen)
     p.drawPath(self.arrow_path)
     p.end()
예제 #39
0
        def _fetch_marvin_cover(with_border=False):
            '''
            Retrieve LargeCoverJpg from cache
            '''
            self._log_location()
            con = sqlite3.connect(self.marvin_db_path)
            with con:
                con.row_factory = sqlite3.Row

                # Fetch Hash from mainDb
                cover_cur = con.cursor()
                cover_cur.execute('''SELECT
                                      Hash
                                     FROM Books
                                     WHERE ID = '{0}'
                                  '''.format(self.book_id))
                row = cover_cur.fetchone()

            book_hash = row[b'Hash']
            large_covers_subpath = self.connected_device._cover_subpath(
                size="large")
            cover_path = '/'.join([large_covers_subpath, '%s.jpg' % book_hash])
            stats = self.parent.ios.exists(cover_path)
            if stats:
                self._log("fetching large cover from cache")
                #self._log("cover size: {:,} bytes".format(int(stats['st_size'])))
                cover_bytes = self.parent.ios.read(cover_path, mode='rb')
                m_image = QImage()
                m_image.loadFromData(cover_bytes)

                if with_border:
                    m_image = m_image.scaledToHeight(
                        self.COVER_ICON_SIZE - self.BORDER_WIDTH * 2,
                        Qt.SmoothTransformation)

                    # Construct a QPixmap with yellow background
                    self.m_pixmap = QPixmap(
                        QSize(m_image.width() + self.BORDER_WIDTH * 2,
                              m_image.height() + self.BORDER_WIDTH * 2))

                    m_painter = QPainter(self.m_pixmap)
                    m_painter.setRenderHints(m_painter.Antialiasing)

                    m_painter.fillRect(self.m_pixmap.rect(),
                                       QColor(0xFD, 0xFF, 0x99))
                    m_painter.drawImage(self.BORDER_WIDTH, self.BORDER_WIDTH,
                                        m_image)
                else:
                    m_image = m_image.scaledToHeight(self.COVER_ICON_SIZE,
                                                     Qt.SmoothTransformation)

                    self.m_pixmap = QPixmap(
                        QSize(m_image.width(), m_image.height()))

                    m_painter = QPainter(self.m_pixmap)
                    m_painter.setRenderHints(m_painter.Antialiasing)

                    m_painter.drawImage(0, 0, m_image)

                self.marvin_cover.setPixmap(self.m_pixmap)
            else:
                # No cover available, use generic
                self._log("No cached cover, using generic")
                pixmap = QPixmap()
                pixmap.load(I('book.png'))
                pixmap = pixmap.scaled(self.COVER_ICON_SIZE,
                                       self.COVER_ICON_SIZE,
                                       aspectRatioMode=Qt.KeepAspectRatio,
                                       transformMode=Qt.SmoothTransformation)
                self.marvin_cover.setPixmap(pixmap)
예제 #40
0
 def paintEvent(self, event):
     QWidget.paintEvent(self, event)
     pmap = self._pixmap
     if pmap.isNull():
         return
     w, h = pmap.width(), pmap.height()
     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.)
     y = int(abs(ch - h) / 2.)
     target = QRect(x, y, w, h)
     p = QPainter(self)
     p.setRenderHints(QPainter.Antialiasing
                      | QPainter.SmoothPixmapTransform)
     p.drawPixmap(target, pmap)
     pen = QPen()
     pen.setWidth(self.BORDER_WIDTH)
     p.setPen(pen)
     if self.draw_border:
         p.drawRect(target)
     #p.drawRect(self.rect())
     p.end()
예제 #41
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)
        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()
                p.loadFromData(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')
예제 #42
0
class PDFWriter(QObject):
    def _pass_json_value_getter(self):
        val = json.dumps(self.bridge_value)
        return QString(val)

    def _pass_json_value_setter(self, value):
        self.bridge_value = json.loads(unicode(value))

    _pass_json_value = pyqtProperty(QString,
                                    fget=_pass_json_value_getter,
                                    fset=_pass_json_value_setter)

    @pyqtSlot(result=unicode)
    def title(self):
        return self.doc_title

    @pyqtSlot(result=unicode)
    def author(self):
        return self.doc_author

    @pyqtSlot(result=unicode)
    def section(self):
        return self.current_section

    def __init__(self, opts, log, cover_data=None, toc=None):
        from calibre.gui2 import is_ok_to_use_qt
        if not is_ok_to_use_qt():
            raise Exception('Not OK to use Qt')
        QObject.__init__(self)

        self.logger = self.log = log
        self.opts = opts
        self.cover_data = cover_data
        self.paged_js = None
        self.toc = toc

        self.loop = QEventLoop()
        self.view = QWebView()
        self.page = Page(opts, self.log)
        self.view.setPage(self.page)
        self.view.setRenderHints(QPainter.Antialiasing
                                 | QPainter.TextAntialiasing
                                 | QPainter.SmoothPixmapTransform)
        self.view.loadFinished.connect(self.render_html,
                                       type=Qt.QueuedConnection)
        for x in (Qt.Horizontal, Qt.Vertical):
            self.view.page().mainFrame().setScrollBarPolicy(
                x, Qt.ScrollBarAlwaysOff)
        self.report_progress = lambda x, y: x
        self.current_section = ''

    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)
        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()
                p.loadFromData(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')

    def render_book(self):
        if self.doc.errors_occurred:
            return self.loop.exit(1)
        try:
            if not self.render_queue:
                self.loop.exit()
            else:
                self.render_next()
        except:
            self.logger.exception('Rendering failed')
            self.loop.exit(1)

    def render_next(self):
        item = unicode(self.render_queue.pop(0))

        self.logger.debug('Processing %s...' % item)
        self.current_item = item
        load_html(item, self.view)

    def render_html(self, ok):
        if ok:
            try:
                self.do_paged_render()
            except:
                self.log.exception('Rendering failed')
                self.loop.exit(1)
                return
        else:
            # The document is so corrupt that we can't render the page.
            self.logger.error('Document cannot be rendered.')
            self.loop.exit(1)
            return
        done = self.total_items - len(self.render_queue)
        self.report_progress(
            done / self.total_items,
            _('Rendered %s' % os.path.basename(self.current_item)))
        self.render_book()

    @property
    def current_page_num(self):
        return self.doc.current_page_num

    def load_mathjax(self):
        evaljs = self.view.page().mainFrame().evaluateJavaScript
        mjpath = P(u'viewer/mathjax').replace(os.sep, '/')
        if iswindows:
            mjpath = u'/' + mjpath
        if evaljs('''
                    window.mathjax.base = %s;
                    mathjax.check_for_math(); mathjax.math_present
                    ''' % (json.dumps(mjpath, ensure_ascii=False))).toBool():
            self.log.debug('Math present, loading MathJax')
            while not evaljs('mathjax.math_loaded').toBool():
                self.loop.processEvents(self.loop.ExcludeUserInputEvents)
            evaljs(
                'document.getElementById("MathJax_Message").style.display="none";'
            )

    def get_sections(self, anchor_map):
        sections = {}
        ci = os.path.abspath(os.path.normcase(self.current_item))
        if self.toc is not None:
            for toc in self.toc.flat():
                path = toc.abspath or None
                frag = toc.fragment or None
                if path is None:
                    continue
                path = os.path.abspath(os.path.normcase(path))
                if path == ci:
                    col = 0
                    if frag and frag in anchor_map:
                        col = anchor_map[frag]['column']
                    if col not in sections:
                        sections[col] = toc.text or _('Untitled')

        return sections

    def do_paged_render(self):
        if self.paged_js is None:
            import uuid
            from calibre.utils.resources import compiled_coffeescript as cc
            self.paged_js = cc('ebooks.oeb.display.utils')
            self.paged_js += cc('ebooks.oeb.display.indexing')
            self.paged_js += cc('ebooks.oeb.display.paged')
            self.paged_js += cc('ebooks.oeb.display.mathjax')
            self.hf_uuid = str(uuid.uuid4()).replace('-', '')

        self.view.page().mainFrame().addToJavaScriptWindowObject(
            "py_bridge", self)
        self.view.page().longjs_counter = 0
        evaljs = self.view.page().mainFrame().evaluateJavaScript
        evaljs(self.paged_js)
        self.load_mathjax()

        evaljs('''
        py_bridge.__defineGetter__('value', function() {
            return JSON.parse(this._pass_json_value);
        });
        py_bridge.__defineSetter__('value', function(val) {
            this._pass_json_value = JSON.stringify(val);
        });

        document.body.style.backgroundColor = "white";
        paged_display.set_geometry(1, %d, %d, %d);
        paged_display.layout();
        paged_display.fit_images();
        py_bridge.value = book_indexing.all_links_and_anchors();
        ''' % (self.margin_top, 0, self.margin_bottom))

        amap = self.bridge_value
        if not isinstance(amap, dict):
            amap = {
                'links': [],
                'anchors': {}
            }  # Some javascript error occurred
        sections = self.get_sections(amap['anchors'])
        col = 0

        if self.header:
            self.bridge_value = self.header
            evaljs('paged_display.header_template = py_bridge.value')
        if self.footer:
            self.bridge_value = self.footer
            evaljs('paged_display.footer_template = py_bridge.value')
        if self.header or self.footer:
            evaljs('paged_display.create_header_footer("%s");' % self.hf_uuid)

        start_page = self.current_page_num

        mf = self.view.page().mainFrame()
        while True:
            if col in sections:
                self.current_section = sections[col]
            self.doc.init_page()
            if self.header or self.footer:
                evaljs('paged_display.update_header_footer(%d)' %
                       self.current_page_num)
            self.painter.save()
            mf.render(self.painter)
            self.painter.restore()
            nsl = evaljs('paged_display.next_screen_location()').toInt()
            self.doc.end_page()
            if not nsl[1] or nsl[0] <= 0:
                break
            evaljs(
                'window.scrollTo(%d, 0); paged_display.position_header_footer();'
                % nsl[0])
            if self.doc.errors_occurred:
                break
            col += 1

        if not self.doc.errors_occurred:
            self.doc.add_links(self.current_item, start_page, amap['links'],
                               amap['anchors'])
예제 #43
0
파일: main.py 프로젝트: kmshi/calibre
 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)
예제 #44
0
파일: view.py 프로젝트: mrmac123/calibre
    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)
예제 #45
0
    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()
예제 #46
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()
예제 #47
0
파일: view.py 프로젝트: mrmac123/calibre
    def paint_line_numbers(self, ev):
        painter = QPainter(self.line_number_area)
        painter.fillRect(ev.rect(),
                         self.line_number_palette.color(QPalette.Base))

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

        while block.isValid() and top <= ev.rect().bottom():
            r = ev.rect()
            if block.isVisible() and bottom >= r.top():
                text = unicode(self.line_number_map.get(num, ''))
                is_start = text != '-' and num in change_starts
                if is_start:
                    painter.save()
                    f = QFont(self.font())
                    f.setBold(True)
                    painter.setFont(f)
                    painter.setPen(
                        self.line_number_palette.color(QPalette.BrightText))
                if text == '-':
                    painter.drawLine(r.left() + 2, (top + bottom) // 2,
                                     r.right() - 2, (top + bottom) // 2)
                else:
                    if self.right:
                        painter.drawText(r.left() + 3, top, r.right(),
                                         self.fontMetrics().height(),
                                         Qt.AlignLeft, text)
                    else:
                        painter.drawText(r.left() + 2, top,
                                         r.right() - 5,
                                         self.fontMetrics().height(),
                                         Qt.AlignRight, text)
                if is_start:
                    painter.restore()
            block = block.next()
            top = bottom
            bottom = top + int(self.blockBoundingRect(block).height())
            num += 1
예제 #48
0
class PaintBoard(QWidget):

    # Define virtual panel coordinates for different shapes/regions
    VPCoord_Start = [316, 332]  #LeftTopX, Y
    VPCoord_Circle = [316, 332, 336, 363]  #LeftTopX, Y, RightBotX, Y
    VPCoord_Rect = [336, 332, 356, 363]  #LeftTopX, Y, RightBotX, Y
    VPCoord_Tri = [316, 363, 336, 395]  #LeftTopX, Y, RightBotX, Y
    VPCoord_Line = [336, 363, 356, 395]  #LeftTopX, Y, RightBotX, Y

    # A flag to check if the user is currently using the virtual panel
    usingVP = False

    def __init__(self, sizeX, sizeY, Parent=None):
        '''
        Constructor
        '''
        super(PaintBoard, self).__init__(Parent)

        self.__InitData(sizeX,
                        sizeY)  #Initialize Data first, then interface/view
        self.__InitView()
        print("Init PaintBoard")

    def __InitView(self):

        self.setFixedSize(self.__size)

    def __InitData(self, sizeX, sizeY):
        self.__size = QSize(sizeX, sizeY)

        self.__board = QPixmap(
            self.__size)  # Make a new QPixmap as paint board,350px * 250px
        self.__board.fill(Qt.white)  #Fill the paint board with white

        self.__IsEmpty = True  #board is empty by default
        self.EraserMode = False  #eraser mode is disabled by default

        self.__lastPos = None
        self.__currentPos = QPoint(0, 0)

        self.__painter = QPainter()

        self.__thickness = 1  #default pen thickness is 1
        self.__penColor = QColor("black")  #default color is black
        self.__colorList = QColor.colorNames()  #get the list of colors

    def Clear(self):
        #Clear the board
        self.__board.fill(Qt.white)
        self.update()
        self.__IsEmpty = True

    def ChangePenColor(self, color="black"):
        self.__penColor = QColor(color)

    def ChangePenThickness(self, thickness=1):
        self.__thickness = thickness

    def IsEmpty(self):
        #Is the board empty
        return self.__IsEmpty

    def GetContentAsQImage(self):
        #return the content of the board (return QImage)
        image = self.__board.toImage()
        return image

    def paintEvent(self, paintEvent):

        self.__painter.begin(self)
        self.__painter.drawPixmap(0, 0, self.__board)
        self.__painter.end()

        # print("inside paintEvent")

    def penPressEvent(self, pos):

        self.__currentPos = QPoint(pos[0], pos[1])
        self.__lastPos = self.__currentPos

    def penMoveEvent(self, pos, pressure, liftedDeque):
        pen_x = pos[0]
        pen_y = pos[1]
        pen_pressure = pressure

        # print(liftedDeque)
        # print(self.__lastPos)

        if self.__lastPos is None:
            self.__lastPos = QPoint(pen_x, pen_y)

        self.__currentPos = QPoint(pen_x, pen_y)
        self.__painter.begin(self.__board)

        if self.EraserMode == False:
            #Non-Eraser mode
            self.__penColor = QColor("blue")
            self.__painter.setPen(QPen(
                self.__penColor, self.__thickness))  #Set pen color, thickness
        else:
            #Eraser mode: pen color is white, thickness is 6
            self.__painter.setPen(QPen(Qt.white, 6))

        self.__painter.drawLine(self.__lastPos, self.__currentPos)
        self.__painter.end()
        self.__lastPos = self.__currentPos

        self.update()  #Show updates

        # If ever detected the pen is lifted, reset the __lastPos variable in order to reposition the pen
        if (True in liftedDeque):
            self.__lastPos = None

    # Virtual Panel event
    def penVPEvent(self, pos, pressure):
        pass

    '''    
        # Check if the pressure is over 500
        if(pen_pressure > 400):
            # Check which region the pen is in and prepare to draw shape accordingly
            if(pen_x < self.VPCoord_Circle[2] and pen_y < self.VPCoord_Circle[3]):
                print("A")        
            elif(pen_x < self.VPCoord_Rect[2] and pen_y < self.VPCoord_Rect[3]):
                print("B")
            elif(pen_x < self.VPCoord_Tri[2] and pen_y < self.VPCoord_Tri[3]):
                print("C")
            elif(pen_x < self.VPCoord_Line[2] and pen_y < self.VPCoord_Line[3]):
                print("D")
    '''

    def penReleaseEvent(self, pos):
        self.__IsEmpty = False  #board is not empty

    def paintEllipse(self, center_x, center_y, radias1, radias2):
        self.__painter.begin(self.__board)
        self.__penColor = QColor("black")
        self.__painter.setPen(QPen(self.__penColor, self.__thickness))
        self.__painter.drawEllipse(QPoint(center_x, center_y), radias1,
                                   radias2)

        self.__painter.end()

        self.update()  #Show updates

    def paintRect(self, center_x, center_y, upper_left_x, upper_left_y):
        width = abs(2 * (center_x - upper_left_x))
        height = abs(2 * (center_y - upper_left_y))

        self.__painter.begin(self.__board)
        self.__penColor = QColor("black")
        self.__painter.setPen(QPen(self.__penColor, self.__thickness))
        self.__painter.drawRect(upper_left_x, upper_left_y, width, height)

        self.__painter.end()

        self.update()  #Show updates

    def paintTriangle(self, points):
        self.__painter.begin(self.__board)
        self.__penColor = QColor("black")
        self.__painter.setPen(QPen(self.__penColor, self.__thickness))
        self.__painter.drawPolygon(points)

        self.__painter.end()

        self.update()  #Show updates

    def paintPolyg(self, x1, y1, x2, y2, x3, y3, x4, y4):
        self.__painter.begin(self.__board)
        self.__penColor = QColor("black")
        self.__painter.setPen(QPen(self.__penColor, self.__thickness))
        self.__painter.drawPolygon(QPoint(x1, y1), QPoint(x2, y2),
                                   QPoint(x3, y3), QPoint(x4, y4))
        self.__painter.end()

        self.update()  #Show updates

    def paintLine(self, P1_x, P1_y, P2_x, P2_y):
        P1 = QPoint(P1_x, P1_y)
        P2 = QPoint(P2_x, P2_y)

        self.__painter.begin(self.__board)
        self.__penColor = QColor("black")
        self.__painter.setPen(QPen(self.__penColor, self.__thickness))
        self.__painter.drawLine(P1, P2)
        self.__painter.end()

        self.update()  #Show updates

    def paintAuxLine(self, P1_x, P1_y, P2_x, P2_y):
        P1 = QPoint(P1_x, P1_y)
        P2 = QPoint(P2_x, P2_y)

        self.__painter.begin(self.__board)
        self.__penColor = QColor("red")
        self.__painter.setPen(QPen(self.__penColor, self.__thickness))
        self.__painter.drawLine(P1, P2)
        self.__painter.end()

        self.update()  #Show updates

    def PointsInCircum(self, r, n, phi):
        return [(math.cos(2 * pi / n * x + phi) * r,
                 math.sin(2 * pi / n * x + phi) * r) for x in range(0, n + 1)
                ]  # defining the points on the Circum of a circle

    def paintPCircle(self, center_x, center_y, start_x, start_y, pers_x,
                     pers_y):
        point = [start_x, start_y]
        center = [center_x, center_y]
        distance = [(point[0] - center[0]), (point[1] - center[1])]
        phi = math.atan2(distance[1], distance[0])
        r = math.sqrt(distance[0] * distance[0] + distance[1] * distance[1])
        points = self.PointsInCircum(r, 300, phi)
        #Drawing the circle in perspective
        dist_x = center_x - pers_x
        print("dist_x", dist_x, pers_x, pers_y, center_x, center_y)
        points = [(j[0], (j[1] + center_x - pers_y) *
                   ((j[0] + center_x) / dist_x) + pers_y - center_y)
                  for j in points]

        self.__painter.begin(self.__board)
        self.__penColor = QColor("blue")
        self.__painter.setPen(QPen(self.__penColor, self.__thickness))
        for x in points:
            self.__painter.drawPoint(round(x[0] + center[0], 3),
                                     round(x[1] / 1.00 + center[1], 3))

        self.__painter.end()

    # returns true if given angle is in the second quadrant;
    # requires angle in degree and in range -180 to 180
    def _isAngleInSecondQuadrant(self, angle):
        if angle > 90 and angle < 180:
            return True
        else:
            return False

    # returns true if given angle is in the third quadrant;
    # requires angle in degree and in range -180 to 180
    def _isAngleInThirdQuadrant(self, angle):
        if angle < -90 and angle > -180:
            return True
        else:
            return False

    def paintArc(self, center_x, center_y, start_x, start_y, end_x, end_y):
        radius = math.sqrt(
            math.pow(center_x - start_x, 2) + math.pow(center_y - start_y, 2))
        rect = QRectF(center_x - radius, center_y - radius, radius * 2,
                      radius * 2)
        # start angle calculation
        startAngle = math.degrees(
            math.atan2(center_y - start_y, start_x - center_x))
        # end angle calculation
        endAngle = math.degrees(math.atan2(center_y - end_y, end_x - center_x))

        # span angle calculation
        spanAngle = endAngle - startAngle
        # assume user always wants to draw clock-wise
        if spanAngle > 0:
            spanAngle = -1 * (360 - spanAngle)
        #print("start angle is " + str(startAngle))
        #print("span angle is " + str(spanAngle))

        self.__painter.begin(self.__board)
        self.__penColor = QColor("black")
        self.__painter.setPen(QPen(self.__penColor, self.__thickness))
        self.__painter.drawArc(rect, 16 * startAngle, 16 * spanAngle)
        self.__painter.end()

        self.update()  #Show updates

    def paintAuxArc(self, center_x, center_y, start_x, start_y, end_x, end_y):
        radius = math.sqrt(
            math.pow(center_x - start_x, 2) + math.pow(center_y - start_y, 2))
        rect = QRectF(center_x - radius, center_y - radius, radius * 2,
                      radius * 2)
        # start angle calculation
        startAngle = math.degrees(
            math.atan2(center_y - start_y, start_x - center_x))
        # end angle calculation
        endAngle = math.degrees(math.atan2(center_y - end_y, end_x - center_x))

        # span angle calculation
        spanAngle = 0
        if (self._isAngleInThirdQuadrant(startAngle)
                and self._isAngleInSecondQuadrant(endAngle)
            ) or (self._isAngleInThirdQuadrant(endAngle)
                  and self._isAngleInSecondQuadrant(startAngle)) or (
                      startAngle == 180
                      and self._isAngleInThirdQuadrant(endAngle)
                  ) or (startAngle == -180
                        and self._isAngleInSecondQuadrant(endAngle)) or (
                            endAngle == 180
                            and self._isAngleInThirdQuadrant(startAngle)) or (
                                endAngle == -180
                                and self._isAngleInSecondQuadrant(startAngle)):
            if startAngle == 180 or self._isAngleInThirdQuadrant(startAngle):
                spanAngle = endAngle - (startAngle + 360)
            else:
                spanAngle = (endAngle + 360) - startAngle
        else:
            spanAngle = endAngle - startAngle
        #print("start angle is " + str(startAngle))
        #print("span angle is " + str(spanAngle))

        self.__painter.begin(self.__board)
        self.__penColor = QColor("red")
        self.__painter.setPen(QPen(self.__penColor, self.__thickness))
        self.__painter.drawArc(rect, 16 * startAngle, 16 * spanAngle)
        self.__painter.end()

        self.update()  #Show updates

    def paintBezierSpline(self, pointListX, pointListY):
        P1 = QPoint(int(pointListX[0]), int(pointListY[0]))
        path = QtGui.QPainterPath()
        path.moveTo(P1)

        self.__painter.begin(self.__board)
        self.__penColor = QColor("black")
        self.__painter.setPen(QPen(self.__penColor, self.__thickness))

        i = 0
        while i < len(pointListX) - 3:
            P2 = QPoint(int(pointListX[i + 1]), int(pointListY[i + 1]))
            P3 = QPoint(int(pointListX[i + 2]), int(pointListY[i + 2]))
            P4 = QPoint(int(pointListX[i + 3]), int(pointListY[i + 3]))
            path.cubicTo(P2, P3, P4)
            self.__painter.drawPath(path)
            i += 3

        self.__painter.end()

        self.update()  #Show updates
예제 #49
0
파일: view.py 프로젝트: mrmac123/calibre
    def paintEvent(self, event):
        QSplitterHandle.paintEvent(self, event)
        left, right = self.parent().left, self.parent().right
        painter = QPainter(self)
        painter.setClipRect(event.rect())
        w = self.width()
        h = self.height()
        painter.setRenderHints(QPainter.Antialiasing, True)

        C = 16  # Curve factor.

        def create_line(ly, ry, right_to_left=False):
            ' Create path that represents upper or lower line of change marker '
            line = QPainterPath()
            if not right_to_left:
                line.moveTo(0, ly)
                line.cubicTo(C, ly, w - C, ry, w, ry)
            else:
                line.moveTo(w, ry)
                line.cubicTo(w - C, ry, C, ly, 0, ly)
            return line

        ldoc, rdoc = left.document(), right.document()
        lorigin, rorigin = left.contentOffset(), right.contentOffset()
        lfv, rfv = left.firstVisibleBlock().blockNumber(
        ), right.firstVisibleBlock().blockNumber()
        lines = []

        for (ltop, lbot, kind), (rtop, rbot,
                                 kind) in zip(left.changes, right.changes):
            if lbot < lfv and rbot < rfv:
                continue
            ly_top = left.blockBoundingGeometry(
                ldoc.findBlockByNumber(ltop)).translated(lorigin).y()
            ly_bot = left.blockBoundingGeometry(
                ldoc.findBlockByNumber(lbot)).translated(lorigin).y()
            ry_top = right.blockBoundingGeometry(
                rdoc.findBlockByNumber(rtop)).translated(rorigin).y()
            ry_bot = right.blockBoundingGeometry(
                rdoc.findBlockByNumber(rbot)).translated(rorigin).y()
            if max(ly_top, ly_bot, ry_top, ry_bot) < 0:
                continue
            if min(ly_top, ly_bot, ry_top, ry_bot) > h:
                break

            upper_line = create_line(ly_top, ry_top)
            lower_line = create_line(ly_bot, ry_bot, True)

            region = QPainterPath()
            region.moveTo(0, ly_top)
            region.connectPath(upper_line)
            region.lineTo(w, ry_bot)
            region.connectPath(lower_line)
            region.closeSubpath()

            painter.fillPath(region, left.diff_backgrounds[kind])
            for path, aa in zip((upper_line, lower_line),
                                (ly_top != ry_top, ly_bot != ry_bot)):
                lines.append((kind, path, aa))

        for kind, path, aa in sorted(
                lines, key=lambda x: {'replace': 0}.get(x[0], 1)):
            painter.setPen(left.diff_foregrounds[kind])
            painter.setRenderHints(QPainter.Antialiasing, aa)
            painter.drawPath(path)

        painter.setFont(left.heading_font)
        for (lnum, text), (rnum, text) in zip(left.headers, right.headers):
            ltop, lbot, rtop, rbot = lnum, lnum + 3, rnum, rnum + 3
            if lbot < lfv and rbot < rfv:
                continue
            ly_top = left.blockBoundingGeometry(
                ldoc.findBlockByNumber(ltop)).translated(lorigin).y()
            ly_bot = left.blockBoundingGeometry(
                ldoc.findBlockByNumber(lbot)).translated(lorigin).y()
            ry_top = right.blockBoundingGeometry(
                rdoc.findBlockByNumber(rtop)).translated(rorigin).y()
            ry_bot = right.blockBoundingGeometry(
                rdoc.findBlockByNumber(rbot)).translated(rorigin).y()
            if max(ly_top, ly_bot, ry_top, ry_bot) < 0:
                continue
            if min(ly_top, ly_bot, ry_top, ry_bot) > h:
                break
            ly = painter.boundingRect(3, ly_top, left.width(),
                                      ly_bot - ly_top - 5, Qt.TextSingleLine,
                                      text).bottom() + 3
            ry = painter.boundingRect(3, ry_top, right.width(),
                                      ry_bot - ry_top - 5, Qt.TextSingleLine,
                                      text).bottom() + 3
            line = create_line(ly, ry)
            painter.setPen(QPen(left.palette().text(), 2))
            painter.setRenderHints(QPainter.Antialiasing, ly != ry)
            painter.drawPath(line)

        painter.end()
        # Paint the splitter without the change lines if the mouse is over the
        # splitter
        if getattr(self, 'hover', False):
            QSplitterHandle.paintEvent(self, event)
예제 #50
0
    def paintEvent(self, event):
        contents_y = self.edit.verticalScrollBar().value()
        page_bottom = contents_y + self.edit.viewport().height()
        font_metrics = self.fontMetrics()
        current_block = self.edit.document().findBlock(
            self.edit.textCursor().position())

        painter = QPainter(self)

        line_count = 0
        # Iterate over all text blocks in the document.
        block = self.edit.document().begin()
        while block.isValid():
            line_count += 1

            # The top left position of the block in the document
            position = self.edit.document().documentLayout().blockBoundingRect(
                block).topLeft()

            # Check if the position of the block is out side of the visible
            # area.
            if position.y() > page_bottom:
                break

            # We want the line number for the selected line to be bold.
            bold = False
            if block == current_block:
                bold = True
                font = painter.font()
                font.setBold(True)
                painter.setFont(font)

            # Draw the line number right justified at the y position of the
            # line. 3 is a magic padding number. drawText(x, y, text).
            painter.drawText(
                self.width() - font_metrics.width(str(line_count)) - 3,
                round(position.y()) - contents_y + font_metrics.ascent(),
                str(line_count))

            # Remove the bold style if it was set previously.
            if bold:
                font = painter.font()
                font.setBold(False)
                painter.setFont(font)

            block = block.next()

        self.highest_line = line_count
        painter.end()

        QWidget.paintEvent(self, event)
예제 #51
0
파일: main.py 프로젝트: JackonYang/calibre
 def paintEvent(self, ev):
     br = ev.region().boundingRect()
     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()
예제 #52
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()
예제 #53
0
파일: text.py 프로젝트: Hainish/calibre
    def paint_line_numbers(self, ev):
        painter = QPainter(self.line_number_area)
        painter.fillRect(ev.rect(),
                         self.line_number_palette.color(QPalette.Base))

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

        while block.isValid() and top <= ev.rect().bottom():
            if block.isVisible() and bottom >= ev.rect().top():
                if current == num:
                    painter.save()
                    painter.setPen(
                        self.line_number_palette.color(QPalette.BrightText))
                    f = QFont(self.font())
                    f.setBold(True)
                    painter.setFont(f)
                    self.last_current_lnum = (top, bottom - top)
                painter.drawText(0, top,
                                 self.line_number_area.width() - 5,
                                 self.fontMetrics().height(), Qt.AlignRight,
                                 str(num + 1))
                if current == num:
                    painter.restore()
            block = block.next()
            top = bottom
            bottom = top + int(self.blockBoundingRect(block).height())
            num += 1
예제 #54
0
        def numberbarPaint(self, number_bar, event):
            font_metrics = self.fontMetrics()
            current_line = self.document().findBlock(
                self.textCursor().position()).blockNumber() + 1

            block = self.firstVisibleBlock()
            line_count = block.blockNumber()
            painter = QPainter(number_bar)
            painter.fillRect(event.rect(), self.palette().base())

            # Iterate over all visible text blocks in the document.
            while block.isValid():
                line_count += 1
                block_top = self.blockBoundingGeometry(block).translated(
                    self.contentOffset()).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

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

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

                block = block.next()

            painter.end()
예제 #55
0
        def numberbarPaint(self, number_bar, event):
            font_metrics = self.fontMetrics()
            current_line = self.document().findBlock(self.textCursor().position()).blockNumber() + 1

            block = self.firstVisibleBlock()
            line_count = block.blockNumber()
            painter = QPainter(number_bar)
            painter.fillRect(event.rect(), self.palette().base())

            # Iterate over all visible text blocks in the document.
            while block.isValid():
                line_count += 1
                block_top = self.blockBoundingGeometry(block).translated(self.contentOffset()).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

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

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

                block = block.next()

            painter.end()
예제 #56
0
    def paintEvent(self, ev):
        offset = QPoint(0, 0)
        p = QPainter(self)
        p.setClipRect(ev.rect())
        bottom = self.rect().bottom()

        if self.results:
            for i, (prefix, full, text) in enumerate(self.results):
                size = prefix.size()
                if offset.y() + size.height() > bottom:
                    break
                self.max_result = i
                offset.setX(0)
                if i in (self.current_result, self.mouse_hover_result):
                    p.save()
                    if i != self.current_result:
                        p.setPen(Qt.DotLine)
                    p.drawLine(offset, QPoint(self.width(), offset.y()))
                    p.restore()
                offset.setY(offset.y() + self.MARGIN // 2)
                p.drawStaticText(offset, prefix)
                offset.setX(self.maxwidth + 5)
                p.drawStaticText(offset, self.divider)
                offset.setX(offset.x() + self.divider.size().width())
                p.drawStaticText(offset, full)
                offset.setY(offset.y() + size.height() + self.MARGIN // 2)
                if i in (self.current_result, self.mouse_hover_result):
                    offset.setX(0)
                    p.save()
                    if i != self.current_result:
                        p.setPen(Qt.DotLine)
                    p.drawLine(offset, QPoint(self.width(), offset.y()))
                    p.restore()
        else:
            p.drawText(self.rect(), Qt.AlignCenter, _('No results found'))

        p.end()
예제 #57
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.)
     y = int(abs(ch - h)/2.)
     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()
예제 #58
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()
예제 #59
0
    def paintEvent(self, event):
        h = self.size().height()
        w = self.size().width()

        contents_y = self.edit.verticalScrollBar().value()
        page_bottom = contents_y + self.edit.viewport().height()
        font_metrics = self.fontMetrics()

        painter = QPainter(self)
        painter.setBackgroundMode(QtCore.Qt.OpaqueMode)
        bgc = QtGui.QColor(0, 0, 0)
        painter.fillRect(0, 0, w, h, bgc)

        numbersborderc = QtGui.QColor(55, 75, 75)
        painter.setPen(numbersborderc)
        painter.drawLine(w - 1, 0, w - 1, h)

        bg = QtGui.QBrush(bgc)
        painter.setBackground(bg)
        textc = QtGui.QColor(55, 255, 255)
        painter.setPen(textc)
        fg = QtGui.QBrush(bgc)
        painter.setBrush(fg)

        line_count = 0
        # Iterate over all text blocks in the document.
        block = self.edit.document().begin()
        while block.isValid():
            line_count += 1

            # The top left position of the block in the document
            position = self.edit.document().documentLayout().blockBoundingRect(
                block).topLeft()

            # Draw the line number right justified at the y position of the
            # line. 3 is a magic padding number. drawText(x, y, text).
            painter.drawText(
                self.width() - font_metrics.width(str(line_count)) - 8,
                round(position.y()) - contents_y + font_metrics.ascent(),
                str(line_count))

            block = block.next()

        self.highest_line = line_count
        painter.end()

        QWidget.paintEvent(self, event)
예제 #60
0
def create_icon(text, palette=None, sz=32, divider=2):
    if palette is None:
        palette = QApplication.palette()
    img = QImage(sz, sz, QImage.Format_ARGB32)
    img.fill(Qt.transparent)
    p = QPainter(img)
    p.setRenderHints(p.TextAntialiasing | p.Antialiasing)
    qDrawShadeRect(p,
                   img.rect(),
                   palette,
                   fill=QColor('#ffffff'),
                   lineWidth=1,
                   midLineWidth=1)
    f = p.font()
    f.setFamily('Liberation Sans'), f.setPixelSize(sz //
                                                   divider), f.setBold(True)
    p.setFont(f), p.setPen(Qt.black)
    p.drawText(img.rect().adjusted(2, 2, -2, -2), Qt.AlignCenter, text)
    p.end()
    return QIcon(QPixmap.fromImage(img))