id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
26,900
alternate_views.py
kovidgoyal_calibre/src/calibre/gui2/library/alternate_views.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' import itertools import math import operator import os import weakref from collections import namedtuple from functools import wraps from io import BytesIO from textwrap import wrap from threading import Event, Thread from qt.core import ( QAbstractItemView, QApplication, QBuffer, QByteArray, QColor, QDrag, QEasingCurve, QEvent, QFont, QHelpEvent, QIcon, QImage, QIODevice, QItemSelection, QItemSelectionModel, QListView, QMimeData, QModelIndex, QPainter, QPalette, QPixmap, QPoint, QPropertyAnimation, QRect, QSize, QStyledItemDelegate, QStyleOptionViewItem, Qt, QTableView, QTimer, QToolTip, QTreeView, QUrl, pyqtProperty, pyqtSignal, pyqtSlot, qBlue, qGreen, qRed, ) from calibre import fit_image, human_readable, prepare_string_for_xml from calibre.constants import DEBUG, config_dir, islinux from calibre.ebooks.metadata import fmt_sidx, rating_to_stars from calibre.gui2 import clip_border_radius, config, empty_index, gprefs, rating_font from calibre.gui2.dnd import path_from_qurl from calibre.gui2.gestures import GestureManager from calibre.gui2.library.caches import CoverCache, ThumbnailCache from calibre.gui2.library.models import themed_icon_name from calibre.gui2.pin_columns import PinContainer from calibre.utils import join_with_timeout from calibre.utils.config import prefs, tweaks from calibre.utils.img import convert_PIL_image_to_pixmap from polyglot.builtins import itervalues from polyglot.queue import LifoQueue CM_TO_INCH = 0.393701 CACHE_FORMAT = 'PPM' def auto_height(widget): # On some broken systems, availableGeometry() returns tiny values, we need # a value of at least 1000 for 200 DPI systems. return max(1000, widget.screen().availableSize().height()) / 5.0 class EncodeError(ValueError): pass def handle_enter_press(self, ev, special_action=None, has_edit_cell=True): if ev.key() in (Qt.Key.Key_Enter, Qt.Key.Key_Return): mods = ev.modifiers() if ( mods & Qt.KeyboardModifier.ControlModifier or mods & Qt.KeyboardModifier.AltModifier or mods & Qt.KeyboardModifier.ShiftModifier or mods & Qt.KeyboardModifier.MetaModifier ): return if self.state() != QAbstractItemView.State.EditingState and self.hasFocus() and self.currentIndex().isValid(): from calibre.gui2.ui import get_gui ev.ignore() tweak = tweaks['enter_key_behavior'] gui = get_gui() if tweak == 'edit_cell': if has_edit_cell: self.edit(self.currentIndex(), QAbstractItemView.EditTrigger.EditKeyPressed, ev) else: gui.iactions['Edit Metadata'].edit_metadata(False) elif tweak == 'edit_metadata': gui.iactions['Edit Metadata'].edit_metadata(False) elif tweak == 'do_nothing': pass elif tweak == 'show_locked_book_details': self.gui.iactions['Show Book Details'].show_book_info(locked=True) elif tweak == 'show_book_details': self.gui.iactions['Show Book Details'].show_book_info() else: if special_action is not None: special_action(self.currentIndex()) gui.iactions['View'].view_triggered(self.currentIndex()) gui.enter_key_pressed_in_book_list.emit(self) return True def image_to_data(image): # {{{ # Although this function is no longer used in this file, it is used in # other places in calibre. Don't delete it. ba = QByteArray() buf = QBuffer(ba) buf.open(QIODevice.OpenModeFlag.WriteOnly) if not image.save(buf, CACHE_FORMAT): raise EncodeError('Failed to encode thumbnail') ret = ba.data() buf.close() return ret # }}} # Drag 'n Drop {{{ def qt_item_view_base_class(self): for q in (QTableView, QListView, QTreeView): if isinstance(self, q): return q return QAbstractItemView def dragMoveEvent(self, event): event.acceptProposedAction() def event_has_mods(self, event=None): mods = event.modifiers() if event is not None else \ QApplication.keyboardModifiers() return mods & Qt.KeyboardModifier.ControlModifier or mods & Qt.KeyboardModifier.ShiftModifier def mousePressEvent(self, event): ep = event.pos() # for performance, check the selection only once we know we need it if event.button() == Qt.MouseButton.LeftButton and not self.event_has_mods() \ and self.indexAt(ep) in self.selectionModel().selectedIndexes(): self.drag_start_pos = ep if hasattr(self, 'handle_mouse_press_event'): return self.handle_mouse_press_event(event) return qt_item_view_base_class(self).mousePressEvent(self, event) def mouseReleaseEvent(self, event): if hasattr(self, 'handle_mouse_release_event'): return self.handle_mouse_release_event(event) return qt_item_view_base_class(self).mouseReleaseEvent(self, event) def drag_icon(self, cover, multiple): cover = cover.scaledToHeight(120, Qt.TransformationMode.SmoothTransformation) if multiple: base_width = cover.width() base_height = cover.height() base = QImage(base_width+21, base_height+21, QImage.Format.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(QPainter.CompositionMode.CompositionMode_SourceAtop) p.drawImage(rect.topLeft(), cover) p.restore() p.drawRect(rect) p.end() cover = base return QPixmap.fromImage(cover) def drag_data(self): m = self.model() db = m.db selected = self.get_selected_ids() ids = ' '.join(map(str, selected)) md = QMimeData() md.setData('application/calibre+from_library', ids.encode('utf-8')) fmt = prefs['output_format'] def url_for_id(i): try: ans = db.format_path(i, fmt, index_is_id=True) except: ans = None if ans is None: fmts = db.formats(i, index_is_id=True) if fmts: fmts = fmts.split(',') else: fmts = [] for f in fmts: try: ans = db.format_path(i, f, index_is_id=True) except: ans = None if ans is None: ans = db.abspath(i, index_is_id=True) return QUrl.fromLocalFile(ans) md.setUrls([url_for_id(i) for i in selected]) drag = QDrag(self) col = self.selectionModel().currentIndex().column() try: md.column_name = self.column_map[col] except AttributeError: md.column_name = 'title' drag.setMimeData(md) cover = self.drag_icon(m.cover(self.currentIndex().row()), len(selected) > 1) drag.setHotSpot(QPoint(-15, -15)) drag.setPixmap(cover) return drag def mouseMoveEvent(self, event): if self.event_has_mods(): self.drag_start_pos = None if not self.drag_allowed: if hasattr(self, 'handle_mouse_move_event'): self.handle_mouse_move_event(event) return if self.drag_start_pos is None: if hasattr(self, 'handle_mouse_move_event'): self.handle_mouse_move_event(event) else: qt_item_view_base_class(self).mouseMoveEvent(self, event) return if not (event.buttons() & Qt.MouseButton.LeftButton) or \ (event.pos() - self.drag_start_pos).manhattanLength() \ < QApplication.startDragDistance(): return index = self.indexAt(event.pos()) if not index.isValid(): return drag = self.drag_data() drag.exec(Qt.DropAction.CopyAction) self.drag_start_pos = None def dnd_merge_ok(md): return md.hasFormat('application/calibre+from_library') and gprefs['dnd_merge'] def dragEnterEvent(self, event): if not event.possibleActions() & (Qt.DropAction.CopyAction | Qt.DropAction.MoveAction): return paths = self.paths_from_event(event) md = event.mimeData() if paths or dnd_merge_ok(md): event.acceptProposedAction() def dropEvent(self, event): md = event.mimeData() if dnd_merge_ok(md): ids = set(map(int, filter(None, bytes(md.data('application/calibre+from_library')).decode('utf-8').split(' ')))) row = self.indexAt(event.position().toPoint()).row() if row > -1 and ids: book_id = self.model().id(row) if book_id and book_id not in ids: self.books_dropped.emit({book_id: ids}) event.setDropAction(Qt.DropAction.CopyAction) event.accept() return paths = self.paths_from_event(event) event.setDropAction(Qt.DropAction.CopyAction) event.accept() self.files_dropped.emit(paths) def paths_from_event(self, event): ''' Accept a drop event and return a list of paths that can be read from and represent files with extensions. ''' md = event.mimeData() if md.hasFormat('text/uri-list') and not md.hasFormat('application/calibre+from_library'): urls = map(path_from_qurl, md.urls()) return [u for u in urls if u and os.path.splitext(u)[1] and os.path.exists(u)] def setup_dnd_interface(cls_or_self): if isinstance(cls_or_self, type): cls = cls_or_self fmap = globals() for x in ( 'dragMoveEvent', 'event_has_mods', 'mousePressEvent', 'mouseMoveEvent', 'mouseReleaseEvent', 'drag_data', 'drag_icon', 'dragEnterEvent', 'dropEvent', 'paths_from_event'): func = fmap[x] setattr(cls, x, func) return cls else: self = cls_or_self self.drag_allowed = True self.drag_start_pos = None self.setDragEnabled(True) self.setDragDropOverwriteMode(False) self.setDragDropMode(QAbstractItemView.DragDropMode.DragDrop) # }}} # Manage slave views {{{ def sync(func): @wraps(func) def ans(self, *args, **kwargs): if self.break_link or self.current_view is self.main_view: return with self: return func(self, *args, **kwargs) return ans class AlternateViews: def __init__(self, main_view): self.views = {None:main_view} self.stack_positions = {None:0} self.current_view = self.main_view = main_view self.stack = None self.break_link = False self.main_connected = False self.current_book_state = None def set_stack(self, stack): self.stack = stack pin_container = PinContainer(self.main_view, stack) self.stack.addWidget(pin_container) return pin_container def add_view(self, key, view): self.views[key] = view self.stack_positions[key] = self.stack.count() self.stack.addWidget(view) self.stack.setCurrentIndex(0) view.setModel(self.main_view._model) view.selectionModel().currentChanged.connect(self.slave_current_changed) view.selectionModel().selectionChanged.connect(self.slave_selection_changed) view.files_dropped.connect(self.main_view.files_dropped) view.books_dropped.connect(self.main_view.books_dropped) def show_view(self, key=None): view = self.views[key] if view is self.current_view: return self.stack.setCurrentIndex(self.stack_positions[key]) self.current_view = view if view is not self.main_view: self.main_current_changed(self.main_view.currentIndex()) self.main_selection_changed() view.shown() if not self.main_connected: self.main_connected = True self.main_view.selectionModel().currentChanged.connect(self.main_current_changed) self.main_view.selectionModel().selectionChanged.connect(self.main_selection_changed) view.setFocus(Qt.FocusReason.OtherFocusReason) def set_database(self, db, stage=0): for view in itervalues(self.views): if view is not self.main_view: view.set_database(db, stage=stage) def __enter__(self): self.break_link = True def __exit__(self, *args): self.break_link = False @sync def slave_current_changed(self, current, *args): self.main_view.set_current_row(current.row(), for_sync=True) @sync def slave_selection_changed(self, *args): rows = {r.row() for r in self.current_view.selectionModel().selectedIndexes()} self.main_view.select_rows(rows, using_ids=False, change_current=False, scroll=False) @sync def main_current_changed(self, current, *args): self.current_view.set_current_row(current.row()) @sync def main_selection_changed(self, *args): rows = {r.row() for r in self.main_view.selectionModel().selectedIndexes()} self.current_view.select_rows(rows) def set_context_menu(self, menu): for view in itervalues(self.views): if view is not self.main_view: view.set_context_menu(menu) def save_current_book_state(self): self.current_book_state = self.current_view, self.current_view.current_book_state() def restore_current_book_state(self): if self.current_book_state is not None: if self.current_book_state[0] is self.current_view: self.current_view.restore_current_book_state(self.current_book_state[1]) self.current_book_state = None def marked_changed(self, old_marked, current_marked): if self.current_view is not self.main_view: self.current_view.marked_changed(old_marked, current_marked) # }}} # Rendering of covers {{{ class CoverDelegate(QStyledItemDelegate): MARGIN = 4 TOP, LEFT, RIGHT, BOTTOM = object(), object(), object(), object() @pyqtProperty(float) def animated_size(self): return self._animated_size @animated_size.setter def animated_size(self, val): self._animated_size = val def __init__(self, parent): super().__init__(parent) self._animated_size = 1.0 self.animation = QPropertyAnimation(self, b'animated_size', self) self.animation.setEasingCurve(QEasingCurve.Type.OutInCirc) self.animation.setDuration(500) self.set_dimensions() self.cover_cache = CoverCache() self.render_queue = LifoQueue() self.animating = None self.highlight_color = QColor(Qt.GlobalColor.white) self.rating_font = QFont(rating_font()) def set_dimensions(self): width = self.original_width = gprefs['cover_grid_width'] height = self.original_height = gprefs['cover_grid_height'] self.original_show_title = show_title = gprefs['cover_grid_show_title'] self.original_show_emblems = gprefs['show_emblems'] self.orginal_emblem_size = gprefs['emblem_size'] self.orginal_emblem_position = gprefs['emblem_position'] self.emblem_size = gprefs['emblem_size'] if self.original_show_emblems else 0 try: self.gutter_position = getattr(self, self.orginal_emblem_position.upper()) except Exception: self.gutter_position = self.TOP if height < 0.1: height = auto_height(self.parent()) else: height *= self.parent().logicalDpiY() * CM_TO_INCH if width < 0.1: width = 0.75 * height else: width *= self.parent().logicalDpiX() * CM_TO_INCH self.cover_size = QSize(int(width), int(height)) self.title_height = 0 if show_title: f = self.parent().font() sz = f.pixelSize() if sz < 5: sz = f.pointSize() * self.parent().logicalDpiY() / 72.0 self.title_height = int(max(25, sz + 10)) self.item_size = self.cover_size + QSize(2 * self.MARGIN, (2 * self.MARGIN) + self.title_height) if self.emblem_size > 0: extra = self.emblem_size + self.MARGIN self.item_size += QSize(extra, 0) if self.gutter_position in (self.LEFT, self.RIGHT) else QSize(0, extra) self.calculate_spacing() self.animation.setStartValue(1.0) self.animation.setKeyValueAt(0.5, 0.5) self.animation.setEndValue(1.0) def calculate_spacing(self): spc = self.original_spacing = gprefs['cover_grid_spacing'] if spc < 0.01: self.spacing = max(10, min(50, int(0.1 * self.original_width))) else: self.spacing = int(self.parent().logicalDpiX() * CM_TO_INCH * spc) def sizeHint(self, option, index): return self.item_size def render_field(self, db, book_id): is_stars = False try: field = db.pref('field_under_covers_in_grid', 'title') if field == 'size': ans = human_readable(db.field_for(field, book_id, default_value=0)) else: mi = db.get_proxy_metadata(book_id) display_name, ans, val, fm = mi.format_field_extended(field) if fm and fm['datatype'] == 'rating': ans = rating_to_stars(val, fm['display'].get('allow_half_stars', False)) is_stars = True return ('' if ans is None else str(ans)), is_stars except Exception: if DEBUG: import traceback traceback.print_exc() return '', is_stars def render_emblem(self, book_id, rule, rule_index, cache, mi, db, formatter, template_cache): ans = cache[book_id].get(rule, False) if ans is not False: return ans, mi ans = None if mi is None: mi = db.get_proxy_metadata(book_id) ans = formatter.safe_format(rule, mi, '', mi, column_name='cover_grid%d' % rule_index, template_cache=template_cache) or None cache[book_id][rule] = ans return ans, mi def cached_emblem(self, cache, name, raw_icon=None): ans = cache.get(name, False) if ans is not False: return ans sz = self.emblem_size ans = None if raw_icon is not None: ans = raw_icon.pixmap(sz, sz) elif name == ':ondevice': ans = QIcon.ic('ok.png').pixmap(sz, sz) elif name: pmap = None d = themed_icon_name(os.path.join(config_dir, 'cc_icons'), name) if d is not None: pmap = QIcon(d).pixmap(sz, sz) if pmap is None: pmap = QIcon(os.path.join(config_dir, 'cc_icons', name)).pixmap(sz, sz) if not pmap.isNull(): ans = pmap cache[name] = ans return ans def paint(self, painter, option, index): with clip_border_radius(painter, option.rect): QStyledItemDelegate.paint(self, painter, option, empty_index) # draw the hover and selection highlights m = index.model() db = m.db try: book_id = db.id(index.row()) except (ValueError, IndexError, KeyError): return if book_id in m.ids_to_highlight_set: painter.save() try: painter.setPen(self.highlight_color) painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) painter.drawRoundedRect(option.rect, 10, 10, Qt.SizeMode.RelativeSize) finally: painter.restore() marked = db.data.get_marked(book_id) db = db.new_api cdata = self.cover_cache[book_id] if cdata is False: # Don't render anything if we haven't cached the rendered cover. # This reduces subtle flashing as covers are repainted. Note that # cdata is None if there isn't a cover vs an unrendered cover. self.render_queue.put(book_id) return device_connected = self.parent().gui.device_connected is not None on_device = device_connected and db.field_for('ondevice', book_id) emblem_rules = db.pref('cover_grid_icon_rules', default=()) emblems = [] if self.emblem_size > 0: mi = None for i, (kind, column, rule) in enumerate(emblem_rules): icon_name, mi = self.render_emblem(book_id, rule, i, m.cover_grid_emblem_cache, mi, db, m.formatter, m.cover_grid_template_cache) if icon_name is not None: for one_icon in filter(None, (i.strip() for i in icon_name.split(':'))): pixmap = self.cached_emblem(m.cover_grid_bitmap_cache, one_icon) if pixmap is not None: emblems.append(pixmap) if marked: emblems.insert(0, self.cached_emblem(m.cover_grid_bitmap_cache, ':marked', m.marked_icon)) if on_device: emblems.insert(0, self.cached_emblem(m.cover_grid_bitmap_cache, ':ondevice')) painter.save() right_adjust = 0 try: rect = option.rect rect.adjust(self.MARGIN, self.MARGIN, -self.MARGIN, -self.MARGIN) if self.emblem_size > 0: self.paint_emblems(painter, rect, emblems) orect = QRect(rect) trect = QRect(rect) if self.title_height != 0: rect.setBottom(rect.bottom() - self.title_height) trect.setTop(trect.bottom() - self.title_height + 5) if cdata is None or cdata is False: title = db.field_for('title', book_id, default_value='') authors = ' & '.join(db.field_for('authors', book_id, default_value=())) painter.setRenderHint(QPainter.RenderHint.TextAntialiasing, True) painter.drawText(rect, Qt.AlignmentFlag.AlignCenter|Qt.TextFlag.TextWordWrap, f'{title}\n\n{authors}') if cdata is False: self.render_queue.put(book_id) # else if None: don't queue the request if self.title_height != 0: self.paint_title(painter, trect, db, book_id) else: if self.animating is not None and self.animating.row() == index.row(): cdata = cdata.scaled(cdata.size() * self._animated_size) dpr = cdata.devicePixelRatio() cw, ch = int(cdata.width() / dpr), int(cdata.height() / dpr) dx = max(0, int((rect.width() - cw)/2.0)) dy = max(0, int((rect.height() - ch)/2.0)) right_adjust = dx rect.adjust(dx, dy, -dx, -dy) self.paint_cover(painter, rect, cdata) if self.title_height != 0: self.paint_title(painter, trect, db, book_id) if self.emblem_size > 0: # We dont draw embossed emblems as the ondevice/marked emblems are drawn in the gutter return if marked: try: p = self.marked_emblem except AttributeError: p = self.marked_emblem = m.marked_icon.pixmap(48, 48) self.paint_embossed_emblem(p, painter, orect, right_adjust) if on_device: try: p = self.on_device_emblem except AttributeError: p = self.on_device_emblem = QIcon.ic('ok.png').pixmap(48, 48) self.paint_embossed_emblem(p, painter, orect, right_adjust, left=False) finally: painter.restore() def paint_cover(self, painter: QPainter, rect: QRect, pixmap: QPixmap): with clip_border_radius(painter, rect): painter.drawPixmap(rect, pixmap) def paint_title(self, painter, rect, db, book_id): painter.setRenderHint(QPainter.RenderHint.TextAntialiasing, True) title, is_stars = self.render_field(db, book_id) if is_stars: painter.setFont(self.rating_font) metrics = painter.fontMetrics() painter.setPen(self.highlight_color) painter.drawText(rect, Qt.AlignmentFlag.AlignCenter|Qt.TextFlag.TextSingleLine, metrics.elidedText(title, Qt.TextElideMode.ElideRight, rect.width())) def paint_emblems(self, painter, rect, emblems): gutter = self.emblem_size + self.MARGIN grect = QRect(rect) gpos = self.gutter_position if gpos is self.TOP: grect.setBottom(grect.top() + gutter) rect.setTop(rect.top() + gutter) elif gpos is self.BOTTOM: grect.setTop(grect.bottom() - gutter + self.MARGIN) rect.setBottom(rect.bottom() - gutter) elif gpos is self.LEFT: grect.setRight(grect.left() + gutter) rect.setLeft(rect.left() + gutter) else: grect.setLeft(grect.right() - gutter + self.MARGIN) rect.setRight(rect.right() - gutter) horizontal = gpos in (self.TOP, self.BOTTOM) painter.save() painter.setClipRect(grect) try: for i, emblem in enumerate(emblems): delta = 0 if i == 0 else self.emblem_size + self.MARGIN grect.moveLeft(grect.left() + delta) if horizontal else grect.moveTop(grect.top() + delta) rect = QRect(grect) rect.setWidth(int(emblem.width() / emblem.devicePixelRatio())), rect.setHeight(int(emblem.height() / emblem.devicePixelRatio())) painter.drawPixmap(rect, emblem) finally: painter.restore() def paint_embossed_emblem(self, pixmap, painter, orect, right_adjust, left=True): drect = QRect(orect) pw = int(pixmap.width() / pixmap.devicePixelRatio()) ph = int(pixmap.height() / pixmap.devicePixelRatio()) if left: drect.setLeft(drect.left() + right_adjust) drect.setRight(drect.left() + pw) else: drect.setRight(drect.right() - right_adjust) drect.setLeft(drect.right() - pw + 1) drect.setBottom(drect.bottom() - self.title_height) drect.setTop(drect.bottom() - ph) painter.drawPixmap(drect, pixmap) @pyqtSlot(QHelpEvent, QAbstractItemView, QStyleOptionViewItem, QModelIndex, result=bool) def helpEvent(self, event, view, option, index): if event is not None and view is not None and event.type() == QEvent.Type.ToolTip: try: db = index.model().db except AttributeError: return False try: book_id = db.id(index.row()) except (ValueError, IndexError, KeyError): return False db = db.new_api device_connected = self.parent().gui.device_connected on_device = device_connected is not None and db.field_for('ondevice', book_id) p = prepare_string_for_xml title = db.field_for('title', book_id) authors = db.field_for('authors', book_id) if title and authors: title = '<b>%s</b>' % ('<br>'.join(wrap(p(title), 120))) authors = '<br>'.join(wrap(p(' & '.join(authors)), 120)) tt = f'{title}<br><br>{authors}' series = db.field_for('series', book_id) if series: use_roman_numbers=config['use_roman_numerals_for_series_number'] val = _('Book %(sidx)s of <span class="series_name">%(series)s</span>')%dict( sidx=fmt_sidx(db.field_for('series_index', book_id), use_roman=use_roman_numbers), series=p(series)) tt += '<br><br>' + val if on_device: val = _('This book is on the device in %s') % on_device tt += '<br><br>' + val QToolTip.showText(event.globalPos(), tt, view) return True return False # }}} CoverTuple = namedtuple('CoverTuple', ['book_id', 'has_cover', 'cache_valid', 'cdata', 'timestamp']) # The View {{{ @setup_dnd_interface class GridView(QListView): update_item = pyqtSignal(object, object) files_dropped = pyqtSignal(object) books_dropped = pyqtSignal(object) def __init__(self, parent): QListView.__init__(self, parent) self.shift_click_start_data = None self.dbref = lambda: None self._ncols = None self.gesture_manager = GestureManager(self) setup_dnd_interface(self) self.setUniformItemSizes(True) self.setWrapping(True) self.setFlow(QListView.Flow.LeftToRight) # We cannot set layout mode to batched, because that breaks # restore_vpos() # self.setLayoutMode(QListView.ResizeMode.Batched) self.setResizeMode(QListView.ResizeMode.Adjust) self.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) self.setVerticalScrollMode(QAbstractItemView.ScrollMode.ScrollPerPixel) self.delegate = CoverDelegate(self) self.delegate.animation.valueChanged.connect(self.animation_value_changed) self.delegate.animation.finished.connect(self.animation_done) self.setItemDelegate(self.delegate) self.setSpacing(self.delegate.spacing) self.set_color() self.ignore_render_requests = Event() dpr = self.device_pixel_ratio # Up the version number if anything changes in how images are stored in # the cache. self.thumbnail_cache = ThumbnailCache(max_size=gprefs['cover_grid_disk_cache_size'], thumbnail_size=(int(dpr * self.delegate.cover_size.width()), int(dpr * self.delegate.cover_size.height())), version=1) self.render_thread = None self.update_item.connect(self.re_render, type=Qt.ConnectionType.QueuedConnection) self.doubleClicked.connect(self.double_clicked) self.setCursor(Qt.CursorShape.PointingHandCursor) self.gui = parent self.context_menu = None self.update_timer = QTimer(self) self.update_timer.setInterval(200) self.update_timer.timeout.connect(self.update_viewport) self.update_timer.setSingleShot(True) self.resize_timer = t = QTimer(self) t.setInterval(200), t.setSingleShot(True) t.timeout.connect(self.update_memory_cover_cache_size) def viewportEvent(self, ev): if hasattr(self, 'gesture_manager'): ret = self.gesture_manager.handle_event(ev) if ret is not None: return ret return super().viewportEvent(ev) @property def device_pixel_ratio(self): return self.devicePixelRatioF() @property def first_visible_row(self): geom = self.viewport().geometry() for y in range(geom.top(), (self.spacing()*2) + geom.top(), 5): for x in range(geom.left(), (self.spacing()*2) + geom.left(), 5): ans = self.indexAt(QPoint(x, y)).row() if ans > -1: return ans @property def last_visible_row(self): geom = self.viewport().geometry() for y in range(geom.bottom(), geom.bottom() - 2 * self.spacing(), -5): for x in range(geom.left(), (self.spacing()*2) + geom.left(), 5): ans = self.indexAt(QPoint(x, y)).row() if ans > -1: item_width = self.delegate.item_size.width() + 2*self.spacing() return ans + (geom.width() // item_width) def update_viewport(self): self.ignore_render_requests.clear() self.update_timer.stop() m = self.model() for r in range(self.first_visible_row or 0, self.last_visible_row or (m.count() - 1)): self.update(m.index(r, 0)) def start_view_animation(self, index): d = self.delegate if d.animating is None and not config['disable_animations']: d.animating = index d.animation.start() def double_clicked(self, index): self.start_view_animation(index) tval = tweaks['doubleclick_on_library_view'] if tval == 'open_viewer': self.gui.iactions['View'].view_triggered(index) elif tval in {'edit_metadata', 'edit_cell'}: self.gui.iactions['Edit Metadata'].edit_metadata(False, False) elif tval == 'show_book_details': self.gui.iactions['Show Book Details'].show_book_info() def animation_value_changed(self, value): if self.delegate.animating is not None: self.update(self.delegate.animating) def animation_done(self): if self.delegate.animating is not None: idx = self.delegate.animating self.delegate.animating = None self.update(idx) def set_color(self): r, g, b = gprefs['cover_grid_color'] tex = gprefs['cover_grid_texture'] pal = self.palette() bgcol = QColor(r, g, b) pal.setColor(QPalette.ColorRole.Base, bgcol) self.setPalette(pal) ss = f'background-color: {bgcol.name()}; border: 0px solid {bgcol.name()};' if tex: from calibre.gui2.preferences.texture_chooser import texture_path path = texture_path(tex) if path: path = os.path.abspath(path).replace(os.sep, '/') ss += f'background-image: url({path});' ss += 'background-attachment: fixed;' pm = QPixmap(path) if not pm.isNull(): val = pm.scaled(1, 1).toImage().pixel(0, 0) r, g, b = qRed(val), qGreen(val), qBlue(val) dark = max(r, g, b) < 115 col = '#eee' if dark else '#111' ss += f'color: {col};' self.delegate.highlight_color = QColor(col) self.setStyleSheet(f'QListView {{ {ss} }}') def refresh_settings(self): size_changed = ( gprefs['cover_grid_width'] != self.delegate.original_width or gprefs['cover_grid_height'] != self.delegate.original_height ) if (size_changed or gprefs[ 'cover_grid_show_title'] != self.delegate.original_show_title or gprefs[ 'show_emblems'] != self.delegate.original_show_emblems or gprefs[ 'emblem_size'] != self.delegate.orginal_emblem_size or gprefs[ 'emblem_position'] != self.delegate.orginal_emblem_position): self.delegate.set_dimensions() self.setSpacing(self.delegate.spacing) if size_changed: self.delegate.cover_cache.clear() if gprefs['cover_grid_spacing'] != self.delegate.original_spacing: self.delegate.calculate_spacing() self.setSpacing(self.delegate.spacing) self.set_color() self.set_thumbnail_cache_image_size() cs = gprefs['cover_grid_disk_cache_size'] if (cs*(1024**2)) != self.thumbnail_cache.max_size: self.thumbnail_cache.set_size(cs) self.update_memory_cover_cache_size() def set_thumbnail_cache_image_size(self): dpr = self.device_pixel_ratio self.thumbnail_cache.set_thumbnail_size( int(dpr * self.delegate.cover_size.width()), int(dpr*self.delegate.cover_size.height())) def resizeEvent(self, ev): self._ncols = None self.resize_timer.start() return QListView.resizeEvent(self, ev) def update_memory_cover_cache_size(self): try: sz = self.delegate.item_size except AttributeError: return rows, cols = self.width() // sz.width(), self.height() // sz.height() num = (rows + 1) * (cols + 1) limit = max(100, num * max(2, gprefs['cover_grid_cache_size_multiple'])) if limit != self.delegate.cover_cache.limit: self.delegate.cover_cache.set_limit(limit) def shown(self): self.update_memory_cover_cache_size() if self.render_thread is None: self.fetch_thread = Thread(target=self.fetch_covers) self.fetch_thread.daemon = True self.fetch_thread.start() def fetch_covers(self): q = self.delegate.render_queue while True: book_id = q.get() try: if book_id is None: return if self.ignore_render_requests.is_set(): continue thumb = None try: # Fetch the cover from the cache or file system cover_tuple = self.fetch_cover_from_cache(book_id) if cover_tuple is not None: # Render/resize the cover. thumb = self.make_thumbnail(cover_tuple) except Exception: import traceback traceback.print_exc() # Tell the GUI to redisplay the thumbnail with the new image self.update_item.emit(book_id, thumb) finally: q.task_done() def fetch_cover_from_cache(self, book_id): ''' This method fetches the cover from the cache if it exists, otherwise the cover.jpg stored in the library. It is called on the cover thread. It returns a CoverTuple containing the following cover and cache data: book_id: The id of the book for which a cover is wanted. has_cover: True if the book has an associated cover image file. cdata: Cover data. Can be None (no cover data), or a rendered cover image. cache_valid: True if the cache has correct data, False if a cover exists but isn't in the cache, None if the cache has data but the cover has been deleted. timestamp: the cover file modtime if the cover came from the file system, the timestamp in the cache if a valid cover is in the cache, otherwise None. ''' if self.ignore_render_requests.is_set(): return None db = self.dbref() if db is None: return None tc = self.thumbnail_cache cdata, timestamp = tc[book_id] # None, None if not cached. if timestamp is None: # Cover not in cache. Try to read the cover from the library. has_cover, cdata, timestamp = db.new_api.cover_or_cache(book_id, 0, as_what='pil_image') if has_cover: # There is a cover.jpg, already rendered as a pil_image cache_valid = False else: # No cover.jpg cache_valid = None else: # A cover is in the cache. Check whether it is up to date. # Note that if tcdata is not None then it is already a PIL image. has_cover, tcdata, timestamp = db.new_api.cover_or_cache(book_id, timestamp, as_what='pil_image') if has_cover: if tcdata is None: from PIL import Image # The cached cover is up-to-date. Convert the cached bytes # to a PIL image cache_valid = True cdata = Image.open(BytesIO(cdata)) else: # The cached cover is stale cache_valid = False cdata = tcdata else: # We found a cached cover for a book without a cover. This can # happen in older version of calibre that can reuse book_ids # between libraries and books in one library have covers where # they don't in another library. This version doesn't have the # problem because the cache UUID is set when the database # changes instead of when the cache thread is created. tc.invalidate((book_id,)) cache_valid = None cdata = None if has_cover and cdata is None: raise RuntimeError('No cover data when has_cover is True') return CoverTuple(book_id=book_id, has_cover=has_cover, cache_valid=cache_valid, cdata=cdata, timestamp=timestamp) def make_thumbnail(self, cover_tuple): # Render the cover image data to the thumbnail size and correct format. # Rendering isn't needed if the cover came from the cache and the cache # is valid. Put newly rendered images into the cache. Returns the # thumbnail as a PIL Image. This method is called on the cover thread. cdata = cover_tuple.cdata book_id = cover_tuple.book_id tc = self.thumbnail_cache thumb = None if cover_tuple.has_cover: # cdata contains either the resized thumbnail, the full cover.jpg # rendered as a PIL image, or None if cover.jpg isn't valid if not cover_tuple.cache_valid: # The cover isn't in the cache, is stale, or isn't a valid # image. We might have the image from cover.jpg, in which case # make it into a thumbnail. if cdata is not None: # We have an image from cover.jpg. Scale it by creating a thumbnail dpr = self.device_pixel_ratio page_width = int(dpr * self.delegate.cover_size.width()) page_height = int(dpr * self.delegate.cover_size.height()) scaled, nwidth, nheight = fit_image(cdata.width, cdata.height, page_width, page_height) if scaled: # The image is the wrong size. Scale it. if self.ignore_render_requests.is_set(): return None # The PIL thumbnail operation works in-place, changing # the source image. cdata.thumbnail((int(nwidth), int(nheight))) thumb = cdata # Put the new thumbnail into the cache. try: with BytesIO() as buf: cdata.save(buf, format=CACHE_FORMAT) # use getbuffer() instead of getvalue() to avoid a copy tc.insert(book_id, cover_tuple.timestamp, buf.getbuffer()) thumb = cdata except Exception: tc.invalidate((book_id,)) import traceback traceback.print_exc() else: # The cover data isn't valid. Remove it from the cache tc.invalidate((book_id,)) else: # Test to see if there is something wrong with the cover data in # the cache. If so, remove it from the cache and queue it to # render again. It isn't clear that this can ever happen. One # possibility is if different versions of calibre are used # interchangeably. def getbbox(img): try: return img.getbbox() except Exception: return None if getbbox(cdata) is None: tc.invalidate((book_id,)) self.render_queue.put(book_id) return None # The data from the cover cache is valid and is already a thumb. thumb = cdata else: # The book doesn't have a cover. if cover_tuple.cache_valid is not None: # Cover was removed, but it exists in cache. Remove it from the cache tc.invalidate((book_id,)) thumb = None # Conversion to QPixmap needs RGBA data. Do it here rather than in the # GUI thread. This check doesn't need to be wrapped in # if thumb is not None: # because None is a first-class object with no attributes. if getattr(thumb, 'mode', None) == 'RGB': thumb = thumb.convert('RGBA') # Return the thumbnail, which is either None or a PIL Image. If not None # the image will be converted to a QPixmap on the GUI thread. Putting # None into the CoverCache ensures re-rendering won't try again. return thumb def re_render(self, book_id, thumb): # This is called on the GUI thread when a cover thumbnail is not in the # CoverCache. The parameter "thumb" is either None if there is no cover # or a PIL Image of the thumbnail. self.delegate.cover_cache.clear_staging() if thumb is not None: # Convert the image to a QPixmap thumb = convert_PIL_image_to_pixmap(thumb, self.device_pixel_ratio) self.delegate.cover_cache.set(book_id, thumb) m = self.model() try: index = m.db.row(book_id) except (IndexError, ValueError, KeyError, AttributeError): return self.update(m.index(index, 0)) def shutdown(self): self.ignore_render_requests.set() self.delegate.render_queue.put(None) self.thumbnail_cache.shutdown() def set_database(self, newdb, stage=0): self.dbref = weakref.ref(newdb) if stage == 0: self.ignore_render_requests.set() try: for x in (self.delegate.cover_cache, self.thumbnail_cache): self.model().db.new_api.remove_cover_cache(x) except AttributeError: pass # db is None for x in (self.delegate.cover_cache, self.thumbnail_cache): newdb.new_api.add_cover_cache(x) # This must be done here so the UUID in the cache is changed when # libraries are switched. self.thumbnail_cache.set_database(newdb) try: # Use a timeout so that if, for some reason, the render thread # gets stuck, we dont deadlock, future covers won't get # rendered, but this is better than a deadlock join_with_timeout(self.delegate.render_queue) except RuntimeError: print('Cover rendering thread is stuck!') finally: self.ignore_render_requests.clear() else: self.delegate.cover_cache.clear() def select_rows(self, rows): sel = QItemSelection() sm = self.selectionModel() m = self.model() # Create a range based selector for each set of contiguous rows # as supplying selectors for each individual row causes very poor # performance if a large number of rows has to be selected. for k, g in itertools.groupby(enumerate(rows), lambda i_x:i_x[0]-i_x[1]): group = list(map(operator.itemgetter(1), g)) sel.merge(QItemSelection(m.index(min(group), 0), m.index(max(group), 0)), QItemSelectionModel.SelectionFlag.Select) sm.select(sel, QItemSelectionModel.SelectionFlag.ClearAndSelect) def selectAll(self): # We re-implement this to ensure that only indexes from column 0 are # selected. The base class implementation selects all columns. This # causes problems with selection syncing, see # https://bugs.launchpad.net/bugs/1236348 m = self.model() sm = self.selectionModel() sel = QItemSelection(m.index(0, 0), m.index(m.rowCount(QModelIndex())-1, 0)) sm.select(sel, QItemSelectionModel.SelectionFlag.ClearAndSelect) def set_current_row(self, row): sm = self.selectionModel() sm.setCurrentIndex(self.model().index(row, 0), QItemSelectionModel.SelectionFlag.NoUpdate) def set_context_menu(self, menu): self.context_menu = menu def contextMenuEvent(self, event): if self.context_menu is None: return from calibre.gui2.main_window import clone_menu m = clone_menu(self.context_menu) if islinux else self.context_menu m.popup(event.globalPos()) event.accept() def get_selected_ids(self): m = self.model() return [m.id(i) for i in self.selectionModel().selectedIndexes()] def restore_vpos(self, vpos): self.verticalScrollBar().setValue(vpos) def restore_hpos(self, hpos): pass def handle_mouse_move_event(self, ev): # handle shift drag to extend selections if not QApplication.keyboardModifiers() & Qt.KeyboardModifier.ShiftModifier: return super().mouseMoveEvent(ev) index = self.indexAt(ev.pos()) if not index.isValid() or not self.shift_click_start_data: return m = self.model() ci = m.index(self.shift_click_start_data[0], 0) if not ci.isValid(): return sm = self.selectionModel() sm.setCurrentIndex(index, QItemSelectionModel.SelectionFlag.NoUpdate) if not sm.hasSelection(): sm.select(index, QItemSelectionModel.SelectionFlag.ClearAndSelect) return True cr = ci.row() tgt = index.row() if cr == tgt: sm.select(index, QItemSelectionModel.SelectionFlag.Select) return if cr < tgt: # mouse is moved after the start pos top = min(self.shift_click_start_data[1], cr) bottom = tgt else: top = tgt bottom = max(self.shift_click_start_data[2], cr) sm.select(QItemSelection(m.index(top, 0), m.index(bottom, 0)), QItemSelectionModel.SelectionFlag.ClearAndSelect) def handle_mouse_press_event(self, ev): # Shift-Click in QListView is broken. It selects extra items in # various circumstances, for example, click on some item in the # middle of a row then click on an item in the next row, all items # in the first row will be selected instead of only items after the # middle item. if not QApplication.keyboardModifiers() & Qt.KeyboardModifier.ShiftModifier: return super().mousePressEvent(ev) self.shift_click_start_data = None index = self.indexAt(ev.pos()) if not index.isValid(): return sm = self.selectionModel() ci = self.currentIndex() try: if not ci.isValid(): return sm.setCurrentIndex(index, QItemSelectionModel.SelectionFlag.NoUpdate) if not sm.hasSelection(): sm.select(index, QItemSelectionModel.SelectionFlag.ClearAndSelect) return cr = ci.row() tgt = index.row() top = self.model().index(min(cr, tgt), 0) bottom = self.model().index(max(cr, tgt), 0) sm.select(QItemSelection(top, bottom), QItemSelectionModel.SelectionFlag.Select) finally: min_row = self.model().rowCount(QModelIndex()) max_row = -1 for idx in sm.selectedIndexes(): r = idx.row() if r < min_row: min_row = r elif r > max_row: max_row = r self.shift_click_start_data = index.row(), min_row, max_row def indices_for_merge(self, resolved=True): return self.selectionModel().selectedIndexes() def number_of_columns(self): # Number of columns currently visible in the grid if self._ncols is None: dpr = self.device_pixel_ratio width = int(dpr * self.delegate.cover_size.width()) height = int(dpr * self.delegate.cover_size.height()) step = max(10, self.spacing()) for y in range(step, 2 * height, step): for x in range(step, 2 * width, step): i = self.indexAt(QPoint(x, y)) if i.isValid(): for x in range(self.viewport().width() - step, self.viewport().width() - width, -step): j = self.indexAt(QPoint(x, y)) if j.isValid(): self._ncols = j.row() - i.row() + 1 return self._ncols return self._ncols def keyPressEvent(self, ev): if handle_enter_press(self, ev, self.start_view_animation, False): return k = ev.key() if ev.modifiers() & Qt.KeyboardModifier.ShiftModifier and k in (Qt.Key.Key_Left, Qt.Key.Key_Right, Qt.Key.Key_Up, Qt.Key.Key_Down): ci = self.currentIndex() if not ci.isValid(): return c = ci.row() ncols = self.number_of_columns() or 1 delta = {Qt.Key.Key_Left: -1, Qt.Key.Key_Right: 1, Qt.Key.Key_Up: -ncols, Qt.Key.Key_Down: ncols}[k] n = max(0, min(c + delta, self.model().rowCount(None) - 1)) if n == c: return sm = self.selectionModel() rows = {i.row() for i in sm.selectedIndexes()} if rows: mi, ma = min(rows), max(rows) end = mi if c == ma else ma if c == mi else c else: end = c top = self.model().index(min(n, end), 0) bottom = self.model().index(max(n, end), 0) sm.select(QItemSelection(top, bottom), QItemSelectionModel.SelectionFlag.ClearAndSelect) sm.setCurrentIndex(self.model().index(n, 0), QItemSelectionModel.SelectionFlag.NoUpdate) else: return QListView.keyPressEvent(self, ev) @property def current_book(self): ci = self.currentIndex() if ci.isValid(): try: return self.model().db.data.index_to_id(ci.row()) except (IndexError, ValueError, KeyError, TypeError, AttributeError): pass def current_book_state(self): return self.current_book def restore_current_book_state(self, state): book_id = state self.setFocus(Qt.FocusReason.OtherFocusReason) try: row = self.model().db.data.id_to_index(book_id) except (IndexError, ValueError, KeyError, TypeError, AttributeError): return self.set_current_row(row) self.select_rows((row,)) self.scrollTo(self.model().index(row, 0), QAbstractItemView.ScrollHint.PositionAtCenter) def marked_changed(self, old_marked, current_marked): changed = old_marked | current_marked m = self.model() for book_id in changed: try: self.update(m.index(m.db.data.id_to_index(book_id), 0)) except ValueError: pass def moveCursor(self, action, modifiers): action = QAbstractItemView.CursorAction(action) index = QListView.moveCursor(self, action, modifiers) if action in (QAbstractItemView.CursorAction.MoveLeft, QAbstractItemView.CursorAction.MoveRight) and index.isValid(): ci = self.currentIndex() if ci.isValid() and index.row() == ci.row(): nr = index.row() + (1 if action == QAbstractItemView.CursorAction.MoveRight else -1) if 0 <= nr < self.model().rowCount(QModelIndex()): index = self.model().index(nr, 0) return index def selectionCommand(self, index, event): if event and event.type() == QEvent.Type.KeyPress and event.key() in (Qt.Key.Key_Home, Qt.Key.Key_End ) and event.modifiers() & Qt.KeyboardModifier.ControlModifier: return QItemSelectionModel.SelectionFlag.ClearAndSelect | QItemSelectionModel.SelectionFlag.Rows return super().selectionCommand(index, event) def wheelEvent(self, ev): if ev.phase() not in (Qt.ScrollPhase.ScrollUpdate, Qt.ScrollPhase.NoScrollPhase, Qt.ScrollPhase.ScrollMomentum): return number_of_pixels = ev.pixelDelta() number_of_degrees = ev.angleDelta() / 8.0 b = self.verticalScrollBar() if number_of_pixels.isNull() or islinux: # pixelDelta() is broken on linux with wheel mice dy = number_of_degrees.y() / 15.0 # Scroll by approximately half a row dy = int(math.ceil((dy) * b.singleStep() / 2.0)) else: dy = number_of_pixels.y() if abs(dy) > 0: b.setValue(b.value() - dy) def paintEvent(self, ev): dpr = self.device_pixel_ratio page_width = int(dpr * self.delegate.cover_size.width()) page_height = int(dpr * self.delegate.cover_size.height()) size_changed = self.thumbnail_cache.set_thumbnail_size(page_width, page_height) if size_changed: self.delegate.cover_cache.clear() return super().paintEvent(ev) # }}}
58,000
Python
.py
1,268
34.547319
145
0.596508
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,901
views.py
kovidgoyal_calibre/src/calibre/gui2/library/views.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import itertools import operator from collections import OrderedDict from functools import partial from qt.core import ( QAbstractItemDelegate, QAbstractItemView, QDialog, QDialogButtonBox, QDrag, QEvent, QFont, QFontMetrics, QGridLayout, QHeaderView, QIcon, QItemSelection, QItemSelectionModel, QLabel, QMenu, QMimeData, QModelIndex, QPoint, QPushButton, QSize, QSpinBox, QStyle, QStyleOptionHeader, Qt, QTableView, QTimer, QUrl, pyqtSignal, ) from calibre import force_unicode from calibre.constants import filesystem_encoding, islinux from calibre.gui2 import BOOK_DETAILS_DISPLAY_DEBOUNCE_DELAY, FunctionDispatcher, error_dialog, gprefs, show_restart_warning from calibre.gui2.dialogs.enum_values_edit import EnumValuesEdit from calibre.gui2.gestures import GestureManager from calibre.gui2.library import DEFAULT_SORT from calibre.gui2.library.alternate_views import AlternateViews, handle_enter_press, setup_dnd_interface from calibre.gui2.library.delegates import ( CcBoolDelegate, CcCommentsDelegate, CcDateDelegate, CcEnumDelegate, CcLongTextDelegate, CcMarkdownDelegate, CcNumberDelegate, CcSeriesDelegate, CcTemplateDelegate, CcTextDelegate, CompleteDelegate, DateDelegate, LanguagesDelegate, PubDateDelegate, RatingDelegate, SeriesDelegate, TextDelegate, ) from calibre.gui2.library.models import BooksModel, DeviceBooksModel from calibre.gui2.pin_columns import PinTableView from calibre.gui2.preferences.create_custom_column import CreateNewCustomColumn from calibre.utils.config import prefs, tweaks from calibre.utils.icu import primary_sort_key from polyglot.builtins import iteritems def max_permitted_column_width(self, col): # arbitrary: scroll bar + header + some sw = self.verticalScrollBar().width() if self.verticalScrollBar().isVisible() else 0 hw = self.verticalHeader().width() if self.verticalHeader().isVisible() else 0 return max(200, self.width() - (sw + hw + 10)) def restrict_column_width(self, col, old_size, new_size): max_width = max_permitted_column_width(self, col) if new_size > max_width: self.column_header.blockSignals(True) self.setColumnWidth(col, max_width) self.column_header.blockSignals(False) class HeaderView(QHeaderView): # {{{ def __init__(self, *args, **kwargs): QHeaderView.__init__(self, *args) if self.orientation() == Qt.Orientation.Horizontal: self.setSectionsMovable(kwargs.get('allow_mouse_movement', True)) self.setSectionsClickable(True) self.setTextElideMode(Qt.TextElideMode.ElideRight) self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.hover = -1 self.current_font = QFont(self.font()) self.current_font.setBold(True) self.current_font.setItalic(True) self.fm = QFontMetrics(self.current_font) def event(self, e): if e.type() in (QEvent.Type.HoverMove, QEvent.Type.HoverEnter): self.hover = self.logicalIndexAt(e.position().toPoint()) elif e.type() in (QEvent.Type.Leave, QEvent.Type.HoverLeave): self.hover = -1 return QHeaderView.event(self, e) def sectionSizeFromContents(self, logical_index): self.ensurePolished() opt = QStyleOptionHeader() self.initStyleOption(opt) opt.section = logical_index opt.orientation = self.orientation() opt.fontMetrics = self.fm model = self.parent().model() opt.text = str(model.headerData(logical_index, opt.orientation, Qt.ItemDataRole.DisplayRole) or '') if opt.orientation == Qt.Orientation.Vertical: try: val = model.headerData(logical_index, opt.orientation, Qt.ItemDataRole.DecorationRole) if val is not None: opt.icon = val opt.iconAlignment = Qt.AlignmentFlag.AlignVCenter except (IndexError, ValueError, TypeError): pass if self.isSortIndicatorShown(): opt.sortIndicator = QStyleOptionHeader.SortIndicator.SortDown return self.style().sizeFromContents(QStyle.ContentsType.CT_HeaderSection, opt, QSize(), self) def paintSection(self, painter, rect, logical_index): opt = QStyleOptionHeader() self.initStyleOption(opt) opt.rect = rect opt.section = logical_index opt.orientation = self.orientation() opt.textAlignment = Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter opt.fontMetrics = self.fm model = self.parent().model() style = self.style() margin = 2 * style.pixelMetric(QStyle.PixelMetric.PM_HeaderMargin, None, self) if self.isSortIndicatorShown() and self.sortIndicatorSection() == logical_index: opt.sortIndicator = QStyleOptionHeader.SortIndicator.SortDown if \ self.sortIndicatorOrder() == Qt.SortOrder.AscendingOrder else QStyleOptionHeader.SortIndicator.SortUp margin += style.pixelMetric(QStyle.PixelMetric.PM_HeaderMarkSize, None, self) opt.text = str(model.headerData(logical_index, opt.orientation, Qt.ItemDataRole.DisplayRole) or '') if self.textElideMode() != Qt.TextElideMode.ElideNone: opt.text = opt.fontMetrics.elidedText(opt.text, Qt.TextElideMode.ElideRight, rect.width() - margin) if self.isEnabled(): opt.state |= QStyle.StateFlag.State_Enabled if self.window().isActiveWindow(): opt.state |= QStyle.StateFlag.State_Active if self.hover == logical_index: opt.state |= QStyle.StateFlag.State_MouseOver sm = self.selectionModel() if opt.orientation == Qt.Orientation.Vertical: try: val = model.headerData(logical_index, opt.orientation, Qt.ItemDataRole.DecorationRole) if val is not None: opt.icon = val opt.iconAlignment = Qt.AlignmentFlag.AlignVCenter except (IndexError, ValueError, TypeError): pass if sm.isRowSelected(logical_index, QModelIndex()): opt.state |= QStyle.StateFlag.State_Sunken painter.save() if ( (opt.orientation == Qt.Orientation.Horizontal and sm.currentIndex().column() == logical_index) or ( opt.orientation == Qt.Orientation.Vertical and sm.currentIndex().row() == logical_index)): painter.setFont(self.current_font) self.style().drawControl(QStyle.ControlElement.CE_Header, opt, painter, self) painter.restore() # }}} class PreserveViewState: # {{{ ''' Save the set of selected books at enter time. If at exit time there are no selected books, restore the previous selection, the previous current index and dont affect the scroll position. ''' def __init__(self, view, preserve_hpos=True, preserve_vpos=True, require_selected_ids=True): self.view = view self.require_selected_ids = require_selected_ids self.preserve_hpos = preserve_hpos self.preserve_vpos = preserve_vpos self.init_vals() def init_vals(self): self.selected_ids = set() self.current_id = None self.vscroll = self.hscroll = 0 self.original_view = None self.row = self.col = -1 def __enter__(self): self.init_vals() try: view = self.original_view = self.view.alternate_views.current_view self.selected_ids = self.view.get_selected_ids() self.current_id = self.view.current_id self.vscroll = view.verticalScrollBar().value() self.hscroll = view.horizontalScrollBar().value() ci = self.view.currentIndex() self.row, self.col = ci.row(), ci.column() except: import traceback traceback.print_exc() def __exit__(self, *args): ci = self.view.model().index(self.row, self.col) if ci.isValid(): self.view.setCurrentIndex(ci) if self.selected_ids or not self.require_selected_ids: if self.current_id is not None: self.view.current_id = self.current_id if self.selected_ids: self.view.select_rows(self.selected_ids, using_ids=True, scroll=False, change_current=self.current_id is None) view = self.original_view if self.view.alternate_views.current_view is view: if self.preserve_vpos: if hasattr(view, 'restore_vpos'): view.restore_vpos(self.vscroll) else: view.verticalScrollBar().setValue(self.vscroll) if self.preserve_hpos: if hasattr(view, 'restore_hpos'): view.restore_hpos(self.hscroll) else: view.horizontalScrollBar().setValue(self.hscroll) self.init_vals() @property def state(self): self.__enter__() return {x:getattr(self, x) for x in ('selected_ids', 'current_id', 'vscroll', 'hscroll', 'row', 'col')} @state.setter def state(self, state): for k, v in iteritems(state): setattr(self, k, v) self.__exit__() # }}} class AdjustColumnSize(QDialog): # {{{ def __init__(self, view, column, name): QDialog.__init__(self) self.setWindowTitle(_('Adjust width of {0}').format(name)) self.view = view self.column = column l = QGridLayout(self) def add_row(a, b=None): r = l.rowCount() if b is None: l.addWidget(a, r, 0, 1, 2) else: if isinstance(a, str): a = QLabel(a) l.addWidget(a, r, 0, 1, 1) l.addWidget(b, r, 1, 1, 1) if isinstance(a, QLabel): a.setBuddy(b) l.addRow = add_row original_size = self.original_size = view.horizontalHeader().sectionSize(column) label = QLabel(_('{0} pixels').format(str(original_size))) label.setToolTip('<p>' + _('The original size can be larger than the maximum if the window has been resized') + '</p>') l.addRow(_('Original size:'), label) self.minimum_size = self.view.horizontalHeader().minimumSectionSize() l.addRow(_('Minimum size:'), QLabel(_('{0} pixels').format(str(self.minimum_size)))) self.maximum_size = max_permitted_column_width(self.view, self.column) l.addRow(_('Maximum size:'), QLabel(_('{0} pixels').format(str(self.maximum_size)))) la = QLabel(_('You can also adjust column widths by dragging the divider between column headers')) la.setWordWrap(True) l.addRow(la) self.shrink_button = QPushButton(_('&Shrink 10%')) b = self.expand_button = QPushButton(_('&Expand 10%')) l.addRow(self.shrink_button, b) b = self.set_minimum_button = QPushButton(_('Set to mi&nimum')) b = self.set_maximum_button = QPushButton(_('Set to ma&ximum')) l.addRow(self.set_minimum_button, b) b = self.resize_to_fit_button = QPushButton(_('&Resize column to fit contents')) b.setToolTip('<p>' + _('The width will be set to the size of the widest entry or the maximum size, whichever is smaller') + '</p>') l.addRow(b) sb = self.spin_box = QSpinBox() sb.setMinimum(self.view.horizontalHeader().minimumSectionSize()) sb.setMaximum(self.maximum_size) sb.setValue(original_size) sb.setSuffix(' ' + _('pixels')) sb.setToolTip(_('This box shows the current width after using the above buttons')) l.addRow(_('Set width &to:'), sb) bb = self.button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) l.addRow(bb) self.shrink_button.clicked.connect(self.shrink_button_clicked) self.expand_button.clicked.connect(self.expand_button_clicked) self.spin_box.valueChanged.connect(self.spin_box_changed) self.set_minimum_button.clicked.connect(self.set_minimum_button_clicked) self.set_maximum_button.clicked.connect(self.set_maximum_button_clicked) self.resize_to_fit_button.clicked.connect(self.resize_to_fit_button_clicked) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) def reject(self): self.view.setColumnWidth(self.column, self.original_size) QDialog.reject(self) def resize_to_fit_button_clicked(self): self.view.resizeColumnToContents(self.column) w = self.view.horizontalHeader().sectionSize(self.column) w = w if w <= self.maximum_size else self.maximum_size self.spin_box.setValue(w) def set_maximum_button_clicked(self): # Do this dance in case the current width exceeds the maximum, which can # happen if the user is playing across multiple monitors self.spin_box.setValue(self.maximum_size-1) self.spin_box.setValue(self.maximum_size) def set_minimum_button_clicked(self): self.spin_box.setValue(self.minimum_size) def shrink_button_clicked(self): w = int(self.view.horizontalHeader().sectionSize(self.column) * 0.9) self.spin_box.setValue(w) def expand_button_clicked(self): w = int(self.view.horizontalHeader().sectionSize(self.column) * 1.1) self.spin_box.setValue(w) def spin_box_changed(self, val): self.view.setColumnWidth(self.column, val) # }}} @setup_dnd_interface class BooksView(QTableView): # {{{ files_dropped = pyqtSignal(object) books_dropped = pyqtSignal(object) selection_changed = pyqtSignal() add_column_signal = pyqtSignal() is_library_view = True def viewportEvent(self, event): if (event.type() == QEvent.Type.ToolTip and not gprefs['book_list_tooltips']): return False if hasattr(self, 'gesture_manager'): ret = self.gesture_manager.handle_event(event) if ret is not None: return ret return super().viewportEvent(event) def __init__(self, parent, modelcls=BooksModel, use_edit_metadata_dialog=True): QTableView.__init__(self, parent) self.pin_view = PinTableView(self, parent) self.gesture_manager = GestureManager(self) self.default_row_height = self.verticalHeader().defaultSectionSize() self.gui = parent self.setProperty('highlight_current_item', 150) self.pin_view.setProperty('highlight_current_item', 150) self.row_sizing_done = False self.alternate_views = AlternateViews(self) for wv in self, self.pin_view: if not tweaks['horizontal_scrolling_per_column']: wv.setHorizontalScrollMode(QAbstractItemView.ScrollMode.ScrollPerPixel) if not tweaks['vertical_scrolling_per_row']: wv.setVerticalScrollMode(QAbstractItemView.ScrollMode.ScrollPerPixel) wv.setEditTriggers(QAbstractItemView.EditTrigger.EditKeyPressed) tval = tweaks['doubleclick_on_library_view'] if tval == 'edit_cell': wv.setEditTriggers(QAbstractItemView.EditTrigger.DoubleClicked|wv.editTriggers()) elif tval == 'open_viewer': wv.setEditTriggers(QAbstractItemView.EditTrigger.SelectedClicked|wv.editTriggers()) wv.doubleClicked.connect(parent.iactions['View'].view_triggered) elif tval in ('show_book_details', 'show_locked_book_details'): wv.setEditTriggers(QAbstractItemView.EditTrigger.SelectedClicked|wv.editTriggers()) wv.doubleClicked.connect(partial(parent.iactions['Show Book Details'].show_book_info, locked=tval == 'show_locked_book_details')) elif tval == 'edit_metadata': # Must not enable single-click to edit, or the field will remain # open in edit mode underneath the edit metadata dialog if use_edit_metadata_dialog: wv.doubleClicked.connect( partial(parent.iactions['Edit Metadata'].edit_metadata, checked=False)) else: wv.setEditTriggers(QAbstractItemView.EditTrigger.DoubleClicked|wv.editTriggers()) setup_dnd_interface(self) for wv in self, self.pin_view: wv.setAlternatingRowColors(True) wv.setWordWrap(False) self.refresh_grid() self.rating_delegate = RatingDelegate(self) self.half_rating_delegate = RatingDelegate(self, is_half_star=True) self.timestamp_delegate = DateDelegate(self) self.pubdate_delegate = PubDateDelegate(self) self.last_modified_delegate = DateDelegate(self, tweak_name='gui_last_modified_display_format') self.languages_delegate = LanguagesDelegate(self) self.tags_delegate = CompleteDelegate(self, ',', 'all_tag_names') self.authors_delegate = CompleteDelegate(self, '&', 'all_author_names', True) self.cc_names_delegate = CompleteDelegate(self, '&', 'all_custom', True) self.series_delegate = SeriesDelegate(self) self.publisher_delegate = TextDelegate(self) self.text_delegate = TextDelegate(self) self.cc_text_delegate = CcTextDelegate(self) self.cc_series_delegate = CcSeriesDelegate(self) self.cc_longtext_delegate = CcLongTextDelegate(self) self.cc_markdown_delegate = CcMarkdownDelegate(self) self.cc_enum_delegate = CcEnumDelegate(self) self.cc_bool_delegate = CcBoolDelegate(self) self.cc_comments_delegate = CcCommentsDelegate(self) self.cc_template_delegate = CcTemplateDelegate(self) self.cc_number_delegate = CcNumberDelegate(self) self.display_parent = parent self._model = modelcls(self) self.setModel(self._model) self.pin_view.setModel(self._model) self._model.count_changed_signal.connect(self.do_row_sizing, type=Qt.ConnectionType.QueuedConnection) for wv in self, self.pin_view: wv.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows) wv.setSortingEnabled(True) self.selectionModel().currentRowChanged.connect(self._model.current_changed, type=Qt.ConnectionType.QueuedConnection) self.selectionModel().selectionChanged.connect(self.selection_changed.emit) self.preserve_state = partial(PreserveViewState, self) self.marked_changed_listener = FunctionDispatcher(self.marked_changed) # {{{ Column Header setup self.can_add_columns = True self.was_restored = False self.allow_save_state = True self.column_header = HeaderView(Qt.Orientation.Horizontal, self, allow_mouse_movement=gprefs.get('allow_column_movement_with_mouse', True)) self.pin_view.column_header = HeaderView(Qt.Orientation.Horizontal, self.pin_view, allow_mouse_movement=gprefs.get('allow_column_movement_with_mouse', True)) self.setHorizontalHeader(self.column_header) self.pin_view.setHorizontalHeader(self.pin_view.column_header) self.column_header.sectionMoved.connect(self.save_state) self.column_header.sortIndicatorChanged.disconnect() self.column_header.sortIndicatorChanged.connect(self.user_sort_requested) self.pin_view.column_header.sortIndicatorChanged.disconnect() self.pin_view.column_header.sortIndicatorChanged.connect(self.pin_view_user_sort_requested) self.column_header.customContextMenuRequested.connect(partial(self.show_column_header_context_menu, view=self)) self.column_header.sectionResized.connect(self.column_resized, Qt.ConnectionType.QueuedConnection) if self.is_library_view: self.pin_view.column_header.sectionResized.connect(self.pin_view_column_resized, Qt.ConnectionType.QueuedConnection) self.pin_view.column_header.sectionMoved.connect(self.pin_view.save_state) self.pin_view.column_header.customContextMenuRequested.connect(partial(self.show_column_header_context_menu, view=self.pin_view)) self.row_header = HeaderView(Qt.Orientation.Vertical, self) self.row_header.setSectionResizeMode(QHeaderView.ResizeMode.Fixed) self.row_header.customContextMenuRequested.connect(self.show_row_header_context_menu) self.setVerticalHeader(self.row_header) # }}} self._model.database_changed.connect(self.database_changed) hv = self.verticalHeader() hv.setSectionsClickable(True) hv.setCursor(Qt.CursorShape.PointingHandCursor) self.set_row_header_visibility() self.allow_mirroring = True if self.is_library_view: self.set_pin_view_visibility(gprefs['book_list_split']) for wv in self, self.pin_view: wv.selectionModel().currentRowChanged.connect(partial(self.mirror_selection_between_views, wv)) wv.selectionModel().selectionChanged.connect(partial(self.mirror_selection_between_views, wv)) wv.verticalScrollBar().valueChanged.connect(partial(self.mirror_vscroll, wv)) wv.verticalScrollBar().rangeChanged.connect(partial(self.mirror_vscroll, wv)) else: self.pin_view.setVisible(False) # Pin view {{{ def set_pin_view_visibility(self, visible=False): self.pin_view.setVisible(visible) self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff if visible else Qt.ScrollBarPolicy.ScrollBarAsNeeded) self.mirror_selection_between_views(self) def mirror_selection_between_views(self, src): if self.allow_mirroring: dest = self.pin_view if src is self else self if dest is self.pin_view and not dest.isVisible(): return self.allow_mirroring = False dest.selectionModel().select(src.selectionModel().selection(), QItemSelectionModel.SelectionFlag.ClearAndSelect) ci = dest.currentIndex() nci = src.selectionModel().currentIndex() # Save/restore horz scroll. ci column may be scrolled out of view. hpos = dest.horizontalScrollBar().value() if ci.isValid(): nci = dest.model().index(nci.row(), ci.column()) dest.selectionModel().setCurrentIndex(nci, QItemSelectionModel.SelectionFlag.NoUpdate) dest.horizontalScrollBar().setValue(hpos) self.allow_mirroring = True def mirror_vscroll(self, src, *a): if self.allow_mirroring: dest = self.pin_view if src is self else self if dest is self.pin_view and not dest.isVisible(): return self.allow_mirroring = False s, d = src.verticalScrollBar(), dest.verticalScrollBar() d.setRange(s.minimum(), s.maximum()), d.setValue(s.value()) self.allow_mirroring = True # }}} # Column Header Context Menu {{{ def column_header_context_handler(self, action=None, column=None, view=None): if action == 'split': self.set_pin_view_visibility(not self.pin_view.isVisible()) gprefs['book_list_split'] = self.pin_view.isVisible() self.save_state() return if not action or not column or not view: return try: idx = self.column_map.index(column) except: return h = view.column_header if action == 'lock': val = not view.column_header.sectionsMovable() self.column_header.setSectionsMovable(val) self.pin_view.column_header.setSectionsMovable(val) gprefs.set('allow_column_movement_with_mouse', val) elif action == 'hide': if h.hiddenSectionCount() >= h.count(): return error_dialog(self, _('Cannot hide all columns'), _( 'You must not hide all columns'), show=True) h.setSectionHidden(idx, True) elif action == 'show': h.setSectionHidden(idx, False) if h.sectionSize(idx) < 3: sz = h.sectionSizeHint(idx) h.resizeSection(idx, sz) elif action == 'ascending': self.sort_by_column_and_order(idx, True) elif action == 'descending': self.sort_by_column_and_order(idx, False) elif action == 'defaults': view.apply_state(view.get_default_state()) elif action == 'addcustcol': self.add_column_signal.emit() elif action == 'editcustcol': def show_restart_dialog(): from calibre.gui2.preferences.main import must_restart_message if show_restart_warning(must_restart_message): self.gui.quit(restart=True) col_manager = CreateNewCustomColumn(self.gui) if col_manager.must_restart(): show_restart_dialog() else: res = col_manager.edit_existing_column(column) if res[0] == CreateNewCustomColumn.Result.COLUMN_EDITED: show_restart_dialog() elif action.startswith('align_'): alignment = action.partition('_')[-1] self._model.change_alignment(column, alignment) elif action.startswith('font_'): self._model.change_column_font(column, action[len('font_'):]) elif action == 'quickview': from calibre.gui2.actions.show_quickview import get_quickview_action_plugin qv = get_quickview_action_plugin() if qv: rows = self.selectionModel().selectedRows() if len(rows) > 0: current_row = rows[0].row() current_col = self.column_map.index(column) index = self.model().index(current_row, current_col) qv.change_quickview_column(index) elif action == 'remember_ondevice_width': gprefs.set('ondevice_column_width', self.columnWidth(idx)) elif action == 'reset_ondevice_width': gprefs.set('ondevice_column_width', 0) self.resizeColumnToContents(idx) elif action == 'edit_enum': EnumValuesEdit(self, self._model.db, column).exec() self.save_state() def create_context_menu(self, col, name, view): ans = QMenu(view) handler = partial(self.column_header_context_handler, view=view, column=col) m = ans.addMenu(_('Sort on %s') % name) m.setIcon(QIcon.ic('sort.png')) a = m.addAction(_('Ascending'), partial(handler, action='ascending')) d = m.addAction(_('Descending'), partial(handler, action='descending')) if self._model.sorted_on[0] == col: ac = a if self._model.sorted_on[1] else d ac.setCheckable(True) ac.setChecked(True) if col not in ('ondevice', 'inlibrary') and \ (not self.model().is_custom_column(col) or (self._model.custom_columns[col]['datatype'] != 'bool' or self._model.custom_columns[col]['display'].get('bools_show_text', False))): m = ans.addMenu(_('Change text alignment for %s') % name) m.setIcon(QIcon.ic('format-justify-center.png')) al = self._model.alignment_map.get(col, 'left') for x, t in (('left', _('Left')), ('right', _('Right')), ('center', _('Center'))): a = m.addAction(QIcon.ic(f'format-justify-{x}.png'), t, partial(handler, action='align_'+x)) if al == x: a.setCheckable(True) a.setChecked(True) if not isinstance(view, DeviceBooksView): col_font = self._model.styled_columns.get(col) m = ans.addMenu(_('Change font style for %s') % name) m.setIcon(QIcon.ic('format-text-bold.png')) for x, t, f in ( ('normal', _('Normal font'), None), ('bold', _('Bold font'), self._model.bold_font), ('italic', _('Italic font'), self._model.italic_font), ('bi', _('Bold and Italic font'), self._model.bi_font), ): a = m.addAction(t, partial(handler, action='font_' + x)) if x in ('bold', 'italic'): a.setIcon(QIcon.ic(f'format-text-{x}.png')) if f is col_font: a.setCheckable(True) a.setChecked(True) ans.addAction(QIcon.ic('width.png'), _('Adjust width of column {0}').format(name), partial(self.manually_adjust_column_size, view, col, name)) if not isinstance(view, DeviceBooksView): col_manager = CreateNewCustomColumn(self.gui) if self.can_add_columns and self.model().is_custom_column(col): act = ans.addAction(QIcon.ic('edit_input.png'), _('Edit column definition for %s') % name, partial(handler, action='editcustcol')) if col_manager.must_restart(): act.setEnabled(False) if self.is_library_view: if self._model.db.field_metadata[col]['is_category']: act = ans.addAction(QIcon.ic('quickview.png'), _('Quickview column %s') % name, partial(handler, action='quickview')) rows = self.selectionModel().selectedRows() if len(rows) > 1: act.setEnabled(False) if self._model.db.field_metadata[col]['datatype'] == 'enumeration': ans.addAction(QIcon.ic('edit_input.png'), _('Edit permissible values for %s') % name, partial(handler, action='edit_enum')) hidden_cols = {self.column_map[i]: i for i in range(view.column_header.count()) if view.column_header.isSectionHidden(i) and self.column_map[i] not in ('ondevice', 'inlibrary')} ans.addSeparator() if col not in ('ondevice', 'inlibrary'): ans.addAction(QIcon.ic('minus.png'), _('Hide column %s') % name, partial(handler, action='hide')) if hidden_cols: m = ans.addMenu(_('Show column')) m.setIcon(QIcon.ic('plus.png')) hcols = [(hcol, str(self.model().headerData(hidx, Qt.Orientation.Horizontal, Qt.ItemDataRole.DisplayRole) or '')) for hcol, hidx in iteritems(hidden_cols)] hcols.sort(key=lambda x: primary_sort_key(x[1])) for hcol, hname in hcols: m.addAction(hname.replace('&', '&&'), partial(handler, action='show', column=hcol)) ans.addSeparator() if col == 'ondevice': ans.addAction(_('Remember On Device column width'), partial(handler, action='remember_ondevice_width')) ans.addAction(_('Reset On Device column width to default'), partial(handler, action='reset_ondevice_width')) ans.addAction(_('Restore default layout'), partial(handler, action='defaults')) if self.can_add_columns: act = ans.addAction(QIcon.ic('column.png'), _('Add your own columns'), partial(handler, action='addcustcol')) col_manager = CreateNewCustomColumn(self.gui) act.setEnabled(not col_manager.must_restart()) return ans def show_row_header_context_menu(self, pos): menu = QMenu(self) # Even when hidden, row numbers show if any marks show, which is why it makes # sense to offer "show row numbers" here. Saves having to go to Preferences # Look & feel, assuming you know the trick. if gprefs['row_numbers_in_book_list']: menu.addAction(_('Hide row numbers'), partial(self.hide_row_numbers, show=False)) else: menu.addAction(_('Show row numbers'), partial(self.hide_row_numbers, show=True)) db = self._model.db row = self.row_header.logicalIndexAt(pos) if row >= 0 and row < len(db.data): book_id_col = db.field_metadata['id']['rec_index'] book_id = db.data[row][book_id_col] m = menu.addAction(_('Toggle mark for book'), lambda: db.data.toggle_marked_ids({book_id,})) ic = QIcon.ic('marked.png') m.setIcon(ic) from calibre.gui2.actions.mark_books import mark_books_with_text m = menu.addAction(_('Mark book with text label'), partial(mark_books_with_text, {book_id,})) m.setIcon(ic) menu.popup(self.mapToGlobal(pos)) # Probably should change the method name, but leave it for compatibility def hide_row_numbers(self, show=False): gprefs['row_numbers_in_book_list'] = show self.set_row_header_visibility() def show_column_header_context_menu_from_action(self): if self.is_library_view: if self.hasFocus(): p = QPoint(self.column_header.sectionViewportPosition(self.currentIndex().column()), 10) self.show_column_header_context_menu(p, view=self) elif self.pin_view.hasFocus(): p = QPoint(self.pin_view.horizontalHeader().sectionViewportPosition(self.pin_view.currentIndex().column()), 10) self.show_column_header_context_menu(p, view=self.pin_view) # else some other widget has the focus, such as the tag browser or quickview def show_column_header_context_menu(self, pos, view=None): view = view or self idx = view.column_header.logicalIndexAt(pos) col = None if idx > -1 and idx < len(self.column_map): col = self.column_map[idx] name = str(self.model().headerData(idx, Qt.Orientation.Horizontal, Qt.ItemDataRole.DisplayRole) or '') view.column_header_context_menu = self.create_context_menu(col, name, view) has_context_menu = hasattr(view, 'column_header_context_menu') if self.is_library_view and has_context_menu: m = view.column_header_context_menu m.addSeparator() if not hasattr(m, 'bl_split_action'): m.bl_split_action = m.addAction(QIcon.ic('split.png'), 'xxx', partial(self.column_header_context_handler, action='split', column='title')) ac = m.bl_split_action if self.pin_view.isVisible(): ac.setText(_('Un-split the book list')) else: ac.setText(_('Split the book list')) ac = getattr(m, 'column_mouse_move_action', None) if ac is None: ac = m.column_mouse_move_action = m.addAction(_("Allow moving columns with the mouse"), partial(self.column_header_context_handler, action='lock', column=col, view=view)) ac.setCheckable(True) ac.setChecked(view.column_header.sectionsMovable()) if has_context_menu: view.column_header_context_menu.popup(view.column_header.mapToGlobal(pos)) # }}} # Sorting {{{ def set_sort_indicator(self, logical_idx, ascending): views = [self, self.pin_view] if self.is_library_view else [self] for v in views: ch = v.column_header ch.blockSignals(True) ch.setSortIndicator(logical_idx, Qt.SortOrder.AscendingOrder if ascending else Qt.SortOrder.DescendingOrder) ch.blockSignals(False) def sort_by_column_and_order(self, col, ascending): order = Qt.SortOrder.AscendingOrder if ascending else Qt.SortOrder.DescendingOrder self.column_header.blockSignals(True) self.column_header.setSortIndicator(col, order) self.column_header.blockSignals(False) with self.preserve_state(preserve_vpos=False, require_selected_ids=False): self.model().sort(col, order) if self.is_library_view: self.set_sort_indicator(col, ascending) def user_sort_requested(self, col, order=Qt.SortOrder.AscendingOrder): if 0 <= col < len(self.column_map): field = self.column_map[col] self.intelligent_sort(field, order == Qt.SortOrder.AscendingOrder) def pin_view_user_sort_requested(self, col, order=Qt.SortOrder.AscendingOrder): if col < len(self.column_map) and col >= 0: field = self.column_map[col] self.intelligent_sort(field, order == Qt.SortOrder.AscendingOrder) def intelligent_sort(self, field, ascending): if isinstance(ascending, Qt.SortOrder): ascending = ascending == Qt.SortOrder.AscendingOrder m = self.model() pname = 'previous_sort_order_' + self.__class__.__name__ previous = gprefs.get(pname, {}) if field == m.sorted_on[0] or field not in previous: self.sort_by_named_field(field, ascending) previous[field] = ascending gprefs[pname] = previous return previous[m.sorted_on[0]] = m.sorted_on[1] gprefs[pname] = previous self.sort_by_named_field(field, previous[field]) def keyboardSearch(self, search): if gprefs.get('allow_keyboard_search_in_library_views', True): super().keyboardSearch(search) def sort_by_named_field(self, field, order, reset=True): if isinstance(order, Qt.SortOrder): order = order == Qt.SortOrder.AscendingOrder if field in self.column_map: idx = self.column_map.index(field) self.sort_by_column_and_order(idx, order) else: with self.preserve_state(preserve_vpos=False, require_selected_ids=False): self._model.sort_by_named_field(field, order, reset) self.set_sort_indicator(-1, True) def multisort(self, fields, reset=True, only_if_different=False): if len(fields) == 0: return sh = self.cleanup_sort_history(self._model.sort_history, ignore_column_map=True) if only_if_different and len(sh) >= len(fields): ret=True for i,t in enumerate(fields): if t[0] != sh[i][0]: ret = False break if ret: return for n,d in reversed(fields): if n in list(self._model.db.field_metadata.keys()): sh.insert(0, (n, d)) sh = self.cleanup_sort_history(sh, ignore_column_map=True) self._model.sort_history = [tuple(x) for x in sh] with self.preserve_state(preserve_vpos=False, require_selected_ids=False): self._model.resort(reset=reset) col = fields[0][0] ascending = fields[0][1] try: idx = self.column_map.index(col) except Exception: idx = -1 self.set_sort_indicator(idx, ascending) def resort(self): with self.preserve_state(preserve_vpos=False, require_selected_ids=False): self._model.resort(reset=True) def reverse_sort(self): m = self.model() try: sort_col, order = m.sorted_on except TypeError: sort_col, order = 'date', True self.sort_by_named_field(sort_col, not order) # }}} # Ondevice column {{{ def set_ondevice_column_visibility(self): col = self._model.column_map.index('ondevice') self.column_header.setSectionHidden(col, not self._model.device_connected) w = gprefs.get('ondevice_column_width', 0) if w > 0: self.setColumnWidth(col, w) if self.is_library_view: self.pin_view.column_header.setSectionHidden(col, True) def set_device_connected(self, is_connected): self._model.set_device_connected(is_connected) self.set_ondevice_column_visibility() # }}} # Save/Restore State {{{ def get_state(self): h = self.column_header cm = self.column_map state = {} state['hidden_columns'] = [cm[i] for i in range(h.count()) if h.isSectionHidden(i) and cm[i] != 'ondevice'] for f in ('last_modified', 'languages', 'formats', 'id', 'path'): state[f+'_injected'] = True state['sort_history'] = \ self.cleanup_sort_history(self.model().sort_history, ignore_column_map=self.is_library_view) state['column_positions'] = {} state['column_sizes'] = {} state['column_alignment'] = self._model.alignment_map for i in range(h.count()): name = cm[i] state['column_positions'][name] = h.visualIndex(i) if name != 'ondevice': state['column_sizes'][name] = h.sectionSize(i) return state def write_state(self, state): db = getattr(self.model(), 'db', None) name = str(self.objectName()) if name and db is not None: db.new_api.set_pref(name + ' books view state', state) def save_state(self): # Only save if we have been initialized (set_database called) if len(self.column_map) > 0 and self.was_restored and self.allow_save_state: state = self.get_state() self.write_state(state) if self.is_library_view: self.pin_view.save_state() def cleanup_sort_history(self, sort_history, ignore_column_map=False): history = [] for col, order in sort_history: if not isinstance(order, bool): continue col = {'date':'timestamp', 'sort':'title'}.get(col, col) if ignore_column_map or col in self.column_map: if (not history or history[-1][0] != col): history.append([col, order]) return history def apply_sort_history(self, saved_history, max_sort_levels=3): if not saved_history: return if self.is_library_view: for col, order in reversed(self.cleanup_sort_history( saved_history, ignore_column_map=True)[:max_sort_levels]): try: self.sort_by_named_field(col, order) except KeyError: pass else: for col, order in reversed(self.cleanup_sort_history( saved_history)[:max_sort_levels]): self.sort_by_column_and_order(self.column_map.index(col), order) def apply_state(self, state, max_sort_levels=3, save_state=True): # set save_state=False if you will save the state yourself after calling # this method. h = self.column_header cmap = {} hidden = state.get('hidden_columns', []) for i, c in enumerate(self.column_map): cmap[c] = i if c != 'ondevice': h.setSectionHidden(i, c in hidden) positions = state.get('column_positions', {}) pmap = {} for col, pos in positions.items(): if col in cmap: pmap[pos] = col need_save_state = False # Resetting column positions triggers a save state. There can be a lot # of these. Batch them up and do it at the end. # Can't use blockSignals() because that prevents needed processing somewhere self.allow_save_state = False for pos in sorted(pmap.keys()): col = pmap[pos] idx = cmap[col] current_pos = h.visualIndex(idx) if current_pos != pos: need_save_state = True h.moveSection(current_pos, pos) self.allow_save_state = True if need_save_state and save_state: self.save_state() # Because of a bug in Qt 5 we have to ensure that the header is actually # relaid out by changing this value, without this sometimes ghost # columns remain visible when changing libraries for i in range(h.count()): val = h.isSectionHidden(i) h.setSectionHidden(i, not val) h.setSectionHidden(i, val) sizes = state.get('column_sizes', {}) for col, size in sizes.items(): if col in cmap: sz = sizes[col] if sz < 3: sz = h.sectionSizeHint(cmap[col]) h.resizeSection(cmap[col], sz) self.apply_sort_history(state.get('sort_history', None), max_sort_levels=max_sort_levels) for col, alignment in state.get('column_alignment', {}).items(): self._model.change_alignment(col, alignment) for i in range(h.count()): if not h.isSectionHidden(i) and h.sectionSize(i) < 3: sz = h.sectionSizeHint(i) h.resizeSection(i, sz) def get_default_state(self): old_state = { 'hidden_columns': ['last_modified', 'languages', 'formats', 'id', 'path'], 'sort_history':[DEFAULT_SORT], 'column_positions': {}, 'column_sizes': {}, 'column_alignment': { 'size':'center', 'timestamp':'center', 'pubdate':'center'}, } for f in ('last_modified', 'languages', 'formats', 'id', 'path'): old_state[f+'_injected'] = True h = self.column_header cm = self.column_map for i in range(h.count()): name = cm[i] old_state['column_positions'][name] = i if name != 'ondevice': old_state['column_sizes'][name] = \ min(350, max(self.sizeHintForColumn(i), h.sectionSizeHint(i))) if name in ('timestamp', 'last_modified'): old_state['column_sizes'][name] += 12 return old_state def get_old_state(self): ans = None name = str(self.objectName()) if name: name += ' books view state' db = getattr(self.model(), 'db', None) if db is not None: ans = db.new_api.pref(name) if ans is None: ans = gprefs.get(name, None) try: del gprefs[name] except: pass if ans is not None: db.new_api.set_pref(name, ans) else: injected = False for f in ('last_modified', 'languages', 'formats', 'id', 'path'): if not ans.get(f+'_injected', False): injected = True ans[f+'_injected'] = True hc = ans.get('hidden_columns', []) if f not in hc: hc.append(f) if injected: db.new_api.set_pref(name, ans) return ans def restore_state(self): old_state = self.get_old_state() if old_state is None: old_state = self.get_default_state() max_levels = 3 if tweaks['sort_columns_at_startup'] is not None: sh = [] try: for c,d in tweaks['sort_columns_at_startup']: if not isinstance(d, bool): d = True if d == 0 else False sh.append((c, d)) except: # Ignore invalid tweak values as users seem to often get them # wrong print('Ignoring invalid sort_columns_at_startup tweak, with error:') import traceback traceback.print_exc() old_state['sort_history'] = sh max_levels = max(3, len(sh)) if self.is_library_view: self.pin_view.restore_state() self.column_header.blockSignals(True) self.apply_state(old_state, max_sort_levels=max_levels) self.column_header.blockSignals(False) self.do_row_sizing() self.was_restored = True def refresh_composite_edit(self): self.cc_template_delegate.refresh() def refresh_row_sizing(self): self.row_sizing_done = False self.do_row_sizing() def refresh_grid(self): for wv in self, self.pin_view: wv.setShowGrid(bool(gprefs['booklist_grid'])) def do_row_sizing(self): # Resize all rows to have the correct height if not self.row_sizing_done and self.model().rowCount(QModelIndex()) > 0: vh = self.verticalHeader() h = max(vh.minimumSectionSize(), self.default_row_height + gprefs['book_list_extra_row_spacing']) vh.setDefaultSectionSize(h) if self.is_library_view: self.pin_view.verticalHeader().setDefaultSectionSize(h) self._model.set_row_height(self.rowHeight(0)) self.row_sizing_done = True def manually_adjust_column_size(self, view, column, name): col = self.column_map.index(column) AdjustColumnSize(view, col, name).exec_() def column_resized(self, col, old_size, new_size): restrict_column_width(self, col, old_size, new_size) def pin_view_column_resized(self, col, old_size, new_size): restrict_column_width(self.pin_view, col, old_size, new_size) # }}} # Initialization/Delegate Setup {{{ def set_database(self, db): self.alternate_views.set_database(db) self.save_state() self._model.set_database(db) self.tags_delegate.set_database(db) self.cc_names_delegate.set_database(db) self.authors_delegate.set_database(db) self.series_delegate.set_auto_complete_function(db.all_series) self.publisher_delegate.set_auto_complete_function(db.all_publishers) self.alternate_views.set_database(db, stage=1) def marked_changed(self, old_marked, current_marked): self.alternate_views.marked_changed(old_marked, current_marked) if bool(old_marked) == bool(current_marked): changed = old_marked | current_marked i = self.model().db.data.id_to_index def f(x): try: return i(x) except ValueError: pass sections = tuple(x for x in map(f, changed) if x is not None) if sections: self.row_header.headerDataChanged(Qt.Orientation.Vertical, min(sections), max(sections)) # This is needed otherwise Qt does not always update the # viewport correctly. See https://bugs.launchpad.net/bugs/1404697 self.row_header.viewport().update() # refresh the rows because there might be a composite that uses marked_books() self.model().refresh_rows(sections) else: # Marked items have either appeared or all been removed self.model().set_row_decoration(current_marked) self.row_header.headerDataChanged(Qt.Orientation.Vertical, 0, self.row_header.count()-1) self.row_header.geometriesChanged.emit() self.set_row_header_visibility() # refresh rows for the ids because there might be a composite that uses marked_books() self.model().refresh_ids(current_marked) def set_row_header_visibility(self): visible = self.model().row_decoration is not None or gprefs['row_numbers_in_book_list'] self.row_header.setVisible(visible) def database_changed(self, db): db.data.add_marked_listener(self.marked_changed_listener) for i in range(self.model().columnCount(None)): for vw in self, self.pin_view: if vw.itemDelegateForColumn(i) in ( self.rating_delegate, self.timestamp_delegate, self.pubdate_delegate, self.last_modified_delegate, self.languages_delegate, self.half_rating_delegate): vw.setItemDelegateForColumn(i, vw.itemDelegate()) cm = self.column_map def set_item_delegate(colhead, delegate): idx = cm.index(colhead) self.setItemDelegateForColumn(idx, delegate) self.pin_view.setItemDelegateForColumn(idx, delegate) for colhead in cm: if self._model.is_custom_column(colhead): cc = self._model.custom_columns[colhead] if cc['datatype'] == 'datetime': delegate = CcDateDelegate(self) delegate.set_format(cc['display'].get('date_format','')) set_item_delegate(colhead, delegate) elif cc['datatype'] == 'comments': ctype = cc['display'].get('interpret_as', 'html') if ctype == 'short-text': set_item_delegate(colhead, self.cc_text_delegate) elif ctype == 'long-text': set_item_delegate(colhead, self.cc_longtext_delegate) elif ctype == 'markdown': set_item_delegate(colhead, self.cc_markdown_delegate) else: set_item_delegate(colhead, self.cc_comments_delegate) elif cc['datatype'] == 'text': if cc['is_multiple']: if cc['display'].get('is_names', False): set_item_delegate(colhead, self.cc_names_delegate) else: set_item_delegate(colhead, self.tags_delegate) else: set_item_delegate(colhead, self.cc_text_delegate) elif cc['datatype'] == 'series': set_item_delegate(colhead, self.cc_series_delegate) elif cc['datatype'] in ('int', 'float'): set_item_delegate(colhead, self.cc_number_delegate) elif cc['datatype'] == 'bool': set_item_delegate(colhead, self.cc_bool_delegate) elif cc['datatype'] == 'rating': d = self.half_rating_delegate if cc['display'].get('allow_half_stars', False) else self.rating_delegate set_item_delegate(colhead, d) elif cc['datatype'] == 'composite': set_item_delegate(colhead, self.cc_template_delegate) elif cc['datatype'] == 'enumeration': set_item_delegate(colhead, self.cc_enum_delegate) else: dattr = colhead+'_delegate' delegate = colhead if hasattr(self, dattr) else 'text' set_item_delegate(colhead, getattr(self, delegate+'_delegate')) self.restore_state() self.set_ondevice_column_visibility() # in case there were marked books self.model().set_row_decoration(set()) self.row_header.headerDataChanged(Qt.Orientation.Vertical, 0, self.row_header.count()-1) self.row_header.geometriesChanged.emit() # }}} # Context Menu {{{ def set_context_menu(self, menu, edit_collections_action): self.setContextMenuPolicy(Qt.ContextMenuPolicy.DefaultContextMenu) self.context_menu = menu self.alternate_views.set_context_menu(menu) self.edit_collections_action = edit_collections_action def show_context_menu(self, menu, event): from calibre.gui2.main_window import clone_menu m = clone_menu(menu) if islinux else menu m.popup(event.globalPos()) event.accept() def contextMenuEvent(self, event): self.show_context_menu(self.context_menu, event) # }}} def handle_mouse_press_event(self, ev): m = ev.modifiers() b = ev.button() if ( m == Qt.KeyboardModifier.NoModifier and b == Qt.MouseButton.LeftButton and self.editTriggers() & QAbstractItemView.EditTrigger.SelectedClicked ): index = self.indexAt(ev.pos()) self.last_mouse_press_on_row = index.row() if m & Qt.KeyboardModifier.ShiftModifier: # Shift-Click in QTableView is badly behaved. index = self.indexAt(ev.pos()) if not index.isValid(): return QTableView.mousePressEvent(self, ev) ci = self.currentIndex() if not ci.isValid(): return QTableView.mousePressEvent(self, ev) clicked_row = index.row() current_row = ci.row() sm = self.selectionModel() if clicked_row == current_row: sm.setCurrentIndex(index, QItemSelectionModel.SelectionFlag.NoUpdate) return sr = sm.selectedRows() if not len(sr): sm.select( index, QItemSelectionModel.SelectionFlag.Select | QItemSelectionModel.SelectionFlag.Clear | QItemSelectionModel.SelectionFlag.Current | QItemSelectionModel.SelectionFlag.Rows) return m = self.model() def new_selection(upper, lower): top_left = m.index(upper, 0) bottom_right = m.index(lower, m.columnCount(None) - 1) return QItemSelection(top_left, bottom_right) currently_selected = tuple(x.row() for x in sr) min_row = min(currently_selected) max_row = max(currently_selected) outside_current_selection = clicked_row < min_row or clicked_row > max_row existing_selection = sm.selection() if outside_current_selection: # We simply extend the current selection if clicked_row < min_row: upper, lower = clicked_row, min_row else: upper, lower = max_row, clicked_row existing_selection.merge(new_selection(upper, lower), QItemSelectionModel.SelectionFlag.Select) else: if current_row < clicked_row: upper, lower = current_row, clicked_row else: upper, lower = clicked_row, current_row existing_selection.merge(new_selection(upper, lower), QItemSelectionModel.SelectionFlag.Toggle) sm.select(existing_selection, QItemSelectionModel.SelectionFlag.ClearAndSelect) sm.setCurrentIndex( # ensure clicked row is always selected index, QItemSelectionModel.SelectionFlag.Select | QItemSelectionModel.SelectionFlag.Rows) else: QTableView.mousePressEvent(self, ev) def handle_mouse_release_event(self, ev): if ( ev.modifiers() == Qt.KeyboardModifier.NoModifier and ev.button() == Qt.MouseButton.LeftButton and self.editTriggers() & QAbstractItemView.EditTrigger.SelectedClicked ): # As of Qt 6, Qt does not clear a multi-row selection when the # edit triggers contain SelectedClicked and the clicked row is # already selected, so do it ourselves index = self.indexAt(ev.pos()) last_press, self.last_mouse_press_on_row = getattr(self, 'last_mouse_press_on_row', -111), -112 if index.row() == last_press: sm = self.selectionModel() if index.isValid() and sm.isSelected(index): self.select_rows((index,), using_ids=False, change_current=False, scroll=False) QTableView.mouseReleaseEvent(self, ev) @property def column_map(self): return self._model.column_map @property def visible_columns(self): h = self.horizontalHeader() logical_indices = (x for x in range(h.count()) if not h.isSectionHidden(x)) rmap = {i:x for i, x in enumerate(self.column_map)} return (rmap[h.visualIndex(x)] for x in logical_indices if h.visualIndex(x) > -1) def refresh_book_details(self, force=False): idx = self.currentIndex() if not idx.isValid() and force: idx = self.model().index(0, 0) if idx.isValid(): self._model.current_changed(idx, idx) return True return False def indices_for_merge(self, resolved=False): if not resolved: return self.alternate_views.current_view.indices_for_merge(resolved=True) return self.selectionModel().selectedRows() def scrollContentsBy(self, dx, dy): # Needed as Qt bug causes headerview to not always update when scrolling QTableView.scrollContentsBy(self, dx, dy) if dy != 0: self.column_header.update() def scroll_to_row(self, row): row = min(row, self.model().rowCount(QModelIndex())-1) if row > -1: # taken from Qt implementation of scrollTo but this ensured horizontal position is not affected vh = self.verticalHeader() viewport_height = self.viewport().height() vertical_offset = vh.offset() vertical_position = vh.sectionPosition(row) cell_height = vh.sectionSize(row) pos = 'center' if vertical_position - vertical_offset < 0 or cell_height > viewport_height: pos = 'top' elif vertical_position - vertical_offset + cell_height > viewport_height: pos = 'bottom' vsb = self.verticalScrollBar() if self.verticalScrollMode() == QAbstractItemView.ScrollMode.ScrollPerPixel: if pos == 'top': vsb.setValue(vertical_position) elif pos == 'bottom': vsb.setValue(vertical_position - viewport_height + cell_height) else: vsb.setValue(vertical_position - ((viewport_height - cell_height) // 2)) else: vertical_index = vh.visualIndex(row) if pos in ('bottom', 'center'): h = (viewport_height // 2) if pos == 'center' else viewport_height y = cell_height while vertical_index > 0: y += vh.sectionSize(vh.logicalIndex(vertical_index -1)) if y > h: break vertical_index -= 1 if vh.sectionsHidden(): for s in range(vertical_index - 1, -1, -1): if vh.isSectionHidden(vh.logicalIndex(s)): vertical_index -= 1 vsb.setValue(vertical_index) @property def current_book(self): ci = self.currentIndex() if ci.isValid(): try: return self.model().db.data.index_to_id(ci.row()) except (IndexError, ValueError, KeyError, TypeError, AttributeError): pass def current_book_state(self): return self.current_book, self.horizontalScrollBar().value(), self.pin_view.horizontalScrollBar().value() def restore_current_book_state(self, state): book_id, hpos, pv_hpos = state try: row = self.model().db.data.id_to_index(book_id) except (IndexError, ValueError, KeyError, TypeError, AttributeError): return self.set_current_row(row) self.scroll_to_row(row) self.horizontalScrollBar().setValue(hpos) if self.pin_view.isVisible(): self.pin_view.horizontalScrollBar().setValue(pv_hpos) def set_current_row(self, row=0, select=True, for_sync=False, book_id=None): if book_id is not None: row = self.model().db.data.id_to_index(book_id) if row > -1 and row < self.model().rowCount(QModelIndex()): h = self.horizontalHeader() hpos = self.horizontalScrollBar().value() logical_indices = list(range(h.count())) logical_indices = [x for x in logical_indices if not h.isSectionHidden(x)] pairs = [(x, h.visualIndex(x)) for x in logical_indices if h.visualIndex(x) > -1] if not pairs: pairs = [(0, 0)] pairs.sort(key=lambda x: x[1]) i = pairs[0][0] index = self.model().index(row, i) ci = self.currentIndex() if ci.isValid(): index = self.model().index(row, ci.column()) if for_sync: sm = self.selectionModel() sm.setCurrentIndex(index, QItemSelectionModel.SelectionFlag.NoUpdate) else: self.setCurrentIndex(index) if select: sm = self.selectionModel() sm.select(index, QItemSelectionModel.SelectionFlag.ClearAndSelect|QItemSelectionModel.SelectionFlag.Rows) self.horizontalScrollBar().setValue(hpos) def select_cell(self, row_number=0, logical_column=0): if row_number > -1 and row_number < self.model().rowCount(QModelIndex()): index = self.model().index(row_number, logical_column) self.setCurrentIndex(index) sm = self.selectionModel() sm.select(index, QItemSelectionModel.SelectionFlag.ClearAndSelect|QItemSelectionModel.SelectionFlag.Rows) sm.select(index, QItemSelectionModel.SelectionFlag.Current) self.clicked.emit(index) def row_at_top(self): pos = 0 while pos < 100: ans = self.rowAt(pos) if ans > -1: return ans pos += 5 def row_at_bottom(self): pos = self.viewport().height() limit = pos - 100 while pos > limit: ans = self.rowAt(pos) if ans > -1: return ans pos -= 5 def moveCursor(self, action, modifiers): orig = self.currentIndex() action = QAbstractItemView.CursorAction(action) index = QTableView.moveCursor(self, action, modifiers) if action == QAbstractItemView.CursorAction.MovePageDown: moved = index.row() - orig.row() try: rows = self.row_at_bottom() - self.row_at_top() except TypeError: rows = moved if moved > rows: index = self.model().index(orig.row() + rows, index.column()) elif action == QAbstractItemView.CursorAction.MovePageUp: moved = orig.row() - index.row() try: rows = self.row_at_bottom() - self.row_at_top() except TypeError: rows = moved if moved > rows: index = self.model().index(orig.row() - rows, index.column()) elif action == QAbstractItemView.CursorAction.MoveHome and modifiers & Qt.KeyboardModifier.ControlModifier: return self.model().index(0, orig.column()) elif action == QAbstractItemView.CursorAction.MoveEnd and modifiers & Qt.KeyboardModifier.ControlModifier: return self.model().index(self.model().rowCount(QModelIndex()) - 1, orig.column()) return index def selectionCommand(self, index, event): if event and event.type() == QEvent.Type.KeyPress and event.key() in ( Qt.Key.Key_Home, Qt.Key.Key_End) and event.modifiers() & Qt.KeyboardModifier.ControlModifier: return QItemSelectionModel.SelectionFlag.ClearAndSelect | QItemSelectionModel.SelectionFlag.Rows return super().selectionCommand(index, event) def keyPressEvent(self, ev): if handle_enter_press(self, ev): return if ev.key() == Qt.Key.Key_F2: key = self.column_map[self.currentIndex().column()] if self._model.db.field_metadata[key]['datatype'] == 'composite': self.cc_template_delegate.allow_one_edit() return QTableView.keyPressEvent(self, ev) def ids_to_rows(self, ids): row_map = OrderedDict() ids = frozenset(ids) m = self.model() for row in range(m.rowCount(QModelIndex())): if len(row_map) >= len(ids): break c = m.id(row) if c in ids: row_map[c] = row return row_map def select_rows(self, identifiers, using_ids=True, change_current=True, scroll=True): ''' Select rows identified by identifiers. identifiers can be a set of ids, row numbers or QModelIndexes. ''' rows = {x.row() if hasattr(x, 'row') else x for x in identifiers} if using_ids: rows = set() identifiers = set(identifiers) m = self.model() for row in range(m.rowCount(QModelIndex())): if m.id(row) in identifiers: rows.add(row) rows = list(sorted(rows)) if rows: row = rows[0] if change_current: self.set_current_row(row, select=False) if scroll: self.scroll_to_row(row) sm = self.selectionModel() sel = QItemSelection() m = self.model() max_col = m.columnCount(QModelIndex()) - 1 # Create a range based selector for each set of contiguous rows # as supplying selectors for each individual row causes very poor # performance if a large number of rows has to be selected. for k, g in itertools.groupby(enumerate(rows), lambda i_x:i_x[0]-i_x[1]): group = list(map(operator.itemgetter(1), g)) sel.merge(QItemSelection(m.index(min(group), 0), m.index(max(group), max_col)), QItemSelectionModel.SelectionFlag.Select) sm.select(sel, QItemSelectionModel.SelectionFlag.ClearAndSelect) return rows def get_selected_ids(self, as_set=False): ans = [] seen = set() m = self.model() for idx in self.selectedIndexes(): r = idx.row() i = m.id(r) if i not in seen and i is not None: ans.append(i) seen.add(i) return seen if as_set else ans @property def current_id(self): try: return self.model().id(self.currentIndex()) except: pass return None @current_id.setter def current_id(self, val): if val is None: return m = self.model() for row in range(m.rowCount(QModelIndex())): if m.id(row) == val: self.set_current_row(row, select=False) break def show_next_book(self): ci = self.currentIndex() if not ci.isValid(): self.set_current_row() return n = (ci.row() + 1) % self.model().rowCount(QModelIndex()) self.set_current_row(n) @property def next_id(self): ''' Return the id of the 'next' row (i.e. the first unselected row after the current row). ''' ci = self.currentIndex() if not ci.isValid(): return None selected_rows = frozenset(i.row() for i in self.selectedIndexes() if i.isValid()) column = ci.column() for i in range(ci.row()+1, self.row_count()): if i in selected_rows: continue try: return self.model().id(self.model().index(i, column)) except: pass # No unselected rows after the current row, look before for i in range(ci.row()-1, -1, -1): if i in selected_rows: continue try: return self.model().id(self.model().index(i, column)) except: pass return None def close(self): self._model.close() def closeEditor(self, editor, hint): # As of Qt 6.7.2, for some reason, Qt opens the next editor after # closing this editor and then immediately closes it again. So # workaround the bug by opening the editor again after an event loop # tick. orig = self.currentIndex() move_by = None if hint is QAbstractItemDelegate.EndEditHint.EditNextItem: move_by = QAbstractItemView.CursorAction.MoveNext elif hint is QAbstractItemDelegate.EndEditHint.EditPreviousItem: move_by = QAbstractItemView.CursorAction.MovePrevious if move_by is not None: hint = QAbstractItemDelegate.EndEditHint.NoHint ans = super().closeEditor(editor, hint) if move_by is not None and self.currentIndex() == orig and self.state() is not QAbstractItemView.State.EditingState: index = self.moveCursor(move_by, Qt.KeyboardModifier.NoModifier) if index.isValid(): def edit(): self.setCurrentIndex(index) self.edit(index) QTimer.singleShot(0, edit) return ans def set_editable(self, editable, supports_backloading): self._model.set_editable(editable) def move_highlighted_row(self, forward): rows = self.selectionModel().selectedRows() if len(rows) > 0: current_row = rows[0].row() else: current_row = None id_to_select = self._model.get_next_highlighted_id(current_row, forward) if id_to_select is not None: self.select_rows([id_to_select], using_ids=True) def search_proxy(self, txt): if self.is_library_view: # Save the current book before doing the search, after the search # is completed, this book will become the current book and be # scrolled to if it is present in the search results self.alternate_views.save_current_book_state() self._model.search(txt) id_to_select = self._model.get_current_highlighted_id() if id_to_select is not None: self.select_rows([id_to_select], using_ids=True) elif self._model.highlight_only: self.clearSelection() if self.isVisible() and getattr(txt, 'as_you_type', False) is not True: self.setFocus(Qt.FocusReason.OtherFocusReason) def connect_to_search_box(self, sb, search_done): sb.search.connect(self.search_proxy) self._search_done = search_done self._model.searched.connect(self.search_done) if self.is_library_view: self._model.search_done.connect(self.alternate_views.restore_current_book_state) def connect_to_book_display(self, bd): self.book_display_callback = bd self.connect_to_book_display_timer = t = QTimer(self) t.setSingleShot(True) t.timeout.connect(self._debounce_book_display) t.setInterval(BOOK_DETAILS_DISPLAY_DEBOUNCE_DELAY) self._model.new_bookdisplay_data.connect(self._timed_connect_to_book_display) def _timed_connect_to_book_display(self, data): self._book_display_data = data self.connect_to_book_display_timer.start() def _debounce_book_display(self): data, self._book_display_data = self._book_display_data, None self.book_display_callback(data) def search_done(self, ok): self._search_done(self, ok) def row_count(self): return self._model.count() # }}} class DeviceBooksView(BooksView): # {{{ is_library_view = False def __init__(self, parent): BooksView.__init__(self, parent, DeviceBooksModel, use_edit_metadata_dialog=False) self._model.resize_rows.connect(self.do_row_sizing, type=Qt.ConnectionType.QueuedConnection) self.can_add_columns = False self.resize_on_select = False self.rating_delegate = None self.half_rating_delegate = None for i in range(10): self.setItemDelegateForColumn(i, TextDelegate(self)) self.setDragDropMode(QAbstractItemView.DragDropMode.NoDragDrop) self.setAcceptDrops(False) self.set_row_header_visibility() def set_row_header_visibility(self): self.row_header.setVisible(gprefs['row_numbers_in_book_list']) def drag_data(self): m = self.model() rows = self.selectionModel().selectedRows() paths = [force_unicode(p, enc=filesystem_encoding) for p in m.paths(rows) if p] md = QMimeData() md.setData('application/calibre+from_device', b'dummy') md.setUrls([QUrl.fromLocalFile(p) for p in paths]) drag = QDrag(self) drag.setMimeData(md) cover = self.drag_icon(m.cover(self.currentIndex().row()), len(paths) > 1) drag.setHotSpot(QPoint(-15, -15)) drag.setPixmap(cover) return drag def contextMenuEvent(self, event): edit_collections = callable(getattr(self._model.db, 'supports_collections', None)) and \ self._model.db.supports_collections() and \ prefs['manage_device_metadata'] == 'manual' self.edit_collections_action.setVisible(edit_collections) self.context_menu.popup(event.globalPos()) event.accept() def get_old_state(self): ans = None name = str(self.objectName()) if name: name += ' books view state' ans = gprefs.get(name, None) return ans def write_state(self, state): name = str(self.objectName()) if name: gprefs.set(name + ' books view state', state) def set_database(self, db): self._model.set_database(db) self.restore_state() def connect_dirtied_signal(self, slot): self._model.booklist_dirtied.connect(slot) def connect_upload_collections_signal(self, func=None, oncard=None): self._model.upload_collections.connect(partial(func, view=self, oncard=oncard)) def dropEvent(self, *args): error_dialog(self, _('Not allowed'), _('Dropping onto a device is not supported. First add the book to the calibre library.')).exec() def set_editable(self, editable, supports_backloading): self._model.set_editable(editable) self.drag_allowed = supports_backloading def resort(self): h = self.horizontalHeader() self.model().sort(h.sortIndicatorSection(), h.sortIndicatorOrder()) def reverse_sort(self): h = self.horizontalHeader() h.setSortIndicator( h.sortIndicatorSection(), Qt.SortOrder.AscendingOrder if h.sortIndicatorOrder() == Qt.SortOrder.DescendingOrder else Qt.SortOrder.DescendingOrder) # }}}
79,644
Python
.py
1,619
37.332922
158
0.603885
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,902
match_books.py
kovidgoyal_calibre/src/calibre/gui2/actions/match_books.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from calibre.gui2 import error_dialog, question_dialog from calibre.gui2.actions import InterfaceAction from calibre.gui2.dialogs.match_books import MatchBooks class MatchBookAction(InterfaceAction): name = 'Match Books' action_spec = (_('Match book to library'), 'book.png', _('Match this book to a book in the library'), ()) dont_add_to = frozenset(('menubar', 'toolbar', 'context-menu', 'toolbar-child', 'context-menu-cover-browser')) action_type = 'current' def genesis(self): self.qaction.triggered.connect(self.match_books_in_library) def location_selected(self, loc): enabled = loc != 'library' self.qaction.setEnabled(enabled) self.menuless_qaction.setEnabled(enabled) def match_books_in_library(self, *args): view = self.gui.current_view() rows = view.selectionModel().selectedRows() if not rows or len(rows) != 1: d = error_dialog(self.gui, _('Match books'), _('You must select one book')) d.exec() return id_ = view.model().indices(rows)[0] MatchBooks(self.gui, view, id_, rows[0]).exec() class ShowMatchedBookAction(InterfaceAction): name = 'Show Matched Book In Library' action_spec = (_('Show matched book in library'), 'lt.png', _('Show the book in the calibre library that matches this book'), ()) dont_add_to = frozenset(('menubar', 'toolbar', 'context-menu', 'toolbar-child', 'context-menu-cover-browser')) action_type = 'current' def genesis(self): self.qaction.triggered.connect(self.show_matched_books_in_library) def location_selected(self, loc): enabled = loc != 'library' self.qaction.setEnabled(enabled) self.menuless_qaction.setEnabled(enabled) def show_matched_books_in_library(self, *args): view = self.gui.current_view() rows = view.selectionModel().selectedRows() if not rows or len(rows) != 1: d = error_dialog(self.gui, _('Match books'), _('You must select one book')) d.exec() return device_book_index = view.model().indices(rows)[0] device_db = view.model().db db = self.gui.current_db.new_api book = device_db[device_book_index] matching_book_ids = db.books_matching_device_book(book.lpath) if not matching_book_ids: if question_dialog(self.gui, _('No matching books'), _( 'No matching books found in the calibre library. Do you want to specify the' ' matching book manually?')): MatchBooks(self.gui, view, device_book_index, rows[0]).exec() return ids = tuple(sorted(matching_book_ids, reverse=True)) self.gui.library_view.select_rows(ids) self.gui.show_library_view() self.gui.iactions['Edit Metadata'].refresh_books_after_metadata_edit(ids)
3,096
Python
.py
64
39.984375
114
0.640133
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,903
fetch_news.py
kovidgoyal_calibre/src/calibre/gui2/actions/fetch_news.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import gc from functools import partial from qt.core import Qt from calibre.gui2 import Dispatcher from calibre.gui2.actions import InterfaceAction from calibre.gui2.tools import fetch_scheduled_recipe class FetchNewsAction(InterfaceAction): name = 'Fetch News' action_spec = (_('Fetch news'), 'news.png', _('Download news in e-book form from various websites all over the world'), _('F')) def location_selected(self, loc): enabled = loc == 'library' self.qaction.setEnabled(enabled) self.menuless_qaction.setEnabled(enabled) def genesis(self): self.conversion_jobs = {} def init_scheduler(self): from calibre.gui2.dialogs.scheduler import Scheduler self.scheduler = Scheduler(self.gui) self.scheduler.start_recipe_fetch.connect(self.download_scheduled_recipe, type=Qt.ConnectionType.QueuedConnection) self.qaction.setMenu(self.scheduler.news_menu) self.qaction.triggered.connect( self.scheduler.show_dialog) def initialization_complete(self): self.connect_scheduler() def connect_scheduler(self): self.scheduler.delete_old_news.connect( self.gui.library_view.model().delete_books_by_id, type=Qt.ConnectionType.QueuedConnection) def download_custom_recipe(self, title, urn): arg = {'title': title, 'urn': urn, 'username': None, 'password': None} func, args, desc, fmt, temp_files = fetch_scheduled_recipe(arg) job = self.gui.job_manager.run_job( Dispatcher(self.custom_recipe_fetched), func, args=args, description=desc) self.conversion_jobs[job] = (temp_files, fmt, arg) self.gui.status_bar.show_message(_('Fetching news from ')+arg['title'], 2000) def custom_recipe_fetched(self, job): temp_files, fmt, arg = self.conversion_jobs.pop(job) fname = temp_files[0].name if job.failed: return self.gui.job_exception(job) self.gui.library_view.model().add_news(fname, arg) def download_scheduled_recipe(self, arg): func, args, desc, fmt, temp_files = \ fetch_scheduled_recipe(arg) job = self.gui.job_manager.run_job( Dispatcher(self.scheduled_recipe_fetched), func, args=args, description=desc) self.conversion_jobs[job] = (temp_files, fmt, arg) self.gui.status_bar.show_message(_('Fetching news from ')+arg['title'], 2000) def scheduled_recipe_fetched(self, job): temp_files, fmt, arg = self.conversion_jobs.pop(job) fname = temp_files[0].name if job.failed: self.scheduler.recipe_download_failed(arg) return self.gui.job_exception(job, retry_func=partial(self.scheduler.download, arg['urn'])) id = self.gui.library_view.model().add_news(fname, arg) # Arg may contain a "keep_issues" variable. If it is non-zero, # delete all but newest x issues. try: keep_issues = int(arg['keep_issues']) except: keep_issues = 0 if keep_issues > 0: ids_with_tag = list(sorted(self.gui.library_view.model(). db.tags_older_than(arg['title'], None, must_have_tag=_('News')), reverse=True)) ids_to_delete = ids_with_tag[keep_issues:] if ids_to_delete: self.gui.library_view.model().delete_books_by_id(ids_to_delete) self.gui.library_view.model().beginResetModel(), self.gui.library_view.model().endResetModel() sync = self.gui.news_to_be_synced sync.add(id) self.gui.news_to_be_synced = sync self.scheduler.recipe_downloaded(arg) self.gui.status_bar.show_message(arg['title'] + _(' fetched.'), 3000) self.gui.email_news(id) self.gui.sync_news() gc.collect()
4,023
Python
.py
81
40.728395
131
0.648738
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,904
device.py
kovidgoyal_calibre/src/calibre/gui2/actions/device.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from qt.core import QIcon, QMenu, QTimer, QToolButton, QUrl, pyqtSignal from calibre.gui2 import info_dialog, open_url, question_dialog from calibre.gui2.actions import InterfaceAction from calibre.gui2.dialogs.smartdevice import SmartdeviceDialog from calibre.startup import connect_lambda from calibre.utils.icu import primary_sort_key from calibre.utils.smtp import config as email_config def local_url_for_content_server(): from calibre.srv.opts import server_config from calibre.utils.network import format_addr_for_url, get_fallback_server_addr opts = server_config() addr = opts.listen_on or get_fallback_server_addr() addr = {'0.0.0.0': '127.0.0.1', '::': '::1'}.get(addr, addr) protocol = 'https' if opts.ssl_certfile and opts.ssl_keyfile else 'http' prefix = opts.url_prefix or '' port = opts.port return f'{protocol}://{format_addr_for_url(addr)}:{port}{prefix}' def open_in_browser(): open_url(QUrl(local_url_for_content_server())) class ShareConnMenu(QMenu): # {{{ connect_to_folder = pyqtSignal() config_email = pyqtSignal() toggle_server = pyqtSignal() control_smartdevice = pyqtSignal() server_state_changed_signal = pyqtSignal(object, object) dont_add_to = frozenset(('context-menu-device',)) DEVICE_MSGS = [_('Start wireless device connection'), _('Stop wireless device connection')] def __init__(self, parent=None): QMenu.__init__(self, parent) self.ip_text = '' mitem = self.addAction(QIcon.ic('devices/folder.png'), _('Connect to folder')) mitem.setEnabled(True) connect_lambda(mitem.triggered, self, lambda self: self.connect_to_folder.emit()) self.connect_to_folder_action = mitem self.addSeparator() self.toggle_server_action = \ self.addAction(QIcon.ic('network-server.png'), _('Start Content server')) connect_lambda(self.toggle_server_action.triggered, self, lambda self: self.toggle_server.emit()) self.open_server_in_browser_action = self.addAction( QIcon.ic('forward.png'), _("Visit Content server in browser")) connect_lambda(self.open_server_in_browser_action.triggered, self, lambda self: open_in_browser()) self.open_server_in_browser_action.setVisible(False) self.control_smartdevice_action = \ self.addAction(QIcon.ic('dot_red.png'), self.DEVICE_MSGS[0]) connect_lambda(self.control_smartdevice_action.triggered, self, lambda self: self.control_smartdevice.emit()) self.addSeparator() self.email_actions = [] if hasattr(parent, 'keyboard'): r = parent.keyboard.register_shortcut prefix = 'Share/Connect Menu ' gr = ConnectShareAction.action_spec[0] for attr in ('folder', ): ac = getattr(self, 'connect_to_%s_action'%attr) r(prefix + attr, str(ac.text()), action=ac, group=gr) r(prefix+' content server', _('Start/stop Content server'), action=self.toggle_server_action, group=gr) r(prefix + ' open server in browser', self.open_server_in_browser_action.text(), action=self.open_server_in_browser_action, group=gr) def server_state_changed(self, running): from calibre.utils.mdns import get_external_ip, verify_ip_address text = _('Start Content server') if running: from calibre.srv.opts import server_config opts = server_config() listen_on = verify_ip_address(opts.listen_on) or get_external_ip() protocol = 'HTTPS' if opts.ssl_certfile and opts.ssl_keyfile else 'HTTP' try: ip_text = ' ' + _('[{ip}, port {port}, {protocol}]').format( ip=listen_on, port=opts.port, protocol=protocol) except Exception: ip_text = f' [{listen_on} {protocol}]' self.ip_text = ip_text self.server_state_changed_signal.emit(running, ip_text) text = _('Stop Content server') + ip_text else: self.ip_text = '' self.toggle_server_action.setText(text) self.open_server_in_browser_action.setVisible(running) def hide_smartdevice_menus(self): self.control_smartdevice_action.setVisible(False) def build_email_entries(self, sync_menu): from calibre.gui2.device import DeviceAction for ac in self.email_actions: self.removeAction(ac) self.email_actions = [] self.memory = [] opts = email_config().parse() if opts.accounts: self.email_to_menu = QMenu(_('Email to')+'...', self) ac = self.addMenu(self.email_to_menu) self.email_actions.append(ac) self.email_to_and_delete_menu = QMenu( _('Email to and delete from library')+'...', self) keys = sorted(opts.accounts.keys()) def sk(account): return primary_sort_key(opts.aliases.get(account) or account) for account in sorted(keys, key=sk): formats, auto, default = opts.accounts[account] subject = opts.subjects.get(account, '') alias = opts.aliases.get(account, '') dest = 'mail:'+account+';'+formats+';'+subject action1 = DeviceAction(dest, False, False, 'mail.png', alias or account) action2 = DeviceAction(dest, True, False, 'mail.png', (alias or account) + ' ' + _('(delete from library)')) self.email_to_menu.addAction(action1) self.email_to_and_delete_menu.addAction(action2) self.memory.append(action1) self.memory.append(action2) if default: ac = DeviceAction(dest, False, False, 'mail.png', _('Email to') + ' ' +(alias or account)) self.addAction(ac) self.email_actions.append(ac) ac.a_s.connect(sync_menu.action_triggered) action1.a_s.connect(sync_menu.action_triggered) action2.a_s.connect(sync_menu.action_triggered) action1 = DeviceAction('choosemail:', False, False, 'mail.png', _('Select recipients')) action2 = DeviceAction('choosemail:', True, False, 'mail.png', _('Select recipients') + ' ' + _('(delete from library)')) self.email_to_menu.addAction(action1) self.email_to_and_delete_menu.addAction(action2) self.memory.append(action1) self.memory.append(action2) tac1 = DeviceAction('choosemail:', False, False, 'mail.png', _('Email to selected recipients...')) self.addAction(tac1) tac1.a_s.connect(sync_menu.action_triggered) self.memory.append(tac1) self.email_actions.append(tac1) ac = self.addMenu(self.email_to_and_delete_menu) self.email_actions.append(ac) action1.a_s.connect(sync_menu.action_triggered) action2.a_s.connect(sync_menu.action_triggered) else: ac = self.addAction(QIcon.ic('mail.png'), _('Setup email based sharing of books')) self.email_actions.append(ac) ac.triggered.connect(self.setup_email) def setup_email(self, *args): self.config_email.emit() def set_state(self, device_connected, device): self.connect_to_folder_action.setEnabled(not device_connected) # }}} class SendToDeviceAction(InterfaceAction): name = 'Send To Device' action_spec = (_('Send to device'), 'sync.png', None, _('D')) dont_add_to = frozenset(('menubar', 'toolbar', 'context-menu', 'toolbar-child')) def genesis(self): self.qaction.triggered.connect(self.do_sync) self.gui.create_device_menu() def location_selected(self, loc): enabled = loc == 'library' self.qaction.setEnabled(enabled) self.menuless_qaction.setEnabled(enabled) def do_sync(self, *args): self.gui._sync_action_triggered() class ConnectShareAction(InterfaceAction): name = 'Connect Share' action_spec = (_('Connect/share'), 'connect_share.png', _('Share books using a web server or email. Connect to special devices, etc.'), None) popup_type = QToolButton.ToolButtonPopupMode.InstantPopup def genesis(self): self.content_server_is_running = False self.share_conn_menu = ShareConnMenu(self.gui) self.share_conn_menu.aboutToShow.connect(self.set_smartdevice_action_state) self.share_conn_menu.toggle_server.connect(self.toggle_content_server) self.share_conn_menu.control_smartdevice.connect(self.control_smartdevice) connect_lambda(self.share_conn_menu.config_email, self, lambda self: self.gui.iactions['Preferences'].do_config(initial_plugin=('Sharing', 'Email'), close_after_initial=True)) self.qaction.setMenu(self.share_conn_menu) self.share_conn_menu.connect_to_folder.connect(self.gui.connect_to_folder) def location_selected(self, loc): enabled = loc == 'library' self.qaction.setEnabled(enabled) self.menuless_qaction.setEnabled(enabled) def set_state(self, device_connected, device): self.share_conn_menu.set_state(device_connected, device) def build_email_entries(self): m = self.gui.iactions['Send To Device'].qaction.menu() self.share_conn_menu.build_email_entries(m) def content_server_state_changed(self, running): self.share_conn_menu.server_state_changed(running) if running: self.content_server_is_running = True self.qaction.setIcon(QIcon.ic('connect_share_on.png')) else: self.content_server_is_running = False self.qaction.setIcon(QIcon.ic('connect_share.png')) def toggle_content_server(self): if self.gui.content_server is None: self.gui.start_content_server() else: self.gui.content_server.stop() self.stopping_msg = info_dialog(self.gui, _('Stopping'), _('Stopping server, this could take up to a minute, please wait...'), show_copy_button=False) QTimer.singleShot(1000, self.check_exited) self.stopping_msg.exec() def check_exited(self): if getattr(self.gui.content_server, 'is_running', False): QTimer.singleShot(50, self.check_exited) return self.gui.content_server = None self.stopping_msg.accept() def control_smartdevice(self): dm = self.gui.device_manager running = dm.is_running('smartdevice') if running: dm.stop_plugin('smartdevice') if dm.get_option('smartdevice', 'autostart'): if not question_dialog(self.gui, _('Disable autostart'), _('Do you want wireless device connections to be' ' started automatically when calibre starts?')): dm.set_option('smartdevice', 'autostart', False) else: sd_dialog = SmartdeviceDialog(self.gui) sd_dialog.exec() self.set_smartdevice_action_state() def check_smartdevice_menus(self): if not self.gui.device_manager.is_enabled('smartdevice'): self.share_conn_menu.hide_smartdevice_menus() def set_smartdevice_action_state(self): from calibre.gui2.dialogs.smartdevice import get_all_ip_addresses dm = self.gui.device_manager forced_ip = dm.get_option('smartdevice', 'force_ip_address') if forced_ip: formatted_addresses = forced_ip show_port = True else: all_ips = get_all_ip_addresses() if len(all_ips) == 0: formatted_addresses = _('Still looking for IP addresses') show_port = False elif len(all_ips) > 3: formatted_addresses = _('Many IP addresses. See Start/Stop dialog.') show_port = False else: formatted_addresses = ' or '.join(get_all_ip_addresses()) show_port = True running = dm.is_running('smartdevice') if not running: text = self.share_conn_menu.DEVICE_MSGS[0] else: use_fixed_port = dm.get_option('smartdevice', 'use_fixed_port') port_number = dm.get_option('smartdevice', 'port_number') if show_port and use_fixed_port: text = self.share_conn_menu.DEVICE_MSGS[1] + ' [%s, port %s]'%( formatted_addresses, port_number) else: text = self.share_conn_menu.DEVICE_MSGS[1] + ' [' + formatted_addresses + ']' icon = 'green' if running else 'red' ac = self.share_conn_menu.control_smartdevice_action ac.setIcon(QIcon.ic('dot_%s.png'%icon)) ac.setText(text)
13,424
Python
.py
263
39.764259
145
0.612827
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,905
choose_library.py
kovidgoyal_calibre/src/calibre/gui2/actions/choose_library.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os import posixpath import sys import weakref from contextlib import suppress from functools import lru_cache, partial from qt.core import ( QAction, QCoreApplication, QDialog, QDialogButtonBox, QGridLayout, QIcon, QInputDialog, QLabel, QLineEdit, QMenu, QSize, Qt, QTimer, QToolButton, QVBoxLayout, pyqtSignal, ) from calibre import isbytestring, sanitize_file_name from calibre.constants import config_dir, filesystem_encoding, get_portable_base, isportable, iswindows from calibre.gui2 import ( Dispatcher, choose_dir, choose_images, error_dialog, gprefs, info_dialog, open_local_file, pixmap_to_data, question_dialog, warning_dialog, ) from calibre.gui2.actions import InterfaceAction from calibre.library import current_library_name from calibre.startup import connect_lambda from calibre.utils.config import prefs, tweaks from calibre.utils.icu import sort_key from calibre.utils.localization import ngettext def db_class(): from calibre.db.legacy import LibraryDatabase return LibraryDatabase def library_icon_path(lib_name=''): return os.path.join(config_dir, 'library_icons', sanitize_file_name(lib_name or current_library_name()) + '.png') @lru_cache(maxsize=512) def library_qicon(lib_name=''): q = library_icon_path(lib_name) if os.path.exists(q): return QIcon(q) return getattr(library_qicon, 'default_icon', None) or QIcon.ic('lt.png') class LibraryUsageStats: # {{{ def __init__(self): self.stats = {} self.read_stats() base = get_portable_base() if base is not None: lp = prefs['library_path'] if lp: # Rename the current library. Renaming of other libraries is # handled by the switch function q = os.path.basename(lp) for loc in list(self.stats): bn = posixpath.basename(loc) if bn.lower() == q.lower(): self.rename(loc, lp) def read_stats(self): stats = gprefs.get('library_usage_stats', {}) self.stats = stats def write_stats(self): locs = list(self.stats.keys()) locs.sort(key=lambda x: self.stats[x], reverse=True) for key in locs[500:]: self.stats.pop(key) gprefs.set('library_usage_stats', self.stats) def remove(self, location): self.stats.pop(location, None) self.write_stats() def canonicalize_path(self, lpath): if isbytestring(lpath): lpath = lpath.decode(filesystem_encoding) lpath = lpath.replace(os.sep, '/') return lpath def library_used(self, db): lpath = self.canonicalize_path(db.library_path) if lpath not in self.stats: self.stats[lpath] = 0 self.stats[lpath] += 1 self.write_stats() return self.pretty(lpath) def locations(self, db, limit=None): lpath = self.canonicalize_path(db.library_path) locs = list(self.stats.keys()) if lpath in locs: locs.remove(lpath) limit = tweaks['many_libraries'] if limit is None else limit key = (lambda x:sort_key(os.path.basename(x))) if len(locs) > limit else self.stats.get locs.sort(key=key, reverse=len(locs)<=limit) for loc in locs: yield self.pretty(loc), loc def pretty(self, loc): if loc.endswith('/'): loc = loc[:-1] return loc.split('/')[-1] def rename(self, location, newloc): newloc = self.canonicalize_path(newloc) stats = self.stats.pop(location, None) if stats is not None: self.stats[newloc] = stats self.write_stats() # }}} class MovedDialog(QDialog): # {{{ def __init__(self, stats, location, parent=None): QDialog.__init__(self, parent) self.setWindowTitle(_('No library found')) self._l = l = QGridLayout(self) self.setLayout(l) self.stats, self.location = stats, location loc = self.oldloc = location.replace('/', os.sep) self.header = QLabel(_('No existing calibre library was found at %s. ' 'If the library was moved, select its new location below. ' 'Otherwise calibre will forget this library.')%loc) self.header.setWordWrap(True) ncols = 2 l.addWidget(self.header, 0, 0, 1, ncols) self.cl = QLabel('<b>'+_('New location of this library:')) l.addWidget(self.cl, l.rowCount(), 0, 1, ncols) self.loc = QLineEdit(loc, self) l.addWidget(self.loc, l.rowCount(), 0, 1, 1) self.cd = QToolButton(self) self.cd.setIcon(QIcon.ic('document_open.png')) self.cd.clicked.connect(self.choose_dir) l.addWidget(self.cd, l.rowCount() - 1, 1, 1, 1) self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Abort) b = self.bb.addButton(_('Library moved'), QDialogButtonBox.ButtonRole.AcceptRole) b.setIcon(QIcon.ic('ok.png')) b = self.bb.addButton(_('Forget library'), QDialogButtonBox.ButtonRole.RejectRole) b.setIcon(QIcon.ic('edit-clear.png')) b.clicked.connect(self.forget_library) self.bb.accepted.connect(self.accept) self.bb.rejected.connect(self.reject) l.addWidget(self.bb, 3, 0, 1, ncols) self.resize(self.sizeHint() + QSize(120, 0)) def choose_dir(self): d = choose_dir(self, 'library moved choose new loc', _('New library location'), default_dir=self.oldloc) if d is not None: self.loc.setText(d) def forget_library(self): self.stats.remove(self.location) def accept(self): newloc = str(self.loc.text()) if not db_class().exists_at(newloc): error_dialog(self, _('No library found'), _('No existing calibre library found at %s')%newloc, show=True) return self.stats.rename(self.location, newloc) self.newloc = newloc QDialog.accept(self) # }}} class BackupStatus(QDialog): # {{{ def __init__(self, gui): QDialog.__init__(self, gui) self.l = l = QVBoxLayout(self) self.msg = QLabel('') self.msg.setWordWrap(True) l.addWidget(self.msg) self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) b = bb.addButton(_('Queue &all books for backup'), QDialogButtonBox.ButtonRole.ActionRole) b.clicked.connect(self.mark_all_dirty) b.setIcon(QIcon.ic('lt.png')) l.addWidget(bb) self.db = weakref.ref(gui.current_db) self.setResult(9) self.setWindowTitle(_('Backup status')) self.update() self.resize(self.sizeHint() + QSize(50, 15)) def update(self): db = self.db() if db is None: return if self.result() != 9: return dirty_text = 'no' try: dirty_text = '%s' % db.dirty_queue_length() except: dirty_text = _('none') self.msg.setText('<p>' + _( 'Book metadata files remaining to be written: %s') % dirty_text) QTimer.singleShot(1000, self.update) def mark_all_dirty(self): db = self.db() if db is None: return db.new_api.mark_as_dirty(db.new_api.all_book_ids()) # }}} current_change_library_action_pi = None def set_change_library_action_plugin(pi): global current_change_library_action_pi current_change_library_action_pi = pi def get_change_library_action_plugin(): return current_change_library_action_pi class ChooseLibraryAction(InterfaceAction): name = 'Choose Library' action_spec = (_('Choose library'), 'lt.png', _('Choose calibre library to work with'), None) dont_add_to = frozenset(('context-menu-device',)) action_add_menu = True action_menu_clone_qaction = _('Switch/create library') restore_view_state = pyqtSignal(object) rebuild_change_library_menus = pyqtSignal() def genesis(self): self.prev_lname = self.last_lname = '' self.count_changed(0) self.action_choose = self.menuless_qaction self.action_exim = ac = QAction(_('Export/import all calibre data'), self.gui) ac.triggered.connect(self.exim_data) self.stats = LibraryUsageStats() self.popup_type = (QToolButton.ToolButtonPopupMode.InstantPopup if len(self.stats.stats) > 1 else QToolButton.ToolButtonPopupMode.MenuButtonPopup) if len(self.stats.stats) > 1: self.action_choose.triggered.connect(self.choose_library) else: self.qaction.triggered.connect(self.choose_library) self.choose_menu = self.qaction.menu() ac = self.create_action(spec=(_('Pick a random book'), 'random.png', None, None), attr='action_pick_random') ac.triggered.connect(self.pick_random) self.choose_library_icon_menu = QMenu(_('Change the icon for this library')) self.choose_library_icon_menu.setIcon(QIcon.ic('icon_choose.png')) self.choose_library_icon_action = self.create_action( spec=(_('Choose an icon'), 'icon_choose.png', None, None), attr='action_choose_library_icon') self.remove_library_icon_action = self.create_action( spec=(_('Remove current icon'), 'trash.png', None, None), attr='action_remove_library_icon') self.choose_library_icon_action.triggered.connect(self.get_library_icon) self.remove_library_icon_action.triggered.connect(partial(self.remove_library_icon, '')) self.choose_library_icon_menu.addAction(self.choose_library_icon_action) self.choose_library_icon_menu.addAction(self.remove_library_icon_action) self.original_library_icon = library_qicon.default_icon = self.qaction.icon() if not os.environ.get('CALIBRE_OVERRIDE_DATABASE_PATH', None): self.choose_menu.addAction(self.action_choose) self.quick_menu = QMenu(_('Quick switch')) self.quick_menu_action = self.choose_menu.addMenu(self.quick_menu) self.choose_menu.addMenu(self.choose_library_icon_menu) self.rename_menu = QMenu(_('Rename library')) self.rename_menu_action = self.choose_menu.addMenu(self.rename_menu) self.choose_menu.addAction(ac) self.delete_menu = QMenu(_('Remove library')) self.delete_menu_action = self.choose_menu.addMenu(self.delete_menu) self.vl_to_apply_menu = QMenu('waiting ...') self.vl_to_apply_action = self.choose_menu.addMenu(self.vl_to_apply_menu) self.rebuild_change_library_menus.connect(self.build_menus, type=Qt.ConnectionType.QueuedConnection) self.choose_menu.addAction(self.action_exim) else: self.choose_menu.addMenu(self.choose_library_icon_menu) self.choose_menu.addAction(ac) self.rename_separator = self.choose_menu.addSeparator() self.switch_actions = [] for i in range(5): ac = self.create_action(spec=('', None, None, None), attr='switch_action%d'%i) ac.setObjectName(str(i)) self.switch_actions.append(ac) ac.setVisible(False) connect_lambda(ac.triggered, self, lambda self: self.switch_requested(self.qs_locations[int(self.gui.sender().objectName())]), type=Qt.ConnectionType.QueuedConnection) self.choose_menu.addAction(ac) self.rename_separator = self.choose_menu.addSeparator() self.maintenance_menu = QMenu(_('Library maintenance')) ac = self.create_action(spec=(_('Library metadata backup status'), 'lt.png', None, None), attr='action_backup_status') ac.triggered.connect(self.backup_status, type=Qt.ConnectionType.QueuedConnection) self.maintenance_menu.addAction(ac) ac = self.create_action(spec=(_('Check library'), 'lt.png', None, None), attr='action_check_library') ac.triggered.connect(self.check_library, type=Qt.ConnectionType.QueuedConnection) self.maintenance_menu.addAction(ac) ac = self.create_action(spec=(_('Restore database'), 'lt.png', None, None), attr='action_restore_database') ac.triggered.connect(self.restore_database, type=Qt.ConnectionType.QueuedConnection) self.maintenance_menu.addAction(ac) self.choose_menu.addMenu(self.maintenance_menu) self.view_state_map = {} self.restore_view_state.connect(self._restore_view_state, type=Qt.ConnectionType.QueuedConnection) ac = self.create_action(spec=(_('Switch to previous library'), 'lt.png', None, None), attr='action_previous_library') ac.triggered.connect(self.switch_to_previous_library, type=Qt.ConnectionType.QueuedConnection) self.gui.keyboard.register_shortcut( self.unique_name + '-' + 'action_previous_library', ac.text(), action=ac, group=self.action_spec[0], default_keys=('Ctrl+Alt+p',)) self.gui.addAction(ac) @property def preserve_state_on_switch(self): ans = getattr(self, '_preserve_state_on_switch', None) if ans is None: self._preserve_state_on_switch = ans = \ self.gui.library_view.preserve_state(require_selected_ids=False) return ans def pick_random(self, *args): self.gui.iactions['Pick Random Book'].pick_random() 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() library_qicon.cache_clear() except Exception: import traceback traceback.print_exc() def rename_library_icon(self, old_name, new_name): old_path = library_icon_path(old_name) new_path = library_icon_path(new_name) try: if os.path.exists(old_path): os.replace(old_path, new_path) library_qicon.cache_clear() except Exception: import traceback traceback.print_exc() def remove_library_icon(self, name=''): try: with suppress(FileNotFoundError): os.remove(library_icon_path(name or current_library_name())) self.set_library_icon() library_qicon.cache_clear() except Exception: import traceback traceback.print_exc() def set_library_icon(self): icon = QIcon.ic(library_icon_path()) has_icon = not icon.isNull() and len(icon.availableSizes()) > 0 if not has_icon: icon = self.original_library_icon self.qaction.setIcon(icon) self.gui.setWindowIcon(icon) self.remove_library_icon_action.setEnabled(has_icon) def exim_data(self): if isportable: return error_dialog(self.gui, _('Cannot export/import'), _( 'You are running calibre portable, all calibre data is already in the' ' calibre portable folder. Export/import is unavailable.'), show=True) if self.gui.job_manager.has_jobs(): return error_dialog(self.gui, _('Cannot export/import'), _('Cannot export/import data while there are running jobs.'), show=True) from calibre.gui2.dialogs.exim import EximDialog d = EximDialog(parent=self.gui) if d.exec() == QDialog.DialogCode.Accepted: if d.restart_needed: self.gui.iactions['Restart'].restart() def library_name(self): db = self.gui.library_view.model().db path = db.library_path if isbytestring(path): path = path.decode(filesystem_encoding) path = path.replace(os.sep, '/') return self.stats.pretty(path) def update_tooltip(self, count): tooltip = self.action_spec[2] + '\n\n' + ngettext('{0} [{1} book]', '{0} [{1} books]', count).format( getattr(self, 'last_lname', ''), count) a = self.qaction a.setToolTip(tooltip) a.setStatusTip(tooltip) a.setWhatsThis(tooltip) def library_changed(self, db): lname = self.stats.library_used(db) if lname != self.last_lname: self.prev_lname = self.last_lname self.last_lname = lname if len(lname) > 16: lname = lname[:16] + '…' a = self.qaction a.setText(lname.replace('&', '&&&')) # I have no idea why this requires a triple ampersand self.update_tooltip(db.count()) self.build_menus() self.set_library_icon() state = self.view_state_map.get(self.stats.canonicalize_path( db.library_path), None) if state is not None: self.restore_view_state.emit(state) def _restore_view_state(self, state): self.preserve_state_on_switch.state = state def initialization_complete(self): self.library_changed(self.gui.library_view.model().db) set_change_library_action_plugin(self) def switch_to_previous_library(self): db = self.gui.library_view.model().db locations = list(self.stats.locations(db)) for name, loc in locations: is_prev_lib = name == self.prev_lname if is_prev_lib: self.switch_requested(loc) break def build_menus(self): if os.environ.get('CALIBRE_OVERRIDE_DATABASE_PATH', None): return db = self.gui.library_view.model().db lname = self.stats.library_used(db) self.vl_to_apply_action.setText(_('Apply Virtual library when %s is opened') % lname) locations = list(self.stats.locations(db)) for ac in self.switch_actions: ac.setVisible(False) self.quick_menu.clear() self.rename_menu.clear() self.delete_menu.clear() quick_actions, rename_actions, delete_actions = [], [], [] for name, loc in locations: is_prev_lib = name == self.prev_lname ic = library_qicon(name) name = name.replace('&', '&&') ac = self.quick_menu.addAction(ic, name, Dispatcher(partial(self.switch_requested, loc))) ac.setStatusTip(_('Switch to: %s') % loc) if is_prev_lib: f = ac.font() f.setBold(True) ac.setFont(f) quick_actions.append(ac) ac = self.rename_menu.addAction(name, Dispatcher(partial(self.rename_requested, name, loc))) rename_actions.append(ac) ac.setStatusTip(_('Rename: %s') % loc) ac = self.delete_menu.addAction(name, Dispatcher(partial(self.delete_requested, name, loc))) delete_actions.append(ac) ac.setStatusTip(_('Remove: %s') % loc) if is_prev_lib: ac.setFont(f) qs_actions = [] locations_by_frequency = locations if len(locations) >= tweaks['many_libraries']: locations_by_frequency = list(self.stats.locations(db, limit=sys.maxsize)) for i, x in enumerate(locations_by_frequency[:len(self.switch_actions)]): name, loc = x ic = library_qicon(name) name = name.replace('&', '&&') ac = self.switch_actions[i] ac.setText(name) ac.setIcon(ic) ac.setStatusTip(_('Switch to: %s') % loc) ac.setVisible(True) qs_actions.append(ac) self.qs_locations = [i[1] for i in locations_by_frequency] self.quick_menu_action.setVisible(bool(locations)) self.rename_menu_action.setVisible(bool(locations)) self.delete_menu_action.setVisible(bool(locations)) self.gui.location_manager.set_switch_actions(quick_actions, rename_actions, delete_actions, qs_actions, self.action_choose) # VL at startup self.vl_to_apply_menu.clear() restrictions = sorted(db.prefs['virtual_libraries'], key=sort_key) # check that the virtual library choice still exists vl_at_startup = db.prefs['virtual_lib_on_startup'] if vl_at_startup and vl_at_startup not in restrictions: vl_at_startup = db.prefs['virtual_lib_on_startup'] = '' restrictions.insert(0, '') for vl in restrictions: if vl == vl_at_startup: self.vl_to_apply_menu.addAction(QIcon.ic('ok.png'), vl if vl else _('No Virtual library'), Dispatcher(partial(self.change_vl_at_startup_requested, vl))) else: self.vl_to_apply_menu.addAction(vl if vl else _('No Virtual library'), Dispatcher(partial(self.change_vl_at_startup_requested, vl))) # Allow the cloned actions in the OS X global menubar to update for a in (self.qaction, self.menuless_qaction): a.changed.emit() def change_vl_at_startup_requested(self, vl): self.gui.library_view.model().db.prefs['virtual_lib_on_startup'] = vl self.build_menus() def location_selected(self, loc): enabled = loc == 'library' self.qaction.setEnabled(enabled) self.menuless_qaction.setEnabled(enabled) def rename_requested(self, name, location): LibraryDatabase = db_class() loc = location.replace('/', os.sep) base = os.path.dirname(loc) old_name = name.replace('&&', '&') newname, ok = QInputDialog.getText(self.gui, _('Rename') + ' ' + old_name, '<p>'+_( 'Choose a new name for the library <b>%s</b>. ')%name + '<p>'+_( 'Note that the actual library folder will be renamed.') + '<p>' + _( 'WARNING: This means that any calibre:// URLs that point to things in this library will stop working.'), text=old_name) newname = sanitize_file_name(str(newname)) if not ok or not newname or newname == old_name: return newloc = os.path.join(base, newname) if os.path.exists(newloc): return error_dialog(self.gui, _('Already exists'), _('The folder %s already exists. Delete it first.') % newloc, show=True) if (iswindows and len(newloc) > LibraryDatabase.WINDOWS_LIBRARY_PATH_LIMIT): return error_dialog(self.gui, _('Too long'), _('Path to library too long. It must be less than' ' %d characters.')%LibraryDatabase.WINDOWS_LIBRARY_PATH_LIMIT, show=True) if not os.path.exists(loc): error_dialog(self.gui, _('Not found'), _('Cannot rename as no library was found at %s. ' 'Try switching to this library first, then switch back ' 'and retry the renaming.')%loc, show=True) return self.gui.library_broker.remove_library(loc) try: os.rename(loc, newloc) except: import traceback det_msg = 'Location: %r New Location: %r\n%s'%(loc, newloc, traceback.format_exc()) error_dialog(self.gui, _('Rename failed'), _('Failed to rename the library at %s. ' 'The most common cause for this is if one of the files' ' in the library is open in another program.') % loc, det_msg=det_msg, show=True) return self.stats.rename(location, newloc) self.rename_library_icon(old_name, newname) self.build_menus() self.gui.iactions['Copy To Library'].build_menus() def delete_requested(self, name, location): loc = location.replace('/', os.sep) if not question_dialog( self.gui, _('Library removed'), _( 'The library %s has been removed from calibre. ' 'The files remain on your computer, if you want ' 'to delete them, you will have to do so manually.') % ('<code>%s</code>' % loc), override_icon='dialog_information.png', yes_text=_('&OK'), no_text=_('&Undo'), yes_icon='ok.png', no_icon='edit-undo.png'): return self.remove_library_icon(name) self.stats.remove(location) self.gui.library_broker.remove_library(location) self.build_menus() self.gui.iactions['Copy To Library'].build_menus() if os.path.exists(loc): open_local_file(loc) def backup_status(self, location): self.__backup_status_dialog = d = BackupStatus(self.gui) d.show() def mark_dirty(self): db = self.gui.library_view.model().db db.dirtied(list(db.data.iterallids())) info_dialog(self.gui, _('Backup metadata'), _('Metadata will be backed up while calibre is running, at the ' 'rate of approximately 1 book every three seconds.'), show=True) def restore_database(self): LibraryDatabase = db_class() m = self.gui.library_view.model() db = m.db if (iswindows and len(db.library_path) > LibraryDatabase.WINDOWS_LIBRARY_PATH_LIMIT): return error_dialog(self.gui, _('Too long'), _('Path to library too long. It must be less than' ' %d characters. Move your library to a location with' ' a shorter path using Windows Explorer, then point' ' calibre to the new location and try again.')% LibraryDatabase.WINDOWS_LIBRARY_PATH_LIMIT, show=True) from calibre.gui2.dialogs.restore_library import restore_database m = self.gui.library_view.model() m.stop_metadata_backup() db = m.db db.prefs.disable_setting = True if restore_database(db, self.gui): self.gui.library_moved(db.library_path) def check_library(self): from calibre.gui2.dialogs.check_library import CheckLibraryDialog, DBCheck self.gui.library_view.save_state() m = self.gui.library_view.model() m.stop_metadata_backup() db = m.db db.prefs.disable_setting = True library_path = db.library_path before = db.new_api.size_stats() d = DBCheck(self.gui, db) try: d.exec() try: m.close() except Exception: pass finally: d.break_cycles() self.gui.library_moved(library_path) if d.rejected: return if d.error is None: after = self.gui.current_db.new_api.size_stats() det_msg = '' from calibre import human_readable for which, title in {'main': _('books'), 'fts': _('full text search'), 'notes': _('notes')}.items(): if which != 'main' and not getattr(d, which).isChecked(): continue det_msg += '\n' if before[which] == after[which]: det_msg += _('Size of the {} database was unchanged.').format(title) else: det_msg += _('Size of the {0} database reduced from {1} to {2}.').format( title, human_readable(before[which]), human_readable(after[which])) if not question_dialog(self.gui, _('Success'), _('Found no errors in your calibre library database.' ' Do you want calibre to check if the files in your' ' library match the information in the database?'), det_msg=det_msg.strip()): return else: return error_dialog(self.gui, _('Failed'), _('Database integrity check failed, click "Show details"' ' for details.'), show=True, det_msg=d.error[1]) self.gui.status_bar.show_message( _('Starting library scan, this may take a while')) try: QCoreApplication.processEvents() d = CheckLibraryDialog(self.gui, m.db) if not d.do_exec(): if question_dialog(self.gui, _('No problems found'), _('The files in your library match the information in the database.\n\n' "Choose 'Open dialog' to change settings and run the check again."), yes_text=_('Open dialog'), yes_icon='gear.png', no_icon='ok.png', no_text=_('Finished')): d.exec() finally: self.gui.status_bar.clear_message() def look_for_portable_lib(self, db, location): base = get_portable_base() if base is None: return False, None loc = location.replace('/', os.sep) candidate = os.path.join(base, os.path.basename(loc)) if db.exists_at(candidate): newloc = candidate.replace(os.sep, '/') self.stats.rename(location, newloc) return True, newloc return False, None def switch_requested(self, location): if not self.change_library_allowed(): return db = self.gui.library_view.model().db current_lib = self.stats.canonicalize_path(db.library_path) self.view_state_map[current_lib] = self.preserve_state_on_switch.state loc = location.replace('/', os.sep) exists = db.exists_at(loc) if not exists: exists, new_location = self.look_for_portable_lib(db, location) if exists: location = new_location loc = location.replace('/', os.sep) if not exists: d = MovedDialog(self.stats, location, self.gui) ret = d.exec() self.build_menus() self.gui.iactions['Copy To Library'].build_menus() if ret == QDialog.DialogCode.Accepted: loc = d.newloc.replace('/', os.sep) else: return # from calibre.utils.mem import memory # import weakref # from qt.core import QTimer # self.dbref = weakref.ref(self.gui.library_view.model().db) # self.before_mem = memory() self.gui.library_moved(loc, allow_rebuild=True) # QTimer.singleShot(5000, self.debug_leak) def debug_leak(self): import gc from calibre.utils.mem import memory ref = self.dbref for i in range(3): gc.collect() if ref() is not None: print('DB object alive:', ref()) for r in gc.get_referrers(ref())[:10]: print(r) print() print('before:', self.before_mem) print('after:', memory()) print() self.dbref = self.before_mem = None def count_changed(self, new_count): self.update_tooltip(new_count) def choose_library(self, *args): if not self.change_library_allowed(): return from calibre.gui2.dialogs.choose_library import ChooseLibrary self.gui.library_view.save_state() db = self.gui.library_view.model().db location = self.stats.canonicalize_path(db.library_path) self.pre_choose_dialog_location = location c = ChooseLibrary(db, self.choose_library_callback, self.gui) c.exec() def choose_library_callback(self, newloc, copy_structure=False, library_renamed=False): self.gui.library_moved(newloc, copy_structure=copy_structure, allow_rebuild=True) if library_renamed: self.stats.rename(self.pre_choose_dialog_location, prefs['library_path']) self.build_menus() self.gui.iactions['Copy To Library'].build_menus() def change_library_allowed(self): if os.environ.get('CALIBRE_OVERRIDE_DATABASE_PATH', None): warning_dialog(self.gui, _('Not allowed'), _('You cannot change libraries while using the environment' ' variable CALIBRE_OVERRIDE_DATABASE_PATH.'), show=True) return False if self.gui.job_manager.has_jobs(): warning_dialog(self.gui, _('Not allowed'), _('You cannot change libraries while jobs' ' are running.'), show=True) return False if self.gui.proceed_question.questions: warning_dialog(self.gui, _('Not allowed'), _('You cannot change libraries until all' ' updates are accepted or rejected.'), show=True) return False return True
33,994
Python
.py
739
34.845737
132
0.592871
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,906
help.py
kovidgoyal_calibre/src/calibre/gui2/actions/help.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from qt.core import QUrl from calibre.gui2 import open_url from calibre.gui2.actions import InterfaceAction from calibre.utils.localization import localize_user_manual_link class HelpAction(InterfaceAction): name = 'Help' action_spec = (_('Help'), 'help.png', _('Browse the calibre User Manual'), _('F1'),) def genesis(self): self.qaction.triggered.connect(self.show_help) def show_help(self, *args): open_url(QUrl(localize_user_manual_link('https://manual.calibre-ebook.com')))
664
Python
.py
15
40.533333
88
0.71875
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,907
add_to_library.py
kovidgoyal_calibre/src/calibre/gui2/actions/add_to_library.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from calibre.gui2.actions import InterfaceAction class AddToLibraryAction(InterfaceAction): name = 'Add To Library' action_spec = (_('Add books to library'), 'add_book.png', _('Add books to your calibre library from the connected device'), ()) dont_add_to = frozenset(('menubar', 'toolbar', 'context-menu', 'toolbar-child')) action_type = 'current' def genesis(self): self.qaction.triggered.connect(self.add_books_to_library) def location_selected(self, loc): enabled = loc != 'library' self.qaction.setEnabled(enabled) self.menuless_qaction.setEnabled(enabled) def add_books_to_library(self, *args): self.gui.iactions['Add Books'].add_books_from_device( self.gui.current_view())
941
Python
.py
21
38.238095
84
0.666301
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,908
saved_searches.py
kovidgoyal_calibre/src/calibre/gui2/actions/saved_searches.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2022, Charles Haley # from qt.core import QMenu, QToolButton from calibre.gui2.actions import InterfaceAction, show_menu_under_widget class SavedSearchesAction(InterfaceAction): name = 'Saved searches' action_spec = (_('Saved searches'), 'folder_saved_search.png', _('Show a menu of saved searches'), None) action_type = 'current' popup_type = QToolButton.ToolButtonPopupMode.InstantPopup action_add_menu = True dont_add_to = frozenset(('context-menu-device', 'menubar-device')) def genesis(self): self.menu = m = self.qaction.menu() m.aboutToShow.connect(self.about_to_show_menu) # Create a "hidden" menu that can have a shortcut. self.hidden_menu = QMenu() self.shortcut_action = self.create_menu_action( menu=self.hidden_menu, unique_name='Saved searches', text=_('Show a menu of saved searches'), icon='folder_saved_search.png', triggered=self.show_menu) # We want to show the menu when a shortcut is used. Apparently the only way # to do that is to scan the toolbar(s) for the action button then exec the # associated menu. The search is done here to take adding and removing the # action from toolbars into account. # # If a shortcut is triggered and there isn't a toolbar button visible then # show the menu in the upper left corner of the library view pane. Yes, this # is a bit weird but it works as well as a popping up a dialog. def show_menu(self): show_menu_under_widget(self.gui, self.menu, self.qaction, self.name) def about_to_show_menu(self): self.gui.populate_add_saved_search_menu(to_menu=self.menu) def location_selected(self, loc): enabled = loc == 'library' self.qaction.setEnabled(enabled) for action in self.menu.actions(): action.setEnabled(enabled)
2,038
Python
.py
41
41.073171
80
0.660292
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,909
mark_books.py
kovidgoyal_calibre/src/calibre/gui2/actions/mark_books.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' from functools import partial from qt.core import QApplication, QDialog, QDialogButtonBox, QEvent, QGridLayout, QIcon, QLabel, QMenu, QPushButton, Qt from calibre.gui2 import error_dialog from calibre.gui2.actions import InterfaceActionWithLibraryDrop from calibre.gui2.widgets2 import HistoryComboBox from calibre.startup import connect_lambda from calibre.utils.icu import sort_key class MyHistoryComboBox(HistoryComboBox): # This is here so we can change the following two class variables without # affecting other users of the HistoryComboBox class max_history_items = 10 min_history_entry_length = 1 class MarkWithTextDialog(QDialog): def __init__(self, gui): QDialog.__init__(self, parent=gui) self.gui = gui self.setWindowTitle(_('Mark books with text label')) layout = QGridLayout() layout.setColumnStretch(1, 10) self.setLayout(layout) self.text_box = textbox = MyHistoryComboBox() textbox.initialize('mark_with_text') history = textbox.all_items button_rows = min(4, len(history)-1) for i in range(0, button_rows): if i == 0: layout.addWidget(QLabel(_('Recently used values:')), 0, 0, 1, 2) button = QPushButton() text = history[i+1] button.setText(text) button.clicked.connect(partial(self.button_pushed, text=text)) row = i + 1 layout.addWidget(button, row, 1) label = QLabel('&' + str(row+1)) label.setBuddy(button) layout.addWidget(label, row, 0) if button_rows > 0: layout.addWidget(QLabel(_('Enter a value:')), button_rows+1, 0, 1, 2) textbox.show_initial_value(history[0] if history else '') layout.addWidget(textbox, button_rows+2, 1) textbox.setFocus() button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) button_box.accepted.connect(self.accept) button_box.rejected.connect(self.reject) layout.addWidget(button_box, button_rows+3, 0, 1, 2) def text(self): return self.text_box.text().strip() def button_pushed(self, checked, text=''): self.text_box.setText(text) self.text_box.save_history() self.accept() def accept(self): if not self.text_box.text().strip(): d = error_dialog(self.gui, _('Value cannot be empty'), _('You must provide a value')) d.exec_() else: super().accept() mark_books_with_text = None class MarkBooksAction(InterfaceActionWithLibraryDrop): name = 'Mark Books' action_spec = (_('Mark books'), 'marked.png', _('Temporarily mark books for easy access'), 'Ctrl+M') action_type = 'current' action_add_menu = True dont_add_to = frozenset([ 'context-menu-device', 'menubar-device', 'context-menu-cover-browser']) action_menu_clone_qaction = _('Toggle mark for selected books') def do_drop(self): book_ids = self.dropped_ids del self.dropped_ids if book_ids: self.toggle_ids(book_ids) def genesis(self): self.search_icon = QIcon.ic('search.png') self.qaction.triggered.connect(self.toggle_selected) self.menu = m = self.qaction.menu() m.aboutToShow.connect(self.about_to_show_menu) ma = partial(self.create_menu_action, m) self.show_marked_action = a = ma('mark_selected', _('Mark all selected books'), icon='marked.png') a.triggered.connect(self.mark_all_selected) self.show_marked_action = a = ma('mark_with_text', _('Mark books with text label'), icon='marked.png') a.triggered.connect(partial(self.mark_with_text, book_ids=None)) global mark_books_with_text mark_books_with_text = self.mark_with_text self.show_marked_action = a = ma('show-marked', _('Show marked books'), icon='search.png', shortcut='Shift+Ctrl+M') a.triggered.connect(self.show_marked) self.show_marked_with_text = QMenu(_('Show marked books with text label')) self.show_marked_with_text.setIcon(self.search_icon) m.addMenu(self.show_marked_with_text) self.clear_selected_marked_action = a = ma('clear-marks-on-selected', _('Clear marks for selected books'), icon='clear_left.png') a.triggered.connect(self.clear_marks_on_selected_books) self.clear_marked_action = a = ma('clear-all-marked', _('Clear all marked books'), icon='clear_left.png') a.triggered.connect(self.clear_all_marked) m.addSeparator() self.mark_author_action = a = ma('mark-author', _('Mark all books by selected author(s)'), icon='plus.png') connect_lambda(a.triggered, self, lambda self: self.mark_field('authors', True)) self.mark_series_action = a = ma('mark-series', _('Mark all books in the selected series'), icon='plus.png') connect_lambda(a.triggered, self, lambda self: self.mark_field('series', True)) m.addSeparator() self.unmark_author_action = a = ma('unmark-author', _('Clear all books by selected author(s)'), icon='minus.png') connect_lambda(a.triggered, self, lambda self: self.mark_field('authors', False)) self.unmark_series_action = a = ma('unmark-series', _('Clear all books in the selected series'), icon='minus.png') connect_lambda(a.triggered, self, lambda self: self.mark_field('series', False)) def gui_layout_complete(self): for x in self.gui.bars_manager.bars: try: w = x.widgetForAction(self.qaction) w.installEventFilter(self) except: continue def eventFilter(self, obj, ev): if ev.type() == QEvent.Type.MouseButtonPress and ev.button() == Qt.MouseButton.LeftButton: mods = QApplication.keyboardModifiers() if mods & Qt.KeyboardModifier.ControlModifier or mods & Qt.KeyboardModifier.ShiftModifier: self.show_marked() return True return False def about_to_show_menu(self): db = self.gui.current_db marked_ids = db.data.marked_ids num = len(frozenset(marked_ids).intersection(db.new_api.all_book_ids())) text = _('Show marked book') if num == 1 else (_('Show marked books') + (' (%d)' % num)) self.show_marked_action.setText(text) counts = dict() for v in marked_ids.values(): counts[v] = counts.get(v, 0) + 1 labels = sorted(counts.keys(), key=sort_key) self.show_marked_with_text.clear() if len(labels): labs = labels[0:40] self.show_marked_with_text.setEnabled(True) for t in labs: ac = self.show_marked_with_text.addAction(self.search_icon, f'{t} ({counts[t]})') ac.triggered.connect(partial(self.show_marked_text, txt=t)) if len(labs) < len(labels): self.show_marked_with_text.addAction( _('{0} labels not shown').format(len(labels) - len(labs))) else: self.show_marked_with_text.setEnabled(False) def location_selected(self, loc): enabled = loc == 'library' self.qaction.setEnabled(enabled) self.menuless_qaction.setEnabled(enabled) for action in self.menu.actions(): action.setEnabled(enabled) def toggle_selected(self): book_ids = self._get_selected_ids() if book_ids: self.toggle_ids(book_ids) def _get_selected_ids(self): rows = self.gui.library_view.selectionModel().selectedRows() if not rows or len(rows) == 0: d = error_dialog(self.gui, _('Cannot mark'), _('No books selected')) d.exec() return set() return set(map(self.gui.library_view.model().id, rows)) def toggle_ids(self, book_ids): self.gui.current_db.data.toggle_marked_ids(book_ids) def add_ids(self, book_ids): self.gui.current_db.data.add_marked_ids(book_ids) def show_marked(self): self.gui.search.set_search_string('marked:true') def show_marked_text(self, txt=None): self.gui.search.set_search_string(f'marked:"={txt}"') def clear_all_marked(self): self.gui.current_db.data.set_marked_ids(()) if str(self.gui.search.text()).startswith('marked:'): self.gui.search.set_search_string('') def mark_field(self, field, add): book_ids = self._get_selected_ids() if not book_ids: return db = self.gui.current_db items = set() for book_id in book_ids: items |= set(db.new_api.field_ids_for(field, book_id)) book_ids = set() for item_id in items: book_ids |= db.new_api.books_for_field(field, item_id) mids = db.data.marked_ids.copy() for book_id in book_ids: if add: mids[book_id] = True else: mids.pop(book_id, None) db.data.set_marked_ids(mids) def mark_all_selected(self): book_ids = self._get_selected_ids() if not book_ids: return self.gui.current_db.data.add_marked_ids(book_ids) def mark_with_text(self, book_ids=None): if book_ids is None: book_ids = self._get_selected_ids() if not book_ids: return dialog = MarkWithTextDialog(self.gui) if dialog.exec_() != QDialog.DialogCode.Accepted: return txt = dialog.text() txt = txt if txt else 'true' db = self.gui.current_db mids = db.data.marked_ids.copy() for book_id in book_ids: mids[book_id] = txt db.data.set_marked_ids(mids) def clear_marks_on_selected_books(self): book_ids = self._get_selected_ids() if not book_ids: return db = self.gui.current_db items = db.data.marked_ids.copy() for book_id in book_ids: items.pop(book_id, None) self.gui.current_db.data.set_marked_ids(items)
10,324
Python
.py
218
37.885321
137
0.62171
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,910
manage_categories.py
kovidgoyal_calibre/src/calibre/gui2/actions/manage_categories.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2022, Charles Haley # from qt.core import QMenu, QToolButton from calibre.gui2.actions import InterfaceAction, show_menu_under_widget class ManageCategoriesAction(InterfaceAction): name = 'Manage categories' action_spec = (_('Manage categories'), 'tags.png', _('Manage categories: authors, tags, series, etc.'), None) action_type = 'current' popup_type = QToolButton.ToolButtonPopupMode.InstantPopup action_add_menu = True dont_add_to = frozenset(['context-menu-device', 'menubar-device']) def genesis(self): self.menu = m = self.qaction.menu() m.aboutToShow.connect(self.about_to_show_menu) # Create a "hidden" menu that can have a shortcut. self.hidden_menu = QMenu() self.shortcut_action = self.create_menu_action( menu=self.hidden_menu, unique_name='Manage categories', text=_('Manage categories: authors, tags, series, etc.'), icon='tags.png', triggered=self.show_menu) # We want to show the menu when a shortcut is used. Apparently the only way # to do that is to scan the toolbar(s) for the action button then exec the # associated menu. The search is done here to take adding and removing the # action from toolbars into account. # # If a shortcut is triggered and there isn't a toolbar button visible then # show the menu in the upper left corner of the library view pane. Yes, this # is a bit weird but it works as well as a popping up a dialog. def show_menu(self): show_menu_under_widget(self.gui, self.menu, self.qaction, self.name) def about_to_show_menu(self): db = self.gui.current_db self.gui.populate_manage_categories_menu(db, self.menu, add_column_items=True) def location_selected(self, loc): enabled = loc == 'library' self.qaction.setEnabled(enabled) for action in self.menu.actions(): action.setEnabled(enabled)
2,107
Python
.py
42
41.52381
86
0.659854
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,911
toc_edit.py
kovidgoyal_calibre/src/calibre/gui2/actions/toc_edit.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os from collections import OrderedDict from itertools import count from qt.core import QCheckBox, QDialog, QDialogButtonBox, QGridLayout, QIcon, QLabel, QTimer from calibre.gui2 import error_dialog, gprefs, question_dialog from calibre.gui2.actions import InterfaceActionWithLibraryDrop from calibre.startup import connect_lambda from calibre.utils.monotonic import monotonic from polyglot.builtins import iteritems SUPPORTED = {'EPUB', 'AZW3'} class ChooseFormat(QDialog): # {{{ def __init__(self, formats, parent=None): QDialog.__init__(self, parent) self.setWindowTitle(_('Choose format to edit')) self.setWindowIcon(QIcon.ic('dialog_question.png')) l = self.l = QGridLayout() self.setLayout(l) la = self.la = QLabel(_('Choose which format you want to edit:')) formats = sorted(formats) l.addWidget(la, 0, 0, 1, -1) self.buttons = [] for i, f in enumerate(formats): b = QCheckBox('&' + f, self) l.addWidget(b, 1, i) self.buttons.append(b) self.formats = gprefs.get('edit_toc_last_selected_formats', ['EPUB',]) bb = self.bb = QDialogButtonBox( QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel) bb.addButton(_('&All formats'), QDialogButtonBox.ButtonRole.ActionRole).clicked.connect(self.do_all) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) l.addWidget(bb, l.rowCount(), 0, 1, -1) self.resize(self.sizeHint()) connect_lambda(self.finished, self, lambda self, code:gprefs.set('edit_toc_last_selected_formats', list(self.formats))) def do_all(self): for b in self.buttons: b.setChecked(True) self.accept() @property def formats(self): for b in self.buttons: if b.isChecked(): yield str(b.text())[1:] @formats.setter def formats(self, formats): formats = {x.upper() for x in formats} for b in self.buttons: b.setChecked(b.text()[1:] in formats) # }}} class ToCEditAction(InterfaceActionWithLibraryDrop): name = 'Edit ToC' action_spec = (_('Edit ToC'), 'toc.png', _('Edit the Table of Contents in your books'), _('K')) dont_add_to = frozenset(['context-menu-device']) action_type = 'current' def do_drop(self): book_id_map = self.get_supported_books(self.dropped_ids) del self.dropped_ids if book_id_map: self.do_edit(book_id_map) def genesis(self): self.shm_count = count() self.qaction.triggered.connect(self.edit_books) self.jobs = [] def get_supported_books(self, book_ids): db = self.gui.library_view.model().db supported = set(SUPPORTED) ans = [(x, set((db.formats(x, index_is_id=True) or '').split(',')) .intersection(supported)) for x in book_ids] ans = [x for x in ans if x[1]] if not ans: error_dialog(self.gui, _('Cannot edit ToC'), _('Editing Table of Contents is only supported for books in the %s' ' formats. Convert to one of those formats before editing.') %_(' or ').join(sorted(supported)), show=True) ans = OrderedDict(ans) if len(ans) > 5: if not question_dialog(self.gui, _('Are you sure?'), _( 'You have chosen to edit the Table of Contents of {} books at once.' ' Doing so will likely slow your computer to a crawl. Are you sure?' ).format(len(ans))): return return ans def get_books_for_editing(self): rows = [r.row() for r in self.gui.library_view.selectionModel().selectedRows()] if not rows or len(rows) == 0: d = error_dialog(self.gui, _('Cannot edit ToC'), _('No books selected')) d.exec() return None db = self.gui.current_db ans = (db.id(r) for r in rows) return self.get_supported_books(ans) def do_edit(self, book_id_map): for book_id, fmts in iteritems(book_id_map): if len(fmts) > 1: d = ChooseFormat(fmts, self.gui) if d.exec() != QDialog.DialogCode.Accepted: return fmts = d.formats for fmt in fmts: self.do_one(book_id, fmt) def do_one(self, book_id, fmt): import atexit import json import struct from calibre.utils.shm import SharedMemory db = self.gui.current_db path = db.format(book_id, fmt, index_is_id=True, as_path=True) title = db.title(book_id, index_is_id=True) + ' [%s]'%fmt job = {'path': path, 'title': title} data = json.dumps(job).encode('utf-8') header = struct.pack('>II', 0, 0) shm = SharedMemory(prefix=f'c{os.getpid()}-{next(self.shm_count)}-', size=len(data) + len(header) + SharedMemory.num_bytes_for_size) shm.write(header) shm.write_data_with_size(data) shm.flush() atexit.register(shm.close) self.gui.job_manager.launch_gui_app('toc-dialog', kwargs={'shm_name': shm.name}) job.update({ 'book_id': book_id, 'fmt': fmt, 'library_id': db.new_api.library_id, 'shm': shm, 'started': False, 'start_time': monotonic()}) self.jobs.append(job) self.check_for_completions() def check_for_completions(self): import struct def remove_job(job): job['shm'].close() self.jobs.remove(job) for job in tuple(self.jobs): path = job['path'] shm = job['shm'] shm.seek(0) state, ok = struct.unpack('>II', shm.read(struct.calcsize('>II'))) if state == 0: # not started if monotonic() - job['start_time'] > 120: remove_job(job) error_dialog(self.gui, _('Failed to start editor'), _( 'Could not edit: {}. The Table of Contents editor did not start in two minutes').format(job['title']), show=True) elif state == 1: # running pass elif state == 2: # finished job['shm'].already_unlinked = True remove_job(job) if ok == 1: db = self.gui.current_db if db.new_api.library_id != job['library_id']: error_dialog(self.gui, _('Library changed'), _( 'Cannot save changes made to {0} by the ToC editor as' ' the calibre library has changed.').format(job['title']), show=True) else: db.new_api.add_format(job['book_id'], job['fmt'], path, run_hooks=False) if self.jobs: QTimer.singleShot(100, self.check_for_completions) def edit_books(self): book_id_map = self.get_books_for_editing() if not book_id_map: return self.do_edit(book_id_map)
7,405
Python
.py
167
33.51497
140
0.571488
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,912
annotate.py
kovidgoyal_calibre/src/calibre/gui2/actions/annotate.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from qt.core import QModelIndex, Qt, QThread, pyqtSignal from calibre.devices.usbms.device import Device from calibre.gui2 import error_dialog from calibre.gui2.actions import InterfaceAction from calibre.gui2.dialogs.progress import ProgressDialog from polyglot.builtins import iteritems class Updater(QThread): # {{{ update_progress = pyqtSignal(int) update_done = pyqtSignal() def __init__(self, parent, db, device, annotation_map, done_callback): QThread.__init__(self, parent) self.errors = {} self.db = db self.keep_going = True self.pd = ProgressDialog(_('Merging user annotations into database'), '', 0, len(annotation_map), parent=parent) self.device = device self.annotation_map = annotation_map self.done_callback = done_callback self.pd.canceled_signal.connect(self.canceled) self.pd.setModal(True) self.pd.show() self.update_progress.connect(self.pd.set_value, type=Qt.ConnectionType.QueuedConnection) self.update_done.connect(self.pd.hide, type=Qt.ConnectionType.QueuedConnection) def canceled(self): self.keep_going = False self.pd.hide() def run(self): for i, id_ in enumerate(self.annotation_map): if not self.keep_going: break bm = Device.UserAnnotation(self.annotation_map[id_][0], self.annotation_map[id_][1]) try: self.device.add_annotation_to_library(self.db, id_, bm) except: import traceback self.errors[id_] = traceback.format_exc() self.update_progress.emit(i) self.update_done.emit() self.done_callback(list(self.annotation_map.keys()), self.errors) # }}} class FetchAnnotationsAction(InterfaceAction): name = 'Fetch Annotations' action_spec = (_('Fetch annotations (experimental)'), None, None, ()) dont_add_to = frozenset(('menubar', 'toolbar', 'context-menu', 'toolbar-child')) action_type = 'current' def genesis(self): self.qaction.triggered.connect(self.fetch_annotations) def fetch_annotations(self, *args): # Generate a path_map from selected ids def get_ids_from_selected_rows(): rows = self.gui.library_view.selectionModel().selectedRows() if not rows or len(rows) < 2: rows = range(self.gui.library_view.model().rowCount(QModelIndex())) ids = list(map(self.gui.library_view.model().id, rows)) return ids def get_formats(id): formats = db.formats(id, index_is_id=True) fmts = [] if formats: for format in formats.split(','): fmts.append(format.lower()) return fmts def get_device_path_from_id(id_): paths = [] for x in ('memory', 'card_a', 'card_b'): x = getattr(self.gui, x+'_view').model() paths += x.paths_for_db_ids({id_}, as_map=True)[id_] return paths[0].path if paths else None def generate_annotation_paths(ids, db, device): # Generate path templates # Individual storage mount points scanned/resolved in driver.get_annotations() path_map = {} for id in ids: path = get_device_path_from_id(id) mi = db.get_metadata(id, index_is_id=True) a_path = device.create_annotations_path(mi, device_path=path) path_map[id] = dict(path=a_path, fmts=get_formats(id)) return path_map device = self.gui.device_manager.device if not getattr(device, 'SUPPORTS_ANNOTATIONS', False): return error_dialog(self.gui, _('Not supported'), _('Fetching annotations is not supported for this device'), show=True) if self.gui.current_view() is not self.gui.library_view: return error_dialog(self.gui, _('Use library only'), _('User annotations generated from main library only'), show=True) db = self.gui.library_view.model().db # Get the list of ids ids = get_ids_from_selected_rows() if not ids: return error_dialog(self.gui, _('No books selected'), _('No books selected to fetch annotations from'), show=True) # Map ids to paths path_map = generate_annotation_paths(ids, db, device) # Dispatch to devices.kindle.driver.get_annotations() self.gui.device_manager.annotations(self.Dispatcher(self.annotations_fetched), path_map) def annotations_fetched(self, job): if not job.result: return if self.gui.current_view() is not self.gui.library_view: return error_dialog(self.gui, _('Use library only'), _('User annotations generated from main library only'), show=True) db = self.gui.library_view.model().db device = self.gui.device_manager.device self.__annotation_updater = Updater(self.gui, db, device, job.result, self.Dispatcher(self.annotations_updated)) self.__annotation_updater.start() def annotations_updated(self, ids, errors): self.gui.library_view.model().refresh_ids(ids) if errors: db = self.gui.library_view.model().db entries = [] for id_, tb in iteritems(errors): title = id_ if isinstance(id_, int): title = db.title(id_, index_is_id=True) entries.extend([title, tb, '']) error_dialog(self.gui, _('Some errors'), _('Could not fetch annotations for some books. Click ' '"Show details" to see which ones.'), det_msg='\n'.join(entries), show=True)
6,203
Python
.py
132
35.575758
90
0.593046
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,913
save_to_disk.py
kovidgoyal_calibre/src/calibre/gui2/actions/save_to_disk.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import numbers import os from functools import partial from calibre.gui2 import Dispatcher, choose_dir, error_dialog from calibre.gui2.actions import InterfaceAction from calibre.utils.config import prefs from polyglot.builtins import itervalues class SaveToDiskAction(InterfaceAction): name = "Save To Disk" action_spec = (_('Save to disk'), 'save.png', _('Export e-book files from the calibre library'), _('S')) action_type = 'current' action_add_menu = True action_menu_clone_qaction = True def genesis(self): self.qaction.triggered.connect(self.save_to_disk) self.save_menu = self.qaction.menu() cm = partial(self.create_menu_action, self.save_menu) cm('single dir', _('Save to disk in a single folder'), triggered=partial(self.save_to_single_dir, False)) cm('single format', _('Save only %s format to disk')% prefs['output_format'].upper(), triggered=partial(self.save_single_format_to_disk, False)) cm('single dir and format', _('Save only %s format to disk in a single folder')% prefs['output_format'].upper(), triggered=partial(self.save_single_fmt_to_single_dir, False)) cm('specific format', _('Save single format to disk...'), triggered=self.save_specific_format_disk) def location_selected(self, loc): enabled = loc == 'library' for action in list(self.save_menu.actions())[1:]: action.setEnabled(enabled) def reread_prefs(self): self.save_menu.actions()[2].setText( _('Save only %s format to disk')% prefs['output_format'].upper()) self.save_menu.actions()[3].setText( _('Save only %s format to disk in a single folder')% prefs['output_format'].upper()) def save_single_format_to_disk(self, checked): self.save_to_disk(checked, False, prefs['output_format']) def save_specific_format_disk(self): rb = self.gui.iactions['Remove Books'] ids = rb._get_selected_ids(err_title=_('Cannot save to disk')) if not ids: return fmts = rb._get_selected_formats( _('Choose format to save to disk'), ids, single=True) if not fmts: return self.save_to_disk(False, False, list(fmts)[0]) def save_to_single_dir(self, checked): self.save_to_disk(checked, True) def save_single_fmt_to_single_dir(self, *args): self.save_to_disk(False, single_dir=True, single_format=prefs['output_format']) def save_to_disk(self, checked, single_dir=False, single_format=None, rows=None, write_opf=None, save_cover=None): if rows is None: rows = self.gui.current_view().selectionModel().selectedRows() if not rows or len(rows) == 0: return error_dialog(self.gui, _('Cannot save to disk'), _('No books selected'), show=True) path = choose_dir(self.gui, 'save to disk dialog', _('Choose destination folder')) if not path: return dpath = os.path.abspath(path).replace('/', os.sep)+os.sep lpath = self.gui.library_view.model().db.library_path.replace('/', os.sep)+os.sep if dpath.startswith(lpath): return error_dialog(self.gui, _('Not allowed'), _('You are trying to save files into the calibre ' 'library. This can cause corruption of your ' 'library. Save to disk is meant to export ' 'files from your calibre library elsewhere.'), show=True) if self.gui.current_view() is self.gui.library_view: from calibre.gui2.save import Saver from calibre.library.save_to_disk import config opts = config().parse() if single_format is not None: opts.formats = single_format # Special case for Kindle annotation files if single_format.lower() in ['mbp','pdr','tan']: opts.to_lowercase = False opts.save_cover = False opts.write_opf = False opts.template = opts.send_template opts.single_dir = single_dir if write_opf is not None: opts.write_opf = write_opf if save_cover is not None: opts.save_cover = save_cover book_ids = set(map(self.gui.library_view.model().id, rows)) Saver(book_ids, self.gui.current_db, opts, path, parent=self.gui, pool=self.gui.spare_pool()) else: paths = self.gui.current_view().model().paths(rows) self.gui.device_manager.save_books( Dispatcher(self.books_saved), paths, path) def save_library_format_by_ids(self, book_ids, fmt, single_dir=True): if isinstance(book_ids, numbers.Integral): book_ids = [book_ids] rows = list(itervalues(self.gui.library_view.ids_to_rows(book_ids))) rows = [self.gui.library_view.model().index(r, 0) for r in rows] self.save_to_disk(True, single_dir=single_dir, single_format=fmt, rows=rows, write_opf=False, save_cover=False) def books_saved(self, job): if job.failed: return self.gui.device_job_exception(job)
5,641
Python
.py
115
37.93913
105
0.598402
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,914
polish.py
kovidgoyal_calibre/src/calibre/gui2/actions/polish.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os import shutil import textwrap import weakref from collections import OrderedDict from functools import partial from qt.core import ( QApplication, QCheckBox, QDialog, QDialogButtonBox, QFrame, QGridLayout, QIcon, QInputDialog, QLabel, QMenu, QModelIndex, QSize, QSizePolicy, QSpacerItem, Qt, QTextEdit, QTimer, ) from calibre.gui2 import Dispatcher, error_dialog, gprefs, question_dialog from calibre.gui2.actions import InterfaceActionWithLibraryDrop from calibre.gui2.convert.metadata import create_opf_file from calibre.gui2.dialogs.progress import ProgressDialog from calibre.ptempfile import PersistentTemporaryDirectory from calibre.startup import connect_lambda from calibre.utils.config_base import tweaks from calibre.utils.localization import ngettext from polyglot.builtins import iteritems, itervalues class Polish(QDialog): # {{{ def __init__(self, db, book_id_map, parent=None): from calibre.ebooks.oeb.polish.main import HELP QDialog.__init__(self, parent) self.db, self.book_id_map = weakref.ref(db), book_id_map self.setWindowIcon(QIcon.ic('polish.png')) title = _('Polish book') if len(book_id_map) > 1: title = _('Polish %d books')%len(book_id_map) self.setWindowTitle(title) self.help_text = { 'polish': _('<h3>About Polishing books</h3>%s')%HELP['about'].format( _('''<p>If you have both EPUB and ORIGINAL_EPUB in your book, then polishing will run on ORIGINAL_EPUB (the same for other ORIGINAL_* formats). So if you want Polishing to not run on the ORIGINAL_* format, delete the ORIGINAL_* format before running it.</p>''') ), 'embed':_('<h3>Embed referenced fonts</h3>%s')%HELP['embed'], 'subset':_('<h3>Subsetting fonts</h3>%s')%HELP['subset'], 'smarten_punctuation': _('<h3>Smarten punctuation</h3>%s')%HELP['smarten_punctuation'], 'metadata':_('<h3>Updating metadata</h3>' '<p>This will update all metadata <i>except</i> the cover in the' ' e-book files to match the current metadata in the' ' calibre library.</p>' ' <p>Note that most e-book' ' formats are not capable of supporting all the' ' metadata in calibre.</p><p>There is a separate option to' ' update the cover.</p>'), 'do_cover': _('<h3>Update cover</h3><p>Update the covers in the e-book files to match the' ' current cover in the calibre library.</p>' '<p>If the e-book file does not have' ' an identifiable cover, a new cover is inserted.</p>' ), 'jacket':_('<h3>Book jacket</h3>%s')%HELP['jacket'], 'remove_jacket':_('<h3>Remove book jacket</h3>%s')%HELP['remove_jacket'], 'remove_unused_css':_('<h3>Remove unused CSS rules</h3>%s')%HELP['remove_unused_css'], 'compress_images': _('<h3>Losslessly compress images</h3>%s') % HELP['compress_images'], 'download_external_resources': _('<h3>Download external resources</h3>%s') % HELP['download_external_resources'], 'add_soft_hyphens': _('<h3>Add soft-hyphens</h3>%s') % HELP['add_soft_hyphens'], 'remove_soft_hyphens': _('<h3>Remove soft-hyphens</h3>%s') % HELP['remove_soft_hyphens'], 'upgrade_book': _('<h3>Upgrade book internals</h3>%s') % HELP['upgrade_book'], } self.l = l = QGridLayout() self.setLayout(l) self.la = la = QLabel('<b>'+_('Select actions to perform:')) l.addWidget(la, 0, 0, 1, 2) count = 0 self.all_actions = OrderedDict([ ('embed', _('&Embed all referenced fonts')), ('subset', _('&Subset all embedded fonts')), ('smarten_punctuation', _('Smarten &punctuation')), ('metadata', _('Update &metadata in the book files')), ('do_cover', _('Update the &cover in the book files')), ('jacket', _('Add/replace metadata as a "book &jacket" page')), ('remove_jacket', _('&Remove a previously inserted book jacket')), ('remove_unused_css', _('Remove &unused CSS rules from the book')), ('compress_images', _('Losslessly &compress images')), ('download_external_resources', _('&Download external resources')), ('add_soft_hyphens', _('Add s&oft hyphens')), ('remove_soft_hyphens', _('Remove so&ft hyphens')), ('upgrade_book', _('&Upgrade book internals')), ]) prefs = gprefs.get('polishing_settings', {}) for name, text in iteritems(self.all_actions): count += 1 x = QCheckBox(text, self) x.setChecked(prefs.get(name, False)) x.setObjectName(name) connect_lambda(x.stateChanged, self, lambda self, state: self.option_toggled(self.sender().objectName(), state)) l.addWidget(x, count, 0, 1, 1) setattr(self, 'opt_'+name, x) la = QLabel(' <a href="#%s">%s</a>'%(name, _('About'))) setattr(self, 'label_'+name, x) la.linkActivated.connect(self.help_link_activated) l.addWidget(la, count, 1, 1, 1) count += 1 l.addItem(QSpacerItem(10, 10, vPolicy=QSizePolicy.Policy.Expanding), count, 1, 1, 2) la = self.help_label = QLabel('') self.help_link_activated('#polish') la.setWordWrap(True) la.setTextFormat(Qt.TextFormat.RichText) la.setFrameShape(QFrame.Shape.StyledPanel) la.setAlignment(Qt.AlignmentFlag.AlignLeft|Qt.AlignmentFlag.AlignTop) la.setLineWidth(2) la.setStyleSheet('QLabel { margin-left: 75px }') l.addWidget(la, 0, 2, count+1, 1) l.setColumnStretch(2, 1) self.show_reports = sr = QCheckBox(_('Show &report'), self) sr.setChecked(gprefs.get('polish_show_reports', True)) sr.setToolTip(textwrap.fill(_('Show a report of all the actions performed' ' after polishing is completed'))) l.addWidget(sr, count+1, 0, 1, 1) self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) self.save_button = sb = bb.addButton(_('&Save settings'), QDialogButtonBox.ButtonRole.ActionRole) sb.clicked.connect(self.save_settings) self.load_button = lb = bb.addButton(_('&Load settings'), QDialogButtonBox.ButtonRole.ActionRole) self.load_menu = QMenu(lb) lb.setMenu(self.load_menu) self.all_button = b = bb.addButton(_('Select &all'), QDialogButtonBox.ButtonRole.ActionRole) connect_lambda(b.clicked, self, lambda self: self.select_all(True)) self.none_button = b = bb.addButton(_('Select &none'), QDialogButtonBox.ButtonRole.ActionRole) connect_lambda(b.clicked, self, lambda self: self.select_all(False)) l.addWidget(bb, count+1, 1, 1, -1) self.setup_load_button() self.resize(self.sizeHint()) def sizeHint(self): sz = super().sizeHint() return QSize(max(950, sz.width()), max(600, sz.height())) def select_all(self, enable): for action in self.all_actions: x = getattr(self, 'opt_'+action) x.blockSignals(True) x.setChecked(enable) x.blockSignals(False) def save_settings(self): if not self.something_selected: return error_dialog(self, _('No actions selected'), _('You must select at least one action before saving'), show=True) name, ok = QInputDialog.getText(self, _('Choose name'), _('Choose a name for these settings')) if ok: name = str(name).strip() if name: settings = {ac:getattr(self, 'opt_'+ac).isChecked() for ac in self.all_actions} saved = gprefs.get('polish_settings', {}) saved[name] = settings gprefs.set('polish_settings', saved) self.setup_load_button() def setup_load_button(self): saved = gprefs.get('polish_settings', {}) m = self.load_menu m.clear() self.__actions = [] a = self.__actions.append for name in sorted(saved): a(m.addAction(name, partial(self.load_settings, name))) m.addSeparator() a(m.addAction(_('Remove saved settings'), self.clear_settings)) self.load_button.setEnabled(bool(saved)) def clear_settings(self): gprefs.set('polish_settings', {}) self.setup_load_button() def load_settings(self, name): saved = gprefs.get('polish_settings', {}).get(name, {}) for action in self.all_actions: checked = saved.get(action, False) x = getattr(self, 'opt_'+action) x.blockSignals(True) x.setChecked(checked) x.blockSignals(False) def option_toggled(self, name, state): if state == Qt.CheckState.Checked: self.help_label.setText(self.help_text[name]) def help_link_activated(self, link): link = str(link)[1:] self.help_label.setText(self.help_text[link]) @property def something_selected(self): for action in self.all_actions: if getattr(self, 'opt_'+action).isChecked(): return True return False def accept(self): self.actions = ac = {} saved_prefs = {} gprefs['polish_show_reports'] = bool(self.show_reports.isChecked()) something = False for action in self.all_actions: ac[action] = saved_prefs[action] = bool(getattr(self, 'opt_'+action).isChecked()) if ac[action]: something = True if ac['jacket'] and not ac['metadata']: if not question_dialog(self, _('Must update metadata'), _('You have selected the option to add metadata as ' 'a "book jacket". For this option to work, you ' 'must also select the option to update metadata in' ' the book files. Do you want to select it?')): return ac['metadata'] = saved_prefs['metadata'] = True self.opt_metadata.setChecked(True) if ac['jacket'] and ac['remove_jacket']: if not question_dialog(self, _('Add or remove jacket?'), _( 'You have chosen to both add and remove the metadata jacket.' ' This will result in the final book having no jacket. Is this' ' what you want?')): return if not something: return error_dialog(self, _('No actions selected'), _('You must select at least one action, or click Cancel.'), show=True) gprefs['polishing_settings'] = saved_prefs self.queue_files() return super().accept() def queue_files(self): self.tdir = PersistentTemporaryDirectory('_queue_polish') self.jobs = [] if len(self.book_id_map) <= 5: for i, (book_id, formats) in enumerate(iteritems(self.book_id_map)): self.do_book(i+1, book_id, formats) else: self.queue = [(i+1, id_) for i, id_ in enumerate(self.book_id_map)] self.pd = ProgressDialog(_('Queueing books for polishing'), max=len(self.queue), parent=self) QTimer.singleShot(0, self.do_one) self.pd.exec() def do_one(self): if not self.queue: self.pd.accept() return if self.pd.canceled: self.jobs = [] self.pd.reject() return num, book_id = self.queue.pop(0) try: self.do_book(num, book_id, self.book_id_map[book_id]) except: self.pd.reject() raise else: self.pd.set_value(num) QTimer.singleShot(0, self.do_one) def do_book(self, num, book_id, formats): base = os.path.join(self.tdir, str(book_id)) os.mkdir(base) db = self.db() opf = os.path.join(base, 'metadata.opf') with open(opf, 'wb') as opf_file: mi = create_opf_file(db, book_id, opf_file=opf_file)[0] data = {'opf':opf, 'files':[]} for action in self.actions: data[action] = bool(getattr(self, 'opt_'+action).isChecked()) cover = os.path.join(base, 'cover.jpg') if db.copy_cover_to(book_id, cover, index_is_id=True): data['cover'] = cover is_orig = {} for fmt in formats: ext = fmt.replace('ORIGINAL_', '').lower() is_orig[ext.upper()] = 'ORIGINAL_' in fmt with open(os.path.join(base, '%s.%s'%(book_id, ext)), 'wb') as f: db.copy_format_to(book_id, fmt, f, index_is_id=True) data['files'].append(f.name) nums = num if hasattr(self, 'pd'): nums = self.pd.max - num desc = ngettext(_('Polish %s')%mi.title, _('Polish book %(nums)s of %(tot)s (%(title)s)')%dict( nums=nums, tot=len(self.book_id_map), title=mi.title), len(self.book_id_map)) if hasattr(self, 'pd'): self.pd.set_msg(_('Queueing book %(nums)s of %(tot)s (%(title)s)')%dict( nums=num, tot=len(self.book_id_map), title=mi.title)) self.jobs.append((desc, data, book_id, base, is_orig)) # }}} class Report(QDialog): # {{{ def __init__(self, parent): QDialog.__init__(self, parent) self.gui = parent self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False) self.setWindowIcon(QIcon.ic('polish.png')) self.reports = [] self.l = l = QGridLayout() self.setLayout(l) self.view = v = QTextEdit(self) v.setReadOnly(True) l.addWidget(self.view, 0, 0, 1, 2) self.backup_msg = la = QLabel('') l.addWidget(la, 1, 0, 1, 2) la.setVisible(False) la.setWordWrap(True) self.ign = QCheckBox(_('Ignore remaining reports'), self) l.addWidget(self.ign, 2, 0) bb = self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) b = self.log_button = bb.addButton(_('View full &log'), QDialogButtonBox.ButtonRole.ActionRole) b.clicked.connect(self.view_log) bb.button(QDialogButtonBox.StandardButton.Close).setDefault(True) l.addWidget(bb, 2, 1) self.finished.connect(self.show_next, type=Qt.ConnectionType.QueuedConnection) self.resize(QSize(800, 600)) def setup_ign(self): self.ign.setText(ngettext( 'Ignore remaining report', 'Ignore remaining {} reports', len(self.reports)).format(len(self.reports))) self.ign.setVisible(bool(self.reports)) self.ign.setChecked(False) def __call__(self, *args): self.reports.append(args) self.setup_ign() if not self.isVisible(): self.show_next() def show_report(self, book_title, book_id, fmts, job, report): from calibre.ebooks.markdown import markdown self.current_log = job.details self.setWindowTitle(_('Polishing of %s')%book_title) self.view.setText(markdown('# %s\n\n'%book_title + report, output_format='html4')) self.bb.button(QDialogButtonBox.StandardButton.Close).setFocus(Qt.FocusReason.OtherFocusReason) self.backup_msg.setVisible(bool(fmts)) if fmts: m = ngettext('The original file has been saved as %s.', 'The original files have been saved as %s.', len(fmts))%( _(' and ').join('ORIGINAL_'+f for f in fmts) ) self.backup_msg.setText(m + ' ' + _( 'If you polish again, the polishing will run on the originals.')%( )) def view_log(self): self.view.setPlainText(self.current_log) self.view.verticalScrollBar().setValue(0) def show_next(self, *args): if not self.reports: return if not self.isVisible(): self.show() self.show_report(*self.reports.pop(0)) self.setup_ign() def accept(self): if self.ign.isChecked(): self.reports = [] if self.reports: self.show_next() return super().accept() def reject(self): if self.ign.isChecked(): self.reports = [] if self.reports: self.show_next() return super().reject() # }}} class PolishAction(InterfaceActionWithLibraryDrop): name = 'Polish Books' action_spec = (_('Polish books'), 'polish.png', _('Apply the shine of perfection to your books'), _('P')) dont_add_to = frozenset(['context-menu-device']) action_type = 'current' def do_drop(self): book_id_map = self.get_supported_books(self.dropped_ids) del self.dropped_ids if book_id_map: self.do_polish(book_id_map) def genesis(self): self.qaction.triggered.connect(self.polish_books) self.report = Report(self.gui) self.to_be_refreshed = set() self.refresh_debounce_timer = t = QTimer(self.gui) t.setSingleShot(True) t.setInterval(1000) t.timeout.connect(self.refresh_after_polish) def shutting_down(self): self.refresh_debounce_timer.stop() def location_selected(self, loc): enabled = loc == 'library' self.qaction.setEnabled(enabled) self.menuless_qaction.setEnabled(enabled) def get_books_for_polishing(self): rows = [r.row() for r in self.gui.library_view.selectionModel().selectedRows()] if not rows or len(rows) == 0: d = error_dialog(self.gui, _('Cannot polish'), _('No books selected')) d.exec() return None db = self.gui.library_view.model().db ans = (db.id(r) for r in rows) ans = self.get_supported_books(ans) for fmts in itervalues(ans): for x in fmts: if x.startswith('ORIGINAL_'): from calibre.gui2.dialogs.confirm_delete import confirm if not confirm(_( 'One of the books you are polishing has an {0} format.' ' Polishing will use this as the source and overwrite' ' any existing {1} format. Are you sure you want to proceed?').format( x, x[len('ORIGINAL_'):]), 'confirm_original_polish', title=_('Are you sure?'), confirm_msg=_('Ask for this confirmation again')): return {} break return ans def get_supported_books(self, book_ids): from calibre.ebooks.oeb.polish.main import SUPPORTED db = self.gui.library_view.model().db supported = set(SUPPORTED) for x in SUPPORTED: supported.add('ORIGINAL_'+x) ans = [(x, set((db.formats(x, index_is_id=True) or '').split(',')) .intersection(supported)) for x in book_ids] ans = [x for x in ans if x[1]] if not ans: error_dialog(self.gui, _('Cannot polish'), _('Polishing is only supported for books in the %s' ' formats. Convert to one of those formats before polishing.') %_(' or ').join(sorted(SUPPORTED)), show=True) ans = OrderedDict(ans) for fmts in itervalues(ans): for x in SUPPORTED: if ('ORIGINAL_'+x) in fmts: fmts.discard(x) return ans def polish_books(self): book_id_map = self.get_books_for_polishing() if not book_id_map: return self.do_polish(book_id_map) def do_polish(self, book_id_map): d = Polish(self.gui.library_view.model().db, book_id_map, parent=self.gui) if d.exec() == QDialog.DialogCode.Accepted and d.jobs: show_reports = bool(d.show_reports.isChecked()) for desc, data, book_id, base, is_orig in reversed(d.jobs): job = self.gui.job_manager.run_job( Dispatcher(self.book_polished), 'gui_polish', args=(data,), description=desc) job.polish_args = (book_id, base, data['files'], show_reports, is_orig) if d.jobs: self.gui.jobs_pointer.start() self.gui.status_bar.show_message( ngettext('Start polishing the book', 'Start polishing of {} books', len(d.jobs)).format(len(d.jobs)), 2000) def book_polished(self, job): if job.failed: self.gui.job_exception(job) return db = self.gui.current_db book_id, base, files, show_reports, is_orig = job.polish_args fmts = set() for path in files: fmt = path.rpartition('.')[-1].upper() if tweaks['save_original_format_when_polishing'] and not is_orig[fmt]: fmts.add(fmt) db.save_original_format(book_id, fmt, notify=False) with open(path, 'rb') as f: db.add_format(book_id, fmt, f, index_is_id=True) self.gui.status_bar.show_message(job.description + _(' completed'), 2000) try: shutil.rmtree(base) parent = os.path.dirname(base) os.rmdir(parent) except: pass self.to_be_refreshed.add(book_id) self.refresh_debounce_timer.start() if show_reports: self.report(db.title(book_id, index_is_id=True), book_id, fmts, job, job.result) def refresh_after_polish(self): self.refresh_debounce_timer.stop() book_ids = tuple(self.to_be_refreshed) self.to_be_refreshed = set() if self.gui.current_view() is self.gui.library_view: self.gui.library_view.model().refresh_ids(book_ids) current = self.gui.library_view.currentIndex() if current.isValid(): self.gui.library_view.model().current_changed(current, QModelIndex()) self.gui.tags_view.recount() if __name__ == '__main__': app = QApplication([]) app from calibre.library import db d = Polish(db(), {1:{'EPUB'}, 2:{'AZW3'}}) d.exec()
23,372
Python
.py
505
34.942574
125
0.573502
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,915
show_stored_templates.py
kovidgoyal_calibre/src/calibre/gui2/actions/show_stored_templates.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2020, Charles Haley from calibre.gui2.actions import InterfaceAction from calibre.gui2.preferences.main import Preferences class ShowTemplateFunctionsAction(InterfaceAction): name = 'Template Functions' action_spec = (_('Template functions'), 'debug.png', None, ()) dont_add_to = frozenset(('context-menu-device',)) action_type = 'current' def genesis(self): self.previous_text = _('Manage template functions') self.first_time = True self.qaction.triggered.connect(self.show_template_editor) def show_template_editor(self, *args): d = Preferences(self.gui, initial_plugin=('Advanced', 'TemplateFunctions'), close_after_initial=True) d.exec()
778
Python
.py
17
39.705882
83
0.704636
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,916
tweak_epub.py
kovidgoyal_calibre/src/calibre/gui2/actions/tweak_epub.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import time from qt.core import QCheckBox, QDialog, QDialogButtonBox, QLabel, Qt, QVBoxLayout from calibre.gui2 import error_dialog, question_dialog from calibre.gui2.actions import InterfaceActionWithLibraryDrop from calibre.startup import connect_lambda class Choose(QDialog): def __init__(self, title, fmts, parent=None): QDialog.__init__(self, parent) self.l = l = QVBoxLayout(self) self.setLayout(l) self.setWindowTitle(_('Choose format to edit')) self.la = la = QLabel(_( 'The book "{}" has multiple formats that can be edited. Choose the format you want to edit.').format(title)) l.addWidget(la) self.rem = QCheckBox(_('Always ask when more than one format is available')) self.rem.setChecked(True) l.addWidget(self.rem) self.bb = bb = QDialogButtonBox(self) l.addWidget(bb) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) self.buts = buts = [] for fmt in fmts: b = bb.addButton(fmt.upper(), QDialogButtonBox.ButtonRole.AcceptRole) b.setObjectName(fmt) connect_lambda(b.clicked, self, lambda self: self.chosen(self.sender().objectName())) buts.append(b) self.fmt = None self.resize(self.sizeHint()) def chosen(self, fmt): self.fmt = fmt def accept(self): from calibre.gui2.tweak_book import tprefs tprefs['choose_tweak_fmt'] = self.rem.isChecked() QDialog.accept(self) class TweakEpubAction(InterfaceActionWithLibraryDrop): name = 'Tweak ePub' action_spec = (_('Edit book'), 'edit_book.png', _('Edit books in the EPUB or AZW formats'), _('T')) dont_add_to = frozenset(('context-menu-device',)) action_type = 'current' def do_drop(self): book_ids = self.dropped_ids del self.dropped_ids if book_ids: self.do_tweak(book_ids[0]) def genesis(self): self.qaction.triggered.connect(self.tweak_book) def tweak_book(self): ids = self.gui.library_view.get_selected_ids() if not ids: return error_dialog(self.gui, _('Cannot Edit book'), _('No book selected'), show=True) if len(ids) > 10 and not question_dialog(self.gui, _('Are you sure?'), _( 'You are trying to edit {} books at once. Are you sure?').format(len(ids))): return for book_id in ids: self.do_tweak(book_id) def do_tweak(self, book_id): if self.gui.current_view() is not self.gui.library_view: return error_dialog(self.gui, _('Cannot edit book'), _( 'Editing of books on the device is not supported'), show=True) from calibre.ebooks.oeb.polish.main import SUPPORTED db = self.gui.library_view.model().db fmts = db.formats(book_id, index_is_id=True) or '' fmts = [x.upper().strip() for x in fmts.split(',') if x] tweakable_fmts = set(fmts).intersection(SUPPORTED) title = db.new_api.field_for('title', book_id) if not tweakable_fmts: if not fmts: if not question_dialog(self.gui, _('No editable formats'), _('Do you want to create an empty EPUB file in the book "{}" to edit?').format(title)): return tweakable_fmts = {'EPUB'} self.gui.iactions['Add Books'].add_empty_format_to_book(book_id, 'EPUB') current_idx = self.gui.library_view.currentIndex() if current_idx.isValid(): self.gui.library_view.model().current_changed(current_idx, current_idx) else: return error_dialog(self.gui, _('Cannot edit book'), _( 'The book "{0}" must be in the {1} formats to edit.' '\n\nFirst convert the book to one of these formats.' ).format(title, _(' or ').join(SUPPORTED)), show=True) from calibre.gui2.tweak_book import tprefs tprefs.refresh() # In case they were changed in a Tweak Book process if len(tweakable_fmts) > 1: if tprefs['choose_tweak_fmt']: d = Choose(title, sorted(tweakable_fmts, key=tprefs.defaults['tweak_fmt_order'].index), self.gui) if d.exec() != QDialog.DialogCode.Accepted: return tweakable_fmts = {d.fmt} else: fmts = [f for f in tprefs['tweak_fmt_order'] if f in tweakable_fmts] if not fmts: fmts = [f for f in tprefs.defaults['tweak_fmt_order'] if f in tweakable_fmts] tweakable_fmts = {fmts[0]} fmt = tuple(tweakable_fmts)[0] self.ebook_edit_format(book_id, fmt) def ebook_edit_format(self, book_id, fmt): ''' Also called from edit_metadata formats list. In that context, SUPPORTED check was already done. ''' db = self.gui.library_view.model().db from calibre.gui2.tweak_book import tprefs tprefs.refresh() # In case they were changed in a Tweak Book process path = db.new_api.format_abspath(book_id, fmt) if path is None: return error_dialog(self.gui, _('File missing'), _( 'The %s format is missing from the calibre library. You should run' ' library maintenance.') % fmt, show=True) try: self.gui.setCursor(Qt.CursorShape.BusyCursor) if tprefs['update_metadata_from_calibre']: db.new_api.embed_metadata((book_id,), only_fmts={fmt}) notify = '%d:%s:%s:%s' % (book_id, fmt, db.library_id, db.library_path) self.gui.job_manager.launch_gui_app('ebook-edit', kwargs=dict(path=path, notify=notify)) time.sleep(2) finally: self.gui.unsetCursor()
6,081
Python
.py
123
38.715447
120
0.600101
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,917
embed.py
kovidgoyal_calibre/src/calibre/gui2/actions/embed.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' from functools import partial from qt.core import QProgressDialog, Qt, QTimer from calibre import force_unicode from calibre.gui2 import gprefs from calibre.gui2.actions import InterfaceActionWithLibraryDrop from calibre.utils.localization import ngettext class EmbedAction(InterfaceActionWithLibraryDrop): name = 'Embed Metadata' action_spec = (_('Embed metadata'), 'modified.png', _('Embed metadata into book files'), None) action_type = 'current' action_add_menu = True action_menu_clone_qaction = _('Embed metadata into book files') def do_drop(self): book_ids = self.dropped_ids del self.dropped_ids if book_ids: self.do_embed(book_ids) def genesis(self): self.qaction.triggered.connect(self.embed) self.embed_menu = self.qaction.menu() m = partial(self.create_menu_action, self.embed_menu) m('embed-specific', _('Embed metadata into files of a specific format from selected books...'), triggered=self.embed_selected_formats) self.qaction.setMenu(self.embed_menu) self.pd_timer = t = QTimer() t.timeout.connect(self.do_one) def embed(self): rb = self.gui.iactions['Remove Books'] ids = rb._get_selected_ids(err_title=_('Cannot embed')) if not ids: return self.do_embed(ids) def embed_selected_formats(self): rb = self.gui.iactions['Remove Books'] ids = rb._get_selected_ids(err_title=_('Cannot embed')) if not ids: return fmts = rb._get_selected_formats( _('Choose formats to be updated'), ids) if not fmts: return self.do_embed(ids, fmts) def do_embed(self, book_ids, only_fmts=None): pd = QProgressDialog(_('Embedding updated metadata into book files...'), _('&Stop'), 0, len(book_ids), self.gui) pd.setWindowTitle(_('Embedding metadata...')) pd.setWindowModality(Qt.WindowModality.WindowModal) errors = [] self.job_data = (0, tuple(book_ids), pd, only_fmts, errors) self.pd_timer.start() def do_one(self): try: i, book_ids, pd, only_fmts, errors = self.job_data except (TypeError, AttributeError): return if i >= len(book_ids) or pd.wasCanceled(): pd.setValue(pd.maximum()) pd.hide() self.pd_timer.stop() self.job_data = None self.gui.library_view.model().refresh_ids(book_ids) if i > 0: self.gui.status_bar.show_message(ngettext( 'Embedded metadata in one book', 'Embedded metadata in {} books', i).format(i), 5000) if errors: det_msg = '\n\n'.join([_('The {0} format of {1}:\n\n{2}\n').format( (fmt or '').upper(), force_unicode(mi.title), force_unicode(tb)) for mi, fmt, tb in errors]) from calibre.gui2.dialogs.message_box import MessageBox title, msg = _('Failed for some files'), _( 'Failed to embed metadata into some book files. Click "Show details" for details.') d = MessageBox(MessageBox.WARNING, _('WARNING:')+ ' ' + title, msg, det_msg, parent=self.gui, show_copy_button=True) tc = d.toggle_checkbox tc.setVisible(True), tc.setText(_('Show the &failed books in the main book list')) tc.setChecked(gprefs.get('show-embed-failed-books', False)) d.resize_needed.emit() d.exec() gprefs['show-embed-failed-books'] = tc.isChecked() if tc.isChecked(): failed_ids = {mi.book_id for mi, fmt, tb in errors} db = self.gui.current_db db.data.set_marked_ids(failed_ids) self.gui.search.set_search_string('marked:true') return pd.setValue(i) db = self.gui.current_db.new_api book_id = book_ids[i] def report_error(mi, fmt, tb): mi.book_id = book_id errors.append((mi, fmt, tb)) try: db.embed_metadata((book_id,), only_fmts=only_fmts, report_error=report_error) except Exception: import traceback mi = db.get_metadata(book_id) report_error(mi, '', traceback.format_exc()) self.job_data = (i + 1, book_ids, pd, only_fmts, errors)
4,605
Python
.py
99
35.787879
132
0.590292
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,918
sort.py
kovidgoyal_calibre/src/calibre/gui2/actions/sort.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' from contextlib import suppress from functools import partial from qt.core import ( QAbstractItemView, QAction, QDialog, QDialogButtonBox, QIcon, QListWidget, QListWidgetItem, QMenu, QSize, Qt, QToolButton, QVBoxLayout, pyqtSignal, ) from calibre.gui2.actions import InterfaceAction, show_menu_under_widget from calibre.library.field_metadata import category_icon_map from calibre.utils.icu import primary_sort_key from polyglot.builtins import iteritems SORT_HIDDEN_PREF = 'sort-action-hidden-fields' class SortAction(QAction): sort_requested = pyqtSignal(object, object) def __init__(self, text, key, ascending, parent): QAction.__init__(self, text, parent) self.key, self.ascending = key, ascending self.triggered.connect(self) ic = category_icon_map['custom:'] if self.key.startswith('#') else category_icon_map.get(key) if ic: self.setIcon(QIcon.ic(ic)) def __call__(self): self.sort_requested.emit(self.key, self.ascending) class SortByAction(InterfaceAction): name = 'Sort By' action_spec = (_('Sort by'), 'sort.png', _('Sort the list of books'), None) action_type = 'current' popup_type = QToolButton.ToolButtonPopupMode.InstantPopup action_add_menu = True dont_add_to = frozenset(('context-menu-cover-browser', )) def genesis(self): self.sorted_icon = QIcon.ic('ok.png') self.menu = m = self.qaction.menu() m.aboutToShow.connect(self.about_to_show_menu) # self.qaction.triggered.connect(self.show_menu) # Create a "hidden" menu that can have a shortcut. This also lets us # manually show the menu instead of letting Qt do it to work around a # problem where Qt can show the menu on the wrong screen. self.hidden_menu = QMenu() self.shortcut_action = self.create_menu_action( menu=self.hidden_menu, unique_name=_('Sort by'), text=_('Show the Sort by menu'), icon=None, shortcut='Ctrl+F5', triggered=self.show_menu) def c(attr, title, tooltip, callback, keys=()): ac = self.create_action(spec=(title, None, tooltip, keys), attr=attr) ac.triggered.connect(callback) self.gui.addAction(ac) return ac self.reverse_action = c('reverse_sort_action', _('Reverse current sort'), _('Reverse the current sort order'), self.reverse_sort, 'shift+f5') self.reapply_action = c('reapply_sort_action', _('Re-apply current sort'), _('Re-apply the current sort'), self.reapply_sort, 'f5') def about_to_show_menu(self): self.update_menu() def show_menu(self): show_menu_under_widget(self.gui, self.qaction.menu(), self.qaction, self.name) def reverse_sort(self): self.gui.current_view().reverse_sort() def reapply_sort(self): self.gui.current_view().resort() def location_selected(self, loc): enabled = loc == 'library' self.qaction.setEnabled(enabled) self.menuless_qaction.setEnabled(enabled) def library_changed(self, db): self.update_menu() def initialization_complete(self): self.update_menu() def update_menu(self, menu=None): menu = menu or self.qaction.menu() for action in menu.actions(): if hasattr(action, 'sort_requested'): action.sort_requested.disconnect() with suppress(TypeError): action.toggled.disconnect() menu.clear() m = self.gui.library_view.model() db = self.gui.current_db # Use these actions so we get the shortcut(s) displayed menu.addAction(self.reapply_action) menu.addAction(self.reverse_action) menu.addSeparator() # Add saved sorts to the menu saved_sorts = db.new_api.pref('saved_multisort_specs', {}) if saved_sorts: for name in sorted(saved_sorts.keys(), key=primary_sort_key): menu.addAction(name, partial(self.named_sort_selected, saved_sorts[name])) menu.addSeparator() # Note the current sort column so it can be specially handled below try: sort_col = m.sorted_on[0] except TypeError: sort_col = 'date' # The operations to choose which columns to display and to create saved sorts menu.addAction(_('Select sortable columns')).triggered.connect(self.select_sortable_columns) menu.addAction(_('Sort on multiple columns'), self.choose_multisort) menu.addSeparator() # Add the columns to the menu fm = db.field_metadata name_map = {v:k for k, v in iteritems(fm.ui_sortable_field_keys())} all_names = sorted(name_map, key=primary_sort_key) hidden = frozenset(db.new_api.pref(SORT_HIDDEN_PREF, default=()) or ()) for name in all_names: key = name_map[name] if key == 'ondevice' and self.gui.device_connected is None: continue if key in hidden: continue sac = SortAction(name, key, None, menu) if key == sort_col: sac.setIcon(self.sorted_icon) sac.sort_requested.connect(self.sort_requested) menu.addAction(sac) def select_sortable_columns(self): db = self.gui.current_db fm = db.field_metadata name_map = {v:k for k, v in iteritems(fm.ui_sortable_field_keys())} hidden = frozenset(db.new_api.pref(SORT_HIDDEN_PREF, default=()) or ()) all_names = sorted(name_map, key=primary_sort_key) items = QListWidget() items.setSelectionMode(QAbstractItemView.SelectionMode.MultiSelection) for display_name in all_names: key = name_map[display_name] i = QListWidgetItem(display_name, items) i.setData(Qt.ItemDataRole.UserRole, key) i.setSelected(key not in hidden) d = QDialog(self.gui) l = QVBoxLayout(d) l.addWidget(items) d.setWindowTitle(_('Select sortable columns')) d.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) d.bb.accepted.connect(d.accept) d.bb.rejected.connect(d.reject) l.addWidget(d.bb) d.resize(d.sizeHint() + QSize(50, 100)) if d.exec() == QDialog.DialogCode.Accepted: hidden = [] for i in (items.item(x) for x in range(items.count())): if not i.isSelected(): hidden.append(i.data(Qt.ItemDataRole.UserRole)) db.new_api.set_pref(SORT_HIDDEN_PREF, tuple(hidden)) self.update_menu() def named_sort_selected(self, sort_spec): self.gui.library_view.multisort(sort_spec) def choose_multisort(self): from calibre.gui2.dialogs.multisort import ChooseMultiSort d = ChooseMultiSort(self.gui.current_db, parent=self.gui, is_device_connected=self.gui.device_connected) if d.exec() == QDialog.DialogCode.Accepted: self.gui.library_view.multisort(d.current_sort_spec) self.update_menu() def sort_requested(self, key, ascending): if ascending is None: self.gui.library_view.intelligent_sort(key, True) else: self.gui.library_view.sort_by_named_field(key, ascending)
7,731
Python
.py
171
35.479532
112
0.627409
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,919
plugin_updates.py
kovidgoyal_calibre/src/calibre/gui2/actions/plugin_updates.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2011, Grant Drake <grant.drake@gmail.com>' __docformat__ = 'restructuredtext en' from qt.core import QApplication, QIcon, Qt from calibre.gui2.actions import InterfaceAction from calibre.gui2.dialogs.plugin_updater import FILTER_ALL, FILTER_UPDATE_AVAILABLE, PluginUpdaterDialog class PluginUpdaterAction(InterfaceAction): name = 'Plugin Updater' action_spec = (_('Plugin updater'), None, _('Update any plugins you have installed in calibre'), ()) action_type = 'current' def genesis(self): self.qaction.setIcon(QIcon.ic('plugins/plugin_updater.png')) self.qaction.triggered.connect(self.check_for_plugin_updates) def check_for_plugin_updates(self): # Get the user to choose a plugin to install initial_filter = FILTER_UPDATE_AVAILABLE mods = QApplication.keyboardModifiers() if mods & Qt.KeyboardModifier.ControlModifier or mods & Qt.KeyboardModifier.ShiftModifier: initial_filter = FILTER_ALL d = PluginUpdaterDialog(self.gui, initial_filter=initial_filter) d.exec() if d.do_restart: self.gui.quit(restart=True)
1,204
Python
.py
24
43.916667
104
0.715385
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,920
convert.py
kovidgoyal_calibre/src/calibre/gui2/actions/convert.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os from functools import partial from qt.core import QModelIndex from calibre.customize.ui import plugin_for_input_format, run_plugins_on_postconvert from calibre.gui2 import Dispatcher, error_dialog, gprefs from calibre.gui2.actions import InterfaceActionWithLibraryDrop from calibre.gui2.tools import convert_bulk_ebook, convert_single_ebook from calibre.utils.config import prefs, tweaks from calibre.utils.localization import ngettext class ConvertAction(InterfaceActionWithLibraryDrop): name = 'Convert Books' action_spec = (_('Convert books'), 'convert.png', _('Convert books between different e-book formats'), _('C')) dont_add_to = frozenset(('context-menu-device',)) action_type = 'current' action_add_menu = True def do_drop(self): book_ids = self.dropped_ids del self.dropped_ids self.do_convert(book_ids) def genesis(self): m = self.convert_menu = self.qaction.menu() cm = partial(self.create_menu_action, self.convert_menu) cm('convert-individual', _('Convert individually'), icon=self.qaction.icon(), triggered=partial(self.convert_ebook, False, bulk=False)) cm('convert-bulk', _('Bulk convert'), triggered=partial(self.convert_ebook, False, bulk=True)) m.addSeparator() cm('create-catalog', _('Create a catalog of the books in your calibre library'), icon='catalog.png', shortcut=False, triggered=self.gui.iactions['Generate Catalog'].generate_catalog) self.qaction.triggered.connect(self.convert_ebook) self.conversion_jobs = {} def location_selected(self, loc): enabled = loc == 'library' self.qaction.setEnabled(enabled) self.menuless_qaction.setEnabled(enabled) for action in list(self.convert_menu.actions()): action.setEnabled(enabled) def auto_convert(self, book_ids, on_card, format): previous = self.gui.library_view.currentIndex() rows = [x.row() for x in self.gui.library_view.selectionModel().selectedRows()] jobs, changed, bad = convert_single_ebook(self.gui, self.gui.library_view.model().db, book_ids, True, format) if jobs == []: return self.queue_convert_jobs(jobs, changed, bad, rows, previous, self.book_auto_converted, extra_job_args=[on_card]) def auto_convert_auto_add(self, book_ids): previous = self.gui.library_view.currentIndex() db = self.gui.current_db needed = set() of = prefs['output_format'].lower() for book_id in book_ids: fmts = db.formats(book_id, index_is_id=True) fmts = {x.lower() for x in fmts.split(',')} if fmts else set() if gprefs['auto_convert_same_fmt'] or of not in fmts: needed.add(book_id) if needed: jobs, changed, bad = convert_single_ebook(self.gui, self.gui.library_view.model().db, needed, True, of, show_no_format_warning=False) if not jobs: return self.queue_convert_jobs(jobs, changed, bad, list(needed), previous, self.book_converted, rows_are_ids=True) def auto_convert_mail(self, to, fmts, delete_from_library, book_ids, format, subject): previous = self.gui.library_view.currentIndex() rows = [x.row() for x in self.gui.library_view.selectionModel().selectedRows()] jobs, changed, bad = convert_single_ebook(self.gui, self.gui.library_view.model().db, book_ids, True, format) if jobs == []: return self.queue_convert_jobs(jobs, changed, bad, rows, previous, self.book_auto_converted_mail, extra_job_args=[delete_from_library, to, fmts, subject]) def auto_convert_multiple_mail(self, book_ids, data, ofmt, delete_from_library): previous = self.gui.library_view.currentIndex() rows = [x.row() for x in self.gui.library_view.selectionModel().selectedRows()] jobs, changed, bad = convert_single_ebook(self.gui, self.gui.library_view.model().db, book_ids, True, ofmt) if jobs == []: return self.queue_convert_jobs(jobs, changed, bad, rows, previous, self.book_auto_converted_multiple_mail, extra_job_args=[delete_from_library, data]) def auto_convert_news(self, book_ids, format): previous = self.gui.library_view.currentIndex() rows = [x.row() for x in self.gui.library_view.selectionModel().selectedRows()] jobs, changed, bad = convert_single_ebook(self.gui, self.gui.library_view.model().db, book_ids, True, format) if jobs == []: return self.queue_convert_jobs(jobs, changed, bad, rows, previous, self.book_auto_converted_news) def auto_convert_catalogs(self, book_ids, format): previous = self.gui.library_view.currentIndex() rows = [x.row() for x in self.gui.library_view.selectionModel().selectedRows()] jobs, changed, bad = convert_single_ebook(self.gui, self.gui.library_view.model().db, book_ids, True, format) if jobs == []: return self.queue_convert_jobs(jobs, changed, bad, rows, previous, self.book_auto_converted_catalogs) def get_books_for_conversion(self): rows = [r.row() for r in self.gui.library_view.selectionModel().selectedRows()] if not rows or len(rows) == 0: d = error_dialog(self.gui, _('Cannot convert'), _('No books selected')) d.exec() return None return [self.gui.library_view.model().db.id(r) for r in rows] def convert_ebook(self, checked, bulk=None): book_ids = self.get_books_for_conversion() if book_ids is None: return self.do_convert(book_ids, bulk=bulk) def convert_ebooks_to_format(self, book_ids, to_fmt): from calibre.customize.ui import available_output_formats to_fmt = to_fmt.upper() if to_fmt.lower() not in available_output_formats(): return error_dialog(self.gui, _('Cannot convert'), _( 'Conversion to the {} format is not supported').format(to_fmt), show=True) self.do_convert(book_ids, output_fmt=to_fmt, auto_conversion=True) def do_convert(self, book_ids, bulk=None, auto_conversion=False, output_fmt=None): previous = self.gui.library_view.currentIndex() rows = [x.row() for x in self.gui.library_view.selectionModel().selectedRows()] num = 0 if bulk or (bulk is None and len(book_ids) > 1): self.__bulk_queue = convert_bulk_ebook(self.gui, self.queue_convert_jobs, self.gui.library_view.model().db, book_ids, out_format=output_fmt or prefs['output_format'], args=(rows, previous, self.book_converted)) if self.__bulk_queue is None: return num = len(self.__bulk_queue.book_ids) else: jobs, changed, bad = convert_single_ebook(self.gui, self.gui.library_view.model().db, book_ids, out_format=output_fmt or prefs['output_format'], auto_conversion=auto_conversion) self.queue_convert_jobs(jobs, changed, bad, rows, previous, self.book_converted) num = len(jobs) if num > 0: self.gui.jobs_pointer.start() self.gui.status_bar.show_message(ngettext( 'Starting conversion of the book', 'Starting conversion of {} books', num).format(num), 2000) def queue_convert_jobs(self, jobs, changed, bad, rows, previous, converted_func, extra_job_args=[], rows_are_ids=False): for func, args, desc, fmt, id, temp_files in jobs: func, _, parts = func.partition(':') parts = {x for x in parts.split(';')} input_file = args[0] input_fmt = os.path.splitext(input_file)[1] core_usage = 1 if input_fmt: input_fmt = input_fmt[1:] plugin = plugin_for_input_format(input_fmt) if plugin is not None: core_usage = plugin.core_usage if id not in bad: job = self.gui.job_manager.run_job(Dispatcher(converted_func), func, args=args, description=desc, core_usage=core_usage) job.conversion_of_same_fmt = 'same_fmt' in parts job.manually_fine_tune_toc = 'manually_fine_tune_toc' in parts args = [temp_files, fmt, id]+extra_job_args self.conversion_jobs[job] = tuple(args) if changed: m = self.gui.library_view.model() if rows_are_ids: m.refresh_ids(rows) else: m.refresh_rows(rows) current = self.gui.library_view.currentIndex() self.gui.library_view.model().current_changed(current, previous) def book_auto_converted(self, job): temp_files, fmt, book_id, on_card = self.conversion_jobs[job] self.book_converted(job) self.gui.sync_to_device(on_card, False, specific_format=fmt, send_ids=[book_id], do_auto_convert=False) def book_auto_converted_mail(self, job): temp_files, fmt, book_id, delete_from_library, to, fmts, subject = self.conversion_jobs[job] self.book_converted(job) self.gui.send_by_mail(to, fmts, delete_from_library, subject=subject, specific_format=fmt, send_ids=[book_id], do_auto_convert=False) def book_auto_converted_multiple_mail(self, job): temp_files, fmt, book_id, delete_from_library, data = self.conversion_jobs[job] self.book_converted(job) for to, subject in data: self.gui.send_by_mail(to, (fmt,), delete_from_library, subject=subject, specific_format=fmt, send_ids=[book_id], do_auto_convert=False) def book_auto_converted_news(self, job): temp_files, fmt, book_id = self.conversion_jobs[job] self.book_converted(job) self.gui.sync_news(send_ids=[book_id], do_auto_convert=False) def book_auto_converted_catalogs(self, job): temp_files, fmt, book_id = self.conversion_jobs[job] self.book_converted(job) self.gui.sync_catalogs(send_ids=[book_id], do_auto_convert=False) def book_converted(self, job): temp_files, fmt, book_id = self.conversion_jobs.pop(job)[:3] try: if job.failed: self.gui.job_exception(job) return db = self.gui.current_db if not db.new_api.has_id(book_id): return error_dialog(self.gui, _('Book deleted'), _( 'The book you were trying to convert has been deleted from the calibre library.'), show=True) same_fmt = getattr(job, 'conversion_of_same_fmt', False) manually_fine_tune_toc = getattr(job, 'manually_fine_tune_toc', False) fmtf = temp_files[-1].name if os.stat(fmtf).st_size < 1: raise Exception(_('Empty output file, ' 'probably the conversion process crashed')) if same_fmt and tweaks['save_original_format']: db.save_original_format(book_id, fmt, notify=False) with open(temp_files[-1].name, 'rb') as data: db.add_format(book_id, fmt, data, index_is_id=True) run_plugins_on_postconvert(db, book_id, fmt) self.gui.book_converted.emit(book_id, fmt) self.gui.status_bar.show_message(job.description + ' ' + _('completed'), 2000) finally: for f in temp_files: try: if os.path.exists(f.name): os.remove(f.name) except: pass self.gui.tags_view.recount() if self.gui.current_view() is self.gui.library_view: lv = self.gui.library_view lv.model().refresh_ids((book_id,)) current = lv.currentIndex() if current.isValid(): lv.model().current_changed(current, QModelIndex()) if manually_fine_tune_toc: self.gui.iactions['Edit ToC'].do_one(book_id, fmt.upper())
12,770
Python
.py
244
40.610656
141
0.603858
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,921
show_quickview.py
kovidgoyal_calibre/src/calibre/gui2/actions/show_quickview.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from qt.core import QAction, QTimer from calibre.gui2 import error_dialog, gprefs from calibre.gui2.actions import InterfaceAction from calibre.gui2.dialogs.quickview import Quickview current_qv_action_pi = None def set_quickview_action_plugin(pi): global current_qv_action_pi current_qv_action_pi = pi def get_quickview_action_plugin(): return current_qv_action_pi class ShowQuickviewAction(InterfaceAction): name = 'Quickview' action_spec = (_('Quickview'), 'quickview.png', _('Toggle Quickview'), 'Q') dont_add_to = frozenset(('context-menu-device',)) action_type = 'current' current_instance = None def genesis(self): self.menuless_qaction.changed.connect(self.update_layout_button) self.qaction.triggered.connect(self.toggle_quick_view) self.focus_action = QAction(self.gui) self.gui.addAction(self.focus_action) self.gui.keyboard.register_shortcut('Focus To Quickview', _('Focus to Quickview'), description=_('Move the focus to the Quickview panel/window'), default_keys=('Shift+Q',), action=self.focus_action, group=self.action_spec[0]) self.focus_action.triggered.connect(self.focus_quickview) self.focus_bl_action = QAction(self.gui) self.gui.addAction(self.focus_bl_action) self.gui.keyboard.register_shortcut('Focus from Quickview', _('Focus from Quickview to the book list'), description=_('Move the focus from Quickview to the book list'), default_keys=('Shift+Alt+Q',), action=self.focus_bl_action, group=self.action_spec[0]) self.focus_bl_action.triggered.connect(self.focus_booklist) self.focus_refresh_action = QAction(self.gui) self.gui.addAction(self.focus_refresh_action) self.gui.keyboard.register_shortcut('Refresh from Quickview', _('Refresh Quickview'), description=_('Refresh the information shown in the Quickview panel'), action=self.focus_refresh_action, group=self.action_spec[0]) self.focus_refresh_action.triggered.connect(self.refill_quickview) self.search_action = QAction(self.gui) self.gui.addAction(self.search_action) self.gui.keyboard.register_shortcut('Search from Quickview', _('Search from Quickview'), description=_('Search for the currently selected Quickview item'), default_keys=('Shift+S',), action=self.search_action, group=self.action_spec[0]) self.search_action.triggered.connect(self.search_quickview) def update_layout_button(self): self.qv_button.update_shortcut(self.menuless_qaction) def toggle_quick_view(self): if self.current_instance and not self.current_instance.is_closed: self._hide_quickview() else: self._show_quickview() @property def qv_button(self): return self.gui.layout_container.quick_view_button def shutting_down(self): is_open = True if not self.current_instance or self.current_instance.is_closed: is_open = False gprefs.set('qv_open_at_shutdown', is_open) def needs_show_on_startup(self): return gprefs.get('qv_open_at_shutdown', False) def initialization_complete(self): set_quickview_action_plugin(self) self.qv_button.toggled.connect(self.toggle_quick_view) def show_on_startup(self): self.gui.hide_panel('quick_view') self._show_quickview() def _hide_quickview(self): ''' This is called only from the QV button toggle ''' if self.current_instance: if not self.current_instance.is_closed: self.current_instance._reject() self.current_instance = None def _show_quickview(self, *args): ''' This is called only from the QV button toggle ''' if self.current_instance: if not self.current_instance.is_closed: self.current_instance._reject() self.current_instance = None if self.gui.current_view() is not self.gui.library_view: error_dialog(self.gui, _('No quickview available'), _('Quickview is not available for books ' 'on the device.')).exec() return self.qv_button.blockSignals(True) self.qv_button.set_state_to_hide() self.qv_button.blockSignals(False) self._create_current_instance() def _create_current_instance(self): index = self.gui.library_view.currentIndex() self.current_instance = Quickview(self.gui, index, self.qaction.shortcut(), focus_booklist_shortcut=self.focus_bl_action.shortcut()) self.current_instance.reopen_after_dock_change.connect(self.open_quickview) self.current_instance.show() self.current_instance.quickview_closed.connect(self.qv_button.set_state_to_show) def open_quickview(self): ''' QV moved from/to dock. Close and reopen the pane/window. Also called when QV is closed and the user asks to move the focus ''' if self.current_instance and not self.current_instance.is_closed: self.current_instance.reject() self.current_instance = None self.qaction.triggered.emit() def refill_quickview(self): ''' Called when the columns shown in the QV pane might have changed. ''' if self.current_instance and not self.current_instance.is_closed: self.current_instance.refill() def refresh_quickview(self, idx): ''' Called when the data shown in the QV pane might have changed. ''' if self.current_instance and not self.current_instance.is_closed: self.current_instance.refresh(idx) def change_quickview_column(self, idx, show=True): ''' Called from the column header context menu to change the QV query column ''' if show or (self.current_instance and not self.current_instance.is_closed): self.focus_quickview() self.current_instance.slave(idx) # This is needed because if this method is invoked from the library # view header context menu, the library view takes back the focus. I # don't know if this happens for any context menu. QTimer.singleShot(0, self.current_instance.set_focus) def library_changed(self, db): ''' If QV is open, close it then reopen it so the columns are correct ''' if self.current_instance and not self.current_instance.is_closed: self.current_instance.reject() self.qaction.triggered.emit() def focus_quickview(self): ''' Used to move the focus to the QV books table. Open QV if needed ''' if not self.current_instance or self.current_instance.is_closed: self.open_quickview() else: self.current_instance.set_focus() def focus_booklist(self): self.gui.activateWindow() self.gui.library_view.setFocus() def search_quickview(self): if not self.current_instance or self.current_instance.is_closed: return self.current_instance.do_search()
7,673
Python
.py
162
37.308642
98
0.643431
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,922
layout_actions.py
kovidgoyal_calibre/src/calibre/gui2/actions/layout_actions.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2022, Charles Haley from enum import Enum from functools import partial from qt.core import QComboBox, QDialog, QDialogButtonBox, QFormLayout, QIcon, QLabel, QMenu, QToolButton, QVBoxLayout from calibre.gui2 import error_dialog, gprefs, question_dialog from calibre.gui2.actions import InterfaceAction, show_menu_under_widget from calibre.gui2.geometry import _restore_geometry, delete_geometry, save_geometry from calibre.utils.icu import sort_key class Panel(Enum): ' See gui2.init for these ' SEARCH_BAR = 'sb' TAG_BROWSER = 'tb' BOOK_DETAILS = 'bd' GRID_VIEW = 'gv' COVER_BROWSER = 'cb' QUICKVIEW = 'qv' class SaveLayoutDialog(QDialog): def __init__(self, parent, names): QDialog.__init__(self, parent) self.names = names l = QVBoxLayout(self) fl = QFormLayout() l.addLayout(fl) self.cb = cb = QComboBox() cb.setEditable(True) cb.setMinimumWidth(200) cb.addItem('') cb.addItems(sorted(names, key=sort_key)) fl.addRow(QLabel(_('Layout name')), cb) bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) l.addWidget(bb) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) def current_name(self): return self.cb.currentText().strip() def accept(self): n = self.current_name() if not n: error_dialog(self, _('Invalid name'), _('The settings name cannot be blank'), show=True, show_copy_button=False) return if self.current_name() in self.names: r = question_dialog(self, _('Replace saved layout'), _('Do you really want to overwrite the saved layout {0}?').format(self.current_name())) if r == QDialog.DialogCode.Accepted: super().accept() else: return super().accept() class LayoutActions(InterfaceAction): name = 'Layout Actions' action_spec = (_('Layout actions'), 'layout.png', _("Save and restore layout item sizes, and add/remove/toggle " "layout items such as the search bar, tag browser, etc. " "Item sizes in saved layouts are saved as a percentage of " "the window size. Restoring a layout doesn't change the " "window size, instead fitting the items into the current window."), None) action_type = 'current' popup_type = QToolButton.ToolButtonPopupMode.InstantPopup action_add_menu = True dont_add_to = frozenset({'context-menu-device', 'menubar-device'}) def genesis(self): self.layout_icon = QIcon.ic('layout.png') self.menu = m = self.qaction.menu() m.aboutToShow.connect(self.about_to_show_menu) # Create a "hidden" menu that can have a shortcut. self.hidden_menu = QMenu() self.shortcut_action = self.create_menu_action( menu=self.hidden_menu, unique_name='Main window layout', shortcut=None, text=_("Save and restore layout item sizes, and add/remove/toggle " "layout items such as the search bar, tag browser, etc. "), icon='layout.png', triggered=self.show_menu) # We want to show the menu when a shortcut is used. Apparently the only way # to do that is to scan the toolbar(s) for the action button then exec the # associated menu. The search is done here to take adding and removing the # action from toolbars into account. # # If a shortcut is triggered and there isn't a toolbar button visible then # show the menu in the upper left corner of the library view pane. Yes, this # is a bit weird but it works as well as a popping up a dialog. def show_menu(self): show_menu_under_widget(self.gui, self.menu, self.qaction, self.name) def toggle_layout(self): self.gui.layout_container.toggle_layout() def gui_layout_complete(self): m = self.qaction.menu() m.aboutToShow.connect(self.about_to_show_menu) def initialization_complete(self): self.populate_menu() def about_to_show_menu(self): self.populate_menu() def populate_menu(self): m = self.qaction.menu() m.clear() lm = m.addMenu(self.layout_icon, _('Restore saved layout')) layouts = gprefs['saved_layouts'] if layouts: for l in sorted(layouts, key=sort_key): lm.addAction(self.layout_icon, l, partial(self.apply_layout, l)) else: lm.setEnabled(False) lm = m.addAction(self.layout_icon, _('Save current layout')) lm.triggered.connect(self.save_current_layout) lm = m.addMenu(self.layout_icon, _('Delete saved layout')) layouts = gprefs['saved_layouts'] if layouts: for l in sorted(layouts, key=sort_key): lm.addAction(self.layout_icon, l, partial(self.delete_layout, l)) else: lm.setEnabled(False) m.addSeparator() m.addAction(_('Hide all'), self.hide_all) for button, name in zip(self.gui.layout_buttons, self.gui.button_order): m.addSeparator() ic = button.icon() m.addAction(ic, _('Show {}').format(button.label), partial(self.set_visible, Panel(name), True)) m.addAction(ic, _('Hide {}').format(button.label), partial(self.set_visible, Panel(name), False)) m.addAction(ic, _('Toggle {}').format(button.label), partial(self.toggle_item, Panel(name))) def _change_item(self, button, show=True): if button.isChecked() and not show: button.click() elif not button.isChecked() and show: button.click() def _toggle_item(self, button): button.click() def _button_from_enum(self, name: Panel): for q, b in zip(self.gui.button_order, self.gui.layout_buttons): if q == name.value: return b # Public API def apply_layout(self, name): '''apply_layout() Apply a saved GUI panel layout. :param:`name` The name of the saved layout Throws KeyError if the name doesn't exist. ''' # This can be called by plugins so let the exception fly # Restore the application window geometry if we have it. _restore_geometry(self.gui, gprefs, f'saved_layout_{name}') # Now the panel sizes inside the central widget layouts = gprefs['saved_layouts'] settings = layouts[name] # Order is important here. change_layout() must be called before # unserializing the settings or panes like book details won't display # properly. self.gui.layout_container.change_layout(self.gui, settings['layout'] == 'wide') self.gui.layout_container.unserialize_settings(settings) self.gui.layout_container.relayout() def save_current_layout(self): '''save_current_layout() Opens a dialog asking for the name to use to save the current layout. Saves the current settings under the provided name. ''' layouts = gprefs['saved_layouts'] d = SaveLayoutDialog(self.gui, layouts.keys()) if d.exec() == QDialog.DialogCode.Accepted: self.save_named_layout(d.current_name(), self.current_settings()) def current_settings(self): '''current_settings() :return: the current gui layout settings. ''' return self.gui.layout_container.serialized_settings() def save_named_layout(self, name, settings): '''save_named_layout() Saves the settings under the provided name. :param:`name` The name for the settings. :param:`settings`: The gui layout settings to save. ''' # Save the main window geometry. save_geometry(self.gui, gprefs, f'saved_layout_{name}') # Now the panel sizes inside the central widget layouts = gprefs['saved_layouts'] layouts.update({name: settings}) gprefs['saved_layouts'] = layouts self.populate_menu() def delete_layout(self, name, show_warning=True): '''delete_layout() Delete a saved layout. :param:`name` The name of the layout to delete :param:`show_warning`: If True a warning dialog will be shown before deleting the layout. ''' if show_warning: if not question_dialog(self.gui, _('Are you sure?'), _('Do you really want to delete the saved layout {0}?').format(name), skip_dialog_name='delete_saved_gui_layout'): return # The information is stored as 2 preferences. Delete them both. delete_geometry(gprefs, f'saved_layout_{name}') layouts = gprefs['saved_layouts'] layouts.pop(name, None) self.populate_menu() def saved_layout_names(self): '''saved_layout_names() Get a list of saved layout names :return: the sorted list of names. The list is empty if there are no names. ''' layouts = gprefs['saved_layouts'] return sorted(layouts.keys(), key=sort_key) def toggle_item(self, name): '''toggle_item() Toggle the visibility of the panel. :param name: specifies which panel to toggle. Valid names are SEARCH_BAR: 'sb' TAG_BROWSER: 'tb' BOOK_DETAILS: 'bd' GRID_VIEW: 'gv' COVER_BROWSER: 'cb' QUICKVIEW: 'qv' ''' self._toggle_item(self._button_from_enum(name)) def set_visible(self, name: Panel, show=True): '''set_visible() Show or hide a panel. Does nothing if the panel is already in the desired state. :param name: specifies which panel to show. Valid names are SEARCH_BAR: 'sb' TAG_BROWSER: 'tb' BOOK_DETAILS: 'bd' GRID_VIEW: 'gv' COVER_BROWSER: 'cb' QUICKVIEW: 'qv' :param show: If True, show the panel, otherwise hide the panel ''' self._change_item(self._button_from_enum(name), show) def is_visible(self, name: Panel): '''is_visible() Returns True if the panel is visible. :param name: specifies which panel. Valid names are SEARCH_BAR: 'sb' TAG_BROWSER: 'tb' BOOK_DETAILS: 'bd' GRID_VIEW: 'gv' COVER_BROWSER: 'cb' QUICKVIEW: 'qv' ''' self._button_from_enum(name).isChecked() def hide_all(self): for name in self.gui.button_order: self.set_visible(Panel(name), show=False) def show_all(self): for name in self.gui.button_order: self.set_visible(Panel(name), show=True) def panel_titles(self): '''panel_titles() Return a dictionary of Panel Enum items to translated human readable title. Simplifies building dialogs, for example combo boxes of all the panel names or check boxes for each panel. :return: {Panel_enum_value: human readable title, ...} ''' return {p: self._button_from_enum(p).label for p in Panel}
11,534
Python
.py
254
35.484252
117
0.614748
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,923
tag_mapper.py
kovidgoyal_calibre/src/calibre/gui2/actions/tag_mapper.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> from qt.core import QDialog from calibre.gui2 import gprefs from calibre.gui2.actions import InterfaceAction from calibre.utils.localization import ngettext from polyglot.builtins import iteritems class TagMapAction(InterfaceAction): name = 'Tag Mapper' action_spec = (_('Tag mapper'), 'tags.png', _('Filter/transform the tags for books in the library'), None) action_type = 'current' def genesis(self): self.qaction.triggered.connect(self.start_map) def start_map(self): rows = self.gui.library_view.selectionModel().selectedRows() selected = True if not rows or len(rows) < 2: selected = False rows = range(self.gui.library_view.model().rowCount(None)) ids = set(map(self.gui.library_view.model().id, rows)) self.do_map(ids, selected) def do_map(self, book_ids, selected): from calibre.ebooks.metadata.tag_mapper import map_tags from calibre.gui2.tag_mapper import RulesDialog from calibre.gui2.widgets import BusyCursor d = RulesDialog(self.gui) d.setWindowTitle(ngettext( 'Map tags for one book in the library', 'Map tags for {} books in the library', len(book_ids)).format(len(book_ids))) d.rules = gprefs.get('library-tag-mapper-ruleset', ()) txt = ngettext( 'The changes will be applied to the <b>selected book</b>', 'The changes will be applied to the <b>{} selected books</b>', len(book_ids)) if selected else ngettext( 'The changes will be applied to <b>one book in the library</b>', 'The changes will be applied to <b>{} books in the library</b>', len(book_ids)) d.edit_widget.msg_label.setText(d.edit_widget.msg_label.text() + '<p>' + txt.format(len(book_ids))) if d.exec() != QDialog.DialogCode.Accepted: return with BusyCursor(): rules = d.rules gprefs.set('library-tag-mapper-ruleset', rules) db = self.gui.current_db.new_api tag_map = db.all_field_for('tags', book_ids) changed_tag_map = {} for book_id, tags in iteritems(tag_map): tags = list(tags) new_tags = map_tags(tags, rules) if tags != new_tags: changed_tag_map[book_id] = new_tags if changed_tag_map: db.set_field('tags', changed_tag_map) self.gui.library_view.model().refresh_ids(tuple(changed_tag_map), current_row=self.gui.library_view.currentIndex().row()) self.gui.tags_view.recount()
2,727
Python
.py
53
41.622642
137
0.629032
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,924
delete.py
kovidgoyal_calibre/src/calibre/gui2/actions/delete.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from collections import Counter from functools import partial from qt.core import QDialog, QModelIndex, QObject, QTimer from calibre.constants import ismacos from calibre.gui2 import Aborted, error_dialog from calibre.gui2.actions import InterfaceActionWithLibraryDrop from calibre.gui2.dialogs.confirm_delete import confirm from calibre.gui2.dialogs.confirm_delete_location import confirm_location from calibre.gui2.dialogs.delete_matching_from_device import DeleteMatchingFromDeviceDialog from calibre.gui2.widgets import BusyCursor from calibre.gui2.widgets2 import MessagePopup from calibre.utils.localization import ngettext single_shot = partial(QTimer.singleShot, 10) class MultiDeleter(QObject): # {{{ def __init__(self, gui, ids, callback): from calibre.gui2.dialogs.progress import ProgressDialog QObject.__init__(self, gui) self.model = gui.library_view.model() self.ids = ids self.permanent = False self.gui = gui self.failures = [] self.deleted_ids = [] self.callback = callback single_shot(self.delete_one) self.pd = ProgressDialog(_('Deleting...'), parent=gui, cancelable=False, min=0, max=len(self.ids), icon='trash.png') self.pd.setModal(True) self.pd.show() def delete_one(self): if not self.ids: self.cleanup() return id_ = self.ids.pop() title = 'id:%d'%id_ try: title_ = self.model.db.title(id_, index_is_id=True) if title_: title = title_ self.model.db.delete_book(id_, notify=False, commit=False, permanent=False) self.deleted_ids.append(id_) except: import traceback self.failures.append((id_, title, traceback.format_exc())) single_shot(self.delete_one) self.pd.value += 1 self.pd.set_msg(_('Deleted') + ' ' + title) def cleanup(self): self.pd.hide() self.pd = None self.model.db.commit() self.model.db.clean() self.model.books_deleted() # calls recount on the tag browser self.callback(self.deleted_ids) if self.failures: msg = ['==> '+x[1]+'\n'+x[2] for x in self.failures] error_dialog(self.gui, _('Failed to delete'), _('Failed to delete some books, click the "Show details" button' ' for details.'), det_msg='\n\n'.join(msg), show=True) # }}} class DeleteAction(InterfaceActionWithLibraryDrop): name = 'Remove Books' action_spec = (_('Remove books'), 'remove_books.png', _('Delete books'), 'Backspace' if ismacos else 'Del') action_type = 'current' action_add_menu = True action_menu_clone_qaction = _('Remove selected books') def do_drop(self): book_ids = self.dropped_ids del self.dropped_ids if book_ids: self.do_library_delete(book_ids) def genesis(self): self.qaction.triggered.connect(self.delete_books) self.delete_menu = self.qaction.menu() m = partial(self.create_menu_action, self.delete_menu) m('delete-specific', _('Remove files of a specific format from selected books'), triggered=self.delete_selected_formats) m('delete-except', _('Remove all formats from selected books, except...'), triggered=self.delete_all_but_selected_formats) self.delete_menu.addSeparator() m('delete-all', _('Remove all formats from selected books'), triggered=self.delete_all_formats) m('delete-covers', _('Remove covers from selected books'), triggered=self.delete_covers) self.delete_menu.addSeparator() m('delete-matching', _('Remove matching books from device'), triggered=self.remove_matching_books_from_device) self.delete_menu.addSeparator() m('delete-undelete', _('Restore recently deleted'), triggered=self.undelete_recent, icon='edit-undo.png') self.qaction.setMenu(self.delete_menu) self.delete_memory = {} def location_selected(self, loc): enabled = loc == 'library' for action in list(self.delete_menu.actions())[1:]: action.setEnabled(enabled) def _get_selected_formats(self, msg, ids, exclude=False, single=False): from calibre.gui2.dialogs.select_formats import SelectFormats c = Counter() db = self.gui.library_view.model().db for x in ids: fmts_ = db.formats(x, index_is_id=True, verify_formats=False) if fmts_: for x in frozenset(x.lower() for x in fmts_.split(',')): c[x] += 1 d = SelectFormats(c, msg, parent=self.gui, exclude=exclude, single=single) if d.exec() != QDialog.DialogCode.Accepted: return None return d.selected_formats def _get_selected_ids(self, err_title=_('Cannot delete')): rows = self.gui.library_view.selectionModel().selectedRows() if not rows or len(rows) == 0: d = error_dialog(self.gui, err_title, _('No book selected')) d.exec() return set() return set(map(self.gui.library_view.model().id, rows)) def _remove_formats_from_ids(self, fmts, ids): self.show_undo_for_deleted_formats(self.gui.library_view.model().db.new_api.remove_formats({bid: fmts for bid in ids})) self.gui.library_view.model().refresh_ids(ids) self.gui.library_view.model().current_changed(self.gui.library_view.currentIndex(), self.gui.library_view.currentIndex()) self.gui.tags_view.recount() def remove_format_by_id(self, book_id, fmt): title = self.gui.current_db.title(book_id, index_is_id=True) if not confirm('<p>'+(_( 'The %(fmt)s format will be <b>deleted</b> from ' '%(title)s. Are you sure?')%dict(fmt=fmt, title=title)) + '</p>', 'library_delete_specific_format', self.gui): return self._remove_formats_from_ids((fmt,), (book_id,)) def remove_format_from_selected_books(self, fmt): ids = self._get_selected_ids() if not ids: return db = self.gui.current_db.new_api fmt = fmt.upper() for bid in ids: if fmt in db.formats(bid): break else: return error_dialog(self.gui, _('Format not found'), _('The {} format is not present in the selected books.').format(fmt), show=True) if not confirm( '<p>'+ ngettext( _('The {fmt} format will be <b>deleted</b> from {title}.'), _('The {fmt} format will be <b>deleted</b> from all {num} selected books.'), len(ids)).format(fmt=fmt.upper(), num=len(ids), title=self.gui.current_db.title(next(iter(ids)), index_is_id=True) ) + ' ' + _('Are you sure?'), 'library_delete_specific_format_from_selected', self.gui ): return self._remove_formats_from_ids((fmt,), ids) def restore_format(self, book_id, original_fmt): self.gui.current_db.restore_original_format(book_id, original_fmt) self.gui.library_view.model().refresh_ids([book_id]) self.gui.library_view.model().current_changed(self.gui.library_view.currentIndex(), self.gui.library_view.currentIndex()) self.gui.tags_view.recount_with_position_based_index() def delete_selected_formats(self, *args): ids = self._get_selected_ids() if not ids: return fmts = self._get_selected_formats( _('Choose formats to be deleted'), ids) if not fmts: return m = self.gui.library_view.model() self.show_undo_for_deleted_formats(m.db.new_api.remove_formats({book_id:fmts for book_id in ids})) m.refresh_ids(ids) m.current_changed(self.gui.library_view.currentIndex(), self.gui.library_view.currentIndex()) if ids: self.gui.tags_view.recount_with_position_based_index() def delete_all_but_selected_formats(self, *args): ids = self._get_selected_ids() if not ids: return fmts = self._get_selected_formats( '<p>'+_('Choose formats <b>not</b> to be deleted.<p>Note that ' 'this will never remove all formats from a book.'), ids, exclude=True) if fmts is None: return m = self.gui.library_view.model() removals = {} for id in ids: bfmts = m.db.formats(id, index_is_id=True) if bfmts is None: continue bfmts = {x.lower() for x in bfmts.split(',')} rfmts = bfmts - set(fmts) if bfmts - rfmts: # Do not delete if it will leave the book with no # formats removals[id] = rfmts if removals: self.show_undo_for_deleted_formats(m.db.new_api.remove_formats(removals)) m.refresh_ids(ids) m.current_changed(self.gui.library_view.currentIndex(), self.gui.library_view.currentIndex()) if ids: self.gui.tags_view.recount_with_position_based_index() def delete_all_formats(self, *args): ids = self._get_selected_ids() if not ids: return if not confirm('<p>'+_('<b>All formats</b> for the selected books will ' 'be <b>deleted</b> from your library.<br>' 'The book metadata will be kept. Are you sure?') + '</p>', 'delete_all_formats', self.gui): return db = self.gui.library_view.model().db removals = {} for id in ids: fmts = db.formats(id, index_is_id=True, verify_formats=False) if fmts: removals[id] = fmts.split(',') if removals: self.show_undo_for_deleted_formats(db.new_api.remove_formats(removals)) self.gui.library_view.model().refresh_ids(ids) self.gui.library_view.model().current_changed(self.gui.library_view.currentIndex(), self.gui.library_view.currentIndex()) if ids: self.gui.tags_view.recount_with_position_based_index() def remove_matching_books_from_device(self, *args): if not self.gui.device_manager.is_device_present: d = error_dialog(self.gui, _('Cannot delete books'), _('No device is connected')) d.exec() return ids = self._get_selected_ids() if not ids: # _get_selected_ids shows a dialog box if nothing is selected, so we # do not need to show one here return to_delete = {} some_to_delete = False for model,name in ((self.gui.memory_view.model(), _('Main memory')), (self.gui.card_a_view.model(), _('Storage card A')), (self.gui.card_b_view.model(), _('Storage card B'))): to_delete[name] = (model, model.paths_for_db_ids(ids)) if len(to_delete[name][1]) > 0: some_to_delete = True if not some_to_delete: d = error_dialog(self.gui, _('No books to delete'), _('None of the selected books are on the device')) d.exec() return d = DeleteMatchingFromDeviceDialog(self.gui, to_delete) if d.exec(): paths = {} ids = {} for (model, id, path) in d.result: if model not in paths: paths[model] = [] ids[model] = [] paths[model].append(path) ids[model].append(id) cv, row = self.gui.current_view(), -1 if cv is not self.gui.library_view: row = cv.currentIndex().row() for model in paths: job = self.gui.remove_paths(paths[model]) self.delete_memory[job] = (paths[model], model) model.mark_for_deletion(job, ids[model], rows_are_ids=True) self.gui.status_bar.show_message(_('Deleting books from device.'), 1000) if row > -1: nrow = row - 1 if row > 0 else row + 1 cv.set_current_row(min(cv.model().rowCount(None), max(0, nrow))) def delete_covers(self, *args): ids = self._get_selected_ids() if not ids: return if not confirm('<p>'+ngettext( 'The cover from the selected book will be <b>permanently deleted</b>. Are you sure?', 'The covers from the {} selected books will be <b>permanently deleted</b>. ' 'Are you sure?', len(ids)).format(len(ids)), 'library_delete_covers', self.gui): return for id in ids: self.gui.library_view.model().db.remove_cover(id) self.gui.library_view.model().refresh_ids(ids) self.gui.library_view.model().current_changed(self.gui.library_view.currentIndex(), self.gui.library_view.currentIndex()) def library_ids_deleted(self, ids_deleted, current_row=None): view = self.gui.library_view for v in (self.gui.memory_view, self.gui.card_a_view, self.gui.card_b_view): if v is None: continue v.model().clear_ondevice(ids_deleted) if current_row is not None: ci = view.model().index(current_row, 0) if not ci.isValid(): # Current row is after the last row, set it to the last row current_row = view.row_count() - 1 view.set_current_row(current_row) if view.model().rowCount(QModelIndex()) < 1: self.gui.book_details.reset_info() @property def show_message_popup(self): if not hasattr(self, 'message_popup'): self.message_popup = MessagePopup(self.gui) self.message_popup.OFFSET_FROM_TOP = 12 self.message_popup.undo_requested.connect(self.undelete) return self.message_popup def library_ids_deleted2(self, ids_deleted, next_id=None, can_undo=False): view = self.gui.library_view current_row = None if next_id is not None: rmap = view.ids_to_rows([next_id]) current_row = rmap.get(next_id, None) self.library_ids_deleted(ids_deleted, current_row=current_row) if can_undo: self.show_message_popup(ngettext('One book deleted from library.', '{} books deleted from library.', len(ids_deleted)).format(len(ids_deleted)), show_undo=(self.gui.current_db.new_api.library_id, ids_deleted)) def show_undo_for_deleted_formats(self, removed_map): num = sum(map(len, removed_map.values())) self.show_message_popup(ngettext('One book format deleted.', '{} book formats deleted.', num).format(num), show_undo=(self.gui.current_db.new_api.library_id, removed_map)) def library_changed(self, db): if hasattr(self, 'message_popup'): self.message_popup.hide() def undelete(self, what): library_id, book_ids = what db = self.gui.current_db.new_api if library_id != db.library_id: return current_idx = self.gui.library_view.currentIndex() if isinstance(book_ids, dict): with BusyCursor(): for book_id, fmts in book_ids.items(): for fmt in fmts: db.move_format_from_trash(book_id, fmt) if current_idx.isValid(): self.gui.library_view.model().current_changed(current_idx, current_idx) else: with BusyCursor(): for book_id in book_ids: db.move_book_from_trash(book_id) self.refresh_after_undelete(book_ids) def refresh_after_undelete(self, book_ids): self.gui.current_db.data.books_added(book_ids) self.gui.iactions['Add Books'].refresh_gui(len(book_ids)) self.gui.library_view.resort() self.gui.library_view.select_rows(set(book_ids), using_ids=True) def undelete_recent(self): from calibre.gui2.trash import TrashView current_idx = self.gui.library_view.currentIndex() d = TrashView(self.gui.current_db, self.gui) d.books_restored.connect(self.refresh_after_undelete) d.exec() if d.formats_restored: if current_idx.isValid(): self.gui.library_view.model().current_changed(current_idx, current_idx) def do_library_delete(self, to_delete_ids): view = self.gui.current_view() next_id = view.next_id # Ask the user if they want to delete the book from the library or device if it is in both. if self.gui.device_manager.is_device_present: on_device = False on_device_ids = self._get_selected_ids() for id in on_device_ids: res = self.gui.book_on_device(id) if res[0] or res[1] or res[2]: on_device = True if on_device: break if on_device: loc = confirm_location('<p>' + _('Some of the selected books are on the attached device. ' '<b>Where</b> do you want the selected files deleted from?'), name='device-and-or-lib', parent=self.gui) if not loc: return elif loc == 'dev': self.remove_matching_books_from_device() return elif loc == 'both': self.remove_matching_books_from_device() # The following will run if the selected books are not on a connected device. # The user has selected to delete from the library or the device and library. if not confirm('<p>'+ngettext( 'The selected book will be <b>deleted</b> and the files ' 'removed from your calibre library. Are you sure?', 'The {} selected books will be <b>deleted</b> and the files ' 'removed from your calibre library. Are you sure?', len(to_delete_ids)).format(len(to_delete_ids)), 'library_delete_books', self.gui): return if len(to_delete_ids) < 5: try: view.model().delete_books_by_id(to_delete_ids) except OSError as err: err.locking_violation_msg = _('Could not change on-disk location of this book\'s files.') raise self.library_ids_deleted2(to_delete_ids, next_id=next_id, can_undo=True) else: try: self.__md = MultiDeleter(self.gui, to_delete_ids, partial(self.library_ids_deleted2, next_id=next_id, can_undo=True)) except Aborted: pass def delete_books(self, *args): ''' Delete selected books from device or library. ''' view = self.gui.current_view() rows = view.selectionModel().selectedRows() if not rows or len(rows) == 0: return # Library view is visible. if self.gui.stack.currentIndex() == 0: to_delete_ids = [view.model().id(r) for r in rows] self.do_library_delete(to_delete_ids) # Device view is visible. else: cv, row = self.gui.current_view(), -1 if cv is not self.gui.library_view: row = cv.currentIndex().row() if self.gui.stack.currentIndex() == 1: view = self.gui.memory_view elif self.gui.stack.currentIndex() == 2: view = self.gui.card_a_view else: view = self.gui.card_b_view paths = view.model().paths(rows) ids = view.model().indices(rows) if not confirm('<p>'+ngettext( 'The selected book will be <b>permanently deleted</b> from your device. Are you sure?', 'The {} selected books will be <b>permanently deleted</b> from your device. Are you sure?', len(paths)).format(len(paths)), 'device_delete_books', self.gui): return job = self.gui.remove_paths(paths) self.delete_memory[job] = (paths, view.model()) view.model().mark_for_deletion(job, ids, rows_are_ids=True) self.gui.status_bar.show_message(_('Deleting books from device.'), 1000) if row > -1: nrow = row - 1 if row > 0 else row + 1 cv.set_current_row(min(cv.model().rowCount(None), max(0, nrow)))
21,320
Python
.py
445
35.862921
156
0.575426
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,925
add.py
kovidgoyal_calibre/src/calibre/gui2/actions/add.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os from collections import defaultdict from functools import partial from qt.core import QApplication, QDialog, QPixmap, QTimer from calibre import as_unicode, guess_type, prepare_string_for_xml from calibre.constants import iswindows from calibre.ebooks import BOOK_EXTENSIONS from calibre.ebooks.metadata import MetaInformation, normalize_isbn from calibre.gui2 import choose_dir, choose_files, choose_files_and_remember_all_files, error_dialog, gprefs, info_dialog, question_dialog, warning_dialog from calibre.gui2.actions import InterfaceAction from calibre.gui2.dialogs.add_empty_book import AddEmptyBookDialog from calibre.gui2.dialogs.confirm_delete import confirm from calibre.gui2.dialogs.progress import ProgressDialog from calibre.ptempfile import PersistentTemporaryFile from calibre.utils.config_base import tweaks from calibre.utils.filenames import ascii_filename, make_long_path_useable from calibre.utils.icu import sort_key from calibre.utils.localization import ngettext from polyglot.builtins import iteritems, string_or_bytes def get_filters(): archives = ['zip', 'rar', '7z'] return [ (_('Books'), [x for x in BOOK_EXTENSIONS if x not in archives]), (_('EPUB books'), ['epub', 'kepub']), (_('Kindle books'), ['mobi', 'prc', 'azw', 'azw3', 'kfx', 'tpz', 'azw1', 'azw4']), (_('PDF books'), ['pdf', 'azw4']), (_('HTML books'), ['htm', 'html', 'xhtm', 'xhtml']), (_('LIT books'), ['lit']), (_('Text books'), ['txt', 'text', 'rtf', 'md', 'markdown', 'textile', 'txtz']), (_('Comics'), ['cbz', 'cbr', 'cbc', 'cb7']), (_('Archives'), archives), (_('Wordprocessor files'), ['odt', 'doc', 'docx']), ] class AddAction(InterfaceAction): name = 'Add Books' action_spec = (_('Add books'), 'add_book.png', _('Add books to the calibre library/device from files on your computer') , _('A')) action_type = 'current' action_add_menu = True action_menu_clone_qaction = _('Add books from a single folder') def genesis(self): self._add_filesystem_book = self.Dispatcher(self.__add_filesystem_book) self.add_menu = self.qaction.menu() ma = partial(self.create_menu_action, self.add_menu) ma('recursive-add', _('Add from folders and sub-folders'), icon='mimetypes/dir.png').triggered.connect(self.add_recursive_question) ma('archive-add-book', _('Add multiple books from archive (ZIP/RAR/7z)'), icon='mimetypes/zip.png').triggered.connect(self.add_from_archive) self.add_menu.addSeparator() ma('add-empty', _('Add empty book (Book entry with no formats)'), shortcut='Shift+Ctrl+E').triggered.connect(self.add_empty) ma('add-isbn', _('Add from ISBN'), icon='identifiers.png').triggered.connect(self.add_from_isbn) self.add_menu.addSeparator() ma('add-formats', _('Add files to selected book records'), triggered=self.add_formats, shortcut='Shift+A') ma('add-formats-clipboard', _('Add files to selected book records from clipboard'), triggered=self.add_formats_from_clipboard, shortcut='Shift+Alt+A', icon='edit-paste.png') ma('add-extra-files-to-books', _( 'Add data files to selected book records')).triggered.connect(self.add_extra_files) ma('add-empty-format-to-books', _( 'Add an empty file to selected book records')).triggered.connect(self.add_empty_format_choose) self.add_menu.addSeparator() ma('add-config', _('Control the adding of books'), icon='config.png', triggered=self.add_config) self.qaction.triggered.connect(self.add_books) def location_selected(self, loc): enabled = loc == 'library' for action in list(self.add_menu.actions())[1:]: action.setEnabled(enabled) def add_config(self): self.gui.iactions['Preferences'].do_config( initial_plugin=('Import/Export', 'Adding'), close_after_initial=True) def _check_add_formats_ok(self): if self.gui.current_view() is not self.gui.library_view: return [] view = self.gui.library_view rows = view.selectionModel().selectedRows() if not rows: error_dialog(self.gui, _('No books selected'), _('Cannot add files as no books are selected'), show=True) ids = [view.model().id(r) for r in rows] return ids def add_formats_from_clipboard(self): ids = self._check_add_formats_ok() if not ids: return md = QApplication.instance().clipboard().mimeData() files_to_add = [] images = [] if md.hasUrls(): for url in md.urls(): if url.isLocalFile(): path = url.toLocalFile() if os.access(path, os.R_OK): mt = guess_type(path)[0] if mt and mt.startswith('image/'): images.append(path) else: files_to_add.append(path) if not files_to_add and not images: return error_dialog(self.gui, _('No files in clipboard'), _('No files have been copied to the clipboard'), show=True) if files_to_add: self._add_formats(files_to_add, ids) if images: if len(ids) > 1 and not question_dialog( self.gui, _('Are you sure?'), _('Are you sure you want to set the same' ' cover for all %d books?')%len(ids)): return with open(images[0], 'rb') as f: cdata = f.read() self.gui.current_db.new_api.set_cover({book_id: cdata for book_id in ids}) self.gui.refresh_cover_browser() m = self.gui.library_view.model() current = self.gui.library_view.currentIndex() m.current_changed(current, current) def add_formats(self, *args): ids = self._check_add_formats_ok() if not ids: return books = choose_files_and_remember_all_files(self.gui, 'add formats dialog dir', _('Select book files'), filters=get_filters()) if books: self._add_formats(books, ids) def _add_extra_files(self, book_ids, paths): rmap = {'data/' + os.path.basename(x): x for x in paths} db = self.gui.current_db.new_api for book_id in book_ids: db.add_extra_files(book_id, rmap) self.gui.library_view.model().refresh_ids(book_ids, current_row=self.gui.library_view.currentIndex().row()) def add_extra_files(self): ids = self._check_add_formats_ok() if not ids: return books = choose_files_and_remember_all_files(self.gui, 'add extra data files dialog dir', _('Select extra data files'), filters=get_filters()) if books: self._add_extra_files(ids, books) def _add_formats(self, paths, ids): if len(ids) > 1 and not question_dialog( self.gui, _('Are you sure?'), _('Are you sure you want to add the same' ' files to all %d books? If the format' ' already exists for a book, it will be replaced.')%len(ids)): return paths = list(map(make_long_path_useable, paths)) db = self.gui.current_db if len(ids) == 1: formats = db.formats(ids[0], index_is_id=True) if formats: formats = {x.upper() for x in formats.split(',')} nformats = {f.rpartition('.')[-1].upper() for f in paths} override = formats.intersection(nformats) if override: title = db.title(ids[0], index_is_id=True) msg = ngettext( 'The {0} format will be replaced in the book {1}. Are you sure?', 'The {0} formats will be replaced in the book {1}. Are you sure?', len(override)).format(', '.join(override), title) if not confirm(msg, 'confirm_format_override_on_add', title=_('Are you sure?'), parent=self.gui): return fmt_map = {os.path.splitext(fpath)[1][1:].upper():fpath for fpath in paths} for id_ in ids: for fmt, fpath in iteritems(fmt_map): if fmt: db.add_format_with_hooks(id_, fmt, fpath, index_is_id=True, notify=True) current_idx = self.gui.library_view.currentIndex() if current_idx.isValid(): self.gui.library_view.model().current_changed(current_idx, current_idx) def is_ok_to_add_empty_formats(self): if self.gui.stack.currentIndex() != 0: return view = self.gui.library_view rows = view.selectionModel().selectedRows() if not rows: return error_dialog(self.gui, _('No books selected'), _('Cannot add files as no books are selected'), show=True) ids = [view.model().id(r) for r in rows] if len(ids) > 1 and not question_dialog( self.gui, _('Are you sure?'), _('Are you sure you want to add the same' ' empty file to all %d books? If the format' ' already exists for a book, it will be replaced.')%len(ids)): return return True def add_empty_format_choose(self): if not self.is_ok_to_add_empty_formats(): return from calibre.ebooks.oeb.polish.create import valid_empty_formats from calibre.gui2.dialogs.choose_format import ChooseFormatDialog d = ChooseFormatDialog(self.gui, _('Choose format of empty file'), sorted(valid_empty_formats)) if d.exec() != QDialog.DialogCode.Accepted or not d.format(): return self._add_empty_format(d.format()) def add_empty_format(self, format_): if not self.is_ok_to_add_empty_formats(): return self._add_empty_format(format_) def _add_empty_format(self, format_): view = self.gui.library_view rows = view.selectionModel().selectedRows() ids = [view.model().id(r) for r in rows] db = self.gui.library_view.model().db if len(ids) == 1: formats = db.formats(ids[0], index_is_id=True) if formats: formats = {x.lower() for x in formats.split(',')} if format_ in formats: title = db.title(ids[0], index_is_id=True) msg = _('The {0} format will be replaced in the book: {1}. Are you sure?').format( format_, title) if not confirm(msg, 'confirm_format_override_on_add', title=_('Are you sure?'), parent=self.gui): return for id_ in ids: self.add_empty_format_to_book(id_, format_) current_idx = self.gui.library_view.currentIndex() if current_idx.isValid(): view.model().current_changed(current_idx, current_idx) def add_empty_format_to_book(self, book_id, fmt): from calibre.ebooks.oeb.polish.create import create_book db = self.gui.current_db pt = PersistentTemporaryFile(suffix='.' + fmt.lower()) pt.close() try: mi = db.new_api.get_metadata(book_id, get_cover=False, get_user_categories=False, cover_as_data=False) create_book(mi, pt.name, fmt=fmt.lower()) db.add_format_with_hooks(book_id, fmt, pt.name, index_is_id=True, notify=True) finally: os.remove(pt.name) def add_archive(self, single): paths = choose_files( self.gui, 'recursive-archive-add', _('Choose archive file'), filters=[(_('Archives'), ('zip', 'rar', '7z'))], all_files=False, select_only_single_file=False) if paths: self.do_add_recursive(paths, single, list_of_archives=True) def add_from_archive(self): single = question_dialog(self.gui, _('Type of archive'), _( 'Will the archive have a single book per internal folder?')) paths = choose_files( self.gui, 'recursive-archive-add', _('Choose archive file'), filters=[(_('Archives'), ('zip', 'rar', '7z'))], all_files=False, select_only_single_file=False) if paths: self.do_add_recursive(paths, single, list_of_archives=True) def add_recursive(self, single): root = choose_dir(self.gui, 'recursive book import root dir dialog', _('Select root folder')) if not root: return lp = os.path.normcase(os.path.abspath(self.gui.current_db.library_path)) if lp.startswith(os.path.normcase(os.path.abspath(root)) + os.pathsep): return error_dialog(self.gui, _('Cannot add'), _( 'Cannot add books from the folder: %s as it contains the currently opened calibre library') % root, show=True) self.do_add_recursive(root, single) def do_add_recursive(self, root, single, list_of_archives=False): from calibre.gui2.add import Adder Adder(root, single_book_per_directory=single, db=self.gui.current_db, list_of_archives=list_of_archives, callback=self._files_added, parent=self.gui, pool=self.gui.spare_pool()) def add_recursive_single(self, *args): ''' Add books from the local filesystem to either the library or the device recursively assuming one book per folder. ''' self.add_recursive(True) def add_recursive_multiple(self, *args): ''' Add books from the local filesystem to either the library or the device recursively assuming multiple books per folder. ''' self.add_recursive(False) def add_recursive_question(self): single = question_dialog(self.gui, _('Multi-file books?'), _( 'Assume all e-book files in a single folder are multiple formats of the same book?')) self.add_recursive(single) def add_empty(self, *args): ''' Add an empty book item to the library. This does not import any formats from a book file. ''' author = series = title = None index = self.gui.library_view.currentIndex() if index.isValid(): raw = index.model().db.authors(index.row()) if raw: authors = [a.strip().replace('|', ',') for a in raw.split(',')] if authors: author = authors[0] series = index.model().db.series(index.row()) title = index.model().db.title(index.row()) dlg = AddEmptyBookDialog(self.gui, self.gui.library_view.model().db, author, series, dup_title=title) if dlg.exec() == QDialog.DialogCode.Accepted: temp_files = [] num = dlg.qty_to_add series = dlg.selected_series title = dlg.selected_title or _('Unknown') db = self.gui.library_view.model().db ids, orig_fmts = [], [] if dlg.duplicate_current_book: origmi = db.get_metadata(index.row(), get_cover=True, cover_as_data=True) if dlg.copy_formats.isChecked(): book_id = db.id(index.row()) orig_fmts = tuple(db.new_api.format(book_id, fmt, as_path=True) for fmt in db.new_api.formats(book_id)) for x in range(num): if dlg.duplicate_current_book: mi = origmi else: mi = MetaInformation(title, dlg.selected_authors) if series: mi.series = series mi.series_index = db.get_next_series_num_for(series) fmts = [] empty_format = gprefs.get('create_empty_format_file', '') if dlg.duplicate_current_book and dlg.copy_formats.isChecked(): fmts = orig_fmts elif empty_format: from calibre.ebooks.oeb.polish.create import create_book pt = PersistentTemporaryFile(suffix='.' + empty_format) pt.close() temp_files.append(pt.name) create_book(mi, pt.name, fmt=empty_format) fmts = [pt.name] ids.append(db.import_book(mi, fmts)) for path in orig_fmts: os.remove(path) self.refresh_gui(num) if ids: ids.reverse() self.gui.library_view.select_rows(ids) for path in temp_files: os.remove(path) def check_for_existing_isbns(self, books): db = self.gui.current_db.new_api book_id_identifiers = db.all_field_for('identifiers', db.all_book_ids(tuple)) existing_isbns = {normalize_isbn(ids.get('isbn', '')): book_id for book_id, ids in book_id_identifiers.items()} existing_isbns.pop('', None) ok = [] duplicates = [] checker_maps = {} for book in books: if 'isbn' in book: q = normalize_isbn(book['isbn']) if q and q in existing_isbns: duplicates.append((book, existing_isbns[q])) else: ok.append(book) else: key = book[''] if key not in checker_maps: checker_maps[key] = {ids.get(key, ''): book_id for book_id, ids in book_id_identifiers.items()} checker_maps[key].pop('', None) q = book[key] if q in checker_maps[key]: duplicates.append((book, checker_maps[key][q])) else: ok.append(book) if duplicates: det_msg = '\n'.join(f'{book[book[""]]}: {db.field_for("title", book_id)}' for book, book_id in duplicates) if question_dialog(self.gui, _('Duplicates found'), _( 'Books with some of the specified ISBNs already exist in the calibre library.' ' Click "Show details" for the full list. Do you want to add them anyway?'), det_msg=det_msg ): ok += [x[0] for x in duplicates] return ok def add_isbns(self, books, add_tags=[], check_for_existing=False): books = list(books) if check_for_existing: books = self.check_for_existing_isbns(books) if not books: return self.isbn_books = books self.add_by_isbn_ids = set() self.isbn_add_tags = add_tags QTimer.singleShot(10, self.do_one_isbn_add) self.isbn_add_dialog = ProgressDialog(_('Adding'), _('Creating book records from ISBNs'), max=len(books), cancelable=False, parent=self.gui) self.isbn_add_dialog.exec() def do_one_isbn_add(self): try: db = self.gui.library_view.model().db try: x = self.isbn_books.pop(0) except IndexError: self.gui.library_view.model().books_added(self.isbn_add_dialog.value) self.isbn_add_dialog.accept() self.gui.iactions['Edit Metadata'].download_metadata( ids=self.add_by_isbn_ids, ensure_fields=frozenset(['title', 'authors'])) return mi = MetaInformation(None) if x[''] == 'isbn': mi.isbn = x['isbn'] else: mi.set_identifiers({x['']:x[x['']]}) if self.isbn_add_tags: mi.tags = list(self.isbn_add_tags) fmts = [] if x['path'] is None else [x['path']] self.add_by_isbn_ids.add(db.import_book(mi, fmts)) self.isbn_add_dialog.value += 1 QTimer.singleShot(10, self.do_one_isbn_add) except: self.isbn_add_dialog.accept() raise def files_dropped(self, paths): to_device = self.gui.stack.currentIndex() != 0 self._add_books(paths, to_device) def remote_file_dropped_on_book(self, url, fname): if self.gui.current_view() is not self.gui.library_view: return db = self.gui.library_view.model().db current_idx = self.gui.library_view.currentIndex() if not current_idx.isValid(): return cid = db.id(current_idx.row()) from calibre.gui2.dnd import DownloadDialog d = DownloadDialog(url, fname, self.gui) d.start_download() if d.err is None: self.files_dropped_on_book(None, [d.fpath], cid=cid) def files_dropped_on_book(self, event, paths, cid=None, do_confirm=True): accept = False if self.gui.current_view() is not self.gui.library_view: return db = self.gui.library_view.model().db cover_changed = False current_idx = self.gui.library_view.currentIndex() if cid is None: if not current_idx.isValid(): return cid = db.id(current_idx.row()) if cid is None else cid formats = [] from calibre.gui2.dnd import image_extensions image_exts = set(image_extensions()) - set(tweaks['cover_drop_exclude']) if iswindows: from calibre.gui2.add import resolve_windows_links paths = list(resolve_windows_links(paths, hwnd=int(self.gui.effectiveWinId()))) for path in paths: ext = os.path.splitext(path)[1].lower() if ext: ext = ext[1:] if ext in image_exts: pmap = QPixmap() pmap.load(path) if not pmap.isNull(): accept = True db.set_cover(cid, pmap) cover_changed = True else: formats.append((ext, path)) accept = True if accept and event is not None: event.accept() add_as_book = add_as_data_files = False if do_confirm and formats: ok, add_as = confirm( _('You have dropped some files onto the book <b>%s</b>. This will' ' add or replace the files for this book. Do you want to proceed?') % db.title(cid, index_is_id=True), 'confirm_drop_on_book', parent=self.gui, extra_button=_('Add as...'), extra_button_choices={ 'book': ngettext('Add as new book', 'Add as new books', len(formats)), 'data_files': ngettext('Add as data file', 'Add as data files', len(formats)), }) if ok: if add_as == 'book': add_as_book = [path for ext, path in formats] formats = [] elif add_as == 'data_files': add_as_data_files = [path for ext, path in formats] formats = [] else: formats = [] for ext, path in formats: db.add_format_with_hooks(cid, ext, path, index_is_id=True) if current_idx.isValid(): self.gui.library_view.model().current_changed(current_idx, current_idx) if cover_changed: self.gui.refresh_cover_browser() if add_as_book: self.files_dropped(add_as_book) if add_as_data_files: self._add_extra_files({cid}, add_as_data_files) def __add_filesystem_book(self, paths, allow_device=True): if isinstance(paths, string_or_bytes): paths = [paths] books = [path for path in map(os.path.abspath, paths) if os.access(path, os.R_OK)] if books: to_device = allow_device and self.gui.stack.currentIndex() != 0 self._add_books(books, to_device) if to_device: self.gui.status_bar.show_message( _('Uploading books to device.'), 2000) def add_filesystem_book(self, paths, allow_device=True): self._add_filesystem_book(paths, allow_device=allow_device) def add_from_isbn(self, *args): from calibre.gui2.dialogs.add_from_isbn import AddFromISBN d = AddFromISBN(self.gui) if d.exec() == QDialog.DialogCode.Accepted and d.books: self.add_isbns(d.books, add_tags=d.set_tags, check_for_existing=d.check_for_existing) def add_books(self, *args): ''' Add books from the local filesystem to either the library or the device. ''' filters = get_filters() to_device = self.gui.stack.currentIndex() != 0 if to_device: fmts = self.gui.device_manager.device.settings().format_map filters = [(_('Supported books'), fmts)] books = choose_files_and_remember_all_files(self.gui, 'add books dialog dir', _('Select books'), filters=filters) if not books: return self._add_books(books, to_device) def _add_books(self, paths, to_device, on_card=None): if on_card is None: on_card = 'carda' if self.gui.stack.currentIndex() == 2 else \ 'cardb' if self.gui.stack.currentIndex() == 3 else None if not paths: return from calibre.gui2.add import Adder Adder(paths, db=None if to_device else self.gui.current_db, parent=self.gui, callback=partial(self._files_added, on_card=on_card), pool=self.gui.spare_pool()) def refresh_gui(self, num, set_current_row=-1, recount=True): self.gui.library_view.model().books_added(num) if set_current_row > -1: self.gui.library_view.set_current_row(0) self.gui.refresh_cover_browser() if recount: self.gui.tags_view.recount() def _files_added(self, adder, on_card=None): if adder.items: paths, infos, names = [], [], [] for mi, cover_path, format_paths in adder.items: mi.cover = cover_path paths.append(format_paths[0]), infos.append(mi) names.append(ascii_filename(os.path.basename(paths[-1]))) self.gui.upload_books(paths, names, infos, on_card=on_card) self.gui.status_bar.show_message( _('Uploading books to device.'), 2000) return if adder.number_of_books_added > 0: self.refresh_gui(adder.number_of_books_added, set_current_row=0) if adder.merged_books: merged = defaultdict(list) for title, author in adder.merged_books: merged[author].append(title) lines = [] for author in sorted(merged, key=sort_key): lines.append(f'<b><i>{prepare_string_for_xml(author)}</i></b><ol style="margin-top: 0">') for title in sorted(merged[author]): lines.append(f'<li>{prepare_string_for_xml(title)}</li>') lines.append('</ol>') pm = ngettext('The following duplicate book was found.', 'The following {} duplicate books were found.', len(adder.merged_books)).format(len(adder.merged_books)) info_dialog(self.gui, _('Merged some books'), pm + ' ' + _('Incoming book formats were processed and merged into your ' 'calibre database according to your auto-merge ' 'settings. Click "Show details" to see the list of merged books.'), det_msg='\n'.join(lines), show=True, only_copy_details=True) if adder.number_of_books_added > 0 or adder.merged_books: # The formats of the current book could have changed if # automerge is enabled current_idx = self.gui.library_view.currentIndex() if current_idx.isValid(): self.gui.library_view.model().current_changed(current_idx, current_idx) def _add_from_device_adder(self, adder, on_card=None, model=None): self._files_added(adder, on_card=on_card) # set the in-library flags, and as a consequence send the library's # metadata for this book to the device. This sets the uuid to the # correct value. Note that set_books_in_library might sync_booklists self.gui.set_books_in_library(booklists=[model.db], reset=True) self.gui.refresh_ondevice() def add_books_from_device(self, view, paths=None): backloading_err = self.gui.device_manager.device.BACKLOADING_ERROR_MESSAGE if backloading_err is not None: return error_dialog(self.gui, _('Add to library'), backloading_err, show=True) if paths is None: rows = view.selectionModel().selectedRows() if not rows or len(rows) == 0: d = error_dialog(self.gui, _('Add to library'), _('No book selected')) d.exec() return paths = [p for p in view.model().paths(rows) if p is not None] ve = self.gui.device_manager.device.VIRTUAL_BOOK_EXTENSIONS def ext(x): ans = os.path.splitext(x)[1] ans = ans[1:] if len(ans) > 1 else ans return ans.lower() remove = {p for p in paths if ext(p) in ve} if remove: paths = [p for p in paths if p not in remove] vmsg = getattr(self.gui.device_manager.device, 'VIRTUAL_BOOK_EXTENSION_MESSAGE', None) or _( 'The following books are virtual and cannot be added' ' to the calibre library:') info_dialog(self.gui, _('Not Implemented'), vmsg, '\n'.join(remove), show=True) if not paths: return if not paths or len(paths) == 0: d = error_dialog(self.gui, _('Add to library'), _('No book files found')) d.exec() return self.gui.device_manager.prepare_addable_books(self.Dispatcher(partial( self.books_prepared, view)), paths) self.bpd = ProgressDialog(_('Downloading books'), msg=_('Downloading books from device'), parent=self.gui, cancelable=False) QTimer.singleShot(1000, self.show_bpd) def show_bpd(self): if self.bpd is not None: self.bpd.show() def books_prepared(self, view, job): self.bpd.hide() self.bpd = None if job.exception is not None: self.gui.device_job_exception(job) return paths = job.result ok_paths = [x for x in paths if isinstance(x, string_or_bytes)] failed_paths = [x for x in paths if isinstance(x, tuple)] if failed_paths: if not ok_paths: msg = _('Could not download files from the device') typ = error_dialog else: msg = _('Could not download some files from the device') typ = warning_dialog det_msg = [x[0]+ '\n ' + as_unicode(x[1]) for x in failed_paths] det_msg = '\n\n'.join(det_msg) typ(self.gui, _('Could not download files'), msg, det_msg=det_msg, show=True) if ok_paths: from calibre.gui2.add import Adder callback = partial(self._add_from_device_adder, on_card=None, model=view.model()) Adder(ok_paths, db=self.gui.current_db, parent=self.gui, callback=callback, pool=self.gui.spare_pool())
32,216
Python
.py
649
37.112481
154
0.568603
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,926
__init__.py
kovidgoyal_calibre/src/calibre/gui2/actions/__init__.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from functools import partial from zipfile import ZipFile from qt.core import QAction, QIcon, QKeySequence, QMenu, QObject, QPoint, QTimer, QToolButton from calibre import prints from calibre.constants import ismacos from calibre.gui2 import Dispatcher from calibre.gui2.keyboard import NameConflict from polyglot.builtins import string_or_bytes def toolbar_widgets_for_action(gui, action): # Search the toolbars for the widget associated with an action, passing # them to the caller for further processing for x in gui.bars_manager.bars: try: w = x.widgetForAction(action) # It seems that multiple copies of the action can exist, such as # when the device-connected menu is changed while the device is # connected. Use the one that has an actual position. if w is None or w.pos().x() == 0: continue # The button might be hidden if not w.isVisible(): continue yield(w) except Exception: continue def show_menu_under_widget(gui, menu, action, name): # First try the tool bar for w in toolbar_widgets_for_action(gui, action): try: # The w.height() assures that the menu opens below the button. menu.exec(w.mapToGlobal(QPoint(0, w.height()))) return except Exception: continue # Now try the menu bar for x in gui.bars_manager.menu_bar.added_actions: # This depends on no two menus with the same name. # I don't know if this works on a Mac if x.text() == name: try: # The menu item might be hidden if not x.isVisible(): continue # We can't use x.trigger() because it doesn't put the menu # in the right place. Instead get the position of the menu # widget on the menu bar p = x.parent().menu_bar r = p.actionGeometry(x) # Make sure that the menu item is actually displayed in the menu # and not the overflow if p.geometry().width() < (r.x() + r.width()): continue # Show the menu under the name in the menu bar menu.exec(p.mapToGlobal(QPoint(r.x()+2, r.height()-2))) return except Exception: continue # No visible button found. Fall back to displaying in upper left corner # of the library view. menu.exec(gui.library_view.mapToGlobal(QPoint(10, 10))) def menu_action_unique_name(plugin, unique_name): return '%s : menu action : %s'%(plugin.unique_name, unique_name) class InterfaceAction(QObject): ''' A plugin representing an "action" that can be taken in the graphical user interface. All the items in the toolbar and context menus are implemented by these plugins. Note that this class is the base class for these plugins, however, to integrate the plugin with calibre's plugin system, you have to make a wrapper class that references the actual plugin. See the :mod:`calibre.customize.builtins` module for examples. If two :class:`InterfaceAction` objects have the same name, the one with higher priority takes precedence. Sub-classes should implement the :meth:`genesis`, :meth:`library_changed`, :meth:`location_selected`, :meth:`shutting_down`, :meth:`initialization_complete` and :meth:`tag_browser_context_action` methods. Once initialized, this plugin has access to the main calibre GUI via the :attr:`gui` member. You can access other plugins by name, for example:: self.gui.iactions['Save To Disk'] To access the actual plugin, use the :attr:`interface_action_base_plugin` attribute, this attribute only becomes available after the plugin has been initialized. Useful if you want to use methods from the plugin class like do_user_config(). The QAction specified by :attr:`action_spec` is automatically create and made available as ``self.qaction``. ''' #: The plugin name. If two plugins with the same name are present, the one #: with higher priority takes precedence. name = 'Implement me' #: The plugin priority. If two plugins with the same name are present, the one #: with higher priority takes precedence. priority = 1 #: The menu popup type for when this plugin is added to a toolbar popup_type = QToolButton.ToolButtonPopupMode.MenuButtonPopup #: Whether this action should be auto repeated when its shortcut #: key is held down. auto_repeat = False #: Of the form: (text, icon_path, tooltip, keyboard shortcut). #: icon, tooltip and keyboard shortcut can be None. #: keyboard shortcut must be either a string, None or tuple of shortcuts. #: If None, a keyboard shortcut corresponding to the action is not #: registered. If you pass an empty tuple, then the shortcut is registered #: with no default key binding. action_spec = ('text', 'icon', None, None) #: If not None, used for the name displayed to the user when customizing #: the keyboard shortcuts for the above action spec instead of action_spec[0] action_shortcut_name = None #: If True, a menu is automatically created and added to self.qaction action_add_menu = False #: If True, a clone of self.qaction is added to the menu of self.qaction #: If you want the text of this action to be different from that of #: self.qaction, set this variable to the new text action_menu_clone_qaction = False #: Set of locations to which this action must not be added. #: See :attr:`all_locations` for a list of possible locations dont_add_to = frozenset() #: Set of locations from which this action must not be removed. #: See :attr:`all_locations` for a list of possible locations dont_remove_from = frozenset() all_locations = frozenset(['toolbar', 'toolbar-device', 'context-menu', 'context-menu-device', 'toolbar-child', 'menubar', 'menubar-device', 'context-menu-cover-browser', 'context-menu-split', 'searchbar']) #: Type of action #: 'current' means acts on the current view #: 'global' means an action that does not act on the current view, but rather #: on calibre as a whole action_type = 'global' #: If True, then this InterfaceAction will have the opportunity to interact #: with drag and drop events. See the methods, :meth:`accept_enter_event`, #: :meth`:accept_drag_move_event`, :meth:`drop_event` for details. accepts_drops = False def __init__(self, parent, site_customization): QObject.__init__(self, parent) self.setObjectName(self.name) self.gui = parent self.site_customization = site_customization self.interface_action_base_plugin = None def accept_enter_event(self, event, mime_data): ''' This method should return True iff this interface action is capable of handling the drag event. Do not call accept/ignore on the event, that will be taken care of by the calibre UI.''' return False def accept_drag_move_event(self, event, mime_data): ''' This method should return True iff this interface action is capable of handling the drag event. Do not call accept/ignore on the event, that will be taken care of by the calibre UI.''' return False def drop_event(self, event, mime_data): ''' This method should perform some useful action and return True iff this interface action is capable of handling the drop event. Do not call accept/ignore on the event, that will be taken care of by the calibre UI. You should not perform blocking/long operations in this function. Instead emit a signal or use QTimer.singleShot and return quickly. See the builtin actions for examples.''' return False def do_genesis(self): self.Dispatcher = partial(Dispatcher, parent=self) self.create_action() self.gui.addAction(self.qaction) self.gui.addAction(self.menuless_qaction) self.genesis() self.location_selected('library') @property def unique_name(self): bn = self.__class__.__name__ if getattr(self.interface_action_base_plugin, 'name'): bn = self.interface_action_base_plugin.name return 'Interface Action: %s (%s)'%(bn, self.name) def create_action(self, spec=None, attr='qaction', shortcut_name=None, persist_shortcut=False): if spec is None: spec = self.action_spec text, icon, tooltip, shortcut = spec if icon is not None: action = QAction(QIcon.ic(icon), text, self.gui) else: action = QAction(text, self.gui) if attr == 'qaction': if hasattr(self.action_menu_clone_qaction, 'rstrip'): mt = str(self.action_menu_clone_qaction) else: mt = action.text() self.menuless_qaction = ma = QAction(action.icon(), mt, self.gui) ma.triggered.connect(action.trigger) for a in ((action, ma) if attr == 'qaction' else (action,)): a.setAutoRepeat(self.auto_repeat) text = tooltip if tooltip else text a.setToolTip(text) a.setStatusTip(text) a.setWhatsThis(text) shortcut_action = action desc = tooltip if tooltip else None if attr == 'qaction': shortcut_action = ma if shortcut is not None: keys = ((shortcut,) if isinstance(shortcut, string_or_bytes) else tuple(shortcut)) if shortcut_name is None: if self.action_shortcut_name is not None: shortcut_name = self.action_shortcut_name elif spec[0]: shortcut_name = str(spec[0]) if shortcut_name and self.action_spec[0] and not ( attr == 'qaction' and self.popup_type == QToolButton.ToolButtonPopupMode.InstantPopup): try: self.gui.keyboard.register_shortcut(self.unique_name + ' - ' + attr, shortcut_name, default_keys=keys, action=shortcut_action, description=desc, group=self.action_spec[0], persist_shortcut=persist_shortcut) except NameConflict as e: try: prints(str(e)) except: pass shortcut_action.setShortcuts([QKeySequence(key, QKeySequence.SequenceFormat.PortableText) for key in keys]) else: self.shortcut_action_for_context_menu = shortcut_action if ismacos: # In Qt 5 keyboard shortcuts dont work unless the # action is explicitly added to the main window self.gui.addAction(shortcut_action) if attr is not None: setattr(self, attr, action) if attr == 'qaction' and self.action_add_menu: menu = QMenu() action.setMenu(menu) if self.action_menu_clone_qaction: menu.addAction(self.menuless_qaction) return action def create_menu_action(self, menu, unique_name, text, icon=None, shortcut=None, description=None, triggered=None, shortcut_name=None, persist_shortcut=False): ''' Convenience method to easily add actions to a QMenu. Returns the created QAction. This action has one extra attribute calibre_shortcut_unique_name which if not None refers to the unique name under which this action is registered with the keyboard manager. :param menu: The QMenu the newly created action will be added to :param unique_name: A unique name for this action, this must be globally unique, so make it as descriptive as possible. If in doubt, add an UUID to it. :param text: The text of the action. :param icon: Either a QIcon or a file name. The file name is passed to the QIcon.ic() builtin, so you do not need to pass the full path to the images folder. :param shortcut: A string, a list of strings, None or False. If False, no keyboard shortcut is registered for this action. If None, a keyboard shortcut with no default keybinding is registered. String and list of strings register a shortcut with default keybinding as specified. :param description: A description for this action. Used to set tooltips. :param triggered: A callable which is connected to the triggered signal of the created action. :param shortcut_name: The text displayed to the user when customizing the keyboard shortcuts for this action. By default it is set to the value of ``text``. :param persist_shortcut: Shortcuts for actions that don't always appear, or are library dependent, may disappear when other keyboard shortcuts are edited unless ```persist_shortcut``` is set True. ''' if shortcut_name is None: shortcut_name = str(text) ac = menu.addAction(text) if icon is not None: if not isinstance(icon, QIcon): icon = QIcon.ic(icon) ac.setIcon(icon) keys = () if shortcut is not None and shortcut is not False: keys = ((shortcut,) if isinstance(shortcut, string_or_bytes) else tuple(shortcut)) unique_name = menu_action_unique_name(self, unique_name) if description is not None: ac.setToolTip(description) ac.setStatusTip(description) ac.setWhatsThis(description) ac.calibre_shortcut_unique_name = unique_name if shortcut is not False: self.gui.keyboard.register_shortcut(unique_name, shortcut_name, default_keys=keys, action=ac, description=description, group=self.action_spec[0], persist_shortcut=persist_shortcut) # In Qt 5 keyboard shortcuts dont work unless the # action is explicitly added to the main window and on OSX and # Unity since the menu might be exported, the shortcuts won't work self.gui.addAction(ac) if triggered is not None: ac.triggered.connect(triggered) return ac def load_resources(self, names): ''' If this plugin comes in a ZIP file (user added plugin), this method will allow you to load resources from the ZIP file. For example to load an image:: pixmap = QPixmap() pixmap.loadFromData(tuple(self.load_resources(['images/icon.png']).values())[0]) icon = QIcon(pixmap) :param names: List of paths to resources in the ZIP file using / as separator :return: A dictionary of the form ``{name : file_contents}``. Any names that were not found in the ZIP file will not be present in the dictionary. ''' if self.plugin_path is None: raise ValueError('This plugin was not loaded from a ZIP file') ans = {} with ZipFile(self.plugin_path, 'r') as zf: for candidate in zf.namelist(): if candidate in names: ans[candidate] = zf.read(candidate) return ans def genesis(self): ''' Setup this plugin. Only called once during initialization. self.gui is available. The action specified by :attr:`action_spec` is available as ``self.qaction``. ''' pass def location_selected(self, loc): ''' Called whenever the book list being displayed in calibre changes. Currently values for loc are: ``library, main, card and cardb``. This method should enable/disable this action and its sub actions as appropriate for the location. ''' pass def library_about_to_change(self, olddb, db): ''' Called whenever the current library is changed. :param olddb: The LibraryDatabase corresponding to the previous library. :param db: The LibraryDatabase corresponding to the new library. ''' pass def library_changed(self, db): ''' Called whenever the current library is changed. :param db: The LibraryDatabase corresponding to the current library. ''' pass def gui_layout_complete(self): ''' Called once per action when the layout of the main GUI is completed. If your action needs to make changes to the layout, they should be done here, rather than in :meth:`initialization_complete`. ''' pass def initialization_complete(self): ''' Called once per action when the initialization of the main GUI is completed. ''' pass def tag_browser_context_action(self, index): ''' Called when displaying the context menu in the Tag browser. ``index`` is the QModelIndex that points to the Tag browser item that was right clicked. Test it for validity with index.valid() and get the underlying TagTreeItem object with index.data(Qt.ItemDataRole.UserRole). Any action objects yielded by this method will be added to the context menu. ''' if False: yield QAction() def shutting_down(self): ''' Called once per plugin when the main GUI is in the process of shutting down. Release any used resources, but try not to block the shutdown for long periods of time. ''' pass class InterfaceActionWithLibraryDrop(InterfaceAction): ''' Subclass of InterfaceAction that implements methods to execute the default action by drop some books from the library. Inside the do_drop() method, the ids of the dropped books are provided by the attribute self.dropped_ids ''' accepts_drops = True mimetype_for_drop = 'application/calibre+from_library' def accept_enter_event(self, event, mime_data): if mime_data.hasFormat(self.mimetype_for_drop): return True return False def accept_drag_move_event(self, event, mime_data): if mime_data.hasFormat(self.mimetype_for_drop): return True return False def drop_event(self, event, mime_data): if mime_data.hasFormat(self.mimetype_for_drop): self.dropped_ids = tuple(map(int, mime_data.data(self.mimetype_for_drop).data().split())) QTimer.singleShot(1, self.do_drop) return True return False def do_drop(self): raise NotImplementedError()
19,347
Python
.py
398
38.628141
107
0.639807
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,927
next_match.py
kovidgoyal_calibre/src/calibre/gui2/actions/next_match.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from calibre.gui2.actions import InterfaceAction class NextMatchAction(InterfaceAction): name = 'Move to next highlighted book' action_spec = (_('Move to next match'), 'arrow-down.png', _('Move to next highlighted match'), [_('N'), _('F3')]) dont_add_to = frozenset(('context-menu-device',)) action_type = 'current' def genesis(self): ''' Setup this plugin. Only called once during initialization. self.gui is available. The action specified by :attr:`action_spec` is available as ``self.qaction``. ''' self.can_move = None self.qaction.triggered.connect(self.move_forward) self.create_action(spec=(_('Move to previous item'), 'arrow-up.png', _('Move to previous highlighted item'), ['Shift+N', 'Shift+F3']), attr='p_action') self.gui.addAction(self.p_action) self.p_action.triggered.connect(self.move_backward) def location_selected(self, loc): self.can_move = loc == 'library' def move_forward(self): if self.can_move is None: self.can_move = self.gui.current_view() is self.gui.library_view if self.can_move: self.gui.current_view().move_highlighted_row(forward=True) def move_backward(self): if self.can_move is None: self.can_move = self.gui.current_view() is self.gui.library_view if self.can_move: self.gui.current_view().move_highlighted_row(forward=False)
1,664
Python
.py
36
38.138889
78
0.635745
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,928
similar_books.py
kovidgoyal_calibre/src/calibre/gui2/actions/similar_books.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from qt.core import QToolButton from calibre.gui2.actions import InterfaceAction from calibre.startup import connect_lambda from calibre.utils.icu import lower as icu_lower from polyglot.builtins import string_or_bytes class SimilarBooksAction(InterfaceAction): name = 'Similar Books' action_spec = (_('Similar books'), 'similar.png', _('Show books similar to the current book'), None) popup_type = QToolButton.ToolButtonPopupMode.InstantPopup action_type = 'current' action_add_menu = True def genesis(self): m = self.qaction.menu() for text, icon, target, shortcut in [ (_('Books by same author'), 'user_profile.png', 'authors', 'Alt+A'), (_('Books in this series'), 'books_in_series.png', 'series', 'Alt+Shift+S'), (_('Books by this publisher'), 'publisher.png', 'publisher', 'Alt+P'), (_('Books with the same tags'), 'tags.png', 'tags', 'Alt+T'),]: ac = self.create_action(spec=(text, icon, None, shortcut), attr=target) ac.setObjectName(target) m.addAction(ac) connect_lambda(ac.triggered, self, lambda self: self.show_similar_books(self.gui.sender().objectName())) self.qaction.setMenu(m) def show_similar_books(self, typ, *args): idx = self.gui.library_view.currentIndex() if not idx.isValid(): return db = idx.model().db row = idx.row() # Get the parameters for this search key = 'similar_' + typ + '_search_key' col = db.prefs[key] match = db.prefs['similar_' + typ + '_match_kind'] if match == 'match_all': join = ' and ' else: join = ' or ' # Get all the data for the current record mi = db.get_metadata(row) # Get the definitive field name to use for this search. If the field # is a grouped search term, the function returns the list of fields that # are to be searched, otherwise it returns the field name. loc = db.field_metadata.search_term_to_field_key(icu_lower(col)) if isinstance(loc, list): # Grouped search terms are a list of fields. Get all the values, # pruning duplicates val = set() for f in loc: v = mi.get(f, None) if not v: continue v = db.new_api.split_if_is_multiple_composite(f, v) if isinstance(v, list): val.update(v) else: val.add(v) else: # Get the value of the requested field. Can be a list or a simple # val. It is possible that col no longer exists, in which case fall # back to the default if col not in mi.all_field_keys(): col = db.prefs.defaults[key] val = mi.get(col, None) if not val: return if isinstance(val, string_or_bytes): val = [val] search = [col + ':"='+t.replace('"', '\\"')+'"' for t in val] if search: self.gui.search.set_search_string(join.join(search), store_in_history=True)
3,391
Python
.py
77
33.818182
116
0.578182
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,929
edit_collections.py
kovidgoyal_calibre/src/calibre/gui2/actions/edit_collections.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from calibre.gui2 import error_dialog from calibre.gui2.actions import InterfaceAction class EditCollectionsAction(InterfaceAction): name = 'Edit Collections' action_spec = (_('Manage collections'), None, _('Manage the collections on this device'), ()) dont_add_to = frozenset(('menubar', 'toolbar', 'context-menu', 'toolbar-child')) action_type = 'current' def genesis(self): self.qaction.triggered.connect(self.edit_collections) def location_selected(self, loc): enabled = loc != 'library' self.qaction.setEnabled(enabled) self.menuless_qaction.setEnabled(enabled) def edit_collections(self, *args): oncard = None cv = self.gui.current_view() if cv is self.gui.library_view: return error_dialog(self.gui, _('In library view'), _( 'Collections can only be edited when showing the books on the device. Click the toolbar button to switch to the device view first.'), show=True) if cv is self.gui.card_a_view: oncard = 'carda' elif cv is self.gui.card_b_view: oncard = 'cardb' self.gui.iactions['Edit Metadata'].edit_device_collections(cv, oncard=oncard)
1,394
Python
.py
30
38.9
160
0.658303
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,930
catalog.py
kovidgoyal_calibre/src/calibre/gui2/actions/catalog.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os import re import shutil from qt.core import QModelIndex from calibre import sanitize_file_name from calibre.gui2 import choose_dir, error_dialog, warning_dialog from calibre.gui2.actions import InterfaceAction from calibre.gui2.tools import generate_catalog from calibre.utils.config import dynamic class GenerateCatalogAction(InterfaceAction): name = 'Generate Catalog' action_spec = (_('Create catalog'), 'catalog.png', _('Create a catalog of the books in your calibre library in different formats'), ()) dont_add_to = frozenset(('context-menu-device',)) def genesis(self): self.qaction.triggered.connect(self.generate_catalog) def location_selected(self, loc): enabled = loc == 'library' self.qaction.setEnabled(enabled) self.menuless_qaction.setEnabled(enabled) def generate_catalog(self): rows = self.gui.library_view.selectionModel().selectedRows() if not rows or len(rows) < 2: rows = range(self.gui.library_view.model().rowCount(QModelIndex())) ids = list(map(self.gui.library_view.model().id, rows)) if not ids: return error_dialog(self.gui, _('No books selected'), _('No books selected for catalog generation'), show=True) db = self.gui.library_view.model().db dbspec = {} for id in ids: dbspec[id] = {'ondevice': db.ondevice(id, index_is_id=True)} # Calling gui2.tools:generate_catalog() ret = generate_catalog(self.gui, dbspec, ids, self.gui.device_manager, db) if ret is None: return func, args, desc, out, sync, title = ret fmt = os.path.splitext(out)[1][1:].upper() job = self.gui.job_manager.run_job( self.Dispatcher(self.catalog_generated), func, args=args, description=desc) job.catalog_file_path = out job.fmt = fmt job.catalog_sync, job.catalog_title = sync, title self.gui.status_bar.show_message(_('Generating %s catalog...')%fmt) def catalog_generated(self, job): if job.result: # Problems during catalog generation # jobs.results is a list - the first entry is the intended title for the dialog # Subsequent strings are error messages dialog_title = job.result.pop(0) if re.search('warning', job.result[0].lower()): msg = _("Catalog generation complete, with warnings.") warning_dialog(self.gui, dialog_title, msg, det_msg='\n'.join(job.result), show=True) else: job.result.append("Catalog generation terminated.") error_dialog(self.gui, dialog_title,'\n'.join(job.result),show=True) return if job.failed: return self.gui.job_exception(job) if dynamic.get('catalog_add_to_library', True): id = self.gui.library_view.model().add_catalog(job.catalog_file_path, job.catalog_title) self.gui.library_view.model().beginResetModel(), self.gui.library_view.model().endResetModel() if job.catalog_sync: sync = dynamic.get('catalogs_to_be_synced', set()) sync.add(id) dynamic.set('catalogs_to_be_synced', sync) self.gui.status_bar.show_message(_('Catalog generated.'), 3000) self.gui.sync_catalogs() if not dynamic.get('catalog_add_to_library', True) or job.fmt not in {'EPUB','MOBI', 'AZW3'}: export_dir = choose_dir(self.gui, _('Export catalog folder'), _('Select destination for %(title)s.%(fmt)s') % dict( title=job.catalog_title, fmt=job.fmt.lower())) if export_dir: destination = os.path.join(export_dir, '{}.{}'.format( sanitize_file_name(job.catalog_title), job.fmt.lower())) try: shutil.copyfile(job.catalog_file_path, destination) except OSError as err: err.locking_violation_msg = _('Could not open the catalog output file.') raise
4,372
Python
.py
87
39.356322
106
0.611905
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,931
copy_to_library.py
kovidgoyal_calibre/src/calibre/gui2/actions/copy_to_library.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os from collections import defaultdict from contextlib import closing from functools import partial from threading import Thread from qt.core import ( QAbstractItemView, QApplication, QCheckBox, QDialog, QDialogButtonBox, QFormLayout, QGridLayout, QHBoxLayout, QIcon, QLabel, QLineEdit, QListWidget, QListWidgetItem, QScrollArea, QSize, Qt, QToolButton, QVBoxLayout, QWidget, ) from calibre import as_unicode from calibre.constants import ismacos from calibre.db.copy_to_library import copy_one_book from calibre.gui2 import Dispatcher, choose_dir, error_dialog, gprefs, info_dialog, warning_dialog from calibre.gui2.actions import InterfaceAction from calibre.gui2.actions.choose_library import library_qicon from calibre.gui2.dialogs.progress import ProgressDialog from calibre.gui2.widgets2 import Dialog from calibre.startup import connect_lambda from calibre.utils.config import prefs from calibre.utils.icu import numeric_sort_key, sort_key from calibre.utils.localization import ngettext from polyglot.builtins import iteritems, itervalues def ask_about_cc_mismatch(gui, db, newdb, missing_cols, incompatible_cols): # {{{ source_metadata = db.field_metadata.custom_field_metadata(include_composites=True) dest_library_path = newdb.library_path ndbname = os.path.basename(dest_library_path) d = QDialog(gui) d.setWindowTitle(_('Different custom columns')) l = QFormLayout() tl = QVBoxLayout() d.setLayout(tl) d.s = QScrollArea(d) tl.addWidget(d.s) d.w = QWidget(d) d.s.setWidget(d.w) d.s.setWidgetResizable(True) d.w.setLayout(l) d.setMinimumWidth(600) d.setMinimumHeight(500) d.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel) msg = _('The custom columns in the <i>{0}</i> library are different from the ' 'custom columns in the <i>{1}</i> library. As a result, some metadata might not be copied.').format( os.path.basename(db.library_path), ndbname) d.la = la = QLabel(msg) la.setWordWrap(True) la.setStyleSheet('QLabel { margin-bottom: 1.5ex }') l.addRow(la) if incompatible_cols: la = d.la2 = QLabel(_('The following columns are incompatible - they have the same name' ' but different data types. They will be ignored: ') + ', '.join(sorted(incompatible_cols, key=sort_key))) la.setWordWrap(True) la.setStyleSheet('QLabel { margin-bottom: 1.5ex }') l.addRow(la) missing_widgets = [] if missing_cols: la = d.la3 = QLabel(_('The following columns are missing in the <i>{0}</i> library.' ' You can choose to add them automatically below.').format( ndbname)) la.setWordWrap(True) l.addRow(la) for k in missing_cols: widgets = (k, QCheckBox(_('Add to the %s library') % ndbname)) l.addRow(QLabel(k), widgets[1]) missing_widgets.append(widgets) d.la4 = la = QLabel(_('This warning is only shown once per library, per session')) la.setWordWrap(True) tl.addWidget(la) tl.addWidget(d.bb) d.bb.accepted.connect(d.accept) d.bb.rejected.connect(d.reject) d.resize(d.sizeHint()) if d.exec() == QDialog.DialogCode.Accepted: changes_made = False for k, cb in missing_widgets: if cb.isChecked(): col_meta = source_metadata[k] newdb.create_custom_column( col_meta['label'], col_meta['name'], col_meta['datatype'], len(col_meta['is_multiple']) > 0, col_meta['is_editable'], col_meta['display']) changes_made = True if changes_made: # Unload the db so that the changes are available # when it is next accessed from calibre.gui2.ui import get_gui library_broker = get_gui().library_broker library_broker.unload_library(dest_library_path) return True return False # }}} class Worker(Thread): # {{{ def __init__(self, ids, db, loc, progress, done, delete_after, add_duplicates): Thread.__init__(self) self.was_canceled = False self.ids = ids self.processed = set() self.db = db self.loc = loc self.error = None self.progress = progress self.done = done self.left_after_cancel = 0 self.delete_after = delete_after self.auto_merged_ids = {} self.add_duplicates = add_duplicates self.duplicate_ids = {} self.check_for_duplicates = not add_duplicates and (prefs['add_formats_to_existing'] or prefs['check_for_dupes_on_ctl']) self.failed_books = {} def cancel_processing(self): self.was_canceled = True def run(self): try: self.doit() except Exception as err: import traceback try: err = str(err) except: err = repr(err) self.error = (err, traceback.format_exc()) self.done() def doit(self): from calibre.gui2.ui import get_gui library_broker = get_gui().library_broker newdb = library_broker.get_library(self.loc) self.find_identical_books_data = None try: if self.check_for_duplicates: self.find_identical_books_data = newdb.new_api.data_for_find_identical_books() self._doit(newdb) finally: library_broker.prune_loaded_dbs() def _doit(self, newdb): for i, x in enumerate(self.ids): if self.was_canceled: self.left_after_cancel = len(self.ids) - i break try: self.do_one(i, x, newdb) except Exception as err: import traceback err = as_unicode(err) self.failed_books[x] = (err, as_unicode(traceback.format_exc())) def do_one(self, num, book_id, newdb): duplicate_action = 'add' if self.check_for_duplicates: duplicate_action = 'add_formats_to_existing' if prefs['add_formats_to_existing'] else 'ignore' rdata = copy_one_book( book_id, self.db, newdb, preserve_date=gprefs['preserve_date_on_ctl'], duplicate_action=duplicate_action, automerge_action=gprefs['automerge'], identical_books_data=self.find_identical_books_data, preserve_uuid=self.delete_after ) self.progress(num, rdata['title']) if rdata['action'] == 'automerge': self.auto_merged_ids[book_id] = _('%(title)s by %(author)s') % dict(title=rdata['title'], author=rdata['author']) elif rdata['action'] == 'duplicate': self.duplicate_ids[book_id] = (rdata['title'], rdata['authors']) self.processed.add(book_id) # }}} class ChooseLibrary(Dialog): # {{{ def __init__(self, parent, locations): self.locations = locations Dialog.__init__(self, _('Choose library'), 'copy_to_choose_library_dialog', parent) self.resort() self.current_changed() def resort(self): if self.sort_alphabetically.isChecked(): sorted_locations = sorted(self.locations, key=lambda name_loc: numeric_sort_key(name_loc[0])) else: sorted_locations = self.locations self.items.clear() for name, loc in sorted_locations: i = QListWidgetItem(name, self.items) i.setData(Qt.ItemDataRole.UserRole, loc) self.items.setCurrentRow(0) def setup_ui(self): self.l = l = QGridLayout(self) self.items = i = QListWidget(self) i.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection) i.currentItemChanged.connect(self.current_changed) l.addWidget(i) self.v = v = QVBoxLayout() l.addLayout(v, 0, 1) self.sort_alphabetically = sa = QCheckBox(_('&Sort libraries alphabetically')) v.addWidget(sa) sa.setChecked(bool(gprefs.get('copy_to_library_choose_library_sort_alphabetically', True))) sa.stateChanged.connect(self.resort) connect_lambda(sa.stateChanged, self, lambda self: gprefs.set('copy_to_library_choose_library_sort_alphabetically', bool(self.sort_alphabetically.isChecked()))) la = self.la = QLabel(_('Library &path:')) v.addWidget(la) le = self.le = QLineEdit(self) la.setBuddy(le) b = self.b = QToolButton(self) b.setIcon(QIcon.ic('document_open.png')) b.setToolTip(_('Browse for library')) b.clicked.connect(self.browse) h = QHBoxLayout() h.addWidget(le), h.addWidget(b) v.addLayout(h) v.addStretch(10) bb = self.bb bb.setStandardButtons(QDialogButtonBox.StandardButton.Cancel) self.delete_after_copy = False b = bb.addButton(_('&Copy'), QDialogButtonBox.ButtonRole.AcceptRole) b.setIcon(QIcon.ic('edit-copy.png')) b.setToolTip(_('Copy to the specified library')) b2 = bb.addButton(_('&Move'), QDialogButtonBox.ButtonRole.AcceptRole) connect_lambda(b2.clicked, self, lambda self: setattr(self, 'delete_after_copy', True)) b2.setIcon(QIcon.ic('edit-cut.png')) b2.setToolTip(_('Copy to the specified library and delete from the current library')) b.setDefault(True) l.addWidget(bb, 1, 0, 1, 2) self.items.setFocus(Qt.FocusReason.OtherFocusReason) def sizeHint(self): return QSize(800, 550) def current_changed(self): i = self.items.currentItem() or self.items.item(0) if i is not None: loc = i.data(Qt.ItemDataRole.UserRole) self.le.setText(loc) def browse(self): d = choose_dir(self, 'choose_library_for_copy', _('Choose library')) if d: self.le.setText(d) @property def args(self): return (str(self.le.text()), self.delete_after_copy) # }}} class DuplicatesQuestion(QDialog): # {{{ def __init__(self, parent, duplicates, loc): QDialog.__init__(self, parent) l = QVBoxLayout() self.setLayout(l) self.la = la = QLabel(_('Books with the same, title, author and language as the following already exist in the library %s.' ' Select which books you want copied anyway.') % os.path.basename(loc)) la.setWordWrap(True) l.addWidget(la) self.setWindowTitle(_('Duplicate books')) self.books = QListWidget(self) self.items = [] for book_id, (title, authors) in iteritems(duplicates): i = QListWidgetItem(_('{0} by {1}').format(title, ' & '.join(authors[:3])), self.books) i.setData(Qt.ItemDataRole.UserRole, book_id) i.setFlags(Qt.ItemFlag.ItemIsUserCheckable | Qt.ItemFlag.ItemIsEnabled) i.setCheckState(Qt.CheckState.Checked) self.items.append(i) l.addWidget(self.books) self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) self.a = b = bb.addButton(_('Select &all'), QDialogButtonBox.ButtonRole.ActionRole) b.clicked.connect(self.select_all), b.setIcon(QIcon.ic('plus.png')) self.n = b = bb.addButton(_('Select &none'), QDialogButtonBox.ButtonRole.ActionRole) b.clicked.connect(self.select_none), b.setIcon(QIcon.ic('minus.png')) self.ctc = b = bb.addButton(_('&Copy to clipboard'), QDialogButtonBox.ButtonRole.ActionRole) b.clicked.connect(self.copy_to_clipboard), b.setIcon(QIcon.ic('edit-copy.png')) l.addWidget(bb) self.resize(600, 400) def copy_to_clipboard(self): items = [('✓' if item.checkState() == Qt.CheckState.Checked else '✗') + ' ' + str(item.text()) for item in self.items] QApplication.clipboard().setText('\n'.join(items)) def select_all(self): for i in self.items: i.setCheckState(Qt.CheckState.Checked) def select_none(self): for i in self.items: i.setCheckState(Qt.CheckState.Unchecked) @property def ids(self): return {int(i.data(Qt.ItemDataRole.UserRole)) for i in self.items if i.checkState() == Qt.CheckState.Checked} # }}} # Static session-long set of pairs of libraries that have had their custom columns # checked for compatibility libraries_with_checked_columns = defaultdict(set) class CopyToLibraryAction(InterfaceAction): name = 'Copy To Library' action_spec = (_('Copy to library'), 'copy-to-library.png', _('Copy selected books to the specified library'), None) popup_type = QToolButton.ToolButtonPopupMode.InstantPopup dont_add_to = frozenset(['context-menu-device']) action_type = 'current' action_add_menu = True def genesis(self): self.menu = self.qaction.menu() @property def stats(self): return self.gui.iactions['Choose Library'].stats def library_changed(self, db): self.build_menus() def initialization_complete(self): self.library_changed(self.gui.library_view.model().db) def location_selected(self, loc): enabled = loc == 'library' self.qaction.setEnabled(enabled) self.menuless_qaction.setEnabled(enabled) def build_menus(self): self.menu.clear() if os.environ.get('CALIBRE_OVERRIDE_DATABASE_PATH', None): self.menu.addAction('disabled', self.cannot_do_dialog) return db = self.gui.library_view.model().db locations = list(self.stats.locations(db)) if len(locations) > 5: self.menu.addAction(_('Choose library...'), self.choose_library) self.menu.addSeparator() for name, loc in locations: ic = library_qicon(name) name = name.replace('&', '&&') self.menu.addAction(ic, name, partial(self.copy_to_library, loc)) self.menu.addAction(ic, name + ' ' + _('(delete after copy)'), partial(self.copy_to_library, loc, delete_after=True)) self.menu.addSeparator() if len(locations) <= 5: self.menu.addAction(_('Choose library...'), self.choose_library) self.qaction.setVisible(bool(locations)) if ismacos: # The cloned action has to have its menu updated self.qaction.changed.emit() def choose_library(self): db = self.gui.library_view.model().db locations = list(self.stats.locations(db)) d = ChooseLibrary(self.gui, locations) if d.exec() == QDialog.DialogCode.Accepted: path, delete_after = d.args if not path: return db = self.gui.library_view.model().db current = os.path.normcase(os.path.abspath(db.library_path)) if current == os.path.normcase(os.path.abspath(path)): return error_dialog(self.gui, _('Cannot copy'), _('Cannot copy to current library.'), show=True) self.copy_to_library(path, delete_after) def _column_is_compatible(self, source_metadata, dest_metadata): return (source_metadata['datatype'] == dest_metadata['datatype'] and (source_metadata['datatype'] != 'text' or source_metadata['is_multiple'] == dest_metadata['is_multiple'])) def copy_to_library(self, loc, delete_after=False): rows = self.gui.library_view.selectionModel().selectedRows() if not rows or len(rows) == 0: return error_dialog(self.gui, _('Cannot copy'), _('No books selected'), show=True) ids = list(map(self.gui.library_view.model().id, rows)) db = self.gui.library_view.model().db if not db.exists_at(loc): return error_dialog(self.gui, _('No library'), _('No library found at %s')%loc, show=True) # Open the new db so we can check the custom columns. We use only the # backend since we only need the custom column definitions, not the # rest of the data in the db. We also do not want the user defined # formatter functions because loading them can poison the template cache global libraries_with_checked_columns from calibre.db.legacy import create_backend newdb = create_backend(loc, load_user_formatter_functions=False) continue_processing = True with closing(newdb): if newdb.library_id not in libraries_with_checked_columns[db.library_id]: newdb_meta = newdb.field_metadata.custom_field_metadata() incompatible_columns = [] missing_columns = [] for k, m in db.field_metadata.custom_iteritems(): if k not in newdb_meta: missing_columns.append(k) elif not self._column_is_compatible(m, newdb_meta[k]): # Note that composite columns are always assumed to be # compatible. No attempt is made to copy the template # from the source to the destination. incompatible_columns.append(k) if missing_columns or incompatible_columns: continue_processing = ask_about_cc_mismatch(self.gui, db, newdb, missing_columns, incompatible_columns) if continue_processing: libraries_with_checked_columns[db.library_id].add(newdb.library_id) newdb.close() del newdb if not continue_processing: return duplicate_ids = self.do_copy(ids, db, loc, delete_after, False) if duplicate_ids: d = DuplicatesQuestion(self.gui, duplicate_ids, loc) if d.exec() == QDialog.DialogCode.Accepted: ids = d.ids if ids: self.do_copy(list(ids), db, loc, delete_after, add_duplicates=True) def do_copy(self, ids, db, loc, delete_after, add_duplicates=False): aname = _('Moving to') if delete_after else _('Copying to') dtitle = '%s %s'%(aname, os.path.basename(loc)) self.pd = ProgressDialog(dtitle, min=0, max=len(ids)-1, parent=self.gui, cancelable=True, icon='lt.png', cancel_confirm_msg=_( 'Aborting this operation means that only some books will be copied' ' and resuming a partial copy is not supported. Are you sure you want to abort?')) def progress(idx, title): self.pd.set_msg(title) self.pd.set_value(idx) self.worker = Worker(ids, db, loc, Dispatcher(progress), Dispatcher(self.pd.accept), delete_after, add_duplicates) self.worker.start() self.pd.canceled_signal.connect(self.worker.cancel_processing) self.pd.exec() self.pd.canceled_signal.disconnect() if self.worker.left_after_cancel: msg = _('The copying process was interrupted. {} books were copied.').format(len(self.worker.processed)) if delete_after: msg += ' ' + _('No books were deleted from this library.') msg += ' ' + _('The best way to resume this operation is to re-copy all the books with the option to' ' "Check for duplicates when copying to library" in Preferences->Import/export->Adding books turned on.') warning_dialog(self.gui, _('Canceled'), msg, show=True) return if self.worker.error is not None: e, tb = self.worker.error error_dialog(self.gui, _('Failed'), _('Could not copy books: ') + e, det_msg=tb, show=True) return if delete_after: donemsg = _('Moved the book to {loc}') if len(self.worker.processed) == 1 else _( 'Moved {num} books to {loc}') else: donemsg = _('Copied the book to {loc}') if len(self.worker.processed) == 1 else _( 'Copied {num} books to {loc}') self.gui.status_bar.show_message(donemsg.format(num=len(self.worker.processed), loc=loc), 2000) if self.worker.auto_merged_ids: books = '\n'.join(itervalues(self.worker.auto_merged_ids)) info_dialog(self.gui, _('Auto merged'), _('Some books were automatically merged into existing ' 'records in the target library. Click "Show ' 'details" to see which ones. This behavior is ' 'controlled by the Auto-merge option in ' 'Preferences->Import/export->Adding books->Adding actions.'), det_msg=books, show=True) done_ids = frozenset(self.worker.processed) - frozenset(self.worker.duplicate_ids) if delete_after and done_ids: v = self.gui.library_view ci = v.currentIndex() row = None if ci.isValid(): row = ci.row() v.model().delete_books_by_id(done_ids, permanent=True) self.gui.iactions['Remove Books'].library_ids_deleted(done_ids, row) if self.worker.failed_books: def fmt_err(book_id): err, tb = self.worker.failed_books[book_id] title = db.title(book_id, index_is_id=True) return _('Copying: {0} failed, with error:\n{1}').format(title, tb) title, msg = _('Failed to copy some books'), _('Could not copy some books, click "Show details" for more information.') tb = '\n\n'.join(map(fmt_err, self.worker.failed_books)) tb = ngettext('Failed to copy a book, see below for details', 'Failed to copy {} books, see below for details', len(self.worker.failed_books)).format( len(self.worker.failed_books)) + '\n\n' + tb if len(ids) == len(self.worker.failed_books): title, msg = _('Failed to copy books'), _('Could not copy any books, click "Show details" for more information.') error_dialog(self.gui, title, msg, det_msg=tb, show=True) return self.worker.duplicate_ids def cannot_do_dialog(self): warning_dialog(self.gui, _('Not allowed'), _('You cannot use other libraries while using the environment' ' variable CALIBRE_OVERRIDE_DATABASE_PATH.'), show=True)
23,168
Python
.py
485
37.228866
131
0.610863
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,932
show_template_tester.py
kovidgoyal_calibre/src/calibre/gui2/actions/show_template_tester.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from calibre.gui2 import error_dialog from calibre.gui2.actions import InterfaceAction from calibre.gui2.dialogs.template_dialog import TemplateDialog class ShowTemplateTesterAction(InterfaceAction): name = 'Template tester' action_spec = (_('Template tester'), 'debug.png', None, ()) dont_add_to = frozenset(('context-menu-device',)) action_type = 'current' def genesis(self): self.previous_text = _('Enter a template to test using data from the selected book') self.first_time = True self.qaction.triggered.connect(self.show_template_editor) self.window_title = self.action_spec[0] # self.hidden_menu = QMenu() # self.non_modal_window_title = _('Template tester -- separate dialog') # self.shortcut_action = self.create_menu_action( # menu=self.hidden_menu, # unique_name='Template tester', # text=self.non_modal_window_title, # icon='debug.png', # triggered=partial(self.show_template_editor, modal=False)) self.non_modal_dialogs = list() def last_template_text(self): return self.previous_text def show_template_editor(self, *args): view = self.gui.current_view() if view is not self.gui.library_view: return error_dialog(self.gui, _('No template tester available'), _('Template tester is not available for books ' 'on the device.')).exec() rows = view.selectionModel().selectedRows() if not rows: return error_dialog(self.gui, _('No books selected'), _('At least one book must be selected'), show=True) mi = [] db = view.model().db for row in rows: if row.isValid(): mi.append(db.new_api.get_proxy_metadata(db.data.index_to_id(row.row()))) if mi: for dn in range(-1, len(self.non_modal_dialogs)): if dn < 0: continue if self.non_modal_dialogs[dn] is None: break else: dn = len(self.non_modal_dialogs) if dn == len(self.non_modal_dialogs): self.non_modal_dialogs.append(True) else: self.non_modal_dialogs[dn] = True t = TemplateDialog(self.gui, self.previous_text, mi, text_is_placeholder=self.first_time, dialog_number=dn) self.non_modal_dialogs[dn] = t t.setWindowTitle(self.window_title, dialog_number=dn+1) t.tester_closed.connect(self.save_template_text) t.show() def save_template_text(self, txt, dialog_number): if txt is not None: self.previous_text = txt self.first_time = False self.non_modal_dialogs[dialog_number] = None
3,117
Python
.py
67
35.731343
92
0.580316
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,933
browse_notes.py
kovidgoyal_calibre/src/calibre/gui2/actions/browse_notes.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> from calibre.gui2.actions import InterfaceAction class BrowseNotesAction(InterfaceAction): name = 'Browse Notes' action_spec = (_('Browse notes'), 'notes.png', _('Browse notes for authors, tags, etc. in the library'), _('Ctrl+Shift+N')) dont_add_to = frozenset(('context-menu-device',)) action_type = 'current' def genesis(self): self.d = None self.qaction.triggered.connect(self.show_browser) def show_browser(self): if self.d is not None and self.d.isVisible(): self.d.raise_and_focus() else: from calibre.gui2.library.notes import NotesBrowser self.d = NotesBrowser(self.gui) self.d.show()
818
Python
.py
19
35.210526
95
0.646465
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,934
open.py
kovidgoyal_calibre/src/calibre/gui2/actions/open.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from functools import partial from calibre.gui2.actions import InterfaceAction class OpenFolderAction(InterfaceAction): name = 'Open Folder' action_spec = (_('Open book folder'), 'document_open.png', _('Open the folder containing the current book\'s files'), _('O')) dont_add_to = frozenset(('context-menu-device',)) action_type = 'current' action_add_menu = True action_menu_clone_qaction = _('Open book folder') def genesis(self): va = self.gui.iactions['View'].view_folder self.qaction.triggered.connect(va) a = self.create_menu_action(self.qaction.menu(), 'show-data-folder', _('Open book data folder'), icon='document_open.png', shortcut=tuple()) a.triggered.connect(partial(va, data_folder=True)) def location_selected(self, loc): enabled = loc == 'library' self.qaction.setEnabled(enabled) self.menuless_qaction.setEnabled(enabled)
1,131
Python
.py
24
39.958333
103
0.65847
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,935
author_mapper.py
kovidgoyal_calibre/src/calibre/gui2/actions/author_mapper.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> from qt.core import QDialog from calibre.gui2 import gprefs from calibre.gui2.actions import InterfaceAction from calibre.utils.localization import ngettext from polyglot.builtins import iteritems class AuthorMapAction(InterfaceAction): name = 'Author Mapper' action_spec = (_('Author mapper'), 'user_profile.png', _('Transform the authors for books in the library'), None) action_type = 'current' def genesis(self): self.qaction.triggered.connect(self.start_map) def start_map(self): rows = self.gui.library_view.selectionModel().selectedRows() selected = True if not rows or len(rows) < 2: selected = False rows = range(self.gui.library_view.model().rowCount(None)) ids = set(map(self.gui.library_view.model().id, rows)) self.do_map(ids, selected) def do_map(self, book_ids, selected): from calibre.ebooks.metadata.author_mapper import compile_rules, map_authors from calibre.gui2.author_mapper import RulesDialog from calibre.gui2.widgets import BusyCursor d = RulesDialog(self.gui) d.setWindowTitle(ngettext( 'Map authors for one book in the library', 'Map authors for {} books in the library', len(book_ids)).format(len(book_ids))) d.rules = gprefs.get('library-author-mapper-ruleset', ()) txt = ngettext( 'The changes will be applied to the <b>selected book</b>', 'The changes will be applied to the <b>{} selected books</b>', len(book_ids)) if selected else ngettext( 'The changes will be applied to <b>one book in the library</b>', 'The changes will be applied to <b>{} books in the library</b>', len(book_ids)) d.edit_widget.msg_label.setText(d.edit_widget.msg_label.text() + '<p>' + txt.format(len(book_ids))) if d.exec() != QDialog.DialogCode.Accepted: return with BusyCursor(): rules = d.rules gprefs.set('library-author-mapper-ruleset', rules) rules = compile_rules(rules) db = self.gui.current_db.new_api author_map = db.all_field_for('authors', book_ids) changed_author_map = {} changed_author_sort_map = {} for book_id, authors in iteritems(author_map): authors = list(authors) new_authors = map_authors(authors, rules) if authors != new_authors: changed_author_map[book_id] = new_authors changed_author_sort_map[book_id] = db.author_sort_from_authors(new_authors) if changed_author_map: db.set_field('authors', changed_author_map) db.set_field('author_sort', changed_author_sort_map) self.gui.library_view.model().refresh_ids(tuple(changed_author_map), current_row=self.gui.library_view.currentIndex().row())
3,033
Python
.py
56
44
140
0.638814
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,936
unpack_book.py
kovidgoyal_calibre/src/calibre/gui2/actions/unpack_book.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os import shutil import weakref from qt.core import QDialog, QFrame, QGridLayout, QGroupBox, QHBoxLayout, QIcon, QLabel, QPushButton, QRadioButton, QSize, QTimer, QVBoxLayout from calibre import as_unicode from calibre.constants import ismacos from calibre.gui2 import error_dialog, gprefs, open_local_file, question_dialog from calibre.gui2.actions import InterfaceActionWithLibraryDrop from calibre.ptempfile import PersistentTemporaryDirectory, PersistentTemporaryFile from calibre.utils.config import prefs, tweaks class UnpackBook(QDialog): def __init__(self, parent, book_id, fmts, db): QDialog.__init__(self, parent) self.setWindowIcon(QIcon.ic('unpack-book.png')) self.book_id, self.fmts, self.db_ref = book_id, fmts, weakref.ref(db) self._exploded = None self._cleanup_dirs = [] self._cleanup_files = [] self.setup_ui() self.setWindowTitle(_('Unpack book') + ' - ' + db.title(book_id, index_is_id=True)) button = self.fmt_choice_buttons[0] button_map = {str(x.text()):x for x in self.fmt_choice_buttons} of = prefs['output_format'].upper() df = tweaks.get('default_tweak_format', None) lf = gprefs.get('last_tweak_format', None) if df and df.lower() == 'remember' and lf in button_map: button = button_map[lf] elif df and df.upper() in button_map: button = button_map[df.upper()] elif of in button_map: button = button_map[of] button.setChecked(True) self.init_state() for button in self.fmt_choice_buttons: button.toggled.connect(self.init_state) def init_state(self, *args): self._exploded = None self.preview_button.setEnabled(False) self.rebuild_button.setEnabled(False) self.explode_button.setEnabled(True) def setup_ui(self): # {{{ self._g = g = QHBoxLayout(self) self.setLayout(g) self._l = l = QVBoxLayout() g.addLayout(l) fmts = sorted(x.upper() for x in self.fmts) self.fmt_choice_box = QGroupBox(_('Choose the format to unpack:'), self) self._fl = fl = QHBoxLayout() self.fmt_choice_box.setLayout(self._fl) self.fmt_choice_buttons = [QRadioButton(y, self) for y in fmts] for x in self.fmt_choice_buttons: fl.addWidget(x, stretch=10 if x is self.fmt_choice_buttons[-1] else 0) l.addWidget(self.fmt_choice_box) self.fmt_choice_box.setVisible(len(fmts) > 1) self.help_label = QLabel(_('''\ <h2>About Unpack book</h2> <p>Unpack book allows you to fine tune the appearance of an e-book by making small changes to its internals. In order to use Unpack book, you need to know a little bit about HTML and CSS, technologies that are used in e-books. Follow the steps:</p> <br> <ol> <li>Click "Explode book": This will "explode" the book into its individual internal components.<br></li> <li>Right click on any individual file and select "Open with..." to edit it in your favorite text editor.<br></li> <li>When you are done: <b>close the file browser window and the editor windows you used to make your tweaks</b>. Then click the "Rebuild book" button, to update the book in your calibre library.</li> </ol>''')) self.help_label.setWordWrap(True) self._fr = QFrame() self._fr.setFrameShape(QFrame.Shape.VLine) g.addWidget(self._fr) g.addWidget(self.help_label) self._b = b = QGridLayout() left, top, right, bottom = b.getContentsMargins() top += top b.setContentsMargins(left, top, right, bottom) l.addLayout(b, stretch=10) self.explode_button = QPushButton(QIcon.ic('wizard.png'), _('&Explode book')) self.preview_button = QPushButton(QIcon.ic('view.png'), _('&Preview book')) self.cancel_button = QPushButton(QIcon.ic('window-close.png'), _('&Cancel')) self.rebuild_button = QPushButton(QIcon.ic('exec.png'), _('&Rebuild book')) self.explode_button.setToolTip( _('Explode the book to edit its components')) self.preview_button.setToolTip( _('Preview the result of your changes')) self.cancel_button.setToolTip( _('Abort without saving any changes')) self.rebuild_button.setToolTip( _('Save your changes and update the book in the calibre library')) a = b.addWidget a(self.explode_button, 0, 0, 1, 1) a(self.preview_button, 0, 1, 1, 1) a(self.cancel_button, 1, 0, 1, 1) a(self.rebuild_button, 1, 1, 1, 1) for x in ('explode', 'preview', 'cancel', 'rebuild'): getattr(self, x+'_button').clicked.connect(getattr(self, x)) self.msg = QLabel('dummy', self) self.msg.setVisible(False) self.msg.setStyleSheet(''' QLabel { text-align: center; background-color: white; color: black; border-width: 1px; border-style: solid; border-radius: 20px; font-size: x-large; font-weight: bold; } ''') self.resize(self.sizeHint() + QSize(40, 10)) # }}} def show_msg(self, msg): self.msg.setText(msg) self.msg.resize(self.size() - QSize(50, 25)) self.msg.move((self.width() - self.msg.width())//2, (self.height() - self.msg.height())//2) self.msg.setVisible(True) def hide_msg(self): self.msg.setVisible(False) def explode(self): self.show_msg(_('Exploding, please wait...')) if len(self.fmt_choice_buttons) > 1: gprefs.set('last_tweak_format', self.current_format.upper()) QTimer.singleShot(5, self.do_explode) def ask_question(self, msg): return question_dialog(self, _('Are you sure?'), msg) def do_explode(self): from calibre.ebooks.tweak import Error, WorkerError, get_tools tdir = PersistentTemporaryDirectory('_tweak_explode') self._cleanup_dirs.append(tdir) det_msg = None try: src = self.db.format(self.book_id, self.current_format, index_is_id=True, as_path=True) self._cleanup_files.append(src) exploder = get_tools(self.current_format)[0] opf = exploder(src, tdir, question=self.ask_question) except WorkerError as e: det_msg = e.orig_tb except Error as e: return error_dialog(self, _('Failed to unpack'), (_('Could not explode the %s file.')%self.current_format) + ' ' + as_unicode(e), show=True) except: import traceback det_msg = traceback.format_exc() finally: self.hide_msg() if det_msg is not None: return error_dialog(self, _('Failed to unpack'), _('Could not explode the %s file. Click "Show details" for ' 'more information.')%self.current_format, det_msg=det_msg, show=True) if opf is None: # The question was answered with No return self._exploded = tdir self.explode_button.setEnabled(False) self.preview_button.setEnabled(True) self.rebuild_button.setEnabled(True) open_local_file(tdir) def rebuild_it(self): from calibre.ebooks.tweak import WorkerError, get_tools src_dir = self._exploded det_msg = None of = PersistentTemporaryFile('_tweak_rebuild.'+self.current_format.lower()) of.close() of = of.name self._cleanup_files.append(of) try: rebuilder = get_tools(self.current_format)[1] rebuilder(src_dir, of) except WorkerError as e: det_msg = e.orig_tb except: import traceback det_msg = traceback.format_exc() finally: self.hide_msg() if det_msg is not None: error_dialog(self, _('Failed to rebuild file'), _('Failed to rebuild %s. For more information, click ' '"Show details".')%self.current_format, det_msg=det_msg, show=True) return None return of def preview(self): self.show_msg(_('Rebuilding, please wait...')) QTimer.singleShot(5, self.do_preview) def do_preview(self): rebuilt = self.rebuild_it() if rebuilt is not None: self.parent().iactions['View']._view_file(rebuilt) def rebuild(self): self.show_msg(_('Rebuilding, please wait...')) QTimer.singleShot(5, self.do_rebuild) def do_rebuild(self): rebuilt = self.rebuild_it() if rebuilt is not None: fmt = os.path.splitext(rebuilt)[1][1:].upper() with open(rebuilt, 'rb') as f: self.db.add_format(self.book_id, fmt, f, index_is_id=True) self.accept() def cancel(self): self.reject() def cleanup(self): if ismacos and self._exploded: try: import appscript self.finder = appscript.app('Finder') self.finder.Finder_windows[os.path.basename(self._exploded)].close() except: pass for f in self._cleanup_files: try: os.remove(f) except: pass for d in self._cleanup_dirs: try: shutil.rmtree(d) except: pass @property def db(self): return self.db_ref() @property def current_format(self): for b in self.fmt_choice_buttons: if b.isChecked(): return str(b.text()) class UnpackBookAction(InterfaceActionWithLibraryDrop): name = 'Unpack Book' action_spec = (_('Unpack book'), 'unpack-book.png', _('Unpack books in the EPUB, AZW3, HTMLZ formats into their individual components'), 'U') dont_add_to = frozenset(['context-menu-device']) action_type = 'current' def do_drop(self): book_ids = self.dropped_ids del self.dropped_ids if book_ids: self.do_tweak(book_ids[0]) def genesis(self): self.qaction.triggered.connect(self.tweak_book) def tweak_book(self): row = self.gui.library_view.currentIndex() if not row.isValid(): return error_dialog(self.gui, _('Cannot unpack book'), _('No book selected'), show=True) book_id = self.gui.library_view.model().id(row) self.do_tweak(book_id) def do_tweak(self, book_id): db = self.gui.library_view.model().db fmts = db.formats(book_id, index_is_id=True) or '' fmts = [x.lower().strip() for x in fmts.split(',')] tweakable_fmts = set(fmts).intersection({'epub', 'htmlz', 'azw3', 'mobi', 'azw'}) if not tweakable_fmts: return error_dialog(self.gui, _('Cannot unpack book'), _('The book must be in EPUB, HTMLZ or AZW3 formats to unpack.' '\n\nFirst convert the book to one of these formats.'), show=True) dlg = UnpackBook(self.gui, book_id, tweakable_fmts, db) dlg.exec() dlg.cleanup()
11,792
Python
.py
275
32.603636
142
0.588871
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,937
browse_annots.py
kovidgoyal_calibre/src/calibre/gui2/actions/browse_annots.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> from qt.core import Qt from calibre.gui2 import error_dialog from calibre.gui2.actions import InterfaceAction class BrowseAnnotationsAction(InterfaceAction): name = 'Browse Annotations' action_spec = (_('Browse annotations'), 'highlight.png', _('Browse highlights and bookmarks from all books in the library'), _('B')) dont_add_to = frozenset(('context-menu-device',)) action_type = 'current' def genesis(self): self.qaction.triggered.connect(self.show_browser) self._browser = None @property def browser(self): if self._browser is None: from calibre.gui2.library.annotations import AnnotationsBrowser self.gui.library_view.selection_changed.connect(self.selection_changed) self._browser = AnnotationsBrowser(self.gui) self._browser.show_book.connect(self.open_book, type=Qt.ConnectionType.QueuedConnection) self._browser.open_annotation.connect(self.open_annotation, type=Qt.ConnectionType.QueuedConnection) return self._browser def show_browser(self): self.browser.show_dialog(self.gui.library_view.get_selected_ids(as_set=True)) def library_changed(self, db): if self._browser is not None: self._browser.reinitialize() def selection_changed(self): if self._browser is not None: self._browser.selection_changed() def open_book(self, book_id, fmt): if not self.gui.library_view.select_rows({book_id}): db = self.gui.current_db.new_api title = db.field_for('title', book_id) return error_dialog(self._browser or self.gui, _('Not visible'), _( 'The book "{}" is not currently visible in the calibre library.' ' If you have a search or a Virtual library applied, first clear' ' it.').format(title), show=True) def open_annotation(self, book_id, fmt, cfi): self.gui.iactions['View'].view_format_by_id(book_id, fmt, open_at=cfi)
2,140
Python
.py
41
43.390244
112
0.669223
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,938
edit_metadata.py
kovidgoyal_calibre/src/calibre/gui2/actions/edit_metadata.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import copy import os import shutil from contextlib import contextmanager from functools import partial from io import BytesIO from qt.core import QAction, QApplication, QDialog, QIcon, QMenu, QMimeData, QModelIndex, QTimer, QUrl from calibre.db.errors import NoSuchFormat from calibre.ebooks.metadata import authors_to_string from calibre.ebooks.metadata.book.base import Metadata from calibre.ebooks.metadata.opf2 import OPF, metadata_to_opf from calibre.ebooks.metadata.sources.prefs import msprefs from calibre.gui2 import Dispatcher, error_dialog, gprefs, question_dialog from calibre.gui2.actions import InterfaceActionWithLibraryDrop from calibre.gui2.actions.show_quickview import get_quickview_action_plugin from calibre.gui2.dialogs.confirm_delete import confirm from calibre.gui2.dialogs.device_category_editor import DeviceCategoryEditor from calibre.gui2.dialogs.metadata_bulk import MetadataBulkDialog from calibre.library.comments import merge_comments from calibre.utils.config import tweaks from calibre.utils.icu import sort_key from calibre.utils.localization import ngettext from polyglot.builtins import iteritems DATA_FILES_ICON_NAME = 'unpack-book.png' class EditMetadataAction(InterfaceActionWithLibraryDrop): name = 'Edit Metadata' action_spec = (_('Edit metadata'), 'edit_input.png', _('Change the title/author/cover etc. of books'), _('E')) action_type = 'current' action_add_menu = True def do_drop(self): book_ids = self.dropped_ids del self.dropped_ids if book_ids: db = self.gui.library_view.model().db rows = [db.row(i) for i in book_ids] self.edit_metadata_for(rows, book_ids) def genesis(self): md = self.qaction.menu() cm = partial(self.create_menu_action, md) cm('individual', _('Edit metadata individually'), icon=self.qaction.icon(), triggered=partial(self.edit_metadata, False, bulk=False)) cm('bulk', _('Edit metadata in bulk'), triggered=partial(self.edit_metadata, False, bulk=True)) md.addSeparator() cm('download', _('Download metadata and covers'), icon='download-metadata.png', triggered=partial(self.download_metadata, ids=None), shortcut='Ctrl+D') self.metadata_menu = md self.metamerge_menu = mb = QMenu() cm2 = partial(self.create_menu_action, mb) cm2('merge delete', _('Merge into first selected book - delete others'), triggered=self.merge_books) mb.addSeparator() cm2('merge keep', _('Merge into first selected book - keep others'), triggered=partial(self.merge_books, safe_merge=True), shortcut='Alt+M') mb.addSeparator() cm2('merge formats', _('Merge only formats into first selected book - delete others'), triggered=partial(self.merge_books, merge_only_formats=True), shortcut='Alt+Shift+M') self.merge_menu = mb md.addSeparator() self.action_copy = cm('copy', _('Copy metadata'), icon='edit-copy.png', triggered=self.copy_metadata) self.action_paste = cm('paste', _('Paste metadata'), icon='edit-paste.png', triggered=self.paste_metadata) self.action_paste_ignore_excluded = ac = cm( 'paste_include_excluded_fields', _('Paste metadata including excluded fields'), icon='edit-paste.png', triggered=self.paste_metadata_including_excluded_fields) ac.setVisible(False) self.action_merge = cm('merge', _('Merge book records'), icon='merge_books.png', shortcut=_('M'), triggered=self.merge_books) self.action_merge.setMenu(mb) self.action_manage_data_files = cm( 'manage_data_files', _('Manage data files'), icon=DATA_FILES_ICON_NAME, triggered=self.manage_data_files) self.qaction.triggered.connect(self.edit_metadata) ac = QAction(_('Copy URL to show book in calibre'), self.gui) ac.setToolTip(_('Copy URLs to show the currently selected books in calibre, to the system clipboard')) ac.triggered.connect(self.copy_show_link) self.gui.addAction(ac) self.gui.keyboard.register_shortcut( self.unique_name + ' - ' + 'copy_show_book', ac.text(), description=ac.toolTip(), action=ac, group=self.action_spec[0]) ac = QAction(_('Copy URL to open book in calibre'), self.gui) ac.triggered.connect(self.copy_view_link) ac.setToolTip(_('Copy URLs to open the currently selected books in calibre, to the system clipboard')) self.gui.addAction(ac) self.gui.keyboard.register_shortcut( self.unique_name + ' - ' + 'copy_view_book', ac.text(), description=ac.toolTip(), action=ac, group=self.action_spec[0]) def manage_data_files(self): from calibre.gui2.dialogs.data_files_manager import DataFilesManager db = self.gui.current_db ids = self.gui.library_view.get_selected_ids() for book_id in ids: d = DataFilesManager(db, book_id, self.gui) d.exec() cr = self.gui.library_view.currentIndex().row() self.gui.library_view.model().refresh_ids(ids, cr) def _copy_links(self, lines): urls = QUrl.fromStringList(lines) cb = QApplication.instance().clipboard() md = QMimeData() md.setText('\n'.join(lines)) md.setUrls(urls) cb.setMimeData(md) def copy_show_link(self): db = self.gui.current_db ids = [db.id(row.row()) for row in self.gui.library_view.selectionModel().selectedRows()] db = db.new_api library_id = getattr(db, 'server_library_id', None) if not library_id or not ids: return lines = [f'calibre://show-book/{library_id}/{book_id}' for book_id in ids] self._copy_links(lines) def copy_view_link(self): from calibre.gui2.actions.view import preferred_format db = self.gui.current_db ids = [db.id(row.row()) for row in self.gui.library_view.selectionModel().selectedRows()] db = db.new_api library_id = getattr(db, 'server_library_id', None) if not library_id or not ids: return lines = [] for book_id in ids: formats = db.new_api.formats(book_id, verify_formats=True) if formats: fmt = preferred_format(formats) lines.append(f'calibre://view-book/{library_id}/{book_id}/{fmt}') if lines: self._copy_links(lines) def location_selected(self, loc): enabled = loc == 'library' self.qaction.setEnabled(enabled) self.menuless_qaction.setEnabled(enabled) for action in self.metamerge_menu.actions() + self.metadata_menu.actions(): action.setEnabled(enabled) def copy_metadata(self): rows = self.gui.library_view.selectionModel().selectedRows() if not rows or len(rows) == 0: return error_dialog(self.gui, _('Cannot copy metadata'), _('No books selected'), show=True) if len(rows) > 1: return error_dialog(self.gui, _('Cannot copy metadata'), _('Multiple books selected, can only copy from one book at a time.'), show=True) db = self.gui.current_db book_id = db.id(rows[0].row()) mi = db.new_api.get_metadata(book_id) md = QMimeData() md.setText(str(mi)) md.setData('application/calibre-book-metadata', bytearray(metadata_to_opf(mi, default_lang='und'))) img = db.new_api.cover(book_id, as_image=True) if img: md.setImageData(img) c = QApplication.clipboard() c.setMimeData(md) def paste_metadata(self): self.do_paste() def paste_metadata_including_excluded_fields(self): self.do_paste(ignore_excluded_fields=True) def do_paste(self, ignore_excluded_fields=False): rows = self.gui.library_view.selectionModel().selectedRows() if not rows or len(rows) == 0: return error_dialog(self.gui, _('Cannot paste metadata'), _('No books selected'), show=True) c = QApplication.clipboard() md = c.mimeData() if not md.hasFormat('application/calibre-book-metadata'): return error_dialog(self.gui, _('Cannot paste metadata'), _('No copied metadata available'), show=True) if len(rows) > 1: if not confirm(_( 'You are pasting metadata onto <b>multiple books</b> ({num_of_books}). Are you' ' sure you want to do that?').format(num_of_books=len(rows)), 'paste-onto-multiple', parent=self.gui): return data = bytes(md.data('application/calibre-book-metadata')) mi = OPF(BytesIO(data), populate_spine=False, read_toc=False, try_to_guess_cover=False).to_book_metadata() mi.application_id = mi.uuid_id = None if ignore_excluded_fields: exclude = set() else: exclude = set(tweaks['exclude_fields_on_paste']) paste_cover = 'cover' not in exclude cover = md.imageData() if paste_cover else None exclude.discard('cover') for field in exclude: mi.set_null(field) db = self.gui.current_db book_ids = {db.id(r.row()) for r in rows} title_excluded = 'title' in exclude authors_excluded = 'authors' in exclude for book_id in book_ids: if title_excluded: mi.title = db.new_api.field_for('title', book_id) if authors_excluded: mi.authors = db.new_api.field_for('authors', book_id) db.new_api.set_metadata(book_id, mi, ignore_errors=True) if cover: db.new_api.set_cover({book_id: cover for book_id in book_ids}) self.refresh_books_after_metadata_edit(book_ids) # Download metadata {{{ def download_metadata(self, ids=None, ensure_fields=None): if ids is None: rows = self.gui.library_view.selectionModel().selectedRows() if not rows or len(rows) == 0: return error_dialog(self.gui, _('Cannot download metadata'), _('No books selected'), show=True) db = self.gui.library_view.model().db ids = [db.id(row.row()) for row in rows] from calibre.ebooks.metadata.sources.update import update_sources from calibre.gui2.metadata.bulk_download import start_download update_sources() start_download(self.gui, ids, Dispatcher(self.metadata_downloaded), ensure_fields=ensure_fields) def cleanup_bulk_download(self, tdir, *args): try: shutil.rmtree(tdir, ignore_errors=True) except: pass def metadata_downloaded(self, job): if job.failed: self.gui.job_exception(job, dialog_title=_('Failed to download metadata')) return from calibre.gui2.metadata.bulk_download import get_job_details (aborted, id_map, tdir, log_file, failed_ids, failed_covers, all_failed, det_msg, lm_map) = get_job_details(job) if aborted: return self.cleanup_bulk_download(tdir) if all_failed: num = len(failed_ids | failed_covers) self.cleanup_bulk_download(tdir) return error_dialog(self.gui, _('Download failed'), ngettext( 'Failed to download metadata or cover for the selected book.', 'Failed to download metadata or covers for any of the {} books.', num ).format(num), det_msg=det_msg, show=True) self.gui.status_bar.show_message(_('Metadata download completed'), 3000) msg = '<p>' + ngettext( 'Finished downloading metadata for the selected book.', 'Finished downloading metadata for <b>{} books</b>.', len(id_map)).format(len(id_map)) + ' ' + \ _('Proceed with updating the metadata in your library?') show_copy_button = False checkbox_msg = None if failed_ids or failed_covers: show_copy_button = True num = len(failed_ids.union(failed_covers)) msg += '<p>'+_('Could not download metadata and/or covers for %d of the books. Click' ' "Show details" to see which books.')%num checkbox_msg = _('Show the &failed books in the main book list ' 'after updating metadata') if getattr(job, 'metadata_and_covers', None) == (False, True): # Only covers, remove failed cover downloads from id_map for book_id in failed_covers: if hasattr(id_map, 'discard'): id_map.discard(book_id) payload = (id_map, tdir, log_file, lm_map, failed_ids.union(failed_covers)) review_apply = partial(self.apply_downloaded_metadata, True) normal_apply = partial(self.apply_downloaded_metadata, False) self.gui.proceed_question( normal_apply, payload, log_file, _('Download log'), _('Metadata download complete'), msg, icon='download-metadata.png', det_msg=det_msg, show_copy_button=show_copy_button, cancel_callback=partial(self.cleanup_bulk_download, tdir), log_is_file=True, checkbox_msg=checkbox_msg, checkbox_checked=False, action_callback=review_apply, action_label=_('Revie&w downloaded metadata'), action_icon=QIcon.ic('auto_author_sort.png')) def apply_downloaded_metadata(self, review, payload, *args): good_ids, tdir, log_file, lm_map, failed_ids = payload if not good_ids: return restrict_to_failed = False modified = set() db = self.gui.current_db for i in good_ids: lm = db.metadata_last_modified(i, index_is_id=True) if lm is not None and lm_map[i] is not None and lm > lm_map[i]: title = db.title(i, index_is_id=True) authors = db.authors(i, index_is_id=True) if authors: authors = [x.replace('|', ',') for x in authors.split(',')] title += ' - ' + authors_to_string(authors) modified.add(title) if modified: from calibre.utils.icu import lower modified = sorted(modified, key=lower) if not question_dialog(self.gui, _('Some books changed'), '<p>' + _( 'The metadata for some books in your library has' ' changed since you started the download. If you' ' proceed, some of those changes may be overwritten. ' 'Click "Show details" to see the list of changed books. ' 'Do you want to proceed?'), det_msg='\n'.join(modified)): return id_map = {} for bid in good_ids: opf = os.path.join(tdir, '%d.mi'%bid) if not os.path.exists(opf): opf = None cov = os.path.join(tdir, '%d.cover'%bid) if not os.path.exists(cov): cov = None id_map[bid] = (opf, cov) if review: def get_metadata(book_id): oldmi = db.get_metadata(book_id, index_is_id=True, get_cover=True, cover_as_data=True) opf, cov = id_map[book_id] if opf is None: newmi = Metadata(oldmi.title, authors=tuple(oldmi.authors)) else: with open(opf, 'rb') as f: newmi = OPF(f, basedir=os.path.dirname(opf), populate_spine=False).to_book_metadata() newmi.cover, newmi.cover_data = None, (None, None) for x in ('title', 'authors'): if newmi.is_null(x): # Title and author are set to null if they are # the same as the originals as an optimization, # we undo that, as it is confusing. newmi.set(x, copy.copy(oldmi.get(x))) if cov: with open(cov, 'rb') as f: newmi.cover_data = ('jpg', f.read()) return oldmi, newmi from calibre.gui2.metadata.diff import CompareMany d = CompareMany( set(id_map), get_metadata, db.field_metadata, parent=self.gui, window_title=_('Review downloaded metadata'), reject_button_tooltip=_('Discard downloaded metadata for this book'), accept_all_tooltip=_('Use the downloaded metadata for all remaining books'), reject_all_tooltip=_('Discard downloaded metadata for all remaining books'), revert_tooltip=_('Discard the downloaded value for: %s'), intro_msg=_('The downloaded metadata is on the left and the original metadata' ' is on the right. If a downloaded value is blank or unknown,' ' the original value is used.'), action_button=(_('&View book'), 'view.png', self.gui.iactions['View'].view_historical), db=db ) if d.exec() == QDialog.DialogCode.Accepted: if d.mark_rejected: failed_ids |= d.rejected_ids restrict_to_failed = True nid_map = {} for book_id, (changed, mi) in iteritems(d.accepted): if mi is None: # discarded continue if changed: opf, cov = id_map[book_id] cfile = mi.cover mi.cover, mi.cover_data = None, (None, None) if opf is not None: with open(opf, 'wb') as f: f.write(metadata_to_opf(mi)) if cfile and cov: shutil.copyfile(cfile, cov) os.remove(cfile) nid_map[book_id] = id_map[book_id] id_map = nid_map else: id_map = {} restrict_to_failed = restrict_to_failed or bool(args and args[0]) restrict_to_failed = restrict_to_failed and bool(failed_ids) if restrict_to_failed: db.data.set_marked_ids(failed_ids) self.apply_metadata_changes( id_map, merge_comments=msprefs['append_comments'], icon='download-metadata.png', callback=partial(self.downloaded_metadata_applied, tdir, restrict_to_failed)) def downloaded_metadata_applied(self, tdir, restrict_to_failed, *args): if restrict_to_failed: self.gui.search.set_search_string('marked:true') self.cleanup_bulk_download(tdir) # }}} def edit_metadata(self, checked, bulk=None): ''' Edit metadata of selected books in library. ''' rows = self.gui.library_view.selectionModel().selectedRows() if not rows or len(rows) == 0: d = error_dialog(self.gui, _('Cannot edit metadata'), _('No books selected')) d.exec() return row_list = [r.row() for r in rows] m = self.gui.library_view.model() ids = [m.id(r) for r in rows] self.edit_metadata_for(row_list, ids, bulk=bulk) def edit_metadata_for(self, rows, book_ids, bulk=None): previous = self.gui.library_view.currentIndex() if bulk or (bulk is None and len(rows) > 1): return self.do_edit_bulk_metadata(rows, book_ids) current_row = 0 row_list = rows editing_multiple = len(row_list) > 1 if not editing_multiple: cr = row_list[0] row_list = \ list(range(self.gui.library_view.model().rowCount(QModelIndex()))) current_row = row_list.index(cr) view = self.gui.library_view.alternate_views.current_view try: hpos = view.horizontalScrollBar().value() except Exception: hpos = 0 changed, rows_to_refresh = self.do_edit_metadata(row_list, current_row, editing_multiple) m = self.gui.library_view.model() if rows_to_refresh: m.refresh_rows(rows_to_refresh) if changed: self.refresh_books_after_metadata_edit(changed, previous) if self.gui.library_view.alternate_views.current_view is view: if hasattr(view, 'restore_hpos'): view.restore_hpos(hpos) else: view.horizontalScrollBar().setValue(hpos) def refresh_books_after_metadata_edit(self, book_ids, previous=None): m = self.gui.library_view.model() m.refresh_ids(list(book_ids)) current = self.gui.library_view.currentIndex() self.gui.refresh_cover_browser() m.current_changed(current, previous or current) self.gui.tags_view.recount_with_position_based_index() qv = get_quickview_action_plugin() if qv: qv.refresh_quickview(current) def do_edit_metadata(self, row_list, current_row, editing_multiple): from calibre.gui2.metadata.single import edit_metadata db = self.gui.library_view.model().db parent = getattr(self, 'override_parent', None) or self.gui changed, rows_to_refresh = edit_metadata(db, row_list, current_row, parent=parent, view_slot=self.view_format_callback, edit_slot=self.edit_format_callback, set_current_callback=self.set_current_callback, editing_multiple=editing_multiple) return changed, rows_to_refresh @contextmanager def different_parent(self, parent): orig = getattr(self, 'override_parent', None) self.override_parent = parent try: yield finally: self.override_parent = orig def set_current_callback(self, id_): db = self.gui.library_view.model().db current_row = db.row(id_) self.gui.library_view.set_current_row(current_row) self.gui.library_view.scroll_to_row(current_row) def view_format_callback(self, id_, fmt): view = self.gui.iactions['View'] if id_ is None: view._view_file(fmt) else: db = self.gui.library_view.model().db view.view_format(db.row(id_), fmt) def edit_format_callback(self, id_, fmt): edit = self.gui.iactions['Tweak ePub'] edit.ebook_edit_format(id_, fmt) def edit_bulk_metadata(self, checked): ''' Edit metadata of selected books in library in bulk. ''' rows = [r.row() for r in self.gui.library_view.selectionModel().selectedRows()] m = self.gui.library_view.model() ids = [m.id(r) for r in rows] if not rows or len(rows) == 0: d = error_dialog(self.gui, _('Cannot edit metadata'), _('No books selected')) d.exec() return self.do_edit_bulk_metadata(rows, ids) def do_edit_bulk_metadata(self, rows, book_ids): # Prevent the TagView from updating due to signals from the database self.gui.tags_view.blockSignals(True) changed = False refresh_books = set(book_ids) try: current_tab = -1 while True: dialog = MetadataBulkDialog(self.gui, rows, self.gui.library_view.model(), current_tab, refresh_books) if dialog.changed: changed = True if not dialog.do_again: break current_tab = dialog.central_widget.currentIndex() finally: self.gui.tags_view.blockSignals(False) if changed: refresh_books |= dialog.refresh_books m = self.gui.library_view.model() if gprefs['refresh_book_list_on_bulk_edit']: m.refresh(reset=False) m.research() else: m.refresh_ids(refresh_books) self.gui.tags_view.recount() self.gui.refresh_cover_browser() self.gui.library_view.select_rows(book_ids) # Merge books {{{ def confirm_large_merge(self, num): if num < 5: return True return confirm('<p>'+_( 'You are about to merge very many ({}) books. ' 'Are you <b>sure</b> you want to proceed?').format(num) + '</p>', 'merge_too_many_books', self.gui) def books_dropped(self, merge_map): covers_replaced = False for dest_id, src_ids in iteritems(merge_map): if not self.confirm_large_merge(len(src_ids) + 1): continue from calibre.gui2.dialogs.confirm_merge import merge_drop d = merge_drop(dest_id, src_ids, self.gui) if d is None: return if d.merge_formats: self.add_formats(dest_id, self.formats_for_ids(list(src_ids))) if d.merge_metadata: self.merge_metadata(dest_id, src_ids, replace_cover=d.replace_cover, save_alternate_cover=d.save_alternate_cover) if d.replace_cover: covers_replaced = True if d.delete_books: self.delete_books_after_merge(src_ids) # leave the selection highlight on the target book row = self.gui.library_view.ids_to_rows([dest_id])[dest_id] self.gui.library_view.set_current_row(row) if covers_replaced: self.gui.refresh_cover_browser() def merge_books(self, safe_merge=False, merge_only_formats=False): ''' Merge selected books in library. ''' from calibre.gui2.dialogs.confirm_merge import confirm_merge if self.gui.current_view() is not self.gui.library_view: return rows = self.gui.library_view.indices_for_merge() if not rows or len(rows) == 0: return error_dialog(self.gui, _('Cannot merge books'), _('No books selected'), show=True) if len(rows) < 2: return error_dialog(self.gui, _('Cannot merge books'), _('At least two books must be selected for merging'), show=True) if not self.confirm_large_merge(len(rows)): return dest_id, src_ids = self.books_to_merge(rows) mi = self.gui.current_db.new_api.get_proxy_metadata(dest_id) title = mi.title hpos = self.gui.library_view.horizontalScrollBar().value() if safe_merge: confirmed, save_alternate_cover = confirm_merge('<p>'+_( 'Book formats and metadata from the selected books ' 'will be added to the <b>first selected book</b> (%s).<br> ' 'The second and subsequently selected books will not ' 'be deleted or changed.<br><br>' 'Please confirm you want to proceed.')%title + '</p>', 'merge_books_safe', self.gui, mi, ask_about_save_alternate_cover=True) if not confirmed: return self.add_formats(dest_id, self.formats_for_books(rows)) self.merge_metadata(dest_id, src_ids, save_alternate_cover=save_alternate_cover) elif merge_only_formats: if not confirm_merge('<p>'+_( 'Book formats from the selected books will be merged ' 'into the <b>first selected book</b> (%s). ' 'Metadata in the first selected book will not be changed. ' 'Author, Title and all other metadata will <i>not</i> be merged.<br><br>' 'After being merged, the second and subsequently ' 'selected books, with any metadata they have will be <b>deleted</b>. <br><br>' 'All book formats of the first selected book will be kept ' 'and any duplicate formats in the second and subsequently selected books ' 'will be permanently <b>deleted</b> from your calibre library.<br><br> ' 'Are you <b>sure</b> you want to proceed?')%title + '</p>', 'merge_only_formats', self.gui, mi)[0]: return self.add_formats(dest_id, self.formats_for_books(rows)) self.delete_books_after_merge(src_ids) else: confirmed, save_alternate_cover = confirm_merge('<p>'+_( 'Book formats and metadata from the selected books will be merged ' 'into the <b>first selected book</b> (%s).<br><br>' 'After being merged, the second and ' 'subsequently selected books will be <b>deleted</b>. <br><br>' 'All book formats of the first selected book will be kept ' 'and any duplicate formats in the second and subsequently selected books ' 'will be permanently <b>deleted</b> from your calibre library.<br><br> ' 'Are you <b>sure</b> you want to proceed?')%title + '</p>', 'merge_books', self.gui, mi, ask_about_save_alternate_cover=True) if not confirmed: return self.add_formats(dest_id, self.formats_for_books(rows)) self.merge_metadata(dest_id, src_ids, save_alternate_cover=save_alternate_cover) self.merge_data_files(dest_id, src_ids) self.delete_books_after_merge(src_ids) # leave the selection highlight on first selected book dest_row = rows[0].row() for row in rows: if row.row() < rows[0].row(): dest_row -= 1 self.gui.library_view.set_current_row(dest_row) cr = self.gui.library_view.currentIndex().row() self.gui.library_view.model().refresh_ids((dest_id,), cr) self.gui.library_view.horizontalScrollBar().setValue(hpos) def merge_data_files(self, dest_id, src_ids): self.gui.current_db.new_api.merge_extra_files(dest_id, src_ids) def add_formats(self, dest_id, src_books, replace=False): for src_book in src_books: if src_book: fmt = os.path.splitext(src_book)[-1].replace('.', '').upper() with open(src_book, 'rb') as f: self.gui.library_view.model().db.add_format(dest_id, fmt, f, index_is_id=True, notify=False, replace=replace) def formats_for_ids(self, ids): m = self.gui.library_view.model() ans = [] for id_ in ids: dbfmts = m.db.formats(id_, index_is_id=True) if dbfmts: for fmt in dbfmts.split(','): try: path = m.db.format(id_, fmt, index_is_id=True, as_path=True) ans.append(path) except NoSuchFormat: continue return ans def formats_for_books(self, rows): m = self.gui.library_view.model() return self.formats_for_ids(list(map(m.id, rows))) def books_to_merge(self, rows): src_ids = [] m = self.gui.library_view.model() for i, row in enumerate(rows): id_ = m.id(row) if i == 0: dest_id = id_ else: src_ids.append(id_) return [dest_id, src_ids] def delete_books_after_merge(self, ids_to_delete): self.gui.library_view.model().delete_books_by_id(ids_to_delete) def merge_metadata(self, dest_id, src_ids, replace_cover=False, save_alternate_cover=False): self.gui.current_db.new_api.merge_book_metadata(dest_id, src_ids, replace_cover, save_alternate_cover=save_alternate_cover) # }}} def edit_device_collections(self, view, oncard=None): model = view.model() result = model.get_collections_with_ids() d = DeviceCategoryEditor(self.gui, tag_to_match=None, data=result, key=sort_key) d.exec() if d.result() == QDialog.DialogCode.Accepted: to_rename = d.to_rename # dict of new text to old ids to_delete = d.to_delete # list of ids for old_id, new_name in iteritems(to_rename): model.rename_collection(old_id, new_name=str(new_name)) for item in to_delete: model.delete_collection_using_id(item) self.gui.upload_collections(model.db, view=view, oncard=oncard) view.reset() # Apply bulk metadata changes {{{ def apply_metadata_changes(self, id_map, title=None, msg='', callback=None, merge_tags=True, merge_comments=False, icon=None): ''' Apply the metadata changes in id_map to the database synchronously id_map must be a mapping of ids to Metadata objects. Set any fields you do not want updated in the Metadata object to null. An easy way to do that is to create a metadata object as Metadata(_('Unknown')) and then only set the fields you want changed on this object. callback can be either None or a function accepting a single argument, in which case it is called after applying is complete with the list of changed ids. id_map can also be a mapping of ids to 2-tuple's where each 2-tuple contains the absolute paths to an OPF and cover file respectively. If either of the paths is None, then the corresponding metadata is not updated. ''' if title is None: title = _('Applying changed metadata') self.apply_id_map = list(iteritems(id_map)) self.apply_current_idx = 0 self.apply_failures = [] self.applied_ids = set() self.apply_pd = None self.apply_callback = callback if len(self.apply_id_map) > 1: from calibre.gui2.dialogs.progress import ProgressDialog self.apply_pd = ProgressDialog(title, msg, min=0, max=len(self.apply_id_map)-1, parent=self.gui, cancelable=False, icon=icon) self.apply_pd.setModal(True) self.apply_pd.show() self._am_merge_tags = merge_tags self._am_merge_comments = merge_comments self.do_one_apply() def do_one_apply(self): if self.apply_current_idx >= len(self.apply_id_map): return self.finalize_apply() i, mi = self.apply_id_map[self.apply_current_idx] if self.gui.current_db.has_id(i): if isinstance(mi, tuple): opf, cover = mi if opf: mi = OPF(open(opf, 'rb'), basedir=os.path.dirname(opf), populate_spine=False).to_book_metadata() self.apply_mi(i, mi) if cover: self.gui.current_db.set_cover(i, open(cover, 'rb'), notify=False, commit=False) self.applied_ids.add(i) else: self.apply_mi(i, mi) self.apply_current_idx += 1 if self.apply_pd is not None: self.apply_pd.value += 1 QTimer.singleShot(5, self.do_one_apply) def apply_mi(self, book_id, mi): db = self.gui.current_db try: set_title = not mi.is_null('title') set_authors = not mi.is_null('authors') idents = db.get_identifiers(book_id, index_is_id=True) if mi.identifiers: idents.update(mi.identifiers) mi.identifiers = idents if mi.is_null('series'): mi.series_index = None if self._am_merge_tags: old_tags = db.tags(book_id, index_is_id=True) if old_tags: tags = [x.strip() for x in old_tags.split(',')] + ( mi.tags if mi.tags else []) mi.tags = list(set(tags)) if self._am_merge_comments: old_comments = db.new_api.field_for('comments', book_id) if old_comments and mi.comments and old_comments != mi.comments: mi.comments = merge_comments(old_comments, mi.comments) db.set_metadata(book_id, mi, commit=False, set_title=set_title, set_authors=set_authors, notify=False) self.applied_ids.add(book_id) except: import traceback self.apply_failures.append((book_id, traceback.format_exc())) try: if mi.cover: os.remove(mi.cover) except: pass def finalize_apply(self): db = self.gui.current_db db.commit() if self.apply_pd is not None: self.apply_pd.hide() if self.apply_failures: msg = [] for i, tb in self.apply_failures: title = db.title(i, index_is_id=True) authors = db.authors(i, index_is_id=True) if authors: authors = [x.replace('|', ',') for x in authors.split(',')] title += ' - ' + authors_to_string(authors) msg.append(title+'\n\n'+tb+'\n'+('*'*80)) error_dialog(self.gui, _('Some failures'), _('Failed to apply updated metadata for some books' ' in your library. Click "Show details" to see ' 'details.'), det_msg='\n\n'.join(msg), show=True) changed_books = len(self.applied_ids or ()) self.refresh_gui(self.applied_ids) self.apply_id_map = [] self.apply_pd = None try: if callable(self.apply_callback): self.apply_callback(list(self.applied_ids)) finally: self.apply_callback = None if changed_books: QApplication.alert(self.gui, 2000) def refresh_gui(self, book_ids, covers_changed=True, tag_browser_changed=True): if book_ids: cr = self.gui.library_view.currentIndex().row() self.gui.library_view.model().refresh_ids( list(book_ids), cr) if covers_changed: self.gui.refresh_cover_browser() if tag_browser_changed: self.gui.tags_view.recount() # }}} def remove_metadata_item(self, book_id, field, value): db = self.gui.current_db.new_api fm = db.field_metadata[field] affected_books = set() if field == 'identifiers': identifiers = db.field_for(field, book_id) if identifiers.pop(value, False) is not False: affected_books = db.set_field(field, {book_id:identifiers}) elif field == 'authors': authors = db.field_for(field, book_id) new_authors = [x for x in authors if x != value] or [_('Unknown')] if new_authors != authors: affected_books = db.set_field(field, {book_id:new_authors}) elif fm['is_multiple']: item_id = db.get_item_id(field, value) if item_id is not None: affected_books = db.remove_items(field, (item_id,), {book_id}) else: affected_books = db.set_field(field, {book_id:''}) if affected_books: self.refresh_books_after_metadata_edit(affected_books) def set_cover_from_format(self, book_id, fmt): from calibre.ebooks.metadata.meta import get_metadata from calibre.utils.config import prefs fmt = fmt.lower() cdata = None db = self.gui.current_db.new_api if fmt in ('pdf', 'cbz', 'cbr'): path = db.format_abspath(book_id, fmt) if path is None: return error_dialog(self.gui, _('Format file missing'), _( 'Cannot read cover as the %s file is missing from this book') % fmt.upper(), show=True) from calibre.gui2.metadata.pdf_covers import PDFCovers d = PDFCovers(path, parent=self.gui) ret = d.exec() if ret == QDialog.DialogCode.Accepted: cpath = d.cover_path if cpath: with open(cpath, 'rb') as f: cdata = f.read() d.cleanup() if ret != QDialog.DialogCode.Accepted: return else: stream = BytesIO() try: db.copy_format_to(book_id, fmt, stream) except NoSuchFormat: return error_dialog(self.gui, _('Format file missing'), _( 'Cannot read cover as the %s file is missing from this book') % fmt.upper(), show=True) old = prefs['read_file_metadata'] if not old: prefs['read_file_metadata'] = True try: stream.seek(0) mi = get_metadata(stream, fmt) except Exception: import traceback return error_dialog(self.gui, _('Could not read metadata'), _('Could not read metadata from %s format')%fmt.upper(), det_msg=traceback.format_exc(), show=True) finally: if old != prefs['read_file_metadata']: prefs['read_file_metadata'] = old if mi.cover and os.access(mi.cover, os.R_OK): with open(mi.cover, 'rb') as f: cdata = f.read() elif mi.cover_data[1] is not None: cdata = mi.cover_data[1] if cdata is None: return error_dialog(self.gui, _('Could not read cover'), _('Could not read cover from %s format')%fmt.upper(), show=True) db.set_cover({book_id:cdata}) current_idx = self.gui.library_view.currentIndex() self.gui.library_view.model().current_changed(current_idx, current_idx) self.gui.refresh_cover_browser()
42,720
Python
.py
864
36.858796
131
0.577691
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,939
fts.py
kovidgoyal_calibre/src/calibre/gui2/actions/fts.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> from calibre.gui2.actions import InterfaceAction class FullTextSearchAction(InterfaceAction): name = 'Full Text Search' action_spec = (_('Search full text'), 'fts.png', _('Search the full text of all books in the calibre library'), ('Ctrl+/', 'Ctrl+Alt+F')) dont_add_to = frozenset(('context-menu-device',)) action_type = 'current' def genesis(self): self.qaction.triggered.connect(self.show_fts) self._dialog = None @property def dialog(self): if self._dialog is None: from calibre.gui2.fts.dialog import FTSDialog self._dialog = FTSDialog(self.gui) return self._dialog def show_fts(self): text = self.gui.search.text() if text and ':' not in text: self.dialog.set_search_text(text) self.dialog.show() self.dialog.raise_and_focus() def library_changed(self, db): if self._dialog is not None: self._dialog.library_changed() def clear_search_history(self): if self._dialog is not None: self._dialog.clear_search_history()
1,225
Python
.py
30
32.866667
107
0.637975
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,940
booklist_context_menu.py
kovidgoyal_calibre/src/calibre/gui2/actions/booklist_context_menu.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2022, Charles Haley # from calibre.gui2.actions import InterfaceAction class BooklistContextMenuAction(InterfaceAction): name = 'Booklist context menu' action_spec = (_('Book list header menu'), 'context_menu.png', _('Show the book list header context menu'), ()) action_type = 'current' action_add_menu = False dont_add_to = frozenset(['context-menu-device', 'menubar-device']) def genesis(self): self.qaction.triggered.connect(self.show_context_menu) def show_context_menu(self): self.gui.library_view.show_column_header_context_menu_from_action() def location_selected(self, loc): self.qaction.setEnabled(loc == 'library')
758
Python
.py
17
38.764706
75
0.700272
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,941
preferences.py
kovidgoyal_calibre/src/calibre/gui2/actions/preferences.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from functools import partial from qt.core import QIcon, Qt from calibre.constants import DEBUG, ismacos from calibre.customize.ui import preferences_plugins from calibre.gui2 import error_dialog, show_restart_warning from calibre.gui2.actions import InterfaceAction from calibre.gui2.preferences.main import Preferences class PreferencesAction(InterfaceAction): name = 'Preferences' action_spec = (_('Preferences'), 'config.png', _('Configure calibre'), 'Ctrl+P') action_add_menu = True action_menu_clone_qaction = _('Change calibre behavior') def genesis(self): pm = self.qaction.menu() cm = partial(self.create_menu_action, pm) if ismacos: pm.addAction(QIcon.ic('config.png'), _('Preferences'), self.do_config) cm('welcome wizard', _('Run Welcome wizard'), icon='wizard.png', triggered=self.gui.run_wizard) cm('plugin updater', _('Get plugins to enhance calibre'), icon='plugins/plugin_updater.png', triggered=self.get_plugins) pm.addSeparator() if not DEBUG: cm('restart', _('Restart in debug mode'), icon='debug.png', triggered=self.debug_restart, shortcut='Ctrl+Shift+R') cm('restart_without_plugins', _('Restart ignoring third party plugins'), icon='debug.png', triggered=self.no_plugins_restart, shortcut='Ctrl+Alt+Shift+R') self.preferences_menu = pm for x in (self.gui.preferences_action, self.qaction): x.triggered.connect(self.do_config) def initialization_complete(self): # Add the individual preferences to the menu. # First, sort them into the same order as shown in the preferences dialog plugins = sorted([p for p in preferences_plugins()], key=lambda p: p.category_order * 100 + p.name_order) pm = self.preferences_menu # The space pushes the separator a bit away from the text pm.addSection(_('Sections') + ' ') config_icon = QIcon.ic('config.png') current_cat = 0 for p in plugins: if p.category_order != current_cat: current_cat = p.category_order cm = pm.addMenu(p.gui_category.replace('&', '&&')) cm.setIcon(config_icon) self.create_menu_action(cm, p.name, p.gui_name.replace('&', '&&'), icon=QIcon.ic(p.icon), shortcut=None, shortcut_name=p.gui_name, triggered=partial(self.do_config, initial_plugin=(p.category, p.name), close_after_initial=True)) def get_plugins(self): from calibre.gui2.dialogs.plugin_updater import FILTER_NOT_INSTALLED, PluginUpdaterDialog d = PluginUpdaterDialog(self.gui, initial_filter=FILTER_NOT_INSTALLED) d.exec() if d.do_restart: self.gui.quit(restart=True) def do_config(self, checked=False, initial_plugin=None, close_after_initial=False): if self.gui.job_manager.has_jobs(): d = error_dialog(self.gui, _('Cannot configure'), _('Cannot configure while there are running jobs.')) d.exec() return if self.gui.must_restart_before_config: do_restart = show_restart_warning(_('Cannot configure before calibre is restarted.')) if do_restart: self.gui.quit(restart=True) return d = Preferences(self.gui, initial_plugin=initial_plugin, close_after_initial=close_after_initial) d.run_wizard_requested.connect(self.gui.run_wizard, type=Qt.ConnectionType.QueuedConnection) d.exec() if d.do_restart: self.gui.quit(restart=True) def debug_restart(self, *args): self.gui.quit(restart=True, debug_on_restart=True) def no_plugins_restart(self, *args): self.gui.quit(restart=True, no_plugins_on_restart=True)
4,212
Python
.py
83
39.855422
106
0.62272
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,942
store.py
kovidgoyal_calibre/src/calibre/gui2/actions/store.py
__license__ = 'GPL 3' __copyright__ = '2011, John Schember <john@nachtimwald.com>' __docformat__ = 'restructuredtext en' from functools import partial from qt.core import QIcon from calibre.gui2 import error_dialog from calibre.gui2.actions import InterfaceAction from calibre.gui2.dialogs.confirm_delete import confirm from calibre.utils.localization import localize_user_manual_link class StoreAction(InterfaceAction): name = 'Store' action_spec = (_('Get books'), 'store.png', _('Search dozens of online e-book retailers for the cheapest books'), _('G')) action_add_menu = True action_menu_clone_qaction = _('Search for e-books') def genesis(self): self.qaction.triggered.connect(self.do_search) self.store_menu = self.qaction.menu() cm = partial(self.create_menu_action, self.store_menu) for x, t in [('author', _('this author')), ('title', _('this title')), ('book', _('this book'))]: func = getattr(self, 'search_%s'%('author_title' if x == 'book' else x)) ac = cm(x, _('Search for %s')%t, triggered=func) setattr(self, 'action_search_by_'+x, ac) self.store_menu.addSeparator() self.store_list_menu = self.store_menu.addMenu(_('Stores')) self.load_menu() self.store_menu.addSeparator() cm('choose stores', _('Choose stores'), triggered=self.choose) def load_menu(self): self.store_list_menu.clear() icon = QIcon.ic('donate.png') for n, p in sorted(self.gui.istores.items(), key=lambda x: x[0].lower()): if p.base_plugin.affiliate: self.store_list_menu.addAction(icon, n, partial(self.open_store, n)) else: self.store_list_menu.addAction(n, partial(self.open_store, n)) def do_search(self): return self.search() def search(self, query=''): self.gui.istores.check_for_updates() self.show_disclaimer() from calibre.gui2.store.search.search import SearchDialog sd = SearchDialog(self.gui, self.gui, query) sd.exec() def _get_selected_row(self): rows = self.gui.current_view().selectionModel().selectedRows() if not rows or len(rows) == 0: return None return rows[0].row() def _get_author(self, row): authors = [] if self.gui.current_view() is self.gui.library_view: a = self.gui.library_view.model().authors(row) authors = a.split(',') else: mi = self.gui.current_view().model().get_book_display_info(row) authors = mi.authors corrected_authors = [] for x in authors: a = x.split('|') a.reverse() a = ' '.join(a) corrected_authors.append(a) return ' & '.join(corrected_authors).strip() def search_author(self): row = self._get_selected_row() if row is None: error_dialog(self.gui, _('Cannot search'), _('No book selected'), show=True) return self.search({'author': self._get_author(row)}) def _get_title(self, row): title = '' if self.gui.current_view() is self.gui.library_view: title = self.gui.library_view.model().title(row) else: mi = self.gui.current_view().model().get_book_display_info(row) title = mi.title return title.strip() def search_title(self): row = self._get_selected_row() if row is None: error_dialog(self.gui, _('Cannot search'), _('No book selected'), show=True) return self.search({'title': self._get_title(row)}) def search_author_title(self): row = self._get_selected_row() if row is None: error_dialog(self.gui, _('Cannot search'), _('No book selected'), show=True) return self.search({'author': self._get_author(row), 'title': self._get_title(row)}) def choose(self): from calibre.gui2.store.config.chooser.chooser_dialog import StoreChooserDialog d = StoreChooserDialog(self.gui) d.exec() self.gui.load_store_plugins() self.load_menu() def open_store(self, store_plugin_name): self.gui.istores.check_for_updates() # self.show_disclaimer() # It's not too important that the updated plugin have finished loading # at this point self.gui.istores.join(1.0) self.gui.istores[store_plugin_name].open(self.gui) def show_disclaimer(self): confirm(('<p>' + _('calibre helps you find the e-books you want by searching ' 'the websites of various commercial and public domain ' 'book sources.') + '<p>' + _('Using the integrated search you can easily find which ' 'store has the book you are looking for, at the best price. ' 'You also get DRM status and other useful information.') + '<p>' + _('All transactions (paid or otherwise) are handled between ' 'you and the book seller. ' 'calibre is not part of this process and any issues related ' 'to a purchase should be directed to the website you are ' 'buying from. Be sure to double check that any books you get ' 'will work with your e-book reader, especially if the book you ' 'are buying has ' '<a href="{}">DRM</a>.' ).format(localize_user_manual_link( 'https://manual.calibre-ebook.com/drm.html'))), 'about_get_books_msg', parent=self.gui, show_cancel_button=False, confirm_msg=_('Show this message again'), pixmap='dialog_information.png', title=_('About Get books'))
5,883
Python
.py
127
36.362205
125
0.596895
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,943
view.py
kovidgoyal_calibre/src/calibre/gui2/actions/view.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import json import os import time from functools import partial from qt.core import QAction, QDialog, QIcon, pyqtSignal from calibre.constants import ismacos, iswindows from calibre.db.constants import DATA_DIR_NAME from calibre.gui2 import Dispatcher, config, elided_text, error_dialog, info_dialog, open_local_file, question_dialog from calibre.gui2.actions import InterfaceAction from calibre.gui2.dialogs.choose_format import ChooseFormatDialog from calibre.ptempfile import PersistentTemporaryFile from calibre.utils.config import prefs, tweaks from polyglot.builtins import as_bytes def preferred_format(formats): formats = tuple(x.upper() for x in formats if x) fmt = formats[0] for format in prefs['input_format_order']: if format in formats: fmt = format break return fmt class HistoryAction(QAction): view_historical = pyqtSignal(object) def __init__(self, id_, title, parent): QAction.__init__(self, title, parent) self.id = id_ self.triggered.connect(self._triggered) def _triggered(self): self.view_historical.emit(self.id) class ViewAction(InterfaceAction): name = 'View' action_spec = (_('View'), 'view.png', _('Read books'), _('V')) action_type = 'current' action_add_menu = True action_menu_clone_qaction = True force_internal_viewer = False def genesis(self): self.persistent_files = [] self.qaction.triggered.connect(self.view_book) self.view_action = self.menuless_qaction self.view_menu = self.qaction.menu() cm = partial(self.create_menu_action, self.view_menu) self.view_specific_action = cm('specific', _('View specific format'), shortcut='Alt+V', triggered=self.view_specific_format) self.internal_view_action = cm('internal', _('View with calibre E-book viewer'), icon='viewer.png', triggered=self.view_internal) self.action_pick_random = cm('pick random', _('Read a random book'), icon='random.png', triggered=self.view_random) self.view_menu.addAction(QIcon.ic('highlight.png'), _('Browse annotations'), self.browse_annots) self.clear_sep1 = self.view_menu.addSeparator() self.clear_sep2 = self.view_menu.addSeparator() self.clear_history_action = cm('clear history', _('Clear recently viewed list'), icon='trash.png', triggered=self.clear_history) self.history_actions = [self.clear_sep1] self.action_view_last_read = ac = self.create_action( spec=(_('Continue reading previous book'), None, _('Continue reading the last opened book'), 'shift+v'), attr='action_view_last_read') ac.triggered.connect(self.view_last_read) self.gui.addAction(ac) def initialization_complete(self): self.build_menus(self.gui.current_db) def build_menus(self, db): for ac in self.history_actions: self.view_menu.removeAction(ac) self.history_actions = [] history = db.new_api.pref('gui_view_history', []) if history: self.view_menu.insertAction(self.clear_sep2, self.clear_sep1) self.history_actions.append(self.clear_sep1) fm = self.gui.fontMetrics() for id_, title in history: ac = HistoryAction(id_, elided_text(title, font=fm, pos='right'), self.view_menu) self.view_menu.insertAction(self.clear_sep2, ac) ac.view_historical.connect(self.view_historical) self.history_actions.append(ac) def view_last_read(self): history = self.gui.current_db.new_api.pref('gui_view_history', []) for book_id, title in history: self.view_historical(book_id) break def browse_annots(self): self.gui.iactions['Browse Annotations'].show_browser() def clear_history(self): db = self.gui.current_db db.new_api.set_pref('gui_view_history', []) self.build_menus(db) def view_historical(self, id_): self._view_calibre_books([id_]) def library_changed(self, db): self.build_menus(db) def location_selected(self, loc): enabled = loc == 'library' for action in list(self.view_menu.actions())[1:]: action.setEnabled(enabled) def view_format(self, row, format): id_ = self.gui.library_view.model().id(row) self.view_format_by_id(id_, format) def calibre_book_data(self, book_id, fmt): from calibre.db.annotations import merge_annotations from calibre.gui2.viewer.config import get_session_pref, vprefs vprefs.refresh() sync_annots_user = get_session_pref('sync_annots_user', default='') db = self.gui.current_db.new_api annotations_map = db.annotations_map_for_book(book_id, fmt) if sync_annots_user: other_annotations_map = db.annotations_map_for_book(book_id, fmt, user_type='web', user=sync_annots_user) if other_annotations_map: merge_annotations(other_annotations_map, annotations_map, merge_last_read=False) return { 'book_id': book_id, 'uuid': db.field_for('uuid', book_id), 'fmt': fmt.upper(), 'annotations_map': annotations_map, 'library_id': getattr(self.gui.current_db.new_api, 'server_library_id', None) } def view_format_by_id(self, id_, format, open_at=None): db = self.gui.current_db fmt_path = db.format_abspath(id_, format, index_is_id=True) if fmt_path: title = db.title(id_, index_is_id=True) self._view_file(fmt_path, calibre_book_data=self.calibre_book_data(id_, format), open_at=open_at) self.update_history([(id_, title)]) else: error_dialog(self.gui, _('E-book file missing'), _( 'The {} format file is missing from the calibre library folder').format(format), show=True) def book_downloaded_for_viewing(self, job): if job.failed: self.gui.device_job_exception(job) return self._view_file(job.result) def _launch_viewer(self, name=None, viewer='ebook-viewer', internal=True, calibre_book_data=None, open_at=None): from calibre.gui2.widgets import BusyCursor with BusyCursor(): if internal: args = [viewer] if ismacos and 'ebook' in viewer: args.append('--raise-window') if name is not None: args.append(name) if viewer != 'lrfviewer': if open_at is not None: args.append('--open-at=' + open_at) if calibre_book_data is not None: with PersistentTemporaryFile('.json') as ptf: ptf.write(as_bytes(json.dumps(calibre_book_data))) args.append('--internal-book-data=' + ptf.name) self.gui.job_manager.launch_gui_app(viewer, kwargs=dict(args=args)) else: if iswindows: from calibre_extensions import winutil ext = name.rpartition('.')[-1] if ext: try: prog = winutil.file_association(str('.' + ext)) except Exception: prog = None if prog and prog.lower().endswith('calibre.exe'): name = os.path.basename(name) return error_dialog( self.gui, _('No associated program'), _( 'Windows will try to open %s with calibre itself' ' resulting in a duplicate in your calibre library. You' ' should install some program capable of viewing this' ' file format and tell Windows to use that program to open' ' files of this type.') % name, show=True) open_local_file(name) time.sleep(2) # User feedback def _view_file(self, name, calibre_book_data=None, open_at=None): ext = os.path.splitext(name)[1].upper().replace('.', '').replace('ORIGINAL_', '') viewer = 'lrfviewer' if ext == 'LRF' else 'ebook-viewer' internal = self.force_internal_viewer or ext in config['internally_viewed_formats'] or open_at is not None self._launch_viewer(name, viewer, internal, calibre_book_data=calibre_book_data, open_at=open_at) def view_specific_format(self, triggered): rows = list(self.gui.library_view.selectionModel().selectedRows()) if not rows or len(rows) == 0: d = error_dialog(self.gui, _('Cannot view'), _('No book selected')) d.exec() return db = self.gui.library_view.model().db rows = [r.row() for r in rows] book_ids = [db.id(r) for r in rows] formats = [[x.upper() for x in db.new_api.formats(book_id)] for book_id in book_ids] all_fmts = set() for x in formats: if x: for f in x: all_fmts.add(f) if not all_fmts: error_dialog(self.gui, _('Format unavailable'), _('Selected books have no formats'), show=True) return d = ChooseFormatDialog(self.gui, _('Choose the format to view'), list(sorted(all_fmts)), show_open_with=True) self.gui.book_converted.connect(d.book_converted) if d.exec() == QDialog.DialogCode.Accepted: formats = [[x.upper() for x in db.new_api.formats(book_id)] for book_id in book_ids] fmt = d.format() orig_num = len(rows) rows = [rows[i] for i in range(len(rows)) if formats[i] and fmt in formats[i]] if self._view_check(len(rows)): for row in rows: if d.open_with_format is None: self.view_format(row, fmt) else: self.open_fmt_with(row, *d.open_with_format) if len(rows) < orig_num: info_dialog(self.gui, _('Format unavailable'), _('Not all the selected books were available in' ' the %s format. You should convert' ' them first.')%fmt, show=True) self.gui.book_converted.disconnect(d.book_converted) def open_fmt_with(self, row, fmt, entry): book_id = self.gui.library_view.model().id(row) self.gui.book_details.open_fmt_with.emit(book_id, fmt, entry) def _view_check(self, num, max_=5, skip_dialog_name=None): if num <= max_: return True return question_dialog(self.gui, _('Multiple books selected'), _('You are attempting to open %d books. Opening too many ' 'books at once can be slow and have a negative effect on the ' 'responsiveness of your computer. Once started the process ' 'cannot be stopped until complete. Do you wish to continue?' ) % num, show_copy_button=False, skip_dialog_name=skip_dialog_name) def view_folder(self, *args, **kwargs): rows = self.gui.current_view().selectionModel().selectedRows() if not rows or len(rows) == 0: d = error_dialog(self.gui, _('Cannot open folder'), _('No book selected')) d.exec() return if not self._view_check(len(rows), max_=10, skip_dialog_name='open-folder-many-check'): return data_folder = kwargs.get('data_folder', False) db = self.gui.current_db for i, row in enumerate(rows): self.gui.extra_files_watcher.watch_book(db.id(row.row())) path = db.abspath(row.row()) if path: if data_folder: path = os.path.join(path, DATA_DIR_NAME) if not os.path.exists(path): try: os.mkdir(path) except Exception as e: error_dialog(self.gui, _('Failed to create folder'), str(e), show=True) continue try: open_local_file(path) except Exception as e: # We shouldn't get here ... error_dialog(self.gui, _('Cannot open folder'), str(e), show=True) if ismacos and i < len(rows) - 1: time.sleep(0.1) # Finder cannot handle multiple folder opens def view_folder_for_id(self, id_): self.gui.extra_files_watcher.watch_book(id_) path = self.gui.current_db.abspath(id_, index_is_id=True) open_local_file(path) def view_data_folder_for_id(self, id_): self.gui.extra_files_watcher.watch_book(id_) path = self.gui.current_db.abspath(id_, index_is_id=True) path = os.path.join(path, DATA_DIR_NAME) if not os.path.exists(path): try: os.mkdir(path) except Exception as e: error_dialog(self.gui, _('Failed to create folder'), str(e), show=True) return open_local_file(path) def view_book(self, triggered): rows = self.gui.current_view().selectionModel().selectedRows() self._view_books(rows) def view_internal(self, triggered): try: self.force_internal_viewer = True self.view_book(triggered) finally: self.force_internal_viewer = False def view_triggered(self, index): self._view_books([index]) def view_specific_book(self, index): self._view_books([index]) def view_random(self, *args): self.gui.iactions['Pick Random Book'].pick_random() self._view_books([self.gui.library_view.currentIndex()]) def _view_calibre_books(self, ids): db = self.gui.current_db views = [] for id_ in ids: try: title = db.title(id_, index_is_id=True) except: error_dialog(self.gui, _('Cannot view'), _('This book no longer exists in your library'), show=True) self.update_history([], remove={id_}) continue formats = db.new_api.formats(id_, verify_formats=True) if not formats: error_dialog(self.gui, _('Cannot view'), _('%s has no available formats.')%(title,), show=True) continue fmt = preferred_format(formats) views.append((id_, title)) self.view_format_by_id(id_, fmt) self.update_history(views) def update_history(self, views, remove=frozenset()): db = self.gui.current_db vh = tweaks['gui_view_history_size'] if views: seen = set() history = [] for id_, title in views + db.new_api.pref('gui_view_history', []): if title not in seen: seen.add(title) history.append((id_, title)) db.new_api.set_pref('gui_view_history', history[:vh]) self.build_menus(db) if remove: history = db.new_api.pref('gui_view_history', []) history = [x for x in history if x[0] not in remove] db.new_api.set_pref('gui_view_history', history[:vh]) self.build_menus(db) def view_device_book(self, path): pt = PersistentTemporaryFile('_view_device_book'+ os.path.splitext(path)[1]) self.persistent_files.append(pt) pt.close() self.gui.device_manager.view_book( Dispatcher(self.book_downloaded_for_viewing), path, pt.name) def _view_books(self, rows): if not rows or len(rows) == 0: return error_dialog(self.gui, _('Cannot view'), _('No books selected'), show=True) if not self._view_check(len(rows)): return if self.gui.current_view() is self.gui.library_view: ids = [] m = self.gui.library_view.model().id for r in rows: try: ids.append(m(r)) except Exception: pass if ids: self._view_calibre_books(ids) else: paths = self.gui.current_view().model().paths(rows) for path in paths: self.view_device_book(path)
17,082
Python
.py
351
35.897436
146
0.568987
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,944
show_book_details.py
kovidgoyal_calibre/src/calibre/gui2/actions/show_book_details.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from qt.core import Qt, sip from calibre.gui2 import error_dialog from calibre.gui2.actions import InterfaceAction from calibre.gui2.dialogs.book_info import BookInfo, DialogNumbers class ShowBookDetailsAction(InterfaceAction): name = 'Show Book Details' action_spec = (_('Book details'), 'dialog_information.png', _('Show the detailed metadata for the current book in a separate window'), _('I')) action_shortcut_name = _('Show Book details in a separate window') dont_add_to = frozenset(('context-menu-device',)) action_type = 'current' action_add_menu = True action_menu_clone_qaction = _('Show Book details in a separate window') def genesis(self): self.dialogs = [None, None, None] m = self.qaction.menu() self.show_info_locked = l = self.create_menu_action(m, 'show_locked_details', _('Show Book details in a separate locked window'), icon='drm-locked.png', shortcut=None) l.triggered.connect(self.open_locked_window) l = self.create_menu_action(m, 'close_all_details', _('Close all Book details windows'), icon='close.png', shortcut=None) l.triggered.connect(self.close_all_windows) self.qaction.triggered.connect(self.show_book_info) def show_book_info(self, *args, **kwargs): library_path = kwargs.get('library_path', None) book_id = kwargs.get('book_id', None) library_id = kwargs.get('library_id', None) locked = kwargs.get('locked', False) index = self.gui.library_view.currentIndex() if self.gui.current_view() is not self.gui.library_view and not library_path: error_dialog(self.gui, _('No detailed info available'), _('No detailed information is available for books ' 'on the device.')).exec() return if library_path: dn = DialogNumbers.DetailsLink else: if not index.isValid(): return dn = DialogNumbers.Locked if locked else DialogNumbers.Slaved if self.dialogs[dn] is not None: if dn == DialogNumbers.Slaved: # This is the slaved window. It will update automatically return else: # Replace the other windows. There is a signals race condition # between closing the existing window and opening the new one, # so do all the work here d = self.dialogs[dn] d.closed.disconnect(self.closed) d.done(0) self.dialogs[dn] = None try: d = BookInfo(self.gui, self.gui.library_view, index, self.gui.book_details.handle_click_from_popup, dialog_number=dn, library_id=library_id, library_path=library_path, book_id=book_id) except ValueError as e: error_dialog(self.gui, _('Book not found'), str(e)).exec() return d.open_cover_with.connect(self.gui.bd_open_cover_with, type=Qt.ConnectionType.QueuedConnection) self.dialogs[dn] = d d.closed.connect(self.closed, type=Qt.ConnectionType.QueuedConnection) d.show() def open_locked_window(self): self.show_book_info(locked=True) def shutting_down(self): self.close_all_windows() def close_all_windows(self): for dialog in [d for d in self.dialogs if d is not None]: dialog.done(0) def library_about_to_change(self, *args): for dialog in [d for d in self.dialogs[1:] if d is not None]: dialog.done(0) def closed(self, d): try: d.closed.disconnect(self.closed) self.dialogs[d.dialog_number] = None except ValueError: pass else: sip.delete(d) del d
4,035
Python
.py
87
36.229885
103
0.617086
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,945
restart.py
kovidgoyal_calibre/src/calibre/gui2/actions/restart.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from calibre.gui2.actions import InterfaceAction class RestartAction(InterfaceAction): name = 'Restart' action_spec = (_('Restart'), 'restart.png', _('Restart calibre'), 'Ctrl+R') def genesis(self): self.qaction.triggered.connect(self.restart) def restart(self, *args): self.gui.quit(restart=True)
483
Python
.py
12
35.833333
79
0.692641
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,946
virtual_library.py
kovidgoyal_calibre/src/calibre/gui2/actions/virtual_library.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> from qt.core import QAction, QToolButton from calibre.gui2.actions import InterfaceAction class VirtualLibraryAction(InterfaceAction): name = 'Virtual library' action_spec = ( _('Virtual library'), 'vl.png', _('Change the current Virtual library'), None ) action_type = 'current' action_add_menu = True popup_type = QToolButton.ToolButtonPopupMode.InstantPopup dont_add_to = frozenset(('context-menu-device', 'menubar-device')) def genesis(self): self.menu = m = self.qaction.menu() m.aboutToShow.connect(self.about_to_show_menu) self.qs_action = QAction(self.gui) self.gui.addAction(self.qs_action) self.qs_action.triggered.connect(self.gui.choose_vl_triggerred) self.gui.keyboard.register_shortcut(self.unique_name + ' - ' + 'quick-select-vl', _('Quick select Virtual library'), default_keys=('Ctrl+T',), action=self.qs_action, description=_('Quick select a Virtual library'), group=self.action_spec[0]) def about_to_show_menu(self): self.gui.build_virtual_library_menu(self.menu, add_tabs_action=False)
1,251
Python
.py
26
41.307692
89
0.686371
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,947
auto_scroll.py
kovidgoyal_calibre/src/calibre/gui2/actions/auto_scroll.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> from calibre.gui2.actions import InterfaceAction class AutoscrollBooksAction(InterfaceAction): name = 'Autoscroll Books' action_spec = (_('Auto scroll through the book list'), 'auto-scroll.png', _('Auto scroll through the book list, particularly useful with the cover browser open'), _('X')) dont_add_to = frozenset(('context-menu-device', 'menubar-device')) action_type = 'current' def genesis(self): self.qaction.triggered.connect(self.gui.toggle_auto_scroll) def location_selected(self, loc): enabled = loc == 'library' self.qaction.setEnabled(enabled) self.menuless_qaction.setEnabled(enabled)
774
Python
.py
15
45.133333
115
0.704787
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,948
all_actions.py
kovidgoyal_calibre/src/calibre/gui2/actions/all_actions.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2022, Charles Haley from functools import partial from math import ceil from qt.core import QIcon, QMenu, Qt, QToolButton from calibre.gui2.actions import InterfaceAction, show_menu_under_widget from calibre.gui2.preferences.toolbar import AllModel, CurrentModel from calibre.utils.icu import sort_key class AllGUIActions(InterfaceAction): name = 'All GUI actions' action_spec = (_('All GUI actions'), 'wizard.png', _("Show a menu of all available GUI and plugin actions.\nThis menu " "is not available when looking at books on a device"), None) action_type = 'current' popup_type = QToolButton.ToolButtonPopupMode.InstantPopup action_add_menu = True dont_add_to = frozenset() def genesis(self): self.layout_icon = QIcon.ic('wizard.png') self.menu = m = self.qaction.menu() m.aboutToShow.connect(self.about_to_show_menu) # Create a "hidden" menu that can have a shortcut. self.hidden_menu = QMenu() self.shortcut_action = self.create_menu_action( menu=self.hidden_menu, unique_name='Main window layout', shortcut=None, text=_("Save and restore layout item sizes, and add/remove/toggle " "layout items such as the search bar, tag browser, etc. "), icon='layout.png', triggered=self.show_menu) # We want to show the menu when a shortcut is used. Apparently the only way # to do that is to scan the toolbar(s) for the action button then exec the # associated menu. The search is done here to take adding and removing the # action from toolbars into account. # # If a shortcut is triggered and there isn't a toolbar button visible then # show the menu in the upper left corner of the library view pane. Yes, this # is a bit weird but it works as well as a popping up a dialog. def show_menu(self): show_menu_under_widget(self.gui, self.menu, self.qaction, self.name) def gui_layout_complete(self): self.qaction.menu().aboutToShow.connect(self.about_to_show_menu) def initialization_complete(self): self.populate_menu() def about_to_show_menu(self): self.populate_menu() def location_selected(self, loc): self.qaction.setEnabled(loc == 'library') def populate_menu(self): # Need to do this on every invocation because shortcuts can change m = self.qaction.menu() m.clear() name_data = {} # A dict of display names to actions data # Use model data from Preferences / Toolbars, with location 'toolbar' or # 'toolbar-device' depending on whether a device is connected. location = 'toolbar' + ('-device' if self.gui.location_manager.has_device else '') for model in (AllModel(location, self.gui), CurrentModel(location, self.gui)): for i in range(0, model.rowCount(None)): dex = model.index(i) name = model.names((dex,))[0] # this is the action name if name is not None and not name.startswith('---'): name_data[model.data(dex, Qt.ItemDataRole.DisplayRole)] = { 'action': model.name_to_action(name, self.gui), 'action_name':name, 'icon': model.data(dex, Qt.ItemDataRole.DecorationRole)} # The loop leaves the variable 'model' set to a valid value # Get display names of builtin and user plugins. We tell the difference # using the class full module name. Plugins start with 'calibre_plugins' builtin_actions = list() user_plugins = list() for display_name, act_data in name_data.items(): act = model.name_to_action(act_data['action_name'], self.gui) if act is not None: module = f'{act.__module__}.{act.__class__ .__name__}' if module.startswith('calibre_plugins'): user_plugins.append(display_name) else: builtin_actions.append(display_name) builtin_actions = sorted(builtin_actions, key=sort_key) user_plugins = sorted(user_plugins, key=sort_key) # Build the map of action shortcuts so we can display the shortcuts for # the actions. For shortcuts sometimes the action name and sometimes the # display name is used. Test both. Unfortunately, there are case # differences to deal with so we use lower case keys. lower_names = ({n['action_name'].lower() for n in name_data.values()} | {n.lower() for n in name_data.keys()}) kbd = self.gui.keyboard shortcut_map = {} for n,v in kbd.keys_map.items(): act_name = kbd.shortcuts[n]['name'].lower() if act_name in lower_names: shortcuts = list((sc.toString() for sc in v)) shortcut_map[act_name] = f'\t{", ".join(shortcuts)}' # This function constructs a menu action, dealing with the action being # either a popup menu or a dialog. It adds the shortcuts to the menu # line. Happily, a tab causes the shortcuts to be right-aligned. The tab # is added when the shortcut map is built. def add_action(menu, display_name): shortcuts = shortcut_map.get(display_name.lower(), '') act = name_data[display_name]['action'] if not hasattr(act, 'popup_type'): # FakeAction return menu_text = f'{display_name}{shortcuts}' icon = name_data[display_name]['icon'] if act.popup_type == QToolButton.ToolButtonPopupMode.MenuButtonPopup: if getattr(act, 'action_add_menu', None) or (getattr(act, 'qaction', None) and act.qaction.menu() and act.qaction.menu().children()): # The action offers both a 'click' and a menu. Use the menu. menu.addAction(icon, menu_text, partial(self._do_menu, display_name, act)) else: # The action is a dialog. menu.addAction(act.qaction.icon(), menu_text, partial(self._do_action, act)) else: # The action is a menu. menu.addAction(icon, menu_text, partial(self._do_menu, display_name, act)) # Finally the real work, building the action menu. Partition long lists # of actions into sublists of some arbitrary length. def partition(names): count_in_partition = 10 # arbitrary if len(names) >= count_in_partition: partition_count = len(names) // (count_in_partition - 1) step = int(ceil(len(names) / partition_count)) for first in range(0, len(names), step): last = min(first + step - 1, len(names) - 1) dnf = names[first] dnl = names[last] if dnf != dnl: sm = m.addMenu(QIcon.ic('wizard.png'), f'{dnf} - {dnl}') else: sm = m.addMenu(QIcon.ic('wizard.png'), f'{dnf}') for name in names[first:last+1]: add_action(sm, name) else: for name in names: add_action(m, name) # Add a named section for builtin actions if user plugins are installed. if user_plugins: m.addSection(_('Built-in calibre actions') + ' ') partition(builtin_actions) m.addSection(_('Plugins') + ' ') partition(user_plugins) else: partition(builtin_actions) # Add access to the toolbars and keyboard shortcuts preferences dialogs m.addSection(_('Preferences') + ' ') m.addAction(QIcon.ic('wizard.png'), _('Toolbars'), self._do_pref_toolbar) m.addAction(QIcon.ic('keyboard-prefs.png'), _('Keyboard shortcuts'), self._do_pref_shortcuts) def _do_pref_toolbar(self): self.gui.iactions['Preferences'].do_config(initial_plugin=('Interface', 'Toolbar'), close_after_initial=True) def _do_pref_shortcuts(self): self.gui.iactions['Preferences'].do_config(initial_plugin=('Advanced', 'Keyboard'), close_after_initial=True) def _do_action(self, action): action.qaction.trigger() def _do_menu(self, name, action): # This method clones and shows the action's menu. If the action is in a # context menu, the action menu is displayed there without using this # method. If not it is displayed underneath a toolbar or menu button. If # neither is true then the menu is displayed in the upper left corner. menu = QMenu() menu.addSection(name) action.qaction.menu().aboutToShow.emit() for m in action.qaction.menu().actions(): menu.addAction(m) show_menu_under_widget(self.gui, menu, self.qaction, self.name)
9,195
Python
.py
164
43.817073
149
0.60462
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,949
random.py
kovidgoyal_calibre/src/calibre/gui2/actions/random.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import random from calibre.gui2.actions import InterfaceAction class PickRandomAction(InterfaceAction): name = 'Pick Random Book' action_spec = (_('Pick a random book'), 'random.png', _('Select a random book from your calibre library'), ()) dont_add_to = frozenset(['context-menu-device']) def genesis(self): self.qaction.triggered.connect(self.pick_random) self.recently_picked = {} try: self.randint = random.SystemRandom().randint except Exception: self.randint = random.randint def location_selected(self, loc): enabled = loc == 'library' self.qaction.setEnabled(enabled) self.menuless_qaction.setEnabled(enabled) def library_changed(self, db): self.recently_picked = {} def pick_random(self): lv = self.gui.library_view count = lv.model().rowCount(None) rp = self.recently_picked while len(rp) > count // 2: n = next(iter(rp)) del rp[n] while True: pick = self.randint(0, count) if pick in rp: continue rp[pick] = True break lv.set_current_row(pick) lv.scroll_to_row(pick)
1,405
Python
.py
39
27.769231
68
0.608118
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,950
fb2_input.py
kovidgoyal_calibre/src/calibre/gui2/convert/fb2_input.py
__license__ = 'GPL 3' __copyright__ = '2009, John Schember <john@nachtimwald.com>' __docformat__ = 'restructuredtext en' from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2.convert import Widget from calibre.gui2.convert.fb2_input_ui import Ui_Form class PluginWidget(Widget, Ui_Form): TITLE = _('FB2 input') HELP = _('Options specific to')+' FB2 '+_('input') COMMIT_NAME = 'fb2_input' ICON = 'mimetypes/fb2.png' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['input']['fb2']) self.db, self.book_id = db, book_id self.initialize_options(get_option, get_help, db, book_id)
704
Python
.py
15
42.666667
76
0.681287
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,951
txt_input.py
kovidgoyal_calibre/src/calibre/gui2/convert/txt_input.py
__license__ = 'GPL 3' __copyright__ = '2009, John Schember <john@nachtimwald.com>' __docformat__ = 'restructuredtext en' from qt.core import QListWidgetItem, Qt from calibre.ebooks.conversion.config import OPTIONS from calibre.ebooks.conversion.plugins.txt_input import MD_EXTENSIONS from calibre.gui2.convert import Widget from calibre.gui2.convert.txt_input_ui import Ui_Form from polyglot.builtins import iteritems, itervalues class PluginWidget(Widget, Ui_Form): TITLE = _('TXT input') HELP = _('Options specific to')+' TXT '+_('input') COMMIT_NAME = 'txt_input' ICON = 'mimetypes/txt.png' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['input']['txt']) self.db, self.book_id = db, book_id for x in get_option('paragraph_type').option.choices: self.opt_paragraph_type.addItem(x) for x in get_option('formatting_type').option.choices: self.opt_formatting_type.addItem(x) self.md_map = {} for name, text in iteritems(MD_EXTENSIONS): i = QListWidgetItem(f'{name} - {text}', self.opt_markdown_extensions) i.setFlags(Qt.ItemFlag.ItemIsUserCheckable | Qt.ItemFlag.ItemIsEnabled) i.setData(Qt.ItemDataRole.UserRole, name) self.md_map[name] = i self.initialize_options(get_option, get_help, db, book_id) def set_value_handler(self, g, val): if g is self.opt_markdown_extensions: for i in itervalues(self.md_map): i.setCheckState(Qt.CheckState.Unchecked) for x in val.split(','): x = x.strip() if x in self.md_map: self.md_map[x].setCheckState(Qt.CheckState.Checked) return True def get_value_handler(self, g): if g is not self.opt_markdown_extensions: return Widget.get_value_handler(self, g) return ', '.join(str(i.data(Qt.ItemDataRole.UserRole) or '') for i in self.md_map.values() if i.checkState() == Qt.CheckState.Checked) def connect_gui_obj_handler(self, g, f): if g is not self.opt_markdown_extensions: raise NotImplementedError() g.itemChanged.connect(self.changed_signal)
2,280
Python
.py
45
42.155556
142
0.653483
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,952
xpath_wizard.py
kovidgoyal_calibre/src/calibre/gui2/convert/xpath_wizard.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from qt.core import QComboBox, QDialog, QDialogButtonBox, QHBoxLayout, QIcon, QLabel, QSize, Qt, QToolButton, QVBoxLayout, QWidget from calibre.gui2.convert.xpath_wizard_ui import Ui_Form from calibre.gui2.widgets import HistoryLineEdit from calibre.utils.localization import localize_user_manual_link class WizardWidget(QWidget, Ui_Form): def __init__(self, parent=None): QWidget.__init__(self, parent) self.setupUi(self) try: self.example_label.setText(self.example_label.text() % localize_user_manual_link( 'https://manual.calibre-ebook.com/xpath.html')) except TypeError: pass @property def xpath(self): tag = str(self.tag.currentText()).strip() if tag != '*': tag = 'h:'+tag attr, val = map(str, (self.attribute.text(), self.value.text())) attr, val = attr.strip(), val.strip() q = '' if attr: if val: q = '[re:test(@%s, "%s", "i")]'%(attr, val) else: q = '[@%s]'%attr elif val: q = '[re:test(., "%s", "i")]'%(val) expr = '//'+tag + q return expr class Wizard(QDialog): def __init__(self, parent=None): QDialog.__init__(self, parent) self.resize(440, 480) self.verticalLayout = QVBoxLayout(self) self.widget = WizardWidget(self) self.verticalLayout.addWidget(self.widget) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Orientation.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.StandardButton.Cancel|QDialogButtonBox.StandardButton.Ok) self.verticalLayout.addWidget(self.buttonBox) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.setWindowModality(Qt.WindowModality.WindowModal) @property def xpath(self): return self.widget.xpath class XPathEdit(QWidget): def __init__(self, parent=None, object_name='', show_msg=True): QWidget.__init__(self, parent) self.h = h = QHBoxLayout(self) h.setContentsMargins(0, 0, 0, 0) self.l = l = QVBoxLayout() h.addLayout(l) self.button = b = QToolButton(self) b.setIcon(QIcon.ic('wizard.png')) b.setToolTip(_('Use a wizard to generate the XPath expression')) b.clicked.connect(self.wizard) h.addWidget(b) self.edit = e = HistoryLineEdit(self) e.setMinimumWidth(350) e.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon) e.setMinimumContentsLength(30) self.msg = QLabel('') l.addWidget(self.msg) l.addWidget(self.edit) if object_name: self.setObjectName(object_name) if show_msg: b.setIconSize(QSize(40, 40)) self.msg.setBuddy(self.edit) else: self.msg.setVisible(False) l.setContentsMargins(0, 0, 0, 0) def setPlaceholderText(self, val): self.edit.setPlaceholderText(val) def wizard(self): wiz = Wizard(self) if wiz.exec() == QDialog.DialogCode.Accepted: self.edit.setText(wiz.xpath) def setObjectName(self, *args): QWidget.setObjectName(self, *args) if hasattr(self, 'edit'): self.edit.initialize('xpath_edit_'+str(self.objectName())) def set_msg(self, msg): self.msg.setText(msg) @property def text(self): return str(self.edit.text()) @text.setter def text(self, val): self.edit.setText(str(val)) value = text @property def xpath(self): return self.text def check(self): from calibre.ebooks.oeb.base import XPath try: if self.text.strip(): XPath(self.text) except: import traceback traceback.print_exc() return False return True if __name__ == '__main__': from qt.core import QApplication app = QApplication([]) w = XPathEdit() w.setObjectName('test') w.show() app.exec() print(w.xpath)
4,365
Python
.py
118
28.618644
130
0.618337
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,953
pml_output.py
kovidgoyal_calibre/src/calibre/gui2/convert/pml_output.py
__license__ = 'GPL 3' __copyright__ = '2009, John Schember <john@nachtimwald.com>' __docformat__ = 'restructuredtext en' from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2.convert import Widget from calibre.gui2.convert.pmlz_output_ui import Ui_Form format_model = None class PluginWidget(Widget, Ui_Form): TITLE = _('PMLZ output') HELP = _('Options specific to')+' PMLZ '+_('output') COMMIT_NAME = 'pmlz_output' ICON = 'mimetypes/unknown.png' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['output']['pml']) self.db, self.book_id = db, book_id self.initialize_options(get_option, get_help, db, book_id)
738
Python
.py
16
42
76
0.689944
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,954
snb_output.py
kovidgoyal_calibre/src/calibre/gui2/convert/snb_output.py
__license__ = 'GPL 3' __copyright__ = '2010, Li Fanxi <lifanxi@freemindworld.com>' __docformat__ = 'restructuredtext en' from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2.convert import Widget from calibre.gui2.convert.snb_output_ui import Ui_Form newline_model = None class PluginWidget(Widget, Ui_Form): TITLE = _('SNB output') HELP = _('Options specific to')+' SNB '+_('output') COMMIT_NAME = 'snb_output' ICON = 'mimetypes/snb.png' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['output']['snb']) self.db, self.book_id = db, book_id self.initialize_options(get_option, get_help, db, book_id)
731
Python
.py
16
41.5625
76
0.686883
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,955
azw3_output.py
kovidgoyal_calibre/src/calibre/gui2/convert/azw3_output.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2.convert import Widget from calibre.gui2.convert.azw3_output_ui import Ui_Form font_family_model = None class PluginWidget(Widget, Ui_Form): TITLE = _('AZW3 output') HELP = _('Options specific to')+' AZW3 '+_('output') COMMIT_NAME = 'azw3_output' ICON = 'mimetypes/azw3.png' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['output']['azw3']) self.db, self.book_id = db, book_id self.initialize_options(get_option, get_help, db, book_id)
768
Python
.py
17
41
76
0.688259
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,956
bulk.py
kovidgoyal_calibre/src/calibre/gui2/convert/bulk.py
__license__ = 'GPL 3' __copyright__ = '2009, John Schember <john@nachtimwald.com>' __docformat__ = 'restructuredtext en' import shutil from qt.core import QDialog, QDialogButtonBox, QModelIndex from calibre.ebooks.conversion.config import get_output_formats, sort_formats_by_preference from calibre.ebooks.conversion.plumber import Plumber from calibre.gui2.convert import GuiRecommendations from calibre.gui2.convert.heuristics import HeuristicsWidget from calibre.gui2.convert.look_and_feel import LookAndFeelWidget from calibre.gui2.convert.page_setup import PageSetupWidget from calibre.gui2.convert.search_and_replace import SearchAndReplaceWidget from calibre.gui2.convert.single import Config, GroupModel, gprefs from calibre.gui2.convert.structure_detection import StructureDetectionWidget from calibre.gui2.convert.toc import TOCWidget from calibre.utils.config import prefs from calibre.utils.localization import ngettext from calibre.utils.logging import Log class BulkConfig(Config): def __init__(self, parent, db, preferred_output_format=None, has_saved_settings=True, book_ids=()): QDialog.__init__(self, parent) self.widgets = [] self.setupUi() try: self.num_of_books = len(book_ids) except Exception: self.num_of_books = 1 self.setup_output_formats(db, preferred_output_format) self.db = db self.setup_pipeline() self.input_label.hide() self.input_formats.hide() self.opt_individual_saved_settings.setVisible(True) self.opt_individual_saved_settings.setChecked(True) self.opt_individual_saved_settings.setToolTip(_('For ' 'settings that cannot be specified in this dialog, use the ' 'values saved in a previous conversion (if they exist) instead ' 'of using the defaults specified in the Preferences')) self.output_formats.currentIndexChanged.connect(self.setup_pipeline) self.groups.setSpacing(5) self.groups.activated[(QModelIndex)].connect(self.show_pane) self.groups.clicked[(QModelIndex)].connect(self.show_pane) self.groups.entered[(QModelIndex)].connect(self.show_group_help) rb = self.buttonBox.button(QDialogButtonBox.StandardButton.RestoreDefaults) rb.setVisible(False) self.groups.setMouseTracking(True) if not has_saved_settings: o = self.opt_individual_saved_settings o.setEnabled(False) o.setToolTip(_('None of the selected books have saved conversion ' 'settings.')) o.setChecked(False) self.restore_geometry(gprefs, 'convert_bulk_dialog_geom') def setup_pipeline(self, *args): oidx = self.groups.currentIndex().row() output_format = self.output_format input_path = 'dummy.epub' output_path = 'dummy.'+output_format log = Log() log.outputs = [] self.plumber = Plumber(input_path, output_path, log, merge_plugin_recs=False) self.plumber.merge_plugin_recs(self.plumber.output_plugin) def widget_factory(cls): return cls(self, self.plumber.get_option_by_name, self.plumber.get_option_help, self.db) self.setWindowTitle( ngettext(_('Bulk convert one book'), _('Bulk convert {} books'), self.num_of_books).format(self.num_of_books) ) lf = widget_factory(LookAndFeelWidget) hw = widget_factory(HeuristicsWidget) sr = widget_factory(SearchAndReplaceWidget) ps = widget_factory(PageSetupWidget) sd = widget_factory(StructureDetectionWidget) toc = widget_factory(TOCWidget) toc.manually_fine_tune_toc.hide() output_widget = self.plumber.output_plugin.gui_configuration_widget( self, self.plumber.get_option_by_name, self.plumber.get_option_help, self.db) self.break_cycles() widgets = self.widgets = [lf, hw, ps, sd, toc, sr] if output_widget is not None: widgets.append(output_widget) for w in widgets: w.set_help_signal.connect(self.help.setPlainText) w.setVisible(False) w.layout().setContentsMargins(0, 0, 0, 0) self._groups_model = GroupModel(widgets) self.groups.setModel(self._groups_model) idx = oidx if -1 < oidx < self._groups_model.rowCount() else 0 self.groups.setCurrentIndex(self._groups_model.index(idx)) self.show_pane(idx) try: shutil.rmtree(self.plumber.archive_input_tdir, ignore_errors=True) except: pass def setup_output_formats(self, db, preferred_output_format): if preferred_output_format: preferred_output_format = preferred_output_format.upper() output_formats = get_output_formats(preferred_output_format) preferred_output_format = preferred_output_format if \ preferred_output_format and preferred_output_format \ in output_formats else sort_formats_by_preference(output_formats, [prefs['output_format']])[0] self.output_formats.addItems(str(x.upper()) for x in output_formats) self.output_formats.setCurrentIndex(output_formats.index(preferred_output_format)) def accept(self): recs = GuiRecommendations() for w in self._groups_model.widgets: if not w.pre_commit_check(): return x = w.commit(save_defaults=False) recs.update(x) self._recommendations = recs QDialog.accept(self) def done(self, r): if self.isVisible(): self.save_geometry(gprefs, 'convert_bulk_dialog_geom') return QDialog.done(self, r)
5,807
Python
.py
119
39.781513
121
0.675962
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,957
page_setup.py
kovidgoyal_calibre/src/calibre/gui2/convert/page_setup.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from qt.core import QAbstractListModel, QItemSelectionModel, QModelIndex, Qt from calibre.customize.ui import input_profiles, output_profiles from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2.convert import Widget from calibre.gui2.convert.page_setup_ui import Ui_Form class ProfileModel(QAbstractListModel): def __init__(self, profiles): QAbstractListModel.__init__(self) self.profiles = list(profiles) def rowCount(self, *args): return len(self.profiles) def data(self, index, role): profile = self.profiles[index.row()] if role == Qt.ItemDataRole.DisplayRole: if profile.name.startswith('Default '): return _('Default profile') return __builtins__['_'](profile.name) if role in (Qt.ItemDataRole.StatusTipRole, Qt.ItemDataRole.WhatsThisRole): w, h = profile.screen_size if w >= 10000: ss = _('unlimited') else: ss = _('%(width)d x %(height)d pixels') % dict(width=w, height=h) ss = _('Screen size: %s') % ss return (f'{profile.description} [{ss}]') return None class PageSetupWidget(Widget, Ui_Form): TITLE = _('Page setup') COMMIT_NAME = 'page_setup' def __init__(self, parent, get_option, get_help, db=None, book_id=None): self.__connections = [] Widget.__init__(self, parent, OPTIONS['pipe']['page_setup']) self.db, self.book_id = db, book_id self.input_model = ProfileModel(input_profiles()) self.output_model = ProfileModel(output_profiles()) self.opt_input_profile.setModel(self.input_model) self.opt_output_profile.setModel(self.output_model) for g, slot in self.__connections: g.selectionModel().currentChanged.connect(slot) del self.__connections for x in (self.opt_input_profile, self.opt_output_profile): x.setMouseTracking(True) x.entered[(QModelIndex)].connect(self.show_desc) self.initialize_options(get_option, get_help, db, book_id) self.opt_input_profile.setToolTip('') self.opt_output_profile.setToolTip('') def show_desc(self, index): desc = str(index.model().data(index, Qt.ItemDataRole.StatusTipRole) or '') self.profile_description.setText(desc) def connect_gui_obj_handler(self, g, slot): if g not in (self.opt_input_profile, self.opt_output_profile): raise NotImplementedError() self.__connections.append((g, slot)) def set_value_handler(self, g, val): if g in (self.opt_input_profile, self.opt_output_profile): g.clearSelection() for idx, p in enumerate(g.model().profiles): if p.short_name == val: break idx = g.model().index(idx) sm = g.selectionModel() g.setCurrentIndex(idx) sm.select(idx, QItemSelectionModel.SelectionFlag.SelectCurrent) return True return False def get_value_handler(self, g): if g in (self.opt_input_profile, self.opt_output_profile): idx = g.currentIndex().row() return g.model().profiles[idx].short_name return Widget.get_value_handler(self, g)
3,470
Python
.py
74
37.689189
82
0.632218
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,958
pdf_output.py
kovidgoyal_calibre/src/calibre/gui2/convert/pdf_output.py
__license__ = 'GPL 3' __copyright__ = '2009, John Schember <john@nachtimwald.com>' __docformat__ = 'restructuredtext en' from qt.core import QCheckBox, QDoubleSpinBox, QFormLayout, QHBoxLayout, QVBoxLayout from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2.convert import Widget from calibre.gui2.convert.pdf_output_ui import Ui_Form from calibre.utils.localization import localize_user_manual_link paper_size_model = None orientation_model = None class PluginWidget(Widget, Ui_Form): TITLE = _('PDF output') HELP = _('Options specific to')+' PDF '+_('output') COMMIT_NAME = 'pdf_output' ICON = 'mimetypes/pdf.png' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['output']['pdf']) self.db, self.book_id = db, book_id try: self.hf_label.setText(self.hf_label.text() % localize_user_manual_link( 'https://manual.calibre-ebook.com/conversion.html#converting-to-pdf')) except TypeError: pass # link already localized self.opt_paper_size.initialize(get_option('paper_size').option.choices) for x in get_option('unit').option.choices: self.opt_unit.addItem(x) for x in get_option('pdf_standard_font').option.choices: self.opt_pdf_standard_font.addItem(x) self.initialize_options(get_option, get_help, db, book_id) self.layout().setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow) self.template_box.layout().setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow) self.profile_size_toggled() def profile_size_toggled(self): enabled = not self.opt_use_profile_size.isChecked() self.opt_paper_size.setEnabled(enabled) self.opt_custom_size.setEnabled(enabled) self.opt_unit.setEnabled(enabled) def setupUi(self, *a): Ui_Form.setupUi(self, *a) v = self.page_margins_box.v = QVBoxLayout(self.page_margins_box) self.opt_pdf_use_document_margins = c = QCheckBox(_('Use page margins from the &document being converted')) v.addWidget(c) h = self.page_margins_box.h = QHBoxLayout() l = self.page_margins_box.l = QFormLayout() r = self.page_margins_box.r = QFormLayout() h.addLayout(l), h.addLayout(r) v.addLayout(h) def margin(which): w = QDoubleSpinBox(self) w.setRange(-100, 500), w.setSuffix(' pt'), w.setDecimals(1) setattr(self, 'opt_pdf_page_margin_' + which, w) return w l.addRow(_('&Left:'), margin('left')) l.addRow(_('&Right:'), margin('right')) r.addRow(_('&Top:'), margin('top')) r.addRow(_('&Bottom:'), margin('bottom')) self.opt_use_profile_size.toggled.connect(self.profile_size_toggled)
2,902
Python
.py
57
43
115
0.663017
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,959
rtf_input.py
kovidgoyal_calibre/src/calibre/gui2/convert/rtf_input.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2.convert import Widget from calibre.gui2.convert.rtf_input_ui import Ui_Form class PluginWidget(Widget, Ui_Form): TITLE = _('RTF input') HELP = _('Options specific to')+' RTF '+_('input') COMMIT_NAME = 'rtf_input' ICON = 'mimetypes/rtf.png' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['input']['rtf']) self.initialize_options(get_option, get_help, db, book_id)
648
Python
.py
14
42.214286
76
0.6874
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,960
gui_conversion.py
kovidgoyal_calibre/src/calibre/gui2/convert/gui_conversion.py
__license__ = 'GPL 3' __copyright__ = '2009, John Schember <john@nachtimwald.com>' __docformat__ = 'restructuredtext en' import os from optparse import OptionParser from calibre.customize.conversion import DummyReporter, OptionRecommendation from calibre.customize.ui import plugin_for_catalog_format from calibre.ebooks.conversion.plumber import Plumber from calibre.utils.logging import Log def gui_convert(input, output, recommendations, notification=DummyReporter(), abort_after_input_dump=False, log=None, override_input_metadata=False): recommendations = list(recommendations) recommendations.append(('verbose', 2, OptionRecommendation.HIGH)) if log is None: log = Log() plumber = Plumber(input, output, log, report_progress=notification, abort_after_input_dump=abort_after_input_dump, override_input_metadata=override_input_metadata) plumber.merge_ui_recommendations(recommendations) plumber.run() def gui_convert_recipe(input, output, recommendations, notification=DummyReporter(), abort_after_input_dump=False, log=None, override_input_metadata=False): os.environ['CALIBRE_RECIPE_URN'] = input gui_convert('from-gui.recipe', output, recommendations, notification=notification, abort_after_input_dump=abort_after_input_dump, log=log, override_input_metadata=override_input_metadata) def gui_convert_override(input, output, recommendations, notification=DummyReporter(), abort_after_input_dump=False, log=None): gui_convert(input, output, recommendations, notification=notification, abort_after_input_dump=abort_after_input_dump, log=log, override_input_metadata=True) def gui_catalog(fmt, title, dbspec, ids, out_file_name, sync, fmt_options, connected_device, notification=DummyReporter(), log=None): if log is None: log = Log() from calibre.library import db from calibre.utils.config import prefs prefs.refresh() db = db(read_only=True) db.catalog_plugin_on_device_temp_mapping = dbspec # Create a minimal OptionParser that we can append to parser = OptionParser() args = [] parser.add_option("--verbose", action="store_true", dest="verbose", default=True) opts, args = parser.parse_args() # Populate opts # opts.gui_search_text = something opts.catalog_title = title opts.connected_device = connected_device opts.ids = ids opts.search_text = None opts.sort_by = None opts.sync = sync # Extract the option dictionary to comma-separated lists for option in fmt_options: if isinstance(fmt_options[option],list): setattr(opts,option, ','.join(fmt_options[option])) else: setattr(opts,option, fmt_options[option]) # Fetch and run the plugin for fmt # Returns 0 if successful, 1 if no catalog built plugin = plugin_for_catalog_format(fmt) return plugin.run(out_file_name, opts, db, notification=notification)
3,026
Python
.py
63
42.095238
92
0.724898
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,961
txtz_output.py
kovidgoyal_calibre/src/calibre/gui2/convert/txtz_output.py
__license__ = 'GPL 3' __copyright__ = '2011, John Schember <john@nachtimwald.com>' __docformat__ = 'restructuredtext en' from calibre.gui2.convert.txt_output import PluginWidget as TXTPluginWidget class PluginWidget(TXTPluginWidget): TITLE = _('TXTZ output') HELP = _('Options specific to')+' TXTZ '+_('output') COMMIT_NAME = 'txtz_output'
357
Python
.py
8
41.5
75
0.712209
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,962
toc.py
kovidgoyal_calibre/src/calibre/gui2/convert/toc.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2 import error_dialog from calibre.gui2.convert import Widget from calibre.gui2.convert.toc_ui import Ui_Form from calibre.utils.localization import localize_user_manual_link class TOCWidget(Widget, Ui_Form): TITLE = _('Table of\nContents') ICON = 'toc.png' HELP = _('Control the creation/conversion of the Table of Contents.') COMMIT_NAME = 'toc' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['pipe']['toc']) self.db, self.book_id = db, book_id self.initialize_options(get_option, get_help, db, book_id) self.opt_level1_toc.set_msg(_('Level &1 TOC (XPath expression):')) self.opt_level2_toc.set_msg(_('Level &2 TOC (XPath expression):')) self.opt_level3_toc.set_msg(_('Level &3 TOC (XPath expression):')) try: self.help_label.setText(self.help_label.text() % localize_user_manual_link( 'https://manual.calibre-ebook.com/conversion.html#table-of-contents')) except TypeError: pass # link already localized def pre_commit_check(self): for x in ('level1', 'level2', 'level3'): x = getattr(self, 'opt_'+x+'_toc') if not x.check(): error_dialog(self, _('Invalid XPath'), _('The XPath expression %s is invalid.')%x.text).exec() return False return True
1,654
Python
.py
34
41.029412
87
0.639354
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,963
font_key.py
kovidgoyal_calibre/src/calibre/gui2/convert/font_key.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from qt.core import QDialog, QDialogButtonBox from calibre.gui2.convert.font_key_ui import Ui_Dialog from calibre.utils.localization import localize_user_manual_link class FontKeyChooser(QDialog, Ui_Dialog): def __init__(self, parent=None, base_font_size=0.0, font_key=None): QDialog.__init__(self, parent) self.setupUi(self) try: self.wh_label.setText(self.wh_label.text() % localize_user_manual_link( 'https://manual.calibre-ebook.com/conversion.html#font-size-rescaling')) except TypeError: pass # link already localized self.default_font_key = font_key self.default_base_font_size = base_font_size self.buttonBox.clicked.connect(self.button_clicked) self.button_use_default.clicked.connect(self.use_default) for x in ('input_base_font_size', 'input_font_size', 'output_base_font_size'): getattr(self, x).valueChanged.connect(self.calculate) self.font_size_key.textChanged.connect(self.calculate) self.initialize() def initialize(self): self.input_base_font_size.setValue(12.0) self.input_font_size.setValue(12.0) self.input_mapped_font_size.setText('0.0 pt') self.output_base_font_size.setValue(self.default_base_font_size) if self.default_font_key: self.font_size_key.setText(self.default_font_key) else: self.font_size_key.setText('') self.calculate() def button_clicked(self, button): if button is self.buttonBox.button(QDialogButtonBox.StandardButton.RestoreDefaults): self.output_base_font_size.setValue(0.0) self.font_size_key.setText('') self.calculate() def get_profile_values(self): from calibre.ebooks.conversion.config import load_defaults recs = load_defaults('page_setup') pfname = recs.get('output_profile', 'default') from calibre.customize.ui import output_profiles for profile in output_profiles(): if profile.short_name == pfname: break dbase = profile.fbase fsizes = profile.fkey return dbase, fsizes @property def fsizes(self): key = str(self.font_size_key.text()).strip() return [float(x.strip()) for x in key.split(',' if ',' in key else ' ') if x.strip()] @property def dbase(self): return self.output_base_font_size.value() def calculate(self, *args): sbase = self.input_base_font_size.value() dbase = self.dbase fsize = self.input_font_size.value() try: fsizes = self.fsizes except: return if dbase == 0.0 or not fsizes: pd, pfs = self.get_profile_values() if dbase == 0.0: dbase = pd if not fsizes: fsizes = pfs from calibre.ebooks.oeb.transforms.flatcss import KeyMapper mapper = KeyMapper(sbase, dbase, fsizes) msize = mapper[fsize] self.input_mapped_font_size.setText('%.1f pt'%msize) def use_default(self): dbase, fsizes = self.get_profile_values() self.output_base_font_size.setValue(dbase) self.font_size_key.setText(', '.join(['%.1f'%x for x in fsizes])) if __name__ == '__main__': from qt.core import QApplication app = QApplication([]) d = FontKeyChooser() d.exec() del app
3,633
Python
.py
86
33.465116
93
0.630743
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,964
docx_input.py
kovidgoyal_calibre/src/calibre/gui2/convert/docx_input.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2.convert import Widget from calibre.gui2.convert.docx_input_ui import Ui_Form class PluginWidget(Widget, Ui_Form): TITLE = _('DOCX input') HELP = _('Options specific to')+' DOCX '+_('input') COMMIT_NAME = 'docx_input' ICON = 'mimetypes/docx.png' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['input']['docx']) self.initialize_options(get_option, get_help, db, book_id)
654
Python
.py
14
42.642857
76
0.690363
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,965
metadata.py
kovidgoyal_calibre/src/calibre/gui2/convert/metadata.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os import re from qt.core import QApplication, QPixmap from calibre.ebooks.conversion.config import OPTIONS from calibre.ebooks.metadata import MetaInformation, string_to_authors, title_sort from calibre.ebooks.metadata.opf2 import metadata_to_opf from calibre.gui2 import choose_images, error_dialog from calibre.gui2.convert import Widget from calibre.gui2.convert.metadata_ui import Ui_Form from calibre.library.comments import comments_to_html from calibre.ptempfile import PersistentTemporaryFile from calibre.utils.config import tweaks from calibre.utils.icu import sort_key def create_opf_file(db, book_id, opf_file=None): mi = db.get_metadata(book_id, index_is_id=True) old_cover = mi.cover mi.cover = None mi.application_id = mi.uuid raw = metadata_to_opf(mi) mi.cover = old_cover if opf_file is None: opf_file = PersistentTemporaryFile('.opf') opf_file.write(raw) opf_file.close() return mi, opf_file def create_cover_file(db, book_id): cover = db.cover(book_id, index_is_id=True) cf = None if cover: cf = PersistentTemporaryFile('.jpeg') cf.write(cover) cf.close() return cf class MetadataWidget(Widget, Ui_Form): TITLE = _('Metadata') ICON = 'dialog_information.png' HELP = _('Set the metadata. The output file will contain as much of this ' 'metadata as possible.') COMMIT_NAME = 'metadata' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['pipe']['metadata']) self.db, self.book_id = db, book_id self.cover_changed = False self.cover_data = None if self.db is not None: self.initialize_metadata_options() self.initialize_options(get_option, get_help, db, book_id) self.cover_button.clicked.connect(self.select_cover) self.comment.hide_toolbars() self.cover.cover_changed.connect(self.change_cover) self.series.currentTextChanged.connect(self.series_changed) self.cover.draw_border = False def change_cover(self, data): self.cover_changed = True self.cover_data = data def deduce_author_sort(self, *args): au = str(self.author.currentText()) au = re.sub(r'\s+et al\.$', '', au) authors = string_to_authors(au) self.author_sort.setText(self.db.author_sort_from_authors(authors)) self.author_sort.home(False) 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(self.devicePixelRatio()) self.cover.setPixmap(pm) self.cover_data = cover self.set_cover_tooltip(pm) else: pm = QApplication.instance().cached_qpixmap('default_cover.png', device_pixel_ratio=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 series_changed(self): self.series_index.setEnabled(len(self.series.currentText().strip()) > 0) def set_cover_tooltip(self, pm): tt = _('Cover size: %(width)d x %(height)d pixels') % dict( width=pm.width(), height=pm.height()) self.cover.setToolTip(tt) def initialize_combos(self): self.initalize_authors() self.initialize_series() self.initialize_publisher() def initalize_authors(self): all_authors = self.db.all_authors() all_authors.sort(key=lambda x : sort_key(x[1])) self.author.set_separator('&') self.author.set_space_before_sep(True) self.author.set_add_separator(tweaks['authors_completer_append_separator']) self.author.update_items_cache(self.db.new_api.all_field_names('authors')) au = self.db.authors(self.book_id, True) if not au: au = _('Unknown') au = ' & '.join([a.strip().replace('|', ',') for a in au.split(',')]) self.author.show_initial_value(au) self.author.home(False) def initialize_series(self): self.series.set_separator(None) self.series.update_items_cache(self.db.new_api.all_field_names('series')) def initialize_publisher(self): self.publisher.set_separator(None) self.publisher.update_items_cache(self.db.new_api.all_field_names('publisher')) def get_title_and_authors(self): title = str(self.title.text()).strip() if not title: title = _('Unknown') authors = str(self.author.text()).strip() authors = string_to_authors(authors) if authors else [_('Unknown')] return title, authors def get_metadata(self): title, authors = self.get_title_and_authors() mi = MetaInformation(title, authors) publisher = str(self.publisher.text()).strip() if publisher: mi.publisher = publisher author_sort = str(self.author_sort.text()).strip() if author_sort: mi.author_sort = author_sort comments = self.comment.html if comments: mi.comments = comments mi.series_index = float(self.series_index.value()) series = str(self.series.currentText()).strip() if series: mi.series = series tags = [t.strip() for t in str(self.tags.text()).strip().split(',')] if tags: mi.tags = tags return mi def select_cover(self): files = choose_images(self, 'change cover dialog', _('Choose cover for ') + str(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 OSError 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 get_recommendations(self): return { 'prefer_metadata_cover': bool(self.opt_prefer_metadata_cover.isChecked()), } def pre_commit_check(self): if self.db is None: return True db = self.db.new_api title, authors = self.get_title_and_authors() try: if title != db.field_for('title', self.book_id): db.set_field('title', {self.book_id:title}) langs = db.field_for('languages', self.book_id) if langs: db.set_field('sort', {self.book_id:title_sort(title, langs[0])}) if list(authors) != list(db.field_for('authors', self.book_id)): db.set_field('authors', {self.book_id:authors}) if self.cover_changed and self.cover_data is not None: self.db.set_cover(self.book_id, self.cover_data) except OSError as err: err.locking_violation_msg = _('Failed to change on disk location of this book\'s files.') raise publisher = self.publisher.text().strip() if publisher != db.field_for('publisher', self.book_id): db.set_field('publisher', {self.book_id:publisher}) author_sort = self.author_sort.text().strip() if author_sort != db.field_for('author_sort', self.book_id): db.set_field('author_sort', {self.book_id:author_sort}) tags = [t.strip() for t in self.tags.text().strip().split(',')] if tags != list(db.field_for('tags', self.book_id)): db.set_field('tags', {self.book_id:tags}) series_index = float(self.series_index.value()) series = self.series.currentText().strip() if series != db.field_for('series', self.book_id): db.set_field('series', {self.book_id:series}) if series and series_index != db.field_for('series_index', self.book_id): db.set_field('series_index', {self.book_id:series_index}) return True def commit(self, save_defaults=False): ''' Settings are stored in two attributes: `opf_file` and `cover_file`. Both may be None. Also returns a recommendation dictionary. ''' recs = self.commit_options(save_defaults) self.user_mi = self.get_metadata() self.cover_file = self.opf_file = None if self.db is not None: self.mi, self.opf_file = create_opf_file(self.db, self.book_id) cover = self.db.cover(self.book_id, index_is_id=True) if cover: cf = PersistentTemporaryFile('.jpeg') cf.write(cover) cf.close() self.cover_file = cf return recs
11,226
Python
.py
249
34.803213
120
0.597716
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,966
rb_output.py
kovidgoyal_calibre/src/calibre/gui2/convert/rb_output.py
__license__ = 'GPL 3' __copyright__ = '2009, John Schember <john@nachtimwald.com>' __docformat__ = 'restructuredtext en' from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2.convert import Widget from calibre.gui2.convert.rb_output_ui import Ui_Form format_model = None class PluginWidget(Widget, Ui_Form): TITLE = _('RB output') HELP = _('Options specific to')+' RB '+_('output') COMMIT_NAME = 'rb_output' ICON = 'mimetypes/unknown.png' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['output']['rb']) self.db, self.book_id = db, book_id self.initialize_options(get_option, get_help, db, book_id)
729
Python
.py
16
41.4375
76
0.685997
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,967
heuristics.py
kovidgoyal_calibre/src/calibre/gui2/convert/heuristics.py
__license__ = 'GPL 3' __copyright__ = '2011, John Schember <john@nachtimwald.com>' __docformat__ = 'restructuredtext en' from qt.core import Qt from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2 import gprefs from calibre.gui2.convert import Widget from calibre.gui2.convert.heuristics_ui import Ui_Form from calibre.utils.localization import localize_user_manual_link class HeuristicsWidget(Widget, Ui_Form): TITLE = _('Heuristic\nprocessing') HELP = _('Modify the document text and structure using common patterns.') COMMIT_NAME = 'heuristics' ICON = 'heuristics.png' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['pipe']['heuristics']) self.db, self.book_id = db, book_id self.rssb_defaults = ['', '<hr />', '∗ ∗ ∗', '• • •', '♦ ♦ ♦', '† †', '‡ ‡ ‡', '∞ ∞ ∞', '¤ ¤ ¤', '§'] self.initialize_options(get_option, get_help, db, book_id) self.load_histories() self.opt_enable_heuristics.stateChanged.connect(self.enable_heuristics) self.opt_unwrap_lines.stateChanged.connect(self.enable_unwrap) self.enable_heuristics(self.opt_enable_heuristics.checkState()) try: self.help_label.setText(self.help_label.text() % localize_user_manual_link( 'https://manual.calibre-ebook.com/conversion.html#heuristic-processing')) except TypeError: pass # link already localized def restore_defaults(self, get_option): Widget.restore_defaults(self, get_option) self.save_histories() rssb_hist = gprefs['replace_scene_breaks_history'] for x in self.rssb_defaults: if x in rssb_hist: del rssb_hist[rssb_hist.index(x)] gprefs['replace_scene_breaks_history'] = self.rssb_defaults + gprefs['replace_scene_breaks_history'] self.load_histories() def commit_options(self, save_defaults=False): self.save_histories() return Widget.commit_options(self, save_defaults) def break_cycles(self): Widget.break_cycles(self) try: self.opt_enable_heuristics.stateChanged.disconnect() self.opt_unwrap_lines.stateChanged.disconnect() except: pass def set_value_handler(self, g, val): if val is None and g is self.opt_html_unwrap_factor: g.setValue(0.0) return True if not val and g is self.opt_replace_scene_breaks: g.lineEdit().setText('') return True def load_histories(self): val = str(self.opt_replace_scene_breaks.currentText()) self.opt_replace_scene_breaks.clear() self.opt_replace_scene_breaks.lineEdit().setText('') rssb_hist = gprefs.get('replace_scene_breaks_history', self.rssb_defaults) if val in rssb_hist: del rssb_hist[rssb_hist.index(val)] rssb_hist.insert(0, val) for v in rssb_hist: # Ensure we don't have duplicate items. if self.opt_replace_scene_breaks.findText(v) == -1: self.opt_replace_scene_breaks.addItem(v) self.opt_replace_scene_breaks.setCurrentIndex(0) def save_histories(self): rssb_history = [] history_pats = [str(self.opt_replace_scene_breaks.lineEdit().text())] + [str(self.opt_replace_scene_breaks.itemText(i)) for i in range(self.opt_replace_scene_breaks.count())] for p in history_pats[:10]: # Ensure we don't have duplicate items. if p not in rssb_history: rssb_history.append(p) gprefs['replace_scene_breaks_history'] = rssb_history def enable_heuristics(self, state): self.heuristic_options.setEnabled(self.opt_enable_heuristics.isChecked()) def enable_unwrap(self, state): if state == Qt.CheckState.Checked: state = True else: state = False self.opt_html_unwrap_factor.setEnabled(state)
4,118
Python
.py
85
38.741176
127
0.638057
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,968
__init__.py
kovidgoyal_calibre/src/calibre/gui2/convert/__init__.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import codecs import importlib import textwrap from functools import partial from qt.core import ( QCheckBox, QComboBox, QDoubleSpinBox, QFont, QFontComboBox, QFontInfo, QIcon, QLabel, QLineEdit, QPlainTextEdit, QSpinBox, Qt, QTextEdit, QWidget, pyqtSignal, ) from calibre import prepare_string_for_xml from calibre.customize.conversion import OptionRecommendation from calibre.customize.ui import plugin_for_input_format from calibre.ebooks.conversion.config import GuiRecommendations, load_defaults, load_specifics from calibre.ebooks.conversion.config import save_defaults as save_defaults_ from calibre.gui2.font_family_chooser import FontFamilyChooser def config_widget_for_input_plugin(plugin): name = plugin.name.lower().replace(' ', '_') try: return importlib.import_module( 'calibre.gui2.convert.'+name).PluginWidget except ImportError: # If this is not a builtin plugin, we have to import it differently if plugin.__module__ and plugin.__module__.startswith('calibre_plugins.'): try: ans = importlib.import_module(plugin.__module__+'.'+name).PluginWidget except (ImportError, AttributeError, TypeError): pass else: if issubclass(ans, Widget): return ans def bulk_defaults_for_input_format(fmt): plugin = plugin_for_input_format(fmt) if plugin is not None: w = config_widget_for_input_plugin(plugin) if w is not None: return load_defaults(w.COMMIT_NAME) return {} class Widget(QWidget): TITLE = _('Unknown') ICON = 'config.png' HELP = '' COMMIT_NAME = None # If True, leading and trailing spaces are removed from line and text edit # fields STRIP_TEXT_FIELDS = True changed_signal = pyqtSignal() set_help_signal = pyqtSignal(object) def __init__(self, parent, options): options = list(options) QWidget.__init__(self, parent) self.setupUi(self) self._options = options self._name = self.commit_name = self.COMMIT_NAME assert self._name is not None self._icon = QIcon.ic(self.ICON) for name in self._options: if not hasattr(self, 'opt_'+name): raise Exception('Option %s missing in %s'%(name, self.__class__.__name__)) self.connect_gui_obj(getattr(self, 'opt_'+name)) def initialize_options(self, get_option, get_help, db=None, book_id=None): ''' :param get_option: A callable that takes one argument: the option name and returns the corresponding OptionRecommendation. :param get_help: A callable that takes the option name and return a help string. ''' defaults = load_defaults(self._name) defaults.merge_recommendations(get_option, OptionRecommendation.LOW, self._options) if db is not None: specifics = load_specifics(db, book_id) specifics.merge_recommendations(get_option, OptionRecommendation.HIGH, self._options, only_existing=True) defaults.update(specifics) self.apply_recommendations(defaults) self.setup_help(get_help) def process_child(child): for g in child.children(): if isinstance(g, QLabel): buddy = g.buddy() if buddy is not None and hasattr(buddy, '_help'): g._help = buddy._help htext = str(buddy.toolTip()).strip() g.setToolTip(htext) g.setWhatsThis(htext) g.__class__.enterEvent = lambda obj, event: self.set_help(getattr(obj, '_help', obj.toolTip())) else: process_child(g) process_child(self) def restore_defaults(self, get_option): defaults = GuiRecommendations() defaults.merge_recommendations(get_option, OptionRecommendation.LOW, self._options) self.apply_recommendations(defaults) def commit_options(self, save_defaults=False): recs = self.create_recommendations() if save_defaults: save_defaults_(self.commit_name, recs) return recs def create_recommendations(self): recs = GuiRecommendations() for name in self._options: gui_opt = getattr(self, 'opt_'+name, None) if gui_opt is None: continue recs[name] = self.get_value(gui_opt) return recs def apply_recommendations(self, recs): for name, val in recs.items(): gui_opt = getattr(self, 'opt_'+name, None) if gui_opt is None: continue self.set_value(gui_opt, val) if name in getattr(recs, 'disabled_options', []): gui_opt.setDisabled(True) def get_value(self, g): from calibre.gui2.convert.regex_builder import RegexEdit from calibre.gui2.convert.xpath_wizard import XPathEdit from calibre.gui2.widgets import EncodingComboBox ret = self.get_value_handler(g) if ret != 'this is a dummy return value, xcswx1avcx4x': return ret if hasattr(g, 'get_value_for_config'): return g.get_value_for_config if isinstance(g, (QSpinBox, QDoubleSpinBox)): return g.value() elif isinstance(g, (QLineEdit, QTextEdit, QPlainTextEdit)): func = getattr(g, 'toPlainText', getattr(g, 'text', None))() ans = str(func) if self.STRIP_TEXT_FIELDS: ans = ans.strip() if not ans: ans = None return ans elif isinstance(g, QFontComboBox): return str(QFontInfo(g.currentFont()).family()) elif isinstance(g, FontFamilyChooser): return g.font_family elif isinstance(g, EncodingComboBox): ans = str(g.currentText()).strip() try: codecs.lookup(ans) except: ans = '' if not ans: ans = None return ans elif isinstance(g, QComboBox): return str(g.currentText()) elif isinstance(g, QCheckBox): return bool(g.isChecked()) elif isinstance(g, XPathEdit): return g.xpath if g.xpath else None elif isinstance(g, RegexEdit): return g.regex if g.regex else None else: raise Exception('Can\'t get value from %s'%type(g)) def gui_obj_changed(self, gui_obj, *args): self.changed_signal.emit() def connect_gui_obj(self, g): f = partial(self.gui_obj_changed, g) try: self.connect_gui_obj_handler(g, f) return except NotImplementedError: pass from calibre.gui2.convert.regex_builder import RegexEdit from calibre.gui2.convert.xpath_wizard import XPathEdit if isinstance(g, (QSpinBox, QDoubleSpinBox)): g.valueChanged.connect(f) elif isinstance(g, (QLineEdit, QTextEdit, QPlainTextEdit)): g.textChanged.connect(f) elif isinstance(g, QComboBox): g.editTextChanged.connect(f) g.currentIndexChanged.connect(f) elif isinstance(g, QCheckBox): g.stateChanged.connect(f) elif isinstance(g, (XPathEdit, RegexEdit)): g.edit.editTextChanged.connect(f) g.edit.currentIndexChanged.connect(f) elif isinstance(g, FontFamilyChooser): g.family_changed.connect(f) else: raise Exception('Can\'t connect %s'%type(g)) def connect_gui_obj_handler(self, gui_obj, slot): raise NotImplementedError() def set_value(self, g, val): from calibre.gui2.convert.regex_builder import RegexEdit from calibre.gui2.convert.xpath_wizard import XPathEdit from calibre.gui2.widgets import EncodingComboBox if self.set_value_handler(g, val): return if hasattr(g, 'set_value_for_config'): g.set_value_for_config = val return if isinstance(g, (QSpinBox, QDoubleSpinBox)): g.setValue(val) elif isinstance(g, (QLineEdit, QTextEdit, QPlainTextEdit)): if not val: val = '' getattr(g, 'setPlainText', getattr(g, 'setText', None))(val) getattr(g, 'setCursorPosition', lambda x: x)(0) elif isinstance(g, QFontComboBox): g.setCurrentFont(QFont(val or '')) elif isinstance(g, FontFamilyChooser): g.font_family = val elif isinstance(g, EncodingComboBox): if val: g.setEditText(val) else: g.setCurrentIndex(0) elif isinstance(g, QComboBox) and val: idx = g.findText(val, Qt.MatchFlag.MatchFixedString) if idx < 0: g.addItem(val) idx = g.findText(val, Qt.MatchFlag.MatchFixedString) g.setCurrentIndex(idx) elif isinstance(g, QCheckBox): g.setCheckState(Qt.CheckState.Checked if bool(val) else Qt.CheckState.Unchecked) elif isinstance(g, (XPathEdit, RegexEdit)): g.edit.setText(val if val else '') else: raise Exception('Can\'t set value %s in %s'%(repr(val), str(g.objectName()))) self.post_set_value(g, val) def set_help(self, msg): if msg and getattr(msg, 'strip', lambda:True)(): try: self.set_help_signal.emit(msg) except: pass def setup_help(self, help_provider): for name in self._options: g = getattr(self, 'opt_'+name, None) if g is None: continue help = help_provider(name) if not help: continue if self.setup_help_handler(g, help): continue g._help = help self.setup_widget_help(g) def setup_widget_help(self, g): w = textwrap.TextWrapper(80) htext = '<div>%s</div>'%prepare_string_for_xml('\n'.join(w.wrap(g._help))) g.setToolTip(htext) g.setWhatsThis(htext) g.__class__.enterEvent = lambda obj, event: self.set_help(getattr(obj, '_help', obj.toolTip())) def set_value_handler(self, g, val): 'Return True iff you handle setting the value for g' return False def post_set_value(self, g, val): pass def get_value_handler(self, g): return 'this is a dummy return value, xcswx1avcx4x' def post_get_value(self, g): pass def setup_help_handler(self, g, help): return False def break_cycles(self): self.db = None def pre_commit_check(self): return True def commit(self, save_defaults=False): return self.commit_options(save_defaults) def config_title(self): return self.TITLE def config_icon(self): return self._icon
11,397
Python
.py
287
29.484321
119
0.599458
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,969
search_and_replace.py
kovidgoyal_calibre/src/calibre/gui2/convert/search_and_replace.py
__license__ = 'GPL 3' __copyright__ = '2011, John Schember <john@nachtimwald.com>, 2012 Eli Algranti <idea00@hotmail.com>' __docformat__ = 'restructuredtext en' import codecs import json from qt.core import Qt, QTableWidgetItem from calibre import as_unicode from calibre.ebooks.conversion.config import OPTIONS from calibre.ebooks.conversion.search_replace import compile_regular_expression from calibre.gui2 import choose_files, choose_save_file, error_dialog, question_dialog from calibre.gui2.convert import Widget from calibre.gui2.convert.search_and_replace_ui import Ui_Form from calibre.utils.localization import localize_user_manual_link class SearchAndReplaceWidget(Widget, Ui_Form): TITLE = _('Search &\nreplace') HELP = _('Modify the document text and structure using user defined patterns.') COMMIT_NAME = 'search_and_replace' ICON = 'search.png' STRIP_TEXT_FIELDS = False def __init__(self, parent, get_option, get_help, db=None, book_id=None): # Dummy attributes to fool the Widget() option handler code. We handle # everything in our *handler methods. for i in range(1, 4): x = 'sr%d_'%i for y in ('search', 'replace'): z = x + y setattr(self, 'opt_'+z, z) self.opt_search_replace = 'search_replace' Widget.__init__(self, parent, OPTIONS['pipe']['search_and_replace']) self.db, self.book_id = db, book_id self.sr_search.set_msg(_('&Search regular expression:')) self.sr_search.set_book_id(book_id) self.sr_search.set_db(db) self.sr_search.doc_update.connect(self.update_doc) proto = QTableWidgetItem() proto.setFlags(Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEnabled) self.search_replace.setItemPrototype(proto) self.search_replace.setColumnCount(2) self.search_replace.setColumnWidth(0, 320) self.search_replace.setColumnWidth(1, 320) self.search_replace.setHorizontalHeaderLabels([ _('Search regular expression'), _('Replacement text')]) self.sr_add.clicked.connect(self.sr_add_clicked) self.sr_change.clicked.connect(self.sr_change_clicked) self.sr_remove.clicked.connect(self.sr_remove_clicked) self.sr_load.clicked.connect(self.sr_load_clicked) self.sr_save.clicked.connect(self.sr_save_clicked) self.sr_up.clicked.connect(self.sr_up_clicked) self.sr_down.clicked.connect(self.sr_down_clicked) self.search_replace.currentCellChanged.connect(self.sr_currentCellChanged) self.initialize_options(get_option, get_help, db, book_id) try: self.rh_label.setText(self.rh_label.text() % localize_user_manual_link( 'https://manual.calibre-ebook.com/regexp.html')) except TypeError: pass # link already localized def sr_add_clicked(self): if self.sr_search.regex: row = self.sr_add_row(self.sr_search.regex, self.sr_replace.text()) self.search_replace.setCurrentCell(row, 0) def sr_add_row(self, search, replace): row = self.search_replace.rowCount() self.search_replace.setRowCount(row + 1) newItem = self.search_replace.itemPrototype().clone() newItem.setText(search) self.search_replace.setItem(row,0, newItem) newItem = self.search_replace.itemPrototype().clone() newItem.setText(replace) self.search_replace.setItem(row,1, newItem) return row def sr_change_clicked(self): row = self.search_replace.currentRow() if row >= 0: self.search_replace.item(row, 0).setText(self.sr_search.regex) self.search_replace.item(row, 1).setText(self.sr_replace.text()) self.search_replace.setCurrentCell(row, 0) def sr_remove_clicked(self): row = self.search_replace.currentRow() if row >= 0: self.search_replace.removeRow(row) self.search_replace.setCurrentCell(row if row < self.search_replace.rowCount() else row-1, 0) self.sr_search.clear() self.sr_replace.clear() self.changed_signal.emit() def sr_load_clicked(self): files = choose_files(self, 'sr_saved_patterns', _('Load calibre search-replace definitions file'), filters=[ (_('calibre search-replace definitions file'), ['csr']) ], select_only_single_file=True) if files: from calibre.ebooks.conversion.cli import read_sr_patterns try: self.set_value(self.opt_search_replace, read_sr_patterns(files[0])) self.search_replace.setCurrentCell(0, 0) except Exception as e: error_dialog(self, _('Failed to read'), _('Failed to load patterns from %s, click "Show details"' ' to learn more.')%files[0], det_msg=as_unicode(e), show=True) def sr_save_clicked(self): from calibre.ebooks.conversion.cli import escape_sr_pattern as escape filename = choose_save_file(self, 'sr_saved_patterns', _('Save calibre search-replace definitions file'), filters=[ (_('calibre search-replace definitions file'), ['csr']) ]) if filename: with codecs.open(filename, 'w', 'utf-8') as f: for search, replace in self.get_definitions(): f.write(escape(search) + '\n' + escape(replace) + '\n\n') def sr_up_clicked(self): self.cell_rearrange(-1) def sr_down_clicked(self): self.cell_rearrange(1) def cell_rearrange(self, i): row = self.search_replace.currentRow() for col in range(0, self.search_replace.columnCount()): item1 = self.search_replace.item(row, col) item2 = self.search_replace.item(row+i, col) value = item1.text() item1.setText(item2.text()) item2.setText(value) self.search_replace.setCurrentCell(row+i, 0) def sr_currentCellChanged(self, row, column, previousRow, previousColumn) : if row >= 0: self.sr_change.setEnabled(True) self.sr_remove.setEnabled(True) self.sr_save.setEnabled(True) self.sr_search.set_regex(self.search_replace.item(row, 0).text()) self.sr_replace.setText(self.search_replace.item(row, 1).text()) # set the up/down buttons self.sr_up.setEnabled(row > 0) self.sr_down.setEnabled(row < self.search_replace.rowCount()-1) else: self.sr_change.setEnabled(False) self.sr_remove.setEnabled(False) self.sr_save.setEnabled(False) self.sr_down.setEnabled(False) self.sr_up.setEnabled(False) def break_cycles(self): Widget.break_cycles(self) def d(x): try: x.disconnect() except: pass d(self.sr_search) self.sr_search.break_cycles() def update_doc(self, doc): self.sr_search.set_doc(doc) def pre_commit_check(self): definitions = self.get_definitions() # Verify the search/replace in the edit widgets has been # included to the list of search/replace definitions edit_search = self.sr_search.regex if edit_search: edit_replace = str(self.sr_replace.text()) found = False for search, replace in definitions: if search == edit_search and replace == edit_replace: found = True break if not found and not question_dialog(self, _('Unused search & replace definition'), _('The search/replace definition being edited ' ' has not been added to the list of definitions. ' 'Do you wish to continue with the conversion ' '(the definition will not be used)?')): return False # Verify all search expressions are valid for search, replace in definitions: try: compile_regular_expression(search) except Exception as err: error_dialog(self, _('Invalid regular expression'), _('Invalid regular expression: %s')%err, show=True) return False return True # Options handling def connect_gui_obj_handler(self, g, slot): if g is self.opt_search_replace: self.search_replace.cellChanged.connect(slot) def get_value_handler(self, g): if g is self.opt_search_replace: return json.dumps(self.get_definitions()) return None def get_definitions(self): ans = [] for row in range(0, self.search_replace.rowCount()): colItems = [] for col in range(0, self.search_replace.columnCount()): colItems.append(str(self.search_replace.item(row, col).text())) ans.append(colItems) return ans def set_value_handler(self, g, val): if g is not self.opt_search_replace: return True try: rowItems = json.loads(val) if not isinstance(rowItems, list): rowItems = [] except: rowItems = [] if len(rowItems) == 0: self.search_replace.clearContents() self.search_replace.setRowCount(len(rowItems)) for row, colItems in enumerate(rowItems): for col, cellValue in enumerate(colItems): newItem = self.search_replace.itemPrototype().clone() newItem.setText(cellValue) self.search_replace.setItem(row,col, newItem) return True def apply_recommendations(self, recs): ''' Handle the legacy sr* options that may have been previously saved. They are applied only if the new search_replace option has not been set in recs. ''' new_val = None legacy = {} rest = {} for name, val in recs.items(): if name == 'search_replace': new_val = val if name in getattr(recs, 'disabled_options', []): self.search_replace.setDisabled(True) elif name.startswith('sr'): legacy[name] = val if val else '' else: rest[name] = val if rest: super().apply_recommendations(rest) self.set_value(self.opt_search_replace, None) if new_val is None and legacy: for i in range(1, 4): x = 'sr%d'%i s, r = x+'_search', x+'_replace' s, r = legacy.get(s, ''), legacy.get(r, '') if s: self.sr_add_row(s, r) if new_val is not None: self.set_value(self.opt_search_replace, new_val) def setup_help_handler(self, g, help): if g is self.opt_search_replace: self.search_replace._help = _( 'The list of search/replace definitions that will be applied ' 'to this conversion.') self.setup_widget_help(self.search_replace) return True
11,518
Python
.py
251
34.430279
105
0.59836
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,970
lrf_output.py
kovidgoyal_calibre/src/calibre/gui2/convert/lrf_output.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2.convert import Widget from calibre.gui2.convert.lrf_output_ui import Ui_Form font_family_model = None class PluginWidget(Widget, Ui_Form): TITLE = _('LRF output') HELP = _('Options specific to')+' LRF '+_('output') COMMIT_NAME = 'lrf_output' ICON = 'mimetypes/lrf.png' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['output']['lrf']) self.db, self.book_id = db, book_id self.initialize_options(get_option, get_help, db, book_id) self.opt_header.toggle(), self.opt_header.toggle() self.opt_render_tables_as_images.toggle() self.opt_render_tables_as_images.toggle()
920
Python
.py
20
41.15
76
0.682379
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,971
fb2_output.py
kovidgoyal_calibre/src/calibre/gui2/convert/fb2_output.py
__license__ = 'GPL 3' __copyright__ = '2009, John Schember <john@nachtimwald.com>' __docformat__ = 'restructuredtext en' from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2.convert import Widget from calibre.gui2.convert.fb2_output_ui import Ui_Form format_model = None class PluginWidget(Widget, Ui_Form): TITLE = _('FB2 output') HELP = _('Options specific to')+' FB2 '+_('output') COMMIT_NAME = 'fb2_output' ICON = 'mimetypes/fb2.png' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['output']['fb2']) self.db, self.book_id = db, book_id for x in ('toc', 'files', 'nothing'): self.opt_sectionize.addItem(x) for x in get_option('fb2_genre').option.choices: self.opt_fb2_genre.addItem(x) self.initialize_options(get_option, get_help, db, book_id)
918
Python
.py
20
40.4
76
0.662556
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,972
docx_output.py
kovidgoyal_calibre/src/calibre/gui2/convert/docx_output.py
__license__ = 'GPL 3' __copyright__ = '2009, John Schember <john@nachtimwald.com>' __docformat__ = 'restructuredtext en' from qt.core import QCheckBox, QComboBox, QDoubleSpinBox, QFormLayout, QLineEdit, QSizePolicy from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2.convert import Widget paper_size_model = None orientation_model = None class PluginWidget(Widget): TITLE = _('DOCX output') HELP = _('Options specific to')+' DOCX '+_('output') COMMIT_NAME = 'docx_output' ICON = 'mimetypes/docx.png' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['output']['docx']) for x in get_option('docx_page_size').option.choices: self.opt_docx_page_size.addItem(x) self.initialize_options(get_option, get_help, db, book_id) self.layout().setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow) def setupUi(self, *a): self.l = l = QFormLayout(self) self.opt_docx_page_size = QComboBox(self) l.addRow(_('Paper si&ze:'), self.opt_docx_page_size) self.opt_docx_custom_page_size = w = QLineEdit(self) w.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) l.addRow(_('&Custom size:'), w) for i, text in enumerate((_('Page &left margin'), _('Page &top margin'), _('Page &right margin'), _('Page &bottom margin'))): m = 'left top right bottom'.split()[i] w = QDoubleSpinBox(self) w.setRange(-100, 500), w.setSuffix(' pt'), w.setDecimals(1) setattr(self, 'opt_docx_page_margin_' + m, w) l.addRow(text + ':', w) self.opt_docx_no_toc = QCheckBox(_('Do not insert the &Table of Contents as a page at the start of the document')) l.addRow(self.opt_docx_no_toc) self.opt_docx_no_cover = QCheckBox(_('Do not insert &cover as image at start of document')) l.addRow(self.opt_docx_no_cover) self.opt_preserve_cover_aspect_ratio = QCheckBox(_('Preserve the aspect ratio of the image inserted as cover')) l.addRow(self.opt_preserve_cover_aspect_ratio)
2,176
Python
.py
38
49.921053
133
0.660874
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,973
regex_builder.py
kovidgoyal_calibre/src/calibre/gui2/convert/regex_builder.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2009, John Schember <john@nachtimwald.com> import os from contextlib import suppress from qt.core import QBrush, QDialog, QDialogButtonBox, Qt, QTextCursor, QTextEdit, pyqtSignal from calibre.constants import iswindows from calibre.ebooks.conversion.search_replace import compile_regular_expression from calibre.gui2 import choose_files, error_dialog, gprefs from calibre.gui2.convert.regex_builder_ui import Ui_RegexBuilder from calibre.gui2.convert.xpath_wizard import XPathEdit from calibre.gui2.dialogs.choose_format import ChooseFormatDialog from calibre.gui2.widgets2 import to_plain_text from calibre.ptempfile import TemporaryFile from calibre.utils.icu import utf16_length from calibre.utils.ipc.simple_worker import WorkerError, fork_job from polyglot.builtins import native_string_type class RegexBuilder(QDialog, Ui_RegexBuilder): def __init__(self, db, book_id, regex, doc=None, parent=None): QDialog.__init__(self, parent) self.setupUi(self) self.regex.setText(regex) self.regex_valid() if not db or not book_id: button = self.button_box.addButton(QDialogButtonBox.StandardButton.Open) button.clicked.connect(self.open_clicked) elif not doc and not self.select_format(db, book_id): self.cancelled = True return if doc: self.preview.setPlainText(doc) self.cancelled = False self.button_box.accepted.connect(self.accept) self.regex.textChanged[native_string_type].connect(self.regex_valid) for src, slot in (('test', 'do'), ('previous', 'goto'), ('next', 'goto')): getattr(self, src).clicked.connect(getattr(self, '%s_%s'%(slot, src))) self.test.setDefault(True) self.match_locs = [] self.restore_geometry(gprefs, 'regex_builder_geometry') self.finished.connect(self.save_state) def save_state(self, result): self.save_geometry(gprefs, 'regex_builder_geometry') def regex_valid(self): regex = str(self.regex.text()) if regex: try: compile_regular_expression(regex) self.regex.setStyleSheet('QLineEdit { color: black; background-color: rgba(0,255,0,20%); }') return True except: self.regex.setStyleSheet('QLineEdit { color: black; background-color: rgba(255,0,0,20%); }') else: self.regex.setStyleSheet('QLineEdit { color: black; background-color: white; }') self.preview.setExtraSelections([]) self.match_locs = [] self.next.setEnabled(False) self.previous.setEnabled(False) self.occurrences.setText('0') return False def do_test(self): selections = [] self.match_locs = [] class Pos: python: int = 0 qt: int = 0 if self.regex_valid(): text = to_plain_text(self.preview) regex = str(self.regex.text()) cursor = QTextCursor(self.preview.document()) extsel = QTextEdit.ExtraSelection() extsel.cursor = cursor extsel.format.setBackground(QBrush(Qt.GlobalColor.yellow)) with suppress(Exception): prev = Pos() for match in compile_regular_expression(regex).finditer(text): es = QTextEdit.ExtraSelection(extsel) qtchars_to_start = utf16_length(text[prev.python:match.start()]) qt_pos = prev.qt + qtchars_to_start prev.python = match.end() prev.qt = qt_pos + utf16_length(match.group()) es.cursor.setPosition(qt_pos, QTextCursor.MoveMode.MoveAnchor) es.cursor.setPosition(prev.qt, QTextCursor.MoveMode.KeepAnchor) selections.append(es) self.match_locs.append((qt_pos, prev.qt)) self.preview.setExtraSelections(selections) if self.match_locs: self.next.setEnabled(True) self.previous.setEnabled(True) self.occurrences.setText(str(len(self.match_locs))) def goto_previous(self): pos = self.preview.textCursor().position() if self.match_locs: match_loc = len(self.match_locs) - 1 for i in range(len(self.match_locs) - 1, -1, -1): loc = self.match_locs[i][1] if pos > loc: match_loc = i break self.goto_loc( self.match_locs[match_loc][1], operation=QTextCursor.MoveOperation.Left, n=self.match_locs[match_loc][1] - self.match_locs[match_loc][0]) def goto_next(self): pos = self.preview.textCursor().position() if self.match_locs: match_loc = 0 for i in range(len(self.match_locs)): loc = self.match_locs[i][0] if pos < loc: match_loc = i break self.goto_loc(self.match_locs[match_loc][0], n=self.match_locs[match_loc][1] - self.match_locs[match_loc][0]) def goto_loc(self, loc, operation=QTextCursor.MoveOperation.Right, mode=QTextCursor.MoveMode.KeepAnchor, n=0): cursor = QTextCursor(self.preview.document()) cursor.setPosition(loc) if n: cursor.movePosition(operation, mode, n) self.preview.setTextCursor(cursor) def select_format(self, db, book_id): format = None formats = db.formats(book_id, index_is_id=True).upper().split(',') if len(formats) == 1: format = formats[0] elif len(formats) > 1: d = ChooseFormatDialog(self, _('Choose the format to view'), formats) d.exec() if d.result() == QDialog.DialogCode.Accepted: format = d.format() else: return False if not format: error_dialog(self, _('No formats available'), _('Cannot build regex using the GUI builder without a book.'), show=True) return False try: fpath = db.format(book_id, format, index_is_id=True, as_path=True) except OSError: if iswindows: import traceback error_dialog(self, _('Could not open file'), _('Could not open the file, do you have it open in' ' another program?'), show=True, det_msg=traceback.format_exc()) return False raise try: self.open_book(fpath) finally: try: os.remove(fpath) except: # Fails on windows if the input plugin for this format keeps the file open # Happens for LIT files pass return True def open_book(self, pathtoebook): with TemporaryFile('_prepprocess_gui') as tf: err_msg = _('Failed to generate markup for testing. Click ' '"Show details" to learn more.') try: fork_job('calibre.ebooks.oeb.iterator', 'get_preprocess_html', (pathtoebook, tf)) except WorkerError as e: return error_dialog(self, _('Failed to generate preview'), err_msg, det_msg=e.orig_tb, show=True) except: import traceback return error_dialog(self, _('Failed to generate preview'), err_msg, det_msg=traceback.format_exc(), show=True) with open(tf, 'rb') as f: self.preview.setPlainText(f.read().decode('utf-8')) def open_clicked(self): files = choose_files(self, 'regexp tester dialog', _('Open book'), select_only_single_file=True) if files: self.open_book(files[0]) def doc(self): return to_plain_text(self.preview) class RegexEdit(XPathEdit): doc_update = pyqtSignal(str) def __init__(self, parent=None): super().__init__(parent) self.edit.completer().setCaseSensitivity(Qt.CaseSensitivity.CaseSensitive) self.book_id = None self.db = None self.doc_cache = None def wizard(self): return self.builder() def builder(self): if self.db is None: self.doc_cache = _('Click the "Open" button below to open a ' 'e-book to use for testing.') bld = RegexBuilder(self.db, self.book_id, self.edit.text(), self.doc_cache, self) if bld.cancelled: return if not self.doc_cache: self.doc_cache = bld.doc() self.doc_update.emit(self.doc_cache) if bld.exec() == QDialog.DialogCode.Accepted: self.edit.setText(bld.regex.text()) def doc(self): return self.doc_cache def setObjectName(self, *args): super().setObjectName(*args) if hasattr(self, 'edit'): self.edit.initialize('regex_edit_'+str(self.objectName())) def set_msg(self, msg): self.msg.setText(msg) def set_book_id(self, book_id): self.book_id = book_id def set_db(self, db): self.db = db def set_doc(self, doc): self.doc_cache = doc def set_regex(self, regex): self.edit.setText(regex) def break_cycles(self): self.db = self.doc_cache = None @property def text(self): return str(self.edit.text()) @property def regex(self): return self.text def clear(self): self.edit.clear() def check(self): return True if __name__ == '__main__': from calibre.gui2 import Application app = Application([]) d = RegexBuilder(None, None, 'a', doc='😉123abc XYZabc') d.do_test() d.exec() del d del app
10,082
Python
.py
239
31.041841
121
0.585792
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,974
single.py
kovidgoyal_calibre/src/calibre/gui2/convert/single.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2009, Kovid Goyal <kovid at kovidgoyal.net> import shutil from qt.core import ( QAbstractListModel, QCheckBox, QComboBox, QDialog, QDialogButtonBox, QFont, QFrame, QGridLayout, QHBoxLayout, QIcon, QLabel, QListView, QModelIndex, QScrollArea, QSize, QSizePolicy, QSpacerItem, Qt, QTextEdit, QWidget, ) from calibre.customize.conversion import OptionRecommendation from calibre.ebooks.conversion.config import ( GuiRecommendations, delete_specifics, get_input_format_for_book, get_output_formats, save_specifics, sort_formats_by_preference, ) from calibre.ebooks.conversion.plumber import create_dummy_plumber from calibre.gui2 import gprefs from calibre.gui2.convert.debug import DebugWidget from calibre.gui2.convert.heuristics import HeuristicsWidget from calibre.gui2.convert.look_and_feel import LookAndFeelWidget from calibre.gui2.convert.metadata import MetadataWidget from calibre.gui2.convert.page_setup import PageSetupWidget from calibre.gui2.convert.search_and_replace import SearchAndReplaceWidget from calibre.gui2.convert.structure_detection import StructureDetectionWidget from calibre.gui2.convert.toc import TOCWidget from calibre.utils.config import prefs class GroupModel(QAbstractListModel): def __init__(self, widgets): self.widgets = widgets QAbstractListModel.__init__(self) def rowCount(self, *args): return len(self.widgets) def data(self, index, role): try: widget = self.widgets[index.row()] except: return None if role == Qt.ItemDataRole.DisplayRole: return (widget.config_title()) if role == Qt.ItemDataRole.DecorationRole: return (widget.config_icon()) if role == Qt.ItemDataRole.FontRole: f = QFont() f.setBold(True) return (f) return None class Config(QDialog): ''' Configuration dialog for single book conversion. If accepted, has the following important attributes output_format - Output format (without a leading .) input_format - Input format (without a leading .) opf_path - Path to OPF file with user specified metadata cover_path - Path to user specified cover (can be None) recommendations - A pickled list of 3 tuples in the same format as the recommendations member of the Input/Output plugins. ''' def __init__(self, parent, db, book_id, preferred_input_format=None, preferred_output_format=None): QDialog.__init__(self, parent) self.widgets = [] self.setupUi() self.opt_individual_saved_settings.setVisible(False) self.db, self.book_id = db, book_id self.setup_input_output_formats(self.db, self.book_id, preferred_input_format, preferred_output_format) self.setup_pipeline() self.input_formats.currentIndexChanged.connect(self.setup_pipeline) self.output_formats.currentIndexChanged.connect(self.setup_pipeline) self.groups.setSpacing(5) self.groups.entered[(QModelIndex)].connect(self.show_group_help) rb = self.buttonBox.button(QDialogButtonBox.StandardButton.RestoreDefaults) rb.setText(_('Restore &defaults')) rb.setIcon(QIcon.ic('clear_left.png')) rb.clicked.connect(self.restore_defaults) self.groups.setMouseTracking(True) self.restore_geometry(gprefs, 'convert_single_dialog_geom') def current_group_changed(self, cur, prev): self.show_pane(cur) def setupUi(self): self.setObjectName("Dialog") self.resize(1024, 700) self.setWindowIcon(QIcon.ic('convert.png')) self.gridLayout = QGridLayout(self) self.gridLayout.setObjectName("gridLayout") self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.input_label = QLabel(self) self.input_label.setObjectName("input_label") self.horizontalLayout.addWidget(self.input_label) self.input_formats = QComboBox(self) self.input_formats.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon) self.input_formats.setMinimumContentsLength(5) self.input_formats.setObjectName("input_formats") self.horizontalLayout.addWidget(self.input_formats) self.opt_individual_saved_settings = QCheckBox(self) self.opt_individual_saved_settings.setObjectName("opt_individual_saved_settings") self.horizontalLayout.addWidget(self.opt_individual_saved_settings) spacerItem = QSpacerItem(40, 20, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum) self.horizontalLayout.addItem(spacerItem) self.label_2 = QLabel(self) self.label_2.setObjectName("label_2") self.horizontalLayout.addWidget(self.label_2) self.output_formats = QComboBox(self) self.output_formats.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon) self.output_formats.setMinimumContentsLength(5) self.output_formats.setObjectName("output_formats") self.horizontalLayout.addWidget(self.output_formats) self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 2) self.groups = QListView(self) sizePolicy = QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) sizePolicy.setHorizontalStretch(1) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.groups.sizePolicy().hasHeightForWidth()) self.groups.setSizePolicy(sizePolicy) self.groups.setTabKeyNavigation(True) self.groups.setIconSize(QSize(48, 48)) self.groups.setWordWrap(True) self.groups.setObjectName("groups") self.gridLayout.addWidget(self.groups, 1, 0, 3, 1) self.scrollArea = QScrollArea(self) sizePolicy = QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) sizePolicy.setHorizontalStretch(4) sizePolicy.setVerticalStretch(10) sizePolicy.setHeightForWidth(self.scrollArea.sizePolicy().hasHeightForWidth()) self.scrollArea.setSizePolicy(sizePolicy) self.scrollArea.setFrameShape(QFrame.Shape.NoFrame) self.scrollArea.setLineWidth(0) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName("scrollArea") self.page = QWidget() self.page.setObjectName("page") self.gridLayout.addWidget(self.scrollArea, 1, 1, 1, 1) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Orientation.Horizontal) self.buttonBox.setStandardButtons( QDialogButtonBox.StandardButton.Cancel|QDialogButtonBox.StandardButton.Ok| QDialogButtonBox.StandardButton.RestoreDefaults) self.buttonBox.setObjectName("buttonBox") self.gridLayout.addWidget(self.buttonBox, 3, 1, 1, 1) self.help = QTextEdit(self) self.help.setReadOnly(True) sizePolicy = QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.help.sizePolicy().hasHeightForWidth()) self.help.setSizePolicy(sizePolicy) self.help.setMaximumHeight(80) self.help.setObjectName("help") self.gridLayout.addWidget(self.help, 2, 1, 1, 1) self.input_label.setBuddy(self.input_formats) self.label_2.setBuddy(self.output_formats) self.input_label.setText(_("&Input format:")) self.opt_individual_saved_settings.setText(_("Use &saved conversion settings for individual books")) self.label_2.setText(_("&Output format:")) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) def sizeHint(self): geom = self.screen().availableSize() nh, nw = max(300, geom.height()-100), max(400, geom.width()-70) return QSize(nw, nh) def restore_defaults(self): delete_specifics(self.db, self.book_id) self.setup_pipeline() @property def input_format(self): return str(self.input_formats.currentText()).lower() @property def output_format(self): return str(self.output_formats.currentText()).lower() @property def manually_fine_tune_toc(self): for w in self.widgets: if hasattr(w, 'manually_fine_tune_toc'): return w.manually_fine_tune_toc.isChecked() def setup_pipeline(self, *args): oidx = self.groups.currentIndex().row() input_format = self.input_format output_format = self.output_format self.plumber = create_dummy_plumber(input_format, output_format) def widget_factory(cls): return cls(self, self.plumber.get_option_by_name, self.plumber.get_option_help, self.db, self.book_id) self.mw = widget_factory(MetadataWidget) self.setWindowTitle(_('Convert')+ ' ' + str(self.mw.title.text())) lf = widget_factory(LookAndFeelWidget) hw = widget_factory(HeuristicsWidget) sr = widget_factory(SearchAndReplaceWidget) ps = widget_factory(PageSetupWidget) sd = widget_factory(StructureDetectionWidget) toc = widget_factory(TOCWidget) from calibre.gui2.actions.toc_edit import SUPPORTED toc.manually_fine_tune_toc.setVisible(output_format.upper() in SUPPORTED) debug = widget_factory(DebugWidget) output_widget = self.plumber.output_plugin.gui_configuration_widget( self, self.plumber.get_option_by_name, self.plumber.get_option_help, self.db, self.book_id) input_widget = self.plumber.input_plugin.gui_configuration_widget( self, self.plumber.get_option_by_name, self.plumber.get_option_help, self.db, self.book_id) self.break_cycles() self.widgets = widgets = [self.mw, lf, hw, ps, sd, toc, sr] if input_widget is not None: widgets.append(input_widget) if output_widget is not None: widgets.append(output_widget) widgets.append(debug) for w in widgets: w.set_help_signal.connect(self.help.setPlainText) w.setVisible(False) w.layout().setContentsMargins(0, 0, 0, 0) self._groups_model = GroupModel(widgets) self.groups.setModel(self._groups_model) idx = oidx if -1 < oidx < self._groups_model.rowCount() else 0 self.groups.setCurrentIndex(self._groups_model.index(idx)) self.show_pane(idx) self.groups.selectionModel().currentChanged.connect(self.current_group_changed) try: shutil.rmtree(self.plumber.archive_input_tdir, ignore_errors=True) except Exception: pass def setup_input_output_formats(self, db, book_id, preferred_input_format, preferred_output_format): if preferred_output_format: preferred_output_format = preferred_output_format.upper() output_formats = get_output_formats(preferred_output_format) input_format, input_formats = get_input_format_for_book(db, book_id, preferred_input_format) preferred_output_format = preferred_output_format if \ preferred_output_format in output_formats else \ sort_formats_by_preference(output_formats, [prefs['output_format']])[0] self.input_formats.addItems(str(x.upper()) for x in input_formats) self.output_formats.addItems(str(x.upper()) for x in output_formats) self.input_formats.setCurrentIndex(input_formats.index(input_format)) self.output_formats.setCurrentIndex(output_formats.index(preferred_output_format)) def show_pane(self, index): if hasattr(index, 'row'): index = index.row() ow = self.scrollArea.takeWidget() if ow: ow.setParent(self) for i, w in enumerate(self.widgets): if i == index: self.scrollArea.setWidget(w) w.show() else: w.setVisible(False) def accept(self): recs = GuiRecommendations() for w in self._groups_model.widgets: if not w.pre_commit_check(): return x = w.commit(save_defaults=False) recs.update(x) self.opf_file, self.cover_file = self.mw.opf_file, self.mw.cover_file self._recommendations = recs if self.db is not None: recs['gui_preferred_input_format'] = self.input_format save_specifics(self.db, self.book_id, recs) self.break_cycles() QDialog.accept(self) def reject(self): self.break_cycles() QDialog.reject(self) def done(self, r): if self.isVisible(): self.save_geometry(gprefs, 'convert_single_dialog_geom') return QDialog.done(self, r) def break_cycles(self): for w in self.widgets: w.break_cycles() @property def recommendations(self): recs = [(k, v, OptionRecommendation.HIGH) for k, v in self._recommendations.items()] return recs def show_group_help(self, index): widget = self._groups_model.widgets[index.row()] self.help.setPlainText(widget.HELP)
13,624
Python
.py
299
36.959866
113
0.682923
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,975
structure_detection.py
kovidgoyal_calibre/src/calibre/gui2/convert/structure_detection.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2 import error_dialog from calibre.gui2.convert import Widget from calibre.gui2.convert.structure_detection_ui import Ui_Form class StructureDetectionWidget(Widget, Ui_Form): TITLE = _('Structure\ndetection') ICON = 'chapters.png' HELP = _('Fine tune the detection of chapter headings and ' 'other document structure.') COMMIT_NAME = 'structure_detection' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['pipe']['structure_detection']) self.db, self.book_id = db, book_id for x in ('pagebreak', 'rule', 'both', 'none'): self.opt_chapter_mark.addItem(x) self.initialize_options(get_option, get_help, db, book_id) self.opt_chapter.set_msg(_('Detect &chapters at (XPath expression):')) self.opt_page_breaks_before.set_msg(_('Insert &page breaks before ' '(XPath expression):')) self.opt_start_reading_at.set_msg( _('Start &reading at (XPath expression):')) def break_cycles(self): Widget.break_cycles(self) def pre_commit_check(self): for x in ('chapter', 'page_breaks_before', 'start_reading_at'): x = getattr(self, 'opt_'+x) if not x.check(): error_dialog(self, _('Invalid XPath'), _('The XPath expression %s is invalid.')%x.text).exec() return False return True
1,681
Python
.py
35
40.142857
78
0.637141
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,976
debug.py
kovidgoyal_calibre/src/calibre/gui2/convert/debug.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2 import choose_dir, error_dialog from calibre.gui2.convert import Widget from calibre.gui2.convert.debug_ui import Ui_Form class DebugWidget(Widget, Ui_Form): TITLE = _('Debug') ICON = 'debug.png' HELP = _('Debug the conversion process.') COMMIT_NAME = 'debug' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['pipe']['debug']) self.db, self.book_id = db, book_id self.initialize_options(get_option, get_help, db, book_id) self.button_debug_dir.clicked.connect(self.set_debug_dir) def set_debug_dir(self): x = choose_dir(self, 'conversion debug dir', _('Choose debug folder')) if x: self.opt_debug_pipeline.setText(x) def pre_commit_check(self): try: x = str(self.opt_debug_pipeline.text()).strip() if not x: return True x = os.path.abspath(x) if x: if not os.path.exists(x): os.makedirs(x) test = os.path.join(x, 'test') open(test, 'wb').close() os.remove(test) except: import traceback det_msg = traceback.format_exc() error_dialog(self, _('Invalid debug folder'), _('Failed to create debug folder')+': '+ str(self.opt_debug_pipeline.text()), det_msg=det_msg, show=True) return False return True
1,748
Python
.py
43
31.232558
97
0.587021
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,977
pdb_output.py
kovidgoyal_calibre/src/calibre/gui2/convert/pdb_output.py
__license__ = 'GPL 3' __copyright__ = '2009, John Schember <john@nachtimwald.com>' __docformat__ = 'restructuredtext en' from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2.convert import Widget from calibre.gui2.convert.pdb_output_ui import Ui_Form format_model = None class PluginWidget(Widget, Ui_Form): TITLE = _('PDB output') HELP = _('Options specific to')+' PDB '+_('output') COMMIT_NAME = 'pdb_output' ICON = 'mimetypes/unknown.png' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['output']['pdb']) self.db, self.book_id = db, book_id for x in get_option('format').option.choices: self.opt_format.addItem(x) self.initialize_options(get_option, get_help, db, book_id)
829
Python
.py
18
41.055556
76
0.678705
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,978
pdf_input.py
kovidgoyal_calibre/src/calibre/gui2/convert/pdf_input.py
__license__ = 'GPL 3' __copyright__ = '2009, John Schember <john@nachtimwald.com>' __docformat__ = 'restructuredtext en' from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2.convert import QDoubleSpinBox, Widget from calibre.gui2.convert.pdf_input_ui import Ui_Form class PluginWidget(Widget, Ui_Form): TITLE = _('PDF input') HELP = _('Options specific to')+' PDF '+_('input') COMMIT_NAME = 'pdf_input' ICON = 'mimetypes/pdf.png' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['input']['pdf']) self.db, self.book_id = db, book_id from calibre.ebooks.conversion.plugins.pdf_input import ENGINES self.opt_pdf_engine.addItems(ENGINES) self.initialize_options(get_option, get_help, db, book_id) self.opt_pdf_engine.currentIndexChanged.connect(self.update_engine_opts) self.update_engine_opts() def set_value_handler(self, g, val): if val is None and isinstance(g, QDoubleSpinBox): g.setValue(0.0) return True if g is self.opt_pdf_engine: idx = g.findText(val) if idx > -1: g.setCurrentIndex(idx) def update_engine_opts(self): enabled = self.opt_pdf_engine.currentText() == 'calibre' self.opt_pdf_footer_skip.setEnabled(enabled) self.opt_pdf_header_skip.setEnabled(enabled) self.opt_pdf_header_regex.setEnabled(enabled) self.opt_pdf_footer_regex.setEnabled(enabled)
1,554
Python
.py
33
39.69697
80
0.666446
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,979
comic_input.py
kovidgoyal_calibre/src/calibre/gui2/convert/comic_input.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2.convert import Widget from calibre.gui2.convert.comic_input_ui import Ui_Form class PluginWidget(Widget, Ui_Form): TITLE = _('Comic input') HELP = _('Options specific to')+' comic '+_('input') COMMIT_NAME = 'comic_input' ICON = 'mimetypes/png.png' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['input']['comic']) self.db, self.book_id = db, book_id for x in get_option('output_format').option.choices: self.opt_output_format.addItem(x) self.initialize_options(get_option, get_help, db, book_id) self.opt_no_process.toggle() self.opt_no_process.toggle()
921
Python
.py
20
40.65
76
0.673012
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,980
htmlz_output.py
kovidgoyal_calibre/src/calibre/gui2/convert/htmlz_output.py
__license__ = 'GPL 3' __copyright__ = '2009, John Schember <john@nachtimwald.com>' __docformat__ = 'restructuredtext en' from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2.convert import Widget from calibre.gui2.convert.htmlz_output_ui import Ui_Form format_model = None class PluginWidget(Widget, Ui_Form): TITLE = _('HTMLZ output') HELP = _('Options specific to')+' HTMLZ '+_('output') COMMIT_NAME = 'htmlz_output' ICON = 'mimetypes/html.png' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['output']['htmlz']) self.db, self.book_id = db, book_id for x in get_option('htmlz_css_type').option.choices: self.opt_htmlz_css_type.addItem(x) for x in get_option('htmlz_class_style').option.choices: self.opt_htmlz_class_style.addItem(x) self.initialize_options(get_option, get_help, db, book_id)
965
Python
.py
20
42.75
76
0.678381
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,981
look_and_feel.py
kovidgoyal_calibre/src/calibre/gui2/convert/look_and_feel.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import json from qt.core import QDialog, Qt from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2.convert import Widget from calibre.gui2.convert.look_and_feel_ui import Ui_Form from calibre.startup import connect_lambda from polyglot.builtins import iteritems class LookAndFeelWidget(Widget, Ui_Form): TITLE = _('Look & feel') ICON = 'lookfeel.png' HELP = _('Control the look and feel of the output.') COMMIT_NAME = 'look_and_feel' FILTER_CSS = { 'fonts': {'font-family'}, 'margins': {'margin', 'margin-left', 'margin-right', 'margin-top', 'margin-bottom'}, 'padding': {'padding', 'padding-left', 'padding-right', 'padding-top', 'padding-bottom'}, 'floats': {'float'}, 'colors': {'color', 'background', 'background-color'}, } def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['pipe']['look_and_feel']) for val, text in [ ('original', _('Original')), ('left', _('Left align')), ('justify', _('Justify text')) ]: self.opt_change_justification.addItem(text, (val)) self.db, self.book_id = db, book_id self.initialize_options(get_option, get_help, db, book_id) self.opt_disable_font_rescaling.toggle() self.opt_disable_font_rescaling.toggle() self.button_font_key.clicked.connect(self.font_key_wizard) self.opt_remove_paragraph_spacing.toggle() self.opt_remove_paragraph_spacing.toggle() connect_lambda(self.opt_smarten_punctuation.stateChanged, self, lambda self, state: state != Qt.CheckState.Unchecked and self.opt_unsmarten_punctuation.setCheckState(Qt.CheckState.Unchecked)) connect_lambda(self.opt_unsmarten_punctuation.stateChanged, self, lambda self, state: state != Qt.CheckState.Unchecked and self.opt_smarten_punctuation.setCheckState(Qt.CheckState.Unchecked)) def get_value_handler(self, g): if g is self.opt_change_justification: ans = str(g.itemData(g.currentIndex()) or '') return ans if g is self.opt_filter_css: ans = set() for key, item in iteritems(self.FILTER_CSS): w = getattr(self, 'filter_css_%s'%key) if w.isChecked(): ans = ans.union(item) ans = ans.union({x.strip().lower() for x in str(self.filter_css_others.text()).split(',')}) return ','.join(ans) if ans else None if g is self.opt_font_size_mapping: val = str(g.text()).strip() val = [x.strip() for x in val.split(',' if ',' in val else ' ') if x.strip()] return ', '.join(val) or None if g is self.opt_transform_css_rules or g is self.opt_transform_html_rules: return json.dumps(g.rules) return Widget.get_value_handler(self, g) def set_value_handler(self, g, val): if g is self.opt_change_justification: for i in range(g.count()): c = str(g.itemData(i) or '') if val == c: g.setCurrentIndex(i) break return True if g is self.opt_filter_css: if not val: val = '' items = frozenset(x.strip().lower() for x in val.split(',')) for key, vals in iteritems(self.FILTER_CSS): w = getattr(self, 'filter_css_%s'%key) if not vals - items: items = items - vals w.setChecked(True) else: w.setChecked(False) self.filter_css_others.setText(', '.join(items)) return True if g is self.opt_transform_css_rules or g is self.opt_transform_html_rules: g.rules = json.loads(val) if val else [] return True def connect_gui_obj_handler(self, gui_obj, slot): if gui_obj is self.opt_filter_css: for key in self.FILTER_CSS: w = getattr(self, 'filter_css_%s'%key) w.stateChanged.connect(slot) self.filter_css_others.textChanged.connect(slot) return if gui_obj is self.opt_transform_css_rules or gui_obj is self.opt_transform_html_rules: gui_obj.changed.connect(slot) return raise NotImplementedError() def font_key_wizard(self): from calibre.gui2.convert.font_key import FontKeyChooser d = FontKeyChooser(self, self.opt_base_font_size.value(), str(self.opt_font_size_mapping.text()).strip()) if d.exec() == QDialog.DialogCode.Accepted: self.opt_font_size_mapping.setText(', '.join(['%.1f'%x for x in d.fsizes])) self.opt_base_font_size.setValue(d.dbase)
5,129
Python
.py
107
36.672897
123
0.584465
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,982
epub_output.py
kovidgoyal_calibre/src/calibre/gui2/convert/epub_output.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2.convert import Widget from calibre.gui2.convert.epub_output_ui import Ui_Form class PluginWidget(Widget, Ui_Form): TITLE = _('EPUB output') HELP = _('Options specific to')+' EPUB '+_('output') COMMIT_NAME = 'epub_output' ICON = 'mimetypes/epub.png' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['output']['epub']) for i in range(2): self.opt_no_svg_cover.toggle() ev = get_option('epub_version') self.opt_epub_version.addItems(list(ev.option.choices)) self.db, self.book_id = db, book_id self.initialize_options(get_option, get_help, db, book_id)
916
Python
.py
20
40.4
76
0.667793
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,983
txt_output.py
kovidgoyal_calibre/src/calibre/gui2/convert/txt_output.py
__license__ = 'GPL 3' __copyright__ = '2009, John Schember <john@nachtimwald.com>' __docformat__ = 'restructuredtext en' from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2.convert import Widget from calibre.gui2.convert.txt_output_ui import Ui_Form class PluginWidget(Widget, Ui_Form): TITLE = _('TXT output') HELP = _('Options specific to')+' TXT '+_('output') COMMIT_NAME = 'txt_output' ICON = 'mimetypes/txt.png' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['output']['txt']) self.db, self.book_id = db, book_id for x in get_option('newline').option.choices: self.opt_newline.addItem(x) for x in get_option('txt_output_formatting').option.choices: self.opt_txt_output_formatting.addItem(x) self.initialize_options(get_option, get_help, db, book_id) if self.COMMIT_NAME != 'txt_output': self.image_note_label.setText(_( 'Note that for images to be preserved, the formatting option above must be markdown or textile' ' and also enable the setting to not remove image references.')) def break_cycles(self): Widget.break_cycles(self)
1,274
Python
.py
25
43.76
111
0.663446
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,984
mobi_output.py
kovidgoyal_calibre/src/calibre/gui2/convert/mobi_output.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from calibre.ebooks.conversion.config import OPTIONS from calibre.gui2.convert import Widget from calibre.gui2.convert.mobi_output_ui import Ui_Form font_family_model = None class PluginWidget(Widget, Ui_Form): TITLE = _('MOBI output') HELP = _('Options specific to')+' MOBI '+_('output') COMMIT_NAME = 'mobi_output' ICON = 'mimetypes/mobi.png' def __init__(self, parent, get_option, get_help, db=None, book_id=None): Widget.__init__(self, parent, OPTIONS['output']['mobi']) self.db, self.book_id = db, book_id self.opt_mobi_file_type.addItems(['old', 'both', 'new']) self.initialize_options(get_option, get_help, db, book_id)
834
Python
.py
18
41.833333
76
0.679503
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,985
configwidget.py
kovidgoyal_calibre/src/calibre/gui2/device_drivers/configwidget.py
__license__ = 'GPL 3' __copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>' __docformat__ = 'restructuredtext en' import textwrap from qt.core import QCheckBox, QComboBox, QLabel, QLineEdit, QListWidgetItem, Qt, QWidget from calibre.ebooks import BOOK_EXTENSIONS from calibre.gui2 import error_dialog, question_dialog from calibre.gui2.device_drivers.configwidget_ui import Ui_ConfigWidget from calibre.utils.formatter import validation_formatter class ConfigWidget(QWidget, Ui_ConfigWidget): def __init__(self, settings, all_formats, supports_subdirs, must_read_metadata, supports_use_author_sort, extra_customization_message, device, extra_customization_choices=None): QWidget.__init__(self) Ui_ConfigWidget.__init__(self) self.setupUi(self) self.settings = settings all_formats = set(all_formats) self.calibre_known_formats = device.FORMATS try: self.device_name = device.get_gui_name() except TypeError: self.device_name = getattr(device, 'gui_name', None) or _('Device') if device.USER_CAN_ADD_NEW_FORMATS: all_formats = all_formats | set(BOOK_EXTENSIONS) format_map = settings.format_map disabled_formats = all_formats.difference(format_map) for format in format_map + sorted(disabled_formats): item = QListWidgetItem(format, self.columns) item.setData(Qt.ItemDataRole.UserRole, (format)) item.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsUserCheckable|Qt.ItemFlag.ItemIsSelectable) item.setCheckState(Qt.CheckState.Checked if format in format_map else Qt.CheckState.Unchecked) self.column_up.clicked.connect(self.up_column) self.column_down.clicked.connect(self.down_column) if device.HIDE_FORMATS_CONFIG_BOX: self.groupBox.hide() if supports_subdirs: self.opt_use_subdirs.setChecked(self.settings.use_subdirs) else: self.opt_use_subdirs.hide() if not must_read_metadata: self.opt_read_metadata.setChecked(self.settings.read_metadata) else: self.opt_read_metadata.hide() if supports_use_author_sort: self.opt_use_author_sort.setChecked(self.settings.use_author_sort) else: self.opt_use_author_sort.hide() if extra_customization_message: extra_customization_choices = extra_customization_choices or {} def parse_msg(m): msg, _, tt = m.partition(':::') if m else ('', '', '') return msg.strip(), textwrap.fill(tt.strip(), 100) if isinstance(extra_customization_message, list): self.opt_extra_customization = [] if len(extra_customization_message) > 6: def row_func(x, y): return (x // 2 * 2 + y) def col_func(x): return (x % 2) else: def row_func(x, y): return (x * 2 + y) def col_func(x): return 0 for i, m in enumerate(extra_customization_message): label_text, tt = parse_msg(m) if not label_text: self.opt_extra_customization.append(None) continue if isinstance(settings.extra_customization[i], bool): self.opt_extra_customization.append(QCheckBox(label_text)) self.opt_extra_customization[-1].setToolTip(tt) self.opt_extra_customization[i].setChecked(bool(settings.extra_customization[i])) elif i in extra_customization_choices: cb = QComboBox(self) self.opt_extra_customization.append(cb) l = QLabel(label_text) l.setToolTip(tt), cb.setToolTip(tt), l.setBuddy(cb), cb.setToolTip(tt) for li in sorted(extra_customization_choices[i]): self.opt_extra_customization[i].addItem(li) cb.setCurrentIndex(max(0, cb.findText(settings.extra_customization[i]))) else: self.opt_extra_customization.append(QLineEdit(self)) l = QLabel(label_text) l.setToolTip(tt) self.opt_extra_customization[i].setToolTip(tt) l.setBuddy(self.opt_extra_customization[i]) l.setWordWrap(True) self.opt_extra_customization[i].setText(settings.extra_customization[i]) self.opt_extra_customization[i].setCursorPosition(0) self.extra_layout.addWidget(l, row_func(i, 0), col_func(i)) self.extra_layout.addWidget(self.opt_extra_customization[i], row_func(i, 1), col_func(i)) else: self.opt_extra_customization = QLineEdit() label_text, tt = parse_msg(extra_customization_message) l = QLabel(label_text) l.setToolTip(tt) l.setBuddy(self.opt_extra_customization) l.setWordWrap(True) if settings.extra_customization: self.opt_extra_customization.setText(settings.extra_customization) self.opt_extra_customization.setCursorPosition(0) self.opt_extra_customization.setCursorPosition(0) self.extra_layout.addWidget(l, 0, 0) self.extra_layout.addWidget(self.opt_extra_customization, 1, 0) self.opt_save_template.setText(settings.save_template) def up_column(self): idx = self.columns.currentRow() if idx > 0: self.columns.insertItem(idx-1, self.columns.takeItem(idx)) self.columns.setCurrentRow(idx-1) def down_column(self): idx = self.columns.currentRow() if idx < self.columns.count()-1: self.columns.insertItem(idx+1, self.columns.takeItem(idx)) self.columns.setCurrentRow(idx+1) def format_map(self): formats = [ str(self.columns.item(i).data(Qt.ItemDataRole.UserRole) or '') for i in range(self.columns.count()) if self.columns.item(i).checkState()==Qt.CheckState.Checked ] return formats def use_subdirs(self): return self.opt_use_subdirs.isChecked() def read_metadata(self): return self.opt_read_metadata.isChecked() def use_author_sort(self): return self.opt_use_author_sort.isChecked() def validate(self): formats = set(self.format_map()) extra = formats - set(self.calibre_known_formats) if extra: fmts = sorted(x.upper() for x in extra) if not question_dialog(self, _('Unknown formats'), _('You have enabled the <b>{0}</b> formats for' ' your {1}. The {1} may not support them.' ' If you send these formats to your {1} they ' 'may not work. Are you sure?').format( (', '.join(fmts)), self.device_name)): return False tmpl = str(self.opt_save_template.text()) try: validation_formatter.validate(tmpl) return True except Exception as err: error_dialog(self, _('Invalid template'), '<p>'+_('The template %s is invalid:')%tmpl + '<br>'+str(err), show=True) return False
7,850
Python
.py
152
36.875
113
0.575264
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,986
mtp_config.py
kovidgoyal_calibre/src/calibre/gui2/device_drivers/mtp_config.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>' __docformat__ = 'restructuredtext en' import weakref from qt.core import ( QApplication, QComboBox, QDialog, QDialogButtonBox, QGridLayout, QGroupBox, QHBoxLayout, QIcon, QLabel, QLineEdit, QListWidget, QListWidgetItem, QPlainTextEdit, QPushButton, QScrollArea, QSize, QSizePolicy, Qt, QTabWidget, QToolButton, QVBoxLayout, QWidget, pyqtSignal, ) from calibre.ebooks import BOOK_EXTENSIONS from calibre.gui2 import error_dialog from calibre.gui2.device_drivers.mtp_folder_browser import Browser, IgnoredFolders from calibre.gui2.dialogs.template_dialog import TemplateDialog from calibre.utils.date import parse_date from polyglot.builtins import iteritems class FormatsConfig(QWidget): # {{{ def __init__(self, all_formats, format_map): QWidget.__init__(self) self.l = l = QGridLayout() self.setLayout(l) self.f = f = QListWidget(self) l.addWidget(f, 0, 0, 3, 1) unchecked_formats = sorted(all_formats - set(format_map)) for fmt in format_map + unchecked_formats: item = QListWidgetItem(fmt, f) item.setData(Qt.ItemDataRole.UserRole, fmt) item.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsUserCheckable|Qt.ItemFlag.ItemIsSelectable) item.setCheckState(Qt.CheckState.Checked if fmt in format_map else Qt.CheckState.Unchecked) self.button_up = b = QToolButton(self) b.setIcon(QIcon.ic('arrow-up.png')) l.addWidget(b, 0, 1) b.clicked.connect(self.up) self.button_down = b = QToolButton(self) b.setIcon(QIcon.ic('arrow-down.png')) l.addWidget(b, 2, 1) b.clicked.connect(self.down) @property def format_map(self): return [str(self.f.item(i).data(Qt.ItemDataRole.UserRole) or '') for i in range(self.f.count()) if self.f.item(i).checkState()==Qt.CheckState.Checked] def validate(self): if not self.format_map: error_dialog(self, _('No formats selected'), _('You must choose at least one format to send to the' ' device'), show=True) return False return True def up(self): idx = self.f.currentRow() if idx > 0: self.f.insertItem(idx-1, self.f.takeItem(idx)) self.f.setCurrentRow(idx-1) def down(self): idx = self.f.currentRow() if idx < self.f.count()-1: self.f.insertItem(idx+1, self.f.takeItem(idx)) self.f.setCurrentRow(idx+1) # }}} class TemplateConfig(QWidget): # {{{ def __init__(self, val): QWidget.__init__(self) self.t = t = QLineEdit(self) t.setText(val or '') t.setCursorPosition(0) self.setMinimumWidth(400) self.l = l = QGridLayout(self) self.setLayout(l) self.m = m = QLabel('<p>'+_('''<b>Save &template</b> to control the filename and location of files sent to the device:''')) m.setWordWrap(True) m.setBuddy(t) l.addWidget(m, 0, 0, 1, 2) l.addWidget(t, 1, 0, 1, 1) b = self.b = QPushButton(_('&Template editor')) l.addWidget(b, 1, 1, 1, 1) b.clicked.connect(self.edit_template) @property def template(self): return str(self.t.text()).strip() def edit_template(self): t = TemplateDialog(self, self.template) t.setWindowTitle(_('Edit template')) if t.exec(): self.t.setText(t.rule[1]) def validate(self): from calibre.utils.formatter import validation_formatter tmpl = self.template try: validation_formatter.validate(tmpl) return True except Exception as err: error_dialog(self, _('Invalid template'), '<p>'+_('The template %s is invalid:')%tmpl + '<br>'+str(err), show=True) return False # }}} class SendToConfig(QWidget): # {{{ def __init__(self, val, device): QWidget.__init__(self) self.t = t = QLineEdit(self) t.setText(', '.join(val or [])) t.setCursorPosition(0) self.l = l = QGridLayout(self) self.setLayout(l) self.m = m = QLabel('<p>'+_('''A <b>list of &folders</b> on the device to which to send e-books. The first one that exists will be used:''')) m.setWordWrap(True) m.setBuddy(t) l.addWidget(m, 0, 0, 1, 2) l.addWidget(t, 1, 0) self.b = b = QToolButton() l.addWidget(b, 1, 1) b.setIcon(QIcon.ic('document_open.png')) b.clicked.connect(self.browse) b.setToolTip(_('Browse for a folder on the device')) self._device = weakref.ref(device) @property def device(self): return self._device() def browse(self): b = Browser(self.device.filesystem_cache, show_files=False, parent=self) if b.exec() == QDialog.DialogCode.Accepted and b.current_item is not None: sid, path = b.current_item self.t.setText('/'.join(path[1:])) @property def value(self): ans = [x.strip() for x in str(self.t.text()).strip().split(',')] return [x for x in ans if x] # }}} class IgnoredDevices(QWidget): # {{{ def __init__(self, devs, blacklist): QWidget.__init__(self) self.l = l = QVBoxLayout() self.setLayout(l) self.la = la = QLabel('<p>'+_( '''Select the devices to be <b>ignored</b>. calibre <b>will not</b> connect to devices with a checkmark next to their names.''')) la.setWordWrap(True) l.addWidget(la) self.f = f = QListWidget(self) l.addWidget(f) devs = [(snum, (x[0], parse_date(x[1]))) for snum, x in iteritems(devs)] for dev, x in sorted(devs, key=lambda x:x[1][1], reverse=True): name = x[0] name = '%s [%s]'%(name, dev) item = QListWidgetItem(name, f) item.setData(Qt.ItemDataRole.UserRole, dev) item.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsUserCheckable|Qt.ItemFlag.ItemIsSelectable) item.setCheckState(Qt.CheckState.Checked if dev in blacklist else Qt.CheckState.Unchecked) @property def blacklist(self): return [str(self.f.item(i).data(Qt.ItemDataRole.UserRole) or '') for i in range(self.f.count()) if self.f.item(i).checkState()==Qt.CheckState.Checked] def ignore_device(self, snum): for i in range(self.f.count()): i = self.f.item(i) c = str(i.data(Qt.ItemDataRole.UserRole) or '') if c == snum: i.setCheckState(Qt.CheckState.Checked) break # }}} # Rules {{{ class Rule(QWidget): remove = pyqtSignal(object) def __init__(self, device, rule=None): QWidget.__init__(self) self._device = weakref.ref(device) self.l = l = QHBoxLayout() self.setLayout(l) p, s = _('Send the %s format to the folder:').partition('%s')[0::2] self.l1 = l1 = QLabel(p) l.addWidget(l1) self.fmt = f = QComboBox(self) l.addWidget(f) self.l2 = l2 = QLabel(s) l.addWidget(l2) self.folder = f = QLineEdit(self) f.setPlaceholderText(_('Folder on the device')) l.addWidget(f) self.b = b = QToolButton() l.addWidget(b) b.setIcon(QIcon.ic('document_open.png')) b.clicked.connect(self.browse) b.setToolTip(_('Browse for a folder on the device')) self.rb = rb = QPushButton(QIcon.ic('list_remove.png'), _('&Remove rule'), self) l.addWidget(rb) rb.clicked.connect(self.removed) for fmt in sorted(BOOK_EXTENSIONS): self.fmt.addItem(fmt.upper(), fmt.lower()) self.fmt.setCurrentIndex(0) if rule is not None: fmt, folder = rule idx = self.fmt.findText(fmt.upper()) if idx > -1: self.fmt.setCurrentIndex(idx) self.folder.setText(folder) self.ignore = False @property def device(self): return self._device() def browse(self): b = Browser(self.device.filesystem_cache, show_files=False, parent=self) if b.exec() == QDialog.DialogCode.Accepted and b.current_item is not None: sid, path = b.current_item self.folder.setText('/'.join(path[1:])) def removed(self): self.remove.emit(self) @property def rule(self): folder = str(self.folder.text()).strip() if folder: return ( str(self.fmt.itemData(self.fmt.currentIndex()) or ''), folder ) return None class FormatRules(QGroupBox): def __init__(self, device, rules): QGroupBox.__init__(self, _('Format specific sending')) self._device = weakref.ref(device) self.l = l = QVBoxLayout() self.setLayout(l) self.la = la = QLabel('<p>'+_( '''You can create rules that control where e-books of a specific format are sent to on the device. These will take precedence over the folders specified above.''')) la.setWordWrap(True) l.addWidget(la) self.sa = sa = QScrollArea(self) sa.setWidgetResizable(True) self.w = w = QWidget(self) w.l = QVBoxLayout() w.setLayout(w.l) sa.setWidget(w) l.addWidget(sa) self.widgets = [] for rule in rules: r = Rule(device, rule) self.widgets.append(r) w.l.addWidget(r) r.remove.connect(self.remove_rule) if not self.widgets: self.add_rule() self.b = b = QPushButton(QIcon.ic('plus.png'), _('Add a &new rule')) l.addWidget(b) b.clicked.connect(self.add_rule) self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Ignored) @property def device(self): return self._device() def add_rule(self): r = Rule(self.device) self.widgets.append(r) self.w.l.addWidget(r) r.remove.connect(self.remove_rule) self.sa.verticalScrollBar().setValue(self.sa.verticalScrollBar().maximum()) def remove_rule(self, rule): rule.setVisible(False) rule.ignore = True @property def rules(self): for w in self.widgets: if not w.ignore: r = w.rule if r is not None: yield r # }}} class MTPConfig(QTabWidget): def __init__(self, device, parent=None, highlight_ignored_folders=False): QTabWidget.__init__(self, parent) self._device = weakref.ref(device) cd = msg = None if device.current_friendly_name is not None: if device.current_serial_num is None: msg = '<p>' + (_('The <b>%s</b> device has no serial number, ' 'it cannot be configured')%device.current_friendly_name) else: cd = 'device-'+device.current_serial_num else: msg = '<p>' + _('<b>No MTP device connected.</b><p>' ' You can only configure the MTP device plugin when a device' ' is connected.') self.current_device_key = cd if msg: msg += '<p>' + _('If you want to un-ignore a previously' ' ignored MTP device, use the "Ignored devices" tab.') l = QLabel(msg) l.setWordWrap(True) l.setStyleSheet('QLabel { margin-left: 2em }') l.setMinimumWidth(500) l.setMinimumHeight(400) self.insertTab(0, l, _('Cannot configure')) else: self.base = QWidget(self) self.insertTab(0, self.base, _('Configure %s')%self.device.current_friendly_name) l = self.base.l = QGridLayout(self.base) self.base.setLayout(l) self.rules = r = FormatRules(self.device, self.get_pref('rules')) self.formats = FormatsConfig(set(BOOK_EXTENSIONS), self.get_pref('format_map')) self.send_to = SendToConfig(self.get_pref('send_to'), self.device) self.template = TemplateConfig(self.get_pref('send_template')) self.base.la = la = QLabel(_( 'Choose the formats to send to the %s')%self.device.current_friendly_name) la.setWordWrap(True) self.base.b = b = QPushButton(QIcon.ic('list_remove.png'), _('&Ignore the %s in calibre')%device.current_friendly_name, self.base) b.clicked.connect(self.ignore_device) self.config_ign_folders_button = cif = QPushButton( QIcon.ic('tb_folder.png'), _('Change scanned &folders')) cif.setStyleSheet( 'QPushButton { font-weight: bold; }') if highlight_ignored_folders: cif.setIconSize(QSize(64, 64)) self.show_debug_button = bd = QPushButton(QIcon.ic('debug.png'), _('Show device information')) bd.clicked.connect(self.show_debug_info) cif.clicked.connect(self.change_ignored_folders) l.addWidget(b, 0, 0, 1, 2) l.addWidget(la, 1, 0, 1, 1) l.addWidget(self.formats, 2, 0, 5, 1) l.addWidget(cif, 2, 1, 1, 1) l.addWidget(self.template, 3, 1, 1, 1) l.addWidget(self.send_to, 4, 1, 1, 1) l.addWidget(self.show_debug_button, 5, 1, 1, 1) l.setRowStretch(6, 10) l.addWidget(r, 7, 0, 1, 2) l.setRowStretch(7, 100) self.igntab = IgnoredDevices(self.device.prefs['history'], self.device.prefs['blacklist']) self.addTab(self.igntab, _('Ignored devices')) self.current_ignored_folders = self.get_pref('ignored_folders') self.initial_ignored_folders = self.current_ignored_folders self.setCurrentIndex(1 if msg else 0) def show_debug_info(self): info = self.device.device_debug_info() d = QDialog(self) d.l = l = QVBoxLayout() d.setLayout(l) d.v = v = QPlainTextEdit() d.setWindowTitle(self.device.get_gui_name()) v.setPlainText(info) v.setMinimumWidth(400) v.setMinimumHeight(350) l.addWidget(v) bb = d.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) bb.accepted.connect(d.accept) bb.rejected.connect(d.reject) l.addWidget(bb) bb.addButton(_('Copy to clipboard'), QDialogButtonBox.ButtonRole.ActionRole) bb.clicked.connect(lambda : QApplication.clipboard().setText(v.toPlainText())) d.exec() def change_ignored_folders(self): d = IgnoredFolders(self.device, self.current_ignored_folders, parent=self) if d.exec() == QDialog.DialogCode.Accepted: self.current_ignored_folders = d.ignored_folders def ignore_device(self): self.igntab.ignore_device(self.device.current_serial_num) self.base.b.setEnabled(False) self.base.b.setText(_('The %s will be ignored in calibre')% self.device.current_friendly_name) self.base.b.setStyleSheet('QPushButton { font-weight: bold }') self.base.setEnabled(False) def get_pref(self, key): p = self.device.prefs.get(self.current_device_key, {}) if not p and self.current_device_key is not None: self.device.prefs[self.current_device_key] = p return self.device.get_pref(key) @property def device(self): return self._device() def validate(self): if hasattr(self, 'formats'): if not self.formats.validate(): return False if not self.template.validate(): return False return True def commit(self): self.device.prefs['blacklist'] = self.igntab.blacklist p = self.device.prefs.get(self.current_device_key, {}) if hasattr(self, 'formats'): p.pop('format_map', None) f = self.formats.format_map if f and f != self.device.prefs['format_map']: p['format_map'] = f p.pop('send_template', None) t = self.template.template if t and t != self.device.prefs['send_template']: p['send_template'] = t p.pop('send_to', None) s = self.send_to.value if s and s != self.device.prefs['send_to']: p['send_to'] = s p.pop('rules', None) r = list(self.rules.rules) if r and r != self.device.prefs['rules']: p['rules'] = r if self.current_ignored_folders != self.initial_ignored_folders: p['ignored_folders'] = self.current_ignored_folders if self.current_device_key is not None: self.device.prefs[self.current_device_key] = p class SendError(QDialog): def __init__(self, gui, error): QDialog.__init__(self, gui) self.l = l = QVBoxLayout() self.setLayout(l) self.la = la = QLabel('<p>'+ _('You are trying to send books into the <b>%s</b> folder. This ' 'folder is currently ignored by calibre when scanning the ' 'device. You have to tell calibre you want this folder scanned ' 'in order to be able to send books to it. Click the ' '<b>Configure</b> button below to send books to it.')%error.folder) la.setWordWrap(True) la.setMinimumWidth(500) l.addWidget(la) self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) self.b = bb.addButton(_('Configure'), QDialogButtonBox.ButtonRole.AcceptRole) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) l.addWidget(bb) self.setWindowTitle(_('Cannot send to %s')%error.folder) self.setWindowIcon(QIcon.ic('dialog_error.png')) self.resize(self.sizeHint()) def accept(self): QDialog.accept(self) dev = self.parent().device_manager.connected_device dev.highlight_ignored_folders = True self.parent().configure_connected_device() dev.highlight_ignored_folders = False if __name__ == '__main__': from calibre.devices.mtp.driver import MTP_DEVICE from calibre.devices.scanner import DeviceScanner from calibre.gui2 import Application s = DeviceScanner() s.scan() app = Application([]) dev = MTP_DEVICE(None) dev.startup() cd = dev.detect_managed_devices(s.devices) dev.open(cd, 'test') cw = dev.config_widget() d = QDialog() d.l = QVBoxLayout() d.setLayout(d.l) d.l.addWidget(cw) bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel) d.l.addWidget(bb) bb.accepted.connect(d.accept) bb.rejected.connect(d.reject) if d.exec() == QDialog.DialogCode.Accepted: cw.commit() dev.shutdown()
19,494
Python
.py
481
30.823285
113
0.589072
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,987
tabbed_device_config.py
kovidgoyal_calibre/src/calibre/gui2/device_drivers/tabbed_device_config.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>' __docformat__ = 'restructuredtext en' import textwrap import weakref from qt.core import ( QCheckBox, QComboBox, QDialog, QDialogButtonBox, QGridLayout, QGroupBox, QLabel, QLineEdit, QSizePolicy, QSpacerItem, QTabWidget, QVBoxLayout, QWidget, ) from calibre.ebooks import BOOK_EXTENSIONS from calibre.gui2.device_drivers.mtp_config import FormatsConfig, TemplateConfig from calibre.prints import debug_print def wrap_msg(msg): return textwrap.fill(msg.strip(), 100) def setToolTipFor(widget, tt): widget.setToolTip(wrap_msg(tt)) def create_checkbox(title, tt, state): cb = QCheckBox(title) cb.setToolTip(wrap_msg(tt)) cb.setChecked(bool(state)) return cb class TabbedDeviceConfig(QTabWidget): """ This is a generic Tabbed Device config widget. It designed for devices with more complex configuration. But, it is backwards compatible to the standard device configuration widget. The configuration made up of two default tabs plus extra tabs as needed for the device. The extra tabs are defined as part of the subclass of this widget for the device. The two default tabs are the "File Formats" and "Extra Customization". These tabs are the same as the two sections of the standard device configuration widget. The second of these tabs will only be created if the device driver has extra configuration options. All options on these tabs work the same way as for the standard device configuration widget. When implementing a subclass for a device driver, create tabs, subclassed from DeviceConfigTab, for each set of options. Within the tabs, group boxes, subclassed from DeviceOptionsGroupBox, are created to further group the options. The group boxes can be coded to support any control type and dependencies between them. """ def __init__(self, device_settings, all_formats, supports_subdirs, must_read_metadata, supports_use_author_sort, extra_customization_message, device, extra_customization_choices=None, parent=None): QTabWidget.__init__(self, parent) self._device = weakref.ref(device) self.device_settings = device_settings self.all_formats = set(all_formats) self.supports_subdirs = supports_subdirs self.must_read_metadata = must_read_metadata self.supports_use_author_sort = supports_use_author_sort self.extra_customization_message = extra_customization_message self.extra_customization_choices = extra_customization_choices try: self.device_name = device.get_gui_name() except TypeError: self.device_name = getattr(device, 'gui_name', None) or _('Device') if device.USER_CAN_ADD_NEW_FORMATS: self.all_formats = set(self.all_formats) | set(BOOK_EXTENSIONS) self.base = QWidget(self) # self.insertTab(0, self.base, _('Configure %s') % self.device.current_friendly_name) self.insertTab(0, self.base, _("File formats")) l = self.base.l = QGridLayout(self.base) self.base.setLayout(l) self.formats = FormatsConfig(self.all_formats, device_settings.format_map) if device.HIDE_FORMATS_CONFIG_BOX: self.formats.hide() self.opt_use_subdirs = create_checkbox( _("Use sub-folders"), _('Place files in sub-folders if the device supports them'), device_settings.use_subdirs ) self.opt_read_metadata = create_checkbox( _("Read metadata from files on device"), _('Read metadata from files on device'), device_settings.read_metadata ) self.template = TemplateConfig(device_settings.save_template) self.opt_use_author_sort = create_checkbox( _("Use author sort for author"), _("Use author sort for author"), device_settings.read_metadata ) self.opt_use_author_sort.setObjectName("opt_use_author_sort") self.base.la = la = QLabel(_( 'Choose the formats to send to the %s')%self.device_name) la.setWordWrap(True) l.addWidget(la, 1, 0, 1, 1) l.addWidget(self.formats, 2, 0, 1, 1) l.addWidget(self.opt_read_metadata, 3, 0, 1, 1) l.addWidget(self.opt_use_subdirs, 4, 0, 1, 1) l.addWidget(self.opt_use_author_sort, 5, 0, 1, 1) l.addWidget(self.template, 6, 0, 1, 1) l.setRowStretch(2, 10) if device.HIDE_FORMATS_CONFIG_BOX: self.formats.hide() if supports_subdirs: self.opt_use_subdirs.setChecked(device_settings.use_subdirs) else: self.opt_use_subdirs.hide() if not must_read_metadata: self.opt_read_metadata.setChecked(device_settings.read_metadata) else: self.opt_read_metadata.hide() if supports_use_author_sort: self.opt_use_author_sort.setChecked(device_settings.use_author_sort) else: self.opt_use_author_sort.hide() self.extra_tab = ExtraCustomization(self.extra_customization_message, self.extra_customization_choices, self.device_settings) # Only display the extra customization tab if there are options on it. if self.extra_tab.has_extra_customizations: self.addTab(self.extra_tab, _('Extra customization')) self.setCurrentIndex(0) def addDeviceTab(self, tab, label): ''' This is used to add a new tab for the device config. The new tab will always be added as immediately before the "Extra Customization" tab. ''' extra_tab_pos = self.indexOf(self.extra_tab) self.insertTab(extra_tab_pos, tab, label) def __getattr__(self, attr_name): "If the object doesn't have an attribute, then check each tab." try: return super().__getattr__(attr_name) except AttributeError as ae: for i in range(0, self.count()): atab = self.widget(i) try: return getattr(atab, attr_name) except AttributeError: pass raise ae @property def device(self): return self._device() def format_map(self): return self.formats.format_map def use_subdirs(self): return self.opt_use_subdirs.isChecked() def read_metadata(self): return self.opt_read_metadata.isChecked() def use_author_sort(self): return self.opt_use_author_sort.isChecked() @property def opt_save_template(self): # Really shouldn't be accessing the template this way return self.template.t def text(self): # Really shouldn't be accessing the template this way return self.template.t.text() @property def opt_extra_customization(self): return self.extra_tab.opt_extra_customization @property def label(self): return self.opt_save_template def validate(self): if hasattr(self, 'formats'): if not self.formats.validate(): return False if not self.template.validate(): return False return True def commit(self): debug_print("TabbedDeviceConfig::commit: start") p = self.device._configProxy() p['format_map'] = self.formats.format_map p['use_subdirs'] = self.use_subdirs() p['read_metadata'] = self.read_metadata() p['save_template'] = self.template.template p['extra_customization'] = self.extra_tab.extra_customization() return p class DeviceConfigTab(QWidget): # {{{ ''' This is an abstraction for a tab in the configuration. The main reason for it is to abstract the properties of the configuration tab. When a property is accessed, it will iterate over all known widgets looking for the property. ''' def __init__(self, parent=None): QWidget.__init__(self) self.parent = parent self.device_widgets = [] def addDeviceWidget(self, widget): self.device_widgets.append(widget) def __getattr__(self, attr_name): try: return super().__getattr__(attr_name) except AttributeError as ae: for awidget in self.device_widgets: try: return getattr(awidget, attr_name) except AttributeError: pass raise ae class ExtraCustomization(DeviceConfigTab): # {{{ def __init__(self, extra_customization_message, extra_customization_choices, device_settings): super().__init__() debug_print("ExtraCustomization.__init__ - extra_customization_message=", extra_customization_message) debug_print("ExtraCustomization.__init__ - extra_customization_choices=", extra_customization_choices) debug_print("ExtraCustomization.__init__ - device_settings.extra_customization=", device_settings.extra_customization) debug_print("ExtraCustomization.__init__ - device_settings=", device_settings) self.extra_customization_message = extra_customization_message self.l = QVBoxLayout(self) self.setLayout(self.l) options_group = QGroupBox(_("Extra driver customization options"), self) self.l.addWidget(options_group) self.extra_layout = QGridLayout() self.extra_layout.setObjectName("extra_layout") options_group.setLayout(self.extra_layout) if extra_customization_message: extra_customization_choices = extra_customization_choices or {} def parse_msg(m): msg, _, tt = m.partition(':::') if m else ('', '', '') return msg.strip(), textwrap.fill(tt.strip(), 100) if isinstance(extra_customization_message, list): self.opt_extra_customization = [] if len(extra_customization_message) > 6: def row_func(x, y): return (x // 2 * 2 + y) def col_func(x): return (x % 2) else: def row_func(x, y): return (x * 2 + y) def col_func(x): return 0 for i, m in enumerate(extra_customization_message): label_text, tt = parse_msg(m) if not label_text: self.opt_extra_customization.append(None) continue if isinstance(device_settings.extra_customization[i], bool): self.opt_extra_customization.append(QCheckBox(label_text)) self.opt_extra_customization[-1].setToolTip(tt) self.opt_extra_customization[i].setChecked(bool(device_settings.extra_customization[i])) elif i in extra_customization_choices: cb = QComboBox(self) self.opt_extra_customization.append(cb) l = QLabel(label_text) l.setToolTip(tt), cb.setToolTip(tt), l.setBuddy(cb), cb.setToolTip(tt) for li in sorted(extra_customization_choices[i]): self.opt_extra_customization[i].addItem(li) cb.setCurrentIndex(max(0, cb.findText(device_settings.extra_customization[i]))) else: self.opt_extra_customization.append(QLineEdit(self)) l = QLabel(label_text) l.setToolTip(tt) self.opt_extra_customization[i].setToolTip(tt) l.setBuddy(self.opt_extra_customization[i]) l.setWordWrap(True) self.opt_extra_customization[i].setText(device_settings.extra_customization[i]) self.opt_extra_customization[i].setCursorPosition(0) self.extra_layout.addWidget(l, row_func(i + 2, 0), col_func(i)) self.extra_layout.addWidget(self.opt_extra_customization[i], row_func(i + 2, 1), col_func(i)) spacerItem1 = QSpacerItem(10, 10, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Expanding) self.extra_layout.addItem(spacerItem1, row_func(i + 2 + 2, 1), 0, 1, 2) self.extra_layout.setRowStretch(row_func(i + 2 + 2, 1), 2) else: self.opt_extra_customization = QLineEdit() label_text, tt = parse_msg(extra_customization_message) l = QLabel(label_text) l.setToolTip(tt) l.setBuddy(self.opt_extra_customization) l.setWordWrap(True) if device_settings.extra_customization: self.opt_extra_customization.setText(device_settings.extra_customization) self.opt_extra_customization.setCursorPosition(0) self.opt_extra_customization.setCursorPosition(0) self.extra_layout.addWidget(l, 0, 0) self.extra_layout.addWidget(self.opt_extra_customization, 1, 0) def extra_customization(self): ec = [] if self.extra_customization_message: if isinstance(self.extra_customization_message, list): for i in range(0, len(self.extra_customization_message)): if self.opt_extra_customization[i] is None: ec.append(None) continue if hasattr(self.opt_extra_customization[i], 'isChecked'): ec.append(self.opt_extra_customization[i].isChecked()) elif hasattr(self.opt_extra_customization[i], 'currentText'): ec.append(str(self.opt_extra_customization[i].currentText()).strip()) else: ec.append(str(self.opt_extra_customization[i].text()).strip()) else: ec = str(self.opt_extra_customization.text()).strip() if not ec: ec = None return ec @property def has_extra_customizations(self): debug_print("ExtraCustomization::has_extra_customizations - self.extra_customization_message", self.extra_customization_message) return self.extra_customization_message and len(self.extra_customization_message) > 0 # }}} class DeviceOptionsGroupBox(QGroupBox): """ This is a container for the individual options for a device driver. """ def __init__(self, parent, device=None, title=_("Unknown")): QGroupBox.__init__(self, parent) self.device = device self.setTitle(title) if __name__ == '__main__': from calibre.devices.kobo.driver import KOBO from calibre.devices.scanner import DeviceScanner from calibre.gui2 import Application s = DeviceScanner() s.scan() app = Application([]) dev = KOBO(None) debug_print("KOBO:", KOBO) # dev.startup() # cd = dev.detect_managed_devices(s.devices) # dev.open(cd, 'test') cw = dev.config_widget() d = QDialog() d.l = QVBoxLayout() d.setLayout(d.l) d.l.addWidget(cw) bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel) d.l.addWidget(bb) bb.accepted.connect(d.accept) bb.rejected.connect(d.reject) if d.exec() == QDialog.DialogCode.Accepted: cw.commit() dev.shutdown()
16,402
Python
.py
340
35.767647
136
0.596136
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,988
mtp_folder_browser.py
kovidgoyal_calibre/src/calibre/gui2/device_drivers/mtp_folder_browser.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>' __docformat__ = 'restructuredtext en' from operator import attrgetter from qt.core import QDialog, QDialogButtonBox, QIcon, QLabel, QSize, Qt, QTabWidget, QTreeWidget, QTreeWidgetItem, QVBoxLayout, pyqtSignal from calibre.gui2 import file_icon_provider from calibre.utils.icu import lower as icu_lower def browser_item(f, parent): name = f.name if not f.is_folder: name += ' [%s]'%f.last_mod_string ans = QTreeWidgetItem(parent, [name]) ans.setData(0, Qt.ItemDataRole.UserRole, f.full_path) if f.is_folder: ext = 'dir' else: ext = f.name.rpartition('.')[-1] ans.setData(0, Qt.ItemDataRole.DecorationRole, file_icon_provider().icon_from_ext(ext)) return ans class Storage(QTreeWidget): def __init__(self, storage, show_files=False, item_func=browser_item): QTreeWidget.__init__(self) self.item_func = item_func self.show_files = show_files self.create_children(storage, self) self.name = storage.name self.object_id = storage.persistent_id self.setMinimumHeight(350) self.setHeaderHidden(True) self.storage = storage def create_children(self, f, parent): for child in sorted(f.folders, key=attrgetter('name')): i = self.item_func(child, parent) self.create_children(child, i) if self.show_files: for child in sorted(f.files, key=attrgetter('name')): i = self.item_func(child, parent) @property def current_item(self): item = self.currentItem() if item is not None: return (self.object_id, item.data(0, Qt.ItemDataRole.UserRole)) return None class Folders(QTabWidget): selected = pyqtSignal() def __init__(self, filesystem_cache, show_files=True): QTabWidget.__init__(self) self.fs = filesystem_cache for storage in self.fs.entries: w = Storage(storage, show_files) self.addTab(w, w.name) w.doubleClicked.connect(self.selected) self.setCurrentIndex(0) @property def current_item(self): w = self.currentWidget() if w is not None: return w.current_item class Browser(QDialog): def __init__(self, filesystem_cache, show_files=True, parent=None): QDialog.__init__(self, parent) self.l = l = QVBoxLayout() self.setLayout(l) self.folders = cw = Folders(filesystem_cache, show_files=show_files) l.addWidget(cw) bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel) l.addWidget(bb) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) self.setMinimumSize(QSize(500, 500)) self.folders.selected.connect(self.accept) self.setWindowTitle(_('Choose folder on device')) self.setWindowIcon(QIcon.ic('devices/tablet.png')) @property def current_item(self): return self.folders.current_item class IgnoredFolders(QDialog): def __init__(self, dev, ignored_folders=None, parent=None): QDialog.__init__(self, parent) self.l = l = QVBoxLayout() self.setLayout(l) self.la = la = QLabel('<p>'+ _('<b>Scanned folders:</b>') + ' ' + _('You can select which folders calibre will ' 'scan when searching this device for books.')) la.setWordWrap(True) l.addWidget(la) self.tabs = QTabWidget(self) l.addWidget(self.tabs) self.widgets = [] for storage in dev.filesystem_cache.entries: self.dev = dev w = Storage(storage, item_func=self.create_item) del self.dev self.tabs.addTab(w, storage.name) self.widgets.append(w) w.itemChanged.connect(self.item_changed) self.la2 = la = QLabel(_( 'If you a select a previously unselected folder, any sub-folders' ' will not be visible until you restart calibre.')) l.addWidget(la) la.setWordWrap(True) self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) self.bb.accepted.connect(self.accept) self.bb.rejected.connect(self.reject) self.sab = self.bb.addButton(_('Select &all'), QDialogButtonBox.ButtonRole.ActionRole) self.sab.clicked.connect(self.select_all) self.snb = self.bb.addButton(_('Select &none'), QDialogButtonBox.ButtonRole.ActionRole) self.snb.clicked.connect(self.select_none) l.addWidget(self.bb) self.setWindowTitle(_('Choose folders to scan')) self.setWindowIcon(QIcon.ic('devices/tablet.png')) self.resize(600, 500) def item_changed(self, item, column): w = item.treeWidget() root = w.invisibleRootItem() w.itemChanged.disconnect(self.item_changed) try: if item.checkState(0) == Qt.CheckState.Checked: # Ensure that the parents of this item are checked p = item.parent() while p is not None and p is not root: p.setCheckState(0, Qt.CheckState.Checked) p = p.parent() # Set the state of all descendants to the same state as this item for child in self.iterchildren(item): child.setCheckState(0, item.checkState(0)) finally: w.itemChanged.connect(self.item_changed) def iterchildren(self, node): ' Iterate over all descendants of node ' for i in range(node.childCount()): child = node.child(i) yield child yield from self.iterchildren(child) def create_item(self, f, parent): name = f.name ans = QTreeWidgetItem(parent, [name]) ans.setData(0, Qt.ItemDataRole.UserRole, '/'.join(f.full_path[1:])) ans.setFlags(Qt.ItemFlag.ItemIsUserCheckable | Qt.ItemFlag.ItemIsEnabled) ans.setCheckState(0, Qt.CheckState.Unchecked if self.dev.is_folder_ignored(f.storage_id, f.full_path[1:]) else Qt.CheckState.Checked) ans.setData(0, Qt.ItemDataRole.DecorationRole, file_icon_provider().icon_from_ext('dir')) return ans def select_all(self): w = self.tabs.currentWidget() for i in range(w.invisibleRootItem().childCount()): c = w.invisibleRootItem().child(i) c.setCheckState(0, Qt.CheckState.Checked) def select_none(self): w = self.tabs.currentWidget() for i in range(w.invisibleRootItem().childCount()): c = w.invisibleRootItem().child(i) c.setCheckState(0, Qt.CheckState.Unchecked) @property def ignored_folders(self): ans = {} for w in self.widgets: folders = set() for node in self.iterchildren(w.invisibleRootItem()): if node.checkState(0) == Qt.CheckState.Checked: continue path = str(node.data(0, Qt.ItemDataRole.UserRole) or '') parent = path.rpartition('/')[0] if '/' not in path or icu_lower(parent) not in folders: folders.add(icu_lower(path)) ans[str(w.storage.storage_id)] = list(folders) return ans def setup_device(): from calibre.devices.mtp.driver import MTP_DEVICE from calibre.devices.scanner import DeviceScanner s = DeviceScanner() s.scan() dev = MTP_DEVICE(None) dev.startup() cd = dev.detect_managed_devices(s.devices) if cd is None: raise ValueError('No MTP device found') dev.open(cd, 'test') return dev def browse(): from calibre.gui2 import Application app = Application([]) app dev = setup_device() d = Browser(dev.filesystem_cache) d.exec() dev.shutdown() return d.current_item def ignored_folders(): from calibre.gui2 import Application app = Application([]) app dev = setup_device() d = IgnoredFolders(dev) d.exec() dev.shutdown() return d.ignored_folders if __name__ == '__main__': print(browse()) # print ('Ignored:', ignored_folders())
8,379
Python
.py
202
32.633663
138
0.62978
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,989
edit_authors_dialog.py
kovidgoyal_calibre/src/calibre/gui2/dialogs/edit_authors_dialog.py
#!/usr/bin/env python __copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net' __docformat__ = 'restructuredtext en' __license__ = 'GPL v3' from contextlib import contextmanager from functools import partial from qt.core import ( QAbstractItemView, QAction, QApplication, QDialog, QDialogButtonBox, QFrame, QIcon, QLabel, QMenu, QStyledItemDelegate, Qt, QTableWidgetItem, QTimer, ) from calibre.ebooks.metadata import author_to_author_sort, string_to_authors from calibre.gui2 import error_dialog, gprefs from calibre.gui2.dialogs.edit_authors_dialog_ui import Ui_EditAuthorsDialog from calibre.gui2.dialogs.tag_list_editor import NotesTableWidgetItem, NotesUtilities from calibre.utils.config import prefs from calibre.utils.config_base import tweaks from calibre.utils.icu import contains, primary_contains, primary_startswith, sort_key from calibre.utils.icu import lower as icu_lower from calibre.utils.icu import upper as icu_upper QT_HIDDEN_CLEAR_ACTION = '_q_qlineeditclearaction' class TableItem(QTableWidgetItem): def __init__(self, txt, skey=None): QTableWidgetItem.__init__(self, txt) self.sort_key = sort_key(str(txt)) if skey is None else skey def setText(self, txt): self.sort_key = sort_key(str(txt)) QTableWidgetItem.setText(self, txt) def set_sort_key(self): self.sort_key = sort_key(str(self.text())) def __ge__(self, other): return self.sort_key >= other.sort_key def __lt__(self, other): return self.sort_key < other.sort_key class CountTableItem(QTableWidgetItem): def __init__(self, val): QTableWidgetItem.__init__(self, str(val)) self.val = val self.setTextAlignment(Qt.AlignmentFlag.AlignRight|Qt.AlignmentFlag.AlignVCenter) self.setFlags(Qt.ItemFlag.ItemIsEnabled) def setText(self, val): self.val = val QTableWidgetItem.setText(self, str(val)) def set_sort_key(self): pass def __ge__(self, other): return self.val >= other.val def __lt__(self, other): return self.val < other.val AUTHOR_COLUMN = 0 AUTHOR_SORT_COLUMN = 1 COUNTS_COLUMN = 2 LINK_COLUMN = 3 NOTES_COLUMN = 4 class EditColumnDelegate(QStyledItemDelegate): def __init__(self, completion_data, table, notes_utilities, item_id_getter): super().__init__(table) self.table = table self.completion_data = completion_data self.notes_utilities = notes_utilities self.item_id_getter = item_id_getter def createEditor(self, parent, option, index): if index.column() == AUTHOR_COLUMN: if self.completion_data: from calibre.gui2.complete2 import EditWithComplete editor = EditWithComplete(parent) editor.set_separator(None) editor.update_items_cache(self.completion_data) return editor if index.column() == NOTES_COLUMN: self.notes_utilities.edit_note(self.table.itemFromIndex(index)) return None if index.column() == COUNTS_COLUMN: return None from calibre.gui2.widgets import EnLineEdit editor = EnLineEdit(parent) editor.setClearButtonEnabled(True) return editor class EditAuthorsDialog(QDialog, Ui_EditAuthorsDialog): def __init__(self, parent, db, id_to_select, select_sort, select_link, find_aut_func, is_first_letter=False): QDialog.__init__(self, parent) Ui_EditAuthorsDialog.__init__(self) self.setupUi(self) # Remove help icon on title bar icon = self.windowIcon() self.setWindowFlags(self.windowFlags()&(~Qt.WindowType.WindowContextHelpButtonHint)) self.setWindowIcon(icon) try: self.table_column_widths = \ gprefs.get('manage_authors_table_widths', None) self.restore_geometry(gprefs, 'manage_authors_dialog_geometry') except Exception: pass self.notes_utilities = NotesUtilities(self.table, "authors", lambda item: int(self.table.item(item.row(), AUTHOR_COLUMN).data(Qt.ItemDataRole.UserRole))) self.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setText(_('&OK')) self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setText(_('&Cancel')) self.buttonBox.accepted.connect(self.accepted) self.buttonBox.rejected.connect(self.rejected) self.show_button_layout.setSpacing(0) self.show_button_layout.setContentsMargins(0, 0, 0, 0) self.apply_all_checkbox.setContentsMargins(0, 0, 0, 0) self.apply_all_checkbox.setChecked(True) self.apply_vl_checkbox.setContentsMargins(0, 0, 0, 0) self.apply_vl_checkbox.toggled.connect(self.use_vl_changed) self.apply_selection_checkbox.setContentsMargins(0, 0, 0, 0) self.apply_selection_checkbox.toggled.connect(self.apply_selection_box_changed) self.edit_current_cell.clicked.connect(self.edit_cell) self.table.setAlternatingRowColors(True) self.table.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection) self.find_aut_func = find_aut_func self.table.resizeColumnsToContents() if self.table.columnWidth(2) < 200: self.table.setColumnWidth(2, 200) # set up the cellChanged signal only after the table is filled self.ignore_cell_changed = False self.table.cellChanged.connect(self.cell_changed) self.recalc_author_sort.clicked.connect(self.do_recalc_author_sort) self.auth_sort_to_author.clicked.connect(self.do_auth_sort_to_author) # Capture clicks on the horizontal header to sort the table columns hh = self.table.horizontalHeader() hh.sectionResized.connect(self.table_column_resized) hh.setSectionsClickable(True) hh.sectionClicked.connect(self.do_sort) hh.setSortIndicatorShown(True) vh = self.table.verticalHeader() vh.setDefaultSectionSize(gprefs.get('general_category_editor_row_height', vh.defaultSectionSize())) vh.sectionResized.connect(self.row_height_changed) # set up the search & filter boxes self.find_box.initialize('manage_authors_search') le = self.find_box.lineEdit() ac = le.findChild(QAction, QT_HIDDEN_CLEAR_ACTION) if ac is not None: ac.triggered.connect(self.clear_find) le.returnPressed.connect(self.do_find) self.find_box.editTextChanged.connect(self.find_text_changed) self.find_button.clicked.connect(self.do_find) self.find_button.setDefault(True) self.filter_box.initialize('manage_authors_filter') le = self.filter_box.lineEdit() ac = le.findChild(QAction, QT_HIDDEN_CLEAR_ACTION) if ac is not None: ac.triggered.connect(self.clear_filter) self.filter_box.lineEdit().returnPressed.connect(self.do_filter) self.filter_button.clicked.connect(self.do_filter) self.not_found_label = l = QLabel(self.table) l.setFrameStyle(QFrame.Shape.StyledPanel) l.setAutoFillBackground(True) l.setText(_('No matches found')) l.setAlignment(Qt.AlignmentFlag.AlignVCenter) l.resize(l.sizeHint()) l.move(10, 2) l.setVisible(False) self.not_found_label_timer = QTimer() self.not_found_label_timer.setSingleShot(True) self.not_found_label_timer.timeout.connect( self.not_found_label_timer_event, type=Qt.ConnectionType.QueuedConnection) self.table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.table.customContextMenuRequested.connect(self.show_context_menu) # Fetch the data self.authors = {} self.original_authors = {} auts = db.new_api.author_data() self.completion_data = [] counts = db.new_api.get_usage_count_by_id('authors') for id_, v in auts.items(): name = v['name'] name = name.replace('|', ',') self.completion_data.append(name) vals = {'name': name, 'sort': v['sort'], 'link': v['link'], 'count':counts[id_]} self.authors[id_] = vals self.original_authors[id_] = vals.copy() if prefs['use_primary_find_in_search']: self.string_contains = primary_contains else: self.string_contains = contains self.last_sorted_by = 'sort' self.author_order = 1 self.author_sort_order = 0 self.link_order = 1 self.notes_order = 1 self.table.setItemDelegate(EditColumnDelegate(self.completion_data, self.table, self.notes_utilities, self.get_item_id)) self.show_table(id_to_select, select_sort, select_link, is_first_letter) def edit_cell(self): if self.table.currentIndex().isValid(): self.table.editItem(self.table.currentItem()) def get_item_id(self, item): return int(self.table.item(item.row(), AUTHOR_COLUMN).data(Qt.ItemDataRole.UserRole)) @contextmanager def no_cell_changed(self): orig = self.ignore_cell_changed self.ignore_cell_changed = True try: yield finally: self.ignore_cell_changed = orig def use_vl_changed(self, x): self.show_table(None, None, None, False) def apply_selection_box_changed(self, x): self.show_table(None, None, None, False) def selection_to_apply(self): if self.apply_selection_checkbox.isChecked(): return 'selection' if self.apply_vl_checkbox.isChecked(): return 'virtual_library' return None def clear_filter(self): self.filter_box.setText('') self.show_table(None, None, None, False) def do_filter(self): self.show_table(None, None, None, False) def show_table(self, id_to_select, select_sort, select_link, is_first_letter): auts_to_show = {t[0] for t in self.find_aut_func(self.selection_to_apply())} filter_text = icu_lower(str(self.filter_box.text())) if filter_text: auts_to_show = {id_ for id_ in auts_to_show if self.string_contains(filter_text, icu_lower(self.authors[id_]['name']))} self.table.blockSignals(True) self.table.clear() self.table.setColumnCount(5) self.table.setRowCount(len(auts_to_show)) row = 0 from calibre.gui2.ui import get_gui all_items_that_have_notes = get_gui().current_db.new_api.get_all_items_that_have_notes('authors') for id_, v in self.authors.items(): if id_ not in auts_to_show: continue name, sort, link, count = (v['name'], v['sort'], v['link'], v['count']) name = name.replace('|', ',') name_item = TableItem(name) name_item.setData(Qt.ItemDataRole.UserRole, id_) sort_item = TableItem(sort) link_item = TableItem(link) count_item = CountTableItem(count) self.table.setItem(row, AUTHOR_COLUMN, name_item) self.table.setItem(row, AUTHOR_SORT_COLUMN, sort_item) self.table.setItem(row, LINK_COLUMN, link_item) note_item = NotesTableWidgetItem() self.table.setItem(row, NOTES_COLUMN, note_item) self.table.setItem(row, COUNTS_COLUMN, count_item) self.set_icon(name_item, id_) self.set_icon(sort_item, id_) self.set_icon(link_item, id_) self.notes_utilities.set_icon(note_item, id_, id_ in all_items_that_have_notes) row += 1 headers = { # this depends on the dict being ordered, which is true from python 3.7 _('Author'): _('Name of the author'), _('Author sort'): _('Value used to sort this author'), _('Count'): _('Count of books with this author'), _('Link'): _('Link (URL) for this author'), _('Notes'): _('Whether this author has a note attached. The icon changes if the note was created or edited'), } self.table.setHorizontalHeaderLabels(headers.keys()) for i,tt in enumerate(headers.values()): header_item = self.table.horizontalHeaderItem(i) header_item.setToolTip(tt) if self.last_sorted_by == 'sort': self.author_sort_order = 1 - self.author_sort_order self.do_sort_by_author_sort() elif self.last_sorted_by == 'author': self.author_order = 1 - self.author_order self.do_sort_by_author() elif self.last_sorted_by == 'link': self.link_order = 1 - self.link_order self.do_sort_by_link() else: self.notes_order = 1 - self.notes_order self.do_sort_by_notes() # Position on the desired item select_item = None if id_to_select: use_as = tweaks['categories_use_field_for_author_name'] == 'author_sort' for row in range(0, len(auts_to_show)): if is_first_letter: item_txt = str(self.table.item(row, AUTHOR_SORT_COLUMN).text() if use_as else self.table.item(row, AUTHOR_COLUMN).text()) if primary_startswith(item_txt, id_to_select): select_item = self.table.item(row, AUTHOR_SORT_COLUMN if use_as else 0) break elif id_to_select == self.table.item(row, AUTHOR_COLUMN).data(Qt.ItemDataRole.UserRole): if select_sort: select_item = self.table.item(row, AUTHOR_SORT_COLUMN) elif select_link: select_item = self.table.item(row, LINK_COLUMN) else: select_item = (self.table.item(row, AUTHOR_SORT_COLUMN) if use_as else self.table.item(row, AUTHOR_COLUMN)) break if select_item: self.table.setCurrentItem(select_item) self.table.setFocus(Qt.FocusReason.OtherFocusReason) if select_sort or select_link: self.table.editItem(select_item) self.start_find_pos = select_item.row() * 2 + select_item.column() else: self.table.setCurrentCell(0, 0) self.find_box.setFocus() self.start_find_pos = -1 self.table.blockSignals(False) self.table.setFocus(Qt.FocusReason.OtherFocusReason) def row_height_changed(self, row, old, new): self.table.verticalHeader().blockSignals(True) self.table.verticalHeader().setDefaultSectionSize(new) self.table.verticalHeader().blockSignals(False) def save_state(self): self.table_column_widths = [] for c in range(0, self.table.columnCount()): self.table_column_widths.append(self.table.columnWidth(c)) gprefs['general_category_editor_row_height'] = self.table.verticalHeader().sectionSize(0) gprefs['manage_authors_table_widths'] = self.table_column_widths self.save_geometry(gprefs, 'manage_authors_dialog_geometry') def table_column_resized(self, col, old, new): self.table_column_widths = [] for c in range(0, self.table.columnCount()): self.table_column_widths.append(self.table.columnWidth(c)) def resizeEvent(self, *args): QDialog.resizeEvent(self, *args) if self.table_column_widths is not None: for c,w in enumerate(self.table_column_widths): self.table.setColumnWidth(c, w) else: # the vertical scroll bar might not be rendered, so might not yet # have a width. Assume 25. Not a problem because user-changed column # widths will be remembered w = self.table.width() - 25 - self.table.verticalHeader().width() w //= self.table.columnCount() for c in range(0, self.table.columnCount()): self.table.setColumnWidth(c, w) self.save_state() def get_column_name(self, column): return ('name', 'sort', 'count', 'link', 'notes')[column] def item_is_modified(self, item, id_): sub = self.get_column_name(item.column()) if sub == 'notes': return self.notes_utilities.is_note_modified(id_) return item.text() != self.original_authors[id_][sub] def show_context_menu(self, point): self.context_item = self.table.itemAt(point) if self.context_item is None or self.context_item.column() == COUNTS_COLUMN: return case_menu = QMenu(_('Change case')) case_menu.setIcon(QIcon.cached_icon('font_size_larger.png')) action_upper_case = case_menu.addAction(_('Upper case')) action_lower_case = case_menu.addAction(_('Lower case')) action_swap_case = case_menu.addAction(_('Swap case')) action_title_case = case_menu.addAction(_('Title case')) action_capitalize = case_menu.addAction(_('Capitalize')) action_upper_case.triggered.connect(self.upper_case) action_lower_case.triggered.connect(self.lower_case) action_swap_case.triggered.connect(self.swap_case) action_title_case.triggered.connect(self.title_case) action_capitalize.triggered.connect(self.capitalize) m = self.au_context_menu = QMenu(self) idx = self.table.indexAt(point) id_ = int(self.table.item(idx.row(), AUTHOR_COLUMN).data(Qt.ItemDataRole.UserRole)) sub = self.get_column_name(idx.column()) if sub == 'notes': self.notes_utilities.context_menu(m, self.context_item, self.table.item(idx.row(), AUTHOR_COLUMN).text()) else: ca = m.addAction(QIcon.cached_icon('edit-copy.png'), _('Copy')) ca.triggered.connect(self.copy_to_clipboard) ca = m.addAction(QIcon.cached_icon('edit-paste.png'), _('Paste')) ca.triggered.connect(self.paste_from_clipboard) ca = m.addAction(QIcon.cached_icon('edit-undo.png'), _('Undo')) ca.triggered.connect(partial(self.undo_cell, old_value=self.original_authors[id_].get(sub))) ca.setEnabled(self.context_item is not None and self.item_is_modified(self.context_item, id_)) ca = m.addAction(QIcon.cached_icon('edit_input.png'), _('Edit')) ca.triggered.connect(partial(self.table.editItem, self.context_item)) if sub != 'link': m.addSeparator() if self.context_item is not None and sub == 'name': ca = m.addAction(_('Copy to author sort')) ca.triggered.connect(self.copy_au_to_aus) m.addSeparator() ca = m.addAction(QIcon.cached_icon('lt.png'), _("Show books by author in book list")) ca.triggered.connect(self.search_in_book_list) else: ca = m.addAction(_('Copy to author')) ca.triggered.connect(self.copy_aus_to_au) m.addSeparator() m.addMenu(case_menu) m.exec(self.table.viewport().mapToGlobal(point)) def undo_cell(self, old_value): if self.context_item.column() == 3: self.notes_utilities.undo_note_edit(self.context_item) else: self.context_item.setText(old_value) def search_in_book_list(self): from calibre.gui2.ui import get_gui row = self.context_item.row() get_gui().search.set_search_string('authors:="%s"' % str(self.table.item(row, AUTHOR_COLUMN).text()).replace(r'"', r'\"')) def copy_to_clipboard(self): cb = QApplication.clipboard() cb.setText(str(self.context_item.text())) def paste_from_clipboard(self): cb = QApplication.clipboard() self.context_item.setText(cb.text()) def upper_case(self): self.context_item.setText(icu_upper(str(self.context_item.text()))) def lower_case(self): self.context_item.setText(icu_lower(str(self.context_item.text()))) def swap_case(self): self.context_item.setText(str(self.context_item.text()).swapcase()) def title_case(self): from calibre.utils.titlecase import titlecase self.context_item.setText(titlecase(str(self.context_item.text()))) def capitalize(self): from calibre.utils.icu import capitalize self.context_item.setText(capitalize(str(self.context_item.text()))) def copy_aus_to_au(self): row = self.context_item.row() dest = self.table.item(row, AUTHOR_COLUMN) dest.setText(self.context_item.text()) def copy_au_to_aus(self): row = self.context_item.row() dest = self.table.item(row, AUTHOR_SORT_COLUMN) dest.setText(self.context_item.text()) def not_found_label_timer_event(self): self.not_found_label.setVisible(False) def clear_find(self): self.find_box.setText('') self.start_find_pos = -1 self.do_find() def find_text_changed(self): self.start_find_pos = -1 def do_find(self): self.not_found_label.setVisible(False) # For some reason the button box keeps stealing the RETURN shortcut. # Steal it back self.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setDefault(False) self.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setAutoDefault(False) self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setDefault(False) self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setAutoDefault(False) st = icu_lower(str(self.find_box.currentText())) if not st: return for _ in range(0, self.table.rowCount()*2): self.start_find_pos = (self.start_find_pos + 1) % (self.table.rowCount()*2) r = (self.start_find_pos//2) % self.table.rowCount() c = self.start_find_pos % 2 item = self.table.item(r, c) text = icu_lower(str(item.text())) if st in text: self.table.setCurrentItem(item) self.table.setFocus(Qt.FocusReason.OtherFocusReason) return # Nothing found. Pop up the little dialog for 1.5 seconds self.not_found_label.setVisible(True) self.not_found_label_timer.start(1500) def do_sort(self, section): (self.do_sort_by_author, self.do_sort_by_author_sort, self.do_sort_by_link, self.do_sort_by_notes)[section]() def do_sort_by_author(self): self.last_sorted_by = 'author' self.author_order = 1 - self.author_order self.table.sortByColumn(0, Qt.SortOrder(self.author_order)) def do_sort_by_author_sort(self): self.last_sorted_by = 'sort' self.author_sort_order = 1 - self.author_sort_order self.table.sortByColumn(1, Qt.SortOrder(self.author_sort_order)) def do_sort_by_link(self): self.last_sorted_by = 'link' self.link_order = 1 - self.link_order self.table.sortByColumn(2, Qt.SortOrder(self.link_order)) def do_sort_by_notes(self): self.last_sorted_by = 'notes' self.notes_order = 1 - self.notes_order self.table.sortByColumn(3, Qt.SortOrder(self.notes_order)) def accepted(self): self.save_state() self.result = [] for id_, v in self.authors.items(): orig = self.original_authors[id_] if orig != v: self.result.append((id_, orig['name'], v['name'], v['sort'], v['link'])) def rejected(self): self.notes_utilities.restore_all_notes() self.save_state() def do_recalc_author_sort(self): with self.no_cell_changed(): for row in range(0,self.table.rowCount()): item_aut = self.table.item(row, AUTHOR_COLUMN) id_ = int(item_aut.data(Qt.ItemDataRole.UserRole)) aut = str(item_aut.text()).strip() item_aus = self.table.item(row, AUTHOR_SORT_COLUMN) # Sometimes trailing commas are left by changing between copy algs aus = str(author_to_author_sort(aut)).rstrip(',') item_aus.setText(aus) self.authors[id_]['sort'] = aus self.set_icon(item_aus, id_) self.table.setFocus(Qt.FocusReason.OtherFocusReason) def do_auth_sort_to_author(self): with self.no_cell_changed(): for row in range(0,self.table.rowCount()): aus = str(self.table.item(row, AUTHOR_SORT_COLUMN).text()).strip() item_aut = self.table.item(row, AUTHOR_COLUMN) id_ = int(item_aut.data(Qt.ItemDataRole.UserRole)) item_aut.setText(aus) self.authors[id_]['name'] = aus self.set_icon(item_aut, id_) self.table.setFocus(Qt.FocusReason.OtherFocusReason) def set_icon(self, item, id_): if item.column() == NOTES_COLUMN: raise ValueError('got set_icon on notes column') modified = self.item_is_modified(item, id_) item.setIcon(QIcon.cached_icon('modified.png') if modified else QIcon.cached_icon()) def cell_changed(self, row, col): if self.ignore_cell_changed: return with self.no_cell_changed(): id_ = int(self.table.item(row, AUTHOR_COLUMN).data(Qt.ItemDataRole.UserRole)) if col == AUTHOR_COLUMN: item = self.table.item(row, AUTHOR_COLUMN) aut = str(item.text()).strip() aut_list = string_to_authors(aut) if len(aut_list) != 1: error_dialog(self.parent(), _('Invalid author name'), _('You cannot change an author to multiple authors.')).exec() aut = ' % '.join(aut_list) self.table.item(row, AUTHOR_COLUMN).setText(aut) item.set_sort_key() self.authors[id_]['name'] = aut self.set_icon(item, id_) c = self.table.item(row, AUTHOR_SORT_COLUMN) txt = author_to_author_sort(aut) self.authors[id_]['sort'] = txt c.setText(txt) # This triggers another cellChanged event item = c else: item = self.table.item(row, col) name = self.get_column_name(col) if name != 'notes': item.set_sort_key() self.set_icon(item, id_) self.authors[id_][self.get_column_name(col)] = str(item.text()) self.table.setCurrentItem(item) self.table.scrollToItem(item)
27,194
Python
.py
552
38.369565
121
0.618839
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,990
match_books.py
kovidgoyal_calibre/src/calibre/gui2/dialogs/match_books.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal kovid@kovidgoyal.net' __docformat__ = 'restructuredtext en' from qt.core import QAbstractItemView, QApplication, QCursor, QDialog, Qt, QTableWidgetItem, QTimer from calibre.gui2 import error_dialog, gprefs from calibre.gui2.dialogs.match_books_ui import Ui_MatchBooks from calibre.utils.icu import sort_key from calibre.utils.localization import ngettext class TableItem(QTableWidgetItem): ''' A QTableWidgetItem that sorts on a separate string and uses ICU rules ''' def __init__(self, val, sort, idx=0): self.sort = sort self.sort_idx = idx QTableWidgetItem.__init__(self, val) self.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsSelectable) def __ge__(self, other): l = sort_key(self.sort) r = sort_key(other.sort) if l > r: return 1 if l == r: return self.sort_idx >= other.sort_idx return 0 def __lt__(self, other): l = sort_key(self.sort) r = sort_key(other.sort) if l < r: return 1 if l == r: return self.sort_idx < other.sort_idx return 0 class MatchBooks(QDialog, Ui_MatchBooks): def __init__(self, gui, view, id_, row_index): QDialog.__init__(self, gui, flags=Qt.WindowType.Window) Ui_MatchBooks.__init__(self) self.setupUi(self) self.isClosed = False self.books_table_column_widths = None try: self.books_table_column_widths = \ gprefs.get('match_books_dialog_books_table_widths', None) self.restore_geometry(gprefs, 'match_books_dialog_geometry') except: pass self.search_text.initialize('match_books_dialog') # Remove the help button from the window title bar icon = self.windowIcon() self.setWindowFlags(self.windowFlags()&(~Qt.WindowType.WindowContextHelpButtonHint)) self.setWindowIcon(icon) self.device_db = view.model().db self.library_db = gui.library_view.model().db self.view = view self.gui = gui self.current_device_book_id = id_ self.current_device_book_index = row_index self.current_library_book_id = None # Set up the books table columns self.books_table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows) self.books_table.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection) self.books_table.setColumnCount(3) t = QTableWidgetItem(_('Title')) self.books_table.setHorizontalHeaderItem(0, t) t = QTableWidgetItem(_('Authors')) self.books_table.setHorizontalHeaderItem(1, t) t = QTableWidgetItem(ngettext("Series", 'Series', 1)) self.books_table.setHorizontalHeaderItem(2, t) self.books_table_header_height = self.books_table.height() self.books_table.cellDoubleClicked.connect(self.book_doubleclicked) self.books_table.cellClicked.connect(self.book_clicked) self.books_table.sortByColumn(0, Qt.SortOrder.AscendingOrder) # get the standard table row height. Do this here because calling # resizeRowsToContents can word wrap long cell contents, creating # double-high rows self.books_table.setRowCount(1) self.books_table.setItem(0, 0, TableItem('A', '')) self.books_table.resizeRowsToContents() self.books_table_row_height = self.books_table.rowHeight(0) self.books_table.setRowCount(0) self.search_button.clicked.connect(self.do_search) self.search_button.setDefault(False) self.search_text.lineEdit().returnPressed.connect(self.return_pressed) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.ignore_next_key = False search_text = self.device_db[self.current_device_book_id].title search_text = search_text.replace('(', '\\(').replace(')', '\\)') self.search_text.setText(search_text) if search_text and len(self.library_db.new_api.all_book_ids()) < 8000: QTimer.singleShot(0, self.search_button.click) def return_pressed(self): self.ignore_next_key = True self.do_search() def keyPressEvent(self, e): if self.ignore_next_key: self.ignore_next_key = False else: QDialog.keyPressEvent(self, e) def do_search(self): query = str(self.search_text.text()) if not query: d = error_dialog(self.gui, _('Match books'), _('You must enter a search expression into the search field')) d.exec() return try: self.search_button.setEnabled(False) QApplication.setOverrideCursor(QCursor(Qt.CursorShape.WaitCursor)) books = self.library_db.data.search(query, return_matches=True) self.books_table.setRowCount(len(books)) self.books_table.setSortingEnabled(False) for row, b in enumerate(books): mi = self.library_db.get_metadata(b, index_is_id=True, get_user_categories=False) a = TableItem(mi.title, mi.title_sort) a.setData(Qt.ItemDataRole.UserRole, b) self.books_table.setItem(row, 0, a) a = TableItem(' & '.join(mi.authors), mi.author_sort) self.books_table.setItem(row, 1, a) series = mi.format_field('series')[1] if series is None: series = '' a = TableItem(series, mi.series, mi.series_index) self.books_table.setItem(row, 2, a) self.books_table.setRowHeight(row, self.books_table_row_height) self.books_table.setSortingEnabled(True) finally: self.search_button.setEnabled(True) QApplication.restoreOverrideCursor() # Deal with sizing the table columns. Done here because the numbers are not # correct until the first paint. def resizeEvent(self, *args): QDialog.resizeEvent(self, *args) if self.books_table_column_widths is not None: for c,w in enumerate(self.books_table_column_widths): self.books_table.setColumnWidth(c, w) else: # the vertical scroll bar might not be rendered, so might not yet # have a width. Assume 25. Not a problem because user-changed column # widths will be remembered w = self.books_table.width() - 25 - self.books_table.verticalHeader().width() w /= self.books_table.columnCount() for c in range(0, self.books_table.columnCount()): self.books_table.setColumnWidth(c, w) self.save_state() def book_clicked(self, row, column): self.book_selected = True id_ = int(self.books_table.item(row, 0).data(Qt.ItemDataRole.UserRole)) self.current_library_book_id = id_ def book_doubleclicked(self, row, column): self.book_clicked(row, column) self.accept() def save_state(self): self.books_table_column_widths = [] for c in range(0, self.books_table.columnCount()): self.books_table_column_widths.append(self.books_table.columnWidth(c)) gprefs['match_books_dialog_books_table_widths'] = self.books_table_column_widths self.save_geometry(gprefs, 'match_books_dialog_geometry') self.search_text.save_history() def close(self): self.save_state() # clean up to prevent memory leaks self.device_db = self.view = self.gui = None def accept(self): if not self.current_library_book_id: d = error_dialog(self.gui, _('Match books'), _('You must select a matching book')) d.exec() return mi = self.library_db.get_metadata(self.current_library_book_id, index_is_id=True, get_user_categories=False, get_cover=True) book = self.device_db[self.current_device_book_id] book.smart_update(mi, replace_metadata=True) self.gui.update_thumbnail(book) book.in_library_waiting = True self.view.model().current_changed(self.current_device_book_index, self.current_device_book_index) self.save_state() QDialog.accept(self) def reject(self): self.close() QDialog.reject(self)
8,659
Python
.py
184
36.766304
99
0.630257
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,991
password.py
kovidgoyal_calibre/src/calibre/gui2/dialogs/password.py
__license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' import re from qt.core import QDialog, QLineEdit, Qt from calibre.gui2 import dynamic from calibre.gui2.dialogs.password_ui import Ui_Dialog class PasswordDialog(QDialog, Ui_Dialog): def __init__(self, window, name, msg): QDialog.__init__(self, window) Ui_Dialog.__init__(self) self.setupUi(self) self.cfg_key = re.sub(r'[^0-9a-zA-Z]', '_', name) un = dynamic[self.cfg_key+'__un'] pw = dynamic[self.cfg_key+'__pw'] if not un: un = '' if not pw: pw = '' self.gui_username.setText(un) self.gui_password.setText(pw) self.sname = name self.msg.setText(msg) self.show_password.stateChanged.connect(self.toggle_password) def toggle_password(self, state): if Qt.CheckState(state) == Qt.CheckState.Unchecked: self.gui_password.setEchoMode(QLineEdit.EchoMode.Password) else: self.gui_password.setEchoMode(QLineEdit.EchoMode.Normal) def username(self): return str(self.gui_username.text()) def password(self): return str(self.gui_password.text()) def accept(self): dynamic.set(self.cfg_key+'__un', str(self.gui_username.text())) dynamic.set(self.cfg_key+'__pw', str(self.gui_password.text())) QDialog.accept(self)
1,430
Python
.py
36
32.083333
71
0.630513
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,992
comments_dialog.py
kovidgoyal_calibre/src/calibre/gui2/dialogs/comments_dialog.py
#!/usr/bin/env python __copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net' __docformat__ = 'restructuredtext en' __license__ = 'GPL v3' from qt.core import QDialog, QDialogButtonBox, QHBoxLayout, QLabel, QPlainTextEdit, QSize, Qt, QVBoxLayout, pyqtSignal from calibre.gui2 import Application, gprefs from calibre.gui2.comments_editor import Editor from calibre.gui2.widgets2 import Dialog from calibre.library.comments import comments_to_html class CommentsDialog(QDialog): def __init__(self, parent, text, column_name=None): QDialog.__init__(self, parent) self.setObjectName("CommentsDialog") self.setWindowTitle(_("Edit comments")) self.verticalLayout = l = QVBoxLayout(self) self.textbox = tb = Editor(self) self.buttonBox = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel, self) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) l.addWidget(tb) l.addWidget(bb) # Remove help icon on title bar icon = self.windowIcon() self.setWindowFlags(self.windowFlags()&(~Qt.WindowType.WindowContextHelpButtonHint)) self.setWindowIcon(icon) self.textbox.html = comments_to_html(text) if text else '' self.textbox.wyswyg_dirtied() # self.textbox.setTabChangesFocus(True) if column_name: self.setWindowTitle(_('Edit "{0}"').format(column_name)) self.restore_geometry(gprefs, 'comments_dialog_geom') def sizeHint(self): return QSize(650, 600) def accept(self): self.save_geometry(gprefs, 'comments_dialog_geom') QDialog.accept(self) def reject(self): self.save_geometry(gprefs, 'comments_dialog_geom') QDialog.reject(self) def closeEvent(self, ev): self.save_geometry(gprefs, 'comments_dialog_geom') return QDialog.closeEvent(self, ev) class PlainTextEdit(QPlainTextEdit): ctrl_enter_pushed = pyqtSignal() def keyPressEvent(self, event): if event.modifiers() & Qt.KeyboardModifier.ControlModifier and event.key() == Qt.Key.Key_Return: event.accept() self.ctrl_enter_pushed.emit() else: super().keyPressEvent(event) class PlainTextDialog(Dialog): def __init__(self, parent, text, column_name=None): title = _('Edit "{0}"').format(column_name) if column_name else _('Edit text') Dialog.__init__(self, title, 'edit-plain-text-dialog', parent=parent) self.text = text def setup_ui(self): self.l = l = QVBoxLayout(self) self._text = PlainTextEdit(self) self._text.ctrl_enter_pushed.connect(self.ctrl_enter_pushed) l.addWidget(self._text) hl = QHBoxLayout() hl.addWidget(QLabel(_('Press Ctrl+Enter to accept or Esc to cancel'))) hl.addWidget(self.bb) l.addLayout(hl) def ctrl_enter_pushed(self): self.accept() @property def text(self): return self._text.toPlainText() @text.setter def text(self, val): self._text.setPlainText(val or '') def sizeHint(self): return QSize(600, 400) if __name__ == '__main__': app = Application([]) d = CommentsDialog(None, 'testing', 'Comments') d.exec() del d del app
3,352
Python
.py
80
34.675
129
0.666667
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,993
show_category_note.py
kovidgoyal_calibre/src/calibre/gui2/dialogs/show_category_note.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2023, Kovid Goyal <kovid at kovidgoyal.net> import os from qt.core import QApplication, QByteArray, QDialog, QDialogButtonBox, QIcon, QLabel, QMimeData, QSize, Qt, QTextDocument, QUrl, QVBoxLayout from calibre import prepare_string_for_xml from calibre.db.constants import RESOURCE_URL_SCHEME from calibre.ebooks.metadata.book.render import render_author_link from calibre.gui2 import Application, default_author_link, safe_open_url from calibre.gui2.book_details import resolved_css from calibre.gui2.dialogs.edit_category_notes import EditNoteDialog from calibre.gui2.ui import get_gui from calibre.gui2.widgets2 import Dialog, HTMLDisplay class Display(HTMLDisplay): notes_resource_scheme = RESOURCE_URL_SCHEME def __init__(self, parent=None): super().__init__(parent) self.document().setDefaultStyleSheet(resolved_css() + '\n\nli { margin-top: 0.5ex; margin-bottom: 0.5ex; }') self.setFocusPolicy(Qt.FocusPolicy.NoFocus) self.anchor_clicked.connect(self.handle_link_click) def handle_link_click(self, qurl): safe_open_url(qurl) def loadResource(self, rtype, qurl): if qurl.scheme() == RESOURCE_URL_SCHEME and int(rtype) == int(QTextDocument.ResourceType.ImageResource): db = self.parent().db resource = db.get_notes_resource(f'{qurl.host()}:{qurl.path()[1:]}') if resource is not None: return QByteArray(resource['data']) return return super().loadResource(rtype, qurl) class ShowNoteDialog(Dialog): def __init__(self, field, item_id, db, parent=None): self.db = db.new_api self.item_val = self.db.get_item_name(field, item_id) self.has_links = self.db.has_link_map(field) self.item_link = (self.db.link_for(field, item_id) or '') if self.has_links else '' self.extra_link = self.extra_link_tooltip = '' if field == 'authors': lk = default_author_link() if lk != 'calibre': self.extra_link, self.extra_link_tooltip = render_author_link(lk, self.item_val) self.field, self.item_id = field, item_id super().__init__(self.item_val, 'show-notes-for-category', parent=parent) self.setWindowIcon(QIcon.ic('notes.png')) self.refresh() def refresh(self): self.display.setHtml(self.db.notes_for(self.field, self.item_id)) def setup_ui(self): self.l = l = QVBoxLayout(self) x = prepare_string_for_xml src = x(self.item_val) l1 = l2 = l1tt = l2tt = '' if self.extra_link and self.item_link: l1 = self.extra_link l1tt = self.extra_link_tooltip l2 = self.item_link else: if self.item_link: l1 = self.item_link else: l2, l2tt = self.extra_link, self.extra_link_tooltip if l1: src = f'<a href="{x(l1, True)}" style="text-decoration: none" title="{x(l1tt, True)}">{src}</a>' if l2: link_markup = '<img valign="bottom" src="calibre-icon:///external-link.png" width=24 height=24>' src += f' <a style="text-decoration: none" href="{x(l2, True)}" title="{x(l2tt, True)}">{link_markup}</a>' self.title = t = QLabel(f'<h2>{src}</h2>') t.setResourceProvider(lambda qurl: QIcon.icon_as_png(qurl.path().lstrip('/'), as_bytearray=True)) t.setOpenExternalLinks(False) t.linkActivated.connect(self.open_item_link) l.addWidget(t) self.display = d = Display(self) l.addWidget(d) self.bb.clear() self.bb.addButton(QDialogButtonBox.StandardButton.Close) b = self.bb.addButton(_('&Edit'), QDialogButtonBox.ButtonRole.ActionRole) b.setIcon(QIcon.ic('edit_input.png')) b.clicked.connect(self.edit) b.setToolTip(_('Edit this note')) b = self.bb.addButton(_('Find &books'), QDialogButtonBox.ButtonRole.ActionRole) b.setIcon(QIcon.ic('search.png')) b.clicked.connect(self.find_books) if self.field == 'authors': b.setToolTip(_('Search the calibre library for books by: {}').format(self.item_val)) else: b.setToolTip(_('Search the calibre library for books with: {}').format(self.item_val)) b = self.bb.addButton(_('Copy &URL'), QDialogButtonBox.ButtonRole.ActionRole) b.setIcon(QIcon.ic('insert-link.png')) b.clicked.connect(self.copy_url) b.setToolTip(_('Copy a calibre:// URL to the clipboard that can be used to link to this note from other programs')) l.addWidget(self.bb) def sizeHint(self): return QSize(800, 620) def open_item_link(self, url): safe_open_url(url) def copy_url(self): f = self.field if f.startswith('#'): f = '_' + f[1:] url = f'calibre://show-note/{self.db.server_library_id}/{f}/id_{self.item_id}' cb = QApplication.instance().clipboard() md = QMimeData() md.setText(url) md.setUrls([QUrl(url)]) cb.setMimeData(md) def edit(self): d = EditNoteDialog(self.field, self.item_id, self.db, self) if d.exec() == QDialog.DialogCode.Accepted: # Tell the rest of calibre that the note has changed gui = get_gui() if gui is not None: gui.do_field_item_value_changed() self.refresh() self.setFocus(Qt.FocusReason.OtherFocusReason) def find_books(self): q = self.item_val.replace('"', r'\"') search_string = f'{self.field}:"={q}"' gui = get_gui() if gui is not None: gui.apply_virtual_library() gui.search.set_search_string(search_string) def develop_show_note(): from calibre.library import db as dbc app = Application([]) d = ShowNoteDialog('authors', 1, dbc(os.path.expanduser('~/test library'))) d.exec() del d, app if __name__ == '__main__': develop_show_note()
6,077
Python
.py
128
38.804688
142
0.627891
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,994
confirm_merge.py
kovidgoyal_calibre/src/calibre/gui2/dialogs/confirm_merge.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>' from typing import NamedTuple from qt.core import QCheckBox, QDialog, QDialogButtonBox, QLabel, QSplitter, Qt, QTextBrowser, QVBoxLayout, QWidget from calibre.ebooks.metadata import authors_to_string from calibre.ebooks.metadata.book.base import field_metadata from calibre.gui2 import dynamic, gprefs from calibre.gui2.dialogs.confirm_delete import confirm_config_name from calibre.gui2.widgets2 import Dialog, FlowLayout from calibre.startup import connect_lambda from calibre.utils.config import tweaks from calibre.utils.date import format_date class Target(QTextBrowser): def __init__(self, mi, parent=None): QTextBrowser.__init__(self, parent) series = '' fm = field_metadata if mi.series: series = _('{num} of {series}').format(num=mi.format_series_index(), series='<i>%s</i>' % mi.series) self.setHtml(''' <h3 style="text-align:center">{mb}</h3> <p><b>{title}</b> - <i>{authors}</i><br></p> <table> <tr><td>{fm[timestamp][name]}:</td><td>{date}</td></tr> <tr><td>{fm[pubdate][name]}:</td><td>{published}</td></tr> <tr><td>{fm[formats][name]}:</td><td>{formats}</td></tr> <tr><td>{fm[series][name]}:</td><td>{series}</td></tr> <tr><td>{has_cover_title}:</td><td>{has_cover}</td></tr> </table> '''.format( mb=_('Target book'), title=mi.title, has_cover_title=_('Has cover'), has_cover=_('Yes') if mi.has_cover else _('No'), authors=authors_to_string(mi.authors), date=format_date(mi.timestamp, tweaks['gui_timestamp_display_format']), fm=fm, published=(format_date(mi.pubdate, tweaks['gui_pubdate_display_format']) if mi.pubdate else ''), formats=', '.join(mi.formats or ()), series=series )) class ConfirmMerge(Dialog): def __init__(self, msg, name, parent, mi, ask_about_save_alternate_cover=False): self.msg, self.mi, self.conf_name = msg, mi, name self.ask_about_save_alternate_cover = ask_about_save_alternate_cover Dialog.__init__(self, _('Are you sure?'), 'confirm-merge-dialog', parent) needed, sz = self.sizeHint(), self.size() if needed.width() > sz.width() or needed.height() > sz.height(): self.resize(needed) def setup_ui(self): self.l = l = QVBoxLayout(self) self.splitter = s = QSplitter(self) s.setChildrenCollapsible(False) l.addWidget(s), l.addWidget(self.bb) self.bb.setStandardButtons(QDialogButtonBox.StandardButton.Yes | QDialogButtonBox.StandardButton.No) self.left = w = QWidget(self) s.addWidget(w) w.l = l = QVBoxLayout(w) l.setContentsMargins(0, 0, 0, 0) self.la = la = QLabel(self.msg) la.setWordWrap(True) l.addWidget(la) self.save_alternate_cover_cb = c = QCheckBox(_('Save replaced or discarded &cover'), self) c.setToolTip(_('Save the replaced or discarded cover in the data files associated with the target book as an alternate cover')) c.setObjectName('choose-merge-cb-save_alternate_cover') c.setChecked(bool(gprefs.get(c.objectName(), False))) l.addWidget(c) c.setVisible(self.ask_about_save_alternate_cover) c.toggled.connect(self.alternate_covers_toggled) self.confirm = c = QCheckBox(_('Show this confirmation again'), self) c.setChecked(True) c.stateChanged.connect(self.toggle) l.addWidget(c) self.right = r = Target(self.mi, self) s.addWidget(r) def alternate_covers_toggled(self): gprefs.set(self.save_alternate_cover_cb.objectName(), self.save_alternate_cover_cb.isChecked()) def toggle(self): dynamic[confirm_config_name(self.conf_name)] = self.confirm.isChecked() def sizeHint(self): ans = Dialog.sizeHint(self) ans.setWidth(max(700, ans.width())) return ans def confirm_merge(msg, name, parent, mi, ask_about_save_alternate_cover=False): if not dynamic.get(confirm_config_name(name), True): return True, bool(gprefs.get('choose-merge-cb-save_alternate_cover', False)) d = ConfirmMerge(msg, name, parent, mi, ask_about_save_alternate_cover) return d.exec() == QDialog.DialogCode.Accepted, d.save_alternate_cover_cb.isChecked() class ChooseMerge(Dialog): def __init__(self, dest_id, src_ids, gui): self.dest_id, self.src_ids = dest_id, src_ids self.mi = gui.current_db.new_api.get_metadata(dest_id) Dialog.__init__(self, _('Merge books'), 'choose-merge-dialog', parent=gui) def setup_ui(self): self.l = l = QVBoxLayout(self) self.splitter = s = QSplitter(self) s.setChildrenCollapsible(False) l.addWidget(s), l.addWidget(self.bb) self.bb.setStandardButtons(QDialogButtonBox.StandardButton.Yes | QDialogButtonBox.StandardButton.No) self.left = w = QWidget(self) s.addWidget(w) w.l = l = QVBoxLayout(w) l.setContentsMargins(0, 0, 0, 0) w.fl = fl = FlowLayout() l.addLayout(fl) def cb(name, text, tt='', defval=True): ans = QCheckBox(text) fl.addWidget(ans) prefs_key = ans.prefs_key = 'choose-merge-cb-' + name ans.setChecked(gprefs.get(prefs_key, defval)) connect_lambda(ans.stateChanged, self, lambda self, state: self.state_changed(getattr(self, name), state), type=Qt.ConnectionType.QueuedConnection) if tt: ans.setToolTip(tt) setattr(self, name, ans) return ans cb('merge_metadata', _('Merge metadata'), _( 'Merge the metadata of the selected books into the target book')) cb('merge_formats', _('Merge formats'), _( 'Merge the book files of the selected books into the target book')) cb('delete_books', _('Delete merged books'), _( 'Delete the selected books after merging')) cb('replace_cover', _('Replace existing cover'), _( 'Replace the cover in the target book with the dragged cover')) cb('save_alternate_cover', _('Save alternate cover'), _( 'Save the replaced or discarded cover in the data files associated with the target book as an alternate cover'), defval=False) l.addStretch(10) self.msg = la = QLabel(self) la.setWordWrap(True) l.addWidget(la) self.update_msg() self.right = r = Target(self.mi, self) s.addWidget(r) def state_changed(self, cb, state): mm = self.merge_metadata.isChecked() mf = self.merge_formats.isChecked() if not mm and not mf: (self.merge_metadata if cb is self.merge_formats else self.merge_formats).setChecked(True) gprefs[cb.prefs_key] = cb.isChecked() self.update_msg() def update_msg(self): mm = self.merge_metadata.isChecked() mf = self.merge_formats.isChecked() rm = self.delete_books.isChecked() rc = self.replace_cover.isChecked() msg = '<p>' if mm and mf: msg += _( 'Book formats and metadata from the selected books' ' will be merged into the target book ({title}).') if rc or not self.mi.has_cover: msg += ' ' + _('The dragged cover will be used.') elif mf: msg += _('Book formats from the selected books ' 'will be merged into to the target book ({title}).' ' Metadata and cover in the target book will not be changed.') elif mm: msg += _('Metadata from the selected books ' 'will be merged into to the target book ({title}).' ' Formats will not be merged.') if rc or not self.mi.has_cover: msg += ' ' + _('The dragged cover will be used.') msg += '<br>' msg += _('All book formats of the target book will be kept.') + '<br><br>' if rm: msg += _('After being merged, the selected books will be <b>deleted</b>.') if mf: msg += '<br><br>' + _( 'Any duplicate formats in the selected books ' 'will be permanently <b>deleted</b> from your calibre library.') else: if mf: msg += _( 'Any formats not in the target book will be added to it from the selected books.') if not msg.endswith('<br>'): msg += '<br><br>' msg += _('Are you <b>sure</b> you want to proceed?') + '</p>' msg = msg.format(title=self.mi.title) self.msg.setText(msg) @property def merge_type(self): return MergeData( self.merge_metadata.isChecked(), self.merge_formats.isChecked(), self.delete_books.isChecked(), self.replace_cover.isChecked(), self.save_alternate_cover.isChecked(), ) class MergeData(NamedTuple): merge_metadata: bool = False merge_formats: bool = False delete_books: bool = False replace_cover: bool = False save_alternate_cover: bool = False def merge_drop(dest_id, src_ids, gui): d = ChooseMerge(dest_id, src_ids, gui) if d.exec() != QDialog.DialogCode.Accepted: return None return d.merge_type
9,397
Python
.py
194
39.654639
159
0.621551
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,995
choose_library.py
kovidgoyal_calibre/src/calibre/gui2/dialogs/choose_library.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import errno import os from threading import Event, Thread from qt.core import QDialog, Qt, QTimer, pyqtSignal from calibre import force_unicode, isbytestring, patheq from calibre.constants import filesystem_encoding, get_portable_base, iswindows from calibre.gui2 import choose_dir, error_dialog from calibre.gui2.dialogs.choose_library_ui import Ui_Dialog from calibre.gui2.dialogs.progress import ProgressDialog as PD from calibre.utils.localization import localize_user_manual_link class ProgressDialog(PD): on_progress_update = pyqtSignal(object, object, object) finished_moving = pyqtSignal() def __init__(self, *args, **kwargs): PD.__init__(self, *args, **kwargs) self.on_progress_update.connect(self.progressed, type=Qt.ConnectionType.QueuedConnection) self.finished_moving.connect(self.accept, type=Qt.ConnectionType.QueuedConnection) def reject(self): return def progressed(self, item_name, count, total): self.max = total self.value = count self.set_msg(item_name) def show_new_progress(self, *args): self.on_progress_update.emit(*args) class ChooseLibrary(QDialog, Ui_Dialog): def __init__(self, db, callback, parent): super().__init__(parent) self.setupUi(self) self.nas_warning.setText(self.nas_warning.text().format(localize_user_manual_link( 'https://manual.calibre-ebook.com/faq.html#i-am-getting-errors-with-my-calibre-library-on-a-networked-drive-nas'))) self.nas_warning.setOpenExternalLinks(True) self.db = db self.new_db = None self.callback = callback self.location.initialize('choose_library_dialog') lp = db.library_path if isbytestring(lp): lp = lp.decode(filesystem_encoding) loc = str(self.old_location.text()).format(lp) self.old_location.setText(loc) self.browse_button.clicked.connect(self.choose_loc) self.empty_library.toggled.connect(self.empty_library_toggled) self.copy_structure.setEnabled(False) def empty_library_toggled(self, to_what): self.copy_structure.setEnabled(to_what) def choose_loc(self, *args): base = get_portable_base() if base is None: loc = choose_dir(self, 'choose library location', _('Choose location for calibre library')) else: name = force_unicode('choose library loc at' + base, filesystem_encoding) loc = choose_dir(self, name, _('Choose location for calibre library'), default_dir=base, no_save_dir=True) if loc is not None: self.location.setText(loc) def check_action(self, ac, loc): exists = self.db.exists_at(loc) base = get_portable_base() if patheq(loc, self.db.library_path): error_dialog(self, _('Same as current'), _('The location %s contains the current calibre' ' library')%loc, show=True) return False if base is not None and ac in ('new', 'move'): abase = os.path.normcase(os.path.abspath(base)) cal = os.path.normcase(os.path.abspath(os.path.join(abase, 'Calibre'))) aloc = os.path.normcase(os.path.abspath(loc)) if (aloc.startswith(cal+os.sep) or aloc == cal): error_dialog(self, _('Bad location'), _('You should not create a library inside the calibre' ' folder as this folder is automatically deleted during upgrades.'), show=True) return False if aloc.startswith(abase) and os.path.dirname(aloc) != abase: error_dialog(self, _('Bad location'), _('You can only create libraries inside %s at the top ' 'level, not in sub-folders')%base, show=True) return False empty = not os.listdir(loc) if ac == 'existing' and not exists: error_dialog(self, _('No existing library found'), _('There is no existing calibre library at %s')%loc, show=True) return False if ac in ('new', 'move'): from calibre.db.legacy import LibraryDatabase if not empty: error_dialog(self, _('Not empty'), _('The folder %s is not empty. Please choose an empty' ' folder.')%loc, show=True) return False if (iswindows and len(loc) > LibraryDatabase.WINDOWS_LIBRARY_PATH_LIMIT): error_dialog(self, _('Too long'), _('Path to library too long. It must be less than' ' %d characters.')%LibraryDatabase.WINDOWS_LIBRARY_PATH_LIMIT, show=True) return False return True def perform_action(self, ac, loc): if ac in ('new', 'existing'): self.callback(loc, copy_structure=self.copy_structure.isChecked()) else: # move library self.db.prefs.disable_setting = True abort_move = Event() pd = ProgressDialog(_('Moving library, please wait...'), _('Scanning...'), max=0, min=0, icon='lt.png', parent=self) pd.canceled_signal.connect(abort_move.set) self.parent().library_view.model().stop_metadata_backup() move_error = [] def do_move(): try: self.db.new_api.move_library_to(loc, abort=abort_move, progress=pd.show_new_progress) except Exception: import traceback move_error.append(traceback.format_exc()) finally: pd.finished_moving.emit() t = Thread(name='MoveLibrary', target=do_move) QTimer.singleShot(0, t.start) pd.exec() if abort_move.is_set(): self.callback(self.db.library_path) return if move_error: error_dialog(self.parent(), _('Failed to move library'), _( 'There was an error while moving the library. The operation has been aborted. Click' ' "Show details" for details.'), det_msg=move_error[0], show=True) self.callback(self.db.library_path) return self.callback(loc, library_renamed=True) def accept(self): action = 'move' if self.existing_library.isChecked(): action = 'existing' elif self.empty_library.isChecked(): action = 'new' text = str(self.location.text()).strip() if not text: return error_dialog(self, _('No location'), _('No location selected'), show=True) loc = os.path.abspath(text) if action == 'move': try: os.makedirs(loc) except OSError as e: if e.errno != errno.EEXIST: raise if not loc or not os.path.exists(loc) or not os.path.isdir(loc): if action == 'new' and not os.path.exists(loc): os.makedirs(loc) else: return error_dialog(self, _('Bad location'), _('%s is not an existing folder')%loc, show=True) if not self.check_action(action, loc): return self.location.save_history() self.perform_action(action, loc) QDialog.accept(self) # Must be after perform action otherwise the progress dialog is not updated on windows
7,933
Python
.py
169
34.692308
128
0.581804
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,996
choose_format_device.py
kovidgoyal_calibre/src/calibre/gui2/dialogs/choose_format_device.py
__license__ = 'GPL v3' __copyright__ = '2011, John Schember <john@nachtimwald.com>' from qt.core import QDialog, QIcon, QModelIndex, QTreeWidgetItem from calibre.gui2 import file_icon_provider from calibre.gui2.dialogs.choose_format_device_ui import Ui_ChooseFormatDeviceDialog class ChooseFormatDeviceDialog(QDialog, Ui_ChooseFormatDeviceDialog): def __init__(self, window, msg, formats): ''' formats is a list of tuples: [(format, exists, convertible)]. format: Lower case format identifier. E.G. mobi exists: String representing the number of books that exist in the format. convertible: True if the format is a convertible format. formats should be ordered in the device's preferred format ordering. ''' QDialog.__init__(self, window) Ui_ChooseFormatDeviceDialog.__init__(self) self.setupUi(self) self.formats.activated[QModelIndex].connect(self.activated_slot) self.msg.setText(msg) for i, (format, exists, convertible) in enumerate(formats): t_item = QTreeWidgetItem() t_item.setIcon(0, file_icon_provider().icon_from_ext(format.lower())) t_item.setText(0, format.upper()) t_item.setText(1, exists) if convertible: t_item.setIcon(2, QIcon.ic('ok.png')) self.formats.addTopLevelItem(t_item) if i == 0: self.formats.setCurrentItem(t_item) t_item.setSelected(True) self.formats.resizeColumnToContents(2) self.formats.resizeColumnToContents(1) self.formats.resizeColumnToContents(0) self.formats.header().resizeSection(0, self.formats.header().sectionSize(0) * 2) self._format = None def activated_slot(self, *args): self.accept() def format(self): return self._format def accept(self): self._format = str(self.formats.currentItem().text(0)) return QDialog.accept(self)
2,039
Python
.py
43
37.930233
88
0.651233
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,997
smartdevice.py
kovidgoyal_calibre/src/calibre/gui2/dialogs/smartdevice.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' from qt.core import QDialog, QLineEdit, Qt from calibre.gui2 import error_dialog from calibre.gui2.dialogs.smartdevice_ui import Ui_Dialog from calibre.utils.mdns import get_all_ips from polyglot.builtins import itervalues def ipaddr_sort_key(ipaddr): if '.' in ipaddr: parts = tuple(map(int, ipaddr.split('.'))) is_private = parts[0] in (192, 170, 10) return (0 if is_private else 1), parts def get_all_ip_addresses(): ipaddrs = list() for iface in itervalues(get_all_ips()): for addrs in iface: if 'broadcast' in addrs and addrs['addr'] != '127.0.0.1': ipaddrs.append(addrs['addr']) ipaddrs.sort(key=ipaddr_sort_key) return ipaddrs class SmartdeviceDialog(QDialog, Ui_Dialog): def __init__(self, parent): QDialog.__init__(self, parent) Ui_Dialog.__init__(self) self.setupUi(self) self.password_box.setToolTip('<p>' + _('Use a password if calibre is running on a network that ' 'is not secure. For example, if you run calibre on a laptop, ' 'use that laptop in an airport, and want to connect your ' 'smart device to calibre, you should use a password.') + '</p>') self.autostart_box.setToolTip('<p>' + _('Check this box if you want calibre to automatically start the ' 'smart device interface when calibre starts. You should not do ' 'this if you are using a network that is not secure and you ' 'are not setting a password.') + '</p>') self.use_fixed_port.setToolTip('<p>' + _('Check this box if you want calibre to use a fixed network ' 'port. Normally you will not need to do this. However, if ' 'your device consistently fails to connect to calibre, ' 'try checking this box and entering a number.') + '</p>') self.fixed_port.setToolTip('<p>' + _('Try 9090. If calibre says that it fails to connect ' 'to the port, try another number. You can use any number between ' '8,000 and 65,535.') + '</p>') self.ip_addresses.setToolTip('<p>' + _('These are the IP addresses for this computer. If you decide to have your device connect to ' 'calibre using a fixed IP address, one of these addresses should ' 'be the one you use. It is unlikely but possible that the correct ' 'IP address is not listed here, in which case you will need to go ' "to your computer's control panel to get a complete list of " "your computer's network interfaces and IP addresses.") + '</p>') self.show_password.stateChanged[int].connect(self.toggle_password) self.use_fixed_port.stateChanged[int].connect(self.use_fixed_port_changed) self.device_manager = parent.device_manager if self.device_manager.get_option('smartdevice', 'autostart'): self.autostart_box.setChecked(True) pw = self.device_manager.get_option('smartdevice', 'password') if pw: self.password_box.setText(pw) self.orig_fixed_port = self.device_manager.get_option('smartdevice', 'use_fixed_port') self.orig_port_number = self.device_manager.get_option('smartdevice', 'port_number') self.fixed_port.setText(self.orig_port_number) self.use_fixed_port.setChecked(self.orig_fixed_port) if not self.orig_fixed_port: self.fixed_port.setEnabled(False) if pw: self.password_box.setText(pw) forced_ip = self.device_manager.get_option('smartdevice', 'force_ip_address') if forced_ip: self.ip_addresses.setText(forced_ip) else: self.ip_addresses.setText(', '.join(get_all_ip_addresses())) self.resize(self.sizeHint()) def use_fixed_port_changed(self, state): self.fixed_port.setEnabled(Qt.CheckState(state) == Qt.CheckState.Checked) def toggle_password(self, state): self.password_box.setEchoMode(QLineEdit.EchoMode.Password if state == Qt.CheckState.Unchecked else QLineEdit.EchoMode.Normal) def accept(self): port = str(self.fixed_port.text()) if not port: error_dialog(self, _('Invalid port number'), _('You must provide a port number.'), show=True) return try: port = int(port) except: error_dialog(self, _('Invalid port number'), _('The port must be a number between 8000 and 65535.'), show=True) return if port < 8000 or port > 65535: error_dialog(self, _('Invalid port number'), _('The port must be a number between 8000 and 65535.'), show=True) return self.device_manager.set_option('smartdevice', 'password', str(self.password_box.text())) self.device_manager.set_option('smartdevice', 'autostart', self.autostart_box.isChecked()) self.device_manager.set_option('smartdevice', 'use_fixed_port', self.use_fixed_port.isChecked()) self.device_manager.set_option('smartdevice', 'port_number', str(self.fixed_port.text())) message = self.device_manager.start_plugin('smartdevice') if not self.device_manager.is_running('smartdevice'): error_dialog(self, _('Problem starting the wireless device'), _('The wireless device driver had problems starting. It said "%s"')%message, show=True) self.device_manager.set_option('smartdevice', 'use_fixed_port', self.orig_fixed_port) self.device_manager.set_option('smartdevice', 'port_number', self.orig_port_number) else: QDialog.accept(self)
6,304
Python
.py
116
41.482759
107
0.594186
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,998
multisort.py
kovidgoyal_calibre/src/calibre/gui2/dialogs/multisort.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> from qt.core import QAbstractItemView, QDialogButtonBox, QInputDialog, QLabel, QListWidget, QListWidgetItem, QMenu, QSize, Qt, QVBoxLayout from calibre import prepare_string_for_xml from calibre.gui2 import error_dialog from calibre.gui2.actions.sort import SORT_HIDDEN_PREF from calibre.gui2.widgets2 import Dialog from calibre.utils.icu import primary_sort_key ascending_symbol = '⏷' descending_symbol = '⏶' class ChooseMultiSort(Dialog): def __init__(self, db, is_device_connected=False, parent=None, hidden_pref=SORT_HIDDEN_PREF): self.db = db.new_api self.hidden_fields = set(self.db.pref(SORT_HIDDEN_PREF, default=()) or ()) if not is_device_connected: self.hidden_fields.add('ondevice') fm = self.db.field_metadata self.key_map = fm.ui_sortable_field_keys().copy() self.name_map = {v:k for k, v in self.key_map.items()} self.all_names = sorted(self.name_map, key=primary_sort_key) self.sort_order_map = dict.fromkeys(self.key_map, True) super().__init__(_('Sort by multiple columns'), 'multisort-chooser', parent=parent) def sizeHint(self): return QSize(600, 400) def setup_ui(self): self.vl = vl = QVBoxLayout(self) self.la = la = QLabel(_( 'Pick multiple columns to sort by. Drag and drop to re-arrange. Higher columns are more important.' ' Ascending or descending order can be toggled by clicking the column name at the bottom' ' of this dialog, after having selected it.')) la.setWordWrap(True) vl.addWidget(la) self.order_label = la = QLabel('\xa0') la.setTextFormat(Qt.TextFormat.RichText) la.setWordWrap(True) la.linkActivated.connect(self.link_activated) self.column_list = cl = QListWidget(self) vl.addWidget(cl) vl.addWidget(la) vl.addWidget(self.bb) for name in self.all_names: i = QListWidgetItem(cl) i.setText(name) i.setData(Qt.ItemDataRole.UserRole, self.name_map[name]) cl.addItem(i) i.setCheckState(Qt.CheckState.Unchecked) if self.name_map[name] in self.hidden_fields: i.setHidden(True) cl.setDragDropMode(QAbstractItemView.DragDropMode.InternalMove) cl.currentRowChanged.connect(self.current_changed) cl.itemDoubleClicked.connect(self.item_double_clicked) cl.setCurrentRow(0) cl.itemChanged.connect(self.update_order_label) cl.model().rowsMoved.connect(self.update_order_label) self.clear_button = b = self.bb.addButton(_('&Clear'), QDialogButtonBox.ButtonRole.ActionRole) b.setToolTip(_('Clear all selected columns')) b.setAutoDefault(False) b.clicked.connect(self.clear) self.save_button = b = self.bb.addButton(_('&Save'), QDialogButtonBox.ButtonRole.ActionRole) b.setToolTip(_('Save this sort order for easy re-use')) b.clicked.connect(self.save) b.setAutoDefault(False) self.load_button = b = self.bb.addButton(_('&Load'), QDialogButtonBox.ButtonRole.ActionRole) b.setToolTip(_('Load previously saved settings')) b.setAutoDefault(False) self.load_menu = QMenu(b) b.setMenu(self.load_menu) self.load_menu.aboutToShow.connect(self.populate_load_menu) def clear(self): for item in self.iteritems(): item.setCheckState(Qt.CheckState.Unchecked) self.column_list.sortItems() def item_double_clicked(self, item): item.setCheckState(Qt.CheckState.Checked if item.checkState() == Qt.CheckState.Unchecked else Qt.CheckState.Unchecked) def current_changed(self): self.update_order_label() @property def current_sort_spec(self): ans = [] for item in self.iteritems(): if item.checkState() == Qt.CheckState.Checked: k = item.data(Qt.ItemDataRole.UserRole) ans.append((k, self.sort_order_map[k])) return ans def update_order_label(self): t = '' for i, (k, ascending) in enumerate(self.current_sort_spec): name = self.key_map[k] symbol = ascending_symbol if ascending else descending_symbol if i != 0: t += ' :: ' q = bytes.hex(k.encode('utf-8')) dname = prepare_string_for_xml(name).replace(" ", "&nbsp;") t += f' <a href="{q}" style="text-decoration: none">{dname}&nbsp;{symbol}</a>' if t: t = _('Effective sort') + ': ' + t self.order_label.setText(t) def link_activated(self, url): key = bytes.fromhex(url).decode('utf-8') self.sort_order_map[key] ^= True self.update_order_label() def no_column_selected_error(self): return error_dialog(self, _('No sort selected'), _( 'You must select at least one column on which to sort'), show=True) def accept(self): if not self.current_sort_spec: return self.no_column_selected_error() super().accept() @property def saved_specs(self): return self.db.pref('saved_multisort_specs', {}).copy() @saved_specs.setter def saved_specs(self, val): self.db.set_pref('saved_multisort_specs', val.copy()) def save(self): spec = self.current_sort_spec if not spec: return self.no_column_selected_error() d = QInputDialog(self) d.setComboBoxEditable(True) d.setComboBoxItems(sorted(self.saved_specs.keys(), key=primary_sort_key)) d.setWindowTitle(_('Choose name')) d.setLabelText(_('Choose a name for these settings')) if d.exec(): name = d.textValue() if name: q = self.saved_specs q[name] = spec self.saved_specs = q else: error_dialog(self, _('No name provided'), _( 'You must provide a name for the settings'), show=True) def populate_load_menu(self): m = self.load_menu m.clear() specs = self.saved_specs if not specs: m.addAction(_('No saved sorts available')) return for name in sorted(specs, key=primary_sort_key): ac = m.addAction(name, self.load_spec) ac.setObjectName(name) m.addSeparator() m = m.addMenu(_('Remove saved sort')) for name in sorted(specs, key=primary_sort_key): ac = m.addAction(name, self.remove_spec) ac.setObjectName(name) def load_spec(self): name = self.sender().objectName() spec = self.saved_specs[name] self.apply_spec(spec) def remove_spec(self): name = self.sender().objectName() q = self.saved_specs if q.pop(name, None): self.saved_specs = q def iteritems(self): cl = self.column_list return (cl.item(i) for i in range(cl.count())) def apply_spec(self, spec): self.clear() cl = self.column_list imap = {item.data(Qt.ItemDataRole.UserRole): item for item in self.iteritems()} for key, ascending in reversed(spec): item = imap.get(key) if item is not None: item = cl.takeItem(cl.row(item)) cl.insertItem(0, item) self.sort_order_map[key] = ascending item.setCheckState(Qt.CheckState.Checked) if __name__ == '__main__': from calibre.gui2 import Application app = Application([]) from calibre.library import db d = ChooseMultiSort(db()) d.exec() print(d.current_sort_spec) del d del app
7,860
Python
.py
179
34.558659
138
0.620848
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,999
check_library.py
kovidgoyal_calibre/src/calibre/gui2/dialogs/check_library.py
#!/usr/bin/env python __copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net' __docformat__ = 'restructuredtext en' __license__ = 'GPL v3' import os import weakref from threading import Thread from qt.core import ( QApplication, QCheckBox, QCursor, QDialog, QDialogButtonBox, QGridLayout, QHBoxLayout, QIcon, QLabel, QLineEdit, QProgressBar, QPushButton, QSplitter, QStackedLayout, Qt, QTextEdit, QToolButton, QTreeWidget, QTreeWidgetItem, QVBoxLayout, QWidget, pyqtSignal, ) from calibre import as_unicode, prints from calibre.gui2 import open_local_file from calibre.gui2.dialogs.confirm_delete import confirm from calibre.library.check_library import CHECKS, CheckLibrary from calibre.utils.recycle_bin import delete_file, delete_tree class DBCheck(QDialog): # {{{ finished_vacuum = pyqtSignal() def __init__(self, parent, db): QDialog.__init__(self, parent) self.vacuum_started = False self.finished_vacuum.connect(self.accept, type=Qt.ConnectionType.QueuedConnection) self.error = None self.rejected = False s = QStackedLayout(self) s.setContentsMargins(0, 0, 0, 0) one = QWidget(self) s.addWidget(one) two = QWidget(self) s.addWidget(two) l = QVBoxLayout(one) la = QLabel(_('Check database integrity and compact it for improved performance.')) la.setWordWrap(True) l.addWidget(la) self.fts = f = QCheckBox(_('Also compact the Full text search database')) l.addWidget(f) la = QLabel('<p style="margin-left: 20px; font-style: italic">' + _( 'This can be a very slow and memory intensive operation,' ' depending on the size of the Full text database.')) la.setWordWrap(True) l.addWidget(la) self.notes = n = QCheckBox(_('Also compact the notes database')) l.addWidget(n) la = QLabel('<p style="margin-left: 20px; font-style: italic">' + _( 'This can be a very slow and memory intensive operation,' ' depending on the size of the notes database.')) la.setWordWrap(True) l.addWidget(la) l.addStretch(10) self.bb1 = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel, self) l.addWidget(bb) bb.accepted.connect(self.start) bb.rejected.connect(self.reject) self.setWindowTitle(_('Check the database file')) l = QVBoxLayout(two) la = QLabel(_('Vacuuming database to improve performance.') + ' ' + _('This will take a while, please wait...')) la.setWordWrap(True) l.addWidget(la) pb = QProgressBar(self) l.addWidget(pb) pb.setMinimum(0), pb.setMaximum(0) l.addStretch(10) self.resize(self.sizeHint()) self.db = weakref.ref(db.new_api) self.setMinimumWidth(450) def start(self): self.setWindowTitle(_('Vacuuming...')) self.layout().setCurrentIndex(1) QApplication.setOverrideCursor(QCursor(Qt.CursorShape.WaitCursor)) self.vacuum_started = True db = self.db() t = self.thread = Thread(target=self.vacuum, args=(db, self.fts.isChecked(), self.notes.isChecked()), daemon=True, name='VacuumDB') t.start() def vacuum(self, db, include_fts_db, include_notes_db): try: db.vacuum(include_fts_db, include_notes_db) except Exception as e: import traceback self.error = (as_unicode(e), traceback.format_exc()) self.finished_vacuum.emit() def reject(self): self.rejected = True if self.vacuum_started: return return QDialog.reject(self) def closeEvent(self, ev): if self.vacuum_started: ev.ignore() return return super().closeEvent(ev) def break_cycles(self): if self.vacuum_started: QApplication.restoreOverrideCursor() self.thread = None # }}} class TextWithButtonWidget(QWidget): button_icon = None def __init__(self, library_path, text, item_path): QWidget.__init__(self) if self.button_icon is None: self.button_icon = QIcon.ic('document_open.png') self.path = os.path.join(library_path, item_path) if not os.path.isdir(self.path): self.path = os.path.dirname(self.path) l = QHBoxLayout() l.setContentsMargins(0, 0, 0, 0) b = QToolButton() b.setContentsMargins(0, 0, 0, 0) b.clicked.connect(self.button_clicked) b.setIcon(self.button_icon) b.setToolTip(_('Open folder {}').format(self.path)) l.addWidget(b) t = QLabel(text) t.setContentsMargins(0, 0, 0, 0) l.addWidget(t) self.setLayout(l) self.setContentsMargins(0, 0, 0, 0) def button_clicked(self): open_local_file(self.path) class CheckLibraryDialog(QDialog): is_deletable = 1 is_fixable = 2 def __init__(self, parent, db): QDialog.__init__(self, parent) self.db = db self.setWindowTitle(_('Check library -- Problems found')) self.setWindowIcon(QIcon.ic('debug.png')) self._tl = QHBoxLayout() self.setLayout(self._tl) self.splitter = QSplitter(self) self.left = QWidget(self) self.splitter.addWidget(self.left) self.helpw = QTextEdit(self) self.splitter.addWidget(self.helpw) self._tl.addWidget(self.splitter) self._layout = QVBoxLayout() self._layout.setContentsMargins(0, 0, 0, 0) self.left.setLayout(self._layout) self.helpw.setReadOnly(True) self.helpw.setText(_('''\ <h1>Help</h1> <p>calibre stores the list of your books and their metadata in a database. The actual book files and covers are stored as normal files in the calibre library folder. The database contains a list of the files and covers belonging to each book entry. This tool checks that the actual files in the library folder on your computer match the information in the database.</p> <p>The result of each type of check is shown to the left. The various checks are: </p> <ul> <li><b>Invalid titles</b>: These are files and folders appearing in the library where books titles should, but that do not have the correct form to be a book title.</li> <li><b>Extra titles</b>: These are extra files in your calibre library that appear to be correctly-formed titles, but have no corresponding entries in the database.</li> <li><b>Invalid authors</b>: These are files appearing in the library where only author folders should be.</li> <li><b>Extra authors</b>: These are folders in the calibre library that appear to be authors but that do not have entries in the database.</li> <li><b>Missing book formats</b>: These are book formats that are in the database but have no corresponding format file in the book's folder. <li><b>Extra book formats</b>: These are book format files found in the book's folder but not in the database. <li><b>Unknown files in books</b>: These are extra files in the folder of each book that do not correspond to a known format or cover file.</li> <li><b>Missing cover files</b>: These represent books that are marked in the database as having covers but the actual cover files are missing.</li> <li><b>Cover files not in database</b>: These are books that have cover files but are marked as not having covers in the database.</li> <li><b>Folder raising exception</b>: These represent folders in the calibre library that could not be processed/understood by this tool.</li> </ul> <p>There are two kinds of automatic fixes possible: <i>Delete marked</i> and <i>Fix marked</i>.</p> <p><i>Delete marked</i> is used to remove extra files/folders/covers that have no entries in the database. Check the box next to the item you want to delete. Use with caution.</p> <p><i>Fix marked</i> is applicable only to covers and missing formats (the three lines marked 'fixable'). In the case of missing cover files, checking the fixable box and pushing this button will tell calibre that there is no cover for all of the books listed. Use this option if you are not going to restore the covers from a backup. In the case of extra cover files, checking the fixable box and pushing this button will tell calibre that the cover files it found are correct for all the books listed. Use this when you are not going to delete the file(s). In the case of missing formats, checking the fixable box and pushing this button will tell calibre that the formats are really gone. Use this if you are not going to restore the formats from a backup.</p> ''')) self.log = QTreeWidget(self) self.log.itemChanged.connect(self.item_changed) self.log.itemExpanded.connect(self.item_expanded_or_collapsed) self.log.itemCollapsed.connect(self.item_expanded_or_collapsed) self._layout.addWidget(self.log) self.check_button = QPushButton(_('&Run the check again')) self.check_button.setDefault(False) self.check_button.clicked.connect(self.run_the_check) self.copy_button = QPushButton(_('Copy &to clipboard')) self.copy_button.setDefault(False) self.copy_button.clicked.connect(self.copy_to_clipboard) self.ok_button = QPushButton(_('&Done')) self.ok_button.setDefault(True) self.ok_button.clicked.connect(self.accept) self.mark_delete_button = QPushButton(_('Mark &all for delete')) self.mark_delete_button.setToolTip(_('Mark all deletable subitems')) self.mark_delete_button.setDefault(False) self.mark_delete_button.clicked.connect(self.mark_for_delete) self.delete_button = QPushButton(_('Delete &marked')) self.delete_button.setToolTip(_('Delete marked files (checked subitems)')) self.delete_button.setDefault(False) self.delete_button.clicked.connect(self.delete_marked) self.mark_fix_button = QPushButton(_('Mar&k all for fix')) self.mark_fix_button.setToolTip(_('Mark all fixable items')) self.mark_fix_button.setDefault(False) self.mark_fix_button.clicked.connect(self.mark_for_fix) self.fix_button = QPushButton(_('&Fix marked')) self.fix_button.setDefault(False) self.fix_button.setEnabled(False) self.fix_button.setToolTip(_('Fix marked sections (checked fixable items)')) self.fix_button.clicked.connect(self.fix_items) self.bbox = QGridLayout() self.bbox.addWidget(self.check_button, 0, 0) self.bbox.addWidget(self.copy_button, 0, 1) self.bbox.addWidget(self.ok_button, 0, 2) self.bbox.addWidget(self.mark_delete_button, 1, 0) self.bbox.addWidget(self.delete_button, 1, 1) self.bbox.addWidget(self.mark_fix_button, 2, 0) self.bbox.addWidget(self.fix_button, 2, 1) h = QHBoxLayout() ln = QLabel(_('Names to ignore:')) h.addWidget(ln) self.name_ignores = QLineEdit() self.name_ignores.setText(db.new_api.pref('check_library_ignore_names', '')) tt_ext = ('<br><br>' + _('Note: ignoring folders or files inside a book folder can lead to data loss. Ignored ' "folders and files will be lost if you change the book's title or author(s).")) self.name_ignores.setToolTip('<p>' + _('Enter comma-separated standard shell file name wildcards, such as synctoy*.dat. ' 'Used in library, author, and book folders') + tt_ext + '</p>') ln.setBuddy(self.name_ignores) h.addWidget(self.name_ignores) le = QLabel(_('Extensions to ignore:')) h.addWidget(le) self.ext_ignores = QLineEdit() self.ext_ignores.setText(db.new_api.pref('check_library_ignore_extensions', '')) self.ext_ignores.setToolTip('<p>' + _('Enter comma-separated extensions without a leading dot. Used only in book folders') + tt_ext + '</p>') le.setBuddy(self.ext_ignores) h.addWidget(self.ext_ignores) self._layout.addLayout(h) self._layout.addLayout(self.bbox) self.resize(950, 500) def do_exec(self): self.run_the_check() probs = 0 for c in self.problem_count: probs += self.problem_count[c] if probs == 0: return False self.exec() return True def accept(self): self.db.new_api.set_pref('check_library_ignore_extensions', str(self.ext_ignores.text())) self.db.new_api.set_pref('check_library_ignore_names', str(self.name_ignores.text())) QDialog.accept(self) def box_to_list(self, txt): return [f.strip() for f in txt.split(',') if f.strip()] def run_the_check(self): checker = CheckLibrary(self.db.library_path, self.db) checker.scan_library(self.box_to_list(str(self.name_ignores.text())), self.box_to_list(str(self.ext_ignores.text()))) plaintext = [] def builder(tree, checker, check): attr, h, checkable, fixable = check list_ = getattr(checker, attr, None) if list_ is None: self.problem_count[attr] = 0 return else: self.problem_count[attr] = len(list_) tl = QTreeWidgetItem() tl.setText(0, h) if fixable: tl.setData(1, Qt.ItemDataRole.UserRole, self.is_fixable) tl.setText(1, _('(fixable)')) tl.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsUserCheckable) tl.setCheckState(1, Qt.CheckState.Unchecked) else: tl.setData(1, Qt.ItemDataRole.UserRole, self.is_deletable) tl.setData(2, Qt.ItemDataRole.UserRole, self.is_deletable) tl.setText(1, _('(deletable)')) tl.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsUserCheckable) tl.setCheckState(1, Qt.CheckState.Unchecked) if attr == 'extra_covers': tl.setData(2, Qt.ItemDataRole.UserRole, self.is_deletable) tl.setText(2, _('(deletable)')) tl.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsUserCheckable) tl.setCheckState(2, Qt.CheckState.Unchecked) self.top_level_items[attr] = tl for problem in list_: it = QTreeWidgetItem() tl.addChild(it) if checkable: it.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsUserCheckable) it.setCheckState(2, Qt.CheckState.Unchecked) it.setData(2, Qt.ItemDataRole.UserRole, self.is_deletable) else: it.setFlags(Qt.ItemFlag.ItemIsEnabled) tree.setItemWidget(it, 0, TextWithButtonWidget(self.db.library_path, problem[0], problem[1])) it.setData(0, Qt.ItemDataRole.UserRole, problem[2]) it.setText(2, problem[1]) self.all_items.append(it) plaintext.append(','.join([h, problem[0], problem[1]])) tree.addTopLevelItem(tl) t = self.log t.clear() t.setColumnCount(3) t.setHeaderLabels([_('Name'), '', _('Path from library')]) self.all_items = [] self.top_level_items = {} self.problem_count = {} for check in CHECKS: builder(t, checker, check) t.resizeColumnToContents(0) t.resizeColumnToContents(1) self.delete_button.setEnabled(False) self.fix_button.setEnabled(False) self.text_results = '\n'.join(plaintext) def item_expanded_or_collapsed(self, item): self.log.resizeColumnToContents(0) self.log.resizeColumnToContents(1) def item_changed(self, item, column): def set_delete_boxes(node, col, to_what): if isinstance(to_what, bool): to_what = Qt.CheckState.Checked if to_what else Qt.CheckState.Unchecked self.log.blockSignals(True) if col: node.setCheckState(col, to_what) for i in range(0, node.childCount()): node.child(i).setCheckState(2, to_what) self.log.blockSignals(False) def is_child_delete_checked(node): checked = False all_checked = True for i in range(0, node.childCount()): c = node.child(i).checkState(2) checked = checked or c == Qt.CheckState.Checked all_checked = all_checked and c == Qt.CheckState.Checked return (checked, all_checked) def any_child_delete_checked(): for parent in self.top_level_items.values(): (c, _) = is_child_delete_checked(parent) if c: return True return False def any_fix_checked(): for parent in self.top_level_items.values(): if (parent.data(1, Qt.ItemDataRole.UserRole) == self.is_fixable and parent.checkState(1) == Qt.CheckState.Checked): return True return False if item in self.top_level_items.values(): if item.childCount() > 0: if item.data(1, Qt.ItemDataRole.UserRole) == self.is_fixable and column == 1: if item.data(2, Qt.ItemDataRole.UserRole) == self.is_deletable: set_delete_boxes(item, 2, False) else: set_delete_boxes(item, column, item.checkState(column)) if column == 2: self.log.blockSignals(True) item.setCheckState(1, Qt.CheckState.Unchecked) self.log.blockSignals(False) else: item.setCheckState(column, Qt.CheckState.Unchecked) else: for parent in self.top_level_items.values(): if parent.data(2, Qt.ItemDataRole.UserRole) == self.is_deletable: (child_chkd, all_chkd) = is_child_delete_checked(parent) if all_chkd and child_chkd: check_state = Qt.CheckState.Checked elif child_chkd: check_state = Qt.CheckState.PartiallyChecked else: check_state = Qt.CheckState.Unchecked self.log.blockSignals(True) if parent.data(1, Qt.ItemDataRole.UserRole) == self.is_fixable: parent.setCheckState(2, check_state) else: parent.setCheckState(1, check_state) if child_chkd and parent.data(1, Qt.ItemDataRole.UserRole) == self.is_fixable: parent.setCheckState(1, Qt.CheckState.Unchecked) self.log.blockSignals(False) self.delete_button.setEnabled(any_child_delete_checked()) self.fix_button.setEnabled(any_fix_checked()) def mark_for_fix(self): for it in self.top_level_items.values(): if (it.flags() & Qt.ItemFlag.ItemIsUserCheckable and it.data(1, Qt.ItemDataRole.UserRole) == self.is_fixable and it.childCount() > 0): it.setCheckState(1, Qt.CheckState.Checked) def mark_for_delete(self): for it in self.all_items: if (it.flags() & Qt.ItemFlag.ItemIsUserCheckable and it.data(2, Qt.ItemDataRole.UserRole) == self.is_deletable): it.setCheckState(2, Qt.CheckState.Checked) def delete_marked(self): if not confirm('<p>'+_('The marked files and folders will be ' '<b>permanently deleted</b>. Are you sure?') + '</p>', 'check_library_editor_delete', self): return # Sort the paths in reverse length order so that we can be sure that # if an item is in another item, the sub-item will be deleted first. items = sorted(self.all_items, key=lambda x: len(x.text(1)), reverse=True) for it in items: if it.checkState(2) == Qt.CheckState.Checked: try: p = os.path.join(self.db.library_path, str(it.text(2))) if os.path.isdir(p): delete_tree(p) else: delete_file(p) except: prints('failed to delete', os.path.join(self.db.library_path, str(it.text(2)))) self.run_the_check() def fix_missing_formats(self): tl = self.top_level_items['missing_formats'] child_count = tl.childCount() for i in range(0, child_count): item = tl.child(i) id = int(item.data(0, Qt.ItemDataRole.UserRole)) all = self.db.formats(id, index_is_id=True, verify_formats=False) all = {f.strip() for f in all.split(',')} if all else set() valid = self.db.formats(id, index_is_id=True, verify_formats=True) valid = {f.strip() for f in valid.split(',')} if valid else set() for fmt in all-valid: self.db.remove_format(id, fmt, index_is_id=True, db_only=True) def fix_missing_covers(self): tl = self.top_level_items['missing_covers'] child_count = tl.childCount() for i in range(0, child_count): item = tl.child(i) id = int(item.data(0, Qt.ItemDataRole.UserRole)) self.db.set_has_cover(id, False) def fix_extra_covers(self): tl = self.top_level_items['extra_covers'] child_count = tl.childCount() for i in range(0, child_count): item = tl.child(i) id = int(item.data(0, Qt.ItemDataRole.UserRole)) self.db.set_has_cover(id, True) def fix_items(self): for check in CHECKS: attr = check[0] fixable = check[3] tl = self.top_level_items[attr] if fixable and tl.checkState(1) == Qt.CheckState.Checked: func = getattr(self, 'fix_' + attr, None) if func is not None and callable(func): func() self.run_the_check() def copy_to_clipboard(self): QApplication.clipboard().setText(self.text_results) if __name__ == '__main__': from calibre.gui2 import Application app = Application([]) from calibre.library import db as dbconn d = DBCheck(None, dbconn()) d.exec()
23,392
Python
.py
500
35.776
139
0.605539
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)