def entry_to_icon_text(entry, only_text=False): if only_text: return entry.get('name', entry.get('Name')) or _('Unknown') data = entry.get('icon_data') if data is None: icon = QIcon(I('blank.png')) else: pmap = QPixmap() pmap.loadFromData(bytes(data)) icon = QIcon(pmap) return icon, entry.get('name', entry.get('Name')) or _('Unknown')
def __init__(self, parent): QWizard.__init__(self, parent) self.setWindowTitle(__appname__+' '+_('welcome wizard')) p = QPixmap() p.loadFromData(open(P('content_server/calibre.png'), 'rb').read()) self.setPixmap(self.LogoPixmap, p.scaledToHeight(80, Qt.SmoothTransformation)) self.setPixmap(self.WatermarkPixmap, QPixmap(I('welcome_wizard.png'))) self.setPixmap(self.BackgroundPixmap, QPixmap(I('wizard.png'))) self.device_page = DevicePage() self.library_page = LibraryPage() self.library_page.retranslate.connect(self.retranslate) self.finish_page = FinishPage() self.set_finish_text() self.kindle_page = KindlePage() self.stanza_page = StanzaPage() self.setPage(self.library_page.ID, self.library_page) self.setPage(self.device_page.ID, self.device_page) self.setPage(self.finish_page.ID, self.finish_page) self.setPage(self.kindle_page.ID, self.kindle_page) self.setPage(self.stanza_page.ID, self.stanza_page) self.device_extra_page = None nh, nw = min_available_height()-75, available_width()-30 if nh < 0: nh = 580 if nw < 0: nw = 400 nh = min(400, nh) nw = min(580, nw) self.resize(nw, nh) self.set_button_texts()
class CoverView(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.current_pixmap_size = QSize(0, 0) self.pixmap = QPixmap() self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) def set_pixmap(self, data): self.pixmap.loadFromData(data) self.current_pixmap_size = self.pixmap.size() self.update() def paintEvent(self, event): if self.pixmap.isNull(): return canvas_size = self.rect() width = self.current_pixmap_size.width() extrax = canvas_size.width() - width if extrax < 0: extrax = 0 x = int(extrax / 2.0) height = self.current_pixmap_size.height() extray = canvas_size.height() - height if extray < 0: extray = 0 y = int(extray / 2.0) target = QRect(x, y, min(canvas_size.width(), width), min(canvas_size.height(), height)) p = QPainter(self) p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform) p.drawPixmap(target, self.pixmap.scaled(target.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)) p.end() def sizeHint(self): return QSize(300, 400)
def __init__(self, controller): super().__init__() self.setWindowTitle("QuickText") self.setGeometry(100,100,1030,800) pixmap = QPixmap() pixmap.loadFromData(get_data(__name__, 'icon.png')) self.setWindowIcon(QIcon(pixmap)) self.setStatusBar(QuiStatusBar()) self.addDockWidget(Qt.RightDockWidgetArea, QuiDock(controller)) self.setCentralWidget(controller.document_editor) self.addToolBar(QuiToolbar(self, 'FileToolbar', [ (None, "Open", "Open a file", None, controller.load), (None, "Save", "Save the current file", None, controller.save), (None, "Exit", "Exit", None, controller.end), ])) self.addToolBar(QuiToolbar(self, 'FormatToolbar', [ (None, "Heading 1", "Heading level one", "Ctrl+1", lambda: controller.document_editor.setCurrentFont(controller.document_editor.format_h1)), (None, "Heading 2", "Heading level two", "Ctrl+2", lambda: controller.document_editor.setCurrentFont(controller.document_editor.format_h2)), (None, "Heading 3", "Heading level three", "Ctrl+3", lambda: controller.document_editor.setCurrentFont(controller.document_editor.format_h3)), (None, "Heading 4", "Heading level four", "Ctrl+4", lambda: controller.document_editor.setCurrentFont(controller.document_editor.format_h4)), (None, "Heading 5", "Heading level five", "Ctrl+5", lambda: controller.document_editor.setCurrentFont(controller.document_editor.format_h5)), (None, "Heading 6", "Heading level six", "Ctrl+6", lambda: controller.document_editor.setCurrentFont(controller.document_editor.format_h6)), (None, "Body", "Simple body text", "Ctrl+`", lambda: controller.document_editor.setCurrentFont(controller.document_editor.format_p)), ]))
def get_pixmap(icon_name): ''' Retrieve a QPixmap for the named image Any icons belonging to the plugin must be prefixed with 'images/' ''' global plugin_icon_resources, plugin_name if not icon_name.startswith('images/'): # We know this is definitely not an icon belonging to this plugin pixmap = QPixmap() pixmap.load(I(icon_name)) return pixmap # Check to see whether the icon exists as a Calibre resource # This will enable skinning if the user stores icons within a folder like: # ...\AppData\Roaming\calibre\resources\images\Plugin Name\ if plugin_name: local_images_dir = get_local_images_dir(plugin_name) local_image_path = os.path.join(local_images_dir, icon_name.replace('images/', '')) if os.path.exists(local_image_path): pixmap = QPixmap() pixmap.load(local_image_path) return pixmap # As we did not find an icon elsewhere, look within our zip resources if icon_name in plugin_icon_resources: pixmap = QPixmap() pixmap.loadFromData(plugin_icon_resources[icon_name]) return pixmap return None
def get_icons(zfp, name_or_list_of_names): ''' Load icons from the plugin zip file :param name_or_list_of_names: List of paths to resources in the zip file using / as separator, or a single path :return: A dictionary of the form ``{name : QIcon}``. Any names that were not found in the zip file will be null QIcons. If a single path is passed in the return value will be A QIcon. ''' from PyQt5.Qt import QIcon, QPixmap names = name_or_list_of_names ans = get_resources(zfp, names) if isinstance(names, basestring): names = [names] if ans is None: ans = {} if isinstance(ans, basestring): ans = dict([(names[0], ans)]) ians = {} for name in names: p = QPixmap() raw = ans.get(name, None) if raw: p.loadFromData(raw) ians[name] = QIcon(p) if len(names) == 1: ians = ians.pop(names[0]) return ians
def initialize_metadata_options(self): self.initialize_combos() self.author.editTextChanged.connect(self.deduce_author_sort) mi = self.db.get_metadata(self.book_id, index_is_id=True) self.title.setText(mi.title) self.publisher.show_initial_value(mi.publisher if mi.publisher else '') self.author_sort.setText(mi.author_sort if mi.author_sort else '') self.tags.setText(', '.join(mi.tags if mi.tags else [])) self.tags.update_items_cache(self.db.all_tags()) self.comment.html = comments_to_html(mi.comments) if mi.comments else '' self.series.show_initial_value(mi.series if mi.series else '') if mi.series_index is not None: try: self.series_index.setValue(mi.series_index) except: self.series_index.setValue(1.0) cover = self.db.cover(self.book_id, index_is_id=True) if cover: pm = QPixmap() pm.loadFromData(cover) if not pm.isNull(): self.cover.setPixmap(pm) self.cover_data = cover self.set_cover_tooltip(pm) else: self.cover.setPixmap(QPixmap(I('default_cover.png'))) self.cover.setToolTip(_('This book has no cover')) for x in ('author', 'series', 'publisher'): x = getattr(self, x) x.lineEdit().deselect()
def select_cover(self): files = choose_images(self, 'change cover dialog', _('Choose cover for ') + unicode(self.title.text())) if not files: return _file = files[0] if _file: _file = os.path.abspath(_file) if not os.access(_file, os.R_OK): d = error_dialog(self.parent(), _('Cannot read'), _('You do not have permission to read the file: ') + _file) d.exec_() return cf, cover = None, None try: cf = open(_file, "rb") cover = cf.read() except IOError as e: d = error_dialog(self.parent(), _('Error reading file'), _("<p>There was an error reading from file: <br /><b>") + _file + "</b></p><br />"+str(e)) d.exec_() if cover: pix = QPixmap() pix.loadFromData(cover) if pix.isNull(): d = error_dialog(self.parent(), _('Error reading file'), _file + _(" is not a valid picture")) d.exec_() else: self.cover_path.setText(_file) self.set_cover_tooltip(pix) self.cover.setPixmap(pix) self.cover_changed = True self.cpixmap = pix self.cover_data = cover
def entry_to_icon_text(entry): data = entry.get('icon_data') if data is None: icon = QIcon(I('blank.png')) else: pmap = QPixmap() pmap.loadFromData(bytes(data)) icon = QIcon(pmap) return icon, entry['Name']
def data(self, index, role): row, col = index.row(), index.column() if row >= len(self.matches): return None result = self.matches[row] if role == Qt.DisplayRole: if col == 1: t = result.title if result.title else _('Unknown') a = result.author if result.author else '' return ('<b>%s</b><br><i>%s</i>' % (t, a)) elif col == 2: return (result.price) elif col == 4: return ('<span>%s<br>%s</span>' % (result.store_name, result.formats)) return None elif role == Qt.DecorationRole: if col == 0 and result.cover_data: p = QPixmap() p.loadFromData(result.cover_data) p.setDevicePixelRatio(QApplication.instance().devicePixelRatio()) return p if col == 3: if result.drm == SearchResult.DRM_LOCKED: return (self.DRM_LOCKED_ICON) elif result.drm == SearchResult.DRM_UNLOCKED: return (self.DRM_UNLOCKED_ICON) elif result.drm == SearchResult.DRM_UNKNOWN: return (self.DRM_UNKNOWN_ICON) if col == 5: if result.downloads: return (self.DOWNLOAD_ICON) if col == 6: if result.affiliate: return (self.DONATE_ICON) elif role == Qt.ToolTipRole: if col == 1: return ('<p>%s</p>' % result.title) elif col == 2: return ('<p>' + _('Detected price as: %s. Check with the store before making a purchase to verify this price is correct. This price often does not include promotions the store may be running.') % result.price + '</p>') # noqa elif col == 3: if result.drm == SearchResult.DRM_LOCKED: return ('<p>' + _('This book as been detected as having DRM restrictions. This book may not work with your reader and you will have limitations placed upon you as to what you can do with this book. Check with the store before making any purchases to ensure you can actually read this book.') + '</p>') # noqa elif result.drm == SearchResult.DRM_UNLOCKED: return ('<p>' + _('This book has been detected as being DRM Free. You should be able to use this book on any device provided it is in a format calibre supports for conversion. However, before making a purchase double check the DRM status with the store. The store may not be disclosing the use of DRM.') + '</p>') # noqa else: return ('<p>' + _('The DRM status of this book could not be determined. There is a very high likelihood that this book is actually DRM restricted.') + '</p>') # noqa elif col == 4: return ('<p>%s</p>' % result.formats) elif col == 5: if result.downloads: return ('<p>' + _('The following formats can be downloaded directly: %s.') % ', '.join(result.downloads.keys()) + '</p>') elif col == 6: if result.affiliate: return ('<p>' + _('Buying from this store supports the calibre developer: %s.') % result.plugin_author + '</p>') elif role == Qt.SizeHintRole: return QSize(64, 64) return None
def __init__(self, data, encoding, x0, y0, x1, y1, xsize, ysize): p = QPixmap() p.loadFromData(data, encoding, Qt.AutoColor) w, h = p.width(), p.height() p = p.copy(x0, y0, min(w, x1-x0), min(h, y1-y0)) if p.width() != xsize or p.height() != ysize: p = p.scaled(xsize, ysize, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) QGraphicsPixmapItem.__init__(self, p) self.height, self.width = ysize, xsize self.setTransformationMode(Qt.SmoothTransformation) self.setShapeMode(QGraphicsPixmapItem.BoundingRectShape)
def load(data): p = QPixmap() p.loadFromData(bytes(data)) try: dpr = self.devicePixelRatioF() except AttributeError: dpr = self.devicePixelRatio() p.setDevicePixelRatio(dpr) if data and p.isNull(): p = self.failed_img return p
def get_icon(name): if not name.startswith("images/"): name = "images/" + name try: return _icon_cache[name] except KeyError: raw = get_data_as_file(name).read() pixmap = QPixmap() pixmap.loadFromData(raw) icon = _icon_cache[name] = QIcon() icon.addPixmap(pixmap) return icon
def icon(self): if self._icon is None: self._icon = QIcon() url = places.favicon_url(self.place_id) if url is not None: f = QApplication.instance().disk_cache.data(QUrl(url)) if f is not None: with closing(f): raw = f.readAll() p = QPixmap() p.loadFromData(raw) if not p.isNull(): self._icon.addPixmap(p) return self._icon
def update_cover(self, pmap=None, cdata=None): if pmap is None: pmap = QPixmap() pmap.loadFromData(cdata) if pmap.isNull(): return self.pixmap = pmap self.do_layout() self.update() self.update_tooltip(getattr(self.parent(), 'current_path', '')) if not config['disable_animations']: self.animation.start() id_ = self.data.get('id', None) if id_ is not None: self.cover_changed.emit(id_, cdata or pixmap_to_data(pmap))
def read_icon(handle, icon): must_use_qt() resource = win32api.LoadResource(handle, win32con.RT_ICON, icon.id) pixmap = QPixmap() pixmap.loadFromData(resource) hicon = None if pixmap.isNull(): if icon.width > 0 and icon.height > 0: hicon = ctypes.windll.user32.CreateIconFromResourceEx( resource, len(resource), True, 0x00030000, icon.width, icon.height, win32con.LR_DEFAULTCOLOR) else: hicon = win32gui.CreateIconFromResource(resource, True) pixmap = hicon_to_pixmap(hicon).copy() win32gui.DestroyIcon(hicon) return pixmap
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()
def dump(self, items, out_stream, pdf_metadata): opts = self.opts page_size = get_page_size(self.opts) ml, mr = opts.margin_left, opts.margin_right self.doc = PdfDevice( out_stream, page_size=page_size, left_margin=ml, top_margin=opts.margin_top, right_margin=mr, bottom_margin=opts.margin_bottom, errors=self.log.error, debug=self.log.debug, compress=not opts.uncompressed_pdf, opts=opts, mark_links=opts.pdf_mark_links) self.painter = QPainter(self.doc) self.doc.set_metadata(title=pdf_metadata.title, author=pdf_metadata.author, tags=pdf_metadata.tags, mi=pdf_metadata.mi) self.doc_title = pdf_metadata.title self.doc_author = pdf_metadata.author for imgpath in items: self.log.debug('Processing %s...' % imgpath) self.doc.init_page() p = QPixmap() with lopen(imgpath, 'rb') as f: if not p.loadFromData(f.read()): raise ValueError('Could not read image from: {}'.format(imgpath)) draw_image_page(QRect(*self.doc.full_page_rect), self.painter, p, preserve_aspect_ratio=True) self.doc.end_page() 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 update_cover(self, pmap=None, cdata=None): if pmap is None: pmap = QPixmap() pmap.loadFromData(cdata) if pmap.isNull(): return if pmap.hasAlphaChannel(): pmap = QPixmap.fromImage(blend_image(image_from_x(pmap))) self.pixmap = pmap self.do_layout() self.update() self.update_tooltip(getattr(self.parent(), 'current_path', '')) if not config['disable_animations']: self.animation.start() id_ = self.data.get('id', None) if id_ is not None: self.cover_changed.emit(id_, cdata or pixmap_to_data(pmap))
def entry_to_icon_text(entry, only_text=False): if only_text: return entry.get('name', entry.get('Name')) or _('Unknown') data = entry.get('icon_data') if isinstance(data, str): with suppress(Exception): from base64 import standard_b64decode data = bytearray(standard_b64decode(data)) if not isinstance(data, (bytearray, bytes)): icon = QIcon(I('blank.png')) else: pmap = QPixmap() pmap.loadFromData(bytes(data)) if pmap.isNull(): icon = QIcon(I('blank.png')) else: icon = QIcon(pmap) return icon, entry.get('name', entry.get('Name')) or _('Unknown')
def load_icon_resource_as_pixmap(icon_resource, size=ICON_SIZE): if not icon_resource: return parts = tuple(filter(None, re.split(r',([-0-9]+$)', icon_resource))) if len(parts) != 2: return module, index = parts index = int(index) if module.startswith('"') and module.endswith('"'): module = split_commandline(module)[0] hmodule = winutil.load_library( module, winutil.LOAD_LIBRARY_AS_DATAFILE | winutil.LOAD_LIBRARY_AS_IMAGE_RESOURCE) icons = winutil.load_icons(hmodule, index) pixmaps = [] must_use_qt() for icon_data, icon_handle in icons: pixmap = QPixmap() pixmap.loadFromData(icon_data) if pixmap.isNull() and bool(icon_handle): pixmap = hicon_to_pixmap(icon_handle) if pixmap.isNull(): continue pixmaps.append(pixmap) if not pixmaps: return def area(p): return p.width() * p.height() pixmaps.sort(key=area) q = size * size for pmap in pixmaps: if area(pmap) >= q: if area(pmap) == q: return pmap return pmap.scaled(size, size, aspectRatioMode=Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation) return pixmaps[-1].scaled(size, size, aspectRatioMode=Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation)
def initialize_metadata_options(self): self.initialize_combos() self.author.editTextChanged.connect(self.deduce_author_sort) mi = self.db.get_metadata(self.book_id, index_is_id=True) self.title.setText(mi.title), self.title.home(False) self.publisher.show_initial_value(mi.publisher if mi.publisher else '') self.publisher.home(False) self.author_sort.setText(mi.author_sort if mi.author_sort else '') self.author_sort.home(False) self.tags.setText(', '.join(mi.tags if mi.tags else [])) self.tags.update_items_cache(self.db.all_tags()) self.tags.home(False) self.comment.html = comments_to_html( mi.comments) if mi.comments else '' self.series.show_initial_value(mi.series if mi.series else '') self.series.home(False) if mi.series_index is not None: try: self.series_index.setValue(mi.series_index) except: self.series_index.setValue(1.0) cover = self.db.cover(self.book_id, index_is_id=True) if cover: pm = QPixmap() pm.loadFromData(cover) if not pm.isNull(): pm.setDevicePixelRatio( getattr(self, 'devicePixelRatioF', self.devicePixelRatio)()) self.cover.setPixmap(pm) self.cover_data = cover self.set_cover_tooltip(pm) else: pm = QPixmap(I('default_cover.png')) pm.setDevicePixelRatio( getattr(self, 'devicePixelRatioF', self.devicePixelRatio)()) self.cover.setPixmap(pm) self.cover.setToolTip(_('This book has no cover')) for x in ('author', 'series', 'publisher'): x = getattr(self, x) x.lineEdit().deselect() self.series_changed()
def data(self, role): if role == Qt.DisplayRole: return (self.title) if role == Qt.DecorationRole: if self.icon is None: icon = '%s.png' % self.urn[8:] p = QPixmap() if icon in self.favicons: try: with zipfile.ZipFile(self.zf, 'r') as zf: p.loadFromData(zf.read(self.favicons[icon])) except: pass if not p.isNull(): self.icon = (QIcon(p)) else: self.icon = self.default_icon return self.icon return None
def data(self, role): if role == Qt.DisplayRole: return (self.title) if role == Qt.DecorationRole: if self.icon is None: icon = '%s.png'%self.urn[8:] p = QPixmap() if icon in self.favicons: try: with zipfile.ZipFile(self.zf, 'r') as zf: p.loadFromData(zf.read(self.favicons[icon])) except: pass if not p.isNull(): self.icon = (QIcon(p)) else: self.icon = self.default_icon return self.icon return None
def select_cover(self): files = choose_images( self, 'change cover dialog', _('Choose cover for ') + unicode(self.title.text())) if not files: return _file = files[0] if _file: _file = os.path.abspath(_file) if not os.access(_file, os.R_OK): d = error_dialog( self.parent(), _('Cannot read'), _('You do not have permission to read the file: ') + _file) d.exec_() return cf, cover = None, None try: cf = open(_file, "rb") cover = cf.read() except IOError as e: d = error_dialog( self.parent(), _('Error reading file'), _("<p>There was an error reading from file: <br /><b>") + _file + "</b></p><br />" + str(e)) d.exec_() if cover: pix = QPixmap() pix.loadFromData(cover) pix.setDevicePixelRatio( getattr(self, 'devicePixelRatioF', self.devicePixelRatio)()) if pix.isNull(): d = error_dialog(self.parent(), _('Error reading file'), _file + _(" is not a valid picture")) d.exec_() else: self.cover_path.setText(_file) self.set_cover_tooltip(pix) self.cover.setPixmap(pix) self.cover_changed = True self.cpixmap = pix self.cover_data = cover
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()
def dropEvent(self, event): event.setDropAction(Qt.CopyAction) md = event.mimeData() x, y = dnd_get_image(md) if x is not None: # We have an image, set cover event.accept() if y is None: # Local image self.handle_image_drop(x) else: # Remote files, use the first file d = DownloadDialog(x, y, self) d.start_download() if d.err is None: pmap = QPixmap() pmap.loadFromData(open(d.fpath, 'rb').read()) if not pmap.isNull(): self.handle_image_drop(pmap)
def dropEvent(self, event): event.setDropAction(Qt.CopyAction) md = event.mimeData() x, y = dnd_get_image(md) if x is not None: # We have an image, set cover event.accept() if y is None: # Local image self.handle_image_drop(x) else: # Remote files, use the first file d = DownloadDialog(x, y, self) d.start_download() if d.err is None: pmap = QPixmap() pmap.loadFromData(open(d.fpath, 'rb').read()) if not pmap.isNull(): self.handle_image_drop(pmap)
class CoverView(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.current_pixmap_size = QSize(0, 0) self.pixmap = QPixmap() self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) def set_pixmap(self, data): self.pixmap.loadFromData(data) self.current_pixmap_size = self.pixmap.size() self.update() def paintEvent(self, event): if self.pixmap.isNull(): return 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, min(canvas_size.width(), width), min(canvas_size.height(), height)) p = QPainter(self) p.setRenderHints(QPainter.RenderHint.Antialiasing | QPainter.RenderHint.SmoothPixmapTransform) p.drawPixmap( target, self.pixmap.scaled(target.size(), Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)) p.end() def sizeHint(self): return QSize(300, 400)
def update_result(self, plugin_name, width, height, data): if plugin_name.endswith('}'): # multi cover plugin plugin_name = plugin_name.partition('{')[0] plugin = [ plugin for plugin in self.plugin_map if plugin.name == plugin_name ] if not plugin: return plugin = plugin[0] last_row = max(self.plugin_map[plugin]) pmap = QPixmap() pmap.loadFromData(data) if pmap.isNull(): return self.beginInsertRows(QModelIndex(), last_row, last_row) for rows in self.plugin_map.itervalues(): for i in xrange(len(rows)): if rows[i] >= last_row: rows[i] += 1 self.plugin_map[plugin].insert(-1, last_row) self.covers.insert(last_row, self.get_item(plugin_name, pmap, waiting=False)) self.endInsertRows() else: # single cover plugin idx = None for plugin, rows in self.plugin_map.iteritems(): if plugin.name == plugin_name: idx = rows[0] break if idx is None: return pmap = QPixmap() pmap.loadFromData(data) if pmap.isNull(): return self.covers[idx] = self.get_item(plugin_name, pmap, waiting=False) self.dataChanged.emit(self.index(idx), self.index(idx))
def dnd_get_image(md, image_exts=None): ''' Get the image in the QMimeData object md. :return: None, None if no image is found QPixmap, None if an image is found, the pixmap is guaranteed not null url, filename if a URL that points to an image is found ''' if md.hasImage(): for x in md.formats(): x = unicode_type(x) if x.startswith('image/'): cdata = bytes(md.data(x)) pmap = QPixmap() pmap.loadFromData(cdata) if not pmap.isNull(): return pmap, None break if md.hasFormat('application/octet-stream'): cdata = bytes(md.data('application/octet-stream')) pmap = QPixmap() pmap.loadFromData(cdata) if not pmap.isNull(): return pmap, None if image_exts is None: image_exts = image_extensions() # No image, look for an URL pointing to an image urls = urls_from_md(md) paths = [path_from_qurl(u) for u in urls] # First look for a local file images = [ xi for xi in paths if posixpath.splitext(unquote(xi))[1][1:].lower() in image_exts ] images = [xi for xi in images if os.path.exists(xi)] p = QPixmap() for path in images: try: with open(path, 'rb') as f: p.loadFromData(f.read()) except Exception: continue if not p.isNull(): return p, None # No local images, look for remote ones # First, see if this is from Firefox rurl, fname = get_firefox_rurl(md, image_exts) if rurl and fname: return rurl, fname # Look through all remaining URLs for remote_url, filename in remote_urls_from_qurl(urls, image_exts): return remote_url, filename return None, None
def customize_ui(self, ui): self._view = ui ui.tool_bar.addSeparator() # to be detected later for toc population ui.annotation_toc_model = None ui.annotation_toc = None # HACK? # append a callback to the javaScriptWindowObjectCleared # signal receiver. If you don't do this, the `py_annotator` # object will be empty (has no python functions callable) # from js ui.view.document.mainFrame().javaScriptWindowObjectCleared.connect( self.add_window_objects) ui.annotation_toc_dock = d = QDockWidget(_('Annotations'), ui) ui.annotation_toc_container = w = QWidget(ui) w.l = QVBoxLayout(w) d.setObjectName('annotation-toc-dock') d.setWidget(w) # d.close() # start hidden? or leave default ui.addDockWidget(Qt.LeftDockWidgetArea, d) d.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) name = 'action_annotate' pixmap = QPixmap() pixmap.loadFromData( self.load_resources(['images/icon.png']).itervalues().next()) icon = QIcon(pixmap) ac = ui.annotation_toc_dock.toggleViewAction() ac.setIcon(icon) setattr(ui.tool_bar, name, ac) ac.setObjectName(name) ui.tool_bar.addAction(ac)
def dnd_get_image(md, image_exts=None): ''' Get the image in the QMimeData object md. :return: None, None if no image is found QPixmap, None if an image is found, the pixmap is guaranteed not null url, filename if a URL that points to an image is found ''' if md.hasImage(): for x in md.formats(): x = unicode_type(x) if x.startswith('image/'): cdata = bytes(md.data(x)) pmap = QPixmap() pmap.loadFromData(cdata) if not pmap.isNull(): return pmap, None break if md.hasFormat('application/octet-stream'): cdata = bytes(md.data('application/octet-stream')) pmap = QPixmap() pmap.loadFromData(cdata) if not pmap.isNull(): return pmap, None if image_exts is None: image_exts = image_extensions() # No image, look for an URL pointing to an image urls = urls_from_md(md) paths = [path_from_qurl(u) for u in urls] # First look for a local file images = [xi for xi in paths if posixpath.splitext(unquote(xi))[1][1:].lower() in image_exts] images = [xi for xi in images if os.path.exists(xi)] p = QPixmap() for path in images: try: with open(path, 'rb') as f: p.loadFromData(f.read()) except Exception: continue if not p.isNull(): return p, None # No local images, look for remote ones # First, see if this is from Firefox rurl, fname = get_firefox_rurl(md, image_exts) if rurl and fname: return rurl, fname # Look through all remaining URLs for remote_url, filename in remote_urls_from_qurl(urls, image_exts): return remote_url, filename return None, None
def from_mi(self, mi): p = getattr(mi, 'cover', None) if p and os.path.exists(p): pmap = QPixmap() with open(p, 'rb') as f: pmap.loadFromData(f.read()) if not pmap.isNull(): self.pixmap = pmap self.update() self.changed.emit() return cd = getattr(mi, 'cover_data', (None, None)) if cd and cd[1]: pmap = QPixmap() pmap.loadFromData(cd[1]) if not pmap.isNull(): self.pixmap = pmap self.update() self.changed.emit() return self.pixmap = None self.update() self.changed.emit()
def from_mi(self, mi): p = getattr(mi, 'cover', None) if p and os.path.exists(p): pmap = QPixmap() with open(p, 'rb') as f: pmap.loadFromData(f.read()) if not pmap.isNull(): self.pixmap = pmap self.update() self.changed.emit() return cd = getattr(mi, 'cover_data', (None, None)) if cd and cd[1]: pmap = QPixmap() pmap.loadFromData(cd[1]) if not pmap.isNull(): self.pixmap = pmap self.update() self.changed.emit() return self.pixmap = None self.update() self.changed.emit()
def customize_ui(self, ui): self._view = ui ui.tool_bar.addSeparator() # to be detected later for toc population ui.annotation_toc_model = None ui.annotation_toc = None # HACK? # append a callback to the javaScriptWindowObjectCleared # signal receiver. If you don't do this, the `py_annotator` # object will be empty (has no python functions callable) # from js ui.view.document.mainFrame().javaScriptWindowObjectCleared.connect( self.add_window_objects) ui.annotation_toc_dock = d = QDockWidget(_('Annotations'), ui) ui.annotation_toc_container = w = QWidget(ui) w.l = QVBoxLayout(w) d.setObjectName('annotation-toc-dock') d.setWidget(w) # d.close() # start hidden? or leave default ui.addDockWidget(Qt.LeftDockWidgetArea, d) d.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) name = 'action_annotate' pixmap = QPixmap() pixmap.loadFromData(self.load_resources(['images/icon.png']).itervalues().next()) icon = QIcon(pixmap) ac = ui.annotation_toc_dock.toggleViewAction() ac.setIcon(icon) setattr(ui.tool_bar, name, ac) ac.setObjectName(name) ui.tool_bar.addAction(ac)
def dnd_get_image(md, image_exts=IMAGE_EXTENSIONS): ''' Get the image in the QMimeData object md. :return: None, None if no image is found QPixmap, None if an image is found, the pixmap is guaranteed not null url, filename if a URL that points to an image is found ''' if dnd_has_image(md): for x in md.formats(): x = unicode(x) if x.startswith('image/'): cdata = bytes(md.data(x)) pmap = QPixmap() pmap.loadFromData(cdata) if not pmap.isNull(): return pmap, None break # No image, look for a URL pointing to an image if md.hasUrls(): urls = [unicode(u.toString(QUrl.None)) for u in md.urls()]
def update_result(self, plugin_name, width, height, data): if plugin_name.endswith("}"): # multi cover plugin plugin_name = plugin_name.partition("{")[0] plugin = [plugin for plugin in self.plugin_map if plugin.name == plugin_name] if not plugin: return plugin = plugin[0] last_row = max(self.plugin_map[plugin]) pmap = QPixmap() pmap.loadFromData(data) if pmap.isNull(): return self.beginInsertRows(QModelIndex(), last_row, last_row) for rows in self.plugin_map.itervalues(): for i in xrange(len(rows)): if rows[i] >= last_row: rows[i] += 1 self.plugin_map[plugin].insert(-1, last_row) self.covers.insert(last_row, self.get_item(plugin_name, pmap, waiting=False)) self.endInsertRows() else: # single cover plugin idx = None for plugin, rows in self.plugin_map.iteritems(): if plugin.name == plugin_name: idx = rows[0] break if idx is None: return pmap = QPixmap() pmap.loadFromData(data) if pmap.isNull(): return self.covers[idx] = self.get_item(plugin_name, pmap, waiting=False) self.dataChanged.emit(self.index(idx), self.index(idx))
def dump(self, items, out_stream, pdf_metadata): opts = self.opts page_size = get_page_size(self.opts) ml, mr = opts.margin_left, opts.margin_right self.doc = PdfDevice(out_stream, page_size=page_size, left_margin=ml, top_margin=opts.margin_top, right_margin=mr, bottom_margin=opts.margin_bottom, errors=self.log.error, debug=self.log.debug, compress=not opts.uncompressed_pdf, opts=opts, mark_links=opts.pdf_mark_links) self.painter = QPainter(self.doc) self.doc.set_metadata(title=pdf_metadata.title, author=pdf_metadata.author, tags=pdf_metadata.tags, mi=pdf_metadata.mi) self.doc_title = pdf_metadata.title self.doc_author = pdf_metadata.author page_rect = QRect(*self.doc.full_page_rect) for imgpath in items: self.log.debug('Processing %s...' % imgpath) self.doc.init_page() p = QPixmap() with lopen(imgpath, 'rb') as f: if not p.loadFromData(f.read()): raise ValueError( 'Could not read image from: {}'.format(imgpath)) draw_image_page(page_rect, self.painter, p, preserve_aspect_ratio=True) self.doc.end_page() 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 dnd_get_local_image_and_pixmap(md, image_exts=None): if md.hasImage(): for x in md.formats(): x = unicode_type(x) if x.startswith('image/'): cdata = bytes(md.data(x)) pmap = QPixmap() pmap.loadFromData(cdata) if not pmap.isNull(): return pmap, cdata if md.hasFormat('application/octet-stream'): cdata = bytes(md.data('application/octet-stream')) pmap = QPixmap() pmap.loadFromData(cdata) if not pmap.isNull(): return pmap, cdata if image_exts is None: image_exts = image_extensions() # No image, look for an URL pointing to an image urls = urls_from_md(md) paths = [path_from_qurl(u) for u in urls] # Look for a local file images = [ xi for xi in paths if posixpath.splitext(unquote(xi))[1][1:].lower() in image_exts ] images = [xi for xi in images if os.path.exists(xi)] for path in images: try: with open(path, 'rb') as f: cdata = f.read() except Exception: continue p = QPixmap() p.loadFromData(cdata) if not p.isNull(): return p, cdata return None, None
def set_obj_picture(self): pic = get_map(self.city_obj[self.city_obj_now]) qpix = QPixmap() qpix.loadFromData(pic) qpix = qpix.scaled(*IMAGE_SIZE) self.city_obj_pic.setPixmap(qpix)
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() def margin(which): val = getattr(opts, 'pdf_page_margin_' + which) if val == 0.0: val = getattr(opts, 'margin_' + which) return val ml, mr, mt, mb = map(margin, 'left right top bottom'.split()) # 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) 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, opts=opts, mark_links=opts.pdf_mark_links, page_margins=(ml, mr, mt, mb)) 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 = 1.5 * opts._final_base_font_size if self.footer and mb < min_margin: self.log.warn( 'Bottom margin is too small for footer, increasing it to %.1fpts' % min_margin) mb = min_margin if self.header and mt < min_margin: self.log.warn( 'Top margin is too small for header, increasing it to %.1fpts' % min_margin) mt = 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, (mt, mb)) self.margin_top, self.margin_bottom = map(lambda x: int(floor(x)), (mt, mb)) self.painter = QPainter(self.doc) try: self.book_language = pdf_metadata.mi.languages[0] except Exception: self.book_language = 'eng' self.doc.set_metadata(title=pdf_metadata.title, author=pdf_metadata.author, tags=pdf_metadata.tags, mi=pdf_metadata.mi) self.doc_title = pdf_metadata.title self.doc_author = pdf_metadata.author self.painter.save() try: if self.cover_data is not None: p = QPixmap() try: p.loadFromData(self.cover_data) except TypeError: self.log.warn( 'This ebook does not have a raster cover, cannot generate cover for PDF' '. Cover type: %s' % type(self.cover_data)) if not p.isNull(): self.doc.init_page() draw_image_page(QRect(*self.doc.full_page_rect), self.painter, p, preserve_aspect_ratio=self.opts. preserve_cover_aspect_ratio) self.doc.end_page() finally: self.painter.restore() QTimer.singleShot(0, self.render_book) if self.loop.exec_() == 1: raise Exception('PDF Output failed, see log for details') if self.toc is not None and len(self.toc) > 0: self.doc.add_outline(self.toc) self.painter.end() if self.doc.errors_occurred: raise Exception('PDF Output failed, see log for details')
# No image, look for a URL pointing to an image if md.hasUrls(): urls = [unicode(u.toString(QUrl.None)) for u in md.urls()] purls = [urlparse(u) for u in urls] # First look for a local file images = [u2p(xu) for xu in purls if xu.scheme in ('', 'file')] images = [xi for xi in images if posixpath.splitext(urllib.unquote(xi))[1][1:].lower() in image_exts] images = [xi for xi in images if os.path.exists(xi)] p = QPixmap() for path in images: try: with open(path, 'rb') as f: p.loadFromData(f.read()) except: continue if not p.isNull(): return p, None # No local images, look for remote ones # First, see if this is from Firefox rurl, fname = get_firefox_rurl(md, image_exts) if rurl and fname: return rurl, fname # Look through all remaining URLs remote_urls = [xu for xu in purls if xu.scheme in ('http', 'https', 'ftp') and posixpath.splitext(xu.path)[1][1:].lower() in image_exts]
def load_pixmap(self, data): pmap = QPixmap() pmap.loadFromData(data) pmap.setDevicePixelRatio(QApplication.instance().devicePixelRatio()) return pmap
def load_pixmap(self, data): pmap = QPixmap() pmap.loadFromData(data) pmap.setDevicePixelRatio(QApplication.instance().devicePixelRatio()) return pmap
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, opts=opts, 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 = 1.5 * opts._final_base_font_size if self.footer and opts.margin_bottom < min_margin: self.log.warn('Bottom margin is too small for footer, increasing it to %.1fpts' % min_margin) 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 to %.1fpts' % min_margin) opts.margin_top = min_margin self.page.setViewportSize(QSize(self.doc.width(), self.doc.height())) self.render_queue = items self.total_items = len(items) mt, mb = map(self.doc.to_px, (opts.margin_top, opts.margin_bottom)) self.margin_top, self.margin_bottom = map(lambda x:int(floor(x)), (mt, mb)) self.painter = QPainter(self.doc) self.doc.set_metadata(title=pdf_metadata.title, author=pdf_metadata.author, tags=pdf_metadata.tags, mi=pdf_metadata.mi) self.doc_title = pdf_metadata.title self.doc_author = pdf_metadata.author self.painter.save() try: if self.cover_data is not None: p = QPixmap() try: p.loadFromData(self.cover_data) except TypeError: self.log.warn('This ebook does not have a raster cover, cannot generate cover for PDF' '. Cover type: %s' % type(self.cover_data)) if not p.isNull(): self.doc.init_page() draw_image_page(QRect(*self.doc.full_page_rect), self.painter, p, preserve_aspect_ratio=self.opts.preserve_cover_aspect_ratio) self.doc.end_page() finally: self.painter.restore() QTimer.singleShot(0, self.render_book) if self.loop.exec_() == 1: raise Exception('PDF Output failed, see log for details') if self.toc is not None and len(self.toc) > 0: self.doc.add_outline(self.toc) self.painter.end() if self.doc.errors_occurred: raise Exception('PDF Output failed, see log for details')
def load(data): p = QPixmap() p.loadFromData(bytes(data)) if data and p.isNull(): p = self.failed_img return p
def data(self, index, role): row, col = index.row(), index.column() if row >= len(self.matches): return None result = self.matches[row] if role == Qt.DisplayRole: if col == 1: t = result.title if result.title else _('Unknown') a = result.author if result.author else '' return ('<b>%s</b><br><i>%s</i>' % (t, a)) elif col == 2: return (result.price) elif col == 4: return ('%s<br>%s' % (result.store_name, result.formats)) return None elif role == Qt.DecorationRole: if col == 0 and result.cover_data: p = QPixmap() p.loadFromData(result.cover_data) return (p) if col == 3: if result.drm == SearchResult.DRM_LOCKED: return (self.DRM_LOCKED_ICON) elif result.drm == SearchResult.DRM_UNLOCKED: return (self.DRM_UNLOCKED_ICON) elif result.drm == SearchResult.DRM_UNKNOWN: return (self.DRM_UNKNOWN_ICON) if col == 5: if result.downloads: return (self.DOWNLOAD_ICON) if col == 6: if result.affiliate: return (self.DONATE_ICON) elif role == Qt.ToolTipRole: if col == 1: return ('<p>%s</p>' % result.title) elif col == 2: return ('<p>' + _( 'Detected price as: %s. Check with the store before making a purchase to verify this price is correct. This price often does not include promotions the store may be running.' ) % result.price + '</p>') # noqa elif col == 3: if result.drm == SearchResult.DRM_LOCKED: return ('<p>' + _( 'This book as been detected as having DRM restrictions. This book may not work with your reader and you will have limitations placed upon you as to what you can do with this book. Check with the store before making any purchases to ensure you can actually read this book.' ) + '</p>') # noqa elif result.drm == SearchResult.DRM_UNLOCKED: return ('<p>' + _( 'This book has been detected as being DRM Free. You should be able to use this book on any device provided it is in a format calibre supports for conversion. However, before making a purchase double check the DRM status with the store. The store may not be disclosing the use of DRM.' ) + '</p>') # noqa else: return ('<p>' + _( 'The DRM status of this book could not be determined. There is a very high likelihood that this book is actually DRM restricted.' ) + '</p>') # noqa elif col == 4: return ('<p>%s</p>' % result.formats) elif col == 5: if result.downloads: return ('<p>' + _( 'The following formats can be downloaded directly: %s.' ) % ', '.join(result.downloads.keys()) + '</p>') elif col == 6: if result.affiliate: return ('<p>' + _( 'Buying from this store supports the calibre developer: %s.' ) % result.plugin_author + '</p>') elif role == Qt.SizeHintRole: return QSize(64, 64) return None
def load(data): p = QPixmap() p.loadFromData(bytes(data)) if data and p.isNull(): p = self.failed_img return p
def update_map(self): map_bytes = self.map.get_map_bytes() qpix = QPixmap() qpix.loadFromData(map_bytes) self.mapLabel.setPixmap(qpix)