def filename_button_clicked(self): try: path = choose_files(self, 'choose_category_icon', _('Select Icon'), filters=[ ('Images', ['png', 'gif', 'jpg', 'jpeg'])], all_files=False, select_only_single_file=True) if path: icon_path = path[0] icon_name = sanitize_file_name_unicode( os.path.splitext( os.path.basename(icon_path))[0]+'.png') if icon_name not in self.icon_file_names: self.icon_file_names.append(icon_name) self.update_filename_box() try: p = QIcon(icon_path).pixmap(QSize(128, 128)) d = os.path.join(config_dir, 'cc_icons') if not os.path.exists(os.path.join(d, icon_name)): if not os.path.exists(d): os.makedirs(d) with open(os.path.join(d, icon_name), 'wb') as f: f.write(pixmap_to_data(p, format='PNG')) except: traceback.print_exc() self.icon_files.setCurrentIndex(self.icon_files.findText(icon_name)) self.icon_files.adjustSize() except: traceback.print_exc() return
def get_image_data(self, quality=90): if not self.is_modified: return self.original_image_data fmt = self.original_image_format or 'JPEG' if fmt.lower() not in set(map(lambda x:bytes(x).decode('ascii'), QImageWriter.supportedImageFormats())): return qimage_to_magick(self.current_image).export(fmt) return pixmap_to_data(self.current_image, format=fmt, quality=90)
def fetch_metadata(self, *args): d = FullFetch(self.cover.pixmap(), self) ret = d.start(title=self.title.current_val, authors=self.authors.current_val, identifiers=self.identifiers.current_val) if ret == d.Accepted: self.metadata_before_fetch = {f:getattr(self, f).current_val for f in fetched_fields} from calibre.ebooks.metadata.sources.prefs import msprefs mi = d.book dummy = Metadata(_('Unknown')) for f in msprefs['ignore_fields']: if ':' not in f: setattr(mi, f, getattr(dummy, f)) if mi is not None: pd = mi.pubdate if pd is not None: # Put the downloaded published date into the local timezone # as we discard time info and the date is timezone # invariant. This prevents the as_local_timezone() call in # update_from_mi from changing the pubdate mi.pubdate = datetime(pd.year, pd.month, pd.day, tzinfo=local_tz) self.update_from_mi(mi, merge_comments=msprefs['append_comments']) if d.cover_pixmap is not None: self.metadata_before_fetch['cover'] = self.cover.current_val self.cover.current_val = pixmap_to_data(d.cover_pixmap)
def filename_button_clicked(self): try: path = choose_files(self, 'choose_category_icon', _('Select Icon'), filters=[ (_('Images'), ['png', 'gif', 'jpg', 'jpeg'])], all_files=False, select_only_single_file=True) if path: icon_path = path[0] icon_name = self.sanitize_icon_file_name(icon_path) if icon_name not in self.icon_file_names: self.icon_file_names.append(icon_name) try: p = QIcon(icon_path).pixmap(QSize(128, 128)) d = self.icon_folder if not os.path.exists(os.path.join(d, icon_name)): if not os.path.exists(d): os.makedirs(d) with open(os.path.join(d, icon_name), 'wb') as f: f.write(pixmap_to_data(p, format='PNG')) except: import traceback traceback.print_exc() self.update_filename_box() self.update_remove_button() if self.doing_multiple: if icon_name not in self.rule_icon_files: self.rule_icon_files.append(icon_name) self.update_icon_filenames_in_box() else: self.filename_box.setCurrentIndex(self.filename_box.findText(icon_name)) self.filename_box.adjustSize() except: import traceback traceback.print_exc() return
def paste_from_clipboard(self): cb = QApplication.instance().clipboard() pmap = cb.pixmap() if pmap.isNull() and cb.supportsSelection(): pmap = cb.pixmap(cb.Selection) if not pmap.isNull(): self.set_pixmap(pmap) self.cover_changed.emit(pixmap_to_data(pmap))
def paste_from_clipboard(self): cb = QApplication.instance().clipboard() pmap = cb.pixmap() if pmap.isNull() and cb.supportsSelection(): pmap = cb.pixmap(QClipboard.Mode.Selection) if not pmap.isNull(): self.set_pixmap(pmap) self.cover_changed.emit(pixmap_to_data(pmap, format='PNG'))
def download_cover(self, *args): from calibre.gui2.metadata.single_download import CoverFetch d = CoverFetch(self.cover.pixmap(), self) ret = d.start(self.title.current_val, self.authors.current_val, self.identifiers.current_val) if ret == d.Accepted: if d.cover_pixmap is not None: self.cover.current_val = pixmap_to_data(d.cover_pixmap)
def calibre_cover2(title, author_string='', series_string='', prefs=None, as_qimage=False, logo_path=None): init_environment() title, subtitle, footer = '<b>' + escape_formatting( title), '<i>' + escape_formatting( series_string), '<b>' + escape_formatting(author_string) prefs = prefs or cprefs prefs = {k: prefs.get(k) for k in cprefs.defaults} scale = 800. / prefs['cover_height'] scale_cover(prefs, scale) prefs = Prefs(**prefs) img = QImage(prefs.cover_width, prefs.cover_height, QImage.Format.Format_ARGB32) img.fill(Qt.GlobalColor.white) # colors = to_theme('ffffff ffffff 000000 000000') color_theme = theme_to_colors(fallback_colors) class CalibeLogoStyle(Style): NAME = GUI_NAME = 'calibre' def __call__(self, painter, rect, color_theme, title_block, subtitle_block, footer_block): top = title_block.position.y + 10 extra_spacing = subtitle_block.line_spacing // 2 if subtitle_block.line_spacing else title_block.line_spacing // 3 height = title_block.height + subtitle_block.height + extra_spacing + title_block.leading top += height + 25 bottom = footer_block.position.y - 50 logo = QImage(logo_path or I('library.png')) pwidth, pheight = rect.width(), bottom - top scaled, width, height = fit_image(logo.width(), logo.height(), pwidth, pheight) x, y = (pwidth - width) // 2, (pheight - height) // 2 rect = QRect(x, top + y, width, height) painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform) painter.drawImage(rect, logo) return self.ccolor1, self.ccolor1, self.ccolor1 style = CalibeLogoStyle(color_theme, prefs) title_block, subtitle_block, footer_block = layout_text( prefs, img, title, subtitle, footer, img.height() // 3, style) p = QPainter(img) rect = QRect(0, 0, img.width(), img.height()) colors = style(p, rect, color_theme, title_block, subtitle_block, footer_block) for block, color in zip((title_block, subtitle_block, footer_block), colors): p.setPen(color) block.draw(p) p.end() img.setText('Generated cover', '%s %s' % (__appname__, __version__)) if as_qimage: return img return pixmap_to_data(img)
def get_image_data(self, quality=90): if not self.is_modified: return self.original_image_data fmt = self.original_image_format or 'JPEG' if fmt.lower() not in set( map(lambda x: bytes(x).decode('ascii'), QImageWriter.supportedImageFormats())): return qimage_to_magick(self.current_image).export(fmt) return pixmap_to_data(self.current_image, format=fmt, quality=90)
def message_image(text, width=500, height=400, font_size=20): init_environment() img = QImage(width, height, QImage.Format_ARGB32) img.fill(Qt.white) p = QPainter(img) f = QFont() f.setPixelSize(font_size) p.setFont(f) r = img.rect().adjusted(10, 10, -10, -10) p.drawText(r, Qt.AlignJustify | Qt.AlignVCenter | Qt.TextWordWrap, text) p.end() return pixmap_to_data(img)
def get_image_data(self, quality=90): if not self.is_modified: return self.original_image_data fmt = self.original_image_format or 'JPEG' if fmt.lower() not in set(map(lambda x:bytes(x).decode('ascii'), QImageWriter.supportedImageFormats())): if fmt.lower() == 'gif': data = image_to_data(self.current_image, fmt='PNG', png_compression_level=0) from PIL import Image i = Image.open(BytesIO(data)) buf = BytesIO() i.save(buf, 'gif') return buf.getvalue() else: raise ValueError('Cannot save %s format images' % fmt) return pixmap_to_data(self.current_image, format=fmt, quality=90)
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 get_library_icon(self): try: paths = choose_images( self.gui, 'choose_library_icon', _('Select icon for library "%s"') % current_library_name()) if paths: path = paths[0] p = QIcon(path).pixmap(QSize(256, 256)) icp = library_icon_path() os.makedirs(os.path.dirname(icp), exist_ok=True) with open(icp, 'wb') as f: f.write(pixmap_to_data(p, format='PNG')) self.set_library_icon() except Exception: import traceback traceback.print_exc()
def paste_from_clipboard(self, pmap=None): if not isinstance(pmap, QPixmap): cb = QApplication.instance().clipboard() pmap = cb.pixmap() if pmap.isNull() and cb.supportsSelection(): pmap = cb.pixmap(cb.Selection) if not pmap.isNull(): 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_, pixmap_to_data(pmap))
def set_cover(self, book_id, path, data): path = os.path.abspath(os.path.join(self.library_path, path)) if not os.path.exists(path): os.makedirs(path) path = os.path.join(path, 'cover.jpg') if callable(getattr(data, 'save', None)): from calibre.gui2 import pixmap_to_data data = pixmap_to_data(data) else: if callable(getattr(data, 'read', None)): data = data.read() try: save_cover_data_to(data, path) except (IOError, OSError): time.sleep(0.2) save_cover_data_to(data, path)
def paste_from_clipboard(self, pmap=None): if not isinstance(pmap, QPixmap): cb = QApplication.instance().clipboard() pmap = cb.pixmap() if pmap.isNull() and cb.supportsSelection(): pmap = cb.pixmap(cb.Selection) if not pmap.isNull(): 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_, pixmap_to_data(pmap))
def generate_masthead(title, output_path=None, width=600, height=60, as_qimage=False, font_family=None): init_environment() font_family = font_family or cprefs['title_font_family'] or 'Liberation Serif' img = QImage(width, height, QImage.Format_ARGB32) img.fill(Qt.white) p = QPainter(img) f = QFont(font_family) f.setPixelSize((height * 3) // 4), f.setBold(True) p.setFont(f) p.drawText(img.rect(), Qt.AlignLeft | Qt.AlignVCenter, sanitize(title)) p.end() if as_qimage: return img data = pixmap_to_data(img) if output_path is None: return data with open(output_path, 'wb') as f: f.write(data)
def calibre_cover2(title, author_string='', series_string='', prefs=None, as_qimage=False, logo_path=None): init_environment() title, subtitle, footer = '<b>' + escape_formatting(title), '<i>' + escape_formatting(series_string), '<b>' + escape_formatting(author_string) prefs = prefs or cprefs prefs = {k:prefs.get(k) for k in cprefs.defaults} scale = 800. / prefs['cover_height'] scale_cover(prefs, scale) prefs = Prefs(**prefs) img = QImage(prefs.cover_width, prefs.cover_height, QImage.Format_ARGB32) img.fill(Qt.white) # colors = to_theme('ffffff ffffff 000000 000000') color_theme = theme_to_colors(fallback_colors) class CalibeLogoStyle(Style): NAME = GUI_NAME = 'calibre' def __call__(self, painter, rect, color_theme, title_block, subtitle_block, footer_block): top = title_block.position.y + 10 extra_spacing = subtitle_block.line_spacing // 2 if subtitle_block.line_spacing else title_block.line_spacing // 3 height = title_block.height + subtitle_block.height + extra_spacing + title_block.leading top += height + 25 bottom = footer_block.position.y - 50 logo = QImage(logo_path or I('library.png')) pwidth, pheight = rect.width(), bottom - top scaled, width, height = fit_image(logo.width(), logo.height(), pwidth, pheight) x, y = (pwidth - width) // 2, (pheight - height) // 2 rect = QRect(x, top + y, width, height) painter.setRenderHint(QPainter.SmoothPixmapTransform) painter.drawImage(rect, logo) return self.ccolor1, self.ccolor1, self.ccolor1 style = CalibeLogoStyle(color_theme, prefs) title_block, subtitle_block, footer_block = layout_text( prefs, img, title, subtitle, footer, img.height() // 3, style) p = QPainter(img) rect = QRect(0, 0, img.width(), img.height()) colors = style(p, rect, color_theme, title_block, subtitle_block, footer_block) for block, color in zip((title_block, subtitle_block, footer_block), colors): p.setPen(color) block.draw(p) p.end() img.setText('Generated cover', '%s %s' % (__appname__, __version__)) if as_qimage: return img return pixmap_to_data(img)
def __call__(self, container): from PyQt4.Qt import QImage from calibre.gui2 import pixmap_to_data ext = container.mime_map[self.name].split('/')[-1].upper() if ext == 'JPG': ext = 'JPEG' if ext not in ('PNG', 'JPEG', 'GIF'): return False with container.open(self.name, 'r+b') as f: raw = f.read() i = QImage() i.loadFromData(raw) if i.isNull(): return False raw = pixmap_to_data(i, format=ext, quality=95) f.seek(0) f.truncate() f.write(raw) return True
def paste_image(self): c = QApplication.instance().clipboard() img = c.image() if img.isNull(): img = c.image(c.Selection) if img.isNull(): return error_dialog(self, _('No image'), _( 'There is no image on the clipboard'), show=True) d = ChooseName('image.jpg', self) if d.exec_() == d.Accepted and d.filename: fmt = d.filename.rpartition('.')[-1].lower() if fmt not in {'jpg', 'jpeg', 'png'}: return error_dialog(self, _('Invalid file extension'), _( 'The file name you choose must have a .jpg or .png extension'), show=True) t = PersistentTemporaryFile(prefix='editor-paste-image-', suffix='.' + fmt) t.write(pixmap_to_data(img, fmt)) t.close() self.chosen_image_is_external = (d.filename, t.name) self.accept()
def __call__(self, container): from qt.core import QImage from calibre.gui2 import pixmap_to_data ext = container.mime_map[self.name].split('/')[-1].upper() if ext == 'JPG': ext = 'JPEG' if ext not in ('PNG', 'JPEG', 'GIF'): return False with container.open(self.name, 'r+b') as f: raw = f.read() i = QImage() i.loadFromData(raw) if i.isNull(): return False raw = pixmap_to_data(i, format=ext, quality=95) f.seek(0) f.truncate() f.write(raw) return True
def filename_button_clicked(self): try: path = choose_files(self, 'choose_category_icon', _('Select Icon'), filters=[('Images', ['png', 'gif', 'jpg', 'jpeg'])], all_files=False, select_only_single_file=True) if path: icon_path = path[0] icon_name = lower( sanitize_file_name_unicode( os.path.splitext(os.path.basename(icon_path))[0] + '.png')) if icon_name not in self.icon_file_names: self.icon_file_names.append(icon_name) self.update_filename_box() self.update_remove_button() try: p = QIcon(icon_path).pixmap(QSize(128, 128)) d = self.icon_folder if not os.path.exists(os.path.join(d, icon_name)): if not os.path.exists(d): os.makedirs(d) with open(os.path.join(d, icon_name), 'wb') as f: f.write(pixmap_to_data(p, format='PNG')) except: import traceback traceback.print_exc() if self.doing_multiple: if icon_name not in self.rule_icon_files: self.rule_icon_files.append(icon_name) self.update_icon_filenames_in_box() else: self.filename_box.setCurrentIndex( self.filename_box.findText(icon_name)) self.filename_box.adjustSize() except: import traceback traceback.print_exc() return
def generate_masthead(title, output_path=None, width=600, height=60, as_qimage=False, font_family=None): init_environment() font_family = font_family or cprefs['title_font_family'] or 'Liberation Serif' img = QImage(width, height, QImage.Format_ARGB32) img.fill(Qt.white) p = QPainter(img) p.setRenderHints(QPainter.Antialiasing | QPainter.TextAntialiasing) f = QFont(font_family) f.setStyleStrategy(QFont.PreferAntialias) f.setPixelSize((height * 3) // 4), f.setBold(True) p.setFont(f) p.drawText(img.rect(), Qt.AlignLeft | Qt.AlignVCenter, sanitize(title)) p.end() if as_qimage: return img data = pixmap_to_data(img) if output_path is None: return data with open(output_path, 'wb') as f: f.write(data)
def qimage_to_magick(img): ans = Image() if isosx: # For some reson, on OSX MagickConstituteImage fails, and I can't be # bothered figuring out why. Dumping to uncompressed PNG is reasonably # fast. raw = pixmap_to_data(img, 'PNG', quality=100) ans.load(raw) return ans fmt = get_pixel_map() if not img.hasAlphaChannel(): if img.format() != img.Format_RGB32: img = QImage(img) img.setFormat(QImage.Format_RGB32) fmt = fmt.replace('A', 'P') else: if img.format() != img.Format_ARGB32: img = QImage(img) img.setFormat(img.Format_ARGB32) raw = img.constBits().ascapsule() ans.constitute(img.width(), img.height(), fmt, raw) return ans
def generate_cover(mi, prefs=None, as_qimage=False): init_environment() prefs = prefs or cprefs prefs = {k:prefs.get(k) for k in cprefs.defaults} prefs = Prefs(**prefs) color_theme = random.choice(load_color_themes(prefs)) style = random.choice(load_styles(prefs))(color_theme, prefs) title, subtitle, footer = format_text(mi, prefs) img = QImage(prefs.cover_width, prefs.cover_height, QImage.Format_ARGB32) title_block, subtitle_block, footer_block = layout_text( prefs, img, title, subtitle, footer, img.height() // 3, style) p = QPainter(img) rect = QRect(0, 0, img.width(), img.height()) colors = style(p, rect, color_theme, title_block, subtitle_block, footer_block) for block, color in zip((title_block, subtitle_block, footer_block), colors): p.setPen(color) block.draw(p) p.end() img.setText('Generated cover', '%s %s' % (__appname__, __version__)) if as_qimage: return img return pixmap_to_data(img)
def fetch_metadata(self, *args): d = FullFetch(self.cover.pixmap(), self) ret = d.start(title=self.title.current_val, authors=self.authors.current_val, identifiers=self.identifiers.current_val) if ret == d.Accepted: from calibre.ebooks.metadata.sources.base import msprefs mi = d.book dummy = Metadata(_('Unknown')) for f in msprefs['ignore_fields']: if ':' not in f: setattr(mi, f, getattr(dummy, f)) if mi is not None: pd = mi.pubdate if pd is not None: # Put the downloaded published date into the local timezone # as we discard time info and the date is timezone # invariant. This prevents the as_local_timezone() call in # update_from_mi from changing the pubdate mi.pubdate = datetime(pd.year, pd.month, pd.day, tzinfo=local_tz) self.update_from_mi(mi) if d.cover_pixmap is not None: self.cover.current_val = pixmap_to_data(d.cover_pixmap)
def get_image_data(self, quality=90): if not self.is_modified: return self.original_image_data return pixmap_to_data(self.current_image, format=self.original_image_format or 'JPEG', quality=90)
def to_mi(self, mi): mi.cover, mi.cover_data = None, (None, None) if self.pixmap is not None and not self.pixmap.isNull(): with PersistentTemporaryFile('.jpg') as pt: pt.write(pixmap_to_data(self.pixmap)) mi.cover = pt.name
def rescale(self, qt=True): from calibre.utils.magick.draw import Image is_image_collection = getattr(self.opts, 'is_image_collection', False) if is_image_collection: page_width, page_height = self.opts.dest.comic_screen_size else: page_width, page_height = self.opts.dest.width, self.opts.dest.height page_width -= (self.opts.margin_left + self.opts.margin_right) * self.opts.dest.dpi/72. page_height -= (self.opts.margin_top + self.opts.margin_bottom) * self.opts.dest.dpi/72. for item in self.oeb.manifest: if item.media_type.startswith('image'): ext = item.media_type.split('/')[-1].upper() if ext == 'JPG': ext = 'JPEG' if ext not in ('PNG', 'JPEG', 'GIF'): ext = 'JPEG' raw = item.data if hasattr(raw, 'xpath') or not raw: # Probably an svg image continue try: img = Image() img.load(raw) except: continue width, height = img.size try: if self.check_colorspaces and img.colorspace == 'CMYKColorspace': # We cannot do an imagemagick conversion of CMYK to RGB as # ImageMagick inverts colors if you just set the colorspace # to rgb. See for example: https://bugs.launchpad.net/bugs/1246710 from PyQt4.Qt import QImage from calibre.gui2 import pixmap_to_data qimg = QImage() qimg.loadFromData(raw) if not qimg.isNull(): raw = item.data = pixmap_to_data(qimg, format=ext, quality=95) img = Image() img.load(raw) self.log.warn( 'The image %s is in the CMYK colorspace, converting it ' 'to RGB as Adobe Digital Editions cannot display CMYK' % item.href) else: self.log.warn( 'The image %s is in the CMYK colorspace, you should convert' ' it to sRGB as Adobe Digital Editions cannot render CMYK' % item.href) except Exception: pass scaled, new_width, new_height = fit_image(width, height, page_width, page_height) if scaled: new_width = max(1, new_width) new_height = max(1, new_height) self.log('Rescaling image from %dx%d to %dx%d'%( width, height, new_width, new_height), item.href) try: img.size = (new_width, new_height) data = img.export(ext.lower()) except KeyboardInterrupt: raise except: self.log.exception('Failed to rescale image') else: item.data = data item.unload_data_from_memory()
def context_menu_handler(self, action=None, category=None, key=None, index=None, search_state=None): if not action: return try: if action == 'set_icon': try: path = choose_files(self, 'choose_category_icon', _('Change Icon for: %s') % key, filters=[ ('Images', ['png', 'gif', 'jpg', 'jpeg']) ], all_files=False, select_only_single_file=True) if path: path = path[0] p = QIcon(path).pixmap(QSize(128, 128)) d = os.path.join(config_dir, 'tb_icons') if not os.path.exists(d): os.makedirs(d) with open( os.path.join( d, 'icon_' + sanitize_file_name_unicode(key) + '.png'), 'wb') as f: f.write(pixmap_to_data(p, format='PNG')) path = os.path.basename(f.name) self._model.set_custom_category_icon( key, unicode(path)) self.recount() except: import traceback traceback.print_exc() return if action == 'clear_icon': self._model.set_custom_category_icon(key, None) self.recount() return if action == 'edit_item': self.edit(index) return if action == 'delete_item': self.tag_item_delete.emit(key, index.id, index.original_name) return if action == 'open_editor': self.tags_list_edit.emit(category, key) return if action == 'manage_categories': self.edit_user_category.emit(category) return if action == 'search': self._toggle(index, set_to=search_state) return if action == 'add_to_category': tag = index.tag if len(index.children) > 0: for c in index.all_children(): self.add_item_to_user_cat.emit(category, c.tag.original_name, c.tag.category) self.add_item_to_user_cat.emit(category, tag.original_name, tag.category) return if action == 'add_subcategory': self.add_subcategory.emit(key) return if action == 'search_category': self._toggle(index, set_to=search_state) return if action == 'delete_user_category': self.delete_user_category.emit(key) return if action == 'delete_search': saved_searches().delete(key) self.rebuild_saved_searches.emit() return if action == 'delete_item_from_user_category': tag = index.tag if len(index.children) > 0: for c in index.children: self.del_item_from_user_cat.emit( key, c.tag.original_name, c.tag.category) self.del_item_from_user_cat.emit(key, tag.original_name, tag.category) return if action == 'manage_searches': self.saved_search_edit.emit(category) return if action == 'edit_author_sort': self.author_sort_edit.emit(self, index, True, False) return if action == 'edit_author_link': self.author_sort_edit.emit(self, index, False, True) return reset_filter_categories = True if action == 'hide': self.hidden_categories.add(category) elif action == 'show': self.hidden_categories.discard(category) elif action == 'categorization': changed = self.collapse_model != category self._model.collapse_model = category if changed: reset_filter_categories = False gprefs['tags_browser_partition_method'] = category elif action == 'defaults': self.hidden_categories.clear() self.db.prefs.set('tag_browser_hidden_categories', list(self.hidden_categories)) if reset_filter_categories: self._model.set_categories_filter(None) self._model.rebuild_node_tree() except: return
def handle_image_drop(self, pmap, data=None): self.set_pixmap(pmap) self.cover_changed.emit(data or pixmap_to_data(pmap, format='PNG'))
def context_menu_handler(self, action=None, category=None, key=None, index=None, search_state=None, use_vl=None, is_first_letter=False): if not action: return try: if action == 'set_icon': try: path = choose_files(self, 'choose_category_icon', _('Change icon for: %s')%key, filters=[ ('Images', ['png', 'gif', 'jpg', 'jpeg'])], all_files=False, select_only_single_file=True) if path: path = path[0] p = QIcon(path).pixmap(QSize(128, 128)) d = os.path.join(config_dir, 'tb_icons') if not os.path.exists(d): os.makedirs(d) with open(os.path.join(d, 'icon_' + sanitize_file_name(key)+'.png'), 'wb') as f: f.write(pixmap_to_data(p, format='PNG')) path = os.path.basename(f.name) self._model.set_custom_category_icon(key, unicode_type(path)) self.recount() except: import traceback traceback.print_exc() return if action == 'clear_icon': self._model.set_custom_category_icon(key, None) self.recount() return def set_completion_data(category): try: completion_data = self.db.new_api.all_field_names(category) except: completion_data = None self.itemDelegate().set_completion_data(completion_data) if action == 'edit_item_no_vl': item = self.model().get_node(index) item.use_vl = False set_completion_data(category) self.edit(index) return if action == 'edit_item_in_vl': item = self.model().get_node(index) item.use_vl = True set_completion_data(category) self.edit(index) return if action == 'delete_item_in_vl': tag = index.tag children = index.child_tags() self.tag_item_delete.emit(key, tag.id, tag.original_name, self.model().get_book_ids_to_use(), children) return if action == 'delete_item_no_vl': tag = index.tag children = index.child_tags() self.tag_item_delete.emit(key, tag.id, tag.original_name, None, children) return if action == 'open_editor': self.tags_list_edit.emit(category, key, is_first_letter) return if action == 'manage_categories': self.edit_user_category.emit(category) return if action == 'search': self._toggle(index, set_to=search_state) return if action == "raw_search": from calibre.gui2.ui import get_gui get_gui().get_saved_search_text(search_name='search:' + key) return if action == 'add_to_category': tag = index.tag if len(index.children) > 0: for c in index.all_children(): self.add_item_to_user_cat.emit(category, c.tag.original_name, c.tag.category) self.add_item_to_user_cat.emit(category, tag.original_name, tag.category) return if action == 'add_subcategory': self.add_subcategory.emit(key) return if action == 'search_category': self._toggle(index, set_to=search_state) return if action == 'delete_user_category': self.delete_user_category.emit(key) return if action == 'delete_search': self.model().db.saved_search_delete(key) self.rebuild_saved_searches.emit() return if action == 'delete_item_from_user_category': tag = index.tag if len(index.children) > 0: for c in index.children: self.del_item_from_user_cat.emit(key, c.tag.original_name, c.tag.category) self.del_item_from_user_cat.emit(key, tag.original_name, tag.category) return if action == 'manage_searches': self.saved_search_edit.emit(category) return if action == 'edit_authors': self.author_sort_edit.emit(self, index, False, False, is_first_letter) return if action == 'edit_author_sort': self.author_sort_edit.emit(self, index, True, False, is_first_letter) return if action == 'edit_author_link': self.author_sort_edit.emit(self, index, False, True, False) return reset_filter_categories = True if action == 'hide': self.hidden_categories.add(category) elif action == 'show': self.hidden_categories.discard(category) elif action == 'categorization': changed = self.collapse_model != category self._model.collapse_model = category if changed: reset_filter_categories = False gprefs['tags_browser_partition_method'] = category elif action == 'defaults': self.hidden_categories.clear() elif action == 'add_tag': item = self.model().get_node(index) if item is not None: self.apply_to_selected_books(item) return elif action == 'remove_tag': item = self.model().get_node(index) if item is not None: self.apply_to_selected_books(item, True) return self.db.new_api.set_pref('tag_browser_hidden_categories', list(self.hidden_categories)) if reset_filter_categories: self._model.set_categories_filter(None) self._model.rebuild_node_tree() except Exception: import traceback traceback.print_exc() return
def context_menu_handler(self, action=None, category=None, key=None, index=None, search_state=None): if not action: return try: if action == 'set_icon': try: path = choose_files(self, 'choose_category_icon', _('Change Icon for: %s')%key, filters=[ ('Images', ['png', 'gif', 'jpg', 'jpeg'])], all_files=False, select_only_single_file=True) if path: path = path[0] p = QIcon(path).pixmap(QSize(128, 128)) d = os.path.join(config_dir, 'tb_icons') if not os.path.exists(d): os.makedirs(d) with open(os.path.join(d, 'icon_'+ sanitize_file_name_unicode(key)+'.png'), 'wb') as f: f.write(pixmap_to_data(p, format='PNG')) path = os.path.basename(f.name) self._model.set_custom_category_icon(key, unicode(path)) self.recount() except: import traceback traceback.print_exc() return if action == 'clear_icon': self._model.set_custom_category_icon(key, None) self.recount() return if action == 'edit_item': self.edit(index) return if action == 'delete_item': self.tag_item_delete.emit(key, index.id, index.original_name) return if action == 'open_editor': self.tags_list_edit.emit(category, key) return if action == 'manage_categories': self.edit_user_category.emit(category) return if action == 'search': self._toggle(index, set_to=search_state) return if action == 'add_to_category': tag = index.tag if len(index.children) > 0: for c in index.all_children(): self.add_item_to_user_cat.emit(category, c.tag.original_name, c.tag.category) self.add_item_to_user_cat.emit(category, tag.original_name, tag.category) return if action == 'add_subcategory': self.add_subcategory.emit(key) return if action == 'search_category': self._toggle(index, set_to=search_state) return if action == 'delete_user_category': self.delete_user_category.emit(key) return if action == 'delete_search': saved_searches().delete(key) self.rebuild_saved_searches.emit() return if action == 'delete_item_from_user_category': tag = index.tag if len(index.children) > 0: for c in index.children: self.del_item_from_user_cat.emit(key, c.tag.original_name, c.tag.category) self.del_item_from_user_cat.emit(key, tag.original_name, tag.category) return if action == 'manage_searches': self.saved_search_edit.emit(category) return if action == 'edit_author_sort': self.author_sort_edit.emit(self, index, True, False) return if action == 'edit_author_link': self.author_sort_edit.emit(self, index, False, True) return reset_filter_categories = True if action == 'hide': self.hidden_categories.add(category) elif action == 'show': self.hidden_categories.discard(category) elif action == 'categorization': changed = self.collapse_model != category self._model.collapse_model = category if changed: reset_filter_categories = False gprefs['tags_browser_partition_method'] = category elif action == 'defaults': self.hidden_categories.clear() self.db.prefs.set('tag_browser_hidden_categories', list(self.hidden_categories)) if reset_filter_categories: self._model.set_categories_filter(None) self._model.rebuild_node_tree() except: return
def context_menu_handler(self, action=None, category=None, key=None, index=None, search_state=None): if not action: return try: if action == "set_icon": try: path = choose_files( self, "choose_category_icon", _("Change Icon for: %s") % key, filters=[("Images", ["png", "gif", "jpg", "jpeg"])], all_files=False, select_only_single_file=True, ) if path: path = path[0] p = QIcon(path).pixmap(QSize(128, 128)) d = os.path.join(config_dir, "tb_icons") if not os.path.exists(d): os.makedirs(d) with open(os.path.join(d, "icon_" + sanitize_file_name_unicode(key) + ".png"), "wb") as f: f.write(pixmap_to_data(p, format="PNG")) path = os.path.basename(f.name) self._model.set_custom_category_icon(key, unicode(path)) self.recount() except: import traceback traceback.print_exc() return if action == "clear_icon": self._model.set_custom_category_icon(key, None) self.recount() return if action == "edit_item": self.edit(index) return if action == "delete_item": self.tag_item_delete.emit(key, index.id, index.original_name) return if action == "open_editor": self.tags_list_edit.emit(category, key) return if action == "manage_categories": self.edit_user_category.emit(category) return if action == "search": self._toggle(index, set_to=search_state) return if action == "add_to_category": tag = index.tag if len(index.children) > 0: for c in index.all_children(): self.add_item_to_user_cat.emit(category, c.tag.original_name, c.tag.category) self.add_item_to_user_cat.emit(category, tag.original_name, tag.category) return if action == "add_subcategory": self.add_subcategory.emit(key) return if action == "search_category": self._toggle(index, set_to=search_state) return if action == "delete_user_category": self.delete_user_category.emit(key) return if action == "delete_search": self.model().db.saved_search_delete(key) self.rebuild_saved_searches.emit() return if action == "delete_item_from_user_category": tag = index.tag if len(index.children) > 0: for c in index.children: self.del_item_from_user_cat.emit(key, c.tag.original_name, c.tag.category) self.del_item_from_user_cat.emit(key, tag.original_name, tag.category) return if action == "manage_searches": self.saved_search_edit.emit(category) return if action == "edit_author_sort": self.author_sort_edit.emit(self, index, True, False) return if action == "edit_author_link": self.author_sort_edit.emit(self, index, False, True) return reset_filter_categories = True if action == "hide": self.hidden_categories.add(category) elif action == "show": self.hidden_categories.discard(category) elif action == "categorization": changed = self.collapse_model != category self._model.collapse_model = category if changed: reset_filter_categories = False gprefs["tags_browser_partition_method"] = category elif action == "defaults": self.hidden_categories.clear() self.db.prefs.set("tag_browser_hidden_categories", list(self.hidden_categories)) if reset_filter_categories: self._model.set_categories_filter(None) self._model.rebuild_node_tree() except: return
def handle_image_drop(self, pmap): self.set_pixmap(pmap) self.cover_changed.emit(pixmap_to_data(pmap, quality=100))