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 qt.core import QIcon, QPixmap names = name_or_list_of_names ans = get_resources(zfp, names) if isinstance(names, string_or_bytes): names = [names] if ans is None: ans = {} if isinstance(ans, string_or_bytes): 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 dropEvent(self, event): event.setDropAction(Qt.DropAction.CopyAction) md = event.mimeData() pmap, data = dnd_get_local_image_and_pixmap(md) if pmap is not None: self.handle_image_drop(pmap, data) return 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() with lopen(d.fpath, 'rb') as f: data = f.read() pmap.loadFromData(data) if not pmap.isNull(): self.handle_image_drop(pmap, data=data)
def load(data): p = QPixmap() p.loadFromData(as_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 __init__(self, data, encoding, x0, y0, x1, y1, xsize, ysize): p = QPixmap() p.loadFromData(data, encoding, Qt.ImageConversionFlag.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(int(xsize), int(ysize), Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation) QGraphicsPixmapItem.__init__(self, p) self.height, self.width = ysize, xsize self.setTransformationMode(Qt.TransformationMode.SmoothTransformation) self.setShapeMode(QGraphicsPixmapItem.ShapeMode.BoundingRectShape)
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 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.AspectRatioMode.KeepAspectRatio, transformMode=Qt.TransformationMode.SmoothTransformation) return pixmaps[-1].scaled( size, size, aspectRatioMode=Qt.AspectRatioMode.KeepAspectRatio, transformMode=Qt.TransformationMode.SmoothTransformation)
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 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.new_api.all_field_names('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 select_cover(self): files = choose_images( self, 'change cover dialog', _('Choose cover for ') + unicode_type(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 cover = None try: with open(_file, "rb") as f: cover = f.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 />" + unicode_type(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 data(self, role): if role == Qt.ItemDataRole.DisplayRole: return (self.title) if role == Qt.ItemDataRole.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 Exception: pass if not p.isNull(): self.icon = (QIcon(p)) else: self.icon = self.default_icon return self.icon if role == Qt.ItemDataRole.UserRole: return self.urn
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 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 dnd_get_local_image_and_pixmap(md, image_exts=None): if md.hasImage(): for x in md.formats(): x = str(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 extension(xi) 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 load_pixmap(self, data): pmap = QPixmap() pmap.loadFromData(data) pmap.setDevicePixelRatio(QApplication.instance().devicePixelRatio()) return pmap
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.ItemDataRole.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.ItemDataRole.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.ItemDataRole.ToolTipRole: if col == 1: return ('<p>%s</p>' % result.title) elif col == 2: if result.price: 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>') return '<p>' + _( 'No price was found') 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.ItemDataRole.SizeHintRole: return QSize(64, 64) return None