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,700
polish.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/polish.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' import re from threading import Thread from qt.core import ( QAbstractItemView, QApplication, QCheckBox, QDialog, QDialogButtonBox, QHBoxLayout, QIcon, QLabel, QListWidget, QListWidgetItem, QPalette, QPen, QPixmap, QProgressBar, QSize, QSpinBox, QStyle, QStyledItemDelegate, Qt, QTextBrowser, QVBoxLayout, QWidget, pyqtSignal, ) from calibre import fit_image, force_unicode, human_readable from calibre.ebooks.oeb.polish.main import CUSTOMIZATION from calibre.gui2 import empty_index, question_dialog from calibre.gui2.tweak_book import current_container, set_current_container, tprefs from calibre.gui2.tweak_book.widgets import Dialog from calibre.startup import connect_lambda from calibre.utils.icu import numeric_sort_key class Abort(Exception): pass def customize_remove_unused_css(name, parent, ans): d = QDialog(parent) d.l = l = QVBoxLayout() d.setLayout(d.l) d.setWindowTitle(_('Remove unused CSS')) def label(text): la = QLabel(text) la.setWordWrap(True), l.addWidget(la), la.setMinimumWidth(450) l.addWidget(la) return la d.la = label(_( 'This will remove all CSS rules that do not match any actual content.' ' There are a couple of additional cleanups you can enable, below:')) d.c = c = QCheckBox(_('Remove unused &class attributes')) c.setChecked(tprefs['remove_unused_classes']) l.addWidget(c) d.la2 = label('<span style="font-size:small; font-style: italic">' + _( 'Remove all class attributes from the HTML that do not match any existing CSS rules')) d.m = m = QCheckBox(_('Merge CSS rules with identical &selectors')) m.setChecked(tprefs['merge_identical_selectors']) l.addWidget(m) d.la3 = label('<span style="font-size:small; font-style: italic">' + _( 'Merge CSS rules in the same stylesheet that have identical selectors.' ' Note that in rare cases merging can result in a change to the effective styling' ' of the book, so use with care.')) d.p = p = QCheckBox(_('Merge CSS rules with identical &properties')) p.setChecked(tprefs['merge_rules_with_identical_properties']) l.addWidget(p) d.la4 = label('<span style="font-size:small; font-style: italic">' + _( 'Merge CSS rules in the same stylesheet that have identical properties.' ' Note that in rare cases merging can result in a change to the effective styling' ' of the book, so use with care.')) d.u = u = QCheckBox(_('Remove &unreferenced style sheets')) u.setChecked(tprefs['remove_unreferenced_sheets']) l.addWidget(u) d.la5 = label('<span style="font-size:small; font-style: italic">' + _( 'Remove stylesheets that are not referenced by any content.' )) d.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) d.l.addWidget(d.bb) d.bb.rejected.connect(d.reject) d.bb.accepted.connect(d.accept) ret = d.exec() ans['remove_unused_classes'] = tprefs['remove_unused_classes'] = c.isChecked() ans['merge_identical_selectors'] = tprefs['merge_identical_selectors'] = m.isChecked() ans['merge_rules_with_identical_properties'] = tprefs['merge_rules_with_identical_properties'] = p.isChecked() ans['remove_unreferenced_sheets'] = tprefs['remove_unreferenced_sheets'] = u.isChecked() if ret != QDialog.DialogCode.Accepted: raise Abort() def get_customization(action, name, parent): ans = CUSTOMIZATION.copy() try: if action == 'remove_unused_css': customize_remove_unused_css(name, parent, ans) elif action == 'upgrade_book': ans['remove_ncx'] = tprefs['remove_ncx'] = question_dialog( parent, _('Remove NCX ToC file'), _('Remove the legacy Table of Contents in NCX form?'), _('This form of Table of Contents is superseded by the new HTML based Table of Contents.' ' Leaving it behind is useful only if you expect this book to be read on very' ' old devices that lack proper support for EPUB 3'), skip_dialog_name='edit-book-remove-ncx', skip_dialog_msg=_('Ask this question again in the future'), skip_dialog_skipped_value=tprefs['remove_ncx'], yes_text=_('Remove NCX'), no_text=_('Keep NCX') ) except Abort: return None return ans def format_report(title, report): from calibre.ebooks.markdown import markdown report = [force_unicode(line) for line in report] return markdown('# %s\n\n'%force_unicode(title) + '\n\n'.join(report), output_format='html4') def show_report(changed, title, report, parent, show_current_diff): report = format_report(title, report) d = QDialog(parent) d.setWindowTitle(_('Action report')) d.l = QVBoxLayout() d.setLayout(d.l) d.e = QTextBrowser(d) d.l.addWidget(d.e) d.e.setHtml(report) d.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) d.show_changes = False if changed: b = d.b = d.bb.addButton(_('See what &changed'), QDialogButtonBox.ButtonRole.AcceptRole) b.setIcon(QIcon.ic('diff.png')), b.setAutoDefault(False) connect_lambda(b.clicked, d, lambda d: setattr(d, 'show_changes', True)) b = d.bb.addButton(_('&Copy to clipboard'), QDialogButtonBox.ButtonRole.ActionRole) b.setIcon(QIcon.ic('edit-copy.png')), b.setAutoDefault(False) def copy_report(): text = re.sub(r'</.+?>', '\n', report) text = re.sub(r'<.+?>', '', text) cp = QApplication.instance().clipboard() cp.setText(text) b.clicked.connect(copy_report) d.bb.button(QDialogButtonBox.StandardButton.Close).setDefault(True) d.l.addWidget(d.bb) d.bb.rejected.connect(d.reject) d.bb.accepted.connect(d.accept) d.resize(600, 400) d.exec() b.clicked.disconnect() if d.show_changes: show_current_diff(allow_revert=True) # CompressImages {{{ class ImageItemDelegate(QStyledItemDelegate): def sizeHint(self, option, index): return QSize(300, 100) def paint(self, painter, option, index): name = index.data(Qt.ItemDataRole.DisplayRole) sz = human_readable(index.data(Qt.ItemDataRole.UserRole)) pmap = index.data(Qt.ItemDataRole.UserRole+1) irect = option.rect.adjusted(0, 5, 0, -5) irect.setRight(irect.left() + 70) if pmap is None: pmap = QPixmap(current_container().get_file_path_for_processing(name)) scaled, nwidth, nheight = fit_image(pmap.width(), pmap.height(), irect.width(), irect.height()) if scaled: pmap = pmap.scaled(nwidth, nheight, transformMode=Qt.TransformationMode.SmoothTransformation) index.model().setData(index, pmap, Qt.ItemDataRole.UserRole+1) x, y = (irect.width() - pmap.width())//2, (irect.height() - pmap.height())//2 r = irect.adjusted(x, y, -x, -y) QStyledItemDelegate.paint(self, painter, option, empty_index) painter.drawPixmap(r, pmap) trect = irect.adjusted(irect.width() + 10, 0, 0, 0) trect.setRight(option.rect.right()) painter.save() if option.state & QStyle.StateFlag.State_Selected: painter.setPen(QPen(option.palette.color(QPalette.ColorRole.HighlightedText))) painter.drawText(trect, Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft, name + '\n' + sz) painter.restore() class LossyCompression(QWidget): def __init__(self, image_type, default_compression=80, parent=None): super().__init__(parent) l = QVBoxLayout(self) image_type = image_type.upper() self.enable_lossy = el = QCheckBox(_('Enable &lossy compression of {} images').format(image_type)) el.setToolTip(_('This allows you to change the quality factor used for {} images.\nBy lowering' ' the quality you can greatly reduce file size, at the expense of the image looking blurred.'.format(image_type))) l.addWidget(el) self.h2 = h = QHBoxLayout() l.addLayout(h) self.jq = jq = QSpinBox(self) image_type = image_type.lower() self.image_type = image_type self.quality_pref_name = f'{image_type}_compression_quality_for_lossless_compression' jq.setMinimum(1), jq.setMaximum(100), jq.setValue(tprefs.get(self.quality_pref_name, default_compression)) jq.setEnabled(False) jq.setToolTip(_('The image quality, 1 is high compression with low image quality, 100 is low compression with high image quality')) jq.valueChanged.connect(self.save_compression_quality) el.toggled.connect(jq.setEnabled) self.jql = la = QLabel(_('Image &quality:')) la.setBuddy(jq) h.addWidget(la), h.addWidget(jq) def save_compression_quality(self): tprefs.set(self.quality_pref_name, self.jq.value()) class CompressImages(Dialog): def __init__(self, parent=None): Dialog.__init__(self, _('Compress images'), 'compress-images', parent=parent) def setup_ui(self): from calibre.ebooks.oeb.polish.images import get_compressible_images self.setWindowIcon(QIcon.ic('compress-image.png')) self.h = h = QHBoxLayout(self) self.images = i = QListWidget(self) h.addWidget(i) self.l = l = QVBoxLayout() h.addLayout(l) c = current_container() for name in sorted(get_compressible_images(c), key=numeric_sort_key): x = QListWidgetItem(name, i) x.setData(Qt.ItemDataRole.UserRole, c.filesize(name)) i.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) i.setMinimumHeight(350), i.setMinimumWidth(350) i.selectAll(), i.setSpacing(5) self.delegate = ImageItemDelegate(self) i.setItemDelegate(self.delegate) self.la = la = QLabel(_( 'You can compress the images in this book losslessly, reducing the file size of the book,' ' without affecting image quality. Typically image size is reduced by 5 - 15%.')) la.setWordWrap(True) la.setMinimumWidth(250) l.addWidget(la) self.jpeg = LossyCompression('jpeg', parent=self) l.addSpacing(30), l.addWidget(self.jpeg) self.webp = LossyCompression('webp', default_compression=75, parent=self) l.addSpacing(30), l.addWidget(self.webp) l.addStretch(10) l.addWidget(self.bb) @property def names(self): return {item.text() for item in self.images.selectedItems()} @property def jpeg_quality(self): if not self.jpeg.enable_lossy.isChecked(): return None return self.jpeg.jq.value() @property def webp_quality(self): if not self.webp.enable_lossy.isChecked(): return None return self.webp.jq.value() class CompressImagesProgress(Dialog): gui_loop = pyqtSignal(object, object, object) cidone = pyqtSignal() def __init__(self, names=None, jpeg_quality=None, webp_quality=None, parent=None): self.names, self.jpeg_quality = names, jpeg_quality self.webp_quality = webp_quality self.keep_going = True self.result = (None, '') Dialog.__init__(self, _('Compressing images...'), 'compress-images-progress', parent=parent) self.gui_loop.connect(self.update_progress, type=Qt.ConnectionType.QueuedConnection) self.cidone.connect(self.accept, type=Qt.ConnectionType.QueuedConnection) t = Thread(name='RunCompressImages', target=self.run_compress) t.daemon = True t.start() def run_compress(self): from calibre.ebooks.oeb.polish.images import compress_images from calibre.gui2.tweak_book import current_container report = [] try: self.result = (compress_images( current_container(), report=report.append, names=self.names, jpeg_quality=self.jpeg_quality, webp_quality=self.webp_quality, progress_callback=self.progress_callback )[0], report) except Exception: import traceback self.result = (None, traceback.format_exc()) self.cidone.emit() def setup_ui(self): self.setWindowIcon(QIcon.ic('compress-image.png')) self.setCursor(Qt.CursorShape.BusyCursor) self.setMinimumWidth(350) self.l = l = QVBoxLayout(self) self.la = la = QLabel(_('Compressing images, please wait...')) la.setStyleSheet('QLabel { font-weight: bold }'), la.setAlignment(Qt.AlignmentFlag.AlignCenter), la.setTextFormat(Qt.TextFormat.PlainText) l.addWidget(la) self.progress = p = QProgressBar(self) p.setMinimum(0), p.setMaximum(0) l.addWidget(p) self.msg = la = QLabel('\xa0') la.setAlignment(Qt.AlignmentFlag.AlignCenter), la.setTextFormat(Qt.TextFormat.PlainText) l.addWidget(la) self.bb.setStandardButtons(QDialogButtonBox.StandardButton.Cancel) l.addWidget(self.bb) def reject(self): self.keep_going = False self.bb.button(QDialogButtonBox.StandardButton.Cancel).setEnabled(False) Dialog.reject(self) def progress_callback(self, num, total, name): self.gui_loop.emit(num, total, name) return self.keep_going def update_progress(self, num, total, name): self.progress.setMaximum(total), self.progress.setValue(num) self.msg.setText(name) # }}} if __name__ == '__main__': from calibre.gui2 import Application app = Application([]) import sys import sip from calibre.ebooks.oeb.polish.container import get_container c = get_container(sys.argv[-1], tweak_mode=True) set_current_container(c) d = CompressImages() if d.exec() == QDialog.DialogCode.Accepted: pass sip.delete(app) del app
14,184
Python
.py
308
38.532468
146
0.665292
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,701
search.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/search.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2013, Kovid Goyal <kovid at kovidgoyal.net> import copy import json import time from collections import Counter, OrderedDict from functools import partial import regex from qt.core import ( QAbstractItemView, QAbstractListModel, QAction, QApplication, QCheckBox, QComboBox, QDialog, QDialogButtonBox, QEvent, QFont, QFrame, QGridLayout, QHBoxLayout, QIcon, QItemSelection, QItemSelectionModel, QKeySequence, QLabel, QLineEdit, QListView, QMenu, QMimeData, QModelIndex, QPushButton, QScrollArea, QSize, QSizePolicy, QStackedLayout, QStyledItemDelegate, Qt, QTimer, QToolBar, QToolButton, QVBoxLayout, QWidget, pyqtSignal, ) from calibre import prepare_string_for_xml from calibre.constants import iswindows from calibre.ebooks.conversion.search_replace import REGEX_FLAGS, compile_regular_expression from calibre.gui2 import choose_files, choose_save_file, error_dialog, info_dialog from calibre.gui2.dialogs.confirm_delete import confirm from calibre.gui2.dialogs.message_box import MessageBox from calibre.gui2.tweak_book import current_container, editors, tprefs from calibre.gui2.tweak_book.editor.snippets import KEY, MODIFIER, SnippetTextEdit, find_matching_snip, parse_template, string_length from calibre.gui2.tweak_book.function_replace import Function, FunctionBox, FunctionEditor, remove_function from calibre.gui2.tweak_book.function_replace import functions as replace_functions from calibre.gui2.widgets import BusyCursor from calibre.gui2.widgets2 import FlowLayout, HistoryComboBox from calibre.startup import connect_lambda from calibre.utils.icu import primary_contains from polyglot.builtins import error_message, iteritems # The search panel {{{ class AnimatablePushButton(QPushButton): 'A push button that can be animated without actually emitting a clicked signal' def __init__(self, *args, **kwargs): QPushButton.__init__(self, *args, **kwargs) self.timer = t = QTimer(self) t.setSingleShot(True), t.timeout.connect(self.animate_done) def animate_click(self, msec=100): self.setDown(True) self.update() self.timer.start(msec) def animate_done(self): self.setDown(False) self.update() class PushButton(AnimatablePushButton): def __init__(self, text, action, parent): AnimatablePushButton.__init__(self, text, parent) connect_lambda(self.clicked, parent, lambda parent: parent.search_triggered.emit(action)) def expand_template(line_edit): pos = line_edit.cursorPosition() text = line_edit.text()[:pos] if text: snip, trigger = find_matching_snip(text) if snip is None: error_dialog(line_edit, _('No snippet found'), _( 'No matching snippet was found'), show=True) return False text, tab_stops = parse_template(snip['template']) ft = line_edit.text() l = string_length(trigger) line_edit.setText(ft[:pos - l] + text + ft[pos:]) line_edit.setCursorPosition(pos - l + string_length(text)) return True return False class HistoryBox(HistoryComboBox): max_history_items = 100 save_search = pyqtSignal() show_saved_searches = pyqtSignal() min_history_entry_length = 1 def __init__(self, parent, clear_msg): HistoryComboBox.__init__(self, parent, strip_completion_entries=False) self.disable_popup = tprefs['disable_completion_popup_for_search'] self.clear_msg = clear_msg self.ignore_snip_expansion = False self.lineEdit().setClearButtonEnabled(True) self.set_uniform_item_sizes(False) def event(self, ev): if ev.type() in (QEvent.Type.ShortcutOverride, QEvent.Type.KeyPress) and ev.key() == KEY and ev.modifiers() & MODIFIER: if not self.ignore_snip_expansion: self.ignore_snip_expansion = True expand_template(self.lineEdit()) QTimer.singleShot(100, lambda : setattr(self, 'ignore_snip_expansion', False)) ev.accept() return True return HistoryComboBox.event(self, ev) def contextMenuEvent(self, event): menu = self.lineEdit().createStandardContextMenu() menu.addSeparator() menu.addAction(self.clear_msg, self.clear_history) menu.addAction((_('Enable completion based on search history') if self.disable_popup else _( 'Disable completion based on search history')), self.toggle_popups) menu.addSeparator() menu.addAction(_('Save current search'), self.save_search.emit) menu.addAction(_('Show saved searches'), self.show_saved_searches.emit) menu.exec(event.globalPos()) def toggle_popups(self): self.disable_popup = not bool(self.disable_popup) tprefs['disable_completion_popup_for_search'] = self.disable_popup class WhereBox(QComboBox): def __init__(self, parent, emphasize=False): QComboBox.__init__(self) self.addItems([_('Current file'), _('All text files'), _('All style files'), _('Selected files'), _('Open files'), _('Marked text')]) self.setToolTip('<style>dd {margin-bottom: 1.5ex}</style>' + _( ''' Where to search/replace: <dl> <dt><b>Current file</b></dt> <dd>Search only inside the currently opened file</dd> <dt><b>All text files</b></dt> <dd>Search in all text (HTML) files</dd> <dt><b>All style files</b></dt> <dd>Search in all style (CSS) files</dd> <dt><b>Selected files</b></dt> <dd>Search in the files currently selected in the File browser</dd> <dt><b>Open files</b></dt> <dd>Search in the files currently open in the editor</dd> <dt><b>Marked text</b></dt> <dd>Search only within the marked text in the currently opened file. You can mark text using the Search menu.</dd> </dl>''')) self.emphasize = emphasize self.ofont = QFont(self.font()) if emphasize: f = self.emph_font = QFont(self.ofont) f.setBold(True), f.setItalic(True) self.setFont(f) @property def where(self): wm = {0:'current', 1:'text', 2:'styles', 3:'selected', 4:'open', 5:'selected-text'} return wm[self.currentIndex()] @where.setter def where(self, val): wm = {0:'current', 1:'text', 2:'styles', 3:'selected', 4:'open', 5:'selected-text'} self.setCurrentIndex({v:k for k, v in iteritems(wm)}[val]) def showPopup(self): # We do it like this so that the popup uses a normal font if self.emphasize: self.setFont(self.ofont) QComboBox.showPopup(self) def hidePopup(self): if self.emphasize: self.setFont(self.emph_font) QComboBox.hidePopup(self) class DirectionBox(QComboBox): def __init__(self, parent): QComboBox.__init__(self, parent) self.addItems([_('Down'), _('Up')]) self.setToolTip('<style>dd {margin-bottom: 1.5ex}</style>' + _( ''' Direction to search: <dl> <dt><b>Down</b></dt> <dd>Search for the next match from your current position</dd> <dt><b>Up</b></dt> <dd>Search for the previous match from your current position</dd> </dl>''')) @property def direction(self): return 'down' if self.currentIndex() == 0 else 'up' @direction.setter def direction(self, val): self.setCurrentIndex(1 if val == 'up' else 0) class ModeBox(QComboBox): def __init__(self, parent): QComboBox.__init__(self, parent) self.addItems([_('Normal'), _('Fuzzy'), _('Regex'), _('Regex-function')]) self.setToolTip('<style>dd {margin-bottom: 1.5ex}</style>' + _( '''Select how the search expression is interpreted <dl> <dt><b>Normal</b></dt> <dd>The search expression is treated as normal text, calibre will look for the exact text</dd> <dt><b>Fuzzy</b></dt> <dd>The search expression is treated as "fuzzy" which means spaces will match any space character, including tabs and line breaks. Plain quotes will match the typographical equivalents, etc.</dd> <dt><b>Regex</b></dt> <dd>The search expression is interpreted as a regular expression. See the User Manual for more help on using regular expressions.</dd> <dt><b>Regex-function</b></dt> <dd>The search expression is interpreted as a regular expression. The replace expression is an arbitrarily powerful Python function.</dd> </dl>''')) @property def mode(self): return ('normal', 'fuzzy', 'regex', 'function')[self.currentIndex()] @mode.setter def mode(self, val): self.setCurrentIndex({'fuzzy': 1, 'regex':2, 'function':3}.get(val, 0)) class SearchWidget(QWidget): DEFAULT_STATE = { 'mode': 'normal', 'where': 'current', 'case_sensitive': False, 'direction': 'down', 'wrap': True, 'dot_all': False, } search_triggered = pyqtSignal(object) save_search = pyqtSignal() show_saved_searches = pyqtSignal() def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QGridLayout(self) left, top, right, bottom = l.getContentsMargins() l.setContentsMargins(0, 0, right, 0) self.fl = fl = QLabel(_('&Find:')) fl.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignCenter) self.find_text = ft = HistoryBox(self, _('Clear search &history')) ft.save_search.connect(self.save_search) ft.show_saved_searches.connect(self.show_saved_searches) ft.initialize('tweak_book_find_edit') connect_lambda(ft.lineEdit().returnPressed, self, lambda self: self.search_triggered.emit('find')) fl.setBuddy(ft) l.addWidget(fl, 0, 0) l.addWidget(ft, 0, 1) l.setColumnStretch(1, 10) self.rl = rl = QLabel(_('&Replace:')) rl.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignCenter) self.replace_text = rt = HistoryBox(self, _('Clear replace &history')) rt.save_search.connect(self.save_search) rt.show_saved_searches.connect(self.show_saved_searches) rt.initialize('tweak_book_replace_edit') rl.setBuddy(rt) self.replace_stack1 = rs1 = QVBoxLayout() self.replace_stack2 = rs2 = QVBoxLayout() rs1.addWidget(rl), rs2.addWidget(rt) l.addLayout(rs1, 1, 0) l.addLayout(rs2, 1, 1) self.rl2 = rl2 = QLabel(_('F&unction:')) rl2.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignCenter) self.functions = fb = FunctionBox(self, show_saved_search_actions=True) fb.show_saved_searches.connect(self.show_saved_searches) fb.save_search.connect(self.save_search) rl2.setBuddy(fb) rs1.addWidget(rl2) self.functions_container = w = QWidget(self) rs2.addWidget(w) self.fhl = fhl = QHBoxLayout(w) fhl.setContentsMargins(0, 0, 0, 0) fhl.addWidget(fb, stretch=10, alignment=Qt.AlignmentFlag.AlignVCenter) self.ae_func = b = QPushButton(_('Create/&edit'), self) b.clicked.connect(self.edit_function) b.setToolTip(_('Create a new function, or edit an existing function')) fhl.addWidget(b) self.rm_func = b = QPushButton(_('Remo&ve'), self) b.setToolTip(_('Remove this function')) b.clicked.connect(self.remove_function) fhl.addWidget(b) self.fsep = f = QFrame(self) f.setFrameShape(QFrame.Shape.VLine) fhl.addWidget(f) self.fb = fb = PushButton(_('Fin&d'), 'find', self) self.rfb = rfb = PushButton(_('Replace a&nd Find'), 'replace-find', self) self.rb = rb = PushButton(_('Re&place'), 'replace', self) self.rab = rab = PushButton(_('Replace &all'), 'replace-all', self) l.addWidget(fb, 0, 2) l.addWidget(rfb, 0, 3) l.addWidget(rb, 1, 2) l.addWidget(rab, 1, 3) self.ml = ml = QLabel(_('&Mode:')) self.ol = ol = FlowLayout() ml.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter) l.addWidget(ml, 2, 0) l.addLayout(ol, 2, 1, 1, 3) self.mode_box = mb = ModeBox(self) ml.setBuddy(mb) ol.addWidget(mb) self.where_box = wb = WhereBox(self) ol.addWidget(wb) self.direction_box = db = DirectionBox(self) ol.addWidget(db) self.cs = cs = QCheckBox(_('&Case sensitive')) ol.addWidget(cs) self.wr = wr = QCheckBox(_('&Wrap')) wr.setToolTip('<p>'+_('When searching reaches the end, wrap around to the beginning and continue the search')) ol.addWidget(wr) self.da = da = QCheckBox(_('&Dot all')) da.setToolTip('<p>'+_("Make the '.' special character match any character at all, including a newline")) ol.addWidget(da) self.mode_box.currentIndexChanged.connect(self.mode_changed) self.mode_changed(self.mode_box.currentIndex()) def edit_function(self): d = FunctionEditor(func_name=self.functions.text().strip(), parent=self) if d.exec() == QDialog.DialogCode.Accepted: self.functions.setText(d.func_name) def remove_function(self): fname = self.functions.text().strip() if fname: if remove_function(fname, self): self.functions.setText('') def mode_changed(self, idx): self.da.setVisible(idx > 1) function_mode = idx == 3 self.rl.setVisible(not function_mode) self.rl2.setVisible(function_mode) self.replace_text.setVisible(not function_mode) self.functions_container.setVisible(function_mode) @property def mode(self): return self.mode_box.mode @mode.setter def mode(self, val): self.mode_box.mode = val self.da.setVisible(self.mode in ('regex', 'function')) @property def find(self): return str(self.find_text.text()) @find.setter def find(self, val): self.find_text.setText(val) @property def replace(self): if self.mode == 'function': return self.functions.text() return str(self.replace_text.text()) @replace.setter def replace(self, val): self.replace_text.setText(val) @property def where(self): return self.where_box.where @where.setter def where(self, val): self.where_box.where = val @property def case_sensitive(self): return self.cs.isChecked() @case_sensitive.setter def case_sensitive(self, val): self.cs.setChecked(bool(val)) @property def direction(self): return self.direction_box.direction @direction.setter def direction(self, val): self.direction_box.direction = val @property def wrap(self): return self.wr.isChecked() @wrap.setter def wrap(self, val): self.wr.setChecked(bool(val)) @property def dot_all(self): return self.da.isChecked() @dot_all.setter def dot_all(self, val): self.da.setChecked(bool(val)) @property def state(self): return {x:getattr(self, x) for x in self.DEFAULT_STATE} @state.setter def state(self, val): for x in self.DEFAULT_STATE: if x in val: setattr(self, x, val[x]) def restore_state(self): self.state = tprefs.get('find-widget-state', self.DEFAULT_STATE) if self.where == 'selected-text': self.where = self.DEFAULT_STATE['where'] def save_state(self): tprefs.set('find-widget-state', self.state) def pre_fill(self, text): if self.mode in ('regex', 'function'): text = regex.escape(text, special_only=True, literal_spaces=True) self.find = text self.find_text.lineEdit().setSelection(0, len(text)+10) def paste_saved_search(self, s): self.case_sensitive = s.get('case_sensitive') or False self.dot_all = s.get('dot_all') or False if 'wrap' in s: self.wrap = s.get('wrap') or False self.mode = s.get('mode') or 'normal' self.find = s.get('find') or '' self.replace = s.get('replace') or '' # }}} class SearchPanel(QWidget): # {{{ search_triggered = pyqtSignal(object) save_search = pyqtSignal() show_saved_searches = pyqtSignal() def __init__(self, parent=None): QWidget.__init__(self, parent) self.where_before_marked = None self.l = l = QHBoxLayout() self.setLayout(l) l.setContentsMargins(0, 0, 0, 0) self.t = t = QToolBar(self) l.addWidget(t) t.setOrientation(Qt.Orientation.Vertical) t.setIconSize(QSize(12, 12)) t.setMovable(False) t.setFloatable(False) t.cl = ac = t.addAction(QIcon.ic('window-close.png'), _('Close search panel')) ac.triggered.connect(self.hide_panel) self.widget = SearchWidget(self) l.addWidget(self.widget) self.restore_state, self.save_state = self.widget.restore_state, self.widget.save_state self.widget.search_triggered.connect(self.search_triggered) self.widget.save_search.connect(self.save_search) self.widget.show_saved_searches.connect(self.show_saved_searches) self.pre_fill = self.widget.pre_fill def paste_saved_search(self, s): self.widget.paste_saved_search(s) def hide_panel(self): self.setVisible(False) def show_panel(self): self.setVisible(True) self.widget.find_text.setFocus(Qt.FocusReason.OtherFocusReason) le = self.widget.find_text.lineEdit() le.setSelection(0, le.maxLength()) @property def state(self): ans = self.widget.state ans['find'] = self.widget.find ans['replace'] = self.widget.replace return ans def set_where(self, val): if val == 'selected-text' and self.widget.where != 'selected-text': self.where_before_marked = self.widget.where self.widget.where = val def unset_marked(self): if self.widget.where == 'selected-text': self.widget.where = self.where_before_marked or self.widget.DEFAULT_STATE['where'] self.where_before_marked = None def keyPressEvent(self, ev): if ev.key() == Qt.Key.Key_Escape: self.hide_panel() ev.accept() else: return QWidget.keyPressEvent(self, ev) # }}} class SearchDescription(QScrollArea): def __init__(self, parent): QScrollArea.__init__(self, parent) self.label = QLabel(' \n \n ') self.setWidget(self.label) self.setWidgetResizable(True) self.label.setTextFormat(Qt.TextFormat.PlainText) self.label.setWordWrap(True) self.set_text = self.label.setText class SearchesModel(QAbstractListModel): def __init__(self, parent): QAbstractListModel.__init__(self, parent) self.searches = tprefs['saved_searches'] self.filtered_searches = list(range(len(self.searches))) def rowCount(self, parent=QModelIndex()): return len(self.filtered_searches) def supportedDropActions(self): return Qt.DropAction.MoveAction def flags(self, index): ans = QAbstractListModel.flags(self, index) if index.isValid(): ans |= Qt.ItemFlag.ItemIsDragEnabled else: ans |= Qt.ItemFlag.ItemIsDropEnabled return ans def mimeTypes(self): return ['x-calibre/searches-rows', 'application/vnd.text.list'] def mimeData(self, indices): ans = QMimeData() names, rows = [], [] for i in indices: if i.isValid(): names.append(i.data()) rows.append(i.row()) ans.setData('x-calibre/searches-rows', ','.join(map(str, rows)).encode('ascii')) ans.setData('application/vnd.text.list', '\n'.join(names).encode('utf-8')) return ans def dropMimeData(self, data, action, row, column, parent): if parent.isValid() or action != Qt.DropAction.MoveAction or not data.hasFormat('x-calibre/searches-rows') or not self.filtered_searches: return False rows = sorted(map(int, bytes(bytearray(data.data('x-calibre/searches-rows'))).decode('ascii').split(','))) moved_searches = [self.searches[self.filtered_searches[r]] for r in rows] moved_searches_q = {id(s) for s in moved_searches} insert_at = max(0, min(row, len(self.filtered_searches))) while insert_at < len(self.filtered_searches): s = self.searches[self.filtered_searches[insert_at]] if id(s) in moved_searches_q: insert_at += 1 else: break insert_before = id(self.searches[self.filtered_searches[insert_at]]) if insert_at < len(self.filtered_searches) else None visible_searches = {id(self.searches[self.filtered_searches[r]]) for r in self.filtered_searches} unmoved_searches = list(filter(lambda s:id(s) not in moved_searches_q, self.searches)) if insert_before is None: searches = unmoved_searches + moved_searches else: idx = {id(x):i for i, x in enumerate(unmoved_searches)}[insert_before] searches = unmoved_searches[:idx] + moved_searches + unmoved_searches[idx:] filtered_searches = [] for i, s in enumerate(searches): if id(s) in visible_searches: filtered_searches.append(i) self.modelAboutToBeReset.emit() self.searches, self.filtered_searches = searches, filtered_searches self.modelReset.emit() tprefs['saved_searches'] = self.searches return True def data(self, index, role): try: if role == Qt.ItemDataRole.DisplayRole: search = self.searches[self.filtered_searches[index.row()]] return search['name'] if role == Qt.ItemDataRole.ToolTipRole: search = self.searches[self.filtered_searches[index.row()]] tt = '\n'.join((search['find'], search['replace'])) return tt if role == Qt.ItemDataRole.UserRole: search = self.searches[self.filtered_searches[index.row()]] return (self.filtered_searches[index.row()], search) except IndexError: pass return None def do_filter(self, text): text = str(text) self.beginResetModel() self.filtered_searches = [] for i, search in enumerate(self.searches): if primary_contains(text, search['name']): self.filtered_searches.append(i) self.endResetModel() def search_for_index(self, index): try: return self.searches[self.filtered_searches[index.row()]] except IndexError: pass def index_for_search(self, search): for row, si in enumerate(self.filtered_searches): if self.searches[si] is search: return self.index(row) return self.index(-1) def move_entry(self, row, delta): a, b = row, row + delta if 0 <= b < len(self.filtered_searches): ai, bi = self.filtered_searches[a], self.filtered_searches[b] self.searches[ai], self.searches[bi] = self.searches[bi], self.searches[ai] self.dataChanged.emit(self.index(a), self.index(a)) self.dataChanged.emit(self.index(b), self.index(b)) tprefs['saved_searches'] = self.searches def add_searches(self, count=1): self.beginResetModel() self.searches = tprefs['saved_searches'] self.filtered_searches.extend(range(len(self.searches) - count, len(self.searches), 1)) self.endResetModel() def remove_searches(self, rows): indices = {self.filtered_searches[row] for row in frozenset(rows)} for idx in sorted(indices, reverse=True): del self.searches[idx] tprefs['saved_searches'] = self.searches self.do_filter('') class EditSearch(QFrame): # {{{ done = pyqtSignal(object) def __init__(self, parent=None): QFrame.__init__(self, parent) self.setFrameShape(QFrame.Shape.StyledPanel) self.search_index = -1 self.search = {} self.original_name = None self.l = l = QVBoxLayout(self) self.title = la = QLabel('<h2>Edit...') self.ht = h = QHBoxLayout() l.addLayout(h) h.addWidget(la) self.cb = cb = QToolButton(self) cb.setIcon(QIcon.ic('window-close.png')) cb.setToolTip(_('Abort editing of search')) h.addWidget(cb) cb.clicked.connect(self.abort_editing) self.search_name = n = QLineEdit('', self) n.setPlaceholderText(_('The name with which to save this search')) self.la1 = la = QLabel(_('&Name:')) la.setBuddy(n) self.h3 = h = QHBoxLayout() h.addWidget(la), h.addWidget(n) l.addLayout(h) self.find = f = SnippetTextEdit('', self) self.la2 = la = QLabel(_('&Find:')) la.setBuddy(f) l.addWidget(la), l.addWidget(f) self.replace = r = SnippetTextEdit('', self) self.la3 = la = QLabel(_('&Replace:')) la.setBuddy(r) l.addWidget(la), l.addWidget(r) self.functions_container = w = QWidget() l.addWidget(w) w.g = g = QGridLayout(w) self.la7 = la = QLabel(_('F&unction:')) self.function = f = FunctionBox(self) g.addWidget(la), g.addWidget(f) g.setContentsMargins(0, 0, 0, 0) la.setBuddy(f) self.ae_func = b = QPushButton(_('Create/&edit'), self) b.setToolTip(_('Create a new function, or edit an existing function')) b.clicked.connect(self.edit_function) g.addWidget(b, 1, 1) g.setColumnStretch(0, 10) self.rm_func = b = QPushButton(_('Remo&ve'), self) b.setToolTip(_('Remove this function')) b.clicked.connect(self.remove_function) g.addWidget(b, 1, 2) self.case_sensitive = c = QCheckBox(_('Case sensitive')) self.h = h = QHBoxLayout() l.addLayout(h) h.addWidget(c) self.dot_all = d = QCheckBox(_('Dot matches all')) h.addWidget(d), h.addStretch(2) self.h2 = h = QHBoxLayout() l.addLayout(h) self.mode_box = m = ModeBox(self) m.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) self.la4 = la = QLabel(_('&Mode:')) la.setBuddy(m) h.addWidget(la), h.addWidget(m), h.addStretch(2) self.done_button = b = QPushButton(QIcon.ic('ok.png'), _('&Done')) b.setToolTip(_('Finish editing of search')) h.addWidget(b) b.clicked.connect(self.emit_done) self.mode_box.currentIndexChanged.connect(self.mode_changed) self.mode_changed(self.mode_box.currentIndex()) def edit_function(self): d = FunctionEditor(func_name=self.function.text().strip(), parent=self) if d.exec() == QDialog.DialogCode.Accepted: self.function.setText(d.func_name) def remove_function(self): fname = self.function.text().strip() if fname: if remove_function(fname, self): self.function.setText('') def mode_changed(self, idx): mode = self.mode_box.mode self.dot_all.setVisible(mode in ('regex', 'function')) function_mode = mode == 'function' self.functions_container.setVisible(function_mode) self.la3.setVisible(not function_mode) self.replace.setVisible(not function_mode) def show_search(self, search=None, search_index=-1, state=None): self.title.setText('<h2>' + (_('Add search') if search_index == -1 else _('Edit search'))) self.search = search or {} self.original_name = self.search.get('name', None) self.search_index = search_index self.mode_box.mode = self.search.get('mode', 'regex') self.search_name.setText(self.search.get('name', '')) self.find.setPlainText(self.search.get('find', '')) if self.mode_box.mode == 'function': self.function.setText(self.search.get('replace', '')) else: self.replace.setPlainText(self.search.get('replace', '')) self.case_sensitive.setChecked(self.search.get('case_sensitive', SearchWidget.DEFAULT_STATE['case_sensitive'])) self.dot_all.setChecked(self.search.get('dot_all', SearchWidget.DEFAULT_STATE['dot_all'])) if state is not None: self.find.setPlainText(state['find']) self.mode_box.mode = state.get('mode') if self.mode_box.mode == 'function': self.function.setText(state['replace']) else: self.replace.setPlainText(state['replace']) self.case_sensitive.setChecked(state['case_sensitive']) self.dot_all.setChecked(state['dot_all']) def emit_done(self): self.done.emit(True) def keyPressEvent(self, ev): if ev.key() == Qt.Key.Key_Escape: self.abort_editing() ev.accept() return return QFrame.keyPressEvent(self, ev) def abort_editing(self): self.done.emit(False) @property def current_search(self): search = self.search.copy() f = str(self.find.toPlainText()) search['find'] = f search['dot_all'] = bool(self.dot_all.isChecked()) search['case_sensitive'] = bool(self.case_sensitive.isChecked()) search['mode'] = self.mode_box.mode if search['mode'] == 'function': r = self.function.text() else: r = str(self.replace.toPlainText()) search['replace'] = r return search def save_changes(self): searches = tprefs['saved_searches'] all_names = {x['name'] for x in searches} - {self.original_name} n = self.search_name.text().strip() if not n: error_dialog(self, _('Must specify name'), _( 'You must specify a search name'), show=True) return False if n in all_names: error_dialog(self, _('Name exists'), _( 'Another search with the name %s already exists') % n, show=True) return False search = self.search search['name'] = n f = str(self.find.toPlainText()) if not f: error_dialog(self, _('Must specify find'), _( 'You must specify a find expression'), show=True) return False search['find'] = f search['mode'] = self.mode_box.mode if search['mode'] == 'function': r = self.function.text() if not r: error_dialog(self, _('Must specify function'), _( 'You must specify a function name in Function-Regex mode'), show=True) return False else: r = str(self.replace.toPlainText()) search['replace'] = r search['dot_all'] = bool(self.dot_all.isChecked()) search['case_sensitive'] = bool(self.case_sensitive.isChecked()) if self.search_index == -1: searches.append(search) else: searches[self.search_index] = search tprefs.set('saved_searches', searches) return True # }}} class SearchDelegate(QStyledItemDelegate): def sizeHint(self, *args): ans = QStyledItemDelegate.sizeHint(self, *args) ans.setHeight(ans.height() + 4) return ans class SavedSearches(QWidget): run_saved_searches = pyqtSignal(object, object) copy_search_to_search_panel = pyqtSignal(object) def __init__(self, parent=None): QWidget.__init__(self, parent) self.setup_ui() def setup_ui(self): self.l = l = QVBoxLayout(self) self.filter_text = ft = QLineEdit(self) ft.setClearButtonEnabled(True) ft.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Fixed) ft.textChanged.connect(self.do_filter) ft.setPlaceholderText(_('Filter displayed searches')) l.addWidget(ft) self.h2 = h = QHBoxLayout() self.searches = searches = QListView(self) self.stack = stack = QStackedLayout() self.main_widget = mw = QWidget(self) stack.addWidget(mw) self.edit_search_widget = es = EditSearch(self) es.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred) stack.addWidget(es) es.done.connect(self.search_editing_done) mw.v = QVBoxLayout(mw) mw.v.setContentsMargins(0, 0, 0, 0) mw.v.addWidget(searches) searches.doubleClicked.connect(self.edit_search) self.model = SearchesModel(self.searches) self.model.dataChanged.connect(self.show_details) searches.setModel(self.model) searches.selectionModel().currentChanged.connect(self.show_details) searches.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) self.delegate = SearchDelegate(searches) searches.setItemDelegate(self.delegate) searches.setAlternatingRowColors(True) searches.setDragEnabled(True), searches.setAcceptDrops(True), searches.setDragDropMode(QAbstractItemView.DragDropMode.InternalMove) searches.setDropIndicatorShown(True) h.addLayout(stack, stretch=10) self.v = v = QVBoxLayout() h.addLayout(v) l.addLayout(h) stack.currentChanged.connect(self.stack_current_changed) def pb(text, tooltip=None, action=None): b = AnimatablePushButton(text, self) b.setToolTip(tooltip or '') if action: b.setObjectName(action) b.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed) return b mulmsg = '\n\n' + _('The entries are tried in order until the first one matches.') self.action_button_map = {} for text, action, tooltip in [ (_('&Find'), 'find', _('Run the search using the selected entries.') + mulmsg), (_('&Replace'), 'replace', _('Run replace using the selected entries.') + mulmsg), (_('Replace a&nd Find'), 'replace-find', _('Run replace and then find using the selected entries.') + mulmsg), (_('Replace &all'), 'replace-all', _('Run Replace all for all selected entries in the order selected')), (_('&Count all'), 'count', _('Run Count all for all selected entries')), ]: self.action_button_map[action] = b = pb(text, tooltip, action) v.addWidget(b) connect_lambda(b.clicked, self, lambda self: self.run_search(self.sender().objectName())) self.d1 = d = QFrame(self) d.setFrameStyle(QFrame.Shape.HLine) v.addWidget(d) self.h3 = h = QHBoxLayout() self.upb = b = QToolButton(self) self.move_up_action = a = QAction(self) a.setShortcut(QKeySequence('Alt+Up')) b.setIcon(QIcon.ic('arrow-up.png')) b.setToolTip(_('Move selected entries up') + ' [%s]' % a.shortcut().toString(QKeySequence.SequenceFormat.NativeText)) connect_lambda(a.triggered, self, lambda self: self.move_entry(-1)) self.searches.addAction(a) connect_lambda(b.clicked, self, lambda self: self.move_entry(-1)) self.dnb = b = QToolButton(self) self.move_down_action = a = QAction(self) a.setShortcut(QKeySequence('Alt+Down')) b.setIcon(QIcon.ic('arrow-down.png')) b.setToolTip(_('Move selected entries down') + ' [%s]' % a.shortcut().toString(QKeySequence.SequenceFormat.NativeText)) connect_lambda(a.triggered, self, lambda self: self.move_entry(1)) self.searches.addAction(a) connect_lambda(b.clicked, self, lambda self: self.move_entry(1)) h.addWidget(self.upb), h.addWidget(self.dnb) v.addLayout(h) self.eb = b = pb(_('&Edit search'), _('Edit the currently selected search')) b.clicked.connect(self.edit_search) v.addWidget(b) self.rb = b = pb(_('Re&move search'), _('Remove the currently selected searches')) b.clicked.connect(self.remove_search) v.addWidget(b) self.ab = b = pb(_('&Add search'), _('Add a new saved search')) b.clicked.connect(self.add_search) v.addWidget(b) self.d2 = d = QFrame(self) d.setFrameStyle(QFrame.Shape.HLine) v.addWidget(d) self.where_box = wb = WhereBox(self, emphasize=True) self.where = SearchWidget.DEFAULT_STATE['where'] v.addWidget(wb) self.direction_box = db = DirectionBox(self) self.direction = SearchWidget.DEFAULT_STATE['direction'] v.addWidget(db) self.wr = wr = QCheckBox(_('&Wrap')) wr.setToolTip('<p>'+_('When searching reaches the end, wrap around to the beginning and continue the search')) self.wr.setChecked(SearchWidget.DEFAULT_STATE['wrap']) v.addWidget(wr) self.d3 = d = QFrame(self) d.setFrameStyle(QFrame.Shape.HLine) v.addWidget(d) self.description = d = SearchDescription(self) mw.v.addWidget(d) mw.v.setStretch(0, 10) self.ib = b = pb(_('&Import'), _('Import saved searches')) b.clicked.connect(self.import_searches) v.addWidget(b) self.eb2 = b = pb(_('E&xport'), _('Export saved searches')) v.addWidget(b) self.em = m = QMenu(_('Export')) m.addAction(_('Export all'), lambda : QTimer.singleShot(0, partial(self.export_searches, all=True))) m.addAction(_('Export selected'), lambda : QTimer.singleShot(0, partial(self.export_searches, all=False))) m.addAction(_('Copy to search panel'), lambda : QTimer.singleShot(0, self.copy_to_search_panel)) b.setMenu(m) self.searches.setFocus(Qt.FocusReason.OtherFocusReason) @property def state(self): return {'wrap':self.wrap, 'direction':self.direction, 'where':self.where} @state.setter def state(self, val): self.wrap, self.where, self.direction = val['wrap'], val['where'], val['direction'] def save_state(self): tprefs['saved_seaches_state'] = self.state def restore_state(self): self.state = tprefs.get('saved_seaches_state', SearchWidget.DEFAULT_STATE) def has_focus(self): if self.hasFocus(): return True for child in self.findChildren(QWidget): if child.hasFocus(): return True return False def trigger_action(self, action, overrides=None): b = self.action_button_map.get(action) if b is not None: b.animate_click(300) self._run_search(action, overrides) def stack_current_changed(self, index): visible = index == 0 for x in ('eb', 'ab', 'rb', 'upb', 'dnb', 'd2', 'filter_text', 'd3', 'ib', 'eb2'): getattr(self, x).setVisible(visible) @property def where(self): return self.where_box.where @where.setter def where(self, val): self.where_box.where = val @property def direction(self): return self.direction_box.direction @direction.setter def direction(self, val): self.direction_box.direction = val @property def wrap(self): return self.wr.isChecked() @wrap.setter def wrap(self, val): self.wr.setChecked(bool(val)) def do_filter(self, text): self.model.do_filter(text) self.searches.scrollTo(self.model.index(0)) def run_search(self, action): return self._run_search(action) def _run_search(self, action, overrides=None): searches = [] def fill_in_search(search): search['wrap'] = self.wrap search['direction'] = self.direction search['where'] = self.where search['mode'] = search.get('mode', 'regex') if self.editing_search: search = SearchWidget.DEFAULT_STATE.copy() del search['mode'] search.update(self.edit_search_widget.current_search) fill_in_search(search) searches.append(search) else: seen = set() for index in self.searches.selectionModel().selectedIndexes(): if index.row() in seen: continue seen.add(index.row()) search = SearchWidget.DEFAULT_STATE.copy() del search['mode'] search_index, s = index.data(Qt.ItemDataRole.UserRole) search.update(s) fill_in_search(search) searches.append(search) if not searches: return error_dialog(self, _('Cannot search'), _( 'No saved search is selected'), show=True) if overrides: [sc.update(overrides) for sc in searches] self.run_saved_searches.emit(searches, action) @property def editing_search(self): return self.stack.currentIndex() != 0 def move_entry(self, delta): if self.editing_search: return sm = self.searches.selectionModel() rows = {index.row() for index in sm.selectedIndexes()} - {-1} if rows: searches = [self.model.search_for_index(index) for index in sm.selectedIndexes()] current_search = self.model.search_for_index(self.searches.currentIndex()) with tprefs: for row in sorted(rows, reverse=delta > 0): self.model.move_entry(row, delta) sm.clear() for s in searches: index = self.model.index_for_search(s) if index.isValid() and index.row() > -1: if s is current_search: sm.setCurrentIndex(index, QItemSelectionModel.SelectionFlag.Select) else: sm.select(index, QItemSelectionModel.SelectionFlag.Select) def search_editing_done(self, save_changes): if save_changes and not self.edit_search_widget.save_changes(): return self.stack.setCurrentIndex(0) if save_changes: if self.edit_search_widget.search_index == -1: self._add_search() else: index = self.searches.currentIndex() if index.isValid(): self.model.dataChanged.emit(index, index) def edit_search(self): index = self.searches.currentIndex() if not index.isValid(): return error_dialog(self, _('Cannot edit'), _( 'Cannot edit search - no search selected.'), show=True) if not self.editing_search: search_index, search = index.data(Qt.ItemDataRole.UserRole) self.edit_search_widget.show_search(search=search, search_index=search_index) self.stack.setCurrentIndex(1) self.edit_search_widget.find.setFocus(Qt.FocusReason.OtherFocusReason) def remove_search(self): if self.editing_search: return if confirm(_('Are you sure you want to permanently delete the selected saved searches?'), 'confirm-remove-editor-saved-search', config_set=tprefs): rows = {index.row() for index in self.searches.selectionModel().selectedIndexes()} - {-1} self.model.remove_searches(rows) self.show_details() def add_search(self): if self.editing_search: return self.edit_search_widget.show_search() self.stack.setCurrentIndex(1) self.edit_search_widget.search_name.setFocus(Qt.FocusReason.OtherFocusReason) def _add_search(self): self.model.add_searches() index = self.model.index(self.model.rowCount() - 1) self.searches.scrollTo(index) sm = self.searches.selectionModel() sm.setCurrentIndex(index, QItemSelectionModel.SelectionFlag.ClearAndSelect) self.show_details() def add_predefined_search(self, state): if self.editing_search: return self.edit_search_widget.show_search(state=state) self.stack.setCurrentIndex(1) self.edit_search_widget.search_name.setFocus(Qt.FocusReason.OtherFocusReason) def show_details(self): self.description.set_text(' \n \n ') i = self.searches.currentIndex() if i.isValid(): try: search_index, search = i.data(Qt.ItemDataRole.UserRole) except TypeError: return # no saved searches cs = '✓' if search.get('case_sensitive', SearchWidget.DEFAULT_STATE['case_sensitive']) else '✗' da = '✓' if search.get('dot_all', SearchWidget.DEFAULT_STATE['dot_all']) else '✗' if search.get('mode', SearchWidget.DEFAULT_STATE['mode']) in ('regex', 'function'): ts = _('(Case sensitive: {0} Dot all: {1})').format(cs, da) else: ts = _('(Case sensitive: {0} [Normal search])').format(cs) self.description.set_text(_('{2} {3}\nFind: {0}\nReplace: {1}').format( search.get('find', ''), search.get('replace', ''), search.get('name', ''), ts)) def import_searches(self): path = choose_files(self, 'import_saved_searches', _('Choose file'), filters=[ (_('Saved searches'), ['json'])], all_files=False, select_only_single_file=True) if path: with open(path[0], 'rb') as f: obj = json.loads(f.read()) needed_keys = {'name', 'find', 'replace', 'case_sensitive', 'dot_all', 'mode'} def err(): error_dialog(self, _('Invalid data'), _( 'The file %s does not contain valid saved searches') % path, show=True) if not isinstance(obj, dict) or 'version' not in obj or 'searches' not in obj or obj['version'] not in (1,): return err() searches = [] for item in obj['searches']: if not isinstance(item, dict) or not set(item).issuperset(needed_keys): return err searches.append({k:item[k] for k in needed_keys}) if searches: tprefs['saved_searches'] = tprefs['saved_searches'] + searches count = len(searches) self.model.add_searches(count=count) sm = self.searches.selectionModel() top, bottom = self.model.index(self.model.rowCount() - count), self.model.index(self.model.rowCount() - 1) sm.select(QItemSelection(top, bottom), QItemSelectionModel.SelectionFlag.ClearAndSelect) self.searches.scrollTo(bottom) def copy_to_search_panel(self): ci = self.searches.selectionModel().currentIndex() if ci and ci.isValid(): search = ci.data(Qt.ItemDataRole.UserRole)[-1] self.copy_search_to_search_panel.emit(search) def export_searches(self, all=True): if all: searches = copy.deepcopy(tprefs['saved_searches']) if not searches: return error_dialog(self, _('No searches'), _( 'No searches available to be saved'), show=True) else: searches = [] for index in self.searches.selectionModel().selectedIndexes(): search = index.data(Qt.ItemDataRole.UserRole)[-1] searches.append(search.copy()) if not searches: return error_dialog(self, _('No searches'), _( 'No searches selected'), show=True) [s.__setitem__('mode', s.get('mode', 'regex')) for s in searches] path = choose_save_file(self, 'export-saved-searches', _('Choose file'), filters=[ (_('Saved searches'), ['json'])], all_files=False) if path: if not path.lower().endswith('.json'): path += '.json' raw = json.dumps({'version':1, 'searches':searches}, ensure_ascii=False, indent=2, sort_keys=True) with open(path, 'wb') as f: f.write(raw.encode('utf-8')) def validate_search_request(name, searchable_names, has_marked_text, state, gui_parent): err = None where = state['where'] if name is None and where in {'current', 'selected-text'}: err = _('No file is being edited.') elif where == 'selected' and not searchable_names['selected']: err = _('No files are selected in the File browser') elif where == 'selected-text' and not has_marked_text: err = _('No text is marked. First select some text, and then use' ' The "Mark selected text" action in the Search menu to mark it.') if not err and not state['find']: err = _('No search query specified') if err: error_dialog(gui_parent, _('Cannot search'), err, show=True) return False return True class InvalidRegex(regex.error): def __init__(self, raw, e): regex.error.__init__(self, error_message(e)) self.regex = raw def get_search_regex(state): raw = state['find'] is_regex = state['mode'] not in ('normal', 'fuzzy') if not is_regex: if state['mode'] == 'fuzzy': from calibre.gui2.viewer.search import text_to_regex raw = text_to_regex(raw) else: raw = regex.escape(raw, special_only=True) flags = REGEX_FLAGS if not state['case_sensitive']: flags |= regex.IGNORECASE if is_regex and state['dot_all']: flags |= regex.DOTALL if state['direction'] == 'up': flags |= regex.REVERSE try: ans = compile_regular_expression(raw, flags=flags) except regex.error as e: raise InvalidRegex(raw, e) return ans def get_search_function(state): ans = state['replace'] is_regex = state['mode'] not in ('normal', 'fuzzy') if not is_regex: # We dont want backslash escape sequences interpreted in normal mode return lambda m: ans if state['mode'] == 'function': try: return replace_functions()[ans] except KeyError: if not ans: return Function('empty-function', '') raise NoSuchFunction(ans) return ans def get_search_name(state): return state.get('name', state['find']) def initialize_search_request(state, action, current_editor, current_editor_name, searchable_names): editor = None where = state['where'] files = OrderedDict() do_all = state.get('wrap') or action in {'replace-all', 'count'} marked = False if where == 'current': editor = current_editor elif where in {'styles', 'text', 'selected', 'open'}: files = searchable_names[where] if current_editor_name in files: # Start searching in the current editor editor = current_editor # Re-order the list of other files so that we search in the same # order every time. Depending on direction, search the files # that come after the current file, or before the current file, # first. lfiles = list(files) idx = lfiles.index(current_editor_name) before, after = lfiles[:idx], lfiles[idx+1:] if state['direction'] == 'up': lfiles = list(reversed(before)) if do_all: lfiles += list(reversed(after)) + [current_editor_name] else: lfiles = after if do_all: lfiles += before + [current_editor_name] files = OrderedDict((m, files[m]) for m in lfiles) else: editor = current_editor marked = True return editor, where, files, do_all, marked class NoSuchFunction(ValueError): pass def show_function_debug_output(func): if isinstance(func, Function): val = func.debug_buf.getvalue().strip() func.debug_buf.truncate(0) if val: from calibre.gui2.tweak_book.boss import get_boss get_boss().gui.sr_debug_output.show_log(func.name, val) def reorder_files(names, order): reverse = order in {'spine-reverse', 'reverse-spine'} spine_order = {name:i for i, (name, is_linear) in enumerate(current_container().spine_names)} return sorted(frozenset(names), key=spine_order.get, reverse=reverse) def run_search( searches, action, current_editor, current_editor_name, searchable_names, gui_parent, show_editor, edit_file, show_current_diff, add_savepoint, rewind_savepoint, set_modified): if isinstance(searches, dict): searches = [searches] editor, where, files, do_all, marked = initialize_search_request(searches[0], action, current_editor, current_editor_name, searchable_names) wrap = searches[0]['wrap'] errfind = searches[0]['find'] if len(searches) > 1: errfind = _('the selected searches') search_names = [get_search_name(search) for search in searches] try: searches = [(get_search_regex(search), get_search_function(search)) for search in searches] except InvalidRegex as e: return error_dialog(gui_parent, _('Invalid regex'), '<p>' + _( 'The regular expression you entered is invalid: <pre>{0}</pre>With error: {1}').format( prepare_string_for_xml(e.regex), error_message(e)), show=True) except NoSuchFunction as e: return error_dialog(gui_parent, _('No such function'), '<p>' + _( 'No replace function with the name: %s exists') % prepare_string_for_xml(error_message(e)), show=True) def no_match(): QApplication.restoreOverrideCursor() msg = '<p>' + _('No matches were found for %s') % ('<pre style="font-style:italic">' + prepare_string_for_xml(errfind) + '</pre>') if not wrap: msg += '<p>' + _('You have turned off search wrapping, so all text might not have been searched.' ' Try the search again, with wrapping enabled. Wrapping is enabled via the' ' "Wrap" checkbox at the bottom of the search panel.') return error_dialog( gui_parent, _('Not found'), msg, show=True) def do_find(): for p, __ in searches: if editor is not None: if editor.find(p, marked=marked, save_match='gui'): return True if wrap and not files and editor.find(p, wrap=True, marked=marked, save_match='gui'): return True for fname, syntax in iteritems(files): ed = editors.get(fname, None) if ed is not None: if not wrap and ed is editor: continue if ed.find(p, complete=True, save_match='gui'): show_editor(fname) return True else: raw = current_container().raw_data(fname) if p.search(raw) is not None: edit_file(fname, syntax) if editors[fname].find(p, complete=True, save_match='gui'): return True return no_match() def no_replace(prefix=''): QApplication.restoreOverrideCursor() if prefix: prefix += ' ' error_dialog( gui_parent, _('Cannot replace'), prefix + _( 'You must first click "Find", before trying to replace'), show=True) return False def do_replace(): if editor is None: return no_replace() for p, repl in searches: repl_is_func = isinstance(repl, Function) if repl_is_func: repl.init_env(current_editor_name) if editor.replace(p, repl, saved_match='gui'): if repl_is_func: repl.end() show_function_debug_output(repl) return True return no_replace(_( 'Currently selected text does not match the search query.')) def count_message(replaced, count, show_diff=False, show_dialog=True, count_map=None): if show_dialog: if replaced: msg = _('Performed the replacement at {num} occurrences of {query}') else: msg = _('Found {num} occurrences of {query}') msg = msg.format(num=count, query=prepare_string_for_xml(errfind)) det_msg = '' if count_map is not None and count > 0 and len(count_map) > 1: for k in sorted(count_map): det_msg += _('{0}: {1} occurrences').format(k, count_map[k]) + '\n' if show_diff and count > 0: d = MessageBox(MessageBox.INFO, _('Searching done'), '<p>'+msg, parent=gui_parent, show_copy_button=False, det_msg=det_msg) d.diffb = b = d.bb.addButton(_('See what &changed'), QDialogButtonBox.ButtonRole.AcceptRole) d.show_changes = False b.setIcon(QIcon.ic('diff.png')), b.clicked.connect(d.accept) connect_lambda(b.clicked, d, lambda d: setattr(d, 'show_changes', True)) d.exec() if d.show_changes: show_current_diff(allow_revert=True) else: info_dialog(gui_parent, _('Searching done'), prepare_string_for_xml(msg), show=True, det_msg=det_msg) def do_all(replace=True): count = 0 count_map = Counter() if not files and editor is None: return 0 lfiles = files or {current_editor_name:editor.syntax} updates = set() raw_data = {} for n in lfiles: if n in editors: raw = editors[n].get_raw_data() else: raw = current_container().raw_data(n) raw_data[n] = raw for search_name, (p, repl) in zip(search_names, searches): repl_is_func = isinstance(repl, Function) file_iterator = lfiles if repl_is_func: repl.init_env() if repl.file_order is not None and len(lfiles) > 1: file_iterator = reorder_files(file_iterator, repl.file_order) for n in file_iterator: raw = raw_data[n] if replace: if repl_is_func: repl.context_name = n raw, num = p.subn(repl, raw) if num > 0: updates.add(n) raw_data[n] = raw else: num = len(p.findall(raw)) count += num count_map[search_name] += num if repl_is_func: repl.end() show_function_debug_output(repl) for n in updates: raw = raw_data[n] if n in editors: editors[n].replace_data(raw) else: try: with current_container().open(n, 'wb') as f: f.write(raw.encode('utf-8')) except PermissionError: if not iswindows: raise time.sleep(2) with current_container().open(n, 'wb') as f: f.write(raw.encode('utf-8')) QApplication.restoreOverrideCursor() count_message(replace, count, show_diff=replace, count_map=count_map) return count with BusyCursor(): if action == 'find': return do_find() if action == 'replace': return do_replace() if action == 'replace-find' and do_replace(): return do_find() if action == 'replace-all': if marked: show_result_dialog = True for p, repl in searches: if getattr(getattr(repl, 'func', None), 'suppress_result_dialog', False): show_result_dialog = False break return count_message(True, sum(editor.all_in_marked(p, repl) for p, repl in searches), show_dialog=show_result_dialog) add_savepoint(_('Before: Replace all')) count = do_all() if count == 0: rewind_savepoint() else: set_modified() return if action == 'count': if marked: return count_message(False, sum(editor.all_in_marked(p) for p, __ in searches)) return do_all(replace=False) if __name__ == '__main__': app = QApplication([]) d = SavedSearches() d.show() app.exec()
61,617
Python
.py
1,377
34.738562
149
0.603644
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,702
toc.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/toc.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' from time import monotonic from qt.core import ( QAction, QApplication, QDialog, QDialogButtonBox, QGridLayout, QIcon, QMenu, QSize, QStackedWidget, QStyledItemDelegate, Qt, QTimer, QTreeWidget, QTreeWidgetItem, QVBoxLayout, QWidget, pyqtSignal, ) from calibre.constants import ismacos from calibre.ebooks.oeb.polish.toc import commit_toc, get_toc from calibre.gui2 import error_dialog, info_dialog, make_view_use_window_background from calibre.gui2.toc.main import ItemEdit, TOCView from calibre.gui2.tweak_book import TOP, actions, current_container, tprefs from calibre_extensions.progress_indicator import set_no_activate_on_click class TOCEditor(QDialog): explode_done = pyqtSignal(object) writing_done = pyqtSignal(object) def __init__(self, title=None, parent=None): QDialog.__init__(self, parent) self.last_reject_at = self.last_accept_at = -1000 t = title or current_container().mi.title self.book_title = t self.setWindowTitle(_('Edit the ToC in %s')%t) self.setWindowIcon(QIcon.ic('toc.png')) l = self.l = QVBoxLayout() self.setLayout(l) self.stacks = s = QStackedWidget(self) l.addWidget(s) self.toc_view = TOCView(self, tprefs) self.toc_view.add_new_item.connect(self.add_new_item) s.addWidget(self.toc_view) self.item_edit = ItemEdit(self, tprefs) s.addWidget(self.item_edit) bb = self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel) l.addWidget(bb) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) self.undo_button = b = bb.addButton(_('&Undo'), QDialogButtonBox.ButtonRole.ActionRole) b.setToolTip(_('Undo the last action, if any')) b.setIcon(QIcon.ic('edit-undo.png')) b.clicked.connect(self.toc_view.undo) self.read_toc() self.restore_geometry(tprefs, 'toc_editor_window_geom') def sizeHint(self): return QSize(950, 630) def add_new_item(self, item, where): self.item_edit(item, where) self.stacks.setCurrentIndex(1) if ismacos: QTimer.singleShot(0, self.workaround_macos_mouse_with_webview_bug) def workaround_macos_mouse_with_webview_bug(self): # macOS is weird: https://bugs.launchpad.net/calibre/+bug/2004639 # needed as of Qt 6.4.2 d = info_dialog(self, _('Loading...'), _('Loading table of contents view, please wait...'), show_copy_button=False) QTimer.singleShot(0, d.reject) d.exec() def accept(self): if monotonic() - self.last_accept_at < 1: return self.last_accept_at = monotonic() if self.stacks.currentIndex() == 1: self.toc_view.update_item(*self.item_edit.result) tprefs['toc_edit_splitter_state'] = bytearray(self.item_edit.splitter.saveState()) self.stacks.setCurrentIndex(0) elif self.stacks.currentIndex() == 0: self.write_toc() self.save_geometry(tprefs, 'toc_editor_window_geom') super().accept() def really_accept(self, tb): self.save_geometry(tprefs, 'toc_editor_window_geom') if tb: error_dialog(self, _('Failed to write book'), _('Could not write %s. Click "Show details" for' ' more information.')%self.book_title, det_msg=tb, show=True) super().reject() return super().accept() def reject(self): if not self.bb.isEnabled(): return if monotonic() - self.last_reject_at < 1: return self.last_reject_at = monotonic() if self.stacks.currentIndex() == 1: tprefs['toc_edit_splitter_state'] = bytearray(self.item_edit.splitter.saveState()) self.stacks.setCurrentIndex(0) else: self.save_geometry(tprefs, 'toc_editor_window_geom') super().reject() def read_toc(self): self.toc_view(current_container()) self.item_edit.load(current_container()) self.stacks.setCurrentIndex(0) def write_toc(self): toc = self.toc_view.create_toc() toc.toc_title = getattr(self.toc_view, 'toc_title', None) commit_toc(current_container(), toc, lang=self.toc_view.toc_lang, uid=self.toc_view.toc_uid) DEST_ROLE = Qt.ItemDataRole.UserRole FRAG_ROLE = DEST_ROLE + 1 class Delegate(QStyledItemDelegate): def sizeHint(self, *args): ans = QStyledItemDelegate.sizeHint(self, *args) return ans + QSize(0, 10) class TOCViewer(QWidget): navigate_requested = pyqtSignal(object, object) refresh_requested = pyqtSignal() def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QGridLayout(self) self.toc_title = None self.setLayout(l) l.setContentsMargins(0, 0, 0, 0) self.view = make_view_use_window_background(QTreeWidget(self)) self.delegate = Delegate(self.view) self.view.setItemDelegate(self.delegate) self.view.setHeaderHidden(True) self.view.setAnimated(True) self.view.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.view.customContextMenuRequested.connect(self.show_context_menu, type=Qt.ConnectionType.QueuedConnection) self.view.itemActivated.connect(self.emit_navigate) self.view.itemPressed.connect(self.item_pressed) set_no_activate_on_click(self.view) self.view.itemDoubleClicked.connect(self.emit_navigate) l.addWidget(self.view) self.refresh_action = QAction(QIcon.ic('view-refresh.png'), _('&Refresh'), self) self.refresh_action.triggered.connect(self.refresh) self.refresh_timer = t = QTimer(self) t.setInterval(1000), t.setSingleShot(True) t.timeout.connect(self.auto_refresh) self.toc_name = None self.currently_editing = None def start_refresh_timer(self, name): if self.isVisible() and self.toc_name == name: self.refresh_timer.start() def auto_refresh(self): if self.isVisible(): try: self.refresh() except Exception: # ignore errors during live refresh of the toc import traceback traceback.print_exc() def refresh(self): self.refresh_requested.emit() # Give boss a chance to commit dirty editors to the container self.build() def item_pressed(self, item): if QApplication.mouseButtons() & Qt.MouseButton.LeftButton: QTimer.singleShot(0, self.emit_navigate) def show_context_menu(self, pos): menu = QMenu(self) menu.addAction(actions['edit-toc']) menu.addAction(QIcon.ic('plus.png'), _('&Expand all'), self.view.expandAll) menu.addAction(QIcon.ic('minus.png'), _('&Collapse all'), self.view.collapseAll) menu.addAction(self.refresh_action) menu.exec(self.view.mapToGlobal(pos)) def iter_items(self, parent=None): if parent is None: parent = self.invisibleRootItem() for i in range(parent.childCount()): child = parent.child(i) yield child yield from self.iter_items(parent=child) def emit_navigate(self, *args): item = self.view.currentItem() if item is not None: dest = str(item.data(0, DEST_ROLE) or '') frag = str(item.data(0, FRAG_ROLE) or '') if not frag: frag = TOP self.navigate_requested.emit(dest, frag) def build(self): c = current_container() if c is None: return toc = get_toc(c, verify_destinations=False) self.toc_name = getattr(toc, 'toc_file_name', None) self.toc_title = toc.toc_title def process_node(toc, parent): for child in toc: node = QTreeWidgetItem(parent) node.setText(0, child.title or '') node.setData(0, DEST_ROLE, child.dest or '') node.setData(0, FRAG_ROLE, child.frag or '') tt = _('File: {0}\nAnchor: {1}').format( child.dest or '', child.frag or _('Top of file')) node.setData(0, Qt.ItemDataRole.ToolTipRole, tt) process_node(child, node) self.view.clear() process_node(toc, self.view.invisibleRootItem()) def showEvent(self, ev): if self.toc_name is None or not ev.spontaneous(): self.build() return super().showEvent(ev) def update_if_visible(self): if self.isVisible(): self.build()
8,968
Python
.py
212
33.264151
123
0.63054
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,703
reports.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/reports.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>' import os import textwrap import time from collections import defaultdict from contextlib import suppress from csv import writer as csv_writer from functools import lru_cache, partial from io import StringIO from operator import itemgetter from threading import Thread import regex from qt.core import ( QAbstractItemModel, QAbstractItemView, QAbstractTableModel, QApplication, QByteArray, QComboBox, QDialogButtonBox, QFont, QFontDatabase, QHBoxLayout, QIcon, QLabel, QLineEdit, QListWidget, QListWidgetItem, QMenu, QModelIndex, QPalette, QPixmap, QRadioButton, QRect, QSize, QSortFilterProxyModel, QSplitter, QStackedLayout, QStackedWidget, QStyle, QStyledItemDelegate, Qt, QTableView, QTextCursor, QTimer, QTreeView, QUrl, QVBoxLayout, QWidget, pyqtSignal, ) from calibre import fit_image, human_readable from calibre.constants import DEBUG from calibre.ebooks.oeb.polish.report import ClassElement, ClassEntry, ClassFileMatch, CSSEntry, CSSFileMatch, CSSRule, LinkLocation, MatchLocation, gather_data from calibre.gui2 import choose_save_file, error_dialog, open_url, question_dialog from calibre.gui2.progress_indicator import ProgressIndicator from calibre.gui2.tweak_book import current_container, dictionaries, tprefs from calibre.gui2.tweak_book.widgets import Dialog from calibre.gui2.webengine import RestartingWebEngineView from calibre.utils.icu import numeric_sort_key, primary_contains from calibre.utils.localization import calibre_langcode_to_name, canonicalize_lang from calibre.utils.unicode_names import character_name_from_code from calibre.utils.webengine import secure_webengine from polyglot.builtins import as_bytes, iteritems # Utils {{{ ROOT = QModelIndex() def psk(x): return QByteArray(numeric_sort_key(x)) def read_state(name, default=None): data = tprefs.get('reports-ui-state') if data is None: tprefs['reports-ui-state'] = data = {} return data.get(name, default) def save_state(name, val): data = tprefs.get('reports-ui-state') if isinstance(val, QByteArray): val = bytearray(val) if data is None: tprefs['reports-ui-state'] = data = {} data[name] = val SORT_ROLE = Qt.ItemDataRole.UserRole + 1 class ProxyModel(QSortFilterProxyModel): def __init__(self, parent=None): QSortFilterProxyModel.__init__(self, parent) self._filter_text = None self.setSortRole(SORT_ROLE) def filter_text(self, text): self._filter_text = text self.setFilterFixedString(text) def filterAcceptsRow(self, row, parent): if not self._filter_text: return True sm = self.sourceModel() for item in (sm.data(sm.index(row, c, parent)) or '' for c in range(sm.columnCount())): if item and primary_contains(self._filter_text, item): return True return False def headerData(self, section, orientation, role=Qt.ItemDataRole.DisplayRole): if orientation == Qt.Orientation.Vertical and role == Qt.ItemDataRole.DisplayRole: return section + 1 return QSortFilterProxyModel.headerData(self, section, orientation, role) class FileCollection(QAbstractTableModel): COLUMN_HEADERS = () alignments = () def __init__(self, parent=None): self.files = self.sort_keys = () self.total_size = 0 QAbstractTableModel.__init__(self, parent) def columnCount(self, parent=None): return len(self.COLUMN_HEADERS) def rowCount(self, parent=None): return len(self.files) def headerData(self, section, orientation, role=Qt.ItemDataRole.DisplayRole): if orientation == Qt.Orientation.Horizontal: if role == Qt.ItemDataRole.DisplayRole: with suppress(IndexError): return self.COLUMN_HEADERS[section] elif role == Qt.ItemDataRole.TextAlignmentRole: with suppress(IndexError): return int(self.alignments[section]) # https://bugreports.qt.io/browse/PYSIDE-1974 return QAbstractTableModel.headerData(self, section, orientation, role) def location(self, index): try: return self.files[index.row()].name except (IndexError, AttributeError): pass class FilesView(QTableView): double_clicked = pyqtSignal(object) delete_requested = pyqtSignal(object, object) current_changed = pyqtSignal(object, object) DELETE_POSSIBLE = True def __init__(self, model, parent=None): QTableView.__init__(self, parent) self.setProperty('highlight_current_item', 150) self.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows) self.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) self.setAlternatingRowColors(True) self.setSortingEnabled(True) self.proxy = p = ProxyModel(self) p.setSourceModel(model) self.setModel(p) self.doubleClicked.connect(self._double_clicked) self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.customContextMenuRequested.connect(self.show_context_menu) def currentChanged(self, current, previous): QTableView.currentChanged(self, current, previous) self.current_changed.emit(*map(self.proxy.mapToSource, (current, previous))) def customize_context_menu(self, menu, selected_locations, current_location): pass def resize_rows(self): if self.model().rowCount() > 0: num = min(5, self.model().rowCount()) h = 1000000 for i in range(num): self.resizeRowToContents(i) h = min(h, self.rowHeight(i)) self.verticalHeader().setDefaultSectionSize(h) def _double_clicked(self, index): index = self.proxy.mapToSource(index) if index.isValid(): self.double_clicked.emit(index) def keyPressEvent(self, ev): if self.DELETE_POSSIBLE and ev.key() == Qt.Key.Key_Delete: self.delete_selected() ev.accept() return return QTableView.keyPressEvent(self, ev) @property def selected_locations(self): return list(filter(None, (self.proxy.sourceModel().location(self.proxy.mapToSource(index)) for index in self.selectionModel().selectedIndexes()))) @property def current_location(self): index = self.selectionModel().currentIndex() return self.proxy.sourceModel().location(self.proxy.mapToSource(index)) def delete_selected(self): if self.DELETE_POSSIBLE: locations = self.selected_locations if locations: names = frozenset(locations) spine_names = {n for n, l in current_container().spine_names} other_items = names - spine_names spine_items = [(name, name in names) for name, is_linear in current_container().spine_names] self.delete_requested.emit(spine_items, other_items) def show_context_menu(self, pos): pos = self.viewport().mapToGlobal(pos) locations = self.selected_locations m = QMenu(self) if locations: m.addAction(_('Delete selected files'), self.delete_selected) self.customize_context_menu(m, locations, self.current_location) if len(m.actions()) > 0: m.exec(pos) def to_csv(self): buf = StringIO(newline='') w = csv_writer(buf) w.writerow(self.proxy.sourceModel().COLUMN_HEADERS) cols = self.proxy.columnCount() for r in range(self.proxy.rowCount()): items = [self.proxy.index(r, c).data(Qt.ItemDataRole.DisplayRole) for c in range(cols)] w.writerow(items) return buf.getvalue() def save_table(self, name): save_state(name, bytearray(self.horizontalHeader().saveState())) def restore_table(self, name, sort_column=0, sort_order=Qt.SortOrder.AscendingOrder): h = self.horizontalHeader() try: h.restoreState(read_state(name)) except TypeError: self.sortByColumn(sort_column, sort_order) h.setSectionsMovable(True), h.setSectionsClickable(True) h.setDragEnabled(True), h.setAcceptDrops(True) h.setDragDropMode(QAbstractItemView.DragDropMode.InternalMove) # }}} # Files {{{ class FilesModel(FileCollection): COLUMN_HEADERS = (_('Folder'), _('Name'), _('Size (KB)'), _('Type'), _('Word count')) alignments = Qt.AlignmentFlag.AlignLeft, Qt.AlignmentFlag.AlignLeft, Qt.AlignmentFlag.AlignRight, Qt.AlignmentFlag.AlignLeft, Qt.AlignmentFlag.AlignRight CATEGORY_NAMES = { 'image':_('Image'), 'text': _('Text'), 'font': _('Font'), 'style': _('Style'), 'opf': _('Metadata'), 'toc': _('Table of Contents'), } def __init__(self, parent=None): FileCollection.__init__(self, parent) self.images_size = self.fonts_size = 0 def __call__(self, data): self.beginResetModel() self.files = data['files'] self.total_size = sum(map(itemgetter(3), self.files)) self.images_size = sum(map(itemgetter(3), (f for f in self.files if f.category == 'image'))) self.fonts_size = sum(map(itemgetter(3), (f for f in self.files if f.category == 'font'))) self.sort_keys = tuple((psk(entry.dir), psk(entry.basename), entry.size, psk(self.CATEGORY_NAMES.get(entry.category, '')), entry.word_count) for entry in self.files) self.endResetModel() def data(self, index, role=Qt.ItemDataRole.DisplayRole): if role == SORT_ROLE: try: return self.sort_keys[index.row()][index.column()] except IndexError: pass elif role == Qt.ItemDataRole.DisplayRole: col = index.column() try: entry = self.files[index.row()] except IndexError: return None if col == 0: return entry.dir if col == 1: return entry.basename if col == 2: sz = entry.size / 1024. return '%.2f ' % sz if col == 3: return self.CATEGORY_NAMES.get(entry.category) if col == 4: ans = entry.word_count if ans > -1: return str(ans) elif role == Qt.ItemDataRole.TextAlignmentRole: return int(Qt.AlignVCenter | self.alignments[index.column()]) # https://bugreports.qt.io/browse/PYSIDE-1974 class FilesWidget(QWidget): edit_requested = pyqtSignal(object) delete_requested = pyqtSignal(object, object) def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QVBoxLayout(self) self.filter_edit = e = QLineEdit(self) l.addWidget(e) e.setPlaceholderText(_('Filter')) e.setClearButtonEnabled(True) self.model = m = FilesModel(self) self.files = f = FilesView(m, self) self.to_csv = f.to_csv f.delete_requested.connect(self.delete_requested) f.double_clicked.connect(self.double_clicked) e.textChanged.connect(f.proxy.filter_text) l.addWidget(f) self.summary = s = QLabel(self) l.addWidget(s) s.setText('\xa0') self.files.restore_table('all-files-table', 1, Qt.SortOrder.AscendingOrder) def __call__(self, data): self.model(data) self.files.resize_rows() self.filter_edit.clear() m = self.model self.summary.setText(_('Total uncompressed size of all files: {0} :: Images: {1} :: Fonts: {2}').format(*map( human_readable, (m.total_size, m.images_size, m.fonts_size)))) def double_clicked(self, index): location = self.model.location(index) if location is not None: self.edit_requested.emit(location) def save(self): self.files.save_table('all-files-table') # }}} # Jump {{{ def jump_to_location(loc): from calibre.gui2.tweak_book.boss import get_boss boss = get_boss() if boss is None: return name = loc.name editor = boss.edit_file_requested(name) if editor is None: return editor = editor.editor if loc.line_number is not None: block = editor.document().findBlockByNumber(loc.line_number - 1) # blockNumber() is zero based if not block.isValid(): return c = editor.textCursor() c.setPosition(block.position(), QTextCursor.MoveMode.MoveAnchor) editor.setTextCursor(c) if loc.text_on_line is not None: editor.find(regex.compile(regex.escape(loc.text_on_line))) class Jump: def __init__(self): self.pos_map = defaultdict(lambda : -1) def clear(self): self.pos_map.clear() def __call__(self, key, locations): if len(locations): self.pos_map[key] = (self.pos_map[key] + 1) % len(locations) loc = locations[self.pos_map[key]] jump_to_location(loc) jump = Jump() # }}} # Images {{{ class ImagesDelegate(QStyledItemDelegate): MARGIN = 5 def __init__(self, *args): QStyledItemDelegate.__init__(self, *args) def sizeHint(self, option, index): style = (option.styleObject or self.parent() or QApplication.instance()).style() self.initStyleOption(option, index) ans = style.sizeFromContents(QStyle.ContentsType.CT_ItemViewItem, option, QSize(), option.styleObject or self.parent()) entry = index.data(Qt.ItemDataRole.UserRole) if entry is None: return ans th = int(self.parent().thumbnail_height * self.parent().devicePixelRatio()) pmap = self.pixmap(th, entry._replace(usage=()), self.parent().devicePixelRatioF()) if pmap.isNull(): width = height = 0 else: width, height = int(pmap.width() / pmap.devicePixelRatio()), int(pmap.height() / pmap.devicePixelRatio()) m = self.MARGIN * 2 return QSize(max(width + m, ans.width()), height + m + self.MARGIN + ans.height()) def paint(self, painter, option, index): style = (option.styleObject or self.parent() or QApplication.instance()).style() self.initStyleOption(option, index) option.text = '' style.drawControl(QStyle.ControlElement.CE_ItemViewItem, option, painter, option.styleObject or self.parent()) entry = index.data(Qt.ItemDataRole.UserRole) if entry is None: return painter.save() th = int(self.parent().thumbnail_height * self.parent().devicePixelRatio()) pmap = self.pixmap(th, entry._replace(usage=()), painter.device().devicePixelRatioF()) if pmap.isNull(): bottom = option.rect.top() else: m = 2 * self.MARGIN x = option.rect.left() + (option.rect.width() - m - int(pmap.width()/pmap.devicePixelRatio())) // 2 painter.drawPixmap(x, option.rect.top() + self.MARGIN, pmap) bottom = m + int(pmap.height() / pmap.devicePixelRatio()) + option.rect.top() rect = QRect(option.rect.left(), bottom, option.rect.width(), option.rect.bottom() - bottom) if option.state & QStyle.StateFlag.State_Selected: painter.setPen(self.parent().palette().color(QPalette.ColorRole.HighlightedText)) painter.drawText(rect, Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter, entry.basename) painter.restore() @lru_cache(maxsize=1024) def pixmap(self, thumbnail_height, entry, dpr): entry_ok = entry.width > 0 and entry.height > 0 entry_ok |= entry.mime_type == 'image/svg+xml' pmap = QPixmap(current_container().name_to_abspath(entry.name)) if entry_ok > 0 else QPixmap() if not pmap.isNull(): pmap.setDevicePixelRatio(dpr) scaled, width, height = fit_image(pmap.width(), pmap.height(), thumbnail_height, thumbnail_height) if scaled: pmap = pmap.scaled(width, height, transformMode=Qt.TransformationMode.SmoothTransformation) return pmap class ImagesModel(FileCollection): COLUMN_HEADERS = [_('Image'), _('Size (KB)'), _('Times used'), _('Resolution')] alignments = Qt.AlignmentFlag.AlignLeft, Qt.AlignmentFlag.AlignRight, Qt.AlignmentFlag.AlignRight, Qt.AlignmentFlag.AlignRight def __init__(self, parent=None): FileCollection.__init__(self, parent) def __call__(self, data): self.beginResetModel() self.files = data['images'] self.total_size = sum(map(itemgetter(3), self.files)) self.sort_keys = tuple((psk(entry.basename), entry.size, len(entry.usage), (entry.width, entry.height)) for entry in self.files) self.endResetModel() def data(self, index, role=Qt.ItemDataRole.DisplayRole): if role == SORT_ROLE: try: return self.sort_keys[index.row()][index.column()] except IndexError: pass elif role == Qt.ItemDataRole.DisplayRole: col = index.column() try: entry = self.files[index.row()] except IndexError: return None if col == 0: return entry.basename if col == 1: sz = entry.size / 1024. return ('%.2f' % sz if int(sz) != sz else str(sz)) if col == 2: return str(len(entry.usage)) if col == 3: return '%d x %d' % (entry.width, entry.height) elif role == Qt.ItemDataRole.UserRole: try: return self.files[index.row()] except IndexError: pass elif role == Qt.ItemDataRole.TextAlignmentRole: with suppress(IndexError): return int(self.alignments[index.column()]) # https://bugreports.qt.io/browse/PYSIDE-1974 class ImagesWidget(QWidget): edit_requested = pyqtSignal(object) delete_requested = pyqtSignal(object, object) def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QVBoxLayout(self) self.thumbnail_height = 64 self.filter_edit = e = QLineEdit(self) l.addWidget(e) e.setPlaceholderText(_('Filter')) e.setClearButtonEnabled(True) self.model = m = ImagesModel(self) self.files = f = FilesView(m, self) self.to_csv = f.to_csv f.customize_context_menu = self.customize_context_menu f.delete_requested.connect(self.delete_requested) f.horizontalHeader().sortIndicatorChanged.connect(self.resize_to_contents) self.delegate = ImagesDelegate(self) f.setItemDelegateForColumn(0, self.delegate) f.double_clicked.connect(self.double_clicked) e.textChanged.connect(f.proxy.filter_text) l.addWidget(f) self.files.restore_table('image-files-table') def __call__(self, data): self.model(data) self.filter_edit.clear() self.delegate.pixmap.cache_clear() self.files.resizeRowsToContents() def resize_to_contents(self, *args): QTimer.singleShot(0, self.files.resizeRowsToContents) def double_clicked(self, index): entry = index.data(Qt.ItemDataRole.UserRole) if entry is not None: jump((id(self), entry.id), entry.usage) def customize_context_menu(self, menu, selected_locations, current_location): if current_location is not None: menu.addAction(_('Edit the image: %s') % current_location, partial(self.edit_requested.emit, current_location)) def save(self): self.files.save_table('image-files-table') # }}} # Links {{{ class LinksModel(FileCollection): COLUMN_HEADERS = ['✓', _('Source'), _('Source text'), _('Target'), _('Anchor'), _('Target text')] def __init__(self, parent=None): FileCollection.__init__(self, parent) self.num_bad = 0 def __call__(self, data): self.beginResetModel() self.links = self.files = data['links'] self.total_size = len(self.links) self.num_bad = sum(1 for link in self.links if link.ok is False) self.sort_keys = tuple(( link.ok, psk(link.location.name), psk(link.text or ''), psk(link.href or ''), psk(link.anchor.id or ''), psk(link.anchor.text or '')) for link in self.links) self.endResetModel() def data(self, index, role=Qt.ItemDataRole.DisplayRole): if role == SORT_ROLE: try: return self.sort_keys[index.row()][index.column()] except IndexError: pass elif role == Qt.ItemDataRole.DisplayRole: col = index.column() try: link = self.links[index.row()] except IndexError: return None if col == 0: return {True:'✓', False:'✗'}.get(link.ok) if col == 1: return link.location.name if col == 2: return link.text if col == 3: return link.href if col == 4: return link.anchor.id if col == 5: return link.anchor.text elif role == Qt.ItemDataRole.ToolTipRole: col = index.column() try: link = self.links[index.row()] except IndexError: return None if col == 0: return {True:_('The link destination exists'), False:_('The link destination does not exist')}.get( link.ok, _('The link destination could not be verified')) if col == 2: if link.text: return textwrap.fill(link.text) if col == 5: if link.anchor.text: return textwrap.fill(link.anchor.text) elif role == Qt.ItemDataRole.UserRole: try: return self.links[index.row()] except IndexError: pass class WebView(RestartingWebEngineView): def sizeHint(self): return QSize(600, 200) class LinksWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QVBoxLayout(self) self.filter_edit = e = QLineEdit(self) l.addWidget(e) self.splitter = s = QSplitter(Qt.Orientation.Vertical, self) l.addWidget(s) e.setPlaceholderText(_('Filter')) e.setClearButtonEnabled(True) self.model = m = LinksModel(self) self.links = f = FilesView(m, self) f.DELETE_POSSIBLE = False self.to_csv = f.to_csv f.double_clicked.connect(self.double_clicked) e.textChanged.connect(f.proxy.filter_text) s.addWidget(f) self.links.restore_table('links-table', sort_column=1) self.view = None self.setContextMenuPolicy(Qt.ContextMenuPolicy.NoContextMenu) self.ignore_current_change = False self.current_url = None f.current_changed.connect(self.current_changed) try: s.restoreState(read_state('links-view-splitter')) except TypeError: pass s.setCollapsible(0, False) s.setStretchFactor(0, 10) def __call__(self, data): if self.view is None: self.view = WebView(self) secure_webengine(self.view) self.view.setContextMenuPolicy(Qt.ContextMenuPolicy.NoContextMenu) self.splitter.addWidget(self.view) self.splitter.setCollapsible(1, True) self.ignore_current_change = True self.model(data) self.filter_edit.clear() self.links.resize_rows() self.view.setHtml('<p>'+_( 'Click entries above to see their destination here')) self.ignore_current_change = False def current_changed(self, current, previous): link = current.data(Qt.ItemDataRole.UserRole) if link is None: return url = None if link.is_external: if link.href: frag = ('#' + link.anchor.id) if link.anchor.id else '' url = QUrl(link.href + frag) elif link.anchor.location: path = current_container().name_to_abspath(link.anchor.location.name) if path and os.path.exists(path): url = QUrl.fromLocalFile(path) if link.anchor.id: url.setFragment(link.anchor.id) if url is None: if self.view: self.view.setHtml('<p>' + _('No destination found for this link')) self.current_url = url elif url != self.current_url: self.current_url = url if self.view: self.view.setUrl(url) def double_clicked(self, index): link = index.data(Qt.ItemDataRole.UserRole) if link is None: return if index.column() < 3: # Jump to source jump_to_location(link.location) else: # Jump to destination if link.is_external: if link.href: open_url(link.href) elif link.anchor.location: jump_to_location(link.anchor.location) def save(self): self.links.save_table('links-table') save_state('links-view-splitter', bytearray(self.splitter.saveState())) # }}} # Words {{{ class WordsModel(FileCollection): COLUMN_HEADERS = (_('Word'), _('Language'), _('Times used')) alignments = Qt.AlignmentFlag.AlignLeft, Qt.AlignmentFlag.AlignLeft, Qt.AlignmentFlag.AlignRight total_words = 0 def __call__(self, data): self.beginResetModel() self.total_words, self.files = data['words'] self.total_size = len({entry.locale for entry in self.files}) lsk_cache = {} def locale_sort_key(loc): try: return lsk_cache[loc] except KeyError: lsk_cache[loc] = psk(calibre_langcode_to_name(canonicalize_lang(loc[0])) + (loc[1] or '')) return lsk_cache[loc] self.sort_keys = tuple((psk(entry.word), locale_sort_key(entry.locale), len(entry.usage)) for entry in self.files) self.endResetModel() def data(self, index, role=Qt.ItemDataRole.DisplayRole): if role == SORT_ROLE: try: return self.sort_keys[index.row()][index.column()] except IndexError: pass elif role == Qt.ItemDataRole.DisplayRole: col = index.column() try: entry = self.files[index.row()] except IndexError: return None if col == 0: return entry.word if col == 1: ans = calibre_langcode_to_name(canonicalize_lang(entry.locale.langcode)) or '' if entry.locale.countrycode: ans += ' (%s)' % entry.locale.countrycode return ans if col == 2: return str(len(entry.usage)) elif role == Qt.ItemDataRole.UserRole: try: return self.files[index.row()] except IndexError: pass elif role == Qt.ItemDataRole.TextAlignmentRole: with suppress(IndexError): return int(self.alignments[index.column()]) # https://bugreports.qt.io/browse/PYSIDE-1974 def location(self, index): return None class WordsWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QVBoxLayout(self) self.filter_edit = e = QLineEdit(self) l.addWidget(e) e.setPlaceholderText(_('Filter')) e.setClearButtonEnabled(True) self.model = m = WordsModel(self) self.words = f = FilesView(m, self) self.to_csv = f.to_csv f.DELETE_POSSIBLE = False f.double_clicked.connect(self.double_clicked) e.textChanged.connect(f.proxy.filter_text) l.addWidget(f) self.summary = la = QLabel('\xa0') l.addWidget(la) self.words.restore_table('words-table') def __call__(self, data): self.model(data) self.words.resize_rows() self.filter_edit.clear() self.summary.setText(_('Words: {2} :: Unique Words: :: {0} :: Languages: {1}').format( self.model.rowCount(), self.model.total_size, self.model.total_words)) def double_clicked(self, index): entry = index.data(Qt.ItemDataRole.UserRole) if entry is not None: from calibre.gui2.tweak_book.boss import get_boss boss = get_boss() if boss is not None: boss.find_word((entry.word, entry.locale), entry.usage) def save(self): self.words.save_table('words-table') # }}} # Characters {{{ class CharsModel(FileCollection): COLUMN_HEADERS = (_('Character'), _('Name'), _('Codepoint'), _('Times used')) alignments = Qt.AlignmentFlag.AlignLeft, Qt.AlignmentFlag.AlignLeft, Qt.AlignmentFlag.AlignLeft, Qt.AlignmentFlag.AlignRight all_chars = () def __call__(self, data): self.beginResetModel() self.files = data['chars'] self.all_chars = tuple(entry.char for entry in self.files) self.sort_keys = tuple((psk(entry.char), None, entry.codepoint, entry.count) for entry in self.files) self.endResetModel() def data(self, index, role=Qt.ItemDataRole.DisplayRole): if role == SORT_ROLE: if index.column() == 1: return self.data(index) try: return self.sort_keys[index.row()][index.column()] except IndexError: pass elif role == Qt.ItemDataRole.DisplayRole: col = index.column() try: entry = self.files[index.row()] except IndexError: return None if col == 0: return entry.char if col == 1: return {0xa:'LINE FEED', 0xd:'CARRIAGE RETURN', 0x9:'TAB'}.get(entry.codepoint, character_name_from_code(entry.codepoint)) if col == 2: return ('U+%04X' if entry.codepoint < 0x10000 else 'U+%06X') % entry.codepoint if col == 3: return str(entry.count) elif role == Qt.ItemDataRole.UserRole: try: return self.files[index.row()] except IndexError: pass elif role == Qt.ItemDataRole.TextAlignmentRole: with suppress(IndexError): return int(self.alignments[index.column()]) # https://bugreports.qt.io/browse/PYSIDE-1974 def location(self, index): return None class CharsWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QVBoxLayout(self) self.filter_edit = e = QLineEdit(self) l.addWidget(e) e.setPlaceholderText(_('Filter')) e.setClearButtonEnabled(True) self.model = m = CharsModel(self) self.chars = f = FilesView(m, self) self.to_csv = f.to_csv f.DELETE_POSSIBLE = False f.double_clicked.connect(self.double_clicked) e.textChanged.connect(f.proxy.filter_text) l.addWidget(f) self.summary = la = QLineEdit(self) la.setReadOnly(True) la.setToolTip(_('All the characters in the book')) l.addWidget(la) self.chars.restore_table('chars-table') def __call__(self, data): self.model(data) self.chars.resize_rows() self.summary.setText(''.join(self.model.all_chars)) self.filter_edit.clear() def double_clicked(self, index): entry = index.data(Qt.ItemDataRole.UserRole) if entry is not None: self.find_next_location(entry) def save(self): self.chars.save_table('chars-table') def find_next_location(self, entry): from calibre.gui2.tweak_book.boss import get_boss boss = get_boss() if boss is None: return files = entry.usage current_editor_name = boss.currently_editing if current_editor_name not in files: current_editor_name = None else: idx = files.index(current_editor_name) before, after = files[:idx], files[idx+1:] files = [current_editor_name] + after + before + [current_editor_name] pat = regex.compile(regex.escape(entry.char)) for file_name in files: from_cursor = False if file_name == current_editor_name: from_cursor = True current_editor_name = None ed = boss.edit_file_requested(file_name) if ed is None: return if ed.editor.find_text(pat, complete=not from_cursor): boss.show_editor(file_name) return True return False # }}} # CSS {{{ class CSSRulesModel(QAbstractItemModel): def __init__(self, parent): QAbstractItemModel.__init__(self, parent) self.rules = () self.sort_on_count = True self.num_size = 1 self.num_unused = 0 self.build_maps() self.main_font = f = QFontDatabase.systemFont(QFontDatabase.SystemFont.FixedFont) f.setBold(True), f.setPointSize(parent.font().pointSize() + 2) self.italic_font = f = QFont(parent.font()) f.setItalic(True) def build_maps(self): self.parent_map = pm = {} for i, entry in enumerate(self.rules): container = entry.matched_files pm[container] = (i, self.rules) for i, child in enumerate(container): gcontainer = child.locations pm[gcontainer] = (i, container) for i, gc in enumerate(gcontainer): pm[gc] = (i, gcontainer) def index(self, row, column, parent=ROOT): container = self.to_container(self.index_to_entry(parent) or self.rules) return self.createIndex(row, column, container) if -1 < row < len(container) else ROOT def to_container(self, entry): if isinstance(entry, CSSEntry): return entry.matched_files elif isinstance(entry, CSSFileMatch): return entry.locations return entry def index_to_entry(self, index): if index.isValid(): try: return index.internalPointer()[index.row()] except IndexError: pass def parent(self, index): if not index.isValid(): return ROOT parent = index.internalPointer() if parent is self.rules or parent is None: return ROOT try: pidx, grand_parent = self.parent_map[parent] except KeyError: return ROOT return self.createIndex(pidx, 0, grand_parent) def rowCount(self, parent=ROOT): if not parent.isValid(): return len(self.rules) entry = self.index_to_entry(parent) c = self.to_container(entry) return 0 if c is entry else len(c) def columnCount(self, parent=ROOT): return 1 def data(self, index, role=Qt.ItemDataRole.DisplayRole): if role == SORT_ROLE: entry = self.index_to_entry(index) if isinstance(entry, CSSEntry): return entry.count if self.sort_on_count else entry.sort_key if isinstance(entry, CSSFileMatch): return len(entry.locations) if self.sort_on_count else entry.sort_key if isinstance(entry, MatchLocation): return entry.sourceline elif role == Qt.ItemDataRole.DisplayRole: entry = self.index_to_entry(index) if isinstance(entry, CSSEntry): return f'[%{self.num_size}d] %s' % (entry.count, entry.rule.selector) elif isinstance(entry, CSSFileMatch): return _('{0} [{1} elements]').format(entry.file_name, len(entry.locations)) elif isinstance(entry, MatchLocation): return f'{entry.tag} @ {entry.sourceline}' elif role == Qt.ItemDataRole.UserRole: return self.index_to_entry(index) elif role == Qt.ItemDataRole.FontRole: entry = self.index_to_entry(index) if isinstance(entry, CSSEntry): return self.main_font elif isinstance(entry, CSSFileMatch): return self.italic_font def __call__(self, data): self.beginResetModel() self.rules = data['css'] self.num_unused = sum(1 for r in self.rules if r.count == 0) try: self.num_size = len(str(max(r.count for r in self.rules))) except ValueError: self.num_size = 1 self.build_maps() self.endResetModel() class CSSProxyModel(QSortFilterProxyModel): def __init__(self, parent=None): QSortFilterProxyModel.__init__(self, parent) self._filter_text = None self.setSortRole(SORT_ROLE) def filter_text(self, text): self._filter_text = text self.setFilterFixedString(text) def filterAcceptsRow(self, row, parent): if not self._filter_text: return True sm = self.sourceModel() entry = sm.index_to_entry(sm.index(row, 0, parent)) if not isinstance(entry, CSSEntry): return True return primary_contains(self._filter_text, entry.rule.selector) class CSSWidget(QWidget): SETTING_PREFIX = 'css-' MODEL = CSSRulesModel PROXY = CSSProxyModel def read_state(self, name, default=None): return read_state(self.SETTING_PREFIX+name, default) def save_state(self, name, val): return save_state(self.SETTING_PREFIX + name, val) def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QVBoxLayout(self) self.h = h = QHBoxLayout() self.filter_edit = e = QLineEdit(self) l.addWidget(e) e.setPlaceholderText(_('Filter')) e.setClearButtonEnabled(True) self.model = m = self.MODEL(self) self.proxy = p = self.PROXY(self) p.setSourceModel(m) self.view = f = QTreeView(self) f.setAlternatingRowColors(True) f.setHeaderHidden(True), f.setExpandsOnDoubleClick(False) f.setModel(p) l.addWidget(f) f.doubleClicked.connect(self.double_clicked) e.textChanged.connect(p.filter_text) l.addLayout(h) h.addWidget(QLabel(_('Sort by:'))) self.counts_button = b = QRadioButton(_('&Counts'), self) b.setChecked(self.read_state('sort-on-counts', True)) h.addWidget(b) self.name_button = b = QRadioButton(_('&Name'), self) b.setChecked(not self.read_state('sort-on-counts', True)) h.addWidget(b) b.toggled.connect(self.resort) h.addStrut(20) self._sort_order = o = QComboBox(self) o.addItems([_('Ascending'), _('Descending')]) o.setCurrentIndex(0 if self.read_state('sort-ascending', True) else 1) o.setEditable(False) o.currentIndexChanged.connect(self.resort) h.addWidget(o) h.addStretch(10) self.summary = la = QLabel('\xa0') h.addWidget(la) @property def sort_order(self): return [Qt.SortOrder.AscendingOrder, Qt.SortOrder.DescendingOrder][self._sort_order.currentIndex()] @sort_order.setter def sort_order(self, val): self._sort_order.setCurrentIndex({Qt.SortOrder.AscendingOrder:0}.get(val, 1)) def update_summary(self): self.summary.setText(_('{0} rules, {1} unused').format(self.model.rowCount(), self.model.num_unused)) def __call__(self, data): self.model(data) self.update_summary() self.filter_edit.clear() self.resort() def save(self): self.save_state('sort-on-counts', self.counts_button.isChecked()) self.save_state('sort-ascending', self.sort_order == Qt.SortOrder.AscendingOrder) def resort(self, *args): self.model.sort_on_count = self.counts_button.isChecked() self.proxy.sort(-1, self.sort_order) # for some reason the proxy model does not resort without this self.proxy.sort(0, self.sort_order) def to_csv(self): buf = StringIO(newline='') w = csv_writer(buf) w.writerow([_('Style Rule'), _('Number of matches')]) for r in range(self.proxy.rowCount()): entry = self.proxy.mapToSource(self.proxy.index(r, 0)).data(Qt.ItemDataRole.UserRole) w.writerow([entry.rule.selector, entry.count]) return buf.getvalue() def double_clicked(self, index): from calibre.gui2.tweak_book.boss import get_boss boss = get_boss() if boss is None: return index = self.proxy.mapToSource(index) entry = self.model.index_to_entry(index) if entry is None: return self.handle_double_click(entry, index, boss) def handle_double_click(self, entry, index, boss): if isinstance(entry, CSSEntry): loc = entry.rule.location name, sourceline, col = loc elif isinstance(entry, CSSFileMatch): name, sourceline = entry.file_name, 0 else: name = self.model.index_to_entry(index.parent()).file_name sourceline = entry.sourceline self.show_line(name, sourceline, boss) def show_line(self, name, sourceline, boss): editor = boss.edit_file_requested(name) if editor is None: return editor = editor.editor block = editor.document().findBlockByNumber(max(0, sourceline - 1)) # blockNumber() is zero based c = editor.textCursor() c.setPosition(block.position() if block.isValid() else 0) editor.setTextCursor(c) boss.show_editor(name) # }}} # Classes {{{ class ClassesModel(CSSRulesModel): def __init__(self, parent): self.classes = self.rules = () CSSRulesModel.__init__(self, parent) self.sort_on_count = True self.num_size = 1 self.num_unused = 0 self.build_maps() def build_maps(self): self.parent_map = pm = {} for i, entry in enumerate(self.classes): container = entry.matched_files pm[container] = (i, self.classes) for i, child in enumerate(container): gcontainer = child.class_elements pm[gcontainer] = (i, container) for i, gc in enumerate(gcontainer): ggcontainer = gc.matched_rules pm[gc] = (i, gcontainer) for i, ggc in enumerate(ggcontainer): pm[ggc] = (i, ggcontainer) def to_container(self, entry): if isinstance(entry, ClassEntry): return entry.matched_files elif isinstance(entry, ClassFileMatch): return entry.class_elements elif isinstance(entry, ClassElement): return entry.matched_rules return entry def data(self, index, role=Qt.ItemDataRole.DisplayRole): if role == SORT_ROLE: entry = self.index_to_entry(index) if isinstance(entry, ClassEntry): return entry.num_of_matches if self.sort_on_count else entry.sort_key if isinstance(entry, ClassFileMatch): return len(entry.class_elements) if self.sort_on_count else entry.sort_key if isinstance(entry, ClassElement): return entry.line_number if isinstance(entry, CSSRule): return entry.location.file_name elif role == Qt.ItemDataRole.DisplayRole: entry = self.index_to_entry(index) if isinstance(entry, ClassEntry): return f'[%{self.num_size}d] %s' % (entry.num_of_matches, entry.cls) elif isinstance(entry, ClassFileMatch): return _('{0} [{1} elements]').format(entry.file_name, len(entry.class_elements)) elif isinstance(entry, ClassElement): return f'{entry.tag} @ {entry.line_number}' elif isinstance(entry, CSSRule): return f'{entry.selector} @ {entry.location.file_name}:{entry.location.line}' elif role == Qt.ItemDataRole.UserRole: return self.index_to_entry(index) elif role == Qt.ItemDataRole.FontRole: entry = self.index_to_entry(index) if isinstance(entry, ClassEntry): return self.main_font elif isinstance(entry, ClassFileMatch): return self.italic_font def __call__(self, data): self.beginResetModel() self.rules = self.classes = tuple(data['classes']) self.num_unused = sum(1 for ce in self.classes if ce.num_of_matches == 0) try: self.num_size = len(str(max(r.num_of_matches for r in self.classes))) except ValueError: self.num_size = 1 self.build_maps() self.endResetModel() class ClassProxyModel(CSSProxyModel): def filterAcceptsRow(self, row, parent): if not self._filter_text: return True sm = self.sourceModel() entry = sm.index_to_entry(sm.index(row, 0, parent)) if not isinstance(entry, ClassEntry): return True return primary_contains(self._filter_text, entry.cls) class ClassesWidget(CSSWidget): SETTING_PREFIX = 'classes-' MODEL = ClassesModel PROXY = ClassProxyModel def update_summary(self): self.summary.setText(_('{0} classes, {1} unused').format(self.model.rowCount(), self.model.num_unused)) def to_csv(self): buf = StringIO(newline='') w = csv_writer(buf) w.writerow([_('Class'), _('Number of matches')]) for r in range(self.proxy.rowCount()): entry = self.proxy.mapToSource(self.proxy.index(r, 0)).data(Qt.ItemDataRole.UserRole) w.writerow([entry.cls, entry.num_of_matches]) return buf.getvalue() def handle_double_click(self, entry, index, boss): if isinstance(entry, ClassEntry): def uniq(vals): vals = vals or () seen = set() seen_add = seen.add return tuple(x for x in vals if x not in seen and not seen_add(x)) rules = tuple(uniq([LinkLocation(rule.location.file_name, rule.location.line, None) for cfm in entry.matched_files for ce in cfm.class_elements for rule in ce.matched_rules])) if rules: jump((id(self), id(entry)), rules) return elif isinstance(entry, ClassFileMatch): name, sourceline = entry.file_name, 0 elif isinstance(entry, ClassElement): return jump_to_location(entry) else: loc = entry.location name, sourceline, col = loc self.show_line(name, sourceline, boss) # }}} # Wrapper UI {{{ class ReportsWidget(QWidget): edit_requested = pyqtSignal(object) delete_requested = pyqtSignal(object, object) def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = QVBoxLayout(self) self.splitter = l = QSplitter(self) l.setChildrenCollapsible(False) self.layout().addWidget(l) self.reports = r = QListWidget(self) l.addWidget(r) self.stack = s = QStackedWidget(self) l.addWidget(s) r.currentRowChanged.connect(s.setCurrentIndex) self.files = f = FilesWidget(self) f.edit_requested.connect(self.edit_requested) f.delete_requested.connect(self.delete_requested) s.addWidget(f) QListWidgetItem(_('Files'), r) self.words = w = WordsWidget(self) s.addWidget(w) QListWidgetItem(_('Words'), r) self.images = i = ImagesWidget(self) i.edit_requested.connect(self.edit_requested) i.delete_requested.connect(self.delete_requested) s.addWidget(i) QListWidgetItem(_('Images'), r) self.css = c = CSSWidget(self) s.addWidget(c) QListWidgetItem(_('Style rules'), r) self.css = c = ClassesWidget(self) s.addWidget(c) QListWidgetItem(_('Style classes'), r) self.chars = c = CharsWidget(self) s.addWidget(c) QListWidgetItem(_('Characters'), r) self.links = li = LinksWidget(self) s.addWidget(li) QListWidgetItem(_('Links'), r) self.splitter.setStretchFactor(1, 500) try: self.splitter.restoreState(read_state('splitter-state')) except TypeError: pass current_page = read_state('report-page') if current_page is not None: self.reports.setCurrentRow(current_page) self.layout().setContentsMargins(0, 0, 0, 0) for i in range(self.stack.count()): self.stack.widget(i).layout().setContentsMargins(0, 0, 0, 0) def __call__(self, data): jump.clear() for i in range(self.stack.count()): st = time.time() self.stack.widget(i)(data) if DEBUG: category = self.reports.item(i).data(Qt.ItemDataRole.DisplayRole) print('Widget time for %12s: %.2fs seconds' % (category, time.time() - st)) def save(self): save_state('splitter-state', bytearray(self.splitter.saveState())) save_state('report-page', self.reports.currentRow()) for i in range(self.stack.count()): self.stack.widget(i).save() def to_csv(self): w = self.stack.currentWidget() category = self.reports.currentItem().data(Qt.ItemDataRole.DisplayRole) if not hasattr(w, 'to_csv'): return error_dialog(self, _('Not supported'), _( 'Export of %s data is not supported') % category, show=True) data = w.to_csv() fname = choose_save_file(self, 'report-csv-export', _('Choose a filename for the data'), filters=[ (_('CSV files'), ['csv'])], all_files=False, initial_filename='%s.csv' % category) if fname: with open(fname, 'wb') as f: f.write(as_bytes(data)) class Reports(Dialog): data_gathered = pyqtSignal(object, object) edit_requested = pyqtSignal(object) refresh_starting = pyqtSignal() delete_requested = pyqtSignal(object, object) def __init__(self, parent=None): Dialog.__init__(self, _('Reports'), 'reports-dialog', parent=parent) self.data_gathered.connect(self.display_data, type=Qt.ConnectionType.QueuedConnection) self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False) self.setWindowIcon(QIcon.ic('reports.png')) def setup_ui(self): self.l = l = QVBoxLayout(self) self.wait_stack = s = QStackedLayout() l.addLayout(s) l.addWidget(self.bb) self.reports = r = ReportsWidget(self) r.edit_requested.connect(self.edit_requested) r.delete_requested.connect(self.confirm_delete) self.pw = pw = QWidget(self) s.addWidget(pw), s.addWidget(r) pw.l = l = QVBoxLayout(pw) self.pi = pi = ProgressIndicator(self, 256) l.addStretch(1), l.addWidget(pi, alignment=Qt.AlignmentFlag.AlignHCenter), l.addSpacing(10) pw.la = la = QLabel(_('Gathering data, please wait...')) la.setStyleSheet('QLabel { font-size: 30pt; font-weight: bold }') l.addWidget(la, alignment=Qt.AlignmentFlag.AlignHCenter), l.addStretch(1) self.bb.setStandardButtons(QDialogButtonBox.StandardButton.Close) self.refresh_button = b = self.bb.addButton(_('&Refresh'), QDialogButtonBox.ButtonRole.ActionRole) b.clicked.connect(self.refresh) b.setIcon(QIcon.ic('view-refresh.png')) self.save_button = b = self.bb.addButton(_('&Save'), QDialogButtonBox.ButtonRole.ActionRole) b.clicked.connect(self.reports.to_csv) b.setIcon(QIcon.ic('save.png')) b.setToolTip(_('Export the currently shown report as a CSV file')) def sizeHint(self): return QSize(950, 600) def confirm_delete(self, spine_items, other_names): spine_names = {name for name, remove in spine_items if remove} if not question_dialog(self, _('Are you sure?'), _( 'Are you sure you want to delete the selected files?'), det_msg='\n'.join(spine_names | other_names)): return self.delete_requested.emit(spine_items, other_names) QTimer.singleShot(10, self.refresh) def refresh(self): self.wait_stack.setCurrentIndex(0) self.setCursor(Qt.CursorShape.BusyCursor) self.pi.startAnimation() self.refresh_starting.emit() t = Thread(name='GatherReportData', target=self.gather_data) t.daemon = True t.start() def gather_data(self): try: ok, data = True, gather_data(current_container(), dictionaries.default_locale) except Exception: import traceback traceback.print_exc() ok, data = False, traceback.format_exc() self.data_gathered.emit(ok, data) def display_data(self, ok, data): self.wait_stack.setCurrentIndex(1) self.unsetCursor() self.pi.stopAnimation() if not ok: return error_dialog(self, _('Failed to gather data'), _( 'Failed to gather data for the report. Click "Show details" for more' ' information.'), det_msg=data, show=True) data, timing = data if DEBUG: for x, t in sorted(iteritems(timing), key=itemgetter(1)): print('Time for %6s data: %.3f seconds' % (x, t)) self.reports(data) def accept(self): with tprefs: self.reports.save() Dialog.accept(self) def reject(self): self.reports.save() Dialog.reject(self) # }}} if __name__ == '__main__': import sys from calibre.gui2 import Application app = Application([]) from calibre.gui2.tweak_book import set_current_container from calibre.gui2.tweak_book.boss import get_container set_current_container(get_container(sys.argv[-1])) d = Reports() d.refresh() d.exec() del d, app
55,204
Python
.py
1,289
33.050427
160
0.612499
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,704
__init__.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/__init__.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' import string from calibre.spell.dictionary import Dictionaries, parse_lang_code from calibre.utils.config import JSONConfig from polyglot.builtins import iteritems CONTAINER_DND_MIMETYPE = 'application/x-calibre-container-name-list' tprefs = JSONConfig('tweak_book_gui') d = tprefs.defaults d['editor_theme'] = None d['editor_font_family'] = None d['editor_font_size'] = 12 d['editor_line_wrap'] = True d['editor_tab_stop_width'] = 2 d['editor_cursor_width'] = 1 d['editor_show_char_under_cursor'] = True d['replace_entities_as_typed'] = True d['preview_refresh_time'] = 2 d['choose_tweak_fmt'] = True d['tweak_fmt_order'] = ['EPUB', 'AZW3'] d['update_metadata_from_calibre'] = True d['nestable_dock_widgets'] = False d['dock_top_left'] = 'horizontal' d['dock_top_right'] = 'horizontal' d['dock_bottom_left'] = 'horizontal' d['dock_bottom_right'] = 'horizontal' d['engine_preview_serif_family'] = None d['engine_preview_sans_family'] = None d['engine_preview_mono_family'] = None d['preview_standard_font_family'] = 'serif' d['preview_base_font_size'] = 18 d['preview_mono_font_size'] = 14 d['preview_minimum_font_size'] = 8 d['preview_sync_context'] = 0 d['preview_background'] = 'auto' d['preview_foreground'] = 'auto' d['preview_link_color'] = 'auto' d['remove_existing_links_when_linking_sheets'] = True d['charmap_favorites'] = list(map(ord, '\xa0\u2002\u2003\u2009\xad' '‘’“”‹›«»‚„' '—–§¶†‡©®™' '→⇒•·°±−×÷¼½½¾' '…µ¢£€¿¡¨´¸ˆ˜' 'ÀÁÂÃÄÅÆÇÈÉÊË' 'ÌÍÎÏÐÑÒÓÔÕÖØ' 'ŒŠÙÚÛÜÝŸÞßàá' 'âãäåæçèéêëìí' 'îïðñòóôõöøœš' 'ùúûüýÿþªºαΩ∞')) # noqa d['folders_for_types'] = {'style':'styles', 'image':'images', 'font':'fonts', 'audio':'audio', 'video':'video'} d['pretty_print_on_open'] = False d['disable_completion_popup_for_search'] = False d['saved_searches'] = [] d['insert_tag_mru'] = ['p', 'div', 'li', 'h1', 'h2', 'h3', 'h4', 'em', 'strong', 'td', 'tr'] d['spell_check_case_sensitive_sort'] = False d['inline_spell_check'] = True d['custom_themes'] = {} d['remove_unused_classes'] = False d['merge_identical_selectors'] = False d['merge_identical_selectors'] = False d['merge_rules_with_identical_properties'] = False d['remove_unreferenced_sheets'] = True d['global_book_toolbar'] = [ 'new-file', 'open-book', 'save-book', None, 'global-undo', 'global-redo', 'create-checkpoint', None, 'donate', 'user-manual'] d['global_tools_toolbar'] = [ 'check-book', 'spell-check-book', 'edit-toc', 'insert-character', 'manage-fonts', 'smarten-punctuation', 'remove-unused-css', 'show-reports' ] d['global_plugins_toolbar'] = [] d['editor_common_toolbar'] = [('editor-' + x) if x else None for x in ('undo', 'redo', None, 'cut', 'copy', 'paste', 'smart-comment')] d['editor_css_toolbar'] = ['pretty-current', 'editor-sort-css', 'insert-image'] d['editor_xml_toolbar'] = ['pretty-current', 'insert-tag'] d['editor_html_toolbar'] = ['fix-html-current', 'pretty-current', 'insert-image', 'insert-hyperlink', 'insert-tag', 'change-paragraph'] d['editor_format_toolbar'] = [('format-text-' + x) if x else x for x in ( 'bold', 'italic', 'underline', 'strikethrough', 'subscript', 'superscript', None, 'color', 'background-color', None, 'justify-left', 'justify-center', 'justify-right', 'justify-fill')] d['spell_check_case_sensitive_search'] = False d['add_cover_preserve_aspect_ratio'] = False d['templates'] = {} d['auto_close_tags'] = True d['restore_book_state'] = True d['editor_accepts_drops'] = True d['toolbar_icon_size'] = 24 d['insert_full_screen_image'] = False d['preserve_aspect_ratio_when_inserting_image'] = False d['file_list_shows_full_pathname'] = False d['auto_link_stylesheets'] = True d['check_external_link_anchors'] = True d['remove_ncx'] = True d['html_transform_scope'] = 'current' del d ucase_map = {l:string.ascii_uppercase[i] for i, l in enumerate(string.ascii_lowercase)} def capitalize(x): return ucase_map[x[0]] + x[1:] _current_container = None def current_container(): return _current_container def set_current_container(container): global _current_container _current_container = container class NonReplaceDict(dict): def __setitem__(self, k, v): if k in self: raise ValueError('The key %s is already present' % k) dict.__setitem__(self, k, v) actions = NonReplaceDict() editors = NonReplaceDict() toolbar_actions = NonReplaceDict() editor_toolbar_actions = { 'format':NonReplaceDict(), 'html':NonReplaceDict(), 'xml':NonReplaceDict(), 'css':NonReplaceDict()} TOP = object() dictionaries = Dictionaries() def editor_name(editor): for n, ed in iteritems(editors): if ed is editor: return n def set_book_locale(lang): dictionaries.initialize() try: dictionaries.default_locale = parse_lang_code(lang) if dictionaries.default_locale.langcode == 'und': raise ValueError('') except ValueError: dictionaries.default_locale = dictionaries.ui_locale from calibre.gui2.tweak_book.editor.syntax.html import refresh_spell_check_status refresh_spell_check_status() def verify_link(url, name=None): if _current_container is None or name is None: return None try: target = _current_container.href_to_name(url, name) except ValueError: return False # Absolute URLs that point to a different drive on windows cause this if _current_container.has_name(target): return True if url.startswith('#'): return True if url.partition(':')[0] in {'http', 'https', 'mailto'}: return True return False def update_mark_text_action(ed=None): has_mark = False if ed is not None and ed.has_line_numbers: has_mark = bool(ed.selected_text) or not ed.has_marked_text ac = actions['mark-selected-text'] ac.setText(ac.default_text if has_mark else _('&Unmark marked text'))
6,068
Python
.py
138
39.978261
223
0.687771
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,705
check_links.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/check_links.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> from collections import defaultdict from threading import Thread from qt.core import ( QCheckBox, QDialogButtonBox, QHBoxLayout, QIcon, QInputDialog, QLabel, QProgressBar, QSizePolicy, QStackedWidget, Qt, QTextBrowser, QVBoxLayout, QWidget, pyqtSignal, ) from calibre.gui2 import error_dialog from calibre.gui2.tweak_book import current_container, editors, set_current_container, tprefs from calibre.gui2.tweak_book.boss import get_boss from calibre.gui2.tweak_book.widgets import Dialog from calibre.utils.localization import ngettext from polyglot.builtins import iteritems def get_data(name): 'Get the data for name. Returns a unicode string if name is a text document/stylesheet' if name in editors: return editors[name].get_raw_data() return current_container().raw_data(name) def set_data(name, val): if name in editors: editors[name].replace_data(val, only_if_different=False) else: with current_container().open(name, 'wb') as f: if isinstance(val, str): val = val.encode('utf-8') f.write(val) get_boss().set_modified() class CheckExternalLinks(Dialog): progress_made = pyqtSignal(object, object) def __init__(self, parent=None): Dialog.__init__(self, _('Check external links'), 'check-external-links-dialog', parent) self.progress_made.connect(self.on_progress_made, type=Qt.ConnectionType.QueuedConnection) def show(self): if self.rb.isEnabled(): self.refresh() return Dialog.show(self) def refresh(self): self.stack.setCurrentIndex(0) self.rb.setEnabled(False) t = Thread(name='CheckLinksMaster', target=self.run) t.daemon = True t.start() def setup_ui(self): self.pb = pb = QProgressBar(self) pb.setTextVisible(True) pb.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) pb.setRange(0, 0) self.w = w = QWidget(self) self.w.l = l = QVBoxLayout(w) l.addStretch(), l.addWidget(pb) self.w.la = la = QLabel(_('Checking external links, please wait...')) la.setStyleSheet('QLabel { font-size: 20px; font-weight: bold }') l.addWidget(la, 0, Qt.AlignmentFlag.AlignCenter), l.addStretch() self.l = l = QVBoxLayout(self) self.results = QTextBrowser(self) self.results.setOpenLinks(False) self.results.anchorClicked.connect(self.anchor_clicked) self.stack = s = QStackedWidget(self) s.addWidget(w), s.addWidget(self.results) l.addWidget(s) self.bh = h = QHBoxLayout() self.check_anchors = ca = QCheckBox(_('Check &anchors')) ca.setToolTip(_('Check HTML anchors in links (the part after the #).\n' ' This can be a little slow, since it requires downloading and parsing all the HTML pages.')) ca.setChecked(tprefs.get('check_external_link_anchors', True)) ca.stateChanged.connect(self.anchors_changed) h.addWidget(ca), h.addStretch(100), h.addWidget(self.bb) l.addLayout(h) self.bb.setStandardButtons(QDialogButtonBox.StandardButton.Close) self.rb = b = self.bb.addButton(_('&Refresh'), QDialogButtonBox.ButtonRole.ActionRole) b.setIcon(QIcon.ic('view-refresh.png')) b.clicked.connect(self.refresh) def anchors_changed(self): tprefs.set('check_external_link_anchors', self.check_anchors.isChecked()) def sizeHint(self): ans = Dialog.sizeHint(self) ans.setHeight(600) ans.setWidth(max(ans.width(), 800)) return ans def run(self): from calibre.ebooks.oeb.polish.check.links import check_external_links self.tb = None self.errors = [] try: self.errors = check_external_links(current_container(), self.progress_made.emit, check_anchors=self.check_anchors.isChecked()) except Exception: import traceback self.tb = traceback.format_exc() self.progress_made.emit(None, None) def on_progress_made(self, curr, total): if curr is None: self.results.setText('') self.stack.setCurrentIndex(1) self.fixed_errors = set() self.rb.setEnabled(True) if self.tb is not None: return error_dialog(self, _('Checking failed'), _( 'There was an error while checking links, click "Show details" for more information'), det_msg=self.tb, show=True) if not self.errors: self.results.setText(_('No broken links found')) else: self.populate_results() else: self.pb.setMaximum(total), self.pb.setValue(curr) def populate_results(self, preserve_pos=False): num = len(self.errors) - len(self.fixed_errors) text = '<h3>%s</h3><ol>' % (ngettext( 'Found a broken link', 'Found {} broken links', num).format(num)) for i, (locations, err, url) in enumerate(self.errors): if i in self.fixed_errors: continue text += '<li><b>%s</b> \xa0<a href="err:%d">[%s]</a><br>%s<br><ul>' % (url, i, _('Fix this link'), err) for name, href, lnum, col in locations: text += '<li>{name} \xa0<a href="loc:{lnum},{name}">[{line}: {lnum}]</a></li>'.format( name=name, lnum=lnum, line=_('line number')) text += '</ul></li><hr>' self.results.setHtml(text) def anchor_clicked(self, qurl): url = qurl.toString() if url.startswith('err:'): errnum = int(url[4:]) err = self.errors[errnum] newurl, ok = QInputDialog.getText(self, _('Fix URL'), _('Enter the corrected URL:') + '\xa0'*40, text=err[2]) if not ok: return nmap = defaultdict(set) for name, href in {(l[0], l[1]) for l in err[0]}: nmap[name].add(href) for name, hrefs in iteritems(nmap): raw = oraw = get_data(name) for href in hrefs: raw = raw.replace(href, newurl) if raw != oraw: set_data(name, raw) self.fixed_errors.add(errnum) self.populate_results() elif url.startswith('loc:'): lnum, name = url[4:].partition(',')[::2] lnum = int(lnum or 1) editor = get_boss().edit_file(name) if lnum and editor is not None and editor.has_line_numbers: editor.current_line = lnum if __name__ == '__main__': import sys from calibre.gui2 import Application from calibre.gui2.tweak_book.boss import get_container app = Application([]) set_current_container(get_container(sys.argv[-1])) d = CheckExternalLinks() d.refresh() d.exec() del app
7,099
Python
.py
166
33.560241
138
0.613347
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,706
widgets.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/widgets.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' import os import textwrap import unicodedata from collections import OrderedDict from math import ceil from qt.core import ( QAbstractListModel, QApplication, QCheckBox, QComboBox, QDialog, QDialogButtonBox, QEvent, QFormLayout, QFrame, QGridLayout, QGroupBox, QHBoxLayout, QIcon, QItemSelectionModel, QLabel, QLineEdit, QListView, QMimeData, QModelIndex, QPainter, QPalette, QPixmap, QPlainTextEdit, QPoint, QRect, QSize, QSizePolicy, QSplitter, QStaticText, QStyle, QStyledItemDelegate, Qt, QTextCursor, QTextDocument, QTextOption, QToolButton, QVBoxLayout, QWidget, pyqtSignal, ) from calibre import human_readable, prepare_string_for_xml from calibre.constants import iswindows from calibre.ebooks.oeb.polish.cover import get_raster_cover_name from calibre.ebooks.oeb.polish.toc import ensure_container_has_nav, get_guide_landmarks, get_nav_landmarks, set_landmarks from calibre.ebooks.oeb.polish.upgrade import guide_epubtype_map from calibre.ebooks.oeb.polish.utils import guess_type, lead_text from calibre.gui2 import choose_files, choose_images, choose_save_file, error_dialog, info_dialog from calibre.gui2.complete2 import EditWithComplete from calibre.gui2.tweak_book import current_container, tprefs from calibre.gui2.widgets2 import PARAGRAPH_SEPARATOR, HistoryComboBox, to_plain_text from calibre.gui2.widgets2 import Dialog as BaseDialog from calibre.startup import connect_lambda from calibre.utils.icu import numeric_sort_key, primary_contains, primary_sort_key, sort_key from calibre.utils.matcher import DEFAULT_LEVEL1, DEFAULT_LEVEL2, DEFAULT_LEVEL3, Matcher, get_char from polyglot.builtins import iteritems ROOT = QModelIndex() class Dialog(BaseDialog): def __init__(self, title, name, parent=None): BaseDialog.__init__(self, title, name, parent=parent, prefs=tprefs) class InsertTag(Dialog): # {{{ def __init__(self, parent=None): Dialog.__init__(self, _('Choose tag name'), 'insert-tag', parent=parent) def setup_ui(self): from calibre.ebooks.constants import html5_tags self.l = l = QVBoxLayout(self) self.setLayout(l) self.la = la = QLabel(_('Specify the name of the &tag to insert:')) l.addWidget(la) self.tag_input = ti = EditWithComplete(self) ti.set_separator(None) ti.all_items = html5_tags | frozenset(tprefs['insert_tag_mru']) la.setBuddy(ti) l.addWidget(ti) l.addWidget(self.bb) ti.setFocus(Qt.FocusReason.OtherFocusReason) @property def tag(self): return str(self.tag_input.text()).strip() @classmethod def test(cls): d = cls() if d.exec() == QDialog.DialogCode.Accepted: print(d.tag) # }}} class RationalizeFolders(Dialog): # {{{ TYPE_MAP = ( ('text', _('Text (HTML) files')), ('style', _('Style (CSS) files')), ('image', _('Images')), ('font', _('Fonts')), ('audio', _('Audio')), ('video', _('Video')), ('opf', _('OPF file (metadata)')), ('toc', _('Table of contents file (NCX)')), ) def __init__(self, parent=None): Dialog.__init__(self, _('Arrange in folders'), 'rationalize-folders', parent=parent) def setup_ui(self): self.l = l = QGridLayout() self.setLayout(l) self.la = la = QLabel(_( 'Arrange the files in this book into sub-folders based on their types.' ' If you leave a folder blank, the files will be placed in the root.')) la.setWordWrap(True) l.addWidget(la, 0, 0, 1, -1) folders = tprefs['folders_for_types'] for i, (typ, text) in enumerate(self.TYPE_MAP): la = QLabel('&' + text) setattr(self, '%s_label' % typ, la) le = QLineEdit(self) setattr(self, '%s_folder' % typ, le) val = folders.get(typ, '') if val and not val.endswith('/'): val += '/' le.setText(val) la.setBuddy(le) l.addWidget(la, i + 1, 0) l.addWidget(le, i + 1, 1) self.la2 = la = QLabel(_( 'Note that this will only arrange files inside the book,' ' it will not affect how they are displayed in the File browser')) la.setWordWrap(True) l.addWidget(la, i + 2, 0, 1, -1) l.addWidget(self.bb, i + 3, 0, 1, -1) @property def folder_map(self): ans = {} for typ, x in self.TYPE_MAP: val = str(getattr(self, '%s_folder' % typ).text()).strip().strip('/') ans[typ] = val return ans def accept(self): tprefs['folders_for_types'] = self.folder_map return Dialog.accept(self) # }}} class MultiSplit(Dialog): # {{{ def __init__(self, parent=None): Dialog.__init__(self, _('Specify locations to split at'), 'multisplit-xpath', parent=parent) def setup_ui(self): from calibre.gui2.convert.xpath_wizard import XPathEdit self.l = l = QVBoxLayout(self) self.setLayout(l) self.la = la = QLabel(_( 'Specify the locations to split at, using an XPath expression (click' ' the wizard button for help with generating XPath expressions).')) la.setWordWrap(True) l.addWidget(la) self._xpath = xp = XPathEdit(self) xp.set_msg(_('&XPath expression:')) xp.setObjectName('editor-multisplit-xpath-edit') l.addWidget(xp) l.addWidget(self.bb) def accept(self): if not self._xpath.check(): return error_dialog(self, _('Invalid XPath expression'), _( 'The XPath expression %s is invalid.') % self.xpath) return Dialog.accept(self) @property def xpath(self): return self._xpath.xpath # }}} class ImportForeign(Dialog): # {{{ def __init__(self, parent=None): Dialog.__init__(self, _('Choose file to import'), 'import-foreign') def sizeHint(self): ans = Dialog.sizeHint(self) ans.setWidth(ans.width() + 200) return ans def setup_ui(self): self.l = l = QFormLayout(self) l.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow) self.setLayout(l) la = self.la = QLabel(_( 'You can import an HTML or DOCX file directly as an EPUB and edit it. The EPUB' ' will be generated with minimal changes from the source, unlike doing a full' ' conversion in calibre.')) la.setWordWrap(True) l.addRow(la) self.h1 = h1 = QHBoxLayout() self.src = src = QLineEdit(self) src.setPlaceholderText(_('Choose the file to import')) h1.addWidget(src) self.b1 = b = QToolButton(self) b.setIcon(QIcon.ic('document_open.png')) b.setText(_('Choose file')) h1.addWidget(b) l.addRow(_('Source file:'), h1) b.clicked.connect(self.choose_source) b.setFocus(Qt.FocusReason.OtherFocusReason) self.h2 = h1 = QHBoxLayout() self.dest = src = QLineEdit(self) src.setPlaceholderText(_('Choose the location for the newly created EPUB')) h1.addWidget(src) self.b2 = b = QToolButton(self) b.setIcon(QIcon.ic('document_open.png')) b.setText(_('Choose file')) h1.addWidget(b) l.addRow(_('Destination file:'), h1) b.clicked.connect(self.choose_destination) l.addRow(self.bb) def choose_source(self): from calibre.ebooks.oeb.polish.import_book import IMPORTABLE path = choose_files(self, 'edit-book-choose-file-to-import', _('Choose file'), filters=[ (_('Importable files'), list(IMPORTABLE))], select_only_single_file=True) if path: self.set_src(path[0]) def set_src(self, path): self.src.setText(path) self.dest.setText(self.data[1]) def choose_destination(self): path = choose_save_file(self, 'edit-book-destination-for-generated-epub', _('Choose destination'), filters=[ (_('EPUB files'), ['epub'])], all_files=False) if path: if not path.lower().endswith('.epub'): path += '.epub' self.dest.setText(path) def accept(self): if not str(self.src.text()): return error_dialog(self, _('Need document'), _( 'You must specify the source file that will be imported.'), show=True) Dialog.accept(self) @property def data(self): src = str(self.src.text()).strip() dest = str(self.dest.text()).strip() if not dest: dest = src.rpartition('.')[0] + '.epub' return src, dest # }}} # Quick Open {{{ def make_highlighted_text(emph, text, positions): positions = sorted(set(positions) - {-1}) if positions: parts = [] pos = 0 for p in positions: ch = get_char(text, p) parts.append(prepare_string_for_xml(text[pos:p])) parts.append(f'<span style="{emph}">{prepare_string_for_xml(ch)}</span>') pos = p + len(ch) parts.append(prepare_string_for_xml(text[pos:])) return ''.join(parts) return text def emphasis_style(): pal = QApplication.instance().palette() return f'color: {pal.color(QPalette.ColorRole.Link).name()}; font-weight: bold' class Results(QWidget): MARGIN = 4 item_selected = pyqtSignal() def __init__(self, parent=None): QWidget.__init__(self, parent=parent) self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) self.results = () self.current_result = -1 self.max_result = -1 self.mouse_hover_result = -1 self.setMouseTracking(True) self.setFocusPolicy(Qt.FocusPolicy.NoFocus) self.text_option = to = QTextOption() to.setWrapMode(QTextOption.WrapMode.NoWrap) self.divider = QStaticText('\xa0→ \xa0') self.divider.setTextFormat(Qt.TextFormat.PlainText) def item_from_y(self, y): if not self.results: return delta = self.results[0][0].size().height() + self.MARGIN maxy = self.height() pos = 0 for i, r in enumerate(self.results): bottom = pos + delta if pos <= y < bottom: return i break pos = bottom if pos > min(y, maxy): break return -1 def mouseMoveEvent(self, ev): y = ev.pos().y() prev = self.mouse_hover_result self.mouse_hover_result = self.item_from_y(y) if prev != self.mouse_hover_result: self.update() def mousePressEvent(self, ev): if ev.button() == 1: i = self.item_from_y(ev.pos().y()) if i != -1: ev.accept() self.current_result = i self.update() self.item_selected.emit() return return QWidget.mousePressEvent(self, ev) def change_current(self, delta=1): if not self.results: return nc = self.current_result + delta if 0 <= nc <= self.max_result: self.current_result = nc self.update() def __call__(self, results): if results: self.current_result = 0 prefixes = [QStaticText('<b>%s</b>' % os.path.basename(x)) for x in results] [(p.setTextFormat(Qt.TextFormat.RichText), p.setTextOption(self.text_option)) for p in prefixes] self.maxwidth = max(int(ceil(x.size().width())) for x in prefixes) self.results = tuple((prefix, self.make_text(text, positions), text) for prefix, (text, positions) in zip(prefixes, iteritems(results))) else: self.results = () self.current_result = -1 self.max_result = min(10, len(self.results) - 1) self.mouse_hover_result = -1 self.update() def make_text(self, text, positions): text = QStaticText(make_highlighted_text(emphasis_style(), text, positions)) text.setTextOption(self.text_option) text.setTextFormat(Qt.TextFormat.RichText) return text def paintEvent(self, ev): offset = QPoint(0, 0) p = QPainter(self) p.setClipRect(ev.rect()) bottom = self.rect().bottom() if self.results: for i, (prefix, full, text) in enumerate(self.results): size = prefix.size() if offset.y() + size.height() > bottom: break self.max_result = i offset.setX(0) if i in (self.current_result, self.mouse_hover_result): p.save() if i != self.current_result: p.setPen(Qt.PenStyle.DotLine) p.drawLine(offset, QPoint(self.width(), offset.y())) p.restore() offset.setY(offset.y() + self.MARGIN // 2) p.drawStaticText(offset, prefix) offset.setX(self.maxwidth + 5) p.drawStaticText(offset, self.divider) offset.setX(offset.x() + int(ceil(self.divider.size().width()))) p.drawStaticText(offset, full) offset.setY(int(offset.y() + size.height() + self.MARGIN // 2)) if i in (self.current_result, self.mouse_hover_result): offset.setX(0) p.save() if i != self.current_result: p.setPen(Qt.PenStyle.DotLine) p.drawLine(offset, QPoint(self.width(), offset.y())) p.restore() else: p.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, _('No results found')) p.end() @property def selected_result(self): try: return self.results[self.current_result][-1] except IndexError: pass class QuickOpen(Dialog): def __init__(self, items, parent=None, title=None, name='quick-open', level1=DEFAULT_LEVEL1, level2=DEFAULT_LEVEL2, level3=DEFAULT_LEVEL3, help_text=None): self.matcher = Matcher(items, level1=level1, level2=level2, level3=level3) self.matches = () self.selected_result = None self.help_text = help_text or self.default_help_text() Dialog.__init__(self, title or _('Choose file to edit'), name, parent=parent) def sizeHint(self): ans = Dialog.sizeHint(self) ans.setWidth(800) ans.setHeight(max(600, ans.height())) return ans def default_help_text(self): example = '<pre>{0}i{1}mages/{0}c{1}hapter1/{0}s{1}cene{0}3{1}.jpg</pre>'.format( '<span style="%s">' % emphasis_style(), '</span>') chars = '<pre style="%s">ics3</pre>' % emphasis_style() return _('''<p>Quickly choose a file by typing in just a few characters from the file name into the field above. For example, if want to choose the file: {example} Simply type in the characters: {chars} and press Enter.''').format(example=example, chars=chars) def setup_ui(self): self.l = l = QVBoxLayout(self) self.setLayout(l) self.text = t = QLineEdit(self) t.textEdited.connect(self.update_matches) t.setClearButtonEnabled(True) t.setPlaceholderText(_('Search')) l.addWidget(t, alignment=Qt.AlignmentFlag.AlignTop) self.help_label = hl = QLabel(self.help_text) hl.setContentsMargins(50, 50, 50, 50), hl.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignHCenter) l.addWidget(hl) self.results = Results(self) self.results.setVisible(False) self.results.item_selected.connect(self.accept) l.addWidget(self.results) l.addWidget(self.bb, alignment=Qt.AlignmentFlag.AlignBottom) def update_matches(self, text): text = str(text).strip() self.help_label.setVisible(False) self.results.setVisible(True) matches = self.matcher(text, limit=100) self.results(matches) self.matches = tuple(matches) def keyPressEvent(self, ev): if ev.key() in (Qt.Key.Key_Up, Qt.Key.Key_Down): ev.accept() self.results.change_current(delta=-1 if ev.key() == Qt.Key.Key_Up else 1) return return Dialog.keyPressEvent(self, ev) def accept(self): self.selected_result = self.results.selected_result return Dialog.accept(self) @classmethod def test(cls): from calibre.utils.matcher import get_items_from_dir items = get_items_from_dir(os.getcwd(), lambda x:not x.endswith('.pyc')) d = cls(items) d.exec() print(d.selected_result) # }}} # Filterable names list {{{ class NamesDelegate(QStyledItemDelegate): def sizeHint(self, option, index): ans = QStyledItemDelegate.sizeHint(self, option, index) ans.setHeight(ans.height() + 10) return ans def paint(self, painter, option, index): QStyledItemDelegate.paint(self, painter, option, index) text, positions = index.data(Qt.ItemDataRole.UserRole) self.initStyleOption(option, index) painter.save() painter.setFont(option.font) p = option.palette c = QPalette.ColorRole.HighlightedText if option.state & QStyle.StateFlag.State_Selected else QPalette.ColorRole.Text group = (QPalette.ColorGroup.Active if option.state & QStyle.StateFlag.State_Active else QPalette.ColorGroup.Inactive) c = p.color(group, c) painter.setClipRect(option.rect) if positions is None or -1 in positions: painter.setPen(c) painter.drawText(option.rect, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter | Qt.TextFlag.TextSingleLine, text) else: to = QTextOption() to.setWrapMode(QTextOption.WrapMode.NoWrap) to.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter) positions = sorted(set(positions) - {-1}, reverse=True) text = '<body>%s</body>' % make_highlighted_text(emphasis_style(), text, positions) doc = QTextDocument() c = 'rgb(%d, %d, %d)'%c.getRgb()[:3] doc.setDefaultStyleSheet(' body { color: %s }'%c) doc.setHtml(text) doc.setDefaultFont(option.font) doc.setDocumentMargin(0.0) doc.setDefaultTextOption(to) height = doc.size().height() painter.translate(option.rect.left(), option.rect.top() + (max(0, option.rect.height() - height) // 2)) doc.drawContents(painter) painter.restore() class NamesModel(QAbstractListModel): filtered = pyqtSignal(object) def __init__(self, names, parent=None): self.items = [] QAbstractListModel.__init__(self, parent) self.set_names(names) def set_names(self, names): self.names = names self.matcher = Matcher(names) self.filter('') def rowCount(self, parent=ROOT): return len(self.items) def data(self, index, role): if role == Qt.ItemDataRole.UserRole: return self.items[index.row()] if role == Qt.ItemDataRole.DisplayRole: return '\xa0' * 20 def filter(self, query): query = str(query or '') self.beginResetModel() if not query: self.items = tuple((text, None) for text in self.names) else: self.items = tuple(iteritems(self.matcher(query))) self.endResetModel() self.filtered.emit(not bool(query)) def find_name(self, name): for i, (text, positions) in enumerate(self.items): if text == name: return i def name_for_index(self, index): try: return self.items[index.row()][0] except IndexError: pass def create_filterable_names_list(names, filter_text=None, parent=None, model=NamesModel): nl = QListView(parent) nl.m = m = model(names, parent=nl) connect_lambda(m.filtered, nl, lambda nl, all_items: nl.scrollTo(m.index(0))) nl.setModel(m) if model is NamesModel: nl.d = NamesDelegate(nl) nl.setItemDelegate(nl.d) f = QLineEdit(parent) f.setPlaceholderText(filter_text or '') f.textEdited.connect(m.filter) return nl, f # }}} # Insert Link {{{ class AnchorsModel(QAbstractListModel): filtered = pyqtSignal(object) def __init__(self, names, parent=None): self.items = [] self.names = [] QAbstractListModel.__init__(self, parent=parent) def rowCount(self, parent=ROOT): return len(self.items) def data(self, index, role): if role == Qt.ItemDataRole.UserRole: return self.items[index.row()] if role == Qt.ItemDataRole.DisplayRole: return '\n'.join(self.items[index.row()]) if role == Qt.ItemDataRole.ToolTipRole: text, frag = self.items[index.row()] return _('Anchor: {0}\nLeading text: {1}').format(frag, text) def set_names(self, names): self.names = names self.filter('') def filter(self, query): query = str(query or '') self.beginResetModel() self.items = [x for x in self.names if primary_contains(query, x[0]) or primary_contains(query, x[1])] self.endResetModel() self.filtered.emit(not bool(query)) class InsertLink(Dialog): def __init__(self, container, source_name, initial_text=None, parent=None): self.container = container self.source_name = source_name self.initial_text = initial_text Dialog.__init__(self, _('Insert hyperlink'), 'insert-hyperlink', parent=parent) self.anchor_cache = {} def sizeHint(self): return QSize(800, 600) def setup_ui(self): self.l = l = QVBoxLayout(self) self.setLayout(l) self.h = h = QHBoxLayout() l.addLayout(h) names = [n for n, linear in self.container.spine_names] fn, f = create_filterable_names_list(names, filter_text=_('Filter files'), parent=self) self.file_names, self.file_names_filter = fn, f fn.selectionModel().selectionChanged.connect(self.selected_file_changed) self.fnl = fnl = QVBoxLayout() self.la1 = la = QLabel(_('Choose a &file to link to:')) la.setBuddy(fn) fnl.addWidget(la), fnl.addWidget(f), fnl.addWidget(fn) h.addLayout(fnl), h.setStretch(0, 2) fn, f = create_filterable_names_list([], filter_text=_('Filter locations'), parent=self, model=AnchorsModel) fn.setSpacing(5) self.anchor_names, self.anchor_names_filter = fn, f fn.selectionModel().selectionChanged.connect(self.update_target) fn.doubleClicked.connect(self.accept, type=Qt.ConnectionType.QueuedConnection) self.anl = fnl = QVBoxLayout() self.la2 = la = QLabel(_('Choose a &location (anchor) in the file:')) la.setBuddy(fn) fnl.addWidget(la), fnl.addWidget(f), fnl.addWidget(fn) h.addLayout(fnl), h.setStretch(1, 1) self.tl = tl = QFormLayout() tl.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow) self.target = t = QLineEdit(self) t.setPlaceholderText(_('The destination (href) for the link')) tl.addRow(_('&Target:'), t) l.addLayout(tl) self.text_edit = t = QLineEdit(self) la.setBuddy(t) tl.addRow(_('Te&xt:'), t) t.setText(self.initial_text or '') t.setPlaceholderText(_('The (optional) text for the link')) self.template_edit = t = HistoryComboBox(self) t.lineEdit().setClearButtonEnabled(True) t.initialize('edit_book_insert_link_template_history') tl.addRow(_('Tem&plate:'), t) from calibre.gui2.tweak_book.editor.smarts.html import DEFAULT_LINK_TEMPLATE t.setText(tprefs.get('insert-hyperlink-template', None) or DEFAULT_LINK_TEMPLATE) t.setToolTip('<p>' + _(''' The template to use for generating the link. In addition to {0} and {1} you can also use {2}, {3} and {4} variables in the template, they will be replaced by the source filename, the destination filename and the anchor, respectively. ''').format( '_TEXT_', '_TARGET_', '_SOURCE_FILENAME_', '_DEST_FILENAME_', '_ANCHOR_')) l.addWidget(self.bb) def accept(self): from calibre.gui2.tweak_book.editor.smarts.html import DEFAULT_LINK_TEMPLATE t = self.template if t: if t == DEFAULT_LINK_TEMPLATE: t = None tprefs.set('insert-hyperlink-template', self.template) return Dialog.accept(self) def selected_file_changed(self, *args): rows = list(self.file_names.selectionModel().selectedRows()) if not rows: self.anchor_names.model().set_names([]) else: name, positions = self.file_names.model().data(rows[0], Qt.ItemDataRole.UserRole) self.populate_anchors(name) def populate_anchors(self, name): if name not in self.anchor_cache: from calibre.ebooks.oeb.base import XHTML_NS root = self.container.parsed(name) ac = self.anchor_cache[name] = [] for item in set(root.xpath('//*[@id]')) | set(root.xpath('//h:a[@name]', namespaces={'h':XHTML_NS})): frag = item.get('id', None) or item.get('name') if not frag: continue text = lead_text(item, num_words=4).strip() ac.append((text, frag)) ac.sort(key=lambda text_frag: numeric_sort_key(text_frag[0] or text_frag[1])) self.anchor_names.model().set_names(self.anchor_cache[name]) self.update_target() def update_target(self): rows = list(self.file_names.selectionModel().selectedRows()) if not rows: return name = self.file_names.model().data(rows[0], Qt.ItemDataRole.UserRole)[0] if name == self.source_name: href = '' else: href = self.container.name_to_href(name, self.source_name) frag = '' rows = list(self.anchor_names.selectionModel().selectedRows()) if rows: anchor = self.anchor_names.model().data(rows[0], Qt.ItemDataRole.UserRole)[1] if anchor: frag = '#' + anchor href += frag self.target.setText(href or '#') @property def href(self): return str(self.target.text()).strip() @property def text(self): return str(self.text_edit.text()).strip() @property def template(self): return self.template_edit.text().strip() or None @property def rendered_template(self): ans = self.template if ans: target = self.href frag = target.partition('#')[-1] if target.startswith('#'): target = '' else: target = target.split('#', 1)[0] target = self.container.href_to_name(target) ans = ans.replace('_SOURCE_FILENAME_', self.source_name or '') ans = ans.replace('_DEST_FILENAME_', target or '') ans = ans.replace('_ANCHOR_', frag or '') return ans @classmethod def test(cls): import sys from calibre.ebooks.oeb.polish.container import get_container c = get_container(sys.argv[-1], tweak_mode=True) d = cls(c, next(c.spine_names)[0]) if d.exec() == QDialog.DialogCode.Accepted: print(d.href, d.text) # }}} # Insert Semantics {{{ class InsertSemantics(Dialog): def __init__(self, container, parent=None): self.container = container self.create_known_type_map() self.anchor_cache = {} self.original_guide_map = {item['type']: item for item in get_guide_landmarks(container)} self.original_nav_map = {item['type']: item for item in get_nav_landmarks(container)} self.changes = {} Dialog.__init__(self, _('Set semantics'), 'insert-semantics', parent=parent) def sizeHint(self): return QSize(800, 600) def create_known_type_map(self): def _(x): return x self.epubtype_guide_map = {v: k for k, v in guide_epubtype_map.items()} self.known_type_map = { 'titlepage': _('Title page'), 'toc': _('Table of Contents'), 'index': _('Index'), 'glossary': _('Glossary'), 'acknowledgments': _('Acknowledgements'), 'bibliography': _('Bibliography'), 'colophon': _('Colophon'), 'cover': _('Cover'), 'copyright-page': _('Copyright page'), 'dedication': _('Dedication'), 'epigraph': _('Epigraph'), 'foreword': _('Foreword'), 'loi': _('List of illustrations'), 'lot': _('List of tables'), 'notes': _('Notes'), 'preface': _('Preface'), 'bodymatter': _('Text'), } _ = __builtins__['_'] type_map_help = { 'titlepage': _('Page with title, author, publisher, etc.'), 'cover': _('The book cover, typically a single HTML file with a cover image inside'), 'index': _('Back-of-book style index'), 'bodymatter': _('First "real" page of content'), } t = _ all_types = [(k, ((f'{t(v)} ({type_map_help[k]})') if k in type_map_help else t(v))) for k, v in iteritems(self.known_type_map)] all_types.sort(key=lambda x: sort_key(x[1])) self.all_types = OrderedDict(all_types) def setup_ui(self): self.l = l = QVBoxLayout(self) self.setLayout(l) self.tl = tl = QFormLayout() tl.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow) self.semantic_type = QComboBox(self) for key, val in iteritems(self.all_types): self.semantic_type.addItem(val, key) tl.addRow(_('Type of &semantics:'), self.semantic_type) self.target = t = QLineEdit(self) t.setClearButtonEnabled(True) t.setPlaceholderText(_('The destination (href) for the link')) tl.addRow(_('&Target:'), t) l.addLayout(tl) self.hline = hl = QFrame(self) hl.setFrameStyle(QFrame.Shape.HLine) l.addWidget(hl) self.h = h = QHBoxLayout() l.addLayout(h) names = [n for n, linear in self.container.spine_names] fn, f = create_filterable_names_list(names, filter_text=_('Filter files'), parent=self) self.file_names, self.file_names_filter = fn, f fn.selectionModel().selectionChanged.connect(self.selected_file_changed) self.fnl = fnl = QVBoxLayout() self.la1 = la = QLabel(_('Choose a &file:')) la.setBuddy(fn) fnl.addWidget(la), fnl.addWidget(f), fnl.addWidget(fn) h.addLayout(fnl), h.setStretch(0, 2) fn, f = create_filterable_names_list([], filter_text=_('Filter locations'), parent=self) self.anchor_names, self.anchor_names_filter = fn, f fn.selectionModel().selectionChanged.connect(self.update_target) fn.doubleClicked.connect(self.accept, type=Qt.ConnectionType.QueuedConnection) self.anl = fnl = QVBoxLayout() self.la2 = la = QLabel(_('Choose a &location (anchor) in the file:')) la.setBuddy(fn) fnl.addWidget(la), fnl.addWidget(f), fnl.addWidget(fn) h.addLayout(fnl), h.setStretch(1, 1) self.bb.addButton(QDialogButtonBox.StandardButton.Help) self.bb.helpRequested.connect(self.help_requested) l.addWidget(self.bb) self.semantic_type_changed() self.semantic_type.currentIndexChanged.connect(self.semantic_type_changed) self.target.textChanged.connect(self.target_text_changed) def help_requested(self): d = info_dialog(self, _('About semantics'), _( 'Semantics refer to additional information about specific locations in the book.' ' For example, you can specify that a particular location is the dedication or the preface' ' or the Table of Contents and so on.\n\nFirst choose the type of semantic information, then' ' choose a file and optionally a location within the file to point to.\n\nThe' ' semantic information will be written in the <guide> section of the OPF file.')) d.resize(d.sizeHint()) d.exec() def dest_for_type(self, item_type): if item_type in self.changes: return self.changes[item_type] if item_type in self.original_nav_map: item = self.original_nav_map[item_type] return item['dest'], item['frag'] item_type = self.epubtype_guide_map.get(item_type, item_type) if item_type in self.original_guide_map: item = self.original_guide_map[item_type] return item['dest'], item['frag'] return None, None def semantic_type_changed(self): item_type = str(self.semantic_type.itemData(self.semantic_type.currentIndex()) or '') name, frag = self.dest_for_type(item_type) self.show_type(name, frag) def show_type(self, name, frag): self.file_names_filter.clear(), self.anchor_names_filter.clear() self.file_names.clearSelection(), self.anchor_names.clearSelection() if name is not None: row = self.file_names.model().find_name(name) if row is not None: sm = self.file_names.selectionModel() sm.select(self.file_names.model().index(row), QItemSelectionModel.SelectionFlag.ClearAndSelect) if frag: row = self.anchor_names.model().find_name(frag) if row is not None: sm = self.anchor_names.selectionModel() sm.select(self.anchor_names.model().index(row), QItemSelectionModel.SelectionFlag.ClearAndSelect) self.target.blockSignals(True) if name is not None: self.target.setText(name + (('#' + frag) if frag else '')) else: self.target.setText('') self.target.blockSignals(False) def target_text_changed(self): name, frag = str(self.target.text()).partition('#')[::2] item_type = str(self.semantic_type.itemData(self.semantic_type.currentIndex()) or '') if item_type: self.changes[item_type] = (name, frag or None) def selected_file_changed(self, *args): rows = list(self.file_names.selectionModel().selectedRows()) if not rows: self.anchor_names.model().set_names([]) else: name, positions = self.file_names.model().data(rows[0], Qt.ItemDataRole.UserRole) self.populate_anchors(name) def populate_anchors(self, name): if name not in self.anchor_cache: from calibre.ebooks.oeb.base import XHTML_NS root = self.container.parsed(name) self.anchor_cache[name] = sorted( (set(root.xpath('//*/@id')) | set(root.xpath('//h:a/@name', namespaces={'h':XHTML_NS}))) - {''}, key=primary_sort_key) self.anchor_names.model().set_names(self.anchor_cache[name]) self.update_target() def update_target(self): rows = list(self.file_names.selectionModel().selectedRows()) if not rows: return name = self.file_names.model().data(rows[0], Qt.ItemDataRole.UserRole)[0] href = name frag = '' rows = list(self.anchor_names.selectionModel().selectedRows()) if rows: anchor = self.anchor_names.model().data(rows[0], Qt.ItemDataRole.UserRole)[0] if anchor: frag = '#' + anchor href += frag self.target.setText(href or '#') def apply_changes(self, container): from calibre.ebooks.oeb.polish.opf import get_book_language, set_guide_item from calibre.translations.dynamic import translate lang = get_book_language(container) def title_for_type(item_type): title = self.known_type_map.get(item_type, item_type) if lang: title = translate(lang, title) return title for item_type, (name, frag) in self.changes.items(): guide_type = self.epubtype_guide_map.get(item_type) if not guide_type: if container.opf_version_parsed.major < 3: raise KeyError(_('Cannot set {} type semantics in EPUB 2 or AZW3 books').format(name)) continue set_guide_item(container, guide_type, title_for_type(item_type), name, frag=frag) if container.opf_version_parsed.major > 2: final = self.original_nav_map.copy() for item_type, (name, frag) in self.changes.items(): final[item_type] = {'dest': name, 'frag': frag or '', 'title': title_for_type(item_type), 'type': item_type} tocname, root = ensure_container_has_nav(container, lang=lang) set_landmarks(container, root, tocname, final.values()) container.dirty(tocname) @classmethod def test(cls): import sys from calibre.ebooks.oeb.polish.container import get_container c = get_container(sys.argv[-1], tweak_mode=True) d = cls(c) if d.exec() == QDialog.DialogCode.Accepted: import pprint pprint.pprint(d.changed_type_map) d.apply_changes(d.container) # }}} class FilterCSS(Dialog): # {{{ def __init__(self, current_name=None, parent=None): self.current_name = current_name Dialog.__init__(self, _('Filter style information'), 'filter-css', parent=parent) def setup_ui(self): from calibre.gui2.convert.look_and_feel_ui import Ui_Form f, w = Ui_Form(), QWidget() f.setupUi(w) self.l = l = QFormLayout(self) self.setLayout(l) l.addRow(QLabel(_('Select what style information you want completely removed:'))) self.h = h = QHBoxLayout() for name, text in ( ('fonts', _('&Fonts')), ('margins', _('&Margins')), ('padding', _('&Padding')), ('floats', _('Flo&ats')), ('colors', _('&Colors')), ): c = QCheckBox(text) setattr(self, 'opt_' + name, c) h.addWidget(c) c.setToolTip(getattr(f, 'filter_css_' + name).toolTip()) l.addRow(h) self.others = o = QLineEdit(self) l.addRow(_('&Other CSS properties:'), o) o.setToolTip(f.filter_css_others.toolTip()) if self.current_name is not None: self.filter_current = c = QCheckBox(_('Only filter CSS in the current file (%s)') % self.current_name) l.addRow(c) l.addRow(self.bb) @property def filter_names(self): if self.current_name is not None and self.filter_current.isChecked(): return (self.current_name,) return () @property def filtered_properties(self): ans = set() a = ans.add if self.opt_fonts.isChecked(): a('font-family') if self.opt_margins.isChecked(): a('margin') if self.opt_padding.isChecked(): a('padding') if self.opt_floats.isChecked(): a('float'), a('clear') if self.opt_colors.isChecked(): a('color'), a('background-color') for x in str(self.others.text()).split(','): x = x.strip() if x: a(x) return ans @classmethod def test(cls): d = cls() if d.exec() == QDialog.DialogCode.Accepted: print(d.filtered_properties) # }}} # Add Cover {{{ class CoverView(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.current_pixmap_size = QSize(0, 0) self.pixmap = QPixmap() self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) def set_pixmap(self, data): self.pixmap.loadFromData(data) self.current_pixmap_size = self.pixmap.size() self.update() def paintEvent(self, event): if self.pixmap.isNull(): return canvas_size = self.rect() width = self.current_pixmap_size.width() extrax = canvas_size.width() - width if extrax < 0: extrax = 0 x = int(extrax/2.) height = self.current_pixmap_size.height() extray = canvas_size.height() - height if extray < 0: extray = 0 y = int(extray/2.) target = QRect(x, y, min(canvas_size.width(), width), min(canvas_size.height(), height)) p = QPainter(self) p.setRenderHints(QPainter.RenderHint.Antialiasing | QPainter.RenderHint.SmoothPixmapTransform) p.drawPixmap(target, self.pixmap.scaled(target.size(), Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)) p.end() def sizeHint(self): return QSize(300, 400) class AddCover(Dialog): import_requested = pyqtSignal(object, object) def __init__(self, container, parent=None): self.container = container Dialog.__init__(self, _('Add a cover'), 'add-cover-wizard', parent) @property def image_names(self): img_types = {guess_type('a.'+x) for x in ('png', 'jpeg', 'gif')} for name, mt in iteritems(self.container.mime_map): if mt.lower() in img_types: yield name def setup_ui(self): self.l = l = QVBoxLayout(self) self.setLayout(l) self.gb = gb = QGroupBox(_('&Images in book'), self) self.v = v = QVBoxLayout(gb) gb.setLayout(v), gb.setFlat(True) self.names, self.names_filter = create_filterable_names_list( sorted(self.image_names, key=sort_key), filter_text=_('Filter the list of images'), parent=self) self.names.doubleClicked.connect(self.double_clicked, type=Qt.ConnectionType.QueuedConnection) self.cover_view = CoverView(self) l.addWidget(self.names_filter) v.addWidget(self.names) self.splitter = s = QSplitter(self) l.addWidget(s) s.addWidget(gb) s.addWidget(self.cover_view) self.h = h = QHBoxLayout() self.preserve = p = QCheckBox(_('Preserve aspect ratio')) p.setToolTip(textwrap.fill(_('If enabled the cover image you select will be embedded' ' into the book in such a way that when viewed, its aspect' ' ratio (ratio of width to height) will be preserved.' ' This will mean blank spaces around the image if the screen' ' the book is being viewed on has an aspect ratio different' ' to the image.'))) p.setChecked(tprefs['add_cover_preserve_aspect_ratio']) p.setVisible(self.container.book_type != 'azw3') def on_state_change(s): tprefs.set('add_cover_preserve_aspect_ratio', Qt.CheckState(s) == Qt.CheckState.Checked) p.stateChanged.connect(on_state_change) self.info_label = il = QLabel('\xa0') h.addWidget(p), h.addStretch(1), h.addWidget(il) l.addLayout(h) l.addWidget(self.bb) b = self.bb.addButton(_('Import &image'), QDialogButtonBox.ButtonRole.ActionRole) b.clicked.connect(self.import_image) b.setIcon(QIcon.ic('document_open.png')) self.names.setFocus(Qt.FocusReason.OtherFocusReason) self.names.selectionModel().currentChanged.connect(self.current_image_changed) cname = get_raster_cover_name(self.container) if cname: row = self.names.model().find_name(cname) if row > -1: self.names.setCurrentIndex(self.names.model().index(row)) def double_clicked(self): self.accept() @property def file_name(self): return self.names.model().name_for_index(self.names.currentIndex()) def current_image_changed(self): self.info_label.setText('') name = self.file_name if name is not None: data = self.container.raw_data(name, decode=False) self.cover_view.set_pixmap(data) self.info_label.setText('{}x{}px | {}'.format( self.cover_view.pixmap.width(), self.cover_view.pixmap.height(), human_readable(len(data)))) def import_image(self): ans = choose_images(self, 'add-cover-choose-image', _('Choose a cover image'), formats=( 'jpg', 'jpeg', 'png', 'gif')) if ans: from calibre.gui2.tweak_book.file_list import NewFileDialog d = NewFileDialog(self) d.do_import_file(ans[0], hide_button=True) if d.exec() == QDialog.DialogCode.Accepted: self.import_requested.emit(d.file_name, d.file_data) self.container = current_container() self.names_filter.clear() self.names.model().set_names(sorted(self.image_names, key=sort_key)) i = self.names.model().find_name(d.file_name) self.names.setCurrentIndex(self.names.model().index(i)) self.current_image_changed() @classmethod def test(cls): import sys from calibre.ebooks.oeb.polish.container import get_container c = get_container(sys.argv[-1], tweak_mode=True) d = cls(c) if d.exec() == QDialog.DialogCode.Accepted: pass # }}} class PlainTextEdit(QPlainTextEdit): # {{{ ''' A class that overrides some methods from QPlainTextEdit to fix handling of the nbsp unicode character and AltGr input method on windows. ''' def __init__(self, parent=None): QPlainTextEdit.__init__(self, parent) self.syntax = None def toPlainText(self): return to_plain_text(self) def selected_text_from_cursor(self, cursor): return unicodedata.normalize('NFC', str(cursor.selectedText()).replace(PARAGRAPH_SEPARATOR, '\n').rstrip('\0')) @property def selected_text(self): return self.selected_text_from_cursor(self.textCursor()) def createMimeDataFromSelection(self): ans = QMimeData() ans.setText(self.selected_text) return ans def show_tooltip(self, ev): pass def override_shortcut(self, ev): if iswindows and self.windows_ignore_altgr_shortcut(ev): ev.accept() return True def windows_ignore_altgr_shortcut(self, ev): from calibre_extensions import winutil s = winutil.get_async_key_state(winutil.VK_RMENU) # VK_RMENU == R_ALT return s & 0x8000 def event(self, ev): et = ev.type() if et == QEvent.Type.ToolTip: self.show_tooltip(ev) return True if et == QEvent.Type.ShortcutOverride: ret = self.override_shortcut(ev) if ret: return True return QPlainTextEdit.event(self, ev) def mouseDoubleClickEvent(self, ev): super().mouseDoubleClickEvent(ev) c = self.textCursor() # Workaround for QTextCursor considering smart quotes as word # characters https://bugreports.qt.io/browse/QTBUG-101372 changed = False while True: q = c.selectedText() if not q: break left = min(c.anchor(), c.position()) right = max(c.anchor(), c.position()) if q[0] in '“‘': changed = True c.setPosition(left + 1) c.setPosition(right, QTextCursor.MoveMode.KeepAnchor) elif q[-1] in '’”': changed = True c.setPosition(left) c.setPosition(right - 1, QTextCursor.MoveMode.KeepAnchor) else: break if changed: self.setTextCursor(c) # }}} if __name__ == '__main__': app = QApplication([]) AddCover.test()
48,899
Python
.py
1,125
33.776889
159
0.602049
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,707
job.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/job.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' import time from functools import partial from threading import Thread from qt.core import QApplication, QBrush, QCursor, QLabel, QPainter, QRect, Qt, QVBoxLayout, QWidget from calibre.gui2 import Dispatcher from calibre.gui2.progress_indicator import ProgressIndicator class LongJob(Thread): daemon = True def __init__(self, name, user_text, callback, function, *args, **kwargs): Thread.__init__(self, name=name) self.user_text = user_text self.function = function self.args, self.kwargs = args, kwargs self.result = self.traceback = None self.time_taken = None self.callback = callback def run(self): st = time.time() try: self.result = self.function(*self.args, **self.kwargs) except: import traceback self.traceback = traceback.format_exc() self.time_taken = time.time() - st try: self.callback(self) finally: pass class BlockingJob(QWidget): def __init__(self, parent): QWidget.__init__(self, parent) l = QVBoxLayout() self.setLayout(l) l.addStretch(10) self.pi = ProgressIndicator(self, 128) l.addWidget(self.pi, alignment=Qt.AlignmentFlag.AlignHCenter) self.dummy = QLabel('<h2>\xa0') l.addSpacing(10) l.addWidget(self.dummy, alignment=Qt.AlignmentFlag.AlignHCenter) l.addStretch(10) self.setVisible(False) self.text = '' self.setFocusPolicy(Qt.FocusPolicy.NoFocus) def start(self): self.setGeometry(0, 0, self.parent().width(), self.parent().height()) self.setVisible(True) # Prevent any actions from being triggered by key presses self.parent().setEnabled(False) self.raise_and_focus() self.setFocus(Qt.FocusReason.OtherFocusReason) self.pi.startAnimation() QApplication.setOverrideCursor(QCursor(Qt.CursorShape.WaitCursor)) def stop(self): QApplication.restoreOverrideCursor() self.pi.stopAnimation() self.setVisible(False) self.parent().setEnabled(True) # The following line is needed on OS X, because of this bug: # https://bugreports.qt-project.org/browse/QTBUG-34371 it causes # keyboard events to no longer work self.parent().setFocus(Qt.FocusReason.OtherFocusReason) def job_done(self, callback, job): del job.callback self.stop() callback(job) def paintEvent(self, ev): br = ev.region().boundingRect() p = QPainter(self) p.setOpacity(0.2) p.fillRect(br, QBrush(self.palette().text())) p.end() QWidget.paintEvent(self, ev) p = QPainter(self) p.setClipRect(br) f = p.font() f.setBold(True) f.setPointSize(20) p.setFont(f) p.setPen(Qt.PenStyle.SolidLine) r = QRect(0, self.dummy.geometry().top() + 10, self.geometry().width(), 150) p.drawText(r, Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop | Qt.TextFlag.TextSingleLine, self.text) p.end() def set_msg(self, text): self.text = text def __call__(self, name, user_text, callback, function, *args, **kwargs): ' Run a job that blocks the GUI providing some feedback to the user ' self.set_msg(user_text) job = LongJob(name, user_text, Dispatcher(partial(self.job_done, callback)), function, *args, **kwargs) job.start() self.start()
3,668
Python
.py
93
31.397849
120
0.639483
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,708
preferences.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/preferences.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' import numbers from collections import namedtuple from copy import copy, deepcopy from functools import partial from itertools import product from operator import attrgetter, methodcaller from qt.core import ( QAbstractItemView, QCheckBox, QComboBox, QDialog, QDialogButtonBox, QDoubleSpinBox, QFont, QFontComboBox, QFormLayout, QGridLayout, QGroupBox, QHBoxLayout, QIcon, QLabel, QListView, QListWidget, QListWidgetItem, QPushButton, QRadioButton, QSize, QSizePolicy, QSpacerItem, QSpinBox, QStackedWidget, Qt, QTimer, QToolButton, QVBoxLayout, QWidget, pyqtSignal, ) from calibre import prepare_string_for_xml from calibre.gui2 import info_dialog from calibre.gui2.font_family_chooser import FontFamilyChooser from calibre.gui2.keyboard import ShortcutConfig from calibre.gui2.tweak_book import actions, editor_toolbar_actions, toolbar_actions, tprefs from calibre.gui2.tweak_book.editor.themes import ThemeEditor, all_theme_names, default_theme from calibre.gui2.tweak_book.spell import ManageDictionaries from calibre.gui2.tweak_book.widgets import Dialog from calibre.gui2.widgets2 import ColorButton from calibre.startup import connect_lambda from calibre.utils.localization import get_lang, ngettext from polyglot.builtins import iteritems, itervalues class BasicSettings(QWidget): # {{{ changed_signal = pyqtSignal() def __init__(self, parent=None): QWidget.__init__(self, parent) self.settings = {} self._prevent_changed = False self.Setting = namedtuple('Setting', 'name prefs widget getter setter initial_value') def __call__(self, name, widget=None, getter=None, setter=None, prefs=None): prefs = prefs or tprefs defval = prefs.defaults[name] inval = prefs[name] if widget is None: if isinstance(defval, bool): widget = QCheckBox(self) getter = getter or methodcaller('isChecked') setter = setter or (lambda x, v: x.setChecked(v)) widget.toggled.connect(self.emit_changed) elif isinstance(defval, numbers.Number): widget = (QSpinBox if isinstance(defval, numbers.Integral) else QDoubleSpinBox)(self) getter = getter or methodcaller('value') setter = setter or (lambda x, v:x.setValue(v)) widget.valueChanged.connect(self.emit_changed) else: raise TypeError('Unknown setting type for setting: %s' % name) else: if getter is None or setter is None: raise ValueError("getter or setter not provided for: %s" % name) self._prevent_changed = True setter(widget, inval) self._prevent_changed = False self.settings[name] = self.Setting(name, prefs, widget, getter, setter, inval) return widget def choices_widget(self, name, choices, fallback_val, none_val, prefs=None): prefs = prefs or tprefs widget = QComboBox(self) widget.currentIndexChanged.connect(self.emit_changed) for key, human in sorted(iteritems(choices), key=lambda key_human: key_human[1] or key_human[0]): widget.addItem(human or key, key) def getter(w): ans = str(w.itemData(w.currentIndex()) or '') return {none_val:None}.get(ans, ans) def setter(w, val): val = {None:none_val}.get(val, val) idx = w.findData(val, flags=Qt.MatchFlag.MatchFixedString|Qt.MatchFlag.MatchCaseSensitive) if idx == -1: idx = w.findData(fallback_val, flags=Qt.MatchFlag.MatchFixedString|Qt.MatchFlag.MatchCaseSensitive) w.setCurrentIndex(idx) return self(name, widget=widget, getter=getter, setter=setter, prefs=prefs) def order_widget(self, name, prefs=None): prefs = prefs or tprefs widget = QListWidget(self) widget.addItems(prefs.defaults[name]) widget.setDragEnabled(True) widget.setDragDropMode(QAbstractItemView.DragDropMode.InternalMove) widget.viewport().setAcceptDrops(True) widget.setDropIndicatorShown(True) widget.indexesMoved.connect(self.emit_changed) widget.setDefaultDropAction(Qt.DropAction.MoveAction) widget.setMovement(QListView.Movement.Snap) widget.setSpacing(5) widget.defaults = prefs.defaults[name] def getter(w): return list(map(str, (w.item(i).text() for i in range(w.count())))) def setter(w, val): order_map = {x:i for i, x in enumerate(val)} items = list(w.defaults) limit = len(items) items.sort(key=lambda x:order_map.get(x, limit)) w.clear() for x in items: i = QListWidgetItem(w) i.setText(x) i.setFlags(i.flags() | Qt.ItemFlag.ItemIsDragEnabled) return self(name, widget=widget, getter=getter, setter=setter, prefs=prefs) def emit_changed(self, *args): if not self._prevent_changed: self.changed_signal.emit() def commit(self): with tprefs: for name in self.settings: cv = self.current_value(name) if self.initial_value(name) != cv: prefs = self.settings[name].prefs if cv == self.default_value(name): del prefs[name] else: prefs[name] = cv def restore_defaults(self): for setting in itervalues(self.settings): setting.setter(setting.widget, self.default_value(setting.name)) def initial_value(self, name): return self.settings[name].initial_value def current_value(self, name): s = self.settings[name] return s.getter(s.widget) def default_value(self, name): s = self.settings[name] return s.prefs.defaults[name] def setting_changed(self, name): return self.current_value(name) != self.initial_value(name) # }}} class EditorSettings(BasicSettings): # {{{ def __init__(self, parent=None): BasicSettings.__init__(self, parent) self.dictionaries_changed = self.snippets_changed = False self.l = l = QFormLayout(self) self.setLayout(l) fc = FontFamilyChooser(self) self('editor_font_family', widget=fc, getter=attrgetter('font_family'), setter=lambda x, val: setattr(x, 'font_family', val)) fc.family_changed.connect(self.emit_changed) l.addRow(_('Editor font &family:'), fc) fs = self('editor_font_size') fs.setMinimum(8), fs.setSuffix(' pt'), fs.setMaximum(50) l.addRow(_('Editor font &size:'), fs) cs = self('editor_cursor_width') cs.setMinimum(1), cs.setSuffix(' px'), cs.setMaximum(50) l.addRow(_('Editor cursor &width:'), cs) choices = self.theme_choices() theme = self.choices_widget('editor_theme', choices, 'auto', 'auto') self.custom_theme_button = b = QPushButton(_('Create/edit &custom color schemes')) b.clicked.connect(self.custom_theme) h = QHBoxLayout() h.addWidget(theme), h.addWidget(b) l.addRow(_('&Color scheme:'), h) l.labelForField(h).setBuddy(theme) tw = self('editor_tab_stop_width') tw.setMinimum(2), tw.setSuffix(_(' characters')), tw.setMaximum(20) l.addRow(_('W&idth of tabs:'), tw) self.tb = b = QPushButton(_('Change &templates')) l.addRow(_('Templates for new files:'), b) connect_lambda(b.clicked, self, lambda self: TemplatesDialog(self).exec()) lw = self('editor_line_wrap') lw.setText(_('&Wrap long lines in the editor')) l.addRow(lw) lw = self('replace_entities_as_typed') lw.setText(_('&Replace HTML entities as they are typed')) lw.setToolTip('<p>' + _( 'With this option, every time you type in a complete html entity, such as &amp;hellip;' ' it is automatically replaced by its corresponding character. The replacement' ' happens only when the trailing semi-colon is typed.')) l.addRow(lw) lw = self('auto_close_tags') lw.setText(_('Auto close t&ags when typing </')) lw.setToolTip('<p>' + prepare_string_for_xml(_( 'With this option, every time you type </ the current HTML closing tag is auto-completed'))) l.addRow(lw) lw = self('editor_show_char_under_cursor') lw.setText(_('Show the &name of the current character before the cursor along with the line and column number')) l.addRow(lw) lw = self('pretty_print_on_open') lw.setText(_('Beautify individual &files automatically when they are opened')) lw.setToolTip('<p>' + _( 'This will cause the beautify current file action to be performed automatically every' ' time you open a HTML/CSS/etc. file for editing.')) l.addRow(lw) lw = self('inline_spell_check') lw.setText(_('Show &misspelled words underlined in the code view')) lw.setToolTip('<p>' + _( 'This will cause spelling errors to be highlighted in the code view' ' for easy correction as you type.')) l.addRow(lw) lw = self('editor_accepts_drops') lw.setText(_('Allow drag and drop &editing of text')) lw.setToolTip('<p>' + _( 'Allow using drag and drop to move text around in the editor.' ' It can be useful to turn this off if you have a misbehaving touchpad.')) l.addRow(lw) self.dictionaries = d = QPushButton(_('Manage &spelling dictionaries'), self) d.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) d.clicked.connect(self.manage_dictionaries) l.addRow(d) self.snippets = s = QPushButton(_('Manage sni&ppets'), self) s.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) s.clicked.connect(self.manage_snippets) l.addRow(s) def manage_dictionaries(self): d = ManageDictionaries(self) d.exec() self.dictionaries_changed = True def manage_snippets(self): from calibre.gui2.tweak_book.editor.snippets import UserSnippets d = UserSnippets(self) if d.exec() == QDialog.DialogCode.Accepted: self.snippets_changed = True def theme_choices(self): choices = {k:k for k in all_theme_names()} choices['auto'] = _('Automatic (%s)') % default_theme() return choices def custom_theme(self): d = ThemeEditor(parent=self) d.exec() choices = self.theme_choices() s = self.settings['editor_theme'] current_val = s.getter(s.widget) s.widget.clear() for key, human in sorted(iteritems(choices), key=lambda key_human1: key_human1[1] or key_human1[0]): s.widget.addItem(human or key, key) s.setter(s.widget, current_val) if d.theme_name: s.setter(s.widget, d.theme_name) # }}} class IntegrationSettings(BasicSettings): # {{{ def __init__(self, parent=None): BasicSettings.__init__(self, parent) self.l = l = QFormLayout(self) self.setLayout(l) um = self('update_metadata_from_calibre') um.setText(_('Update &metadata embedded in the book when opening')) um.setToolTip('<p>' + _( 'When the file is opened, update the metadata embedded in the book file to the current metadata' ' in the calibre library.')) l.addRow(um) ask = self('choose_tweak_fmt') ask.setText(_('Ask which &format to edit if more than one format is available for the book')) l.addRow(ask) order = self.order_widget('tweak_fmt_order') order.setToolTip(_('When auto-selecting the format to edit for a book with' ' multiple formats, this is the preference order.')) l.addRow(_('Preferred format order (drag and drop to change)'), order) # }}} class MainWindowSettings(BasicSettings): # {{{ def __init__(self, parent=None): BasicSettings.__init__(self, parent) self.l = l = QFormLayout(self) self.setLayout(l) nd = self('nestable_dock_widgets') nd.setText(_('Allow dockable &windows to be nested inside the dock areas')) nd.setToolTip('<p>' + _( 'By default, you can have only a single row or column of windows in the dock' ' areas (the areas around the central editors). This option allows' ' for more flexible window layout, but is a little more complex to use.')) l.addRow(nd) l.addRow(QLabel(_('Choose which windows will occupy the corners of the dockable areas'))) for v, h in product(('top', 'bottom'), ('left', 'right')): choices = {'vertical':{'left':_('Left'), 'right':_('Right')}[h], 'horizontal':{'top':_('Top'), 'bottom':_('Bottom')}[v]} name = f'dock_{v}_{h}' w = self.choices_widget(name, choices, 'horizontal', 'horizontal') cn = {('top', 'left'): _('The &top-left corner'), ('top', 'right'):_('The top-&right corner'), ('bottom', 'left'):_('The &bottom-left corner'), ('bottom', 'right'):_('The bottom-ri&ght corner')}[(v, h)] l.addRow(cn + ':', w) nd = self('restore_book_state') nd.setText(_('Restore &state of previously edited book when opening it again')) nd.setToolTip('<p>' + _( 'When opening a previously edited book again, restore its state. That means all open' ' files are automatically re-opened and the cursor is positioned at its previous location.' )) l.addRow(nd) nd = self('file_list_shows_full_pathname') nd.setText(_('Show full &file paths in the File browser')) nd.setToolTip('<p>' + _( 'Showing the full file paths is useful when editing books that contain' ' multiple files with the same file name.' )) l.addRow(nd) # }}} class PreviewSettings(BasicSettings): # {{{ def __init__(self, parent=None): BasicSettings.__init__(self, parent) self.l = l = QFormLayout(self) self.setLayout(l) self.default_font_settings = {} def default_font(which): if not self.default_font_settings: from qt.webengine import QWebEnginePage, QWebEngineSettings page = QWebEnginePage() s = page.settings() self.default_font_settings = { 'serif': s.fontFamily(QWebEngineSettings.FontFamily.SerifFont), 'sans': s.fontFamily(QWebEngineSettings.FontFamily.SansSerifFont), 'mono': s.fontFamily(QWebEngineSettings.FontFamily.FixedFont), } return self.default_font_settings[which] def family_getter(which, w): ans = str(w.currentFont().family()) if ans == default_font(which): ans = None return ans def family_setter(which, w, val): w.setCurrentFont(QFont(val or default_font(which))) families = {'serif':_('Serif text'), 'sans':_('Sans-serif text'), 'mono':_('Monospaced text')} for fam in sorted(families): text = families[fam] w = QFontComboBox(self) self('engine_preview_%s_family' % fam, widget=w, getter=partial(family_getter, fam), setter=partial(family_setter, fam)) l.addRow(_('Font family for &%s:') % text, w) w = self.choices_widget('preview_standard_font_family', families, 'serif', 'serif') l.addRow(_('Style for standard &text:'), w) w = self('preview_base_font_size') w.setMinimum(8), w.setMaximum(100), w.setSuffix(' px') l.addRow(_('&Default font size:'), w) w = self('preview_mono_font_size') w.setMinimum(8), w.setMaximum(100), w.setSuffix(' px') l.addRow(_('&Monospace font size:'), w) w = self('preview_minimum_font_size') w.setMinimum(4), w.setMaximum(100), w.setSuffix(' px') l.addRow(_('Mi&nimum font size:'), w) w = self('preview_sync_context') w.setMinimum(0), w.setMaximum(10), w.setSuffix(' ' + _('lines')) w.setToolTip('<p>' + _( 'Number of lines that are shown above the current line when syncing the text shown in the preview panel to the cursor position in the code view')) l.addRow(_('Visible lines above s&ync point:'), w) l.addRow(_('Background color:'), self.color_override('preview_background')) l.addRow(_('Foreground color:'), self.color_override('preview_foreground')) l.addRow(_('Link color:'), self.color_override('preview_link_color')) def color_override(self, name): w = QWidget(self) l = QHBoxLayout(w) def b(name, text, tt): ans = QRadioButton(text, w) l.addWidget(ans) ans.setToolTip(tt) setattr(w, name, ans) ans.setObjectName(name) return ans b('unset', _('No change'), _('Use the colors from the book styles, defaulting to black-on-white.' ' Note that in dark mode, you must set all three colors to "No change"' ' otherwise the book is rendered with dark colors.')) b('auto', _('Theme based'), _('When using a dark theme force dark colors, otherwise same as "No change"')) b('manual', _('Custom'), _('Choose a custom color')) c = w.color_button = ColorButton(parent=w) l.addWidget(c) connect_lambda(c.clicked, w, lambda w: w.manual.setChecked(True)) def getter(w): if w.unset.isChecked(): return 'unset' if w.auto.isChecked(): return 'auto' return w.color_button.color or 'auto' def setter(w, val): val = val or 'auto' if val == 'unset': w.unset.setChecked(True) elif val == 'auto': w.auto.setChecked(True) else: w.manual.setChecked(True) w.color_button.color = val self(name, widget=w, getter=getter, setter=setter) l.setContentsMargins(0, 0, 0, 0) return w # }}} # ToolbarSettings {{{ class ToolbarList(QListWidget): def __init__(self, parent=None): QListWidget.__init__(self, parent) self.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) class ToolbarSettings(QWidget): changed_signal = pyqtSignal() def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = gl = QGridLayout(self) self.changed = False self.bars = b = QComboBox(self) b.addItem(_('Choose which toolbar you want to customize')) ft = _('Tools for %s editors') for name, text in ( ('global_book_toolbar', _('Book wide actions'),), ('global_tools_toolbar', _('Book wide tools'),), ('global_plugins_toolbar', _('Book wide tools from third party plugins'),), ('editor_common_toolbar', _('Common tools for all editors')), ('editor_html_toolbar', ft % 'HTML',), ('editor_css_toolbar', ft % 'CSS',), ('editor_xml_toolbar', ft % 'XML',), ('editor_format_toolbar', _('Text formatting actions'),), ): b.addItem(text, name) self.la = la = QLabel(_('&Toolbar to customize:')) la.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) la.setBuddy(b) gl.addWidget(la), gl.addWidget(b, 0, 1) self.sl = l = QGridLayout() gl.addLayout(l, 1, 0, 1, -1) self.gb1 = gb1 = QGroupBox(_('A&vailable actions'), self) self.gb2 = gb2 = QGroupBox(_('&Current actions'), self) gb1.setFlat(True), gb2.setFlat(True) gb1.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) gb2.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) l.addWidget(gb1, 0, 0, -1, 1), l.addWidget(gb2, 0, 2, -1, 1) self.available, self.current = ToolbarList(self), ToolbarList(self) self.available.itemDoubleClicked.connect(self.add_single_action) self.current.itemDoubleClicked.connect(self.remove_single_action) self.ub = b = QToolButton(self) connect_lambda(b.clicked, self, lambda self: self.move(up=True)) b.setToolTip(_('Move selected action up')), b.setIcon(QIcon.ic('arrow-up.png')) self.db = b = QToolButton(self) connect_lambda(b.clicked, self, lambda self: self.move(up=False)) b.setToolTip(_('Move selected action down')), b.setIcon(QIcon.ic('arrow-down.png')) self.gl1 = gl1 = QVBoxLayout() gl1.addWidget(self.available), gb1.setLayout(gl1) self.gl2 = gl2 = QGridLayout() gl2.addWidget(self.current, 0, 0, -1, 1) gl2.addWidget(self.ub, 0, 1), gl2.addWidget(self.db, 2, 1) gb2.setLayout(gl2) self.lb = b = QToolButton(self) b.setToolTip(_('Add selected actions to the toolbar')), b.setIcon(QIcon.ic('forward.png')) l.addWidget(b, 1, 1), b.clicked.connect(self.add_action) self.rb = b = QToolButton(self) b.setToolTip(_('Remove selected actions from the toolbar')), b.setIcon(QIcon.ic('back.png')) l.addWidget(b, 3, 1), b.clicked.connect(self.remove_action) self.si = QSpacerItem(20, 10, hPolicy=QSizePolicy.Policy.Preferred, vPolicy=QSizePolicy.Policy.Expanding) l.setRowStretch(0, 10), l.setRowStretch(2, 10), l.setRowStretch(4, 10) l.addItem(self.si, 4, 1) self.read_settings() self.toggle_visibility(False) self.bars.currentIndexChanged.connect(self.bar_changed) self.toolbar_icon_size = ics = QSpinBox(self) ics.setMinimum(16), ics.setMaximum(128), ics.setSuffix(' px'), ics.setValue(tprefs['toolbar_icon_size']) ics.setToolTip('<p>' + _('Adjust the size of icons on all toolbars')) self.h = h = QHBoxLayout() gl.addLayout(h, gl.rowCount(), 0, 1, -1) self.toolbar_icon_size_label = la = QLabel(_('Toolbar &icon size:')) la.setBuddy(ics) h.addWidget(la), h.addWidget(ics), h.addStretch(10) def read_settings(self, prefs=None): prefs = prefs or tprefs val = self.original_settings = {} for i in range(1, self.bars.count()): name = str(self.bars.itemData(i) or '') val[name] = copy(prefs[name]) self.current_settings = deepcopy(val) @property def current_name(self): return str(self.bars.itemData(self.bars.currentIndex()) or '') def build_lists(self): from calibre.gui2.tweak_book.plugin import plugin_toolbar_actions self.available.clear(), self.current.clear() name = self.current_name if not name: return items = self.current_settings[name] applied = set(items) if name == 'global_plugins_toolbar': all_items = {x.sid:x for x in plugin_toolbar_actions} elif name.startswith('global_'): all_items = toolbar_actions elif name == 'editor_common_toolbar': all_items = {x:actions[x] for x in tprefs.defaults[name] if x} else: all_items = editor_toolbar_actions[name.split('_')[1]] blank = QIcon.ic('blank.png') def to_item(key, ac, parent): ic = ac.icon() if not ic or ic.isNull(): ic = blank ans = QListWidgetItem(ic, str(ac.text()).replace('&', ''), parent) ans.setData(Qt.ItemDataRole.UserRole, key) ans.setToolTip(ac.toolTip()) return ans for key, ac in sorted(iteritems(all_items), key=lambda k_ac: str(k_ac[1].text())): if key not in applied: to_item(key, ac, self.available) if name == 'global_book_toolbar' and 'donate' not in applied: QListWidgetItem(QIcon.ic('donate.png'), _('Donate'), self.available).setData(Qt.ItemDataRole.UserRole, 'donate') QListWidgetItem(blank, '--- %s ---' % _('Separator'), self.available) for key in items: if key is None: QListWidgetItem(blank, '--- %s ---' % _('Separator'), self.current) else: if key == 'donate': QListWidgetItem(QIcon.ic('donate.png'), _('Donate'), self.current).setData(Qt.ItemDataRole.UserRole, 'donate') else: try: ac = all_items[key] except KeyError: pass else: to_item(key, ac, self.current) def bar_changed(self): name = self.current_name self.toggle_visibility(bool(name)) self.build_lists() def toggle_visibility(self, visible): for x in ('gb1', 'gb2', 'lb', 'rb'): getattr(self, x).setVisible(visible) def move(self, up=True): r = self.current.currentRow() v = self.current if r < 0 or (r < 1 and up) or (r > v.count() - 2 and not up): return try: s = self.current_settings[self.current_name] except KeyError: return item = v.takeItem(r) nr = r + (-1 if up else 1) v.insertItem(nr, item) v.setCurrentItem(item) s[r], s[nr] = s[nr], s[r] self.changed_signal.emit() def add_action(self): self._add_action(self.available.selectedItems()) def add_single_action(self, item): self._add_action([item]) def _add_action(self, items): try: s = self.current_settings[self.current_name] except KeyError: return names = [str(i.data(Qt.ItemDataRole.UserRole) or '') for i in items] if not names: return for n in names: s.append(n or None) self.build_lists() self.changed_signal.emit() def remove_action(self): self._remove_action(self.current.selectedItems()) def remove_single_action(self, item): self._remove_action([item]) def _remove_action(self, items): try: s = self.current_settings[self.current_name] except KeyError: return rows = sorted({self.current.row(i) for i in items}, reverse=True) if not rows: return for r in rows: s.pop(r) self.build_lists() self.changed_signal.emit() def restore_defaults(self): o = self.original_settings self.read_settings(tprefs.defaults) self.original_settings = o self.build_lists() self.toolbar_icon_size.setValue(tprefs.defaults['toolbar_icon_size']) self.changed_signal.emit() def commit(self): if self.toolbar_icon_size.value() != tprefs['toolbar_icon_size']: tprefs['toolbar_icon_size'] = self.toolbar_icon_size.value() if self.original_settings != self.current_settings: self.changed = True with tprefs: tprefs.update(self.current_settings) # }}} class TemplatesDialog(Dialog): # {{{ def __init__(self, parent=None): self.ignore_changes = False Dialog.__init__(self, _('Customize templates'), 'customize-templates', parent=parent) def setup_ui(self): from calibre.gui2.tweak_book.editor.text import TextEdit from calibre.gui2.tweak_book.templates import DEFAULT_TEMPLATES # Cannot use QFormLayout as it does not play nice with TextEdit on windows self.l = l = QVBoxLayout(self) self.syntaxes = s = QComboBox(self) s.addItems(sorted(DEFAULT_TEMPLATES)) s.setCurrentIndex(s.findText('html')) h = QHBoxLayout() l.addLayout(h) la = QLabel(_('Choose the &type of template to edit:')) la.setBuddy(s) h.addWidget(la), h.addWidget(s), h.addStretch(10) s.currentIndexChanged.connect(self.show_template) self.helpl = la = QLabel(_( 'The variables {0} and {1} will be replaced with the title and author of the book. {2}' ' is where the cursor will be positioned. If you want to include braces in your template,' ' for example for CSS rules, you have to escape them, like this: {3}').format(*('<code>%s</code>'%x for x in ['{TITLE}', '{AUTHOR}', '%CURSOR%', 'body {{ color: red }}']))) la.setWordWrap(True) l.addWidget(la) self.save_timer = t = QTimer(self) t.setSingleShot(True), t.setInterval(100) t.timeout.connect(self._save_syntax) self.editor = e = TextEdit(self) l.addWidget(e) e.textChanged.connect(self.save_syntax) self.show_template() self.bb.clear() self.bb.addButton(QDialogButtonBox.StandardButton.Close) self.rd = b = self.bb.addButton(QDialogButtonBox.StandardButton.RestoreDefaults) b.clicked.connect(self.restore_defaults) l.addWidget(self.bb) @property def current_syntax(self): return str(self.syntaxes.currentText()) def show_template(self): from calibre.gui2.tweak_book.templates import raw_template_for syntax = self.current_syntax self.ignore_changes = True try: self.editor.load_text(raw_template_for(syntax), syntax=syntax) finally: self.ignore_changes = False def save_syntax(self): if self.ignore_changes: return self.save_timer.start() def _save_syntax(self): custom = tprefs['templates'] custom[self.current_syntax] = str(self.editor.toPlainText()) tprefs['templates'] = custom def restore_defaults(self): custom = tprefs['templates'] custom.pop(self.current_syntax, None) tprefs['templates'] = custom self.show_template() self._save_syntax() # }}} class Preferences(QDialog): def __init__(self, gui, initial_panel=None): QDialog.__init__(self, gui) self.l = l = QGridLayout(self) self.setLayout(l) self.setWindowTitle(_('Preferences for Edit book')) self.setWindowIcon(QIcon.ic('config.png')) self.stacks = QStackedWidget(self) l.addWidget(self.stacks, 0, 1, 1, 1) self.categories_list = cl = QListWidget(self) cl.currentRowChanged.connect(self.stacks.setCurrentIndex) cl.clearPropertyFlags() cl.setViewMode(QListView.ViewMode.IconMode) cl.setFlow(QListView.Flow.TopToBottom) cl.setMovement(QListView.Movement.Static) cl.setWrapping(False) cl.setSpacing(15) if get_lang()[:2] not in ('zh', 'ja'): cl.setWordWrap(True) l.addWidget(cl, 0, 0, 1, 1) self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) self.rdb = b = bb.addButton(_('Restore all &defaults'), QDialogButtonBox.ButtonRole.ResetRole) b.setToolTip(_('Restore defaults for all preferences')) b.clicked.connect(self.restore_all_defaults) self.rcdb = b = bb.addButton(_('Restore &current defaults'), QDialogButtonBox.ButtonRole.ResetRole) b.setToolTip(_('Restore defaults for currently displayed preferences')) b.clicked.connect(self.restore_current_defaults) self.rconfs = b = bb.addButton(_('Restore c&onfirmations'), QDialogButtonBox.ButtonRole.ResetRole) b.setToolTip(_('Restore all disabled confirmation prompts')) b.clicked.connect(self.restore_confirmations) l.addWidget(bb, 1, 0, 1, 2) self.restore_geometry(tprefs, 'preferences_geom') self.keyboard_panel = ShortcutConfig(self) self.keyboard_panel.initialize(gui.keyboard) self.editor_panel = EditorSettings(self) self.integration_panel = IntegrationSettings(self) self.main_window_panel = MainWindowSettings(self) self.preview_panel = PreviewSettings(self) self.toolbars_panel = ToolbarSettings(self) for name, icon, panel in [ (_('Main window'), 'page.png', 'main_window'), (_('Editor settings'), 'modified.png', 'editor'), (_('Preview settings'), 'viewer.png', 'preview'), (_('Keyboard shortcuts'), 'keyboard-prefs.png', 'keyboard'), (_('Toolbars'), 'wizard.png', 'toolbars'), (_('Integration with calibre'), 'lt.png', 'integration'), ]: i = QListWidgetItem(QIcon.ic(icon), name, cl) i.setToolTip(name) cl.addItem(i) self.stacks.addWidget(getattr(self, panel + '_panel')) cl.setCurrentRow(0) cl.item(0).setSelected(True) w, h = cl.sizeHintForColumn(0), 0 for i in range(cl.count()): h = cl.sizeHintForRow(i) cl.item(i).setSizeHint(QSize(w, h)) cl.setMaximumWidth(cl.sizeHintForColumn(0) + 35) cl.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) cl.setMinimumWidth(min(cl.maximumWidth(), cl.sizeHint().width())) def sizeHint(self): return QSize(800, 600) @property def dictionaries_changed(self): return self.editor_panel.dictionaries_changed @property def snippets_changed(self): return self.editor_panel.snippets_changed @property def toolbars_changed(self): return self.toolbars_panel.changed def restore_all_defaults(self): for i in range(self.stacks.count()): w = self.stacks.widget(i) w.restore_defaults() def restore_current_defaults(self): self.stacks.currentWidget().restore_defaults() def restore_confirmations(self): changed = 0 for key in tuple(tprefs): if key.endswith('_again') and tprefs.get(key) is False: del tprefs[key] changed += 1 elif key.startswith('skip_ask_to_show_current_diff_for_'): del tprefs[key] changed += 1 elif key == 'questions_to_auto_skip': changed += len(tprefs[key] or ()) del tprefs[key] msg = _('There are no disabled confirmation prompts') if changed: msg = ngettext( 'One disabled confirmation prompt was restored', '{} disabled confirmation prompts were restored', changed).format(changed) info_dialog(self, _('Disabled confirmations restored'), msg, show=True) def accept(self): self.save_geometry(tprefs, 'preferences_geom') for i in range(self.stacks.count()): w = self.stacks.widget(i) w.commit() QDialog.accept(self) def reject(self): self.save_geometry(tprefs, 'preferences_geom') QDialog.reject(self) if __name__ == '__main__': from calibre.gui2 import Application from calibre.gui2.tweak_book.main import option_parser from calibre.gui2.tweak_book.ui import Main app = Application([]) opts = option_parser().parse_args(['dev']) main = Main(opts) d = Preferences(main) d.exec()
35,896
Python
.py
767
36.945241
158
0.613012
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,709
live_css.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/live_css.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' import sys from css_selectors import SelectorError, parse from qt.core import ( QApplication, QColor, QIcon, QLabel, QMenu, QPainter, QPalette, QRect, QScrollArea, QSize, QSizePolicy, QStackedLayout, Qt, QTimer, QUrl, QVBoxLayout, QWidget, pyqtSignal, ) from calibre.constants import FAKE_HOST, FAKE_PROTOCOL from calibre.gui2.tweak_book import actions, editors, tprefs from calibre.gui2.tweak_book.editor.text import default_font_family from calibre.gui2.tweak_book.editor.themes import get_theme, theme_color lowest_specificity = (-sys.maxsize, 0, 0, 0, 0, 0) class Heading(QWidget): # {{{ toggled = pyqtSignal(object) context_menu_requested = pyqtSignal(object, object) def __init__(self, text, expanded=True, parent=None): QWidget.__init__(self, parent) self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Minimum) self.setCursor(Qt.CursorShape.PointingHandCursor) self.text = text self.expanded = expanded self.hovering = False self.do_layout() @property def lines_for_copy(self): return [self.text] def do_layout(self): try: f = self.parent().font() except AttributeError: return f.setBold(True) self.setFont(f) def mousePressEvent(self, ev): if ev.button() == Qt.MouseButton.LeftButton: ev.accept() self.expanded ^= True self.toggled.emit(self) self.update() else: return QWidget.mousePressEvent(self, ev) @property def rendered_text(self): return ('▾' if self.expanded else '▸') + '\xa0' + self.text def sizeHint(self): fm = self.fontMetrics() sz = fm.boundingRect(self.rendered_text).size() return sz def paintEvent(self, ev): p = QPainter(self) p.setClipRect(ev.rect()) bg = self.palette().color(QPalette.ColorRole.AlternateBase) if self.hovering: bg = bg.lighter(115) p.fillRect(self.rect(), bg) try: p.drawText(self.rect(), Qt.AlignmentFlag.AlignLeft|Qt.AlignmentFlag.AlignVCenter|Qt.TextFlag.TextSingleLine, self.rendered_text) finally: p.end() def enterEvent(self, ev): self.hovering = True self.update() return QWidget.enterEvent(self, ev) def leaveEvent(self, ev): self.hovering = False self.update() return QWidget.leaveEvent(self, ev) def contextMenuEvent(self, ev): self.context_menu_requested.emit(self, ev) # }}} class Cell: # {{{ __slots__ = ('rect', 'text', 'right_align', 'color_role', 'override_color', 'swatch', 'is_overriden') SIDE_MARGIN = 5 FLAGS = Qt.AlignmentFlag.AlignVCenter | Qt.TextFlag.TextSingleLine | Qt.TextFlag.TextIncludeTrailingSpaces def __init__(self, text, rect, right_align=False, color_role=QPalette.ColorRole.WindowText, swatch=None, is_overriden=False): self.rect, self.text = rect, text self.right_align = right_align self.is_overriden = is_overriden self.color_role = color_role self.override_color = None self.swatch = swatch if swatch is not None: self.swatch = QColor(swatch[0], swatch[1], swatch[2], int(255 * swatch[3])) def draw(self, painter, width, palette): flags = self.FLAGS | (Qt.AlignmentFlag.AlignRight if self.right_align else Qt.AlignmentFlag.AlignLeft) rect = QRect(self.rect) if self.right_align: rect.setRight(width - self.SIDE_MARGIN) painter.setPen(palette.color(self.color_role) if self.override_color is None else self.override_color) br = painter.drawText(rect, flags, self.text) if self.swatch is not None: r = QRect(br.right() + self.SIDE_MARGIN // 2, br.top() + 2, br.height() - 4, br.height() - 4) painter.fillRect(r, self.swatch) br.setRight(r.right()) if self.is_overriden: painter.setPen(palette.color(QPalette.ColorRole.WindowText)) painter.drawLine(br.left(), br.top() + br.height() // 2, br.right(), br.top() + br.height() // 2) # }}} class Declaration(QWidget): hyperlink_activated = pyqtSignal(object) context_menu_requested = pyqtSignal(object, object) def __init__(self, html_name, data, is_first=False, parent=None): QWidget.__init__(self, parent) self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Minimum) self.data = data self.is_first = is_first self.html_name = html_name self.lines_for_copy = [] self.do_layout() self.setMouseTracking(True) def do_layout(self): fm = self.fontMetrics() def bounding_rect(text): return fm.boundingRect(0, 0, 10000, 10000, Cell.FLAGS, text) line_spacing = 2 side_margin = Cell.SIDE_MARGIN self.rows = [] ypos = line_spacing + (1 if self.is_first else 0) if 'href' in self.data: name = self.data['href'] if isinstance(name, list): name = self.html_name br1 = bounding_rect(name) sel = self.data['selector'] or '' if self.data['type'] == 'inline': sel = 'style=""' br2 = bounding_rect(sel) self.hyperlink_rect = QRect(side_margin, ypos, br1.width(), br1.height()) self.rows.append([ Cell(name, self.hyperlink_rect, color_role=QPalette.ColorRole.Link), Cell(sel, QRect(br1.right() + side_margin, ypos, br2.width(), br2.height()), right_align=True) ]) ypos += max(br1.height(), br2.height()) + 2 * line_spacing self.lines_for_copy.append(name + ' ' + sel) for prop in self.data['properties']: text = prop.name + ':\xa0' br1 = bounding_rect(text) vtext = prop.value + '\xa0' + ('!' if prop.important else '') + prop.important br2 = bounding_rect(vtext) self.rows.append([ Cell(text, QRect(side_margin, ypos, br1.width(), br1.height()), color_role=QPalette.ColorRole.LinkVisited, is_overriden=prop.is_overriden), Cell(vtext, QRect(br1.right() + side_margin, ypos, br2.width(), br2.height()), swatch=prop.color, is_overriden=prop.is_overriden) ]) self.lines_for_copy.append(text + vtext) if prop.is_overriden: self.lines_for_copy[-1] += ' [overridden]' ypos += max(br1.height(), br2.height()) + line_spacing self.lines_for_copy.append('--------------------------\n') self.height_hint = ypos + line_spacing self.width_hint = max(row[-1].rect.right() + side_margin for row in self.rows) if self.rows else 0 def sizeHint(self): return QSize(self.width_hint, self.height_hint) def paintEvent(self, ev): p = QPainter(self) p.setClipRect(ev.rect()) palette = self.palette() p.setPen(palette.color(QPalette.ColorRole.WindowText)) if not self.is_first: p.drawLine(0, 0, self.width(), 0) parent = self while parent is not None: parent = parent.parent() if isinstance(parent, LiveCSS): palette = parent.palette() break try: for row in self.rows: for cell in row: p.save() try: cell.draw(p, self.width(), palette) finally: p.restore() finally: p.end() def mouseMoveEvent(self, ev): if hasattr(self, 'hyperlink_rect'): pos = ev.pos() hovering = self.hyperlink_rect.contains(pos) self.update_hover(hovering) cursor = Qt.CursorShape.ArrowCursor for r, row in enumerate(self.rows): for cell in row: if cell.rect.contains(pos): cursor = Qt.CursorShape.PointingHandCursor if cell.rect is self.hyperlink_rect else Qt.CursorShape.IBeamCursor if r == 0: break if cursor != Qt.CursorShape.ArrowCursor: break self.setCursor(cursor) return QWidget.mouseMoveEvent(self, ev) def mousePressEvent(self, ev): if hasattr(self, 'hyperlink_rect') and ev.button() == Qt.MouseButton.LeftButton: pos = ev.pos() if self.hyperlink_rect.contains(pos): self.emit_hyperlink_activated() return QWidget.mousePressEvent(self, ev) def emit_hyperlink_activated(self): dt = self.data['type'] data = {'type':dt, 'name':self.html_name, 'syntax':'html'} if dt == 'inline': # style attribute data['sourceline_address'] = self.data['href'] elif dt == 'elem': # <style> tag data['sourceline_address'] = self.data['href'] data['rule_address'] = self.data['rule_address'] else: # stylesheet data['name'] = self.data['href'] data['rule_address'] = self.data['rule_address'] data['syntax'] = 'css' self.hyperlink_activated.emit(data) def leaveEvent(self, ev): self.update_hover(False) self.setCursor(Qt.CursorShape.ArrowCursor) return QWidget.leaveEvent(self, ev) def update_hover(self, hovering): cell = self.rows[0][0] if (hovering and cell.override_color is None) or ( not hovering and cell.override_color is not None): cell.override_color = QColor(Qt.GlobalColor.red) if hovering else None self.update() def contextMenuEvent(self, ev): self.context_menu_requested.emit(self, ev) class Box(QWidget): hyperlink_activated = pyqtSignal(object) def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QVBoxLayout(self) l.setAlignment(Qt.AlignmentFlag.AlignTop) self.setLayout(l) self.widgets = [] def show_data(self, data): for w in self.widgets: self.layout().removeWidget(w) for x in ('toggled', 'hyperlink_activated', 'context_menu_requested'): if hasattr(w, x): try: getattr(w, x).disconnect() except TypeError: pass w.deleteLater() self.widgets = [] for node in data['nodes']: node_name = node['name'] + ' @%s' % node['sourceline'] if node['ancestor_specificity'] != 0: title = _('Inherited from %s') % node_name else: title = _('Matched CSS rules for %s') % node_name h = Heading(title, parent=self) h.toggled.connect(self.heading_toggled) self.widgets.append(h), self.layout().addWidget(h) for i, declaration in enumerate(node['css']): d = Declaration(data['html_name'], declaration, is_first=i == 0, parent=self) d.hyperlink_activated.connect(self.hyperlink_activated) self.widgets.append(d), self.layout().addWidget(d) h = Heading(_('Computed final style'), parent=self) h.toggled.connect(self.heading_toggled) self.widgets.append(h), self.layout().addWidget(h) ccss = data['computed_css'] declaration = {'properties':[Property([k, ccss[k][0], '', ccss[k][1]]) for k in sorted(ccss)]} d = Declaration(None, declaration, is_first=True, parent=self) self.widgets.append(d), self.layout().addWidget(d) for w in self.widgets: w.context_menu_requested.connect(self.context_menu_requested) def heading_toggled(self, heading): for i, w in enumerate(self.widgets): if w is heading: for b in self.widgets[i + 1:]: if isinstance(b, Heading): break b.setVisible(heading.expanded) break def relayout(self): for w in self.widgets: w.do_layout() w.updateGeometry() @property def lines_for_copy(self): ans = [] for w in self.widgets: ans += w.lines_for_copy return ans def context_menu_requested(self, widget, ev): if isinstance(widget, Heading): start = widget else: found = False for w in reversed(self.widgets): if w is widget: found = True elif found and isinstance(w, Heading): start = w break else: return found = False lines = [] for w in self.widgets: if found and isinstance(w, Heading): break if w is start: found = True if found: lines += w.lines_for_copy if not lines: return block = '\n'.join(lines).replace('\xa0', ' ') heading = lines[0] m = QMenu(self) m.addAction(QIcon.ic('edit-copy.png'), _('Copy') + ' ' + heading.replace('\xa0', ' '), lambda : QApplication.instance().clipboard().setText(block)) all_lines = [] for w in self.widgets: all_lines += w.lines_for_copy all_text = '\n'.join(all_lines).replace('\xa0', ' ') m.addAction(QIcon.ic('edit-copy.png'), _('Copy everything'), lambda : QApplication.instance().clipboard().setText(all_text)) m.exec(ev.globalPos()) class Property: __slots__ = 'name', 'value', 'important', 'color', 'specificity', 'is_overriden' def __init__(self, prop, specificity=()): self.name, self.value, self.important, self.color = prop self.specificity = tuple(specificity) self.is_overriden = False def __repr__(self): return '<Property name={} value={} important={} color={} specificity={} is_overriden={}>'.format( self.name, self.value, self.important, self.color, self.specificity, self.is_overriden) class LiveCSS(QWidget): goto_declaration = pyqtSignal(object) def __init__(self, preview, parent=None): QWidget.__init__(self, parent) self.preview = preview preview.live_css_data.connect(self.got_live_css_data) self.preview_is_refreshing = False self.refresh_needed = False preview.refresh_starting.connect(self.preview_refresh_starting) preview.refreshed.connect(self.preview_refreshed) self.apply_theme() self.setAutoFillBackground(True) self.update_timer = QTimer(self) self.update_timer.timeout.connect(self.update_data) self.update_timer.setSingleShot(True) self.update_timer.setInterval(500) self.now_showing = (None, None, None) self.stack = s = QStackedLayout(self) self.setLayout(s) self.clear_label = la = QLabel('<h3>' + _( 'No style information found') + '</h3><p>' + _( 'Move the cursor inside a HTML tag to see what styles' ' apply to that tag.')) la.setWordWrap(True) la.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft) s.addWidget(la) self.box = box = Box(self) box.hyperlink_activated.connect(self.goto_declaration, type=Qt.ConnectionType.QueuedConnection) self.scroll = sc = QScrollArea(self) sc.setWidget(box) sc.setWidgetResizable(True) s.addWidget(sc) def preview_refresh_starting(self): self.preview_is_refreshing = True def preview_refreshed(self): self.preview_is_refreshing = False self.refresh_needed = True self.start_update_timer() def apply_theme(self): f = self.font() f.setFamily(tprefs['editor_font_family'] or default_font_family()) f.setPointSizeF(tprefs['editor_font_size']) self.setFont(f) theme = get_theme(tprefs['editor_theme']) pal = self.palette() pal.setColor(QPalette.ColorRole.Window, theme_color(theme, 'Normal', 'bg')) pal.setColor(QPalette.ColorRole.WindowText, theme_color(theme, 'Normal', 'fg')) pal.setColor(QPalette.ColorRole.AlternateBase, theme_color(theme, 'HighlightRegion', 'bg')) pal.setColor(QPalette.ColorRole.Link, theme_color(theme, 'Link', 'fg')) pal.setColor(QPalette.ColorRole.LinkVisited, theme_color(theme, 'Keyword', 'fg')) self.setPalette(pal) if hasattr(self, 'box'): self.box.relayout() self.update() def clear(self): self.stack.setCurrentIndex(0) def show_data(self, editor_name, sourceline, tags): if self.preview_is_refreshing: return if sourceline is None: self.clear() else: self.preview.request_live_css_data(editor_name, sourceline, tags) def got_live_css_data(self, result): maximum_specificities = {} for node in result['nodes']: for rule in node['css']: self.process_rule(rule, node['ancestor_specificity'], maximum_specificities) for node in result['nodes']: for rule in node['css']: for prop in rule['properties']: if prop.specificity < maximum_specificities[prop.name]: prop.is_overriden = True self.display_received_live_css_data(result) def display_received_live_css_data(self, data): editor_name = data['editor_name'] sourceline = data['sourceline'] tags = data['tags'] if data is None or len(data['computed_css']) < 1: if editor_name == self.current_name and (editor_name, sourceline, tags) == self.now_showing: # Try again in a little while in case there was a transient # error in the web view self.start_update_timer() return self.clear() return self.now_showing = (editor_name, sourceline, tags) data['html_name'] = editor_name self.box.show_data(data) self.refresh_needed = False self.stack.setCurrentIndex(1) def process_rule(self, rule, ancestor_specificity, maximum_specificities): selector = rule['selector'] sheet_index = rule['sheet_index'] rule_address = rule['rule_address'] or () if selector is not None: try: specificity = [0] + list(parse(selector)[0].specificity()) except (AttributeError, TypeError, SelectorError): specificity = [0, 0, 0, 0] else: # style attribute specificity = [1, 0, 0, 0] specificity.extend((sheet_index, tuple(rule_address))) properties = [] for prop in rule['properties']: important = 1 if prop[-1] == 'important' else 0 p = Property(prop, [ancestor_specificity] + [important] + specificity) properties.append(p) if p.specificity > maximum_specificities.get(p.name, lowest_specificity): maximum_specificities[p.name] = p.specificity rule['properties'] = properties href = rule['href'] if hasattr(href, 'startswith') and href.startswith(f'{FAKE_PROTOCOL}://{FAKE_HOST}'): qurl = QUrl(href) name = qurl.path()[1:] if name: rule['href'] = name @property def current_name(self): return self.preview.current_name @property def is_visible(self): return self.isVisible() def showEvent(self, ev): self.update_timer.start() actions['auto-reload-preview'].setEnabled(True) return QWidget.showEvent(self, ev) def sync_to_editor(self): self.update_data() def update_data(self): if not self.is_visible or self.preview_is_refreshing: return editor_name = self.current_name ed = editors.get(editor_name, None) if self.update_timer.isActive() or (ed is None and editor_name is not None): return QTimer.singleShot(100, self.update_data) if ed is not None: sourceline, tags = ed.current_tag(for_position_sync=False) if self.refresh_needed or self.now_showing != (editor_name, sourceline, tags): self.show_data(editor_name, sourceline, tags) def start_update_timer(self): if self.is_visible: self.update_timer.start() def stop_update_timer(self): self.update_timer.stop() def navigate_to_declaration(self, data, editor): if data['type'] == 'inline': sourceline, tags = data['sourceline_address'] editor.goto_sourceline(sourceline, tags, attribute='style') elif data['type'] == 'sheet': editor.goto_css_rule(data['rule_address']) elif data['type'] == 'elem': editor.goto_css_rule(data['rule_address'], sourceline_address=data['sourceline_address'])
21,496
Python
.py
495
33.052525
155
0.592389
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,710
boss.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/boss.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2013, Kovid Goyal <kovid at kovidgoyal.net> import errno import os import shutil import subprocess import sys import tempfile from functools import partial, wraps from qt.core import ( QApplication, QCheckBox, QDialog, QDialogButtonBox, QGridLayout, QIcon, QInputDialog, QLabel, QMimeData, QObject, QSize, Qt, QTimer, QUrl, QVBoxLayout, pyqtSignal, ) from calibre import isbytestring, prints from calibre.constants import cache_dir, islinux, ismacos, iswindows from calibre.ebooks.oeb.base import urlnormalize from calibre.ebooks.oeb.polish.container import OEB_DOCS, OEB_STYLES, clone_container, guess_type from calibre.ebooks.oeb.polish.container import get_container as _gc from calibre.ebooks.oeb.polish.cover import mark_as_cover, mark_as_titlepage, set_cover from calibre.ebooks.oeb.polish.css import filter_css, rename_class from calibre.ebooks.oeb.polish.main import SUPPORTED, tweak_polish from calibre.ebooks.oeb.polish.pretty import fix_all_html, pretty_all from calibre.ebooks.oeb.polish.replace import get_recommended_folders, rationalize_folders, rename_files, replace_file from calibre.ebooks.oeb.polish.split import AbortError, merge, multisplit, split from calibre.ebooks.oeb.polish.toc import create_inline_toc, mark_as_nav, remove_names_from_toc from calibre.ebooks.oeb.polish.utils import link_stylesheets from calibre.ebooks.oeb.polish.utils import setup_css_parser_serialization as scs from calibre.gui2 import ( add_to_recent_docs, choose_dir, choose_files, choose_save_file, error_dialog, info_dialog, open_url, question_dialog, sanitize_env_vars, warning_dialog, ) from calibre.gui2.dialogs.confirm_delete import confirm from calibre.gui2.tweak_book import actions, current_container, dictionaries, editor_name, editors, set_book_locale, set_current_container, tprefs from calibre.gui2.tweak_book.completion.worker import completion_worker from calibre.gui2.tweak_book.editor import editor_from_syntax, syntax_from_mime from calibre.gui2.tweak_book.editor.insert_resource import NewBook, get_resource_data from calibre.gui2.tweak_book.file_list import FILE_COPY_MIME, NewFileDialog from calibre.gui2.tweak_book.preferences import Preferences from calibre.gui2.tweak_book.preview import parse_worker from calibre.gui2.tweak_book.save import SaveManager, find_first_existing_ancestor, save_container from calibre.gui2.tweak_book.search import run_search, validate_search_request from calibre.gui2.tweak_book.spell import find_next as find_next_word from calibre.gui2.tweak_book.spell import find_next_error from calibre.gui2.tweak_book.toc import TOCEditor from calibre.gui2.tweak_book.undo import GlobalUndoHistory from calibre.gui2.tweak_book.widgets import ( AddCover, FilterCSS, ImportForeign, InsertLink, InsertSemantics, InsertTag, MultiSplit, QuickOpen, RationalizeFolders, ) from calibre.gui2.widgets import BusyCursor from calibre.ptempfile import PersistentTemporaryDirectory, TemporaryDirectory from calibre.startup import connect_lambda from calibre.utils.config import JSONConfig from calibre.utils.icu import numeric_sort_key from calibre.utils.imghdr import identify from calibre.utils.ipc.launch import exe_path, macos_edit_book_bundle_path from calibre.utils.localization import ngettext from calibre.utils.tdir_in_cache import tdir_in_cache from polyglot.builtins import as_bytes, iteritems, itervalues, string_or_bytes from polyglot.urllib import urlparse _diff_dialogs = [] last_used_transform_rules = [] last_used_html_transform_rules = [] def get_container(*args, **kwargs): kwargs['tweak_mode'] = True container = _gc(*args, **kwargs) return container def setup_css_parser_serialization(): scs(tprefs['editor_tab_stop_width']) def in_thread_job(func): @wraps(func) def ans(*args, **kwargs): with BusyCursor(): return func(*args, **kwargs) return ans def get_boss(): return get_boss.boss def open_path_in_new_editor_instance(path: str): import subprocess from calibre.gui2 import sanitize_env_vars with sanitize_env_vars(): if ismacos: from calibre.utils.ipc.launch import macos_edit_book_bundle_path bundle = os.path.dirname(os.path.dirname(macos_edit_book_bundle_path().rstrip('/'))) subprocess.Popen(['open', '-n', '-a', bundle, path]) else: subprocess.Popen([sys.executable, path]) class Boss(QObject): handle_completion_result_signal = pyqtSignal(object) def __init__(self, parent, notify=None): QObject.__init__(self, parent) self.global_undo = GlobalUndoHistory() self.file_was_readonly = False self.container_count = 0 self.tdir = None self.save_manager = SaveManager(parent, notify) self.save_manager.report_error.connect(self.report_save_error) self.save_manager.check_for_completion.connect(self.check_terminal_save) self.doing_terminal_save = False self.ignore_preview_to_editor_sync = False setup_css_parser_serialization() get_boss.boss = self self.gui = parent completion_worker().result_callback = self.handle_completion_result_signal.emit self.handle_completion_result_signal.connect(self.handle_completion_result, Qt.ConnectionType.QueuedConnection) self.completion_request_count = 0 self.editor_cache = JSONConfig('editor-cache', base_path=cache_dir()) d = self.editor_cache.defaults d['edit_book_state'] = {} d['edit_book_state_order'] = [] def __call__(self, gui): self.gui = gui gui.message_popup.undo_requested.connect(self.do_global_undo) fl = gui.file_list fl.delete_requested.connect(self.delete_requested) fl.reorder_spine.connect(self.reorder_spine) fl.rename_requested.connect(self.rename_requested) fl.bulk_rename_requested.connect(self.bulk_rename_requested) fl.edit_file.connect(self.edit_file_requested) fl.merge_requested.connect(self.merge_requested) fl.mark_requested.connect(self.mark_requested) fl.export_requested.connect(self.export_requested) fl.replace_requested.connect(self.replace_requested) fl.link_stylesheets_requested.connect(self.link_stylesheets_requested) fl.initiate_file_copy.connect(self.copy_files_to_clipboard) fl.initiate_file_paste.connect(self.paste_files_from_clipboard) fl.open_file_with.connect(self.open_file_with) self.gui.central.current_editor_changed.connect(self.apply_current_editor_state) self.gui.central.close_requested.connect(self.editor_close_requested) self.gui.central.search_panel.search_triggered.connect(self.search) self.gui.text_search.find_text.connect(self.find_text) self.gui.preview.sync_requested.connect(self.sync_editor_to_preview) self.gui.preview.split_start_requested.connect(self.split_start_requested) self.gui.preview.split_requested.connect(self.split_requested) self.gui.preview.link_clicked.connect(self.link_clicked) self.gui.preview.render_process_restarted.connect(self.report_render_process_restart) self.gui.preview.open_file_with.connect(self.open_file_with) self.gui.preview.edit_file.connect(self.edit_file_requested) self.gui.check_book.item_activated.connect(self.check_item_activated) self.gui.check_book.check_requested.connect(self.check_requested) self.gui.check_book.fix_requested.connect(self.fix_requested) self.gui.toc_view.navigate_requested.connect(self.link_clicked) self.gui.toc_view.refresh_requested.connect(self.commit_all_editors_to_container) self.gui.image_browser.image_activated.connect(self.image_activated) self.gui.checkpoints.revert_requested.connect(self.revert_requested) self.gui.checkpoints.compare_requested.connect(self.compare_requested) self.gui.saved_searches.run_saved_searches.connect(self.run_saved_searches) self.gui.saved_searches.copy_search_to_search_panel.connect(self.gui.central.search_panel.paste_saved_search) self.gui.central.search_panel.save_search.connect(self.save_search) self.gui.central.search_panel.show_saved_searches.connect(self.show_saved_searches) self.gui.spell_check.find_word.connect(self.find_word) self.gui.spell_check.refresh_requested.connect(self.commit_all_editors_to_container) self.gui.spell_check.word_replaced.connect(self.word_replaced) self.gui.spell_check.word_ignored.connect(self.word_ignored) self.gui.spell_check.change_requested.connect(self.word_change_requested) self.gui.live_css.goto_declaration.connect(self.goto_style_declaration) self.gui.manage_fonts.container_changed.connect(self.apply_container_update_to_gui) self.gui.manage_fonts.embed_all_fonts.connect(self.manage_fonts_embed) self.gui.manage_fonts.subset_all_fonts.connect(self.manage_fonts_subset) self.gui.reports.edit_requested.connect(self.reports_edit_requested) self.gui.reports.refresh_starting.connect(self.commit_all_editors_to_container) self.gui.reports.delete_requested.connect(self.delete_requested) def report_render_process_restart(self): self.gui.show_status_message(_('The Qt WebEngine Render process crashed and has been restarted')) @property def currently_editing(self): ' Return the name of the file being edited currently or None if no file is being edited ' return editor_name(self.gui.central.current_editor) def preferences(self): orig_spell = tprefs['inline_spell_check'] orig_size = tprefs['toolbar_icon_size'] p = Preferences(self.gui) ret = p.exec() if p.dictionaries_changed: dictionaries.clear_caches() dictionaries.initialize(force=True) # Reread user dictionaries if p.toolbars_changed: self.gui.populate_toolbars() for ed in itervalues(editors): if hasattr(ed, 'populate_toolbars'): ed.populate_toolbars() if orig_size != tprefs['toolbar_icon_size']: for ed in itervalues(editors): if hasattr(ed, 'bars'): for bar in ed.bars: bar.setIconSize(QSize(tprefs['toolbar_icon_size'], tprefs['toolbar_icon_size'])) if ret == QDialog.DialogCode.Accepted: setup_css_parser_serialization() self.gui.apply_settings() self.refresh_file_list() self.gui.preview.start_refresh_timer() if ret == QDialog.DialogCode.Accepted or p.dictionaries_changed: for ed in itervalues(editors): ed.apply_settings(dictionaries_changed=p.dictionaries_changed) if orig_spell != tprefs['inline_spell_check']: from calibre.gui2.tweak_book.editor.syntax.html import refresh_spell_check_status refresh_spell_check_status() for ed in itervalues(editors): try: ed.editor.highlighter.rehighlight() except AttributeError: pass def mark_requested(self, name, action): self.commit_dirty_opf() c = current_container() if action == 'cover': mark_as_cover(current_container(), name) elif action.startswith('titlepage:'): action, move_to_start = action.partition(':')[0::2] move_to_start = move_to_start == 'True' mark_as_titlepage(current_container(), name, move_to_start=move_to_start) elif action == 'nav': mark_as_nav(current_container(), name) if c.opf_name in editors: editors[c.opf_name].replace_data(c.raw_data(c.opf_name)) self.gui.file_list.build(c) self.set_modified() def mkdtemp(self, prefix=''): self.container_count += 1 return tempfile.mkdtemp(prefix='%s%05d-' % (prefix, self.container_count), dir=self.tdir) def _check_before_open(self): if self.gui.action_save.isEnabled(): if not question_dialog(self.gui, _('Unsaved changes'), _( 'The current book has unsaved changes. If you open a new book, they will be lost.' ' Are you sure you want to proceed?')): return if self.save_manager.has_tasks: return info_dialog(self.gui, _('Cannot open'), _('The current book is being saved, you cannot open a new book until' ' the saving is completed'), show=True) return True def new_book(self): if not self._check_before_open(): return d = NewBook(self.gui) if d.exec() == QDialog.DialogCode.Accepted: fmt = d.fmt.lower() path = choose_save_file(self.gui, 'edit-book-new-book', _('Choose file location'), filters=[(fmt.upper(), (fmt,))], all_files=False) if path is not None: if not path.lower().endswith('.' + fmt): path = path + '.' + fmt from calibre.ebooks.oeb.polish.create import create_book create_book(d.mi, path, fmt=fmt) self.open_book(path=path) def import_book(self, path=None): if not self._check_before_open(): return d = ImportForeign(self.gui) if hasattr(path, 'rstrip'): d.set_src(os.path.abspath(path)) if d.exec() == QDialog.DialogCode.Accepted: for name in tuple(editors): self.close_editor(name) from calibre.ebooks.oeb.polish.import_book import import_book_as_epub src, dest = d.data self._clear_notify_data = True def func(src, dest, tdir): import_book_as_epub(src, dest) return get_container(dest, tdir=tdir) self.gui.blocking_job('import_book', _('Importing book, please wait...'), self.book_opened, func, src, dest, tdir=self.mkdtemp()) def open_book(self, path=None, edit_file=None, clear_notify_data=True, open_folder=False, search_text=None): ''' Open the e-book at ``path`` for editing. Will show an error if the e-book is not in a supported format or the current book has unsaved changes. :param edit_file: The name of a file inside the newly opened book to start editing. Can also be a list of names. ''' if isinstance(path, (list, tuple)) and path: # Can happen from an file_event_hook on OS X when drag and dropping # onto the icon in the dock or using open -a extra_paths = path[1:] path = path[0] for x in extra_paths: open_path_in_new_editor_instance(x) if not self._check_before_open(): return if not hasattr(path, 'rpartition'): if open_folder: path = choose_dir(self.gui, 'open-book-folder-for-tweaking', _('Choose book folder')) if path: path = [path] else: path = choose_files(self.gui, 'open-book-for-tweaking', _('Choose book'), [(_('Books'), [x.lower() for x in SUPPORTED])], all_files=False, select_only_single_file=True) if not path: return path = path[0] if not os.path.exists(path): return error_dialog(self.gui, _('File not found'), _( 'The file %s does not exist.') % path, show=True) isdir = os.path.isdir(path) ext = path.rpartition('.')[-1].upper() if ext not in SUPPORTED and not isdir: from calibre.ebooks.oeb.polish.import_book import IMPORTABLE if ext.lower() in IMPORTABLE: return self.import_book(path) return error_dialog(self.gui, _('Unsupported format'), _('Tweaking is only supported for books in the %s formats.' ' Convert your book to one of these formats first.') % _(' and ').join(sorted(SUPPORTED)), show=True) self.file_was_readonly = not os.access(path, os.W_OK) if self.file_was_readonly: warning_dialog(self.gui, _('Read-only file'), _( 'The file {} is read-only. Saving changes to it will either fail or cause its permissions to be reset.').format(path), show=True) with self.editor_cache: self.save_book_edit_state() for name in tuple(editors): self.close_editor(name) self.gui.preview.clear() self.gui.live_css.clear() self.container_count = -1 if self.tdir: shutil.rmtree(self.tdir, ignore_errors=True) # We use the cache dir rather than the temporary dir to try and prevent # temp file cleaners from nuking ebooks. See https://bugs.launchpad.net/bugs/1740460 self.tdir = tdir_in_cache('ee') self._edit_file_on_open = edit_file self._search_text_on_open = search_text self._clear_notify_data = clear_notify_data self.gui.blocking_job('open_book', _('Opening book, please wait...'), self.book_opened, get_container, path, tdir=self.mkdtemp()) def book_opened(self, job): ef = getattr(self, '_edit_file_on_open', None) cn = getattr(self, '_clear_notify_data', True) st = getattr(self, '_search_text_on_open', None) self._edit_file_on_open = self._search_text_on_open = None if job.traceback is not None: self.gui.update_status_bar_default_message() if 'DRMError:' in job.traceback: from calibre.gui2.dialogs.drm_error import DRMErrorMessage return DRMErrorMessage(self.gui).exec() if 'ObfuscationKeyMissing:' in job.traceback: return error_dialog(self.gui, _('Failed to open book'), _( 'Failed to open book, it has obfuscated fonts, but the obfuscation key is missing from the OPF.' ' Do an EPUB to EPUB conversion before trying to edit this book.'), show=True) return error_dialog(self.gui, _('Failed to open book'), _('Failed to open book, click "Show details" for more information.'), det_msg=job.traceback, show=True) if cn: self.save_manager.clear_notify_data() self.gui.check_book.clear_at_startup() self.gui.spell_check.clear_caches() dictionaries.clear_ignored(), dictionaries.clear_caches() parse_worker.clear() container = job.result set_current_container(container) completion_worker().clear_caches() with BusyCursor(): self.current_metadata = self.gui.current_metadata = container.mi lang = container.opf_xpath('//dc:language/text()') or [self.current_metadata.language] set_book_locale(lang[0]) self.global_undo.open_book(container) self.gui.update_window_title() self.gui.file_list.current_edited_name = None self.gui.file_list.build(container, preserve_state=False) self.gui.action_save.setEnabled(False) self.update_global_history_actions() recent_books = list(tprefs.get('recent-books', [])) path = os.path.abspath(container.path_to_ebook) if path in recent_books: recent_books.remove(path) self.gui.update_status_bar_default_message(path) recent_books.insert(0, path) tprefs['recent-books'] = recent_books[:10] self.gui.update_recent_books() if iswindows: try: add_to_recent_docs(path) except Exception: import traceback traceback.print_exc() if ef: if isinstance(ef, str): ef = [ef] for i in ef: self.gui.file_list.request_edit(i) else: if tprefs['restore_book_state']: self.restore_book_edit_state() self.gui.toc_view.update_if_visible() self.add_savepoint(_('Start of editing session')) if st: self.find_initial_text(st) def update_editors_from_container(self, container=None, names=None): c = container or current_container() for name, ed in tuple(iteritems(editors)): if c.has_name(name): if names is None or name in names: ed.replace_data(c.raw_data(name)) ed.is_synced_to_container = True else: self.close_editor(name) def refresh_file_list(self): container = current_container() self.gui.file_list.build(container) completion_worker().clear_caches('names') def apply_container_update_to_gui(self, mark_as_modified=True): ''' Update all the components of the user interface to reflect the latest data in the current book container. :param mark_as_modified: If True, the book will be marked as modified, so the user will be prompted to save it when quitting. ''' self.refresh_file_list() self.update_global_history_actions() self.update_editors_from_container() if mark_as_modified: self.set_modified() self.gui.toc_view.update_if_visible() completion_worker().clear_caches() self.gui.preview.start_refresh_timer() @in_thread_job def delete_requested(self, spine_items, other_items): self.add_savepoint(_('Before: Delete files')) self.commit_dirty_opf() c = current_container() c.remove_from_spine(spine_items) for name in other_items: c.remove_item(name) self.set_modified() self.gui.file_list.delete_done(spine_items, other_items) spine_names = [x for x, remove in spine_items if remove] completion_worker().clear_caches('names') items = spine_names + list(other_items) for name in items: if name in editors: self.close_editor(name) if not editors: self.gui.preview.clear() self.gui.live_css.clear() changed = remove_names_from_toc(current_container(), spine_names + list(other_items)) if changed: self.gui.toc_view.update_if_visible() for toc in changed: if toc and toc in editors: editors[toc].replace_data(c.raw_data(toc)) if c.opf_name in editors: editors[c.opf_name].replace_data(c.raw_data(c.opf_name)) self.gui.message_popup(ngettext( 'One file deleted', '{} files deleted', len(items)).format(len(items))) def commit_dirty_opf(self): c = current_container() if c.opf_name in editors and not editors[c.opf_name].is_synced_to_container: self.commit_editor_to_container(c.opf_name) self.gui.update_window_title() def reorder_spine(self, items): if not self.ensure_book(): return self.add_savepoint(_('Before: Re-order text')) c = current_container() c.set_spine(items) self.set_modified() self.gui.file_list.build(current_container()) # needed as the linear flag may have changed on some items if c.opf_name in editors: editors[c.opf_name].replace_data(c.raw_data(c.opf_name)) completion_worker().clear_caches('names') def add_file(self): if not self.ensure_book(_('You must first open a book to edit, before trying to create new files in it.')): return self.commit_dirty_opf() d = NewFileDialog(self.gui) if d.exec() != QDialog.DialogCode.Accepted: return added_name = self.do_add_file(d.file_name, d.file_data, using_template=d.using_template, edit_file=True) if d.file_name.rpartition('.')[2].lower() in ('ttf', 'otf', 'woff'): from calibre.gui2.tweak_book.manage_fonts import show_font_face_rule_for_font_file show_font_face_rule_for_font_file(d.file_data, added_name, self.gui) def do_add_file(self, file_name, data, using_template=False, edit_file=False): self.add_savepoint(_('Before: Add file %s') % self.gui.elided_text(file_name)) c = current_container() adata = data.replace(b'%CURSOR%', b'') if using_template else data spine_index = c.index_in_spine(self.currently_editing or '') if spine_index is not None: spine_index += 1 try: added_name = c.add_file(file_name, adata, spine_index=spine_index) except: self.rewind_savepoint() raise self.gui.file_list.build(c) self.gui.file_list.select_name(file_name) if c.opf_name in editors: editors[c.opf_name].replace_data(c.raw_data(c.opf_name)) mt = c.mime_map[file_name] syntax = syntax_from_mime(file_name, mt) if syntax and edit_file: if using_template: self.edit_file(file_name, syntax, use_template=data.decode('utf-8')) else: self.edit_file(file_name, syntax) self.set_modified() completion_worker().clear_caches('names') return added_name def add_files(self): if not self.ensure_book(_('You must first open a book to edit, before trying to create new files in it.')): return files = choose_files(self.gui, 'tweak-book-bulk-import-files', _('Choose files')) if files: folder_map = get_recommended_folders(current_container(), files) files = {x:('/'.join((folder, os.path.basename(x))) if folder else os.path.basename(x)) for x, folder in iteritems(folder_map)} self.add_savepoint(_('Before: Add files')) c = current_container() added_fonts = set() for path in sorted(files, key=numeric_sort_key): name = files[path] i = 0 while c.exists(name) or c.manifest_has_name(name) or c.has_name_case_insensitive(name): i += 1 name, ext = name.rpartition('.')[0::2] name = '%s_%d.%s' % (name, i, ext) try: with open(path, 'rb') as f: c.add_file(name, f.read()) except: self.rewind_savepoint() raise if name.rpartition('.')[2].lower() in ('ttf', 'otf', 'woff'): added_fonts.add(name) self.gui.file_list.build(c) if c.opf_name in editors: editors[c.opf_name].replace_data(c.raw_data(c.opf_name)) self.set_modified() completion_worker().clear_caches('names') if added_fonts: from calibre.gui2.tweak_book.manage_fonts import show_font_face_rule_for_font_files show_font_face_rule_for_font_files(c, added_fonts, self.gui) def add_cover(self): if not self.ensure_book(): return d = AddCover(current_container(), self.gui) d.import_requested.connect(self.do_add_file) try: if d.exec() == QDialog.DialogCode.Accepted and d.file_name is not None: report = [] with BusyCursor(): self.add_savepoint(_('Before: Add cover')) set_cover(current_container(), d.file_name, report.append, options={ 'existing_image':True, 'keep_aspect':tprefs['add_cover_preserve_aspect_ratio']}) self.apply_container_update_to_gui() finally: d.import_requested.disconnect() def ensure_book(self, msg=None): msg = msg or _('No book is currently open. You must first open a book.') if current_container() is None: error_dialog(self.gui, _('No book open'), msg, show=True) return False return True def edit_toc(self): if not self.ensure_book(_('You must open a book before trying to edit the Table of Contents.')): return self.add_savepoint(_('Before: Edit Table of Contents')) d = TOCEditor(title=self.current_metadata.title, parent=self.gui) if d.exec() != QDialog.DialogCode.Accepted: self.rewind_savepoint() return with BusyCursor(): self.set_modified() self.update_editors_from_container() self.gui.toc_view.update_if_visible() self.gui.file_list.build(current_container()) def insert_inline_toc(self): if not self.ensure_book(): return self.commit_all_editors_to_container() self.add_savepoint(_('Before: Insert inline Table of Contents')) name = create_inline_toc(current_container()) if name is None: self.rewind_savepoint() return error_dialog(self.gui, _('No Table of Contents'), _( 'Cannot create an inline Table of Contents as this book has no existing' ' Table of Contents. You must first create a Table of Contents using the' ' Edit Table of Contents tool.'), show=True) self.apply_container_update_to_gui() self.edit_file(name, 'html') def polish(self, action, name, parent=None): if not self.ensure_book(): return from calibre.gui2.tweak_book.polish import get_customization, show_report customization = get_customization(action, name, parent or self.gui) if customization is None: return with BusyCursor(): self.add_savepoint(_('Before: %s') % name) try: report, changed = tweak_polish(current_container(), {action:True}, customization=customization) except: self.rewind_savepoint() raise if changed: self.apply_container_update_to_gui() self.gui.update_window_title() if not changed: self.rewind_savepoint() show_report(changed, self.current_metadata.title, report, parent or self.gui, self.show_current_diff) def transform_html(self): global last_used_html_transform_rules if not self.ensure_book(_('You must first open a book in order to transform styles.')): return from calibre.ebooks.html_transform_rules import transform_container from calibre.gui2.html_transform_rules import RulesDialog d = RulesDialog(self.gui) d.rules = last_used_html_transform_rules d.transform_scope = tprefs['html_transform_scope'] ret = d.exec() last_used_html_transform_rules = d.rules scope = d.transform_scope tprefs.set('html_transform_scope', scope) if ret != QDialog.DialogCode.Accepted: return mime_map = current_container().mime_map names = () if scope == 'current': if not self.currently_editing or mime_map.get(self.currently_editing) not in OEB_DOCS: return error_dialog(self.gui, _('No HTML file'), _('Not currently editing an HTML file'), show=True) names = (self.currently_editing,) elif scope == 'open': names = tuple(name for name in editors if mime_map.get(name) in OEB_DOCS) if not names: return error_dialog(self.gui, _('No HTML files'), _('Not currently editing any HTML files'), show=True) elif scope == 'selected': names = tuple(name for name in self.gui.file_list.file_list.selected_names if mime_map.get(name) in OEB_DOCS) if not names: return error_dialog(self.gui, _('No HTML files'), _('No HTML files are currently selected in the File browser'), show=True) with BusyCursor(): self.add_savepoint(_('Before HTML transformation')) try: changed = transform_container(current_container(), last_used_html_transform_rules, names) except: self.rewind_savepoint() raise if changed: self.apply_container_update_to_gui() if not changed: self.rewind_savepoint() return info_dialog(self.gui, _('No changes'), _('No HTML was changed.'), show=True) self.show_current_diff() def transform_styles(self): global last_used_transform_rules if not self.ensure_book(_('You must first open a book in order to transform styles.')): return from calibre.ebooks.css_transform_rules import transform_container from calibre.gui2.css_transform_rules import RulesDialog d = RulesDialog(self.gui) d.rules = last_used_transform_rules ret = d.exec() last_used_transform_rules = d.rules if ret != QDialog.DialogCode.Accepted: return with BusyCursor(): self.add_savepoint(_('Before style transformation')) try: changed = transform_container(current_container(), last_used_transform_rules) except: self.rewind_savepoint() raise if changed: self.apply_container_update_to_gui() if not changed: self.rewind_savepoint() info_dialog(self.gui, _('No changes'), _( 'No styles were changed.'), show=True) return self.show_current_diff() def get_external_resources(self): if not self.ensure_book(_('You must first open a book in order to transform styles.')): return from calibre.gui2.tweak_book.download import DownloadResources with BusyCursor(): self.add_savepoint(_('Before: Get external resources')) try: d = DownloadResources(self.gui) d.exec() except Exception: self.rewind_savepoint() raise if d.resources_replaced: self.apply_container_update_to_gui() if d.show_diff: self.show_current_diff() else: self.rewind_savepoint() def manage_fonts(self): if not self.ensure_book(_('No book is currently open. You must first open a book to manage fonts.')): return self.commit_all_editors_to_container() self.gui.manage_fonts.display() def manage_fonts_embed(self): self.polish('embed', _('Embed all fonts'), parent=self.gui.manage_fonts) self.gui.manage_fonts.refresh() def manage_fonts_subset(self): self.polish('subset', _('Subset all fonts'), parent=self.gui.manage_fonts) # Renaming {{{ def rationalize_folders(self): if not self.ensure_book(): return c = current_container() if not c.SUPPORTS_FILENAMES: return error_dialog(self.gui, _('Not supported'), _('The %s format does not support file and folder names internally, therefore' ' arranging files into folders is not allowed.') % c.book_type.upper(), show=True) d = RationalizeFolders(self.gui) if d.exec() != QDialog.DialogCode.Accepted: return self.commit_all_editors_to_container() name_map = rationalize_folders(c, d.folder_map) if not name_map: confirm(_( 'The files in this book are already arranged into folders'), 'already-arranged-into-folders', self.gui, pixmap='dialog_information.png', title=_('Nothing to do'), show_cancel_button=False, config_set=tprefs, confirm_msg=_('Show this message &again')) return self.add_savepoint(_('Before: Arrange into folders')) self.gui.blocking_job( 'rationalize_folders', _('Renaming and updating links...'), partial(self.rename_done, name_map), rename_files, current_container(), name_map) def rename_requested(self, oldname, newname): self.commit_all_editors_to_container() if guess_type(oldname) != guess_type(newname): args = os.path.splitext(oldname) + os.path.splitext(newname) if not confirm( _('You are changing the file type of {0}<b>{1}</b> to {2}<b>{3}</b>.' ' Doing so can cause problems, are you sure?').format(*args), 'confirm-filetype-change', parent=self.gui, title=_('Are you sure?'), config_set=tprefs): return if urlnormalize(newname) != newname: if not confirm( _('The name you have chosen {0} contains special characters, internally' ' it will look like: {1}Try to use only the English alphabet [a-z], numbers [0-9],' ' hyphens and underscores for file names. Other characters can cause problems for ' ' different e-book viewers. Are you sure you want to proceed?').format( '<pre>%s</pre>'%newname, '<pre>%s</pre>' % urlnormalize(newname)), 'confirm-urlunsafe-change', parent=self.gui, title=_('Are you sure?'), config_set=tprefs): return self.add_savepoint(_('Before: Rename %s') % oldname) name_map = {oldname:newname} self.gui.blocking_job( 'rename_file', _('Renaming and updating links...'), partial(self.rename_done, name_map, from_filelist=self.gui.file_list.current_name), rename_files, current_container(), name_map) def bulk_rename_requested(self, name_map): self.add_savepoint(_('Before: Bulk rename')) self.gui.blocking_job( 'bulk_rename_files', _('Renaming and updating links...'), partial(self.rename_done, name_map, from_filelist=self.gui.file_list.current_name), rename_files, current_container(), name_map) def rename_done(self, name_map, job, from_filelist=None): if job.traceback is not None: self.gui.file_list.restore_temp_names() return error_dialog(self.gui, _('Failed to rename files'), _('Failed to rename files, click "Show details" for more information.'), det_msg=job.traceback, show=True) self.gui.file_list.build(current_container()) self.set_modified() for oldname, newname in iteritems(name_map): if oldname in editors: editors[newname] = ed = editors.pop(oldname) ed.change_document_name(newname) self.gui.central.rename_editor(editors[newname], newname) if self.gui.preview.current_name == oldname: self.gui.preview.current_name = newname self.apply_container_update_to_gui() if from_filelist: self.gui.file_list.select_names(frozenset(itervalues(name_map)), current_name=name_map.get(from_filelist)) self.gui.file_list.file_list.setFocus(Qt.FocusReason.PopupFocusReason) # }}} # Global history {{{ def do_global_undo(self, *a): container = self.global_undo.undo() if container is not None: set_current_container(container) self.apply_container_update_to_gui() def do_global_redo(self): container = self.global_undo.redo() if container is not None: set_current_container(container) self.apply_container_update_to_gui() def update_global_history_actions(self): gu = self.global_undo for x, text in (('undo', _('&Revert to')), ('redo', _('&Revert to'))): ac = getattr(self.gui, 'action_global_%s' % x) ac.setEnabled(getattr(gu, 'can_' + x)) ac.setText(text + ' "%s"'%(getattr(gu, x + '_msg') or '...')) def add_savepoint(self, msg): ' Create a restore checkpoint with the name specified as ``msg`` ' self.commit_all_editors_to_container() nc = clone_container(current_container(), self.mkdtemp()) self.global_undo.add_savepoint(nc, msg) set_current_container(nc) self.update_global_history_actions() def rewind_savepoint(self): ' Undo the previous creation of a restore checkpoint, useful if you create a checkpoint, then abort the operation with no changes ' container = self.global_undo.rewind_savepoint() if container is not None: set_current_container(container) self.update_global_history_actions() def create_diff_dialog(self, revert_msg=_('&Revert changes'), show_open_in_editor=True): global _diff_dialogs from calibre.gui2.tweak_book.diff.main import Diff def line_activated(name, lnum, right): if right: self.edit_file_requested(name, None, guess_type(name)) if name in editors: editor = editors[name] editor.go_to_line(lnum) editor.setFocus(Qt.FocusReason.OtherFocusReason) self.gui.raise_and_focus() d = Diff(revert_button_msg=revert_msg, show_open_in_editor=show_open_in_editor) [x.break_cycles() for x in _diff_dialogs if not x.isVisible()] _diff_dialogs = [x for x in _diff_dialogs if x.isVisible()] + [d] d.show(), d.raise_and_focus(), d.setFocus(Qt.FocusReason.OtherFocusReason), d.setWindowModality(Qt.WindowModality.NonModal) if show_open_in_editor: d.line_activated.connect(line_activated) return d def show_current_diff(self, allow_revert=True, to_container=None): ''' Show the changes to the book from its last checkpointed state :param allow_revert: If True the diff dialog will have a button to allow the user to revert all changes :param to_container: A container object to compare the current container to. If None, the previously checkpointed container is used ''' self.commit_all_editors_to_container() k = {} if allow_revert else {'revert_msg': None} d = self.create_diff_dialog(**k) previous_container = self.global_undo.previous_container connect_lambda(d.revert_requested, self, lambda self: self.revert_requested(previous_container)) other = to_container or self.global_undo.previous_container d.container_diff(other, self.global_undo.current_container, names=(self.global_undo.label_for_container(other), self.global_undo.label_for_container(self.global_undo.current_container))) def ask_to_show_current_diff(self, name, title, msg, allow_revert=True, to_container=None): if tprefs.get('skip_ask_to_show_current_diff_for_' + name): return d = QDialog(self.gui) k = QVBoxLayout(d) d.setWindowTitle(title) k.addWidget(QLabel(msg)) k.confirm = cb = QCheckBox(_('Show this popup again')) k.addWidget(cb) cb.setChecked(True) connect_lambda(cb.toggled, d, lambda d, checked: tprefs.set('skip_ask_to_show_current_diff_for_' + name, not checked)) d.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close, d) k.addWidget(bb) bb.accepted.connect(d.accept) bb.rejected.connect(d.reject) d.b = b = bb.addButton(_('See what &changed'), QDialogButtonBox.ButtonRole.AcceptRole) b.setIcon(QIcon.ic('diff.png')), b.setAutoDefault(False) bb.button(QDialogButtonBox.StandardButton.Close).setDefault(True) if d.exec() == QDialog.DialogCode.Accepted: self.show_current_diff(allow_revert=allow_revert, to_container=to_container) def compare_book(self): if not self.ensure_book(): return self.commit_all_editors_to_container() c = current_container() path = choose_files(self.gui, 'select-book-for-comparison', _('Choose book'), filters=[ (_('%s books') % c.book_type.upper(), (c.book_type,))], select_only_single_file=True, all_files=False) if path and path[0]: with TemporaryDirectory('_compare') as tdir: other = _gc(path[0], tdir=tdir, tweak_mode=True) d = self.create_diff_dialog(revert_msg=None) d.container_diff(other, c, names=(_('Other book'), _('Current book'))) def revert_requested(self, container): self.commit_all_editors_to_container() nc = self.global_undo.revert_to(container) set_current_container(nc) self.apply_container_update_to_gui() def compare_requested(self, container): self.show_current_diff(to_container=container) # }}} def set_modified(self): ' Mark the book as having been modified ' self.gui.action_save.setEnabled(True) def request_completion(self, name, completion_type, completion_data, query=None): if completion_type is None: completion_worker().clear_caches(completion_data) return request_id = (self.completion_request_count, name) self.completion_request_count += 1 completion_worker().queue_completion(request_id, completion_type, completion_data, query) return request_id[0] def handle_completion_result(self, result): name = result.request_id[1] editor = editors.get(name) if editor is not None: editor.handle_completion_result(result) def fix_html(self, current): if current: ed = self.gui.central.current_editor if hasattr(ed, 'fix_html'): ed.fix_html() else: with BusyCursor(): self.add_savepoint(_('Before: Fix HTML')) fix_all_html(current_container()) self.update_editors_from_container() self.set_modified() self.ask_to_show_current_diff('html-fix', _('Fixing done'), _('All HTML files fixed')) def pretty_print(self, current): if current: ed = self.gui.central.current_editor ed.pretty_print(editor_name(ed)) else: with BusyCursor(): self.add_savepoint(_('Before: Beautify files')) pretty_all(current_container()) self.update_editors_from_container() self.set_modified() QApplication.alert(self.gui) self.ask_to_show_current_diff('beautify', _('Beautified'), _('All files beautified')) def mark_selected_text(self): ed = self.gui.central.current_editor if ed is not None: ed.mark_selected_text() if ed.has_marked_text: self.gui.central.search_panel.set_where('selected-text') else: self.gui.central.search_panel.unset_marked() def editor_action(self, action): ed = self.gui.central.current_editor edname = editor_name(ed) if hasattr(ed, 'action_triggered'): if action and action[0] == 'insert_resource': rtype = action[1] if rtype == 'image' and ed.syntax not in {'css', 'html'}: return error_dialog(self.gui, _('Not supported'), _( 'Inserting images is only supported for HTML and CSS files.'), show=True) rdata = get_resource_data(rtype, self.gui) if rdata is None: return if rtype == 'image': chosen_name, chosen_image_is_external, fullpage, preserve_ar = rdata if chosen_image_is_external: with open(chosen_image_is_external[1], 'rb') as f: current_container().add_file(chosen_image_is_external[0], f.read()) self.refresh_file_list() chosen_name = chosen_image_is_external[0] href = current_container().name_to_href(chosen_name, edname) fmt, width, height = identify(current_container().raw_data(chosen_name, decode=False)) ed.insert_image(href, fullpage=fullpage, preserve_aspect_ratio=preserve_ar, width=width, height=height) elif action[0] == 'insert_hyperlink': self.commit_all_editors_to_container() d = InsertLink(current_container(), edname, initial_text=ed.get_smart_selection(), parent=self.gui) if d.exec() == QDialog.DialogCode.Accepted: ed.insert_hyperlink(d.href, d.text, template=d.rendered_template) elif action[0] == 'insert_tag': d = InsertTag(parent=self.gui) if d.exec() == QDialog.DialogCode.Accepted: ed.insert_tag(d.tag) else: ed.action_triggered(action) def rename_class(self, class_name): self.commit_all_editors_to_container() text, ok = QInputDialog.getText(self.gui, _('New class name'), _( 'Rename the class {} to?').format(class_name)) if ok: self.add_savepoint(_('Before: Rename {}').format(class_name)) with BusyCursor(): changed = rename_class(current_container(), class_name, text.strip()) if changed: self.apply_container_update_to_gui() self.show_current_diff() else: self.rewind_savepoint() return info_dialog(self.gui, _('No matches'), _( 'No class {} found to change').format(class_name), show=True) def set_semantics(self): if not self.ensure_book(): return self.commit_all_editors_to_container() c = current_container() if c.book_type == 'azw3': return error_dialog(self.gui, _('Not supported'), _( 'Semantics are not supported for the AZW3 format.'), show=True) d = InsertSemantics(c, parent=self.gui) if d.exec() == QDialog.DialogCode.Accepted and d.changes: self.add_savepoint(_('Before: Set Semantics')) d.apply_changes(current_container()) self.apply_container_update_to_gui() def filter_css(self): self.commit_all_editors_to_container() c = current_container() ed = self.gui.central.current_editor current_name = editor_name(ed) if current_name and c.mime_map[current_name] not in OEB_DOCS | OEB_STYLES: current_name = None d = FilterCSS(current_name=current_name, parent=self.gui) if d.exec() == QDialog.DialogCode.Accepted and d.filtered_properties: self.add_savepoint(_('Before: Filter style information')) with BusyCursor(): changed = filter_css(current_container(), d.filtered_properties, names=d.filter_names) if changed: self.apply_container_update_to_gui() self.show_current_diff() else: self.rewind_savepoint() return info_dialog(self.gui, _('No matches'), _( 'No matching style rules were found'), show=True) def show_find(self): self.gui.central.show_find() ed = self.gui.central.current_editor if ed is not None and hasattr(ed, 'selected_text'): text = ed.selected_text if text and text.strip(): self.gui.central.pre_fill_search(text) def show_text_search(self): self.gui.text_search_dock.show() self.gui.text_search.find.setFocus(Qt.FocusReason.OtherFocusReason) def search_action_triggered(self, action, overrides=None): ss = self.gui.saved_searches.isVisible() trigger_saved_search = ss and (not self.gui.central.search_panel.isVisible() or self.gui.saved_searches.has_focus()) if trigger_saved_search: return self.gui.saved_searches.trigger_action(action, overrides=overrides) self.search(action, overrides) def run_saved_searches(self, searches, action): ed = self.gui.central.current_editor name = editor_name(ed) searchable_names = self.gui.file_list.searchable_names if not searches or not validate_search_request(name, searchable_names, getattr(ed, 'has_marked_text', False), searches[0], self.gui): return ret = run_search(searches, action, ed, name, searchable_names, self.gui, self.show_editor, self.edit_file, self.show_current_diff, self.add_savepoint, self.rewind_savepoint, self.set_modified) ed = ret is True and self.gui.central.current_editor if getattr(ed, 'has_line_numbers', False): ed.editor.setFocus(Qt.FocusReason.OtherFocusReason) else: self.gui.saved_searches.setFocus(Qt.FocusReason.OtherFocusReason) def search(self, action, overrides=None): # Run a search/replace sp = self.gui.central.search_panel # Ensure the search panel is visible sp.setVisible(True) ed = self.gui.central.current_editor name = editor_name(ed) state = sp.state if overrides: state.update(overrides) searchable_names = self.gui.file_list.searchable_names if not validate_search_request(name, searchable_names, getattr(ed, 'has_marked_text', False), state, self.gui): return ret = run_search(state, action, ed, name, searchable_names, self.gui, self.show_editor, self.edit_file, self.show_current_diff, self.add_savepoint, self.rewind_savepoint, self.set_modified) ed = ret is True and self.gui.central.current_editor if getattr(ed, 'has_line_numbers', False): ed.editor.setFocus(Qt.FocusReason.OtherFocusReason) else: self.gui.saved_searches.setFocus(Qt.FocusReason.OtherFocusReason) def find_text(self, state): from calibre.gui2.tweak_book.text_search import run_text_search searchable_names = self.gui.file_list.searchable_names ed = self.gui.central.current_editor name = editor_name(ed) if not validate_search_request(name, searchable_names, getattr(ed, 'has_marked_text', False), state, self.gui): return ret = run_text_search(state, ed, name, searchable_names, self.gui, self.show_editor, self.edit_file) ed = ret is True and self.gui.central.current_editor if getattr(ed, 'has_line_numbers', False): ed.editor.setFocus(Qt.FocusReason.OtherFocusReason) def find_initial_text(self, text): from calibre.gui2.tweak_book.search import get_search_regex from calibre.gui2.tweak_book.text_search import file_matches_pattern search = {'find': text, 'mode': 'normal', 'case_sensitive': True, 'direction': 'down'} pat = get_search_regex(search) searchable_names = set(self.gui.file_list.searchable_names['text']) for name, ed in iteritems(editors): searchable_names.discard(name) if ed.find_text(pat, complete=True): self.show_editor(name) return for name in searchable_names: if file_matches_pattern(name, pat): self.edit_file(name) if editors[name].find_text(pat, complete=True): return def find_word(self, word, locations): # Go to a word from the spell check dialog ed = self.gui.central.current_editor name = editor_name(ed) find_next_word(word, locations, ed, name, self.gui, self.show_editor, self.edit_file) def next_spell_error(self): # Go to the next spelling error ed = self.gui.central.current_editor name = editor_name(ed) find_next_error(ed, name, self.gui, self.show_editor, self.edit_file, self.close_editor) def word_change_requested(self, w, new_word): if self.commit_all_editors_to_container(): self.gui.spell_check.change_word_after_update(w, new_word) else: self.gui.spell_check.do_change_word(w, new_word) def word_replaced(self, changed_names): self.set_modified() self.update_editors_from_container(names=set(changed_names)) def word_ignored(self, word, locale): if tprefs['inline_spell_check']: for ed in itervalues(editors): try: ed.editor.recheck_word(word, locale) except AttributeError: pass def editor_link_clicked(self, url): ed = self.gui.central.current_editor name = editor_name(ed) if url.startswith('#'): target = name else: target = current_container().href_to_name(url, name) frag = url.partition('#')[-1] if current_container().has_name(target): self.link_clicked(target, frag, show_anchor_not_found=True) else: try: purl = urlparse(url) except ValueError: return if purl.scheme not in {'', 'file'}: open_url(QUrl(url)) else: error_dialog(self.gui, _('Not found'), _( 'No file with the name %s was found in the book') % target, show=True) def editor_class_clicked(self, class_data): from calibre.gui2.tweak_book.jump_to_class import NoMatchingRuleFound, NoMatchingTagFound, find_first_matching_rule ed = self.gui.central.current_editor name = editor_name(ed) try: res = find_first_matching_rule(current_container(), name, ed.get_raw_data(), class_data) except (NoMatchingTagFound, NoMatchingRuleFound): res = None if res is not None and res.file_name and res.rule_address: editor = self.open_editor_for_name(res.file_name) if editor: editor.goto_css_rule(res.rule_address, sourceline_address=res.style_tag_address) else: error_dialog(self.gui, _('No matches found'), _('No style rules that match the class {} were found').format( class_data['class']), show=True) def save_search(self): state = self.gui.central.search_panel.state self.show_saved_searches() self.gui.saved_searches.add_predefined_search(state) def show_saved_searches(self): self.gui.saved_searches_dock.show() saved_searches = show_saved_searches def create_checkpoint(self): text, ok = QInputDialog.getText(self.gui, _('Choose name'), _( 'Choose a name for the checkpoint.\nYou can later restore the book' ' to this checkpoint via the\n"Revert to..." entries in the Edit menu.')) if ok: self.add_savepoint(text) def commit_editor_to_container(self, name, container=None): container = container or current_container() ed = editors[name] with container.open(name, 'wb') as f: f.write(ed.data) if name == container.opf_name: container.refresh_mime_map() lang = container.opf_xpath('//dc:language/text()') or [self.current_metadata.language] set_book_locale(lang[0]) if container is current_container(): ed.is_synced_to_container = True if name == container.opf_name: self.gui.file_list.build(container) def commit_all_editors_to_container(self): ''' Commit any changes that the user has made to files open in editors to the container. You should call this method before performing any actions on the current container ''' changed = False with BusyCursor(): for name, ed in iteritems(editors): if not ed.is_synced_to_container: self.commit_editor_to_container(name) ed.is_synced_to_container = True changed = True return changed def save_book(self): ' Save the book. Saving is performed in the background ' self.gui.update_window_title() c = current_container() for name, ed in iteritems(editors): if ed.is_modified or not ed.is_synced_to_container: self.commit_editor_to_container(name, c) ed.is_modified = False path_to_ebook = os.path.abspath(c.path_to_ebook) destdir = os.path.dirname(path_to_ebook) if not c.is_dir and not os.path.exists(destdir): info_dialog(self.gui, _('Path does not exist'), _( 'The file you are editing (%s) no longer exists. You have to choose a new save location.') % path_to_ebook, show_copy_button=False, show=True) fmt = path_to_ebook.rpartition('.')[-1].lower() start_dir = find_first_existing_ancestor(path_to_ebook) path = choose_save_file( self.gui, 'choose-new-save-location', _('Choose file location'), initial_path=os.path.join(start_dir, os.path.basename(path_to_ebook)), filters=[(fmt.upper(), (fmt,))], all_files=False) if path is not None: if not path.lower().endswith('.' + fmt): path = path + '.' + fmt path = os.path.abspath(path) c.path_to_ebook = path self.global_undo.update_path_to_ebook(path) else: return if os.path.exists(c.path_to_ebook) and not os.access(c.path_to_ebook, os.W_OK): if not question_dialog(self.gui, _('File is read-only'), _( 'The file at {} is read-only. The editor will try to reset its permissions before saving. Proceed with saving?' ).format(c.path_to_ebook), override_icon='dialog_warning.png', yes_text=_('&Save'), no_text=_('&Cancel'), yes_icon='save.png'): return self.gui.action_save.setEnabled(False) tdir = self.mkdtemp(prefix='save-') container = clone_container(c, tdir) self.save_manager.schedule(tdir, container) def _save_copy(self, post_action=None): self.gui.update_window_title() c = current_container() if c.is_dir: return error_dialog(self.gui, _('Cannot save a copy'), _( 'Saving a copy of a folder based book is not supported'), show=True) ext = c.path_to_ebook.rpartition('.')[-1] path = choose_save_file( self.gui, 'tweak_book_save_copy', _('Choose path'), initial_filename=self.current_metadata.title + '.' + ext, filters=[(_('Book (%s)') % ext.upper(), [ext.lower()])], all_files=False) if not path: return if '.' not in os.path.basename(path): path += '.' + ext.lower() tdir = self.mkdtemp(prefix='save-copy-') container = clone_container(c, tdir) for name, ed in iteritems(editors): if ed.is_modified or not ed.is_synced_to_container: self.commit_editor_to_container(name, container) def do_save(c, path, tdir): save_container(c, path) shutil.rmtree(tdir, ignore_errors=True) return path self.gui.blocking_job('save_copy', _('Saving copy, please wait...'), partial(self.copy_saved, post_action=post_action), do_save, container, path, tdir) def save_copy(self): self._save_copy() def copy_saved(self, job, post_action=None): if job.traceback is not None: return error_dialog(self.gui, _('Failed to save copy'), _('Failed to save copy, click "Show details" for more information.'), det_msg=job.traceback, show=True) msg = _('Copy saved to %s') % job.result if post_action is None: info_dialog(self.gui, _('Copy saved'), msg, show=True) elif post_action == 'replace': msg = _('Editing saved copy at: %s') % job.result self.open_book(job.result, edit_file=self.currently_editing) elif post_action == 'edit': if ismacos: cmd = ['open', '-F', '-n', '-a', os.path.dirname(os.path.dirname(os.path.dirname(macos_edit_book_bundle_path()))), '--args'] else: cmd = [exe_path('ebook-edit')] if islinux: cmd.append('--detach') cmd.append(job.result) ce = self.currently_editing if ce: cmd.append(ce) with sanitize_env_vars(): subprocess.Popen(cmd) self.gui.show_status_message(msg, 5) def report_save_error(self, tb): if self.doing_terminal_save: prints(tb, file=sys.stderr) self.abort_terminal_save() self.set_modified() error_dialog(self.gui, _('Could not save'), _('Saving of the book failed. Click "Show details"' ' for more information. You can try to save a copy' ' to a different location, via File->Save a copy'), det_msg=tb, show=True) def go_to_line_number(self): ed = self.gui.central.current_editor if ed is None or not ed.has_line_numbers: return num, ok = QInputDialog.getInt(self.gui, _('Enter line number'), ('Line number:'), ed.current_line, 1, max(100000, ed.number_of_lines)) if ok: ed.current_line = num def split_start_requested(self): self.commit_all_editors_to_container() self.gui.preview.do_start_split() @in_thread_job def split_requested(self, name, loc, totals): self.add_savepoint(_('Before: Split %s') % self.gui.elided_text(name)) try: bottom_name = split(current_container(), name, loc, totals=totals) except AbortError: self.rewind_savepoint() raise self.apply_container_update_to_gui() self.edit_file(bottom_name, 'html') def multisplit(self): ed = self.gui.central.current_editor if ed.syntax != 'html': return name = editor_name(ed) if name is None: return d = MultiSplit(self.gui) if d.exec() == QDialog.DialogCode.Accepted: with BusyCursor(): self.add_savepoint(_('Before: Split %s') % self.gui.elided_text(name)) try: multisplit(current_container(), name, d.xpath) except AbortError: self.rewind_savepoint() raise self.apply_container_update_to_gui() def open_editor_for_name(self, name): if name in editors: editor = editors[name] self.gui.central.show_editor(editor) else: try: mt = current_container().mime_map[name] except KeyError: error_dialog(self.gui, _('Does not exist'), _( 'The file %s does not exist. If you were trying to click an item in' ' the Table of Contents, you may' ' need to refresh it by right-clicking and choosing "Refresh".') % name, show=True) return None syntax = syntax_from_mime(name, mt) if not syntax: error_dialog( self.gui, _('Unsupported file format'), _('Editing files of type %s is not supported') % mt, show=True) return None editor = self.edit_file(name, syntax) return editor def link_clicked(self, name, anchor, show_anchor_not_found=False): if not name: return editor = self.open_editor_for_name(name) if anchor and hasattr(editor, 'go_to_anchor') : if editor.go_to_anchor(anchor): self.gui.preview.pending_go_to_anchor = anchor elif show_anchor_not_found: error_dialog(self.gui, _('Not found'), _( 'The anchor %s was not found in this file') % anchor, show=True) @in_thread_job def check_item_activated(self, item): is_mult = item.has_multiple_locations and getattr(item, 'current_location_index', None) is not None name = item.all_locations[item.current_location_index][0] if is_mult else item.name editor = None if name in editors: editor = editors[name] self.gui.central.show_editor(editor) else: try: editor = self.edit_file_requested(name, None, current_container().mime_map[name]) except KeyError: error_dialog(self.gui, _('File deleted'), _( 'The file {} has already been deleted, re-run Check Book to update the results.').format(name), show=True) if getattr(editor, 'has_line_numbers', False): if is_mult: editor.go_to_line(*(item.all_locations[item.current_location_index][1:3])) else: editor.go_to_line(item.line or 0, item.col or 0) editor.set_focus() @in_thread_job def check_requested(self, *args): if current_container() is None: return self.commit_all_editors_to_container() c = self.gui.check_book c.parent().show() c.parent().raise_and_focus() c.run_checks(current_container()) def spell_check_requested(self): if current_container() is None: return self.commit_all_editors_to_container() self.add_savepoint(_('Before: Spell Check')) self.gui.spell_check.show() @in_thread_job def fix_requested(self, errors): self.add_savepoint(_('Before: Auto-fix errors')) c = self.gui.check_book c.parent().show() c.parent().raise_and_focus() changed = c.fix_errors(current_container(), errors) if changed: self.apply_container_update_to_gui() self.set_modified() else: self.rewind_savepoint() @in_thread_job def merge_requested(self, category, names, master): self.add_savepoint(_('Before: Merge files into %s') % self.gui.elided_text(master)) try: merge(current_container(), category, names, master) except AbortError: self.rewind_savepoint() raise self.apply_container_update_to_gui() if master in editors: self.show_editor(master) self.gui.file_list.merge_completed(master) self.gui.message_popup(_('{} files merged').format(len(names))) @in_thread_job def link_stylesheets_requested(self, names, sheets, remove): self.add_savepoint(_('Before: Link stylesheets')) changed_names = link_stylesheets(current_container(), names, sheets, remove) if changed_names: self.update_editors_from_container(names=changed_names) self.set_modified() @in_thread_job def export_requested(self, name_or_names, path): if isinstance(name_or_names, string_or_bytes): return self.export_file(name_or_names, path) for name in name_or_names: dest = os.path.abspath(os.path.join(path, name)) if '/' in name or os.sep in name: try: os.makedirs(os.path.dirname(dest)) except OSError as err: if err.errno != errno.EEXIST: raise self.export_file(name, dest) def open_file_with(self, file_name, fmt, entry): if file_name in editors and not editors[file_name].is_synced_to_container: self.commit_editor_to_container(file_name) with current_container().open(file_name) as src: tdir = PersistentTemporaryDirectory(suffix='-ee-ow') with open(os.path.join(tdir, os.path.basename(file_name)), 'wb') as dest: shutil.copyfileobj(src, dest) from calibre.gui2.open_with import run_program run_program(entry, dest.name, self) if question_dialog(self.gui, _('File opened'), _( 'When you are done editing {0} click "Import" to update' ' the file in the book or "Discard" to lose any changes.').format(file_name), yes_text=_('Import'), no_text=_('Discard') ): self.add_savepoint(_('Before: Replace %s') % file_name) with open(dest.name, 'rb') as src, current_container().open(file_name, 'wb') as cdest: shutil.copyfileobj(src, cdest) self.apply_container_update_to_gui() try: shutil.rmtree(tdir) except Exception: pass @in_thread_job def copy_files_to_clipboard(self, names): names = tuple(names) for name in names: if name in editors and not editors[name].is_synced_to_container: self.commit_editor_to_container(name) container = current_container() md = QMimeData() url_map = { name:container.get_file_path_for_processing(name, allow_modification=False) for name in names } md.setUrls(list(map(QUrl.fromLocalFile, list(url_map.values())))) import json md.setData(FILE_COPY_MIME, as_bytes(json.dumps({ name: (url_map[name], container.mime_map.get(name)) for name in names }))) QApplication.instance().clipboard().setMimeData(md) @in_thread_job def paste_files_from_clipboard(self): md = QApplication.instance().clipboard().mimeData() if md.hasUrls() and md.hasFormat(FILE_COPY_MIME): import json self.commit_all_editors_to_container() name_map = json.loads(bytes(md.data(FILE_COPY_MIME))) container = current_container() for name, (path, mt) in iteritems(name_map): with open(path, 'rb') as f: container.add_file(name, f.read(), media_type=mt, modify_name_if_needed=True) self.apply_container_update_to_gui() def export_file(self, name, path): if name in editors and not editors[name].is_synced_to_container: self.commit_editor_to_container(name) with current_container().open(name, 'rb') as src, open(path, 'wb') as dest: shutil.copyfileobj(src, dest) @in_thread_job def replace_requested(self, name, path, basename, force_mt): self.add_savepoint(_('Before: Replace %s') % name) replace_file(current_container(), name, path, basename, force_mt) self.apply_container_update_to_gui() def browse_images(self): self.gui.image_browser.refresh() self.gui.image_browser.show() self.gui.image_browser.raise_and_focus() def show_reports(self): if not self.ensure_book(_('You must first open a book in order to see the report.')): return self.gui.reports.refresh() self.gui.reports.show() self.gui.reports.raise_and_focus() def reports_edit_requested(self, name): mt = current_container().mime_map.get(name, guess_type(name)) self.edit_file_requested(name, None, mt) def image_activated(self, name): mt = current_container().mime_map.get(name, guess_type(name)) self.edit_file_requested(name, None, mt) def check_external_links(self): if self.ensure_book(_('You must first open a book in order to check links.')): self.commit_all_editors_to_container() self.gui.check_external_links.show() def embed_tts(self): if not self.ensure_book(_('You must first open a book in order to add Text-to-speech narration.')): return self.commit_all_editors_to_container() from calibre.gui2.tweak_book.tts import TTSEmbed self.add_savepoint(_('Before: adding narration')) d = TTSEmbed(current_container(), self.gui) if d.exec() == QDialog.DialogCode.Accepted: self.apply_container_update_to_gui() self.show_current_diff() else: self.rewind_savepoint() def compress_images(self): if not self.ensure_book(_('You must first open a book in order to compress images.')): return from calibre.gui2.tweak_book.polish import CompressImages, CompressImagesProgress, show_report d = CompressImages(self.gui) if d.exec() == QDialog.DialogCode.Accepted: with BusyCursor(): self.add_savepoint(_('Before: compress images')) d = CompressImagesProgress(names=d.names, jpeg_quality=d.jpeg_quality, webp_quality=d.webp_quality, parent=self.gui) if d.exec() != QDialog.DialogCode.Accepted: self.rewind_savepoint() return changed, report = d.result if changed is None and report: self.rewind_savepoint() return error_dialog(self.gui, _('Unexpected error'), _( 'Failed to compress images, click "Show details" for more information'), det_msg=report, show=True) if changed: self.apply_container_update_to_gui() else: self.rewind_savepoint() show_report(changed, self.current_metadata.title, report, self.gui, self.show_current_diff) def sync_editor_to_preview(self, name, sourceline_address): editor = self.edit_file(name, 'html') self.ignore_preview_to_editor_sync = True try: editor.goto_sourceline(*sourceline_address) finally: self.ignore_preview_to_editor_sync = False def do_sync_preview_to_editor(self, wait_for_highlight_to_finish=False): if self.ignore_preview_to_editor_sync: return ed = self.gui.central.current_editor if ed is not None: name = editor_name(ed) if name is not None and getattr(ed, 'syntax', None) == 'html': hl = getattr(ed, 'highlighter', None) if wait_for_highlight_to_finish: if getattr(hl, 'is_working', False): QTimer.singleShot(75, self.sync_preview_to_editor_on_highlight_finish) return ct = ed.current_tag() self.gui.preview.sync_to_editor(name, ct) if hl is not None and hl.is_working: QTimer.singleShot(75, self.sync_preview_to_editor_on_highlight_finish) def sync_preview_to_editor(self): ' Sync the position of the preview panel to the current cursor position in the current editor ' self.do_sync_preview_to_editor() def sync_preview_to_editor_on_highlight_finish(self): self.do_sync_preview_to_editor(wait_for_highlight_to_finish=True) def show_partial_cfi_in_editor(self, name, cfi): editor = self.edit_file(name, 'html') if not editor or not editor.has_line_numbers: return False from calibre.ebooks.epub.cfi.parse import decode_cfi from calibre.ebooks.oeb.polish.parsing import parse root = parse( editor.get_raw_data(), decoder=lambda x: x.decode('utf-8'), line_numbers=True, linenumber_attribute='data-lnum') node = decode_cfi(root, cfi) def barename(x): return x.tag.partition('}')[-1] if node is not None: lnum = node.get('data-lnum') if lnum: tags_before = [] for tag in root.xpath('//*[@data-lnum="%s"]' % lnum): tags_before.append(barename(tag)) if tag is node: break else: tags_before.append(barename(node)) lnum = int(lnum) return editor.goto_sourceline(lnum, tags_before, attribute='id' if node.get('id') else None) return False def goto_style_declaration(self, data): name = data['name'] editor = self.edit_file(name, syntax=data['syntax']) self.gui.live_css.navigate_to_declaration(data, editor) def init_editor(self, name, editor, data=None, use_template=False): editor.undo_redo_state_changed.connect(self.editor_undo_redo_state_changed) editor.data_changed.connect(self.editor_data_changed) editor.copy_available_state_changed.connect(self.editor_copy_available_state_changed) editor.cursor_position_changed.connect(self.sync_preview_to_editor) editor.cursor_position_changed.connect(self.update_cursor_position) if hasattr(editor, 'word_ignored'): editor.word_ignored.connect(self.word_ignored) if hasattr(editor, 'link_clicked'): editor.link_clicked.connect(self.editor_link_clicked) if hasattr(editor, 'class_clicked'): editor.class_clicked.connect(self.editor_class_clicked) if hasattr(editor, 'rename_class'): editor.rename_class.connect(self.rename_class) if getattr(editor, 'syntax', None) == 'html': editor.smart_highlighting_updated.connect(self.gui.live_css.sync_to_editor) if hasattr(editor, 'set_request_completion'): editor.set_request_completion(partial(self.request_completion, name), name) if data is not None: if use_template: editor.init_from_template(data) else: editor.data = data editor.is_synced_to_container = True editor.modification_state_changed.connect(self.editor_modification_state_changed) self.gui.central.add_editor(name, editor) def edit_file(self, name, syntax=None, use_template=None): ''' Open the file specified by name in an editor :param syntax: The media type of the file, for example, ``'text/html'``. If not specified it is guessed from the file extension. :param use_template: A template to initialize the opened editor with ''' editor = editors.get(name, None) if editor is None: syntax = syntax or syntax_from_mime(name, guess_type(name)) if use_template is None: data = current_container().raw_data(name) if isbytestring(data) and syntax in {'html', 'css', 'text', 'xml', 'javascript'}: try: data = data.decode('utf-8') except UnicodeDecodeError: return error_dialog(self.gui, _('Cannot decode'), _( 'Cannot edit %s as it appears to be in an unknown character encoding') % name, show=True) else: data = use_template editor = editors[name] = editor_from_syntax(syntax, self.gui.editor_tabs) self.init_editor(name, editor, data, use_template=bool(use_template)) if tprefs['pretty_print_on_open']: editor.pretty_print(name) self.show_editor(name) return editor def show_editor(self, name): ' Show the editor that is editing the file specified by ``name`` ' self.gui.central.show_editor(editors[name]) editors[name].set_focus() def edit_file_requested(self, name, syntax=None, mime=None): if name in editors: self.gui.central.show_editor(editors[name]) return editors[name] mime = mime or current_container().mime_map.get(name, guess_type(name)) syntax = syntax or syntax_from_mime(name, mime) if not syntax: return error_dialog( self.gui, _('Unsupported file format'), _('Editing files of type %s is not supported') % mime, show=True) return self.edit_file(name, syntax) def edit_next_file(self, backwards=False): self.gui.file_list.edit_next_file(self.currently_editing, backwards) def quick_open(self): if not self.ensure_book(_('No book is currently open. You must first open a book to edit.')): return c = current_container() files = [name for name, mime in iteritems(c.mime_map) if c.exists(name) and syntax_from_mime(name, mime) is not None] d = QuickOpen(files, parent=self.gui) if d.exec() == QDialog.DialogCode.Accepted and d.selected_result is not None: self.edit_file_requested(d.selected_result, None, c.mime_map[d.selected_result]) # Editor basic controls {{{ def do_editor_undo(self): ed = self.gui.central.current_editor if ed is not None: ed.undo() def do_editor_redo(self): ed = self.gui.central.current_editor if ed is not None: ed.redo() def do_editor_copy(self): ed = self.gui.central.current_editor if ed is not None: ed.copy() def do_editor_cut(self): ed = self.gui.central.current_editor if ed is not None: ed.cut() def do_editor_paste(self): ed = self.gui.central.current_editor if ed is not None: ed.paste() def toggle_line_wrapping_in_all_editors(self): tprefs['editor_line_wrap'] ^= True yes = tprefs['editor_line_wrap'] for ed in editors.values(): if getattr(ed, 'editor', None) and hasattr(ed.editor, 'apply_line_wrap_mode'): ed.editor.apply_line_wrap_mode(yes) def editor_data_changed(self, editor): self.gui.preview.start_refresh_timer() for name, ed in iteritems(editors): if ed is editor: self.gui.toc_view.start_refresh_timer(name) break def editor_undo_redo_state_changed(self, *args): self.apply_current_editor_state() def editor_copy_available_state_changed(self, *args): self.apply_current_editor_state() def editor_modification_state_changed(self, is_modified): self.apply_current_editor_state() if is_modified: self.set_modified() # }}} def apply_current_editor_state(self): ed = self.gui.central.current_editor self.gui.cursor_position_widget.update_position() if ed is not None: actions['editor-undo'].setEnabled(ed.undo_available) actions['editor-redo'].setEnabled(ed.redo_available) actions['editor-copy'].setEnabled(ed.copy_available) actions['editor-cut'].setEnabled(ed.cut_available) actions['go-to-line-number'].setEnabled(ed.has_line_numbers) actions['fix-html-current'].setEnabled(ed.syntax == 'html') name = editor_name(ed) mime = current_container().mime_map.get(name) if name is not None and (getattr(ed, 'syntax', None) == 'html' or mime == 'image/svg+xml'): if self.gui.preview.show(name): # The file being displayed by the preview has changed. # Set the preview's position to the current cursor # position in the editor, in case the editors' cursor # position has not changed, since the last time it was # focused. This is not inefficient since multiple requests # to sync are de-bounced with a 100 msec wait. self.sync_preview_to_editor() if name is not None: self.gui.file_list.mark_name_as_current(name) if ed.has_line_numbers: self.gui.cursor_position_widget.update_position(*ed.cursor_position) else: actions['go-to-line-number'].setEnabled(False) self.gui.file_list.clear_currently_edited_name() def update_cursor_position(self): ed = self.gui.central.current_editor if getattr(ed, 'has_line_numbers', False): self.gui.cursor_position_widget.update_position(*ed.cursor_position) else: self.gui.cursor_position_widget.update_position() def editor_close_requested(self, editor): name = editor_name(editor) if not name: return if not editor.is_synced_to_container: self.commit_editor_to_container(name) self.close_editor(name) def close_editor(self, name): ' Close the editor that is editing the file specified by ``name`` ' editor = editors.pop(name) self.gui.central.close_editor(editor) editor.break_cycles() if not editors or getattr(self.gui.central.current_editor, 'syntax', None) != 'html': self.gui.preview.clear() self.gui.live_css.clear() def insert_character(self): self.gui.insert_char.show() def manage_snippets(self): from calibre.gui2.tweak_book.editor.snippets import UserSnippets UserSnippets(self.gui).exec() def merge_files(self): self.gui.file_list.merge_files() # Shutdown {{{ def quit(self): if self.doing_terminal_save: return False if self.save_manager.has_tasks: if question_dialog( self.gui, _('Are you sure?'), _( 'The current book is being saved in the background. Quitting now will' ' <b>abort the save process</b>! Finish saving first?'), yes_text=_('Finish &saving first'), no_text=_('&Quit immediately')): if self.save_manager.has_tasks: self.start_terminal_save_indicator() return False if not self.confirm_quit(): return False self.shutdown() QApplication.instance().exit() return True def confirm_quit(self): if self.gui.action_save.isEnabled(): d = QDialog(self.gui) d.l = QGridLayout(d) d.setLayout(d.l) d.setWindowTitle(_('Unsaved changes')) d.i = QLabel('') d.i.setMaximumSize(QSize(64, 64)) d.i.setPixmap(QIcon.ic('dialog_warning.png').pixmap(d.i.maximumSize())) d.l.addWidget(d.i, 0, 0) d.m = QLabel(_('There are unsaved changes, if you quit without saving, you will lose them.')) d.m.setWordWrap(True) d.l.addWidget(d.m, 0, 1) d.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel) d.bb.rejected.connect(d.reject) d.bb.accepted.connect(d.accept) d.l.addWidget(d.bb, 1, 0, 1, 2) d.do_save = None def endit(d, x): d.do_save = x d.accept() b = d.bb.addButton(_('&Save and Quit'), QDialogButtonBox.ButtonRole.ActionRole) b.setIcon(QIcon.ic('save.png')) connect_lambda(b.clicked, d, lambda d: endit(d, True)) b = d.bb.addButton(_('&Quit without saving'), QDialogButtonBox.ButtonRole.ActionRole) connect_lambda(b.clicked, d, lambda d: endit(d, False)) d.resize(d.sizeHint()) if d.exec() != QDialog.DialogCode.Accepted or d.do_save is None: return False if d.do_save: self.gui.action_save.trigger() self.start_terminal_save_indicator() return False return True def start_terminal_save_indicator(self): self.save_state() self.gui.blocking_job.set_msg(_('Saving, please wait...')) self.gui.blocking_job.start() self.doing_terminal_save = True def abort_terminal_save(self): self.doing_terminal_save = False self.gui.blocking_job.stop() def check_terminal_save(self): if self.doing_terminal_save and not self.save_manager.has_tasks: # terminal save could have been aborted self.shutdown() QApplication.instance().exit() def shutdown(self): self.save_state() completion_worker().shutdown() self.save_manager.check_for_completion.disconnect() self.gui.preview.stop_refresh_timer() self.gui.live_css.stop_update_timer() [x.reject() for x in _diff_dialogs] del _diff_dialogs[:] self.save_manager.shutdown() parse_worker.shutdown() self.save_manager.wait(0.1) def save_state(self): with self.editor_cache: self.save_book_edit_state() with tprefs: self.gui.save_state() def save_book_edit_state(self): c = current_container() if c and c.path_to_ebook: tprefs = self.editor_cache mem = tprefs['edit_book_state'] order = tprefs['edit_book_state_order'] extra = len(order) - 99 if extra > 0: order = [k for k in order[extra:] if k in mem] mem = {k:mem[k] for k in order} mem[c.path_to_ebook] = { 'editors':{name:ed.current_editing_state for name, ed in iteritems(editors)}, 'currently_editing':self.currently_editing, 'tab_order':self.gui.central.tab_order, } try: order.remove(c.path_to_ebook) except ValueError: pass order.append(c.path_to_ebook) tprefs['edit_book_state'] = mem tprefs['edit_book_state_order'] = order def restore_book_edit_state(self): c = current_container() if c and c.path_to_ebook: tprefs = self.editor_cache state = tprefs['edit_book_state'].get(c.path_to_ebook) if state is not None: opened = set() eds = state.get('editors', {}) for name in state.get('tab_order', ()): if c.has_name(name): try: editor = self.edit_file_requested(name) if editor is not None: opened.add(name) es = eds.get(name) if es is not None: editor.current_editing_state = es except Exception: import traceback traceback.print_exc() ce = state.get('currently_editing') if ce in opened: self.show_editor(ce) # }}}
95,168
Python
.py
1,912
38.348326
159
0.60975
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,711
function_replace.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/function_replace.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' import io import re import sys import weakref from qt.core import QApplication, QDialogButtonBox, QFontMetrics, QHBoxLayout, QIcon, QLabel, QPlainTextEdit, QSize, Qt, QVBoxLayout, pyqtSignal from calibre.ebooks.oeb.polish.utils import apply_func_to_html_text, apply_func_to_match_groups from calibre.gui2 import error_dialog from calibre.gui2.complete2 import EditWithComplete from calibre.gui2.dialogs.confirm_delete import confirm from calibre.gui2.tweak_book import dictionaries, tprefs from calibre.gui2.tweak_book.editor.text import TextEdit from calibre.gui2.tweak_book.widgets import Dialog from calibre.utils.config import JSONConfig from calibre.utils.icu import capitalize, lower, swapcase, upper from calibre.utils.localization import localize_user_manual_link from calibre.utils.resources import get_path as P from calibre.utils.titlecase import titlecase from polyglot.builtins import iteritems from polyglot.io import PolyglotStringIO user_functions = JSONConfig('editor-search-replace-functions') def compile_code(src, name='<string>'): if not isinstance(src, str): match = re.search(br'coding[:=]\s*([-\w.]+)', src[:200]) enc = match.group(1).decode('utf-8') if match else 'utf-8' src = src.decode(enc) if not src or not src.strip(): src = EMPTY_FUNC # Python complains if there is a coding declaration in a unicode string src = re.sub(r'^#.*coding\s*[:=]\s*([-\w.]+)', '#', src, flags=re.MULTILINE) # Translate newlines to \n src = io.StringIO(src, newline=None).getvalue() code = compile(src, name, 'exec') namespace = {} exec(code, namespace) return namespace class Function: def __init__(self, name, source=None, func=None): self._source = source self.is_builtin = source is None self.name = name if func is None: self.mod = compile_code(source, name) self.func = self.mod['replace'] else: self.func = func self.mod = None if not callable(self.func): raise ValueError('%r is not a function' % self.func) self.file_order = getattr(self.func, 'file_order', None) def init_env(self, name=''): from calibre.gui2.tweak_book.boss import get_boss self.context_name = name or '' self.match_index = 0 self.boss = get_boss() self.data = {} self.debug_buf = PolyglotStringIO() self.functions = {name:func.mod for name, func in iteritems(functions()) if func.mod is not None} def __hash__(self): return hash(self.name) def __eq__(self, other): return self.name == getattr(other, 'name', None) def __ne__(self, other): return not self.__eq__(other) def __call__(self, match): self.match_index += 1 oo, oe, sys.stdout, sys.stderr = sys.stdout, sys.stderr, self.debug_buf, self.debug_buf try: return self.func(match, self.match_index, self.context_name, self.boss.current_metadata, dictionaries, self.data, self.functions) finally: sys.stdout, sys.stderr = oo, oe @property def source(self): if self.is_builtin: import json return json.loads(P('editor-functions.json', data=True, allow_user_override=False))[self.name] return self._source def end(self): if getattr(self.func, 'call_after_last_match', False): oo, oe, sys.stdout, sys.stderr = sys.stdout, sys.stderr, self.debug_buf, self.debug_buf try: return self.func(None, self.match_index, self.context_name, self.boss.current_metadata, dictionaries, self.data, self.functions) finally: sys.stdout, sys.stderr = oo, oe self.data, self.boss, self.functions = {}, None, {} class DebugOutput(Dialog): def __init__(self, parent=None): Dialog.__init__(self, 'Debug output', 'sr-function-debug-output') self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False) def setup_ui(self): self.l = l = QVBoxLayout(self) self.text = t = QPlainTextEdit(self) self.log_text = '' l.addWidget(t) l.addWidget(self.bb) self.bb.setStandardButtons(QDialogButtonBox.StandardButton.Close) self.cb = b = self.bb.addButton(_('&Copy to clipboard'), QDialogButtonBox.ButtonRole.ActionRole) b.clicked.connect(self.copy_to_clipboard) b.setIcon(QIcon.ic('edit-copy.png')) def show_log(self, name, text): if isinstance(text, bytes): text = text.decode('utf-8', 'replace') self.setWindowTitle(_('Debug output from %s') % name) self.text.setPlainText(self.windowTitle() + '\n\n' + text) self.log_text = text self.show() self.raise_and_focus() def sizeHint(self): fm = QFontMetrics(self.text.font()) return QSize(fm.averageCharWidth() * 120, 400) def copy_to_clipboard(self): QApplication.instance().clipboard().setText(self.log_text) def builtin_functions(): for name, obj in iteritems(globals()): if name.startswith('replace_') and callable(obj) and hasattr(obj, 'imports'): yield obj _functions = None def functions(refresh=False): global _functions if _functions is None or refresh: ans = _functions = {} for func in builtin_functions(): ans[func.name] = Function(func.name, func=func) for name, source in iteritems(user_functions): try: f = Function(name, source=source) except Exception: continue ans[f.name] = f return _functions def remove_function(name, gui_parent=None): funcs = functions() if not name: return False if name not in funcs: error_dialog(gui_parent, _('No such function'), _( 'There is no function named %s') % name, show=True) return False if name not in user_functions: error_dialog(gui_parent, _('Cannot remove builtin function'), _( 'The function %s is a builtin function, it cannot be removed.') % name, show=True) del user_functions[name] functions(refresh=True) refresh_boxes() return True boxes = [] def refresh_boxes(): for ref in boxes: box = ref() if box is not None: box.refresh() class FunctionBox(EditWithComplete): save_search = pyqtSignal() show_saved_searches = pyqtSignal() def __init__(self, parent=None, show_saved_search_actions=False): EditWithComplete.__init__(self, parent) self.set_separator(None) self.show_saved_search_actions = show_saved_search_actions self.refresh() self.setToolTip(_('Choose a function to run on matched text (by name)')) boxes.append(weakref.ref(self)) def refresh(self): self.update_items_cache(set(functions())) def contextMenuEvent(self, event): menu = self.lineEdit().createStandardContextMenu() if self.show_saved_search_actions: menu.addSeparator() menu.addAction(_('Save current search'), self.save_search.emit) menu.addAction(_('Show saved searches'), self.show_saved_searches.emit) menu.exec(event.globalPos()) class FunctionEditor(Dialog): def __init__(self, func_name='', parent=None): self._func_name = func_name Dialog.__init__(self, _('Create/edit a function'), 'edit-sr-func', parent=parent) def setup_ui(self): self.l = l = QVBoxLayout(self) self.h = h = QHBoxLayout() l.addLayout(h) self.la1 = la = QLabel(_('F&unction name:')) h.addWidget(la) self.fb = fb = FunctionBox(self) la.setBuddy(fb) h.addWidget(fb, stretch=10) self.la3 = la = QLabel(_('&Code:')) self.source_code = TextEdit(self) self.source_code.load_text('', 'python') la.setBuddy(self.source_code) l.addWidget(la), l.addWidget(self.source_code) if self._func_name: self.fb.setText(self._func_name) func = functions().get(self._func_name) if func is not None: self.source_code.setPlainText(func.source or ('\n' + EMPTY_FUNC)) else: self.source_code.setPlainText('\n' + EMPTY_FUNC) self.la2 = la = QLabel(_( 'For help with creating functions, see the <a href="%s">User Manual</a>') % localize_user_manual_link('https://manual.calibre-ebook.com/function_mode.html')) la.setOpenExternalLinks(True) l.addWidget(la) l.addWidget(self.bb) self.initial_source = self.source def sizeHint(self): fm = QFontMetrics(self.font()) return QSize(fm.averageCharWidth() * 120, 600) @property def func_name(self): return self.fb.text().strip() @property def source(self): return self.source_code.toPlainText() def accept(self): if not self.func_name: return error_dialog(self, _('Must specify name'), _( 'You must specify a name for this function.'), show=True) source = self.source try: mod = compile_code(source, self.func_name) except Exception as err: return error_dialog(self, _('Invalid Python code'), _( 'The code you created is not valid Python code, with error: %s') % err, show=True) if not callable(mod.get('replace')): return error_dialog(self, _('No replace function'), _( 'You must create a Python function named replace in your code'), show=True) user_functions[self.func_name] = source functions(refresh=True) refresh_boxes() Dialog.accept(self) def reject(self): if self.source != self.initial_source: if not confirm(_('All unsaved changes will be lost. Are you sure?'), 'function-replace-close-confirm', parent=self, config_set=tprefs): return return super().reject() # Builtin functions ########################################################## def builtin(name, *args): def f(func): func.name = name func.imports = args return func return f EMPTY_FUNC = '''\ def replace(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs): return '' ''' @builtin('Upper-case text', upper, apply_func_to_match_groups) def replace_uppercase(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs): '''Make matched text upper case. If the regular expression contains groups, only the text in the groups will be changed, otherwise the entire text is changed.''' return apply_func_to_match_groups(match, upper) @builtin('Lower-case text', lower, apply_func_to_match_groups) def replace_lowercase(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs): '''Make matched text lower case. If the regular expression contains groups, only the text in the groups will be changed, otherwise the entire text is changed.''' return apply_func_to_match_groups(match, lower) @builtin('Capitalize text', capitalize, apply_func_to_match_groups) def replace_capitalize(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs): '''Capitalize matched text. If the regular expression contains groups, only the text in the groups will be changed, otherwise the entire text is changed.''' return apply_func_to_match_groups(match, capitalize) @builtin('Title-case text', titlecase, apply_func_to_match_groups) def replace_titlecase(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs): '''Title-case matched text. If the regular expression contains groups, only the text in the groups will be changed, otherwise the entire text is changed.''' return apply_func_to_match_groups(match, titlecase) @builtin('Swap the case of text', swapcase, apply_func_to_match_groups) def replace_swapcase(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs): '''Swap the case of the matched text. If the regular expression contains groups, only the text in the groups will be changed, otherwise the entire text is changed.''' return apply_func_to_match_groups(match, swapcase) @builtin('Upper-case text (ignore tags)', upper, apply_func_to_html_text) def replace_uppercase_ignore_tags(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs): '''Make matched text upper case, ignoring the text inside tag definitions.''' return apply_func_to_html_text(match, upper) @builtin('Lower-case text (ignore tags)', lower, apply_func_to_html_text) def replace_lowercase_ignore_tags(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs): '''Make matched text lower case, ignoring the text inside tag definitions.''' return apply_func_to_html_text(match, lower) @builtin('Capitalize text (ignore tags)', capitalize, apply_func_to_html_text) def replace_capitalize_ignore_tags(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs): '''Capitalize matched text, ignoring the text inside tag definitions.''' return apply_func_to_html_text(match, capitalize) @builtin('Title-case text (ignore tags)', titlecase, apply_func_to_html_text) def replace_titlecase_ignore_tags(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs): '''Title-case matched text, ignoring the text inside tag definitions.''' return apply_func_to_html_text(match, titlecase) @builtin('Swap the case of text (ignore tags)', swapcase, apply_func_to_html_text) def replace_swapcase_ignore_tags(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs): '''Swap the case of the matched text, ignoring the text inside tag definitions.''' return apply_func_to_html_text(match, swapcase) if __name__ == '__main__': app = QApplication([]) FunctionEditor().exec() del app
14,367
Python
.py
301
40.428571
144
0.662303
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,712
preview.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/preview.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> import json import time from collections import defaultdict from functools import partial from threading import Thread from qt.core import ( QAction, QApplication, QByteArray, QHBoxLayout, QIcon, QLabel, QMenu, QSize, QSizePolicy, QStackedLayout, Qt, QTimer, QToolBar, QUrl, QVBoxLayout, QWidget, pyqtSignal, ) from qt.webengine import ( QWebEngineContextMenuRequest, QWebEnginePage, QWebEngineProfile, QWebEngineScript, QWebEngineSettings, QWebEngineUrlRequestJob, QWebEngineUrlSchemeHandler, QWebEngineView, ) from calibre import prints from calibre.constants import FAKE_HOST, FAKE_PROTOCOL, __version__, is_running_from_develop, ismacos, iswindows from calibre.ebooks.oeb.base import OEB_DOCS, XHTML_MIME, serialize from calibre.ebooks.oeb.polish.parsing import parse from calibre.gui2 import NO_URL_FORMATTING, QT_HIDDEN_CLEAR_ACTION, error_dialog, is_dark_theme, safe_open_url from calibre.gui2.palette import dark_color, dark_link_color, dark_text_color from calibre.gui2.tweak_book import TOP, actions, current_container, editors, tprefs from calibre.gui2.tweak_book.file_list import OpenWithHandler from calibre.gui2.viewer.web_view import handle_mathjax_request, send_reply from calibre.gui2.webengine import RestartingWebEngineView from calibre.gui2.widgets2 import HistoryLineEdit2 from calibre.utils.ipc.simple_worker import offload_worker from calibre.utils.resources import get_path as P from calibre.utils.webengine import Bridge, create_script, from_js, insert_scripts, secure_webengine, setup_profile, to_js from polyglot.builtins import iteritems from polyglot.queue import Empty, Queue from polyglot.urllib import urlparse shutdown = object() def get_data(name): 'Get the data for name. Returns a unicode string if name is a text document/stylesheet' if name in editors: return editors[name].get_raw_data() return current_container().raw_data(name) # Parsing of html to add linenumbers {{{ def parse_html(raw): root = parse(raw, decoder=lambda x:x.decode('utf-8'), line_numbers=True, linenumber_attribute='data-lnum') ans = serialize(root, 'text/html') if not isinstance(ans, bytes): ans = ans.encode('utf-8') return ans class ParseItem: __slots__ = ('name', 'length', 'fingerprint', 'parsing_done', 'parsed_data') def __init__(self, name): self.name = name self.length, self.fingerprint = 0, None self.parsed_data = None self.parsing_done = False def __repr__(self): return 'ParsedItem(name={!r}, length={!r}, fingerprint={!r}, parsing_done={!r}, parsed_data_is_None={!r})'.format( self.name, self.length, self.fingerprint, self.parsing_done, self.parsed_data is None) class ParseWorker(Thread): daemon = True SLEEP_TIME = 1 def __init__(self): Thread.__init__(self) self.requests = Queue() self.request_count = 0 self.parse_items = {} self.launch_error = None def run(self): mod, func = 'calibre.gui2.tweak_book.preview', 'parse_html' try: # Connect to the worker and send a dummy job to initialize it self.worker = offload_worker(priority='low') self.worker(mod, func, '<p></p>') except: import traceback traceback.print_exc() self.launch_error = traceback.format_exc() return while True: time.sleep(self.SLEEP_TIME) x = self.requests.get() requests = [x] while True: try: requests.append(self.requests.get_nowait()) except Empty: break if shutdown in requests: self.worker.shutdown() break request = sorted(requests, reverse=True)[0] del requests pi, data = request[1:] try: res = self.worker(mod, func, data) except: import traceback traceback.print_exc() else: pi.parsing_done = True parsed_data = res['result'] if res['tb']: prints("Parser error:") prints(res['tb']) else: pi.parsed_data = parsed_data def add_request(self, name): data = get_data(name) ldata, hdata = len(data), hash(data) pi = self.parse_items.get(name, None) if pi is None: self.parse_items[name] = pi = ParseItem(name) else: if pi.parsing_done and pi.length == ldata and pi.fingerprint == hdata: return pi.parsed_data = None pi.parsing_done = False pi.length, pi.fingerprint = ldata, hdata self.requests.put((self.request_count, pi, data)) self.request_count += 1 def shutdown(self): self.requests.put(shutdown) def get_data(self, name): return getattr(self.parse_items.get(name, None), 'parsed_data', None) def clear(self): self.parse_items.clear() def is_alive(self): return Thread.is_alive(self) or (hasattr(self, 'worker') and self.worker.is_alive()) parse_worker = ParseWorker() # }}} # Override network access to load data "live" from the editors {{{ class UrlSchemeHandler(QWebEngineUrlSchemeHandler): def __init__(self, parent=None): QWebEngineUrlSchemeHandler.__init__(self, parent) self.requests = defaultdict(list) def requestStarted(self, rq): if bytes(rq.requestMethod()) != b'GET': rq.fail(QWebEngineUrlRequestJob.Error.RequestDenied) return url = rq.requestUrl() if url.host() != FAKE_HOST or url.scheme() != FAKE_PROTOCOL: rq.fail(QWebEngineUrlRequestJob.Error.UrlNotFound) return name = url.path()[1:] try: if name.startswith('calibre_internal-mathjax/'): handle_mathjax_request(rq, name.partition('-')[-1]) return c = current_container() if not c.has_name(name): rq.fail(QWebEngineUrlRequestJob.Error.UrlNotFound) return mime_type = c.mime_map.get(name, 'application/octet-stream') if mime_type in OEB_DOCS: mime_type = XHTML_MIME self.requests[name].append((mime_type, rq)) QTimer.singleShot(0, self.check_for_parse) else: data = get_data(name) if isinstance(data, str): data = data.encode('utf-8') mime_type = { # Prevent warning in console about mimetype of fonts 'application/vnd.ms-opentype':'application/x-font-ttf', 'application/x-font-truetype':'application/x-font-ttf', 'application/font-sfnt': 'application/x-font-ttf', }.get(mime_type, mime_type) send_reply(rq, mime_type, data) except Exception: import traceback traceback.print_exc() rq.fail(QWebEngineUrlRequestJob.Error.RequestFailed) def check_for_parse(self): remove = [] for name, requests in iteritems(self.requests): data = parse_worker.get_data(name) if data is not None: if not isinstance(data, bytes): data = data.encode('utf-8') for mime_type, rq in requests: send_reply(rq, mime_type, data) remove.append(name) for name in remove: del self.requests[name] if self.requests: return QTimer.singleShot(10, self.check_for_parse) # }}} def uniq(vals): ''' Remove all duplicates from vals, while preserving order. ''' vals = vals or () seen = set() seen_add = seen.add return tuple(x for x in vals if x not in seen and not seen_add(x)) def get_editor_settings(tprefs): dark = is_dark_theme() def get_color(name, dark_val): ans = tprefs[name] if ans == 'auto' and dark: ans = dark_val.name() if ans in ('auto', 'unset'): return None return ans return { 'is_dark_theme': dark, 'bg': get_color('preview_background', dark_color), 'fg': get_color('preview_foreground', dark_text_color), 'link': get_color('preview_link_color', dark_link_color), 'os': 'windows' if iswindows else ('macos' if ismacos else 'linux'), } def create_dark_mode_script(): return create_script('dark-mode.js', ''' (function() { var settings = JSON.parse(navigator.userAgent.split('|')[1]); function apply_body_colors(event) { if (document.documentElement) { if (settings.bg) document.documentElement.style.backgroundColor = settings.bg; if (settings.fg) document.documentElement.style.color = settings.fg; } if (document.body) { if (settings.bg) document.body.style.backgroundColor = settings.bg; if (settings.fg) document.body.style.color = settings.fg; } } function apply_css() { var css = ''; if (settings.link) css += 'html > body :link, html > body :link * { color: ' + settings.link + ' !important; }'; var using_custom_colors = false; if (settings.bg || settings.fg || settings.link) using_custom_colors = true; if (settings.is_dark_theme && using_custom_colors) { css = ':root { color-scheme: dark; }' + css; } var style = document.createElement('style'); style.textContent = css; document.documentElement.appendChild(style); apply_body_colors(); } apply_body_colors(); document.addEventListener("DOMContentLoaded", apply_css); })(); ''', injection_point=QWebEngineScript.InjectionPoint.DocumentCreation) def create_profile(): ans = getattr(create_profile, 'ans', None) if ans is None: ans = QWebEngineProfile(QApplication.instance()) setup_profile(ans) ua = 'calibre-editor-preview ' + __version__ ans.setHttpUserAgent(ua) if is_running_from_develop: from calibre.utils.rapydscript import compile_editor compile_editor() js = P('editor.js', data=True, allow_user_override=False) cparser = P('csscolorparser.js', data=True, allow_user_override=False) insert_scripts(ans, create_script('csscolorparser.js', cparser), create_script('editor.js', js), create_dark_mode_script(), ) url_handler = UrlSchemeHandler(ans) ans.installUrlSchemeHandler(QByteArray(FAKE_PROTOCOL.encode('ascii')), url_handler) s = ans.settings() s.setDefaultTextEncoding('utf-8') s.setAttribute(QWebEngineSettings.WebAttribute.FullScreenSupportEnabled, False) s.setAttribute(QWebEngineSettings.WebAttribute.LinksIncludedInFocusChain, False) create_profile.ans = ans return ans class PreviewBridge(Bridge): request_sync = from_js(object, object, object) request_split = from_js(object, object) live_css_data = from_js(object) go_to_sourceline_address = to_js() go_to_anchor = to_js() set_split_mode = to_js() live_css = to_js() class WebPage(QWebEnginePage): def __init__(self, parent): QWebEnginePage.__init__(self, create_profile(), parent) secure_webengine(self, for_viewer=True) self.bridge = PreviewBridge(self) def javaScriptConsoleMessage(self, level, msg, linenumber, source_id): prints(f'{source_id}:{linenumber}: {msg}') def acceptNavigationRequest(self, url, req_type, is_main_frame): if req_type in (QWebEnginePage.NavigationType.NavigationTypeReload, QWebEnginePage.NavigationType.NavigationTypeBackForward): return True if url.scheme() in (FAKE_PROTOCOL, 'data'): return True if url.scheme() in ('http', 'https', 'calibre') and req_type == QWebEnginePage.NavigationType.NavigationTypeLinkClicked: safe_open_url(url) prints('Blocking navigation request to:', url.toString()) return False def go_to_anchor(self, anchor): if anchor is TOP: anchor = '' self.bridge.go_to_anchor.emit(anchor or '') def runjs(self, src, callback=None): if callback is None: self.runJavaScript(src, QWebEngineScript.ScriptWorldId.ApplicationWorld) else: self.runJavaScript(src, QWebEngineScript.ScriptWorldId.ApplicationWorld, callback) def go_to_sourceline_address(self, sourceline_address): if self.bridge.ready: lnum, tags = sourceline_address if lnum is None: return tags = [x.lower() for x in tags] self.bridge.go_to_sourceline_address.emit(lnum, tags, tprefs['preview_sync_context']) def split_mode(self, enabled): if self.bridge.ready: self.bridge.set_split_mode.emit(1 if enabled else 0) class Inspector(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent=parent) self.view_to_debug = parent self.view = None self.layout = QHBoxLayout(self) self.layout.setContentsMargins(0, 0, 0, 0) def connect_to_dock(self): ac = actions['inspector-dock'] ac.toggled.connect(self.visibility_changed) if ac.isChecked(): self.visibility_changed(True) def visibility_changed(self, visible): if visible and self.view is None: self.view = QWebEngineView(self.view_to_debug) setup_profile(self.view.page().profile()) self.view_to_debug.page().setDevToolsPage(self.view.page()) self.layout.addWidget(self.view) def sizeHint(self): return QSize(1280, 600) class WebView(RestartingWebEngineView, OpenWithHandler): def __init__(self, parent=None): RestartingWebEngineView.__init__(self, parent) self.inspector = Inspector(self) w = self.screen().availableSize().width() self._size_hint = QSize(int(w/3), int(w/2)) self._page = WebPage(self) self.setPage(self._page) self.clear() self.setAcceptDrops(False) self.dead_renderer_error_shown = False self.render_process_failed.connect(self.render_process_died) def render_process_died(self): if self.dead_renderer_error_shown: return self.dead_renderer_error_shown = True error_dialog(self, _('Render process crashed'), _( 'The Qt WebEngine Render process has crashed so Preview/Live CSS will not work.' ' You should try restarting the editor.') , show=True) def sizeHint(self): return self._size_hint def update_settings(self): settings = get_editor_settings(tprefs) p = self._page.profile() ua = p.httpUserAgent().split('|')[0] + '|' + json.dumps(settings) p.setHttpUserAgent(ua) def refresh(self): self.update_settings() self.pageAction(QWebEnginePage.WebAction.ReloadAndBypassCache).trigger() def set_url(self, qurl): self.update_settings() RestartingWebEngineView.setUrl(self, qurl) def clear(self): self.update_settings() self.setHtml(_( ''' <h3>Live preview</h3> <p>Here you will see a live preview of the HTML file you are currently editing. The preview will update automatically as you make changes. <p style="font-size:x-small; color: gray">Note that this is a quick preview only, it is not intended to simulate an actual e-book reader. Some aspects of your e-book will not work, such as page breaks and page margins. ''')) def inspect(self): self.inspector.parent().show() self.inspector.parent().raise_and_focus() self.pageAction(QWebEnginePage.WebAction.InspectElement).trigger() def contextMenuEvent(self, ev): menu = QMenu(self) data = self.lastContextMenuRequest() url = data.linkUrl() url = str(url.toString(NO_URL_FORMATTING)).strip() text = data.selectedText() if text: ca = self.pageAction(QWebEnginePage.WebAction.Copy) if ca.isEnabled(): menu.addAction(ca) menu.addAction(actions['reload-preview']) menu.addAction(QIcon.ic('debug.png'), _('Inspect element'), self.inspect) if url.partition(':')[0].lower() in {'http', 'https'}: menu.addAction(_('Open link'), partial(safe_open_url, data.linkUrl())) if QWebEngineContextMenuRequest.MediaType.MediaTypeImage.value <= data.mediaType().value <= QWebEngineContextMenuRequest.MediaType.MediaTypeFile.value: url = data.mediaUrl() if url.scheme() == FAKE_PROTOCOL: href = url.path().lstrip('/') if href: c = current_container() resource_name = c.href_to_name(href) if resource_name and c.exists(resource_name) and resource_name not in c.names_that_must_not_be_changed: self.add_open_with_actions(menu, resource_name) if data.mediaType() == QWebEngineContextMenuRequest.MediaType.MediaTypeImage: mime = c.mime_map[resource_name] if mime.startswith('image/'): menu.addAction(_('Edit %s') % resource_name, partial(self.edit_image, resource_name)) menu.exec(ev.globalPos()) def open_with(self, file_name, fmt, entry): self.parent().open_file_with.emit(file_name, fmt, entry) def edit_image(self, resource_name): self.parent().edit_file.emit(resource_name) class Preview(QWidget): sync_requested = pyqtSignal(object, object) split_requested = pyqtSignal(object, object, object) split_start_requested = pyqtSignal() link_clicked = pyqtSignal(object, object) refresh_starting = pyqtSignal() refreshed = pyqtSignal() live_css_data = pyqtSignal(object) render_process_restarted = pyqtSignal() open_file_with = pyqtSignal(object, object, object) edit_file = pyqtSignal(object) def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QVBoxLayout() self.setLayout(l) l.setContentsMargins(0, 0, 0, 0) self.stack = QStackedLayout(l) self.stack.setStackingMode(QStackedLayout.StackingMode.StackAll) self.current_sync_retry_count = 0 self.view = WebView(self) self.view._page.bridge.request_sync.connect(self.request_sync) self.view._page.bridge.request_split.connect(self.request_split) self.view._page.bridge.live_css_data.connect(self.live_css_data) self.view._page.bridge.bridge_ready.connect(self.on_bridge_ready) self.view._page.loadFinished.connect(self.load_finished) self.view._page.loadStarted.connect(self.load_started) self.view.render_process_restarted.connect(self.render_process_restarted) self.pending_go_to_anchor = None self.inspector = self.view.inspector self.stack.addWidget(self.view) self.cover = c = QLabel(_('Loading preview, please wait...')) c.setWordWrap(True) c.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) c.setStyleSheet('QLabel { background-color: palette(window); }') c.setAlignment(Qt.AlignmentFlag.AlignCenter) self.stack.addWidget(self.cover) self.stack.setCurrentIndex(self.stack.indexOf(self.cover)) self.bar = QToolBar(self) l.addWidget(self.bar) ac = actions['auto-reload-preview'] ac.setCheckable(True) ac.setChecked(True) ac.toggled.connect(self.auto_reload_toggled) self.auto_reload_toggled(ac.isChecked()) self.bar.addAction(ac) ac = actions['sync-preview-to-editor'] ac.setCheckable(True) ac.setChecked(True) ac.toggled.connect(self.sync_toggled) self.sync_toggled(ac.isChecked()) self.bar.addAction(ac) self.bar.addSeparator() ac = actions['split-in-preview'] ac.setCheckable(True) ac.setChecked(False) ac.toggled.connect(self.split_toggled) self.split_toggled(ac.isChecked()) self.bar.addAction(ac) ac = actions['reload-preview'] ac.triggered.connect(self.refresh) self.bar.addAction(ac) actions['preview-dock'].toggled.connect(self.visibility_changed) self.current_name = None self.last_sync_request = None self.refresh_timer = QTimer(self) self.refresh_timer.timeout.connect(self.refresh) parse_worker.start() self.current_sync_request = None self.search = HistoryLineEdit2(self) self.search.setClearButtonEnabled(True) ac = self.search.findChild(QAction, QT_HIDDEN_CLEAR_ACTION) if ac is not None: ac.triggered.connect(self.clear_clicked) self.search.initialize('tweak_book_preview_search') self.search.setPlaceholderText(_('Search in preview')) self.search.returnPressed.connect(self.find_next) self.bar.addSeparator() self.bar.addWidget(self.search) for d in ('next', 'prev'): ac = actions['find-%s-preview' % d] ac.triggered.connect(getattr(self, 'find_' + d)) self.bar.addAction(ac) def clear_clicked(self): self.view._page.findText('') def find(self, direction): text = str(self.search.text()) self.view._page.findText(text, ( QWebEnginePage.FindFlag.FindBackward if direction == 'prev' else QWebEnginePage.FindFlag(0))) def find_next(self): self.find('next') def find_prev(self): self.find('prev') def go_to_anchor(self, anchor): self.view._page.go_to_anchor(anchor) def request_sync(self, tagname, href, lnum): if self.current_name: c = current_container() if tagname == 'a' and href: if href and href.startswith('#'): name = self.current_name else: name = c.href_to_name(href, self.current_name) if href else None if name == self.current_name: return self.go_to_anchor(urlparse(href).fragment) if name and c.exists(name) and c.mime_map[name] in OEB_DOCS: return self.link_clicked.emit(name, urlparse(href).fragment or TOP) self.sync_requested.emit(self.current_name, lnum) def request_split(self, loc, totals): actions['split-in-preview'].setChecked(False) if not loc or not totals: return error_dialog(self, _('Invalid location'), _('Cannot split on the body tag'), show=True) if self.current_name: self.split_requested.emit(self.current_name, loc, totals) @property def bridge_ready(self): return self.view._page.bridge.ready def sync_to_editor(self, name, sourceline_address): self.current_sync_request = (name, sourceline_address) self.current_sync_retry_count = 0 QTimer.singleShot(100, self._sync_to_editor) def _sync_to_editor(self): if not actions['sync-preview-to-editor'].isChecked() or self.current_sync_retry_count >= 3000 or self.current_sync_request is None: return if self.refresh_timer.isActive() or not self.bridge_ready or self.current_sync_request[0] != self.current_name: self.current_sync_retry_count += 1 return QTimer.singleShot(100, self._sync_to_editor) sourceline_address = self.current_sync_request[1] self.current_sync_request = None self.current_sync_retry_count = 0 self.view._page.go_to_sourceline_address(sourceline_address) def report_worker_launch_error(self): if parse_worker.launch_error is not None: tb, parse_worker.launch_error = parse_worker.launch_error, None error_dialog(self, _('Failed to launch worker'), _( 'Failed to launch the worker process used for rendering the preview'), det_msg=tb, show=True) def name_to_qurl(self, name=None): name = name or self.current_name qurl = QUrl() qurl.setScheme(FAKE_PROTOCOL), qurl.setAuthority(FAKE_HOST), qurl.setPath('/' + name) return qurl def show(self, name): if name != self.current_name: self.refresh_timer.stop() self.current_name = name self.report_worker_launch_error() parse_worker.add_request(name) self.view.set_url(self.name_to_qurl()) return True def refresh(self): if self.current_name: self.refresh_timer.stop() # This will check if the current html has changed in its editor, # and re-parse it if so self.report_worker_launch_error() parse_worker.add_request(self.current_name) # Tell webkit to reload all html and associated resources current_url = self.name_to_qurl() self.refresh_starting.emit() if current_url != self.view.url(): # The container was changed self.view.set_url(current_url) else: self.view.refresh() self.refreshed.emit() def clear(self): self.view.clear() self.current_name = None @property def is_visible(self): return actions['preview-dock'].isChecked() @property def live_css_is_visible(self): try: return actions['live-css-dock'].isChecked() except KeyError: return False def start_refresh_timer(self): if self.live_css_is_visible or (self.is_visible and actions['auto-reload-preview'].isChecked()): self.refresh_timer.start(tprefs['preview_refresh_time'] * 1000) def stop_refresh_timer(self): self.refresh_timer.stop() def auto_reload_toggled(self, checked): if self.live_css_is_visible and not actions['auto-reload-preview'].isChecked(): actions['auto-reload-preview'].setChecked(True) error_dialog(self, _('Cannot disable'), _( 'Auto reloading of the preview panel cannot be disabled while the' ' Live CSS panel is open.'), show=True) actions['auto-reload-preview'].setToolTip(_( 'Auto reload preview when text changes in editor') if not checked else _( 'Disable auto reload of preview')) def sync_toggled(self, checked): actions['sync-preview-to-editor'].setToolTip(_( 'Disable syncing of preview position to editor position') if checked else _( 'Enable syncing of preview position to editor position')) def visibility_changed(self, is_visible): if is_visible: self.refresh() def split_toggled(self, checked): actions['split-in-preview'].setToolTip('<p>' + (_( 'Abort file split') if checked else _( 'Split this file at a specified location.<p>After clicking this button, click' ' inside the preview panel above at the location you want the file to be split.'))) if checked: self.split_start_requested.emit() else: self.view._page.split_mode(False) def do_start_split(self): self.view._page.split_mode(True) def stop_split(self): actions['split-in-preview'].setChecked(False) def load_started(self): self.stack.setCurrentIndex(self.stack.indexOf(self.cover)) def on_bridge_ready(self): self.stack.setCurrentIndex(self.stack.indexOf(self.view)) def load_finished(self, ok): self.stack.setCurrentIndex(self.stack.indexOf(self.view)) if self.pending_go_to_anchor: self.view._page.go_to_anchor(self.pending_go_to_anchor) self.pending_go_to_anchor = None if actions['split-in-preview'].isChecked(): if ok: self.do_start_split() else: self.stop_split() def request_live_css_data(self, editor_name, sourceline, tags): if self.view._page.bridge.ready: self.view._page.bridge.live_css(editor_name, sourceline, tags) def apply_settings(self): s = self.view.settings() s.setFontSize(QWebEngineSettings.FontSize.DefaultFontSize, int(tprefs['preview_base_font_size'])) s.setFontSize(QWebEngineSettings.FontSize.DefaultFixedFontSize, int(tprefs['preview_mono_font_size'])) s.setFontSize(QWebEngineSettings.FontSize.MinimumLogicalFontSize, int(tprefs['preview_minimum_font_size'])) s.setFontSize(QWebEngineSettings.FontSize.MinimumFontSize, int(tprefs['preview_minimum_font_size'])) sf, ssf, mf = tprefs['engine_preview_serif_family'], tprefs['engine_preview_sans_family'], tprefs['engine_preview_mono_family'] if sf: s.setFontFamily(QWebEngineSettings.FontFamily.SerifFont, sf) if ssf: s.setFontFamily(QWebEngineSettings.FontFamily.SansSerifFont, ssf) if mf: s.setFontFamily(QWebEngineSettings.FontFamily.FixedFont, mf) stdfnt = tprefs['preview_standard_font_family'] or 'serif' stdfnt = { 'serif': QWebEngineSettings.FontFamily.SerifFont, 'sans': QWebEngineSettings.FontFamily.SansSerifFont, 'mono': QWebEngineSettings.FontFamily.FixedFont }[stdfnt] s.setFontFamily(QWebEngineSettings.FontFamily.StandardFont, s.fontFamily(stdfnt))
30,380
Python
.py
673
35.358098
159
0.63046
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,713
main.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/main.py
#!/usr/bin/env python import importlib import os import sys import time from qt.core import QIcon from calibre.constants import EDITOR_APP_UID, islinux from calibre.ebooks.oeb.polish.check.css import shutdown as shutdown_css_check_pool from calibre.gui2 import Application, decouple, set_gui_prefs, setup_gui_option_parser from calibre.ptempfile import reset_base_dir from calibre.utils.config import OptionParser __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' def option_parser(): parser = OptionParser( _( '''\ %prog [opts] [path_to_ebook] [name_of_file_inside_book ...] Launch the calibre Edit book tool. You can optionally also specify the names of files inside the book which will be opened for editing automatically. ''' ) ) setup_gui_option_parser(parser) parser.add_option('--select-text', default=None, help=_('The text to select in the book when it is opened for editing')) return parser def gui_main(path=None, notify=None): _run(['ebook-edit', path], notify=notify) def _run(args, notify=None): from calibre.utils.webengine import setup_fake_protocol # Ensure we can continue to function if GUI is closed os.environ.pop('CALIBRE_WORKER_TEMP_DIR', None) reset_base_dir() setup_fake_protocol() # The following two lines are needed to prevent circular imports causing # errors during initialization of plugins that use the polish container # infrastructure. importlib.import_module('calibre.customize.ui') from calibre.gui2.tweak_book import tprefs from calibre.gui2.tweak_book.ui import Main parser = option_parser() opts, args = parser.parse_args(args) decouple('edit-book-'), set_gui_prefs(tprefs) override = 'calibre-ebook-edit' if islinux else None app = Application(args, override_program_name=override, color_prefs=tprefs, windows_app_uid=EDITOR_APP_UID) from calibre.utils.webengine import setup_default_profile setup_default_profile() app.load_builtin_fonts() app.setWindowIcon(QIcon.ic('tweak.png')) main = Main(opts, notify=notify) main.set_exception_handler() main.show() app.shutdown_signal_received.connect(main.boss.quit) if len(args) > 1: main.boss.open_book(args[1], edit_file=args[2:], clear_notify_data=False, search_text=opts.select_text) else: paths = app.get_pending_file_open_events() if paths: if len(paths) > 1: from .boss import open_path_in_new_editor_instance for path in paths[1:]: try: open_path_in_new_editor_instance(path) except Exception: import traceback traceback.print_exc() main.boss.open_book(paths[0]) app.file_event_hook = main.boss.open_book app.exec() # Ensure that the parse worker has quit so that temp files can be deleted # on windows st = time.time() from calibre.gui2.tweak_book.preview import parse_worker while parse_worker.is_alive() and time.time() - st < 120: time.sleep(0.1) def main(args=sys.argv): try: _run(args) finally: shutdown_css_check_pool() if __name__ == '__main__': main()
3,317
Python
.py
82
34.207317
124
0.684178
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,714
tts.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/tts.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net> import os import sys import traceback from time import monotonic from qt.core import QDialog, QDialogButtonBox, QHBoxLayout, QIcon, QLabel, QProgressBar, QStackedLayout, Qt, QTextBrowser, QVBoxLayout, QWidget, pyqtSignal from calibre.db.utils import human_readable_interval from calibre.gui2 import error_dialog from calibre.gui2.tweak_book.widgets import Dialog from calibre.gui2.widgets import BusyCursor class EngineSettingsWidget(QWidget): def __init__(self, parent=None): from calibre.ebooks.oeb.polish.tts import skip_name from calibre.gui2.tts.config import EmbeddingConfig super().__init__(parent) self.h = h = QHBoxLayout(self) h.setContentsMargins(0, 0, 0, 0) self.conf = c = EmbeddingConfig(self) h.addWidget(c) self.help = q = QTextBrowser(self) h.addWidget(q, 10) q.setHtml(_(''' <h2>Add Text-to-speech narration</h2> <p>Add an audio overlay to this book using Text-to-speech technology. Then users reading this book in a reader that supports audio overlays, such as the calibre viewer, will be able to hear the text read to them, if they wish. <p>You can mark different passages to be spoken by different voices as shown in the example below: <div><code>&lt;p data-calibre-tts="{0}"&gt;This will be voiced by "{0}".&lt;/p&gt;</code></div> <div><code>&lt;p data-calibre-tts="{1}"&gt;This will be voiced by "{1}".&lt;/p&gt;</code></div> <div><code>&lt;p data-calibre-tts="{2}"&gt;This text will not be voiced at all.&lt;/p&gt;</code></div> <p style="font-size: small">Note that generating the Text-to-speech audio will be quite slow, at the rate of approximately one sentence per couple of seconds, depending on your computer's hardware, so consider leave it running overnight. ''').format('cory', 'ryan', skip_name)) self.save_settings = c.save_settings class Progress(QWidget): cancel_requested: bool = False current_stage: str = '' stage_start_at: float = 0 def __init__(self, parent: QWidget = None): super().__init__(parent) self.v = v = QVBoxLayout(self) v.setContentsMargins(0, 0, 0, 0) v.addStretch(10) self.stage_label = la = QLabel(self) v.addWidget(la, alignment=Qt.AlignmentFlag.AlignCenter) self.bar = b = QProgressBar(self) v.addWidget(b) self.detail_label = la = QLabel(self) v.addWidget(la, alignment=Qt.AlignmentFlag.AlignCenter) self.time_left = la = QLabel(self) v.addWidget(la, alignment=Qt.AlignmentFlag.AlignCenter) v.addStretch(10) def __call__(self, stage: str, item: str, count: int, total: int) -> bool: self.stage_label.setText('<b>' + stage) self.detail_label.setText(item) self.detail_label.setVisible(bool(item)) self.bar.setRange(0, total) self.bar.setValue(count) now = monotonic() if self.current_stage != stage: self.stage_start_at = now self.current_stage = stage if (time_elapsed := now - self.stage_start_at) >= 5: rate = count / time_elapsed time_left = (total - count) / rate self.time_left.setText(_('Time to complete this stage: {1}').format(stage, human_readable_interval(time_left))) else: self.time_left.setText(_('Estimating time left')) return self.cancel_requested class TTSEmbed(Dialog): report_progress = pyqtSignal(object, object) worker_done = pyqtSignal(object) ensure_voices_downloaded_signal = pyqtSignal(object, object) def __init__(self, container, parent=None): self.container = container super().__init__(_('Add Text-to-speech narration'), 'tts-overlay-dialog', parent=parent) def setup_ui(self): from threading import Thread self.worker_thread = Thread(target=self.worker, daemon=True) self.worker_done.connect(self.on_worker_done, type=Qt.ConnectionType.QueuedConnection) self.ensure_voices_downloaded_signal.connect(self.do_ensure_voices_downloaded, type=Qt.ConnectionType.QueuedConnection) self.v = v = QVBoxLayout(self) self.engine_settings_widget = e = EngineSettingsWidget(self) self.stack = s = QStackedLayout() s.addWidget(e) s.setCurrentIndex(0) v.addLayout(s) self.progress = p = Progress(self) self.report_progress.connect(self.do_report_progress, type=Qt.ConnectionType.QueuedConnection) s.addWidget(p) self.remove_media_button = b = self.bb.addButton(_('&Remove existing audio'), QDialogButtonBox.ButtonRole.ActionRole) b.setToolTip(_('Remove any exisiting audio overlays, such as a previously created Text-to-speech narration from this book')) b.setIcon(QIcon.ic('trash.png')) b.clicked.connect(self.remove_media) v.addWidget(self.bb) self.update_button_box() self.stack.currentChanged.connect(self.update_button_box) def update_button_box(self): if self.stack.currentIndex() == 0: self.bb.setStandardButtons(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) self.remove_media_button.setVisible(True) else: self.bb.setStandardButtons(QDialogButtonBox.StandardButton.Cancel) self.remove_media_button.setVisible(False) def remove_media(self): from calibre.ebooks.oeb.polish.tts import remove_embedded_tts remove_embedded_tts(self.container) super().accept() def accept(self): if self.stack.currentIndex() == 0: self.engine_settings_widget.save_settings() self.stack.setCurrentIndex(1) self.worker_thread.start() def do_report_progress(self, a, kw): self.progress(*a, **kw) def worker(self): from calibre.ebooks.oeb.polish.tts import embed_tts def report_progress(*a, **kw): self.report_progress.emit(a, kw) return self.progress.cancel_requested try: err = embed_tts(self.container, report_progress, self.ensure_voices_downloaded) except Exception as e: err = e err.det_msg = traceback.format_exc() self.worker_done.emit(err) def ensure_voices_downloaded(self, callback): from queue import Queue queue = Queue() self.ensure_voices_downloaded_signal.emit(callback, queue) e = queue.get() if isinstance(e, Exception): raise e return e def do_ensure_voices_downloaded(self, callback, queue): try: queue.put(callback(self)) except Exception as e: e.det_msg = traceback.format_exc() queue.put(e) def on_worker_done(self, err_or_ok): if isinstance(err_or_ok, Exception): error_dialog(self, _('Text-to-speech narration failed'), str(err_or_ok), det_msg=getattr(err_or_ok, 'det_msg', ''), show=True) return super().reject() return super().accept() if err_or_ok else super().reject() def reject(self): if self.stack.currentIndex() == 0: return super().reject() with BusyCursor(): self.progress.cancel_requested = True self.bb.setEnabled(False) self.setWindowTitle(_('Cancelling, please wait...')) self.worker_thread.join() return super().reject() def develop(): from calibre.ebooks.oeb.polish.container import get_container from calibre.gui2 import Application path = sys.argv[-1] container = get_container(path, tweak_mode=True) app = Application([]) d = TTSEmbed(container) if d.exec() == QDialog.DialogCode.Accepted: b, e = os.path.splitext(path) outpath = b + '-tts' + e container.commit(outpath) print('Output saved to:', outpath) else: print('Failed') del d del app if __name__ == '__main__': develop()
8,098
Python
.py
173
38.901734
155
0.661977
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,715
__init__.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/diff/__init__.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' def load_patience_module(): from calibre_extensions import _patiencediff_c return _patiencediff_c def get_sequence_matcher(): return load_patience_module().PatienceSequenceMatcher_c
307
Python
.py
8
35.125
61
0.74744
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,716
view.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/diff/view.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2014, Kovid Goyal <kovid at kovidgoyal.net> import re import unicodedata from collections import OrderedDict, namedtuple from difflib import SequenceMatcher from functools import partial from itertools import chain from math import ceil import regex from qt.core import ( QApplication, QBrush, QColor, QEvent, QEventLoop, QFont, QHBoxLayout, QIcon, QImage, QKeySequence, QMenu, QPainter, QPainterPath, QPalette, QPen, QPixmap, QPlainTextEdit, QRect, QScrollBar, QSplitter, QSplitterHandle, Qt, QTextCharFormat, QTextCursor, QTextLayout, QTimer, QWidget, pyqtSignal, ) from calibre import fit_image, human_readable from calibre.gui2 import info_dialog from calibre.gui2.tweak_book import tprefs from calibre.gui2.tweak_book.diff import get_sequence_matcher from calibre.gui2.tweak_book.diff.highlight import get_highlighter from calibre.gui2.tweak_book.editor.text import LineNumbers, PlainTextEdit, default_font_family from calibre.gui2.tweak_book.editor.themes import get_theme, theme_color from calibre.gui2.widgets import BusyCursor from calibre.startup import connect_lambda from calibre.utils.icu import utf16_length from calibre.utils.xml_parse import safe_xml_fromstring from polyglot.builtins import as_bytes, iteritems Change = namedtuple('Change', 'ltop lbot rtop rbot kind') def beautify_text(raw, syntax): from lxml import etree from calibre.ebooks.chardet import strip_encoding_declarations from calibre.ebooks.oeb.polish.parsing import parse from calibre.ebooks.oeb.polish.pretty import pretty_html_tree, pretty_xml_tree if syntax == 'xml': try: root = safe_xml_fromstring(strip_encoding_declarations(raw)) except etree.XMLSyntaxError: return raw pretty_xml_tree(root) elif syntax == 'css': import logging from css_parser import CSSParser, log from calibre.ebooks.oeb.base import _css_logger, serialize from calibre.ebooks.oeb.polish.utils import setup_css_parser_serialization setup_css_parser_serialization(tprefs['editor_tab_stop_width']) log.setLevel(logging.WARN) log.raiseExceptions = False parser = CSSParser(loglevel=logging.WARNING, # We dont care about @import rules fetcher=lambda x: (None, None), log=_css_logger) data = parser.parseString(raw, href='<string>', validate=False) return serialize(data, 'text/css').decode('utf-8') else: root = parse(raw, line_numbers=False) pretty_html_tree(None, root) return etree.tostring(root, encoding='unicode') class LineNumberMap(dict): # {{{ 'Map line numbers and keep track of the maximum width of the line numbers' def __new__(cls): self = dict.__new__(cls) self.max_width = 1 return self def __setitem__(self, k, v): v = str(v) dict.__setitem__(self, k, v) self.max_width = max(self.max_width, len(v)) def clear(self): dict.clear(self) self.max_width = 1 # }}} class TextBrowser(PlainTextEdit): # {{{ resized = pyqtSignal() wheel_event = pyqtSignal(object) next_change = pyqtSignal(object) scrolled = pyqtSignal() line_activated = pyqtSignal(object, object, object) def __init__(self, right=False, parent=None, show_open_in_editor=False): PlainTextEdit.__init__(self, parent) self.setFrameStyle(0) self.show_open_in_editor = show_open_in_editor self.side_margin = 0 self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.customContextMenuRequested.connect(self.show_context_menu) self.setFocusPolicy(Qt.FocusPolicy.NoFocus) self.right = right self.setReadOnly(True) self.setLineWrapMode(QPlainTextEdit.LineWrapMode.WidgetWidth) font = self.font() ff = tprefs['editor_font_family'] if ff is None: ff = default_font_family() font.setFamily(ff) font.setPointSizeF(tprefs['editor_font_size']) self.setFont(font) self.calculate_metrics() self.setTabStopDistance(tprefs['editor_tab_stop_width'] * self.space_width) font = self.heading_font = QFont(self.font()) font.setPointSizeF(tprefs['editor_font_size'] * 1.5) font.setBold(True) theme = get_theme(tprefs['editor_theme']) pal = self.palette() pal.setColor(QPalette.ColorRole.Base, theme_color(theme, 'Normal', 'bg')) pal.setColor(QPalette.ColorRole.AlternateBase, theme_color(theme, 'CursorLine', 'bg')) pal.setColor(QPalette.ColorRole.Text, theme_color(theme, 'Normal', 'fg')) pal.setColor(QPalette.ColorRole.Highlight, theme_color(theme, 'Visual', 'bg')) pal.setColor(QPalette.ColorRole.HighlightedText, theme_color(theme, 'Visual', 'fg')) self.setPalette(pal) self.viewport().setCursor(Qt.CursorShape.ArrowCursor) self.line_number_area = LineNumbers(self) self.blockCountChanged[int].connect(self.update_line_number_area_width) self.updateRequest.connect(self.update_line_number_area) self.line_number_palette = pal = QPalette() pal.setColor(QPalette.ColorRole.Base, theme_color(theme, 'LineNr', 'bg')) pal.setColor(QPalette.ColorRole.Text, theme_color(theme, 'LineNr', 'fg')) pal.setColor(QPalette.ColorRole.BrightText, theme_color(theme, 'LineNrC', 'fg')) self.line_number_map = LineNumberMap() self.search_header_pos = 0 self.changes, self.headers, self.images = [], [], OrderedDict() self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff), self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) self.diff_backgrounds = { 'replace' : theme_color(theme, 'DiffReplace', 'bg'), 'insert' : theme_color(theme, 'DiffInsert', 'bg'), 'delete' : theme_color(theme, 'DiffDelete', 'bg'), 'replacereplace': theme_color(theme, 'DiffReplaceReplace', 'bg'), 'boundary': QBrush(theme_color(theme, 'Normal', 'fg'), Qt.BrushStyle.Dense7Pattern), } self.diff_foregrounds = { 'replace' : theme_color(theme, 'DiffReplace', 'fg'), 'insert' : theme_color(theme, 'DiffInsert', 'fg'), 'delete' : theme_color(theme, 'DiffDelete', 'fg'), 'boundary': QColor(0, 0, 0, 0), } for x in ('replacereplace', 'insert', 'delete'): f = QTextCharFormat() f.setBackground(self.diff_backgrounds[x]) setattr(self, '%s_format' % x, f) def calculate_metrics(self): fm = self.fontMetrics() self.number_width = max(map(lambda x:fm.horizontalAdvance(str(x)), range(10))) self.space_width = fm.horizontalAdvance(' ') def show_context_menu(self, pos): m = QMenu(self) a = m.addAction i = str(self.textCursor().selectedText()).rstrip('\0') if i: a(QIcon.ic('edit-copy.png'), _('Copy to clipboard'), self.copy).setShortcut(QKeySequence.StandardKey.Copy) if len(self.changes) > 0: a(QIcon.ic('arrow-up.png'), _('Previous change'), partial(self.next_change.emit, -1)) a(QIcon.ic('arrow-down.png'), _('Next change'), partial(self.next_change.emit, 1)) if self.show_open_in_editor: b = self.cursorForPosition(pos).block() if b.isValid(): a(QIcon.ic('tweak.png'), _('Open file in the editor'), partial(self.generate_sync_request, b.blockNumber())) if len(m.actions()) > 0: m.exec(self.mapToGlobal(pos)) def mouseDoubleClickEvent(self, ev): if ev.button() == Qt.MouseButton.LeftButton: b = self.cursorForPosition(ev.pos()).block() if b.isValid(): self.generate_sync_request(b.blockNumber()) return PlainTextEdit.mouseDoubleClickEvent(self, ev) def generate_sync_request(self, block_number): if not self.headers: return try: lnum = int(self.line_number_map.get(block_number, '')) except: lnum = 1 for i, (num, text) in enumerate(self.headers): if num > block_number: name = text if i == 0 else self.headers[i - 1][1] break else: name = self.headers[-1][1] self.line_activated.emit(name, lnum, bool(self.right)) def search(self, query, reverse=False): ''' Search for query, also searching the headers. Matches in headers are not highlighted as managing the highlight is too much of a pain.''' if not query.strip(): return c = self.textCursor() lnum = c.block().blockNumber() cpos = c.positionInBlock() headers = dict(self.headers) if lnum in headers: cpos = self.search_header_pos lines = str(self.toPlainText()).splitlines() for hn, text in self.headers: lines[hn] = text prefix, postfix = lines[lnum][:cpos], lines[lnum][cpos:] before, after = enumerate(lines[0:lnum]), ((lnum+1+i, x) for i, x in enumerate(lines[lnum+1:])) if reverse: sl = chain([(lnum, prefix)], reversed(tuple(before)), reversed(tuple(after)), [(lnum, postfix)]) else: sl = chain([(lnum, postfix)], after, before, [(lnum, prefix)]) flags = regex.REVERSE if reverse else 0 pat = regex.compile(regex.escape(query, special_only=True), flags=regex.UNICODE|regex.IGNORECASE|flags) for num, text in sl: try: m = next(pat.finditer(text)) except StopIteration: continue start, end = m.span() length = end - start if text is postfix: start += cpos c = QTextCursor(self.document().findBlockByNumber(num)) c.setPosition(c.position() + start) if num in headers: self.search_header_pos = start + length else: c.setPosition(c.position() + length, QTextCursor.MoveMode.KeepAnchor) self.search_header_pos = 0 if reverse: pos, anchor = c.position(), c.anchor() c.setPosition(pos), c.setPosition(anchor, QTextCursor.MoveMode.KeepAnchor) self.setTextCursor(c) self.centerCursor() self.scrolled.emit() break else: info_dialog(self, _('No matches found'), _( 'No matches found for query: %s' % query), show=True) def clear(self): PlainTextEdit.clear(self) self.line_number_map.clear() del self.changes[:] del self.headers[:] self.images.clear() self.search_header_pos = 0 self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded) def update_line_number_area_width(self, block_count=0): self.side_margin = self.line_number_area_width() if self.right: self.setViewportMargins(0, 0, self.side_margin, 0) else: self.setViewportMargins(self.side_margin, 0, 0, 0) def available_width(self): return self.width() - self.side_margin def line_number_area_width(self): return 9 + (self.line_number_map.max_width * self.number_width) def update_line_number_area(self, rect, dy): if dy: self.line_number_area.scroll(0, dy) else: self.line_number_area.update(0, rect.y(), self.line_number_area.width(), rect.height()) if rect.contains(self.viewport().rect()): self.update_line_number_area_width() def resizeEvent(self, ev): PlainTextEdit.resizeEvent(self, ev) cr = self.contentsRect() if self.right: self.line_number_area.setGeometry(QRect(cr.right() - self.line_number_area_width(), cr.top(), cr.right(), cr.height())) else: self.line_number_area.setGeometry(QRect(cr.left(), cr.top(), self.line_number_area_width(), cr.height())) self.resized.emit() def paint_line_numbers(self, ev): painter = QPainter(self.line_number_area) painter.fillRect(ev.rect(), self.line_number_palette.color(QPalette.ColorRole.Base)) block = self.firstVisibleBlock() num = block.blockNumber() top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top()) bottom = top + int(self.blockBoundingRect(block).height()) painter.setPen(self.line_number_palette.color(QPalette.ColorRole.Text)) change_starts = {x[0] for x in self.changes} while block.isValid() and top <= ev.rect().bottom(): r = ev.rect() if block.isVisible() and bottom >= r.top(): text = str(self.line_number_map.get(num, '')) is_start = text != '-' and num in change_starts if is_start: painter.save() f = QFont(self.font()) f.setBold(True) painter.setFont(f) painter.setPen(self.line_number_palette.color(QPalette.ColorRole.BrightText)) if text == '-': painter.drawLine(r.left() + 2, (top + bottom)//2, r.right() - 2, (top + bottom)//2) else: if self.right: painter.drawText(r.left() + 3, top, r.right(), self.fontMetrics().height(), Qt.AlignmentFlag.AlignLeft, text) else: painter.drawText(r.left() + 2, top, r.right() - 5, self.fontMetrics().height(), Qt.AlignmentFlag.AlignRight, text) if is_start: painter.restore() block = block.next() top = bottom bottom = top + int(self.blockBoundingRect(block).height()) num += 1 def paintEvent(self, event): w = self.viewport().rect().width() painter = QPainter(self.viewport()) painter.setClipRect(event.rect()) painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform, True) floor = event.rect().bottom() ceiling = event.rect().top() fv = self.firstVisibleBlock().blockNumber() origin = self.contentOffset() doc = self.document() lines = [] for num, text in self.headers: top, bot = num, num + 3 if bot < fv: continue y_top = self.blockBoundingGeometry(doc.findBlockByNumber(top)).translated(origin).y() y_bot = self.blockBoundingGeometry(doc.findBlockByNumber(bot)).translated(origin).y() if max(y_top, y_bot) < ceiling: continue if min(y_top, y_bot) > floor: break painter.setFont(self.heading_font) br = painter.drawText(3, int(y_top), int(w), int(y_bot - y_top - 5), Qt.TextFlag.TextSingleLine, text) painter.setPen(QPen(self.palette().text(), 2)) painter.drawLine(0, int(br.bottom()+3), w, int(br.bottom()+3)) for top, bot, kind in self.changes: if bot < fv: continue y_top = self.blockBoundingGeometry(doc.findBlockByNumber(top)).translated(origin).y() y_bot = self.blockBoundingGeometry(doc.findBlockByNumber(bot)).translated(origin).y() if max(y_top, y_bot) < ceiling: continue if min(y_top, y_bot) > floor: break if y_top != y_bot: painter.fillRect(0, int(y_top), int(w), int(y_bot - y_top), self.diff_backgrounds[kind]) lines.append((y_top, y_bot, kind)) if top in self.images: img, maxw = self.images[top][:2] if bot > top + 1 and not img.isNull(): y_top = self.blockBoundingGeometry(doc.findBlockByNumber(top+1)).translated(origin).y() + 3 y_bot -= 3 scaled, imgw, imgh = fit_image(int(img.width()/img.devicePixelRatio()), int(img.height()/img.devicePixelRatio()), w - 3, y_bot - y_top) painter.drawPixmap(QRect(3, int(y_top), int(imgw), int(imgh)), img) painter.end() PlainTextEdit.paintEvent(self, event) painter = QPainter(self.viewport()) painter.setClipRect(event.rect()) for top, bottom, kind in sorted(lines, key=lambda t_b_k:{'replace':0}.get(t_b_k[2], 1)): painter.setPen(QPen(self.diff_foregrounds[kind], 1)) painter.drawLine(0, int(top), int(w), int(top)) painter.drawLine(0, int(bottom - 1), int(w), int(bottom - 1)) def wheelEvent(self, ev): if ev.angleDelta().x() == 0: self.wheel_event.emit(ev) else: return PlainTextEdit.wheelEvent(self, ev) # }}} class DiffSplitHandle(QSplitterHandle): # {{{ WIDTH = 30 # px wheel_event = pyqtSignal(object) def event(self, ev): if ev.type() in (QEvent.Type.HoverEnter, QEvent.Type.HoverLeave): self.hover = ev.type() == QEvent.Type.HoverEnter return QSplitterHandle.event(self, ev) def paintEvent(self, event): QSplitterHandle.paintEvent(self, event) left, right = self.parent().left, self.parent().right painter = QPainter(self) painter.setClipRect(event.rect()) w = self.width() h = self.height() painter.setRenderHints(QPainter.RenderHint.Antialiasing, True) C = 16 # Curve factor. def create_line(ly, ry, right_to_left=False): ' Create path that represents upper or lower line of change marker ' line = QPainterPath() if not right_to_left: line.moveTo(0, ly) line.cubicTo(C, ly, w - C, ry, w, ry) else: line.moveTo(w, ry) line.cubicTo(w - C, ry, C, ly, 0, ly) return line ldoc, rdoc = left.document(), right.document() lorigin, rorigin = left.contentOffset(), right.contentOffset() lfv, rfv = left.firstVisibleBlock().blockNumber(), right.firstVisibleBlock().blockNumber() lines = [] for (ltop, lbot, kind), (rtop, rbot, kind) in zip(left.changes, right.changes): if lbot < lfv and rbot < rfv: continue ly_top = left.blockBoundingGeometry(ldoc.findBlockByNumber(ltop)).translated(lorigin).y() ly_bot = left.blockBoundingGeometry(ldoc.findBlockByNumber(lbot)).translated(lorigin).y() ry_top = right.blockBoundingGeometry(rdoc.findBlockByNumber(rtop)).translated(rorigin).y() ry_bot = right.blockBoundingGeometry(rdoc.findBlockByNumber(rbot)).translated(rorigin).y() if max(ly_top, ly_bot, ry_top, ry_bot) < 0: continue if min(ly_top, ly_bot, ry_top, ry_bot) > h: break upper_line = create_line(ly_top, ry_top) lower_line = create_line(ly_bot, ry_bot, True) region = QPainterPath() region.moveTo(0, ly_top) region.connectPath(upper_line) region.lineTo(w, ry_bot) region.connectPath(lower_line) region.closeSubpath() painter.fillPath(region, left.diff_backgrounds[kind]) for path, aa in zip((upper_line, lower_line), (ly_top != ry_top, ly_bot != ry_bot)): lines.append((kind, path, aa)) for kind, path, aa in sorted(lines, key=lambda x:{'replace':0}.get(x[0], 1)): painter.setPen(left.diff_foregrounds[kind]) painter.setRenderHints(QPainter.RenderHint.Antialiasing, aa) painter.drawPath(path) painter.setFont(left.heading_font) for (lnum, text), (rnum, text) in zip(left.headers, right.headers): ltop, lbot, rtop, rbot = lnum, lnum + 3, rnum, rnum + 3 if lbot < lfv and rbot < rfv: continue ly_top = left.blockBoundingGeometry(ldoc.findBlockByNumber(ltop)).translated(lorigin).y() ly_bot = left.blockBoundingGeometry(ldoc.findBlockByNumber(lbot)).translated(lorigin).y() ry_top = right.blockBoundingGeometry(rdoc.findBlockByNumber(rtop)).translated(rorigin).y() ry_bot = right.blockBoundingGeometry(rdoc.findBlockByNumber(rbot)).translated(rorigin).y() if max(ly_top, ly_bot, ry_top, ry_bot) < 0: continue if min(ly_top, ly_bot, ry_top, ry_bot) > h: break ly = painter.boundingRect(3, int(ly_top), int(left.width()), int(ly_bot - ly_top - 5), Qt.TextFlag.TextSingleLine, text).bottom() + 3 ry = painter.boundingRect(3, int(ry_top), int(right.width()), int(ry_bot - ry_top - 5), Qt.TextFlag.TextSingleLine, text).bottom() + 3 line = create_line(ly, ry) painter.setPen(QPen(left.palette().text(), 2)) painter.setRenderHints(QPainter.RenderHint.Antialiasing, ly != ry) painter.drawPath(line) painter.end() # Paint the splitter without the change lines if the mouse is over the # splitter if getattr(self, 'hover', False): QSplitterHandle.paintEvent(self, event) def sizeHint(self): ans = QSplitterHandle.sizeHint(self) ans.setWidth(self.WIDTH) return ans def wheelEvent(self, ev): if ev.angleDelta().x() == 0: self.wheel_event.emit(ev) else: return QSplitterHandle.wheelEvent(self, ev) # }}} class DiffSplit(QSplitter): # {{{ def __init__(self, parent=None, show_open_in_editor=False): QSplitter.__init__(self, parent) self._failed_img = None self.left, self.right = TextBrowser(parent=self), TextBrowser(right=True, parent=self, show_open_in_editor=show_open_in_editor) self.addWidget(self.left), self.addWidget(self.right) self.split_words = re.compile(r"\w+|\W", re.UNICODE) self.clear() def createHandle(self): return DiffSplitHandle(self.orientation(), self) def clear(self): self.left.clear(), self.right.clear() def finalize(self): for v in (self.left, self.right): c = v.textCursor() c.movePosition(QTextCursor.MoveOperation.Start) v.setTextCursor(c) self.update() def add_diff(self, left_name, right_name, left_text, right_text, context=None, syntax=None, beautify=False): left_text, right_text = left_text or '', right_text or '' is_identical = len(left_text) == len(right_text) and left_text == right_text and left_name == right_name is_text = isinstance(left_text, str) and isinstance(right_text, str) left_name = left_name or '[%s]'%_('This file was added') right_name = right_name or '[%s]'%_('This file was removed') self.left.headers.append((self.left.blockCount() - 1, left_name)) self.right.headers.append((self.right.blockCount() - 1, right_name)) for v in (self.left, self.right): c = v.textCursor() c.movePosition(QTextCursor.MoveOperation.End) (c.insertBlock(), c.insertBlock(), c.insertBlock()) with BusyCursor(): if is_identical: for v in (self.left, self.right): c = v.textCursor() c.movePosition(QTextCursor.MoveOperation.End) c.insertText('[%s]\n\n' % _('The files are identical')) elif left_name != right_name and not left_text and not right_text: self.add_text_diff(_('[This file was renamed to %s]') % right_name, _('[This file was renamed from %s]') % left_name, context, None) for v in (self.left, self.right): v.appendPlainText('\n') elif is_text: self.add_text_diff(left_text, right_text, context, syntax, beautify=beautify) elif syntax == 'raster_image': self.add_image_diff(left_text, right_text) else: text = '[%s]' % _('Binary file of size: %s') left_text, right_text = text % human_readable(len(left_text)), text % human_readable(len(right_text)) self.add_text_diff(left_text, right_text, None, None) for v in (self.left, self.right): v.appendPlainText('\n') # image diffs {{{ @property def failed_img(self): if self._failed_img is None: try: dpr = self.devicePixelRatioF() except AttributeError: dpr = self.devicePixelRatio() i = QImage(200, 150, QImage.Format.Format_ARGB32) i.setDevicePixelRatio(dpr) i.fill(Qt.GlobalColor.white) p = QPainter(i) r = i.rect().adjusted(10, 10, -10, -10) n = QPen(Qt.PenStyle.DashLine) n.setColor(Qt.GlobalColor.black) p.setPen(n) p.drawRect(r) p.setPen(Qt.GlobalColor.black) f = self.font() f.setPixelSize(20) p.setFont(f) p.drawText(r.adjusted(10, 0, -10, 0), Qt.AlignmentFlag.AlignCenter | Qt.TextFlag.TextWordWrap, _('Image could not be rendered')) p.end() self._failed_img = QPixmap.fromImage(i) return self._failed_img def add_image_diff(self, left_data, right_data): def load(data): p = QPixmap() p.loadFromData(as_bytes(data)) try: dpr = self.devicePixelRatioF() except AttributeError: dpr = self.devicePixelRatio() p.setDevicePixelRatio(dpr) if data and p.isNull(): p = self.failed_img return p left_img, right_img = load(left_data), load(right_data) change = [] # Let any initial resizing of the window finish in case this is the # first diff, to avoid the expensive resize calculation later QApplication.processEvents(QEventLoop.ProcessEventsFlag.ExcludeUserInputEvents | QEventLoop.ProcessEventsFlag.ExcludeSocketNotifiers) for v, img, size in ((self.left, left_img, len(left_data)), (self.right, right_img, len(right_data))): c = v.textCursor() c.movePosition(QTextCursor.MoveOperation.End) start = c.block().blockNumber() lines, w = self.get_lines_for_image(img, v) c.movePosition(QTextCursor.MoveOperation.StartOfBlock) if size > 0: c.beginEditBlock() c.insertText(_('Size: {0} Resolution: {1}x{2}').format(human_readable(size), img.width(), img.height())) for i in range(lines + 1): c.insertBlock() change.extend((start, c.block().blockNumber())) c.insertBlock() c.endEditBlock() v.images[start] = (img, w, lines) change.append('replace' if left_data and right_data else 'delete' if left_data else 'insert') self.left.changes.append((change[0], change[1], change[-1])) self.right.changes.append((change[2], change[3], change[-1])) QApplication.processEvents(QEventLoop.ProcessEventsFlag.ExcludeUserInputEvents | QEventLoop.ProcessEventsFlag.ExcludeSocketNotifiers) def resized(self): ' Resize images to fit in new view size and adjust all line number references accordingly ' for v in (self.left, self.right): changes = [] for i, (top, bot, kind) in enumerate(v.changes): if top in v.images: img, oldw, oldlines = v.images[top] lines, w = self.get_lines_for_image(img, v) if lines != oldlines: changes.append((i, lines, lines - oldlines, img, w)) for i, lines, delta, img, w in changes: top, bot, kind = v.changes[i] c = QTextCursor(v.document().findBlockByNumber(top+1)) c.beginEditBlock() c.movePosition(QTextCursor.MoveOperation.StartOfBlock) if delta > 0: for _ in range(delta): c.insertBlock() else: c.movePosition(QTextCursor.MoveOperation.NextBlock, QTextCursor.MoveMode.KeepAnchor, -delta) c.removeSelectedText() c.endEditBlock() v.images[top] = (img, w, lines) def mapnum(x): return x if x <= top else x + delta lnm = LineNumberMap() lnm.max_width = v.line_number_map.max_width for x, val in iteritems(v.line_number_map): dict.__setitem__(lnm, mapnum(x), val) v.line_number_map = lnm v.changes = [(mapnum(t), mapnum(b), k) for t, b, k in v.changes] v.headers = [(mapnum(x), name) for x, name in v.headers] v.images = OrderedDict((mapnum(x), v) for x, v in iteritems(v.images)) v.viewport().update() def get_lines_for_image(self, img, view): if img.isNull(): return 0, 0 w, h = int(img.width()/img.devicePixelRatio()), int(img.height()/img.devicePixelRatio()) scaled, w, h = fit_image(w, h, view.available_width() - 3, int(0.9 * view.height())) line_height = view.blockBoundingRect(view.document().begin()).height() return int(ceil(h / line_height)) + 1, w # }}} # text diffs {{{ def add_text_diff(self, left_text, right_text, context, syntax, beautify=False): left_text = unicodedata.normalize('NFC', left_text) right_text = unicodedata.normalize('NFC', right_text) if beautify and syntax in {'xml', 'html', 'css'}: left_text, right_text = beautify_text(left_text, syntax), beautify_text(right_text, syntax) if len(left_text) == len(right_text) and left_text == right_text: for v in (self.left, self.right): c = v.textCursor() c.movePosition(QTextCursor.MoveOperation.End) c.insertText('[%s]\n\n' % _('The files are identical after beautifying')) return left_lines = self.left_lines = left_text.splitlines() right_lines = self.right_lines = right_text.splitlines() cruncher = get_sequence_matcher()(None, left_lines, right_lines) left_highlight, right_highlight = get_highlighter(self.left, left_text, syntax), get_highlighter(self.right, right_text, syntax) cl, cr = self.left_cursor, self.right_cursor = self.left.textCursor(), self.right.textCursor() cl.beginEditBlock(), cr.beginEditBlock() cl.movePosition(QTextCursor.MoveOperation.End), cr.movePosition(QTextCursor.MoveOperation.End) self.left_insert = partial(self.do_insert, cl, left_highlight, self.left.line_number_map) self.right_insert = partial(self.do_insert, cr, right_highlight, self.right.line_number_map) self.changes = [] if context is None: for tag, alo, ahi, blo, bhi in cruncher.get_opcodes(): getattr(self, tag)(alo, ahi, blo, bhi) QApplication.processEvents(QEventLoop.ProcessEventsFlag.ExcludeUserInputEvents | QEventLoop.ProcessEventsFlag.ExcludeSocketNotifiers) else: def insert_boundary(): self.changes.append(Change( ltop=cl.block().blockNumber()-1, lbot=cl.block().blockNumber(), rtop=cr.block().blockNumber()-1, rbot=cr.block().blockNumber(), kind='boundary')) self.left.line_number_map[self.changes[-1].ltop] = '-' self.right.line_number_map[self.changes[-1].rtop] = '-' ahi = bhi = 0 for i, group in enumerate(cruncher.get_grouped_opcodes(context)): for j, (tag, alo, ahi, blo, bhi) in enumerate(group): if j == 0 and (i > 0 or min(alo, blo) > 0): insert_boundary() getattr(self, tag)(alo, ahi, blo, bhi) QApplication.processEvents(QEventLoop.ProcessEventsFlag.ExcludeUserInputEvents | QEventLoop.ProcessEventsFlag.ExcludeSocketNotifiers) cl.insertBlock(), cr.insertBlock() if ahi < len(left_lines) - 1 or bhi < len(right_lines) - 1: insert_boundary() cl.endEditBlock(), cr.endEditBlock() del self.left_lines del self.right_lines del self.left_insert del self.right_insert self.coalesce_changes() for ltop, lbot, rtop, rbot, kind in self.changes: if kind != 'equal': self.left.changes.append((ltop, lbot, kind)) self.right.changes.append((rtop, rbot, kind)) del self.changes def coalesce_changes(self): 'Merge neighboring changes of the same kind, if any' changes = [] for x in self.changes: if changes and changes[-1].kind == x.kind: changes[-1] = changes[-1]._replace(lbot=x.lbot, rbot=x.rbot) else: changes.append(x) self.changes = changes def do_insert(self, cursor, highlighter, line_number_map, lo, hi): start_block = cursor.block() highlighter.copy_lines(lo, hi, cursor) for num, i in enumerate(range(start_block.blockNumber(), cursor.blockNumber())): line_number_map[i] = lo + num + 1 return start_block.blockNumber(), cursor.block().blockNumber() def equal(self, alo, ahi, blo, bhi): lsb, lcb = self.left_insert(alo, ahi) rsb, rcb = self.right_insert(blo, bhi) self.changes.append(Change( rtop=rsb, rbot=rcb, ltop=lsb, lbot=lcb, kind='equal')) def delete(self, alo, ahi, blo, bhi): start_block, current_block = self.left_insert(alo, ahi) r = self.right_cursor.block().blockNumber() self.changes.append(Change( ltop=start_block, lbot=current_block, rtop=r, rbot=r, kind='delete')) def insert(self, alo, ahi, blo, bhi): start_block, current_block = self.right_insert(blo, bhi) l = self.left_cursor.block().blockNumber() self.changes.append(Change( rtop=start_block, rbot=current_block, ltop=l, lbot=l, kind='insert')) def trim_identical_leading_lines(self, alo, ahi, blo, bhi): ''' The patience diff algorithm sometimes results in a block of replace lines with identical leading lines. Remove these. This can cause extra lines of context, but that is better than having extra lines of diff with no actual changes. ''' a, b = self.left_lines, self.right_lines leading = 0 while alo < ahi and blo < bhi and a[alo] == b[blo]: leading += 1 alo += 1 blo += 1 if leading > 0: self.equal(alo - leading, alo, blo - leading, blo) return alo, ahi, blo, bhi def replace(self, alo, ahi, blo, bhi): ''' When replacing one block of lines with another, search the blocks for *similar* lines; the best-matching pair (if any) is used as a synch point, and intraline difference marking is done on the similar pair. Lots of work, but often worth it. ''' alo, ahi, blo, bhi = self.trim_identical_leading_lines(alo, ahi, blo, bhi) if alo == ahi and blo == bhi: return if ahi + bhi - alo - blo > 100: # Too many lines, this will be too slow # http://bugs.python.org/issue6931 return self.do_replace(alo, ahi, blo, bhi) # don't synch up unless the lines have a similarity score of at # least cutoff; best_ratio tracks the best score seen so far best_ratio, cutoff = 0.74, 0.75 cruncher = SequenceMatcher() eqi, eqj = None, None # 1st indices of equal lines (if any) a, b = self.left_lines, self.right_lines # search for the pair that matches best without being identical # (identical lines must be junk lines, & we don't want to synch up # on junk -- unless we have to) for j in range(blo, bhi): bj = b[j] cruncher.set_seq2(bj) for i in range(alo, ahi): ai = a[i] if ai == bj: if eqi is None: eqi, eqj = i, j continue cruncher.set_seq1(ai) # computing similarity is expensive, so use the quick # upper bounds first -- have seen this speed up messy # compares by a factor of 3. # note that ratio() is only expensive to compute the first # time it's called on a sequence pair; the expensive part # of the computation is cached by cruncher if (cruncher.real_quick_ratio() > best_ratio and cruncher.quick_ratio() > best_ratio and cruncher.ratio() > best_ratio): best_ratio, best_i, best_j = cruncher.ratio(), i, j if best_ratio < cutoff: # no non-identical "pretty close" pair if eqi is None: # no identical pair either -- treat it as a straight replace self.do_replace(alo, ahi, blo, bhi) return # no close pair, but an identical pair -- synch up on that best_i, best_j, best_ratio = eqi, eqj, 1.0 else: # there's a close pair, so forget the identical pair (if any) eqi = None # a[best_i] very similar to b[best_j]; eqi is None iff they're not # identical # pump out diffs from before the synch point self.replace_helper(alo, best_i, blo, best_j) # do intraline marking on the synch pair if eqi is None: self.do_replace(best_i, best_i+1, best_j, best_j+1) else: # the synch pair is identical self.equal(best_i, best_i+1, best_j, best_j+1) # pump out diffs from after the synch point self.replace_helper(best_i+1, ahi, best_j+1, bhi) def replace_helper(self, alo, ahi, blo, bhi): if alo < ahi: if blo < bhi: self.replace(alo, ahi, blo, bhi) else: self.delete(alo, ahi, blo, blo) elif blo < bhi: self.insert(alo, alo, blo, bhi) def do_replace(self, alo, ahi, blo, bhi): lsb, lcb = self.left_insert(alo, ahi) rsb, rcb = self.right_insert(blo, bhi) self.changes.append(Change( rtop=rsb, rbot=rcb, ltop=lsb, lbot=lcb, kind='replace')) l, r = '\n'.join(self.left_lines[alo:ahi]), '\n'.join(self.right_lines[blo:bhi]) ll, rl = self.split_words.findall(l), self.split_words.findall(r) cruncher = get_sequence_matcher()(None, ll, rl) lsb, rsb = self.left.document().findBlockByNumber(lsb), self.right.document().findBlockByNumber(rsb) def do_tag(block, words, lo, hi, pos, fmts): for word in words[lo:hi]: if word == '\n': if fmts: block.layout().setFormats(fmts) pos, block, fmts = 0, block.next(), [] continue if tag in {'replace', 'insert', 'delete'}: fmt = getattr(self.left, '%s_format' % ('replacereplace' if tag == 'replace' else tag)) f = QTextLayout.FormatRange() f.start, f.length, f.format = pos, len(word), fmt fmts.append(f) pos += utf16_length(word) return block, pos, fmts lfmts, rfmts, lpos, rpos = [], [], 0, 0 for tag, llo, lhi, rlo, rhi in cruncher.get_opcodes(): lsb, lpos, lfmts = do_tag(lsb, ll, llo, lhi, lpos, lfmts) rsb, rpos, rfmts = do_tag(rsb, rl, rlo, rhi, rpos, rfmts) for block, fmts in ((lsb, lfmts), (rsb, rfmts)): if fmts: block.layout().setFormats(fmts) # }}} # }}} class DiffView(QWidget): # {{{ SYNC_POSITION = 0.4 line_activated = pyqtSignal(object, object, object) def __init__(self, parent=None, show_open_in_editor=False): QWidget.__init__(self, parent) self.changes = [[], [], []] self.delta = 0 self.l = l = QHBoxLayout(self) self.setLayout(l) self.syncpos = 0 l.setContentsMargins(0, 0, 0, 0), l.setSpacing(0) self.view = DiffSplit(self, show_open_in_editor=show_open_in_editor) l.addWidget(self.view) self.add_diff = self.view.add_diff self.scrollbar = QScrollBar(self) l.addWidget(self.scrollbar) self.syncing = False self.bars = [] self.resize_timer = QTimer(self) self.resize_timer.setSingleShot(True) self.resize_timer.timeout.connect(self.resize_debounced) for bar in (self.scrollbar, self.view.left.verticalScrollBar(), self.view.right.verticalScrollBar()): self.bars.append(bar) bar.scroll_idx = len(self.bars) - 1 connect_lambda(bar.valueChanged[int], self, lambda self: self.scrolled(self.sender().scroll_idx)) self.view.left.resized.connect(self.resized) for v in (self.view.left, self.view.right, self.view.handle(1)): v.wheel_event.connect(self.scrollbar.wheelEvent) if v is self.view.left or v is self.view.right: v.next_change.connect(self.next_change) v.line_activated.connect(self.line_activated) connect_lambda(v.scrolled, self, lambda self: self.scrolled(1 if self.sender() is self.view.left else 2)) def next_change(self, delta): assert delta in (1, -1) position = self.get_position_from_scrollbar(0) if position[0] == 'in': p = n = position[1] else: p, n = position[1], position[1] + 1 if p < 0: p = None if n >= len(self.changes[0]): n = None if p == n: nc = p + delta if nc < 0 or nc >= len(self.changes[0]): nc = None else: nc = {1:n, -1:p}[delta] if nc is None: self.scrollbar.setValue(0 if delta == -1 else self.scrollbar.maximum()) else: val = self.scrollbar.value() self.scroll_to(0, ('in', nc, 0)) nval = self.scrollbar.value() if nval == val: nval += 5 * delta if 0 <= nval <= self.scrollbar.maximum(): self.scrollbar.setValue(nval) def resized(self): self.resize_timer.start(300) def resize_debounced(self): self.view.resized() self.calculate_length() self.adjust_range() self.view.handle(1).update() def get_position_from_scrollbar(self, which): changes = self.changes[which] bar = self.bars[which] syncpos = self.syncpos + bar.value() prev = 0 for i, (top, bot, kind) in enumerate(changes): if syncpos <= bot: if top <= syncpos: # syncpos is inside a change try: ratio = float(syncpos - top) / (bot - top) except ZeroDivisionError: ratio = 0 return 'in', i, ratio else: # syncpos is after the previous change offset = syncpos - prev return 'after', i - 1, offset else: # syncpos is after the current change prev = bot offset = syncpos - prev return 'after', len(changes) - 1, offset def scroll_to(self, which, position): changes = self.changes[which] bar = self.bars[which] val = None if position[0] == 'in': change_idx, ratio = position[1:] start, end = changes[change_idx][:2] val = start + int((end - start) * ratio) else: change_idx, offset = position[1:] start = 0 if change_idx < 0 else changes[change_idx][1] val = start + offset bar.setValue(val - self.syncpos) def scrolled(self, which, *args): if self.syncing: return position = self.get_position_from_scrollbar(which) with self: for x in {0, 1, 2} - {which}: self.scroll_to(x, position) self.view.handle(1).update() def __enter__(self): self.syncing = True def __exit__(self, *args): self.syncing = False def clear(self): with self: self.view.clear() self.changes = [[], [], []] self.delta = 0 self.scrollbar.setRange(0, 0) def adjust_range(self): ls, rs = self.view.left.verticalScrollBar(), self.view.right.verticalScrollBar() self.scrollbar.setPageStep(min(ls.pageStep(), rs.pageStep())) self.scrollbar.setSingleStep(min(ls.singleStep(), rs.singleStep())) self.scrollbar.setRange(0, ls.maximum() + self.delta) self.scrollbar.setVisible(self.view.left.document().lineCount() > ls.pageStep() or self.view.right.document().lineCount() > rs.pageStep()) self.syncpos = int(ceil(self.scrollbar.pageStep() * self.SYNC_POSITION)) def finalize(self): self.view.finalize() self.changes = [[], [], []] self.calculate_length() self.adjust_range() def calculate_length(self): delta = 0 line_number_changes = ([], []) for v, lmap, changes in zip((self.view.left, self.view.right), ({}, {}), line_number_changes): b = v.document().firstBlock() ebl = v.document().documentLayout().ensureBlockLayout last_line_count = 0 while b.isValid(): ebl(b) lmap[b.blockNumber()] = last_line_count last_line_count += b.layout().lineCount() b = b.next() for top, bot, kind in v.changes: changes.append((lmap[top], lmap[bot], kind)) changes = [] for (l_top, l_bot, kind), (r_top, r_bot, kind) in zip(*line_number_changes): height = max(l_bot - l_top, r_bot - r_top) top = delta + l_top changes.append((top, top + height, kind)) delta = top + height - l_bot self.changes, self.delta = (changes,) + line_number_changes, delta def handle_key(self, ev): amount, d = None, 1 key = ev.key() if key in (Qt.Key.Key_Up, Qt.Key.Key_Down, Qt.Key.Key_J, Qt.Key.Key_K): amount = self.scrollbar.singleStep() if key in (Qt.Key.Key_Up, Qt.Key.Key_K): d = -1 elif key in (Qt.Key.Key_PageUp, Qt.Key.Key_PageDown): amount = self.scrollbar.pageStep() if key in (Qt.Key.Key_PageUp,): d = -1 elif key in (Qt.Key.Key_Home, Qt.Key.Key_End): self.scrollbar.setValue(0 if key == Qt.Key.Key_Home else self.scrollbar.maximum()) return True elif key in (Qt.Key.Key_N, Qt.Key.Key_P): self.next_change(1 if key == Qt.Key.Key_N else -1) return True if amount is not None: self.scrollbar.setValue(self.scrollbar.value() + d * amount) return True return False # }}}
48,180
Python
.py
995
36.992965
155
0.586057
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,717
main.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/diff/main.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' import os import re import sys import textwrap from functools import partial from qt.core import ( QApplication, QCursor, QDialogButtonBox, QEventLoop, QGridLayout, QHBoxLayout, QIcon, QKeySequence, QLabel, QMenu, QPainter, QRadioButton, QRect, QSize, QStackedLayout, Qt, QTimer, QToolButton, QVBoxLayout, QWidget, pyqtSignal, ) from calibre.ebooks.oeb.polish.container import Container from calibre.ebooks.oeb.polish.utils import guess_type from calibre.gui2 import info_dialog from calibre.gui2.progress_indicator import ProgressIndicator from calibre.gui2.tweak_book.diff.view import DiffView from calibre.gui2.tweak_book.editor import syntax_from_mime from calibre.gui2.tweak_book.widgets import Dialog from calibre.gui2.widgets2 import HistoryLineEdit2 from calibre.startup import connect_lambda from calibre.utils.filenames import samefile from calibre.utils.icu import numeric_sort_key from polyglot.builtins import iteritems class BusyWidget(QWidget): # {{{ def __init__(self, parent): QWidget.__init__(self, parent) l = QVBoxLayout() self.setLayout(l) l.addStretch(10) self.pi = ProgressIndicator(self, 128) l.addWidget(self.pi, alignment=Qt.AlignmentFlag.AlignHCenter) self.dummy = QLabel('<h2>\xa0') l.addSpacing(10) l.addWidget(self.dummy, alignment=Qt.AlignmentFlag.AlignHCenter) l.addStretch(10) self.text = _('Calculating differences, please wait...') def paintEvent(self, ev): br = ev.region().boundingRect() QWidget.paintEvent(self, ev) p = QPainter(self) p.setClipRect(br) f = p.font() f.setBold(True) f.setPointSize(20) p.setFont(f) p.setPen(Qt.PenStyle.SolidLine) r = QRect(0, self.dummy.geometry().top() + 10, self.geometry().width(), 150) p.drawText(r, Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop | Qt.TextFlag.TextSingleLine, self.text) p.end() # }}} class Cache: def __init__(self): self._left, self._right = {}, {} self.left, self.right = self._left.get, self._right.get self.set_left, self.set_right = self._left.__setitem__, self._right.__setitem__ def changed_files(list_of_names1, list_of_names2, get_data1, get_data2): list_of_names1, list_of_names2 = frozenset(list_of_names1), frozenset(list_of_names2) changed_names = set() cache = Cache() common_names = list_of_names1.intersection(list_of_names2) for name in common_names: left, right = get_data1(name), get_data2(name) if len(left) == len(right) and left == right: continue cache.set_left(name, left), cache.set_right(name, right) changed_names.add(name) removals = list_of_names1 - common_names adds = set(list_of_names2 - common_names) adata, rdata = {a:get_data2(a) for a in adds}, {r:get_data1(r) for r in removals} ahash = {a:hash(d) for a, d in iteritems(adata)} rhash = {r:hash(d) for r, d in iteritems(rdata)} renamed_names, removed_names, added_names = {}, set(), set() for name, rh in iteritems(rhash): for n, ah in iteritems(ahash): if ah == rh: renamed_names[name] = n adds.discard(n) break else: cache.set_left(name, rdata[name]) removed_names.add(name) for name in adds: cache.set_right(name, adata[name]) added_names.add(name) return cache, changed_names, renamed_names, removed_names, added_names def get_decoded_raw(name): from calibre.ebooks.chardet import force_encoding, xml_to_unicode with open(name, 'rb') as f: raw = f.read() syntax = syntax_from_mime(name, guess_type(name)) if syntax is None: try: raw = raw.decode('utf-8') except ValueError: pass elif syntax != 'raster_image': if syntax in {'html', 'xml'}: raw = xml_to_unicode(raw, verbose=True)[0] else: m = re.search(br"coding[:=]\s*([-\w.]+)", raw[:1024], flags=re.I) if m is not None and m.group(1) != '8bit': enc = m.group(1) if enc == b'unicode': enc = 'utf-8' else: enc = force_encoding(raw, verbose=True) if isinstance(enc, bytes): enc = enc.decode('utf-8', 'ignore') try: raw = raw.decode(enc) except (LookupError, ValueError): try: raw = raw.decode('utf-8') except ValueError: pass return raw, syntax def string_diff(left, right, left_syntax=None, right_syntax=None, left_name='left', right_name='right'): left, right = str(left), str(right) cache = Cache() cache.set_left(left_name, left), cache.set_right(right_name, right) changed_names = {} if left == right else {left_name:right_name} return cache, {left_name:left_syntax, right_name:right_syntax}, changed_names, {}, set(), set() def file_diff(left, right): (raw1, syntax1), (raw2, syntax2) = map(get_decoded_raw, (left, right)) if type(raw1) is not type(raw2): with open(left, 'rb') as f1, open(right, 'rb') as f2: raw1, raw2 = f1.read(), f2.read() cache = Cache() cache.set_left(left, raw1), cache.set_right(right, raw2) changed_names = {} if raw1 == raw2 else {left:right} return cache, {left:syntax1, right:syntax2}, changed_names, {}, set(), set() def dir_diff(left, right): ldata, rdata, lsmap, rsmap = {}, {}, {}, {} for base, data, smap in ((left, ldata, lsmap), (right, rdata, rsmap)): for dirpath, dirnames, filenames in os.walk(base): for filename in filenames: path = os.path.join(dirpath, filename) name = os.path.relpath(path, base) data[name], smap[name] = get_decoded_raw(path) cache, changed_names, renamed_names, removed_names, added_names = changed_files( ldata, rdata, ldata.get, rdata.get) syntax_map = {name:lsmap[name] for name in changed_names} syntax_map.update({name:lsmap[name] for name in renamed_names}) syntax_map.update({name:rsmap[name] for name in added_names}) syntax_map.update({name:lsmap[name] for name in removed_names}) return cache, syntax_map, changed_names, renamed_names, removed_names, added_names def container_diff(left, right): left_names, right_names = set(left.name_path_map), set(right.name_path_map) if left.cloned or right.cloned: # Since containers are often clones of each other, as a performance # optimization, discard identical names that point to the same physical # file, without needing to read the file's contents. # First commit dirtied names for c in (left, right): Container.commit(c, keep_parsed=True) samefile_names = {name for name in left_names & right_names if samefile( left.name_path_map[name], right.name_path_map[name])} left_names -= samefile_names right_names -= samefile_names cache, changed_names, renamed_names, removed_names, added_names = changed_files( left_names, right_names, left.raw_data, right.raw_data) def syntax(container, name): mt = container.mime_map[name] return syntax_from_mime(name, mt) syntax_map = {name:syntax(left, name) for name in changed_names} syntax_map.update({name:syntax(left, name) for name in renamed_names}) syntax_map.update({name:syntax(right, name) for name in added_names}) syntax_map.update({name:syntax(left, name) for name in removed_names}) return cache, syntax_map, changed_names, renamed_names, removed_names, added_names def ebook_diff(path1, path2): from calibre.ebooks.oeb.polish.container import get_container left = get_container(path1, tweak_mode=True) right = get_container(path2, tweak_mode=True) return container_diff(left, right) class Diff(Dialog): revert_requested = pyqtSignal() line_activated = pyqtSignal(object, object, object) def __init__(self, revert_button_msg=None, parent=None, show_open_in_editor=False, show_as_window=False): self.context = 3 self.beautify = False self.apply_diff_calls = [] self.show_open_in_editor = show_open_in_editor self.revert_button_msg = revert_button_msg self.show_as_window = show_as_window Dialog.__init__(self, _('Differences between books'), 'diff-dialog', parent=parent) self.view.line_activated.connect(self.line_activated) def sizeHint(self): geom = self.screen().availableSize() return QSize(int(0.9 * geom.width()), int(0.8 * geom.height())) def setup_ui(self): self.setWindowIcon(QIcon.ic('diff.png')) if self.show_as_window: self.setWindowFlags(Qt.WindowType.Window) else: self.setWindowFlags(self.windowFlags() | Qt.WindowType.WindowMinMaxButtonsHint) self.stacks = st = QStackedLayout(self) self.busy = BusyWidget(self) self.w = QWidget(self) st.addWidget(self.busy), st.addWidget(self.w) self.setLayout(st) self.l = l = QGridLayout() self.w.setLayout(l) self.view = v = DiffView(self, show_open_in_editor=self.show_open_in_editor) l.addWidget(v, l.rowCount(), 0, 1, -1) r = l.rowCount() self.bp = b = QToolButton(self) b.setIcon(QIcon.ic('back.png')) connect_lambda(b.clicked, self, lambda self: self.view.next_change(-1)) b.setToolTip(_('Go to previous change') + ' [p]') b.setText(_('&Previous change')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) l.addWidget(b, r, 0) self.bn = b = QToolButton(self) b.setIcon(QIcon.ic('forward.png')) connect_lambda(b.clicked, self, lambda self: self.view.next_change(1)) b.setToolTip(_('Go to next change') + ' [n]') b.setText(_('&Next change')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) l.addWidget(b, r, 1) self.search = s = HistoryLineEdit2(self) s.initialize('diff_search_history') l.addWidget(s, r, 2) s.setPlaceholderText(_('Search for text')) connect_lambda(s.returnPressed, self, lambda self: self.do_search(False)) self.sbn = b = QToolButton(self) b.setIcon(QIcon.ic('arrow-down.png')) connect_lambda(b.clicked, self, lambda self: self.do_search(False)) b.setToolTip(_('Find next match')) b.setText(_('Next &match')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) l.addWidget(b, r, 3) self.sbp = b = QToolButton(self) b.setIcon(QIcon.ic('arrow-up.png')) connect_lambda(b.clicked, self, lambda self: self.do_search(True)) b.setToolTip(_('Find previous match')) b.setText(_('P&revious match')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) l.addWidget(b, r, 4) self.lb = b = QRadioButton(_('Left panel'), self) b.setToolTip(_('Perform search in the left panel')) l.addWidget(b, r, 5) self.rb = b = QRadioButton(_('Right panel'), self) b.setToolTip(_('Perform search in the right panel')) l.addWidget(b, r, 6) b.setChecked(True) self.pb = b = QToolButton(self) b.setIcon(QIcon.ic('config.png')) b.setText(_('&Options')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) b.setToolTip(_('Change how the differences are displayed')) b.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup) m = QMenu(b) b.setMenu(m) cm = self.cm = QMenu(_('Lines of context around each change')) for i in (3, 5, 10, 50): cm.addAction(_('Show %d lines of context') % i, partial(self.change_context, i)) cm.addAction(_('Show all text'), partial(self.change_context, None)) self.beautify_action = m.addAction('', self.toggle_beautify) self.set_beautify_action_text() m.addMenu(cm) l.addWidget(b, r, 7) self.hl = QHBoxLayout() l.addLayout(self.hl, l.rowCount(), 0, 1, -1) self.names = QLabel('') self.hl.addWidget(self.names, stretch=100) if self.show_open_in_editor: self.edit_msg = QLabel(_('Double click right side to edit')) self.edit_msg.setToolTip(textwrap.fill(_( 'Double click on any change in the right panel to edit that location in the editor'))) self.hl.addWidget(self.edit_msg) self.bb.setStandardButtons(QDialogButtonBox.StandardButton.Close) if self.revert_button_msg is not None: self.rvb = b = self.bb.addButton(self.revert_button_msg, QDialogButtonBox.ButtonRole.ActionRole) b.setIcon(QIcon.ic('edit-undo.png')), b.setAutoDefault(False) b.clicked.connect(self.revert_requested) b.clicked.connect(self.reject) self.bb.button(QDialogButtonBox.StandardButton.Close).setDefault(True) self.hl.addWidget(self.bb) self.view.setFocus(Qt.FocusReason.OtherFocusReason) def break_cycles(self): self.view = None for x in ('revert_requested', 'line_activated'): try: getattr(self, x).disconnect() except: pass def do_search(self, reverse): text = str(self.search.text()) if not text.strip(): return v = self.view.view.left if self.lb.isChecked() else self.view.view.right v.search(text, reverse=reverse) def change_context(self, context): if context == self.context: return self.context = context self.refresh() def refresh(self): with self: self.view.clear() for args, kwargs in self.apply_diff_calls: kwargs['context'] = self.context kwargs['beautify'] = self.beautify self.view.add_diff(*args, **kwargs) self.view.finalize() def toggle_beautify(self): self.beautify = not self.beautify self.set_beautify_action_text() self.refresh() def set_beautify_action_text(self): self.beautify_action.setText( _('Beautify files before comparing them') if not self.beautify else _('Do not beautify files before comparing')) def __enter__(self): self.stacks.setCurrentIndex(0) self.busy.setVisible(True) self.busy.pi.startAnimation() QApplication.setOverrideCursor(QCursor(Qt.CursorShape.WaitCursor)) QApplication.processEvents(QEventLoop.ProcessEventsFlag.ExcludeUserInputEvents | QEventLoop.ProcessEventsFlag.ExcludeSocketNotifiers) def __exit__(self, *args): self.busy.pi.stopAnimation() self.stacks.setCurrentIndex(1) QApplication.restoreOverrideCursor() def set_names(self, names): t = '' if isinstance(names, tuple): t = '%s <--> %s' % names self.names.setText(t) def ebook_diff(self, path1, path2, names=None): self.set_names(names) with self: identical = self.apply_diff(_('The books are identical'), *ebook_diff(path1, path2)) self.view.finalize() if identical: self.reject() def container_diff(self, left, right, identical_msg=None, names=None): self.set_names(names) with self: identical = self.apply_diff(identical_msg or _('No changes found'), *container_diff(left, right)) self.view.finalize() if identical: self.reject() def file_diff(self, left, right, identical_msg=None): with self: identical = self.apply_diff(identical_msg or _('The files are identical'), *file_diff(left, right)) self.view.finalize() if identical: self.reject() def string_diff(self, left, right, **kw): with self: identical = self.apply_diff(kw.pop('identical_msg', None) or _('No differences found'), *string_diff(left, right, **kw)) self.view.finalize() if identical: self.reject() def dir_diff(self, left, right, identical_msg=None): with self: identical = self.apply_diff(identical_msg or _('The folders are identical'), *dir_diff(left, right)) self.view.finalize() if identical: self.reject() def apply_diff(self, identical_msg, cache, syntax_map, changed_names, renamed_names, removed_names, added_names): self.view.clear() self.apply_diff_calls = calls = [] def add(args, kwargs): self.view.add_diff(*args, **kwargs) calls.append((args, kwargs)) if len(changed_names) + len(renamed_names) + len(removed_names) + len(added_names) < 1: self.busy.setVisible(False) info_dialog(self, _('No changes found'), identical_msg, show=True) self.busy.setVisible(True) return True def kwargs(name): return {'context': self.context, 'beautify': self.beautify, 'syntax': syntax_map.get(name, None)} if isinstance(changed_names, dict): for name, other_name in sorted(iteritems(changed_names), key=lambda x:numeric_sort_key(x[0])): args = (name, other_name, cache.left(name), cache.right(other_name)) add(args, kwargs(name)) else: for name in sorted(changed_names, key=numeric_sort_key): args = (name, name, cache.left(name), cache.right(name)) add(args, kwargs(name)) for name in sorted(added_names, key=numeric_sort_key): args = (_('[%s was added]') % name, name, None, cache.right(name)) add(args, kwargs(name)) for name in sorted(removed_names, key=numeric_sort_key): args = (name, _('[%s was removed]') % name, cache.left(name), None) add(args, kwargs(name)) for name, new_name in sorted(iteritems(renamed_names), key=lambda x:numeric_sort_key(x[0])): args = (name, new_name, None, None) add(args, kwargs(name)) def keyPressEvent(self, ev): if not self.view.handle_key(ev): if ev.key() in (Qt.Key.Key_Enter, Qt.Key.Key_Return): return # The enter key is used by the search box, so prevent it closing the dialog if ev.key() == Qt.Key.Key_Slash: return self.search.setFocus(Qt.FocusReason.OtherFocusReason) if ev.matches(QKeySequence.StandardKey.Copy): text = self.view.view.left.selected_text + self.view.view.right.selected_text if text: QApplication.clipboard().setText(text) return if ev.matches(QKeySequence.StandardKey.FindNext): self.sbn.click() return if ev.matches(QKeySequence.StandardKey.FindPrevious): self.sbp.click() return return Dialog.keyPressEvent(self, ev) def compare_books(path1, path2, revert_msg=None, revert_callback=None, parent=None, names=None): d = Diff(parent=parent, revert_button_msg=revert_msg) if revert_msg is not None: d.revert_requested.connect(revert_callback) QTimer.singleShot(0, partial(d.ebook_diff, path1, path2, names=names)) d.exec() try: d.revert_requested.disconnect() except: pass d.break_cycles() def main(args=sys.argv): from calibre.gui2 import Application left, right = args[-2:] ext1, ext2 = left.rpartition('.')[-1].lower(), right.rpartition('.')[-1].lower() if ext1.startswith('original_'): ext1 = ext1.partition('_')[-1] if ext2.startswith('original_'): ext2 = ext2.partition('_')[-2] if os.path.isdir(left): attr = 'dir_diff' elif (ext1, ext2) in {('epub', 'epub'), ('azw3', 'azw3')}: attr = 'ebook_diff' else: attr = 'file_diff' app = Application([]) # noqa d = Diff(show_as_window=True) func = getattr(d, attr) QTimer.singleShot(0, lambda : func(left, right)) d.show() app.exec() return 0 if __name__ == '__main__': main()
20,687
Python
.py
457
36.479212
141
0.627239
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,718
highlight.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/diff/highlight.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' import os from qt.core import QPlainTextDocumentLayout, QTextCursor, QTextDocument from calibre.gui2.tweak_book import tprefs from calibre.gui2.tweak_book.editor.syntax.utils import NULL_FMT, format_for_pygments_token from calibre.gui2.tweak_book.editor.text import SyntaxHighlighter from calibre.gui2.tweak_book.editor.text import get_highlighter as calibre_highlighter from calibre.gui2.tweak_book.editor.themes import get_theme, highlight_to_char_format from polyglot.builtins import iteritems class QtHighlighter(QTextDocument): def __init__(self, parent, text, hlclass): QTextDocument.__init__(self, parent) self.l = QPlainTextDocumentLayout(self) self.setDocumentLayout(self.l) self.highlighter = hlclass() self.highlighter.apply_theme(get_theme(tprefs['editor_theme'])) self.highlighter.set_document(self) self.setPlainText(text) def copy_lines(self, lo, hi, cursor): ''' Copy specified lines from the syntax highlighted buffer into the destination cursor, preserving all formatting created by the syntax highlighter. ''' self.highlighter.join() num = hi - lo if num > 0: block = self.findBlockByNumber(lo) while num > 0: num -= 1 cursor.insertText(block.text()) dest_block = cursor.block() c = QTextCursor(dest_block) try: afs = block.layout().formats() except AttributeError: afs = () for af in afs: start = dest_block.position() + af.start c.setPosition(start), c.setPosition(start + af.length, QTextCursor.MoveMode.KeepAnchor) c.setCharFormat(af.format) cursor.insertBlock() cursor.setCharFormat(NULL_FMT) block = block.next() class NullHighlighter: def __init__(self, text): self.lines = text.splitlines() def copy_lines(self, lo, hi, cursor): for i in range(lo, hi): cursor.insertText(self.lines[i]) cursor.insertBlock() def pygments_lexer(filename): try: from pygments.lexers import get_lexer_for_filename from pygments.util import ClassNotFound except ImportError: return None def glff(n): return get_lexer_for_filename(n, stripnl=False) try: return glff(filename) except ClassNotFound: if filename.lower().endswith('.recipe'): return glff('a.py') return None class PygmentsHighlighter: def __init__(self, text, lexer): theme, cache = get_theme(tprefs['editor_theme']), {} theme = {k:highlight_to_char_format(v) for k, v in iteritems(theme)} theme[None] = NULL_FMT def fmt(token): return format_for_pygments_token(theme, cache, token) from pygments import lex lines = self.lines = [[]] current_line = lines[0] for token, val in lex(text, lexer): for v in val.splitlines(True): current_line.append((fmt(token), v)) if v[-1] in '\n\r': lines.append([]) current_line = lines[-1] continue def copy_lines(self, lo, hi, cursor): for i in range(lo, hi): for fmt, text in self.lines[i]: cursor.insertText(text, fmt) cursor.setCharFormat(NULL_FMT) def get_highlighter(parent, text, syntax): hlclass = calibre_highlighter(syntax) if hlclass is SyntaxHighlighter: filename = os.path.basename(parent.headers[-1][1]) lexer = pygments_lexer(filename) if lexer is None: return NullHighlighter(text) return PygmentsHighlighter(text, lexer) return QtHighlighter(parent, text, hlclass)
4,037
Python
.py
96
32.229167
107
0.622256
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,719
help.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/help.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' import json from functools import partial from lxml import html from calibre import browser from calibre.ebooks.oeb.polish.container import OEB_DOCS from calibre.ebooks.oeb.polish.utils import guess_type from calibre.utils.resources import get_path as P class URLMap: def __init__(self): self.cache = {} def __getitem__(self, key): try: return self.cache[key] except KeyError: try: self.cache[key] = ans = json.loads(P('editor-help/%s.json' % key, data=True)) except OSError: raise KeyError('The mapping %s is not available' % key) return ans _url_map = URLMap() def help_url(item, item_type, doc_name, extra_data=None): url = None url_maps = () item = item.lower() if item_type == 'css_property': url_maps = ('css',) else: mt = guess_type(doc_name) if mt in OEB_DOCS: url_maps = ('html', 'svg', 'mathml') elif mt == guess_type('a.svg'): url_maps = ('svg',) elif mt == guess_type('a.opf'): version = '3' if getattr(extra_data, 'startswith', lambda x: False)('3') else '2' url_maps = (('opf' + version),) elif mt == guess_type('a.svg'): url_maps = ('svg',) elif mt == guess_type('a.ncx'): url_maps = ('opf2',) for umap in url_maps: umap = _url_map[umap] if item in umap: url = umap[item] break item = item.partition(':')[-1] if item and item in umap: url = umap[item] break return url def get_mdn_tag_index(category): url = 'https://developer.mozilla.org/docs/Web/%s/Element' % category if category == 'CSS': url = url.replace('Element', 'Reference') br = browser() raw = br.open(url).read() root = html.fromstring(raw) ans = {} if category == 'CSS': xpath = '//div[@class="index"]/descendant::a[contains(@href, "/Web/CSS/")]/@href' else: xpath = '//a[contains(@href, "/%s/Element/")]/@href' % category for href in root.xpath(xpath): href = href.replace('/en-US/', '/') ans[href.rpartition('/')[-1].lower()] = 'https://developer.mozilla.org' + href return ans def get_opf2_tag_index(): base = 'http://www.idpf.org/epub/20/spec/OPF_2.0.1_draft.htm#' ans = {} for i, tag in enumerate(('package', 'metadata', 'manifest', 'spine', 'tours', 'guide')): ans[tag] = base + 'Section2.%d' % (i + 1) for i, tag in enumerate(( 'title', 'creator', 'subject', 'description', 'publisher', 'contributor', 'date', 'type', 'format', 'identifier', 'source', 'language', 'relation', 'coverage', 'rights')): ans[tag] = base + 'Section2.2.%d' % (i + 1) ans['item'] = ans['manifest'] ans['itemref'] = ans['spine'] ans['reference'] = ans['guide'] for tag in ('ncx', 'docTitle', 'docAuthor', 'navMap', 'navPoint', 'navLabel', 'text', 'content', 'pageList', 'pageTarget'): ans[tag.lower()] = base + 'Section2.4.1.2' return ans def get_opf3_tag_index(): base = 'http://www.idpf.org/epub/301/spec/epub-publications.html#' ans = {} for tag in ( 'package', 'metadata', 'identifier', 'title', 'language', 'meta', 'link', 'manifest', 'item', 'spine', 'itemref', 'guide', 'bindings', 'mediaType', 'collection'): ans[tag.lower()] = base + 'sec-%s-elem' % tag for tag in ('contributor', 'creator', 'date', 'source', 'type',): ans[tag.lower()] = base + 'sec-opf-dc' + tag return ans def write_tag_help(): base = 'editor-help/%s.json' dump = partial(json.dumps, indent=2, sort_keys=True) for category in ('HTML', 'SVG', 'MathML', 'CSS'): data = get_mdn_tag_index(category) with open(P(base % category.lower()), 'wb') as f: f.write(dump(data)) with open(P(base % 'opf2'), 'wb') as f: f.write(dump(get_opf2_tag_index())) with open(P(base % 'opf3'), 'wb') as f: f.write(dump(get_opf3_tag_index())) if __name__ == '__main__': write_tag_help()
4,300
Python
.py
108
32.407407
127
0.564841
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,720
insert_resource.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/insert_resource.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' import os import sys from functools import partial from qt.core import ( QAbstractListModel, QApplication, QCheckBox, QClipboard, QDialog, QDialogButtonBox, QFormLayout, QGridLayout, QHBoxLayout, QIcon, QInputDialog, QLabel, QLineEdit, QListView, QMenu, QPainter, QPixmap, QRect, QSize, QSizePolicy, QSortFilterProxyModel, QStyledItemDelegate, Qt, QToolButton, QTreeWidget, QTreeWidgetItem, QVBoxLayout, pyqtSignal, ) from calibre import fit_image from calibre.ebooks.metadata import string_to_authors from calibre.ebooks.metadata.book.base import Metadata from calibre.gui2 import choose_files, empty_index, error_dialog, pixmap_to_data from calibre.gui2.languages import LanguagesEdit from calibre.gui2.tweak_book import current_container, tprefs from calibre.gui2.tweak_book.file_list import name_is_ok from calibre.gui2.tweak_book.widgets import Dialog from calibre.ptempfile import PersistentTemporaryFile from calibre.startup import connect_lambda from calibre.utils.icu import numeric_sort_key from calibre.utils.localization import canonicalize_lang, get_lang from calibre_extensions.progress_indicator import set_no_activate_on_click class ChooseName(Dialog): # {{{ ''' Chooses the filename for a newly imported file, with error checking ''' def __init__(self, candidate, parent=None): self.candidate = candidate self.filename = None Dialog.__init__(self, _('Choose file name'), 'choose-file-name', parent=parent) def setup_ui(self): self.l = l = QFormLayout(self) self.setLayout(l) self.err_label = QLabel('') self.name_edit = QLineEdit(self) self.name_edit.textChanged.connect(self.verify) self.name_edit.setText(self.candidate) pos = self.candidate.rfind('.') if pos > -1: self.name_edit.setSelection(0, pos) l.addRow(_('File &name:'), self.name_edit) l.addRow(self.err_label) l.addRow(self.bb) def show_error(self, msg): self.err_label.setText('<p style="color:red">' + msg) return False def verify(self): return name_is_ok(str(self.name_edit.text()), self.show_error) def accept(self): if not self.verify(): return error_dialog(self, _('No name specified'), _( 'You must specify a file name for the new file, with an extension.'), show=True) n = str(self.name_edit.text()).replace('\\', '/') name, ext = n.rpartition('.')[0::2] self.filename = name + '.' + ext.lower() super().accept() # }}} # Images {{{ class ImageDelegate(QStyledItemDelegate): MARGIN = 4 def __init__(self, parent): super().__init__(parent) self.current_basic_size = tprefs.get('image-thumbnail-preview-size', [120, 160]) self.set_dimensions() def change_size(self, increase=True): percent = 10 if increase else -10 frac = (100 + percent) / 100. self.current_basic_size[0] = min(1200, max(40, int(frac * self.current_basic_size[0]))) self.current_basic_size[1] = min(1600, max(60, int(frac * self.current_basic_size[1]))) tprefs.set('image-thumbnail-preview-size', self.current_basic_size) self.set_dimensions() def set_dimensions(self): width, height = self.current_basic_size self.cover_size = QSize(width, height) f = self.parent().font() sz = f.pixelSize() if sz < 5: sz = int(f.pointSize() * self.parent().logicalDpiY() / 72.0) self.title_height = max(25, sz + 10) self.item_size = self.cover_size + QSize(2 * self.MARGIN, (2 * self.MARGIN) + self.title_height) self.calculate_spacing() self.cover_cache = {} def calculate_spacing(self): self.spacing = max(10, min(50, int(0.1 * self.item_size.width()))) def sizeHint(self, option, index): return self.item_size def paint(self, painter, option, index): QStyledItemDelegate.paint(self, painter, option, empty_index) # draw the hover and selection highlights name = str(index.data(Qt.ItemDataRole.DisplayRole) or '') cover = self.cover_cache.get(name, None) if cover is None: cover = self.cover_cache[name] = QPixmap() try: raw = current_container().raw_data(name, decode=False) except: pass else: try: dpr = painter.device().devicePixelRatioF() except AttributeError: dpr = painter.device().devicePixelRatio() cover.loadFromData(raw) cover.setDevicePixelRatio(dpr) if not cover.isNull(): scaled, width, height = fit_image(cover.width(), cover.height(), self.cover_size.width(), self.cover_size.height()) if scaled: cover = self.cover_cache[name] = cover.scaled(int(dpr*width), int(dpr*height), transformMode=Qt.TransformationMode.SmoothTransformation) painter.save() try: rect = option.rect rect.adjust(self.MARGIN, self.MARGIN, -self.MARGIN, -self.MARGIN) trect = QRect(rect) rect.setBottom(rect.bottom() - self.title_height) if not cover.isNull(): dx = max(0, int((rect.width() - int(cover.width()/cover.devicePixelRatio()))/2.0)) dy = max(0, rect.height() - int(cover.height()/cover.devicePixelRatio())) rect.adjust(dx, dy, -dx, 0) painter.drawPixmap(rect, cover) rect = trect rect.setTop(rect.bottom() - self.title_height + 5) painter.setRenderHint(QPainter.RenderHint.TextAntialiasing, True) metrics = painter.fontMetrics() painter.drawText(rect, Qt.AlignmentFlag.AlignCenter|Qt.TextFlag.TextSingleLine, metrics.elidedText(name, Qt.TextElideMode.ElideLeft, rect.width())) finally: painter.restore() class Images(QAbstractListModel): def __init__(self, parent): QAbstractListModel.__init__(self, parent) self.icon_size = parent.iconSize() self.build() def build(self): c = current_container() self.image_names = [] self.image_cache = {} if c is not None: for name in sorted(c.mime_map, key=numeric_sort_key): if c.mime_map[name].startswith('image/'): self.image_names.append(name) def refresh(self): from calibre.gui2.tweak_book.boss import get_boss boss = get_boss() boss.commit_all_editors_to_container() self.beginResetModel() self.build() self.endResetModel() def rowCount(self, *args): return len(self.image_names) def data(self, index, role): try: name = self.image_names[index.row()] except IndexError: return None if role in (Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.ToolTipRole): return name return None class InsertImage(Dialog): image_activated = pyqtSignal(object) def __init__(self, parent=None, for_browsing=False): self.for_browsing = for_browsing Dialog.__init__(self, _('Images in book') if for_browsing else _('Choose an image'), 'browse-image-dialog' if for_browsing else 'insert-image-dialog', parent) self.chosen_image = None self.chosen_image_is_external = False def sizeHint(self): return QSize(800, 600) def setup_ui(self): self.l = l = QGridLayout(self) self.setLayout(l) self.la1 = la = QLabel(_('&Existing images in the book')) la.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) l.addWidget(la, 0, 0, 1, 2) if self.for_browsing: la.setVisible(False) self.view = v = QListView(self) v.setViewMode(QListView.ViewMode.IconMode) v.setFlow(QListView.Flow.LeftToRight) v.setSpacing(4) v.setResizeMode(QListView.ResizeMode.Adjust) v.setUniformItemSizes(True) set_no_activate_on_click(v) v.activated.connect(self.activated) v.doubleClicked.connect(self.activated) self.d = ImageDelegate(v) v.setItemDelegate(self.d) self.model = Images(self.view) self.fm = fm = QSortFilterProxyModel(self.view) self.fm.setDynamicSortFilter(self.for_browsing) fm.setSourceModel(self.model) fm.setFilterCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive) v.setModel(fm) l.addWidget(v, 1, 0, 1, 2) v.pressed.connect(self.pressed) la.setBuddy(v) self.filter = f = QLineEdit(self) f.setPlaceholderText(_('Search for image by file name')) l.addWidget(f, 2, 0) self.cb = b = QToolButton(self) b.setIcon(QIcon.ic('clear_left.png')) b.clicked.connect(f.clear) l.addWidget(b, 2, 1) f.textChanged.connect(self.filter_changed) if self.for_browsing: self.bb.clear() self.bb.addButton(QDialogButtonBox.StandardButton.Close) b = self.refresh_button = self.bb.addButton(_('&Refresh'), QDialogButtonBox.ButtonRole.ActionRole) b.clicked.connect(self.refresh) b.setIcon(QIcon.ic('view-refresh.png')) b.setToolTip(_('Refresh the displayed images')) self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False) else: b = self.import_button = self.bb.addButton(_('&Import image'), QDialogButtonBox.ButtonRole.ActionRole) b.clicked.connect(self.import_image) b.setIcon(QIcon.ic('view-image.png')) b.setToolTip(_('Import an image from elsewhere in your computer')) b = self.paste_button = self.bb.addButton(_('&Paste image'), QDialogButtonBox.ButtonRole.ActionRole) b.clicked.connect(self.paste_image) b.setIcon(QIcon.ic('edit-paste.png')) b.setToolTip(_('Paste an image from the clipboard')) self.fullpage = f = QCheckBox(_('Full page image'), self) f.setToolTip(_('Insert the image so that it takes up an entire page when viewed in a reader')) f.setChecked(tprefs['insert_full_screen_image']) self.preserve_aspect_ratio = a = QCheckBox(_('Preserve aspect ratio')) a.setToolTip(_('Preserve the aspect ratio of the inserted image when rendering it full paged')) a.setChecked(tprefs['preserve_aspect_ratio_when_inserting_image']) f.toggled.connect(self.full_page_image_toggled) a.toggled.connect(self.par_toggled) a.setVisible(f.isChecked()) h = QHBoxLayout() l.addLayout(h, 3, 0, 1, -1) h.addWidget(f), h.addStretch(10), h.addWidget(a) b = self.bb.addButton(_('&Zoom in'), QDialogButtonBox.ButtonRole.ActionRole) b.clicked.connect(self.zoom_in) b.setIcon(QIcon.ic('plus.png')) b = self.bb.addButton(_('Zoom &out'), QDialogButtonBox.ButtonRole.ActionRole) b.clicked.connect(self.zoom_out) b.setIcon(QIcon.ic('minus.png')) l.addWidget(self.bb, 4, 0, 1, 2) def full_page_image_toggled(self): tprefs.set('insert_full_screen_image', self.fullpage.isChecked()) self.preserve_aspect_ratio.setVisible(self.fullpage.isChecked()) def par_toggled(self): tprefs.set('preserve_aspect_ratio_when_inserting_image', self.preserve_aspect_ratio.isChecked()) def refresh(self): self.d.cover_cache.clear() self.model.refresh() def import_image(self): path = choose_files(self, 'tweak-book-choose-image-for-import', _('Choose image'), filters=[(_('Images'), ('jpg', 'jpeg', 'png', 'gif', 'svg'))], all_files=True, select_only_single_file=True) if path: path = path[0] basename = os.path.basename(path) n, e = basename.rpartition('.')[0::2] basename = n + '.' + e.lower() d = ChooseName(basename, self) if d.exec() == QDialog.DialogCode.Accepted and d.filename: self.accept() self.chosen_image_is_external = (d.filename, path) def zoom_in(self): self.d.change_size(increase=True) self.model.beginResetModel(), self.model.endResetModel() def zoom_out(self): self.d.change_size(increase=False) self.model.beginResetModel(), self.model.endResetModel() def paste_image(self): c = QApplication.instance().clipboard() img = c.image() if img.isNull(): img = c.image(QClipboard.Mode.Selection) if img.isNull(): return error_dialog(self, _('No image'), _( 'There is no image on the clipboard'), show=True) d = ChooseName('image.jpg', self) if d.exec() == QDialog.DialogCode.Accepted and d.filename: fmt = d.filename.rpartition('.')[-1].lower() if fmt not in {'jpg', 'jpeg', 'png'}: return error_dialog(self, _('Invalid file extension'), _( 'The file name you choose must have a .jpg or .png extension'), show=True) t = PersistentTemporaryFile(prefix='editor-paste-image-', suffix='.' + fmt) t.write(pixmap_to_data(img, fmt)) t.close() self.chosen_image_is_external = (d.filename, t.name) self.accept() def pressed(self, index): if QApplication.mouseButtons() & Qt.MouseButton.LeftButton: self.activated(index) def activated(self, index): if self.for_browsing: return self.image_activated.emit(str(index.data() or '')) self.chosen_image_is_external = False self.accept() def accept(self): self.chosen_image = str(self.view.currentIndex().data() or '') super().accept() def filter_changed(self, *args): f = str(self.filter.text()) self.fm.setFilterFixedString(f) # }}} def get_resource_data(rtype, parent): if rtype == 'image': d = InsertImage(parent) if d.exec() == QDialog.DialogCode.Accepted: return d.chosen_image, d.chosen_image_is_external, d.fullpage.isChecked(), d.preserve_aspect_ratio.isChecked() def create_folder_tree(container): root = {} all_folders = {tuple(x.split('/')[:-1]) for x in container.name_path_map} all_folders.discard(()) for folder_path in all_folders: current = root for x in folder_path: current[x] = current = current.get(x, {}) return root class ChooseFolder(Dialog): # {{{ def __init__(self, msg=None, parent=None): self.msg = msg Dialog.__init__(self, _('Choose folder'), 'choose-folder', parent=parent) def setup_ui(self): self.l = l = QVBoxLayout(self) self.setLayout(l) self.msg = m = QLabel(self.msg or _( 'Choose the folder into which the files will be placed')) l.addWidget(m) m.setWordWrap(True) self.folders = f = QTreeWidget(self) f.setHeaderHidden(True) f.itemDoubleClicked.connect(self.accept) l.addWidget(f) f.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) f.customContextMenuRequested.connect(self.show_context_menu) self.root = QTreeWidgetItem(f, ('/',)) def process(node, parent): parent.setIcon(0, QIcon.ic('mimetypes/dir.png')) for child in sorted(node, key=numeric_sort_key): c = QTreeWidgetItem(parent, (child,)) process(node[child], c) process(create_folder_tree(current_container()), self.root) self.root.setSelected(True) f.expandAll() l.addWidget(self.bb) def show_context_menu(self, point): item = self.folders.itemAt(point) if item is None: return m = QMenu(self) m.addAction(QIcon.ic('mimetypes/dir.png'), _('Create new folder'), partial(self.create_folder, item)) m.popup(self.folders.mapToGlobal(point)) def create_folder(self, item): text, ok = QInputDialog.getText(self, _('Folder name'), _('Enter a name for the new folder')) if ok and str(text): c = QTreeWidgetItem(item, (str(text),)) c.setIcon(0, QIcon.ic('mimetypes/dir.png')) for item in self.folders.selectedItems(): item.setSelected(False) c.setSelected(True) self.folders.setCurrentItem(c) def folder_path(self, item): ans = [] while item is not self.root: ans.append(str(item.text(0))) item = item.parent() return tuple(reversed(ans)) @property def chosen_folder(self): try: return '/'.join(self.folder_path(self.folders.selectedItems()[0])) except IndexError: return '' # }}} class NewBook(Dialog): # {{{ def __init__(self, parent=None): self.fmt = 'epub' Dialog.__init__(self, _('Create new book'), 'create-new-book', parent=parent) def setup_ui(self): self.l = l = QFormLayout(self) self.setLayout(l) self.title = t = QLineEdit(self) l.addRow(_('&Title:'), t) t.setFocus(Qt.FocusReason.OtherFocusReason) self.authors = a = QLineEdit(self) l.addRow(_('&Authors:'), a) a.setText(tprefs.get('previous_new_book_authors', '')) self.languages = la = LanguagesEdit(self) l.addRow(_('&Language:'), la) la.lang_codes = (tprefs.get('previous_new_book_lang', canonicalize_lang(get_lang())),) bb = self.bb l.addRow(bb) bb.clear() bb.addButton(QDialogButtonBox.StandardButton.Cancel) b = bb.addButton('&EPUB', QDialogButtonBox.ButtonRole.AcceptRole) connect_lambda(b.clicked, self, lambda self: self.set_fmt('epub')) b = bb.addButton('&AZW3', QDialogButtonBox.ButtonRole.AcceptRole) connect_lambda(b.clicked, self, lambda self: self.set_fmt('azw3')) def set_fmt(self, fmt): self.fmt = fmt def accept(self): with tprefs: tprefs.set('previous_new_book_authors', str(self.authors.text())) tprefs.set('previous_new_book_lang', (self.languages.lang_codes or [get_lang()])[0]) self.languages.update_recently_used() super().accept() @property def mi(self): mi = Metadata(str(self.title.text()).strip() or _('Unknown')) mi.authors = string_to_authors(str(self.authors.text()).strip()) or [_('Unknown')] mi.languages = self.languages.lang_codes or [get_lang()] return mi # }}} if __name__ == '__main__': app = QApplication([]) # noqa from calibre.gui2.tweak_book import set_current_container from calibre.gui2.tweak_book.boss import get_container set_current_container(get_container(sys.argv[-1])) d = InsertImage(for_browsing=True) d.exec()
19,407
Python
.py
439
34.965831
160
0.619638
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,721
widget.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/widget.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' import math import unicodedata from functools import partial from qt.core import ( QAction, QApplication, QColor, QIcon, QImage, QInputDialog, QMainWindow, QMenu, QPainter, QPixmap, QSize, Qt, QTextCursor, QToolButton, pyqtSignal, qDrawShadeRect, ) from calibre import prints from calibre.constants import DEBUG from calibre.ebooks.chardet import replace_encoding_declarations from calibre.gui2 import error_dialog, open_url from calibre.gui2.tweak_book import actions, current_container, dictionaries, editor_name, editor_toolbar_actions, editors, tprefs, update_mark_text_action from calibre.gui2.tweak_book.editor import CLASS_ATTRIBUTE_PROPERTY, CSS_PROPERTY, LINK_PROPERTY, SPELL_PROPERTY, TAG_NAME_PROPERTY from calibre.gui2.tweak_book.editor.help import help_url from calibre.gui2.tweak_book.editor.text import TextEdit from calibre.utils.icu import primary_sort_key, utf16_length from polyglot.builtins import itervalues, string_or_bytes def create_icon(text, palette=None, sz=None, divider=2, fill='white'): if isinstance(fill, string_or_bytes): fill = QColor(fill) sz = sz or int(math.ceil(tprefs['toolbar_icon_size'] * QApplication.instance().devicePixelRatio())) if palette is None: palette = QApplication.palette() img = QImage(sz, sz, QImage.Format.Format_ARGB32) img.fill(Qt.GlobalColor.transparent) p = QPainter(img) p.setRenderHints(QPainter.RenderHint.TextAntialiasing | QPainter.RenderHint.Antialiasing) if fill is not None: qDrawShadeRect(p, img.rect(), palette, fill=fill, lineWidth=1, midLineWidth=1) f = p.font() f.setFamily('Liberation Sans'), f.setPixelSize(int(sz // divider)), f.setBold(True) p.setFont(f), p.setPen(QColor('#2271d5')) p.drawText(img.rect().adjusted(2, 2, -2, -2), Qt.AlignmentFlag.AlignCenter, text) p.end() return QIcon(QPixmap.fromImage(img)) def register_text_editor_actions(_reg, palette): def reg(*args, **kw): ac = _reg(*args) for s in kw.get('syntaxes', ('format',)): editor_toolbar_actions[s][args[3]] = ac return ac ac = reg('format-text-bold.png', _('&Bold'), ('format_text', 'bold'), 'format-text-bold', 'Ctrl+B', _('Make the selected text bold')) ac.setToolTip(_('<h3>Bold</h3>Make the selected text bold')) ac = reg('format-text-italic.png', _('&Italic'), ('format_text', 'italic'), 'format-text-italic', 'Ctrl+I', _('Make the selected text italic')) ac.setToolTip(_('<h3>Italic</h3>Make the selected text italic')) ac = reg('format-text-underline.png', _('&Underline'), ('format_text', 'underline'), 'format-text-underline', (), _('Underline the selected text')) ac.setToolTip(_('<h3>Underline</h3>Underline the selected text')) ac = reg('format-text-strikethrough.png', _('&Strikethrough'), ('format_text', 'strikethrough'), 'format-text-strikethrough', (), _('Draw a line through the selected text')) ac.setToolTip(_('<h3>Strikethrough</h3>Draw a line through the selected text')) ac = reg('format-text-superscript.png', _('&Superscript'), ('format_text', 'superscript'), 'format-text-superscript', (), _('Make the selected text a superscript')) ac.setToolTip(_('<h3>Superscript</h3>Set the selected text slightly smaller and above the normal line')) ac = reg('format-text-subscript.png', _('&Subscript'), ('format_text', 'subscript'), 'format-text-subscript', (), _('Make the selected text a subscript')) ac.setToolTip(_('<h3>Subscript</h3>Set the selected text slightly smaller and below the normal line')) ac = reg('format-text-color.png', _('&Color'), ('format_text', 'color'), 'format-text-color', (), _('Change text color')) ac.setToolTip(_('<h3>Color</h3>Change the color of the selected text')) ac = reg('format-fill-color.png', _('&Background color'), ('format_text', 'background-color'), 'format-text-background-color', (), _('Change background color of text')) ac.setToolTip(_('<h3>Background color</h3>Change the background color of the selected text')) ac = reg('format-justify-left.png', _('Align &left'), ('format_text', 'justify_left'), 'format-text-justify-left', (), _('Align left')) ac.setToolTip(_('<h3>Align left</h3>Align the paragraph to the left')) ac = reg('format-justify-center.png', _('&Center'), ('format_text', 'justify_center'), 'format-text-justify-center', (), _('Center')) ac.setToolTip(_('<h3>Center</h3>Center the paragraph')) ac = reg('format-justify-right.png', _('Align &right'), ('format_text', 'justify_right'), 'format-text-justify-right', (), _('Align right')) ac.setToolTip(_('<h3>Align right</h3>Align the paragraph to the right')) ac = reg('format-justify-fill.png', _('&Justify'), ('format_text', 'justify_justify'), 'format-text-justify-fill', (), _('Justify')) ac.setToolTip(_('<h3>Justify</h3>Align the paragraph to both the left and right margins')) ac = reg('sort.png', _('&Sort style rules'), ('sort_css',), 'editor-sort-css', (), _('Sort the style rules'), syntaxes=('css',)) ac = reg('view-image.png', _('&Insert image'), ('insert_resource', 'image'), 'insert-image', (), _('Insert an image into the text'), syntaxes=('html', 'css')) ac.setToolTip(_('<h3>Insert image</h3>Insert an image into the text')) ac = reg('insert-link.png', _('Insert &hyperlink'), ('insert_hyperlink',), 'insert-hyperlink', (), _('Insert hyperlink'), syntaxes=('html',)) ac.setToolTip(_('<h3>Insert hyperlink</h3>Insert a hyperlink into the text')) ac = reg(create_icon('/*', divider=1, fill=None), _('Smart &comment'), ('smart_comment',), 'editor-smart-comment', ('Ctrl+`',), _( 'Smart comment (toggle block comments)'), syntaxes=()) ac.setToolTip(_('<h3>Smart comment</h3>Comment or uncomment text<br><br>' 'If the cursor is inside an existing block comment, uncomment it, otherwise comment out the selected text.')) for i, name in enumerate(('h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p')): text = ('&' + name) if name == 'p' else (name[0] + '&' + name[1]) desc = _('Convert the paragraph to &lt;%s&gt;') % name ac = reg(create_icon(name), text, ('rename_block_tag', name), 'rename-block-tag-' + name, 'Ctrl+%d' % (i + 1), desc, syntaxes=()) ac.setToolTip(desc) for transform, text in [ ('upper', _('&Upper case')), ('lower', _('&Lower case')), ('swap', _('&Swap case')), ('title', _('&Title case')), ('capitalize', _('&Capitalize'))]: desc = _('Change the case of the selected text: %s') % text ac = reg(None, text, ('change_case', transform), 'transform-case-' + transform, (), desc, syntaxes=()) ac.setToolTip(desc) ac = reg('code.png', _('Insert &tag'), ('insert_tag',), 'insert-tag', ('Ctrl+<'), _('Insert tag'), syntaxes=('html', 'xml')) ac.setToolTip(_('<h3>Insert tag</h3>Insert a tag, if some text is selected the tag will be inserted around the selected text')) ac = reg('trash.png', _('Remove &tag'), ('remove_tag',), 'remove-tag', ('Ctrl+>'), _('Remove tag'), syntaxes=('html', 'xml')) ac.setToolTip(_('<h3>Remove tag</h3>Remove the currently highlighted tag')) ac = reg('split.png', _('&Split tag'), ('split_tag',), 'split-tag', ('Ctrl+Alt+>'), _('Split current tag'), syntaxes=('html', 'xml')) ac.setToolTip(_('<h3>Split tag</h3>Split the current tag at the cursor position')) editor_toolbar_actions['html']['fix-html-current'] = actions['fix-html-current'] for s in ('xml', 'html', 'css'): editor_toolbar_actions[s]['pretty-current'] = actions['pretty-current'] editor_toolbar_actions['html']['change-paragraph'] = actions['change-paragraph'] = QAction( QIcon.ic('format-text-heading.png'), _('Change paragraph to heading'), ac.parent()) class Editor(QMainWindow): has_line_numbers = True modification_state_changed = pyqtSignal(object) undo_redo_state_changed = pyqtSignal(object, object) copy_available_state_changed = pyqtSignal(object) data_changed = pyqtSignal(object) cursor_position_changed = pyqtSignal() word_ignored = pyqtSignal(object, object) link_clicked = pyqtSignal(object) class_clicked = pyqtSignal(object) rename_class = pyqtSignal(object) smart_highlighting_updated = pyqtSignal() def __init__(self, syntax, parent=None): QMainWindow.__init__(self, parent) if parent is None: self.setWindowFlags(Qt.WindowType.Widget) self.is_synced_to_container = False self.syntax = syntax self.editor = TextEdit(self) self.editor.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.editor.customContextMenuRequested.connect(self.show_context_menu) self.setCentralWidget(self.editor) self.create_toolbars() self.undo_available = False self.redo_available = False self.copy_available = self.cut_available = False self.editor.modificationChanged.connect(self._modification_state_changed) self.editor.undoAvailable.connect(self._undo_available) self.editor.redoAvailable.connect(self._redo_available) self.editor.textChanged.connect(self._data_changed) self.editor.copyAvailable.connect(self._copy_available) self.editor.cursorPositionChanged.connect(self._cursor_position_changed) self.editor.link_clicked.connect(self.link_clicked) self.editor.class_clicked.connect(self.class_clicked) self.editor.smart_highlighting_updated.connect(self.smart_highlighting_updated) @property def current_line(self): return self.editor.textCursor().blockNumber() @current_line.setter def current_line(self, val): self.editor.go_to_line(val) @property def current_editing_state(self): c = self.editor.textCursor() return {'cursor':(c.anchor(), c.position())} @current_editing_state.setter def current_editing_state(self, val): anchor, position = val.get('cursor', (None, None)) if anchor is not None and position is not None: c = self.editor.textCursor() c.setPosition(anchor), c.setPosition(position, QTextCursor.MoveMode.KeepAnchor) self.editor.setTextCursor(c) def current_tag(self, for_position_sync=True): return self.editor.current_tag(for_position_sync=for_position_sync) @property def highlighter(self): return self.editor.highlighter @property def number_of_lines(self): return self.editor.blockCount() @property def data(self): ans = self.get_raw_data() ans, changed = replace_encoding_declarations(ans, enc='utf-8', limit=4*1024) if changed: self.data = ans return ans.encode('utf-8') @data.setter def data(self, val): self.editor.load_text(val, syntax=self.syntax, doc_name=editor_name(self)) def init_from_template(self, template): self.editor.load_text(template, syntax=self.syntax, process_template=True, doc_name=editor_name(self)) def change_document_name(self, newname): self.editor.change_document_name(newname) self.editor.completion_doc_name = newname def get_raw_data(self): # The EPUB spec requires NFC normalization, see section 1.3.6 of # http://www.idpf.org/epub/20/spec/OPS_2.0.1_draft.htm return unicodedata.normalize('NFC', str(self.editor.toPlainText()).rstrip('\0')) def replace_data(self, raw, only_if_different=True): if isinstance(raw, bytes): raw = raw.decode('utf-8') current = self.get_raw_data() if only_if_different else False if current != raw: self.editor.replace_text(raw) def apply_settings(self, prefs=None, dictionaries_changed=False): self.editor.apply_settings(prefs=None, dictionaries_changed=dictionaries_changed) def set_focus(self): self.editor.setFocus(Qt.FocusReason.OtherFocusReason) def action_triggered(self, action): action, args = action[0], action[1:] func = getattr(self.editor, action) func(*args) def insert_image(self, href, fullpage=False, preserve_aspect_ratio=False, width=-1, height=-1): self.editor.insert_image(href, fullpage=fullpage, preserve_aspect_ratio=preserve_aspect_ratio, width=width, height=height) def insert_hyperlink(self, href, text, template=None): self.editor.insert_hyperlink(href, text, template=template) def _build_insert_tag_button_menu(self): m = self.insert_tag_menu m.clear() names = tprefs['insert_tag_mru'] for name in names: m.addAction(name, partial(self.insert_tag, name)) m.addSeparator() m.addAction(_('Add a tag to this menu'), self.add_insert_tag) if names: m = m.addMenu(_('Remove from this menu')) for name in names: m.addAction(name, partial(self.remove_insert_tag, name)) def insert_tag(self, name): self.editor.insert_tag(name) mru = tprefs['insert_tag_mru'] try: mru.remove(name) except ValueError: pass mru.insert(0, name) tprefs['insert_tag_mru'] = mru self._build_insert_tag_button_menu() def add_insert_tag(self): name, ok = QInputDialog.getText(self, _('Name of tag to add'), _( 'Enter the name of the tag')) if ok: mru = tprefs['insert_tag_mru'] mru.insert(0, name) tprefs['insert_tag_mru'] = mru self._build_insert_tag_button_menu() def remove_insert_tag(self, name): mru = tprefs['insert_tag_mru'] try: mru.remove(name) except ValueError: pass tprefs['insert_tag_mru'] = mru self._build_insert_tag_button_menu() def set_request_completion(self, callback=None, doc_name=None): self.editor.request_completion = callback self.editor.completion_doc_name = doc_name def handle_completion_result(self, result): return self.editor.handle_completion_result(result) def undo(self): self.editor.undo() def redo(self): self.editor.redo() @property def selected_text(self): return self.editor.selected_text def get_smart_selection(self, update=True): return self.editor.smarts.get_smart_selection(self.editor, update=update) # Search and replace {{{ def mark_selected_text(self): self.editor.mark_selected_text() def find(self, *args, **kwargs): return self.editor.find(*args, **kwargs) def find_text(self, *args, **kwargs): return self.editor.find_text(*args, **kwargs) def find_spell_word(self, *args, **kwargs): return self.editor.find_spell_word(*args, **kwargs) def replace(self, *args, **kwargs): return self.editor.replace(*args, **kwargs) def all_in_marked(self, *args, **kwargs): return self.editor.all_in_marked(*args, **kwargs) def go_to_anchor(self, *args, **kwargs): return self.editor.go_to_anchor(*args, **kwargs) # }}} @property def has_marked_text(self): return self.editor.current_search_mark is not None @property def is_modified(self): return self.editor.is_modified @is_modified.setter def is_modified(self, val): self.editor.is_modified = val def create_toolbars(self): self.action_bar = b = self.addToolBar(_('Edit actions tool bar')) b.setObjectName('action_bar') # Needed for saveState self.tools_bar = b = self.addToolBar(_('Editor tools')) b.setObjectName('tools_bar') self.bars = [self.action_bar, self.tools_bar] if self.syntax == 'html': self.format_bar = b = self.addToolBar(_('Format text')) b.setObjectName('html_format_bar') self.bars.append(self.format_bar) self.insert_tag_menu = QMenu(self) self.populate_toolbars() for x in self.bars: x.setFloatable(False) x.topLevelChanged.connect(self.toolbar_floated) x.setIconSize(QSize(tprefs['toolbar_icon_size'], tprefs['toolbar_icon_size'])) def toolbar_floated(self, floating): if not floating: self.save_state() for ed in itervalues(editors): if ed is not self: ed.restore_state() def save_state(self): for bar in self.bars: if bar.isFloating(): return tprefs['%s-editor-state' % self.syntax] = bytearray(self.saveState()) def restore_state(self): state = tprefs.get('%s-editor-state' % self.syntax, None) if state is not None: self.restoreState(state) for bar in self.bars: bar.setVisible(len(bar.actions()) > 0) def populate_toolbars(self): self.action_bar.clear(), self.tools_bar.clear() def add_action(name, bar): if name is None: bar.addSeparator() return try: ac = actions[name] except KeyError: if DEBUG: prints('Unknown editor tool: %r' % name) return bar.addAction(ac) if name == 'insert-tag': w = bar.widgetForAction(ac) if hasattr(w, 'setPopupMode'): # For some unknown reason this button is occasionally a # QPushButton instead of a QToolButton w.setPopupMode(QToolButton.ToolButtonPopupMode.MenuButtonPopup) w.setMenu(self.insert_tag_menu) w.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) w.customContextMenuRequested.connect(w.showMenu) self._build_insert_tag_button_menu() elif name == 'change-paragraph': m = ac.m = QMenu() ac.setMenu(m) ch = bar.widgetForAction(ac) if hasattr(ch, 'setPopupMode'): # For some unknown reason this button is occasionally a # QPushButton instead of a QToolButton ch.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup) for name in tuple('h%d' % d for d in range(1, 7)) + ('p',): m.addAction(actions['rename-block-tag-%s' % name]) for name in tprefs.get('editor_common_toolbar', ()): add_action(name, self.action_bar) for name in tprefs.get('editor_%s_toolbar' % self.syntax, ()): add_action(name, self.tools_bar) if self.syntax == 'html': self.format_bar.clear() for name in tprefs['editor_format_toolbar']: add_action(name, self.format_bar) self.restore_state() def break_cycles(self): for x in ('modification_state_changed', 'word_ignored', 'link_clicked', 'class_clicked', 'smart_highlighting_updated'): try: getattr(self, x).disconnect() except TypeError: pass # in case this signal was never connected self.undo_redo_state_changed.disconnect() self.copy_available_state_changed.disconnect() self.cursor_position_changed.disconnect() self.data_changed.disconnect() self.editor.undoAvailable.disconnect() self.editor.redoAvailable.disconnect() self.editor.modificationChanged.disconnect() self.editor.textChanged.disconnect() self.editor.copyAvailable.disconnect() self.editor.cursorPositionChanged.disconnect() self.editor.link_clicked.disconnect() self.editor.class_clicked.disconnect() self.editor.smart_highlighting_updated.disconnect() self.editor.setPlainText('') self.editor.smarts = None self.editor.request_completion = None def _modification_state_changed(self): self.is_synced_to_container = self.is_modified self.modification_state_changed.emit(self.is_modified) def _data_changed(self): self.is_synced_to_container = False self.data_changed.emit(self) def _undo_available(self, available): self.undo_available = available self.undo_redo_state_changed.emit(self.undo_available, self.redo_available) def _redo_available(self, available): self.redo_available = available self.undo_redo_state_changed.emit(self.undo_available, self.redo_available) def _copy_available(self, available): self.copy_available = self.cut_available = available self.copy_available_state_changed.emit(available) def _cursor_position_changed(self, *args): self.cursor_position_changed.emit() @property def cursor_position(self): c = self.editor.textCursor() char = '' col = c.positionInBlock() if not c.atStart(): c.clearSelection() c.movePosition(QTextCursor.MoveOperation.PreviousCharacter, QTextCursor.MoveMode.KeepAnchor) char = str(c.selectedText()).rstrip('\0') return (c.blockNumber() + 1, col, char) def cut(self): self.editor.cut() def copy(self): self.editor.copy() def go_to_line(self, line, col=None): self.editor.go_to_line(line, col=col) def paste(self): if not self.editor.canPaste(): return error_dialog(self, _('No text'), _( 'There is no suitable text in the clipboard to paste.'), show=True) self.editor.paste() def contextMenuEvent(self, ev): ev.ignore() def fix_html(self): if self.syntax == 'html': from calibre.ebooks.oeb.polish.pretty import fix_html self.editor.replace_text(fix_html(current_container(), str(self.editor.toPlainText())).decode('utf-8')) return True return False def pretty_print(self, name): from calibre.ebooks.oeb.polish.pretty import pretty_css, pretty_html, pretty_xml if self.syntax in {'css', 'html', 'xml'}: func = {'css':pretty_css, 'xml':pretty_xml}.get(self.syntax, pretty_html) original_text = str(self.editor.toPlainText()) prettied_text = func(current_container(), name, original_text).decode('utf-8') if original_text != prettied_text: self.editor.replace_text(prettied_text) return True return False def show_context_menu(self, pos): m = QMenu(self) a = m.addAction c = self.editor.cursorForPosition(pos) origc = QTextCursor(c) current_cursor = self.editor.textCursor() r = origr = self.editor.syntax_range_for_cursor(c) if (r is None or not r.format.property(SPELL_PROPERTY)) and c.positionInBlock() > 0 and not current_cursor.hasSelection(): c.setPosition(c.position() - 1) r = self.editor.syntax_range_for_cursor(c) if r is not None and r.format.property(SPELL_PROPERTY): word = self.editor.text_for_range(c.block(), r) locale = self.editor.spellcheck_locale_for_cursor(c) orig_pos = c.position() c.setPosition(orig_pos - utf16_length(word)) found = False self.editor.setTextCursor(c) if locale and self.editor.find_spell_word([word], locale.langcode, center_on_cursor=False): found = True fc = self.editor.textCursor() if fc.position() < c.position(): self.editor.find_spell_word([word], locale.langcode, center_on_cursor=False) spell_cursor = self.editor.textCursor() if current_cursor.hasSelection(): # Restore the current cursor so that any selection is preserved # for the change case actions self.editor.setTextCursor(current_cursor) if found: suggestions = dictionaries.suggestions(word, locale)[:7] if suggestions: for suggestion in suggestions: ac = m.addAction(suggestion, partial(self.editor.simple_replace, suggestion, cursor=spell_cursor)) f = ac.font() f.setBold(True), ac.setFont(f) m.addSeparator() m.addAction(actions['spell-next']) m.addAction(_('Ignore this word'), partial(self._nuke_word, None, word, locale)) dics = dictionaries.active_user_dictionaries if len(dics) > 0: if len(dics) == 1: m.addAction(_('Add this word to the dictionary: {0}').format(dics[0].name), partial( self._nuke_word, dics[0].name, word, locale)) else: ac = m.addAction(_('Add this word to the dictionary')) dmenu = QMenu(m) ac.setMenu(dmenu) for dic in sorted(dics, key=lambda x: primary_sort_key(x.name)): dmenu.addAction(dic.name, partial(self._nuke_word, dic.name, word, locale)) m.addSeparator() if origr is not None and origr.format.property(LINK_PROPERTY): href = self.editor.text_for_range(origc.block(), origr) m.addAction(_('Open %s') % href, partial(self.link_clicked.emit, href)) if origr is not None and origr.format.property(CLASS_ATTRIBUTE_PROPERTY): cls = self.editor.class_for_position(pos) if cls: class_name = cls['class'] m.addAction(_('Rename the class {}').format(class_name), partial(self.rename_class.emit, class_name)) if origr is not None and (origr.format.property(TAG_NAME_PROPERTY) or origr.format.property(CSS_PROPERTY)): word = self.editor.text_for_range(origc.block(), origr) item_type = 'tag_name' if origr.format.property(TAG_NAME_PROPERTY) else 'css_property' url = help_url(word, item_type, self.editor.highlighter.doc_name, extra_data=current_container().opf_version) if url is not None: m.addAction(_('Show help for: %s') % word, partial(open_url, url)) for x in ('undo', 'redo'): ac = actions['editor-%s' % x] if ac.isEnabled(): a(ac) m.addSeparator() for x in ('cut', 'copy', 'paste'): ac = actions['editor-' + x] if ac.isEnabled(): a(ac) m.addSeparator() m.addAction(_('&Select all'), self.editor.select_all) if self.selected_text or self.has_marked_text: update_mark_text_action(self) m.addAction(actions['mark-selected-text']) if self.syntax != 'css' and actions['editor-cut'].isEnabled(): cm = QMenu(_('C&hange case'), m) for ac in 'upper lower swap title capitalize'.split(): cm.addAction(actions['transform-case-' + ac]) m.addMenu(cm) if self.syntax == 'html': m.addAction(actions['multisplit']) m.exec(self.editor.viewport().mapToGlobal(pos)) def goto_sourceline(self, *args, **kwargs): return self.editor.goto_sourceline(*args, **kwargs) def goto_css_rule(self, *args, **kwargs): return self.editor.goto_css_rule(*args, **kwargs) def get_tag_contents(self, *args, **kwargs): return self.editor.get_tag_contents(*args, **kwargs) def _nuke_word(self, dic, word, locale): if dic is None: dictionaries.ignore_word(word, locale) else: dictionaries.add_to_user_dictionary(dic, word, locale) self.word_ignored.emit(word, locale) def launch_editor(path_to_edit, path_is_raw=False, syntax='html', callback=None): from calibre.gui2 import Application from calibre.gui2.tweak_book import dictionaries from calibre.gui2.tweak_book.editor.syntax.html import refresh_spell_check_status from calibre.gui2.tweak_book.main import option_parser from calibre.gui2.tweak_book.ui import Main dictionaries.initialize() refresh_spell_check_status() opts = option_parser().parse_args([]) app = Application([]) # Create the actions that are placed into the editors toolbars main = Main(opts) # noqa if path_is_raw: raw = path_to_edit else: with open(path_to_edit, 'rb') as f: raw = f.read().decode('utf-8') ext = path_to_edit.rpartition('.')[-1].lower() if ext in ('html', 'htm', 'xhtml', 'xhtm'): syntax = 'html' elif ext in ('css',): syntax = 'css' t = Editor(syntax) t.data = raw if callback is not None: callback(t) t.show() app.exec()
29,229
Python
.py
571
41.684764
155
0.628046
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,722
comments.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/comments.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> from qt.core import QTextCursor, QTextDocument opening_map = { 'css':'/*', 'html':'<!--', 'xml':'<!--', 'javascript':'/*', } closing_map = { 'css':'*/', 'html':'-->', 'xml':'-->', 'javascript':'*/', } def apply_smart_comment(editor, opening='/*', closing='*/', line_comment=None): doc = editor.document() c = QTextCursor(editor.textCursor()) c.clearSelection() before_opening = doc.find(opening, c, QTextDocument.FindFlag.FindBackward | QTextDocument.FindFlag.FindCaseSensitively) before_closing = doc.find(closing, c, QTextDocument.FindFlag.FindBackward | QTextDocument.FindFlag.FindCaseSensitively) after_opening = doc.find(opening, c, QTextDocument.FindFlag.FindCaseSensitively) after_closing = doc.find(closing, c, QTextDocument.FindFlag.FindCaseSensitively) in_block_comment = (not before_opening.isNull() and (before_closing.isNull() or before_opening.position() >= before_closing.position())) and \ (not after_closing.isNull() and (after_opening.isNull() or after_closing.position() <= after_opening.position())) if in_block_comment: before_opening.removeSelectedText(), after_closing.removeSelectedText() return c = QTextCursor(editor.textCursor()) left, right = min(c.position(), c.anchor()), max(c.position(), c.anchor()) c.beginEditBlock() c.setPosition(right), c.insertText(closing) c.setPosition(left), c.insertText(opening) c.endEditBlock() def smart_comment(editor, syntax): apply_smart_comment(editor, opening=opening_map.get(syntax, '/*'), closing=closing_map.get(syntax, '*/'))
1,718
Python
.py
36
43.166667
146
0.697133
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,723
text.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/text.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2013, Kovid Goyal <kovid at kovidgoyal.net> import importlib import os import re import textwrap import unicodedata from contextlib import suppress import regex from qt.core import ( QColor, QColorDialog, QFont, QFontDatabase, QKeySequence, QPainter, QPalette, QPlainTextEdit, QRect, QSize, Qt, QTextCursor, QTextEdit, QTextFormat, QTimer, QToolTip, QWidget, pyqtSignal, ) from calibre import prepare_string_for_xml from calibre.ebooks.oeb.base import OEB_DOCS, OEB_STYLES, css_text from calibre.ebooks.oeb.polish.replace import get_recommended_folders from calibre.ebooks.oeb.polish.utils import guess_type from calibre.gui2.tweak_book import CONTAINER_DND_MIMETYPE, TOP, current_container, tprefs from calibre.gui2.tweak_book.completion.popup import CompletionPopup from calibre.gui2.tweak_book.editor import CLASS_ATTRIBUTE_PROPERTY, LINK_PROPERTY, SPELL_LOCALE_PROPERTY, SPELL_PROPERTY, SYNTAX_PROPERTY, store_locale from calibre.gui2.tweak_book.editor.smarts import NullSmarts from calibre.gui2.tweak_book.editor.snippets import SnippetManager from calibre.gui2.tweak_book.editor.syntax.base import SyntaxHighlighter from calibre.gui2.tweak_book.editor.themes import get_theme, theme_color, theme_format from calibre.gui2.tweak_book.widgets import PARAGRAPH_SEPARATOR, PlainTextEdit from calibre.spell.break_iterator import index_of from calibre.utils.icu import capitalize, lower, safe_chr, string_length, swapcase, upper, utf16_length from calibre.utils.img import image_to_data from calibre.utils.titlecase import titlecase from polyglot.builtins import as_unicode def adjust_for_non_bmp_chars(raw: str, start: int, end: int) -> tuple[int, int]: adjusted_start = utf16_length(raw[:start]) end = adjusted_start + utf16_length(raw[start:end]) start = adjusted_start return start, end def get_highlighter(syntax): if syntax: try: return importlib.import_module('calibre.gui2.tweak_book.editor.syntax.' + syntax).Highlighter except (ImportError, AttributeError): pass return SyntaxHighlighter def get_smarts(syntax): if syntax: smartsname = {'xml':'html'}.get(syntax, syntax) try: return importlib.import_module('calibre.gui2.tweak_book.editor.smarts.' + smartsname).Smarts except (ImportError, AttributeError): pass _dff = None def default_font_family(): global _dff if _dff is None: families = set(map(str, QFontDatabase.families())) for x in ('Ubuntu Mono', 'Consolas', 'Liberation Mono'): if x in families: _dff = x break if _dff is None: _dff = 'Courier New' return _dff class LineNumbers(QWidget): # {{{ def __init__(self, parent): QWidget.__init__(self, parent) def sizeHint(self): return QSize(self.parent().line_number_area_width(), 0) def paintEvent(self, ev): self.parent().paint_line_numbers(ev) # }}} class TextEdit(PlainTextEdit): link_clicked = pyqtSignal(object) class_clicked = pyqtSignal(object) smart_highlighting_updated = pyqtSignal() def __init__(self, parent=None, expected_geometry=(100, 50)): PlainTextEdit.__init__(self, parent) self.snippet_manager = SnippetManager(self) self.completion_popup = CompletionPopup(self) self.request_completion = self.completion_doc_name = None self.clear_completion_cache_timer = t = QTimer(self) t.setInterval(5000), t.timeout.connect(self.clear_completion_cache), t.setSingleShot(True) self.textChanged.connect(t.start) self.last_completion_request = -1 self.gutter_width = 0 self.tw = 2 self.expected_geometry = expected_geometry self.saved_matches = {} self.syntax = None self.smarts = NullSmarts(self) self.current_cursor_line = None self.current_search_mark = None self.smarts_highlight_timer = t = QTimer() t.setInterval(750), t.setSingleShot(True), t.timeout.connect(self.update_extra_selections) self.highlighter = SyntaxHighlighter() self.line_number_area = LineNumbers(self) self.apply_settings() self.setMouseTracking(True) self.cursorPositionChanged.connect(self.highlight_cursor_line) self.blockCountChanged[int].connect(self.update_line_number_area_width) self.updateRequest.connect(self.update_line_number_area) def get_droppable_files(self, md): def is_mt_ok(mt): return self.syntax == 'html' and ( mt in OEB_DOCS or mt in OEB_STYLES or mt.startswith('image/') ) if md.hasFormat(CONTAINER_DND_MIMETYPE): for line in as_unicode(bytes(md.data(CONTAINER_DND_MIMETYPE))).splitlines(): mt = current_container().mime_map.get(line, 'application/octet-stream') if is_mt_ok(mt): yield line, mt, True return for qurl in md.urls(): if qurl.isLocalFile() and os.access(qurl.toLocalFile(), os.R_OK): path = qurl.toLocalFile() mt = guess_type(path) if is_mt_ok(mt): yield path, mt, False def canInsertFromMimeData(self, md): if md.hasText() or (md.hasHtml() and self.syntax == 'html') or md.hasImage(): return True elif tuple(self.get_droppable_files(md)): return True return False def insertFromMimeData(self, md): files = tuple(self.get_droppable_files(md)) base = self.highlighter.doc_name or None def get_name(name): folder = get_recommended_folders(current_container(), (name,))[name] or '' if folder: folder += '/' return folder + name def get_href(name): return current_container().name_to_href(name, base) def insert_text(text): c = self.textCursor() c.insertText(text) self.setTextCursor(c) self.ensureCursorVisible() def add_file(name, data, mt=None): from calibre.gui2.tweak_book.boss import get_boss name = current_container().add_file(name, data, media_type=mt, modify_name_if_needed=True) get_boss().refresh_file_list() return name if files: for path, mt, is_name in files: if is_name: name = path else: name = get_name(os.path.basename(path)) with open(path, 'rb') as f: name = add_file(name, f.read(), mt) href = get_href(name) if mt.startswith('image/'): self.insert_image(href) elif mt in OEB_STYLES: insert_text(f'<link href="{href}" rel="stylesheet" type="text/css"/>') elif mt in OEB_DOCS: self.insert_hyperlink(href, name) self.ensureCursorVisible() return if md.hasImage(): img = md.imageData() if img is not None and not img.isNull(): data = image_to_data(img, fmt='PNG') name = add_file(get_name('dropped_image.png'), data) self.insert_image(get_href(name)) self.ensureCursorVisible() return if md.hasText(): return insert_text(md.text()) if md.hasHtml(): insert_text(md.html()) return @property def is_modified(self): ''' True if the document has been modified since it was loaded or since the last time is_modified was set to False. ''' return self.document().isModified() @is_modified.setter def is_modified(self, val): self.document().setModified(bool(val)) def sizeHint(self): return self.size_hint def apply_line_wrap_mode(self, yes: bool = True) -> None: self.setLineWrapMode(QPlainTextEdit.LineWrapMode.WidgetWidth if yes else QPlainTextEdit.LineWrapMode.NoWrap) def apply_settings(self, prefs=None, dictionaries_changed=False): # {{{ prefs = prefs or tprefs self.setAcceptDrops(prefs.get('editor_accepts_drops', True)) self.apply_line_wrap_mode(prefs['editor_line_wrap']) with suppress(Exception): self.setCursorWidth(int(prefs.get('editor_cursor_width', 1))) theme = get_theme(prefs['editor_theme']) self.apply_theme(theme) fm = self.fontMetrics() self.space_width = fm.horizontalAdvance(' ') self.tw = self.smarts.override_tab_stop_width if self.smarts.override_tab_stop_width is not None else prefs['editor_tab_stop_width'] self.setTabStopDistance(self.tw * self.space_width) if dictionaries_changed: self.highlighter.rehighlight() def apply_theme(self, theme): self.theme = theme pal = self.palette() pal.setColor(QPalette.ColorRole.Base, theme_color(theme, 'Normal', 'bg')) pal.setColor(QPalette.ColorRole.AlternateBase, theme_color(theme, 'CursorLine', 'bg')) pal.setColor(QPalette.ColorRole.Text, theme_color(theme, 'Normal', 'fg')) pal.setColor(QPalette.ColorRole.Highlight, theme_color(theme, 'Visual', 'bg')) pal.setColor(QPalette.ColorRole.HighlightedText, theme_color(theme, 'Visual', 'fg')) self.setPalette(pal) vpal = self.viewport().palette() vpal.setColor(QPalette.ColorRole.Base, pal.color(QPalette.ColorRole.Base)) self.viewport().setPalette(vpal) self.tooltip_palette = pal = QPalette() pal.setColor(QPalette.ColorRole.ToolTipBase, theme_color(theme, 'Tooltip', 'bg')) pal.setColor(QPalette.ColorRole.ToolTipText, theme_color(theme, 'Tooltip', 'fg')) self.line_number_palette = pal = QPalette() pal.setColor(QPalette.ColorRole.Base, theme_color(theme, 'LineNr', 'bg')) pal.setColor(QPalette.ColorRole.Text, theme_color(theme, 'LineNr', 'fg')) pal.setColor(QPalette.ColorRole.BrightText, theme_color(theme, 'LineNrC', 'fg')) self.match_paren_format = theme_format(theme, 'MatchParen') font = self.font() ff = tprefs['editor_font_family'] if ff is None: ff = default_font_family() font.setFamily(ff) font.setPointSizeF(tprefs['editor_font_size']) self.tooltip_font = QFont(font) self.tooltip_font.setPointSizeF(font.pointSizeF() - 1.) self.setFont(font) self.highlighter.apply_theme(theme) fm = self.fontMetrics() self.number_width = max(map(lambda x:fm.horizontalAdvance(str(x)), range(10))) self.size_hint = QSize(self.expected_geometry[0] * fm.averageCharWidth(), self.expected_geometry[1] * fm.height()) self.highlight_color = theme_color(theme, 'HighlightRegion', 'bg') self.highlight_cursor_line() self.completion_popup.clear_caches(), self.completion_popup.update() # }}} def load_text(self, text, syntax='html', process_template=False, doc_name=None): self.syntax = syntax self.highlighter = get_highlighter(syntax)() self.highlighter.apply_theme(self.theme) self.highlighter.set_document(self.document(), doc_name=doc_name) sclass = get_smarts(syntax) if sclass is not None: self.smarts = sclass(self) if self.smarts.override_tab_stop_width is not None: self.tw = self.smarts.override_tab_stop_width self.setTabStopDistance(self.tw * self.space_width) if isinstance(text, bytes): text = text.decode('utf-8', 'replace') self.setPlainText(unicodedata.normalize('NFC', str(text))) if process_template and QPlainTextEdit.find(self, '%CURSOR%'): c = self.textCursor() c.insertText('') def change_document_name(self, newname): self.highlighter.doc_name = newname self.highlighter.rehighlight() # Ensure links are checked w.r.t. the new name correctly def replace_text(self, text): c = self.textCursor() pos = c.position() c.beginEditBlock() c.clearSelection() c.select(QTextCursor.SelectionType.Document) c.insertText(unicodedata.normalize('NFC', text)) c.endEditBlock() c.setPosition(min(pos, len(text))) self.setTextCursor(c) self.ensureCursorVisible() def simple_replace(self, text, cursor=None): c = cursor or self.textCursor() c.insertText(unicodedata.normalize('NFC', text)) self.setTextCursor(c) def go_to_line(self, lnum, col=None): lnum = max(1, min(self.blockCount(), lnum)) c = self.textCursor() c.clearSelection() c.movePosition(QTextCursor.MoveOperation.Start) c.movePosition(QTextCursor.MoveOperation.NextBlock, n=lnum - 1) c.movePosition(QTextCursor.MoveOperation.StartOfLine) c.movePosition(QTextCursor.MoveOperation.EndOfLine, QTextCursor.MoveMode.KeepAnchor) text = str(c.selectedText()).rstrip('\0') if col is None: c.movePosition(QTextCursor.MoveOperation.StartOfLine) lt = text.lstrip() if text and lt and lt != text: c.movePosition(QTextCursor.MoveOperation.NextWord) else: c.setPosition(c.block().position() + col) if c.blockNumber() + 1 > lnum: # We have moved past the end of the line c.setPosition(c.block().position()) c.movePosition(QTextCursor.MoveOperation.EndOfBlock) self.setTextCursor(c) self.ensureCursorVisible() def update_extra_selections(self, instant=True): sel = [] if self.current_cursor_line is not None: sel.extend(self.current_cursor_line) if self.current_search_mark is not None: sel.append(self.current_search_mark) if instant and not self.highlighter.has_requests and self.smarts is not None: sel.extend(self.smarts.get_extra_selections(self)) self.smart_highlighting_updated.emit() else: self.smarts_highlight_timer.start() self.setExtraSelections(sel) # Search and replace {{{ def mark_selected_text(self): sel = QTextEdit.ExtraSelection() sel.format.setBackground(self.highlight_color) sel.cursor = self.textCursor() if sel.cursor.hasSelection(): self.current_search_mark = sel c = self.textCursor() c.clearSelection() self.setTextCursor(c) else: self.current_search_mark = None self.update_extra_selections() def find_in_marked(self, pat, wrap=False, save_match=None): if self.current_search_mark is None: return False csm = self.current_search_mark.cursor reverse = pat.flags & regex.REVERSE c = self.textCursor() c.clearSelection() m_start = min(csm.position(), csm.anchor()) m_end = max(csm.position(), csm.anchor()) if c.position() < m_start: c.setPosition(m_start) if c.position() > m_end: c.setPosition(m_end) pos = m_start if reverse else m_end if wrap: pos = m_end if reverse else m_start c.setPosition(pos, QTextCursor.MoveMode.KeepAnchor) raw = str(c.selectedText()).replace(PARAGRAPH_SEPARATOR, '\n').rstrip('\0') m = pat.search(raw) if m is None: return False start, end = m.span() if start == end: return False start, end = adjust_for_non_bmp_chars(raw, start, end) if wrap: if reverse: textpos = c.anchor() start, end = textpos + end, textpos + start else: start, end = m_start + start, m_start + end else: if reverse: start, end = m_start + end, m_start + start else: start, end = c.anchor() + start, c.anchor() + end c.clearSelection() c.setPosition(start) c.setPosition(end, QTextCursor.MoveMode.KeepAnchor) self.setTextCursor(c) # Center search result on screen self.centerCursor() if save_match is not None: self.saved_matches[save_match] = (pat, m) return True def all_in_marked(self, pat, template=None): if self.current_search_mark is None: return 0 c = self.current_search_mark.cursor raw = str(c.selectedText()).replace(PARAGRAPH_SEPARATOR, '\n').rstrip('\0') if template is None: count = len(pat.findall(raw)) else: from calibre.gui2.tweak_book.function_replace import Function repl_is_func = isinstance(template, Function) if repl_is_func: template.init_env() raw, count = pat.subn(template, raw) if repl_is_func: from calibre.gui2.tweak_book.search import show_function_debug_output if getattr(template.func, 'append_final_output_to_marked', False): retval = template.end() if retval: raw += str(retval) else: template.end() show_function_debug_output(template) if count > 0: start_pos = min(c.anchor(), c.position()) c.insertText(raw) end_pos = max(c.anchor(), c.position()) c.setPosition(start_pos), c.setPosition(end_pos, QTextCursor.MoveMode.KeepAnchor) self.update_extra_selections() return count def smart_comment(self): from calibre.gui2.tweak_book.editor.comments import smart_comment smart_comment(self, self.syntax) def sort_css(self): from calibre.gui2.dialogs.confirm_delete import confirm if confirm(_('Sorting CSS rules can in rare cases change the effective styles applied to the book.' ' Are you sure you want to proceed?'), 'edit-book-confirm-sort-css', parent=self, config_set=tprefs): c = self.textCursor() c.beginEditBlock() c.movePosition(QTextCursor.MoveOperation.Start), c.movePosition(QTextCursor.MoveOperation.End, QTextCursor.MoveMode.KeepAnchor) text = str(c.selectedText()).replace(PARAGRAPH_SEPARATOR, '\n').rstrip('\0') from calibre.ebooks.oeb.polish.css import sort_sheet text = css_text(sort_sheet(current_container(), text)) c.insertText(text) c.movePosition(QTextCursor.MoveOperation.Start) c.endEditBlock() self.setTextCursor(c) def find(self, pat, wrap=False, marked=False, complete=False, save_match=None): if marked: return self.find_in_marked(pat, wrap=wrap, save_match=save_match) reverse = pat.flags & regex.REVERSE c = self.textCursor() c.clearSelection() if complete: # Search the entire text c.movePosition(QTextCursor.MoveOperation.End if reverse else QTextCursor.MoveOperation.Start) pos = QTextCursor.MoveOperation.Start if reverse else QTextCursor.MoveOperation.End if wrap and not complete: pos = QTextCursor.MoveOperation.End if reverse else QTextCursor.MoveOperation.Start c.movePosition(pos, QTextCursor.MoveMode.KeepAnchor) raw = str(c.selectedText()).replace(PARAGRAPH_SEPARATOR, '\n').rstrip('\0') m = pat.search(raw) if m is None: return False start, end = m.span() if start == end: return False start, end = adjust_for_non_bmp_chars(raw, start, end) if wrap and not complete: if reverse: textpos = c.anchor() start, end = textpos + end, textpos + start else: if reverse: # Put the cursor at the start of the match start, end = end, start else: textpos = c.anchor() start, end = textpos + start, textpos + end c.clearSelection() c.setPosition(start) c.setPosition(end, QTextCursor.MoveMode.KeepAnchor) self.setTextCursor(c) # Center search result on screen self.centerCursor() if save_match is not None: self.saved_matches[save_match] = (pat, m) return True def find_text(self, pat, wrap=False, complete=False): reverse = pat.flags & regex.REVERSE c = self.textCursor() c.clearSelection() if complete: # Search the entire text c.movePosition(QTextCursor.MoveOperation.End if reverse else QTextCursor.MoveOperation.Start) pos = QTextCursor.MoveOperation.Start if reverse else QTextCursor.MoveOperation.End if wrap and not complete: pos = QTextCursor.MoveOperation.End if reverse else QTextCursor.MoveOperation.Start c.movePosition(pos, QTextCursor.MoveMode.KeepAnchor) if hasattr(self.smarts, 'find_text'): self.highlighter.join() found, start, end = self.smarts.find_text(pat, c, reverse) if not found: return False else: raw = str(c.selectedText()).replace(PARAGRAPH_SEPARATOR, '\n').rstrip('\0') m = pat.search(raw) if m is None: return False start, end = m.span() if start == end: return False start, end = adjust_for_non_bmp_chars(raw, start, end) if reverse: start, end = end, start c.clearSelection() c.setPosition(start) c.setPosition(end, QTextCursor.MoveMode.KeepAnchor) self.setTextCursor(c) # Center search result on screen self.centerCursor() return True def find_spell_word(self, original_words, lang, from_cursor=True, center_on_cursor=True): c = self.textCursor() c.setPosition(c.position()) if not from_cursor: c.movePosition(QTextCursor.MoveOperation.Start) c.movePosition(QTextCursor.MoveOperation.End, QTextCursor.MoveMode.KeepAnchor) def find_first_word(haystack): match_pos, match_word = -1, None for w in original_words: idx = index_of(w, haystack, lang=lang) if idx > -1 and (match_pos == -1 or match_pos > idx): match_pos, match_word = idx, w return match_pos, match_word while True: text = str(c.selectedText()).rstrip('\0') idx, word = find_first_word(text) if idx == -1: return False c.setPosition(c.anchor() + idx) c.setPosition(c.position() + string_length(word), QTextCursor.MoveMode.KeepAnchor) if self.smarts.verify_for_spellcheck(c, self.highlighter): self.highlighter.join() # Ensure highlighting is finished locale = self.spellcheck_locale_for_cursor(c) if not lang or not locale or (locale and lang == locale.langcode): self.setTextCursor(c) if center_on_cursor: self.centerCursor() return True c.setPosition(c.position()) c.movePosition(QTextCursor.MoveOperation.End, QTextCursor.MoveMode.KeepAnchor) return False def find_next_spell_error(self, from_cursor=True): c = self.textCursor() if not from_cursor: c.movePosition(QTextCursor.MoveOperation.Start) block = c.block() while block.isValid(): for r in block.layout().formats(): if r.format.property(SPELL_PROPERTY): if not from_cursor or block.position() + r.start + r.length > c.position(): c.setPosition(block.position() + r.start) c.setPosition(c.position() + r.length, QTextCursor.MoveMode.KeepAnchor) self.setTextCursor(c) return True block = block.next() return False def replace(self, pat, template, saved_match='gui'): c = self.textCursor() raw = str(c.selectedText()).replace(PARAGRAPH_SEPARATOR, '\n').rstrip('\0') m = pat.fullmatch(raw) if m is None: # This can happen if either the user changed the selected text or # the search expression uses lookahead/lookbehind operators. See if # the saved match matches the currently selected text and # use it, if so. if saved_match is not None and saved_match in self.saved_matches: saved_pat, saved = self.saved_matches.pop(saved_match) if saved_pat == pat and saved.group() == raw: m = saved if m is None: return False if callable(template): text = template(m) else: text = m.expand(template) c.insertText(text) return True def go_to_anchor(self, anchor): if anchor is TOP: c = self.textCursor() c.movePosition(QTextCursor.MoveOperation.Start) self.setTextCursor(c) return True base = r'''%%s\s*=\s*['"]{0,1}%s''' % regex.escape(anchor) raw = str(self.toPlainText()) m = regex.search(base % 'id', raw) if m is None: m = regex.search(base % 'name', raw) if m is not None: c = self.textCursor() c.setPosition(m.start()) self.setTextCursor(c) return True return False # }}} # Line numbers and cursor line {{{ def highlight_cursor_line(self): self._highlight_cursor_line() def _highlight_cursor_line(self, highlight_now=True): if self.highlighter.is_working: QTimer.singleShot(10, self.highlight_cursor_line) if not highlight_now: return sel = QTextEdit.ExtraSelection() sel.format.setBackground(self.palette().alternateBase()) sel.format.setProperty(QTextFormat.Property.FullWidthSelection, True) sel.cursor = self.textCursor() sel.cursor.clearSelection() self.current_cursor_line = [sel] # apply any formats that have a background over the cursor line format # to ensure they are visible c = self.textCursor() block = c.block() c.clearSelection() c.select(QTextCursor.SelectionType.LineUnderCursor) start = min(c.anchor(), c.position()) length = max(c.anchor(), c.position()) - start for f in self.highlighter.formats_for_line(block, start, length): sel = QTextEdit.ExtraSelection() c = self.textCursor() c.setPosition(f.start + block.position()) c.setPosition(c.position() + f.length, QTextCursor.MoveMode.KeepAnchor) sel.cursor, sel.format = c, f.format self.current_cursor_line.append(sel) self.update_extra_selections(instant=False) # Update the cursor line's line number in the line number area try: self.line_number_area.update(0, self.last_current_lnum[0], self.line_number_area.width(), self.last_current_lnum[1]) except AttributeError: pass block = self.textCursor().block() top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top()) height = int(self.blockBoundingRect(block).height()) self.line_number_area.update(0, top, self.line_number_area.width(), height) def update_line_number_area_width(self, block_count=0): self.gutter_width = self.line_number_area_width() self.setViewportMargins(self.gutter_width, 0, 0, 0) def line_number_area_width(self): digits = 1 limit = max(1, self.blockCount()) while limit >= 10: limit /= 10 digits += 1 return 8 + self.number_width * digits def update_line_number_area(self, rect, dy): if dy: self.line_number_area.scroll(0, dy) else: self.line_number_area.update(0, rect.y(), self.line_number_area.width(), rect.height()) if rect.contains(self.viewport().rect()): self.update_line_number_area_width() def resizeEvent(self, ev): QPlainTextEdit.resizeEvent(self, ev) cr = self.contentsRect() self.line_number_area.setGeometry(QRect(cr.left(), cr.top(), self.line_number_area_width(), cr.height())) def paint_line_numbers(self, ev): painter = QPainter(self.line_number_area) painter.fillRect(ev.rect(), self.line_number_palette.color(QPalette.ColorRole.Base)) block = self.firstVisibleBlock() num = block.blockNumber() top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top()) bottom = top + int(self.blockBoundingRect(block).height()) current = self.textCursor().block().blockNumber() painter.setPen(self.line_number_palette.color(QPalette.ColorRole.Text)) while block.isValid() and top <= ev.rect().bottom(): if block.isVisible() and bottom >= ev.rect().top(): if current == num: painter.save() painter.setPen(self.line_number_palette.color(QPalette.ColorRole.BrightText)) f = QFont(self.font()) f.setBold(True) painter.setFont(f) self.last_current_lnum = (top, bottom - top) painter.drawText(0, top, self.line_number_area.width() - 5, self.fontMetrics().height(), Qt.AlignmentFlag.AlignRight, str(num + 1)) if current == num: painter.restore() block = block.next() top = bottom bottom = top + int(self.blockBoundingRect(block).height()) num += 1 # }}} def override_shortcut(self, ev): # Let the global cut/copy/paste/undo/redo shortcuts work, this avoids the nbsp # problem as well, since they use the overridden createMimeDataFromSelection() method # instead of the one from Qt (which makes copy() work), and allows proper customization # of the shortcuts if ev in ( QKeySequence.StandardKey.Copy, QKeySequence.StandardKey.Cut, QKeySequence.StandardKey.Paste, QKeySequence.StandardKey.Undo, QKeySequence.StandardKey.Redo ): ev.ignore() return True # This is used to convert typed hex codes into unicode # characters if ev.key() == Qt.Key.Key_X and ev.modifiers() == Qt.KeyboardModifier.AltModifier: ev.accept() return True return PlainTextEdit.override_shortcut(self, ev) def text_for_range(self, block, r): c = self.textCursor() c.setPosition(block.position() + r.start) c.setPosition(c.position() + r.length, QTextCursor.MoveMode.KeepAnchor) return self.selected_text_from_cursor(c) def spellcheck_locale_for_cursor(self, c): with store_locale: formats = self.highlighter.parse_single_block(c.block())[0] pos = c.positionInBlock() for r in formats: if r.start <= pos <= r.start + r.length and r.format.property(SPELL_PROPERTY): return r.format.property(SPELL_LOCALE_PROPERTY) def recheck_word(self, word, locale): c = self.textCursor() c.movePosition(QTextCursor.MoveOperation.Start) block = c.block() while block.isValid(): for r in block.layout().formats(): if r.format.property(SPELL_PROPERTY) and self.text_for_range(block, r) == word: self.highlighter.reformat_block(block) break block = block.next() # Tooltips {{{ def syntax_range_for_cursor(self, cursor): if cursor.isNull(): return pos = cursor.positionInBlock() for r in cursor.block().layout().formats(): if r.start <= pos <= r.start + r.length and r.format.property(SYNTAX_PROPERTY): return r def show_tooltip(self, ev): c = self.cursorForPosition(ev.pos()) fmt_range = self.syntax_range_for_cursor(c) fmt = getattr(fmt_range, 'format', None) if fmt is not None: tt = str(fmt.toolTip()) if tt: QToolTip.setFont(self.tooltip_font) QToolTip.setPalette(self.tooltip_palette) QToolTip.showText(ev.globalPos(), textwrap.fill(tt)) return QToolTip.hideText() ev.ignore() # }}} def link_for_position(self, pos): c = self.cursorForPosition(pos) r = self.syntax_range_for_cursor(c) if r is not None and r.format.property(LINK_PROPERTY): return self.text_for_range(c.block(), r) def select_class_name_at_cursor(self, cursor): valid = re.compile(r'[\w_0-9\-]+', flags=re.UNICODE) def keep_going(): q = cursor.selectedText() m = valid.match(q) return m is not None and m.group() == q def run_loop(forward=True): cursor.setPosition(pos) n, p = QTextCursor.MoveOperation.NextCharacter, QTextCursor.MoveOperation.PreviousCharacter if not forward: n, p = p, n while True: if not cursor.movePosition(n, QTextCursor.MoveMode.KeepAnchor): break if not keep_going(): cursor.movePosition(p, QTextCursor.MoveMode.KeepAnchor) break ans = cursor.position() cursor.setPosition(pos) return ans pos = cursor.position() forwards_limit = run_loop() backwards_limit = run_loop(forward=False) cursor.setPosition(backwards_limit) cursor.setPosition(forwards_limit, QTextCursor.MoveMode.KeepAnchor) return self.selected_text_from_cursor(cursor) def class_for_position(self, pos): c = self.cursorForPosition(pos) r = self.syntax_range_for_cursor(c) if r is not None and r.format.property(CLASS_ATTRIBUTE_PROPERTY): class_name = self.select_class_name_at_cursor(c) if class_name: tags = self.current_tag(for_position_sync=False, cursor=c) return {'class': class_name, 'sourceline_address': tags} def mousePressEvent(self, ev): if self.completion_popup.isVisible() and not self.completion_popup.rect().contains(ev.pos()): # For some reason using eventFilter for this does not work, so we # implement it here self.completion_popup.abort() if ev.modifiers() & Qt.KeyboardModifier.ControlModifier: url = self.link_for_position(ev.pos()) if url is not None: ev.accept() self.link_clicked.emit(url) return class_data = self.class_for_position(ev.pos()) if class_data is not None: ev.accept() self.class_clicked.emit(class_data) return return PlainTextEdit.mousePressEvent(self, ev) def get_range_inside_tag(self): c = self.textCursor() left = min(c.anchor(), c.position()) right = max(c.anchor(), c.position()) # For speed we use QPlainTextEdit's toPlainText as we dont care about # spaces in this context raw = str(QPlainTextEdit.toPlainText(self)) # Make sure the left edge is not within a <> gtpos = raw.find('>', left) ltpos = raw.find('<', left) if gtpos < ltpos: left = gtpos + 1 if gtpos > -1 else left right = max(left, right) if right != left: gtpos = raw.find('>', right) ltpos = raw.find('<', right) if ltpos > gtpos: ltpos = raw.rfind('<', left, right+1) right = max(ltpos, left) return left, right def format_text(self, formatting): if self.syntax != 'html': return if formatting.startswith('justify_'): return self.smarts.set_text_alignment(self, formatting.partition('_')[-1]) color = 'currentColor' if formatting in {'color', 'background-color'}: color = QColorDialog.getColor( QColor(Qt.GlobalColor.black if formatting == 'color' else Qt.GlobalColor.white), self, _('Choose color'), QColorDialog.ColorDialogOption.ShowAlphaChannel) if not color.isValid(): return r, g, b, a = color.getRgb() if a == 255: color = 'rgb(%d, %d, %d)' % (r, g, b) else: color = 'rgba(%d, %d, %d, %.2g)' % (r, g, b, a/255) prefix, suffix = { 'bold': ('<b>', '</b>'), 'italic': ('<i>', '</i>'), 'underline': ('<u>', '</u>'), 'strikethrough': ('<span style="text-decoration: line-through">', '</span>'), 'superscript': ('<sup>', '</sup>'), 'subscript': ('<sub>', '</sub>'), 'color': ('<span style="color: %s">' % color, '</span>'), 'background-color': ('<span style="background-color: %s">' % color, '</span>'), }[formatting] self.smarts.surround_with_custom_tag(self, prefix, suffix) def insert_image(self, href, fullpage=False, preserve_aspect_ratio=False, width=-1, height=-1): if width <= 0: width = 1200 if height <= 0: height = 1600 c = self.textCursor() template, alt = 'url(%s)', '' left = min(c.position(), c.anchor()) if self.syntax == 'html': left, right = self.get_range_inside_tag() c.setPosition(left) c.setPosition(right, QTextCursor.MoveMode.KeepAnchor) href = prepare_string_for_xml(href, True) if fullpage: template = '''\ <div style="page-break-before:always; page-break-after:always; page-break-inside:avoid">\ <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" \ version="1.1" width="100%%" height="100%%" viewBox="0 0 {w} {h}" preserveAspectRatio="{a}">\ <image width="{w}" height="{h}" xlink:href="%s"/>\ </svg></div>'''.format(w=width, h=height, a='xMidYMid meet' if preserve_aspect_ratio else 'none') else: alt = _('Image') template = f'<img alt="{alt}" src="%s" />' text = template % href c.insertText(text) if self.syntax == 'html' and not fullpage: c.setPosition(left + 10) c.setPosition(c.position() + len(alt), QTextCursor.MoveMode.KeepAnchor) else: c.setPosition(left) c.setPosition(left + len(text), QTextCursor.MoveMode.KeepAnchor) self.setTextCursor(c) def insert_hyperlink(self, target, text, template=None): if hasattr(self.smarts, 'insert_hyperlink'): self.smarts.insert_hyperlink(self, target, text, template=template) def insert_tag(self, tag): if hasattr(self.smarts, 'insert_tag'): self.smarts.insert_tag(self, tag) def remove_tag(self): if hasattr(self.smarts, 'remove_tag'): self.smarts.remove_tag(self) def split_tag(self): if hasattr(self.smarts, 'split_tag'): self.smarts.split_tag(self) def keyPressEvent(self, ev): if ev.key() == Qt.Key.Key_X and ev.modifiers() == Qt.KeyboardModifier.AltModifier: if self.replace_possible_unicode_sequence(): ev.accept() return if ev.key() == Qt.Key.Key_Insert: self.setOverwriteMode(self.overwriteMode() ^ True) ev.accept() return if self.snippet_manager.handle_key_press(ev): self.completion_popup.hide() return if self.smarts.handle_key_press(ev, self): self.handle_keypress_completion(ev) return QPlainTextEdit.keyPressEvent(self, ev) self.handle_keypress_completion(ev) def handle_keypress_completion(self, ev): if self.request_completion is None: return code = ev.key() if code in ( 0, Qt.Key.Key_unknown, Qt.Key.Key_Shift, Qt.Key.Key_Control, Qt.Key.Key_Alt, Qt.Key.Key_Meta, Qt.Key.Key_AltGr, Qt.Key.Key_CapsLock, Qt.Key.Key_NumLock, Qt.Key.Key_ScrollLock, Qt.Key.Key_Up, Qt.Key.Key_Down): # We ignore up/down arrow so as to not break scrolling through the # text with the arrow keys return result = self.smarts.get_completion_data(self, ev) if result is None: self.last_completion_request += 1 else: self.last_completion_request = self.request_completion(*result) self.completion_popup.mark_completion(self, None if result is None else result[-1]) def handle_completion_result(self, result): if result.request_id[0] >= self.last_completion_request: self.completion_popup.handle_result(result) def clear_completion_cache(self): if self.request_completion is not None and self.completion_doc_name: self.request_completion(None, 'file:' + self.completion_doc_name) def replace_possible_unicode_sequence(self): c = self.textCursor() has_selection = c.hasSelection() if has_selection: text = str(c.selectedText()).rstrip('\0') else: c.setPosition(c.position() - min(c.positionInBlock(), 6), QTextCursor.MoveMode.KeepAnchor) text = str(c.selectedText()).rstrip('\0') m = re.search(r'[a-fA-F0-9]{2,6}$', text) if m is None: return False text = m.group() try: num = int(text, 16) except ValueError: return False if num > 0x10ffff or num < 1: return False end_pos = max(c.anchor(), c.position()) c.setPosition(end_pos - len(text)), c.setPosition(end_pos, QTextCursor.MoveMode.KeepAnchor) c.insertText(safe_chr(num)) return True def select_all(self): c = self.textCursor() c.clearSelection() c.setPosition(0) c.movePosition(QTextCursor.MoveOperation.End, QTextCursor.MoveMode.KeepAnchor) self.setTextCursor(c) def rename_block_tag(self, new_name): if hasattr(self.smarts, 'rename_block_tag'): self.smarts.rename_block_tag(self, new_name) def current_tag(self, for_position_sync=True, cursor=None): use_matched_tag = False if cursor is None: use_matched_tag = True cursor = self.textCursor() return self.smarts.cursor_position_with_sourceline(cursor, for_position_sync=for_position_sync, use_matched_tag=use_matched_tag) def goto_sourceline(self, sourceline, tags, attribute=None): return self.smarts.goto_sourceline(self, sourceline, tags, attribute=attribute) def get_tag_contents(self): c = self.smarts.get_inner_HTML(self) if c is not None: return self.selected_text_from_cursor(c) def goto_css_rule(self, rule_address, sourceline_address=None): from calibre.gui2.tweak_book.editor.smarts.css import find_rule block = None if self.syntax == 'css': raw = str(self.toPlainText()) line, col = find_rule(raw, rule_address) if line is not None: block = self.document().findBlockByNumber(line - 1) elif sourceline_address is not None: sourceline, tags = sourceline_address if self.goto_sourceline(sourceline, tags): c = self.textCursor() c.setPosition(c.position() + 1) self.setTextCursor(c) raw = self.get_tag_contents() line, col = find_rule(raw, rule_address) if line is not None: block = self.document().findBlockByNumber(c.blockNumber() + line - 1) if block is not None and block.isValid(): c = self.textCursor() c.setPosition(block.position() + col) self.setTextCursor(c) def change_case(self, action, cursor=None): cursor = cursor or self.textCursor() text = self.selected_text_from_cursor(cursor) text = {'lower':lower, 'upper':upper, 'capitalize':capitalize, 'title':titlecase, 'swap':swapcase}[action](text) cursor.insertText(text) self.setTextCursor(cursor)
45,405
Python
.py
991
35.072654
152
0.606978
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,724
__init__.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/__init__.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' from qt.core import QTextCharFormat, QTextFormat from calibre.ebooks.oeb.base import OEB_DOCS, OEB_STYLES from calibre.ebooks.oeb.polish.container import guess_type _xml_types = {'application/oebps-page-map+xml', 'application/vnd.adobe-page-template+xml', 'application/page-template+xml'} | { guess_type('a.'+x) for x in ('ncx', 'opf', 'svg', 'xpgt', 'xml')} _js_types = {'application/javascript', 'application/x-javascript'} def syntax_from_mime(name, mime): for syntax, types in (('html', OEB_DOCS), ('css', OEB_STYLES), ('xml', _xml_types)): if mime in types: return syntax if mime in _js_types: return 'javascript' if mime.startswith('text/'): return 'text' if mime.startswith('image/') and mime.partition('/')[-1].lower() in { 'jpeg', 'jpg', 'gif', 'png', 'webp'}: return 'raster_image' if mime.endswith('+xml'): return 'xml' all_text_syntaxes = frozenset({'text', 'html', 'xml', 'css', 'javascript'}) def editor_from_syntax(syntax, parent=None): if syntax in all_text_syntaxes: from calibre.gui2.tweak_book.editor.widget import Editor return Editor(syntax, parent=parent) elif syntax == 'raster_image': from calibre.gui2.tweak_book.editor.image import Editor return Editor(syntax, parent=parent) SYNTAX_PROPERTY = QTextFormat.Property.UserProperty SPELL_PROPERTY = SYNTAX_PROPERTY + 1 SPELL_LOCALE_PROPERTY = SPELL_PROPERTY + 1 LINK_PROPERTY = SPELL_LOCALE_PROPERTY + 1 TAG_NAME_PROPERTY = LINK_PROPERTY + 1 CSS_PROPERTY = TAG_NAME_PROPERTY + 1 CLASS_ATTRIBUTE_PROPERTY = CSS_PROPERTY + 1 def syntax_text_char_format(*args): ans = QTextCharFormat(*args) ans.setProperty(SYNTAX_PROPERTY, True) return ans class StoreLocale: __slots__ = ('enabled',) def __init__(self): self.enabled = False def __enter__(self): self.enabled = True def __exit__(self, *args): self.enabled = False store_locale = StoreLocale()
2,127
Python
.py
50
37.4
127
0.675268
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,725
canvas.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/canvas.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' import sys import weakref from functools import wraps from io import BytesIO from qt.core import ( QApplication, QColor, QIcon, QImage, QImageWriter, QPainter, QPen, QPixmap, QPointF, QRect, QRectF, Qt, QTransform, QUndoCommand, QUndoStack, QWidget, pyqtSignal, ) from calibre import fit_image from calibre.gui2 import error_dialog, pixmap_to_data from calibre.gui2.dnd import DownloadDialog, dnd_get_image, dnd_has_extension, dnd_has_image, image_extensions from calibre.gui2.tweak_book import capitalize from calibre.utils.img import ( despeckle_image, gaussian_blur_image, gaussian_sharpen_image, image_to_data, normalize_image, oil_paint_image, remove_borders_from_image, ) from calibre.utils.imghdr import identify def painter(func): @wraps(func) def ans(self, painter): painter.save() try: return func(self, painter) finally: painter.restore() return ans class SelectionState: __slots__ = ('last_press_point', 'current_mode', 'rect', 'in_selection', 'drag_corner', 'dragging', 'last_drag_pos') def __init__(self): self.reset() def reset(self, full=True): self.last_press_point = None if full: self.current_mode = None self.rect = None self.in_selection = False self.drag_corner = None self.dragging = None self.last_drag_pos = None class Command(QUndoCommand): TEXT = '' def __init__(self, canvas): QUndoCommand.__init__(self, self.TEXT) self.canvas_ref = weakref.ref(canvas) self.before_image = i = canvas.current_image if i is None: raise ValueError('No image loaded') if i.isNull(): raise ValueError('Cannot perform operations on invalid images') self.after_image = self(canvas) def undo(self): canvas = self.canvas_ref() canvas.set_image(self.before_image) def redo(self): canvas = self.canvas_ref() canvas.set_image(self.after_image) def get_selection_rect(img, sr, target): ' Given selection rect return the corresponding rectangle in the underlying image as left, top, width, height ' left_border = (abs(sr.left() - target.left())/target.width()) * img.width() top_border = (abs(sr.top() - target.top())/target.height()) * img.height() right_border = (abs(target.right() - sr.right())/target.width()) * img.width() bottom_border = (abs(target.bottom() - sr.bottom())/target.height()) * img.height() return left_border, top_border, img.width() - left_border - right_border, img.height() - top_border - bottom_border class Trim(Command): ''' Remove the areas of the image outside the current selection. ''' TEXT = _('Trim image') def __call__(self, canvas): return canvas.current_image.copy(*map(int, canvas.rect_for_trim())) class AutoTrim(Trim): ''' Auto trim borders from the image ''' TEXT = _('Auto-trim image') def __call__(self, canvas): return remove_borders_from_image(canvas.current_image) class Rotate(Command): TEXT = _('Rotate image') def __call__(self, canvas): img = canvas.current_image m = QTransform() m.rotate(90) return img.transformed(m, Qt.TransformationMode.SmoothTransformation) class Scale(Command): TEXT = _('Resize image') def __init__(self, width, height, canvas): self.width, self.height = width, height Command.__init__(self, canvas) def __call__(self, canvas): img = canvas.current_image return img.scaled(self.width, self.height, transformMode=Qt.TransformationMode.SmoothTransformation) class Sharpen(Command): TEXT = _('Sharpen image') FUNC = 'sharpen' def __init__(self, sigma, canvas): self.sigma = sigma Command.__init__(self, canvas) def __call__(self, canvas): return gaussian_sharpen_image(canvas.current_image, sigma=self.sigma) class Blur(Sharpen): TEXT = _('Blur image') FUNC = 'blur' def __call__(self, canvas): return gaussian_blur_image(canvas.current_image, sigma=self.sigma) class Oilify(Command): TEXT = _('Make image look like an oil painting') def __init__(self, radius, canvas): self.radius = radius Command.__init__(self, canvas) def __call__(self, canvas): return oil_paint_image(canvas.current_image, radius=self.radius) class Despeckle(Command): TEXT = _('De-speckle image') def __call__(self, canvas): return despeckle_image(canvas.current_image) class Normalize(Command): TEXT = _('Normalize image') def __call__(self, canvas): return normalize_image(canvas.current_image) class Replace(Command): ''' Replace the current image with another image. If there is a selection, only the region of the selection is replaced. ''' def __init__(self, img, text, canvas): self.after_image = img self.TEXT = text Command.__init__(self, canvas) def __call__(self, canvas): if canvas.has_selection and canvas.selection_state.rect is not None: pimg = self.after_image img = self.after_image = QImage(canvas.current_image) rect = QRectF(*get_selection_rect(img, canvas.selection_state.rect, canvas.target)) p = QPainter(img) p.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform, True) p.drawImage(rect, pimg, QRectF(pimg.rect())) p.end() return self.after_image def imageop(func): @wraps(func) def ans(self, *args, **kwargs): if self.original_image_data is None: return error_dialog(self, _('No image'), _('No image loaded'), show=True) if not self.is_valid: return error_dialog(self, _('Invalid image'), _('The current image is not valid'), show=True) QApplication.setOverrideCursor(Qt.CursorShape.BusyCursor) try: return func(self, *args, **kwargs) finally: QApplication.restoreOverrideCursor() return ans class Canvas(QWidget): BACKGROUND = QColor(60, 60, 60) SHADE_COLOR = QColor(0, 0, 0, 180) SELECT_PEN = QPen(QColor(Qt.GlobalColor.white)) selection_state_changed = pyqtSignal(object) selection_area_changed = pyqtSignal(object) undo_redo_state_changed = pyqtSignal(object, object) image_changed = pyqtSignal(object) @property def has_selection(self): return self.selection_state.current_mode == 'selected' @property def is_modified(self): return self.current_image is not self.original_image # Drag 'n drop {{{ def dragEnterEvent(self, event): md = event.mimeData() if dnd_has_extension(md, image_extensions()) or dnd_has_image(md): event.acceptProposedAction() def dropEvent(self, event): event.setDropAction(Qt.DropAction.CopyAction) md = event.mimeData() x, y = dnd_get_image(md) if x is not None: # We have an image, set cover event.accept() if y is None: # Local image self.undo_stack.push(Replace(x.toImage(), _('Drop image'), self)) else: d = DownloadDialog(x, y, self.gui) d.start_download() if d.err is None: with open(d.fpath, 'rb') as f: img = QImage() img.loadFromData(f.read()) if not img.isNull(): self.undo_stack.push(Replace(img, _('Drop image'), self)) event.accept() def dragMoveEvent(self, event): event.acceptProposedAction() # }}} def __init__(self, parent=None): QWidget.__init__(self, parent) self.setAcceptDrops(True) self.setMouseTracking(True) self.setFocusPolicy(Qt.FocusPolicy.ClickFocus) self.selection_state = SelectionState() self.undo_stack = u = QUndoStack() u.setUndoLimit(10) u.canUndoChanged.connect(self.emit_undo_redo_state) u.canRedoChanged.connect(self.emit_undo_redo_state) self.original_image_data = None self.is_valid = False self.original_image_format = None self.current_image = None self.current_scaled_pixmap = None self.last_canvas_size = None self.target = QRectF(0, 0, 0, 0) self.undo_action = a = self.undo_stack.createUndoAction(self, _('Undo') + ' ') a.setIcon(QIcon.ic('edit-undo.png')) self.redo_action = a = self.undo_stack.createRedoAction(self, _('Redo') + ' ') a.setIcon(QIcon.ic('edit-redo.png')) def load_image(self, data, only_if_different=False): if only_if_different and self.original_image_data and not self.is_modified and self.original_image_data == data: return self.is_valid = False try: fmt = identify(data)[0].encode('ascii') except Exception: fmt = b'' self.original_image_format = fmt.decode('ascii').lower() self.selection_state.reset() self.original_image_data = data self.current_image = i = self.original_image = ( QImage.fromData(data, format=fmt) if fmt else QImage.fromData(data)) self.is_valid = not i.isNull() self.current_scaled_pixmap = None self.update() self.image_changed.emit(self.current_image) def set_image(self, qimage): self.selection_state.reset() self.current_scaled_pixmap = None self.current_image = qimage self.is_valid = not qimage.isNull() self.update() self.image_changed.emit(self.current_image) def get_image_data(self, quality=90): if not self.is_modified: return self.original_image_data fmt = self.original_image_format or 'JPEG' if fmt.lower() not in {x.data().decode('utf-8') for x in QImageWriter.supportedImageFormats()}: if fmt.lower() == 'gif': data = image_to_data(self.current_image, fmt='PNG', png_compression_level=0) from PIL import Image i = Image.open(BytesIO(data)) buf = BytesIO() i.save(buf, 'gif') return buf.getvalue() else: raise ValueError('Cannot save %s format images' % fmt) return pixmap_to_data(self.current_image, format=fmt, quality=90) def copy(self): if not self.is_valid: return clipboard = QApplication.clipboard() if not self.has_selection or self.selection_state.rect is None: clipboard.setImage(self.current_image) else: trim = Trim(self) clipboard.setImage(trim.after_image) trim.before_image = trim.after_image = None def paste(self): clipboard = QApplication.clipboard() md = clipboard.mimeData() if md.hasImage(): img = QImage(md.imageData()) if not img.isNull(): self.undo_stack.push(Replace(img, _('Paste image'), self)) else: error_dialog(self, _('No image'), _( 'No image available in the clipboard'), show=True) def break_cycles(self): self.undo_stack.clear() self.original_image_data = self.current_image = self.current_scaled_pixmap = None def emit_undo_redo_state(self): self.undo_redo_state_changed.emit(self.undo_action.isEnabled(), self.redo_action.isEnabled()) @imageop def trim_image(self): if self.selection_state.rect is None: error_dialog(self, _('No selection'), _( 'No active selection, first select a region in the image, by dragging with your mouse'), show=True) return False self.undo_stack.push(Trim(self)) return True @imageop def autotrim_image(self): self.undo_stack.push(AutoTrim(self)) return True @imageop def rotate_image(self): self.undo_stack.push(Rotate(self)) return True @imageop def resize_image(self, width, height): self.undo_stack.push(Scale(width, height, self)) return True @imageop def sharpen_image(self, sigma=3.0): self.undo_stack.push(Sharpen(sigma, self)) return True @imageop def blur_image(self, sigma=3.0): self.undo_stack.push(Blur(sigma, self)) return True @imageop def despeckle_image(self): self.undo_stack.push(Despeckle(self)) return True @imageop def normalize_image(self): self.undo_stack.push(Normalize(self)) return True @imageop def oilify_image(self, radius=4.0): self.undo_stack.push(Oilify(radius, self)) return True # The selection rectangle {{{ @property def dc_size(self): sr = self.selection_state.rect dx = min(75, sr.width() / 4) dy = min(75, sr.height() / 4) return dx, dy def get_drag_corner(self, pos): dx, dy = self.dc_size sr = self.selection_state.rect x, y = pos.x(), pos.y() hedge = 'left' if x < sr.x() + dx else 'right' if x > sr.right() - dx else None vedge = 'top' if y < sr.y() + dy else 'bottom' if y > sr.bottom() - dy else None return (hedge, vedge) if hedge or vedge else None def get_drag_rect(self): sr = self.selection_state.rect dc = self.selection_state.drag_corner if None in (sr, dc): return dx, dy = self.dc_size if None in dc: # An edge if dc[0] is None: top = sr.top() if dc[1] == 'top' else sr.bottom() - dy ans = QRectF(sr.left() + dx, top, sr.width() - 2 * dx, dy) else: left = sr.left() if dc[0] == 'left' else sr.right() - dx ans = QRectF(left, sr.top() + dy, dx, sr.height() - 2 * dy) else: # A corner left = sr.left() if dc[0] == 'left' else sr.right() - dx top = sr.top() if dc[1] == 'top' else sr.bottom() - dy ans = QRectF(left, top, dx, dy) return ans def get_cursor(self): dc = self.selection_state.drag_corner if dc is None: ans = Qt.CursorShape.OpenHandCursor if self.selection_state.last_drag_pos is None else Qt.CursorShape.ClosedHandCursor elif None in dc: ans = Qt.CursorShape.SizeVerCursor if dc[0] is None else Qt.CursorShape.SizeHorCursor else: ans = Qt.CursorShape.SizeBDiagCursor if dc in {('left', 'bottom'), ('right', 'top')} else Qt.CursorShape.SizeFDiagCursor return ans def update(self): super().update() self.selection_area_changed.emit(self.selection_state.rect) def move_edge(self, edge, dp): sr = self.selection_state.rect horiz = edge in {'left', 'right'} func = getattr(sr, 'set' + capitalize(edge)) delta = getattr(dp, 'x' if horiz else 'y')() buf = 50 if horiz: minv = self.target.left() if edge == 'left' else sr.left() + buf maxv = sr.right() - buf if edge == 'left' else self.target.right() else: minv = self.target.top() if edge == 'top' else sr.top() + buf maxv = sr.bottom() - buf if edge == 'top' else self.target.bottom() func(max(minv, min(maxv, delta + getattr(sr, edge)()))) def move_selection_rect(self, x, y): sr = self.selection_state.rect half_width = sr.width() / 2.0 half_height = sr.height() / 2.0 c = sr.center() nx = c.x() + x ny = c.y() + y minx = self.target.left() + half_width maxx = self.target.right() - half_width miny, maxy = self.target.top() + half_height, self.target.bottom() - half_height nx = max(minx, min(maxx, nx)) ny = max(miny, min(maxy, ny)) sr.moveCenter(QPointF(nx, ny)) def preserve_aspect_ratio_after_move(self, orig_rect, hedge, vedge): r = self.selection_state.rect def is_equal(a, b): return abs(a - b) < 0.001 if vedge is None: new_height = r.width() * (orig_rect.height() / orig_rect.width()) if not is_equal(new_height, r.height()): delta = (r.height() - new_height) / 2.0 r.setTop(max(self.target.top(), r.top() + delta)) r.setBottom(min(r.bottom() - delta, self.target.bottom())) if not is_equal(new_height, r.height()): new_width = r.height() * (orig_rect.width() / orig_rect.height()) delta = r.width() - new_width r.setLeft(r.left() + delta) if hedge == 'left' else r.setRight(r.right() - delta) elif hedge is None: new_width = r.height() * (orig_rect.width() / orig_rect.height()) if not is_equal(new_width, r.width()): delta = (r.width() - new_width) / 2.0 r.setLeft(max(self.target.left(), r.left() + delta)) r.setRight(min(r.right() - delta, self.target.right())) if not is_equal(new_width, r.width()): new_height = r.width() * (orig_rect.height() / orig_rect.width()) delta = r.height() - new_height r.setTop(r.top() + delta) if hedge == 'top' else r.setBottom(r.bottom() - delta) else: buf = 50 def set_width(new_width): if hedge == 'left': r.setLeft(max(self.target.left(), min(r.right() - new_width, r.right() - buf))) else: r.setRight(max(r.left() + buf, min(r.left() + new_width, self.target.right()))) def set_height(new_height): if vedge == 'top': r.setTop(max(self.target.top(), min(r.bottom() - new_height, r.bottom() - buf))) else: r.setBottom(max(r.top() + buf, min(r.top() + new_height, self.target.bottom()))) fractional_h, fractional_v = r.width() / orig_rect.width(), r.height() / orig_rect.height() smaller_frac = fractional_h if abs(fractional_h - 1) < abs(fractional_v - 1) else fractional_v set_width(orig_rect.width() * smaller_frac) frac = r.width() / orig_rect.width() set_height(orig_rect.height() * frac) if r.height() / orig_rect.height() != frac: set_width(orig_rect.width() * frac) def move_selection(self, dp, preserve_aspect_ratio=False): dm = self.selection_state.dragging if dm is None: self.move_selection_rect(dp.x(), dp.y()) else: orig = QRectF(self.selection_state.rect) for edge in dm: if edge is not None: self.move_edge(edge, dp) if preserve_aspect_ratio and dm: self.preserve_aspect_ratio_after_move(orig, dm[0], dm[1]) def rect_for_trim(self): img = self.current_image target = self.target sr = self.selection_state.rect return get_selection_rect(img, sr, target) def mousePressEvent(self, ev): if ev.button() == Qt.MouseButton.LeftButton and self.target.contains(ev.position()): pos = ev.position() self.selection_state.last_press_point = pos if self.selection_state.current_mode is None: self.selection_state.current_mode = 'select' elif self.selection_state.current_mode == 'selected': if self.selection_state.rect is not None and self.selection_state.rect.contains(pos): self.selection_state.drag_corner = self.selection_state.dragging = self.get_drag_corner(pos) self.selection_state.last_drag_pos = pos self.setCursor(self.get_cursor()) else: self.selection_state.current_mode = 'select' self.selection_state.rect = None self.selection_state_changed.emit(False) @property def selection_rect_in_image_coords(self): if self.selection_state.current_mode == 'selected': left, top, width, height = self.rect_for_trim() return QRect(0, 0, int(width), int(height)) return self.current_image.rect() def set_selection_size_in_image_coords(self, width, height): self.selection_state.reset() i = self.current_image self.selection_state.rect = QRectF(self.target.left(), self.target.top(), width * self.target.width() / i.width(), height * self.target.height() / i.height()) self.selection_state.current_mode = 'selected' self.update() self.selection_state_changed.emit(self.has_selection) def mouseMoveEvent(self, ev): changed = False if self.selection_state.in_selection: changed = True self.selection_state.in_selection = False self.selection_state.drag_corner = None pos = ev.position() cursor = Qt.CursorShape.ArrowCursor try: if ev.buttons() & Qt.MouseButton.LeftButton: if self.selection_state.last_press_point is not None and self.selection_state.current_mode is not None: if self.selection_state.current_mode == 'select': r = QRectF(self.selection_state.last_press_point, pos).normalized() r = r.intersected(self.target) self.selection_state.rect = r changed = True elif self.selection_state.last_drag_pos is not None: self.selection_state.in_selection = True self.selection_state.drag_corner = self.selection_state.dragging dp = pos - self.selection_state.last_drag_pos self.selection_state.last_drag_pos = pos self.move_selection(dp, preserve_aspect_ratio=ev.modifiers() & Qt.KeyboardModifier.AltModifier == Qt.KeyboardModifier.AltModifier) cursor = self.get_cursor() changed = True else: if not self.target.contains(QPointF(pos)) or self.selection_state.rect is None or not self.selection_state.rect.contains(QPointF(pos)): return if self.selection_state.current_mode == 'selected': if self.selection_state.rect is not None and self.selection_state.rect.contains(QPointF(pos)): self.selection_state.drag_corner = self.get_drag_corner(pos) self.selection_state.in_selection = True cursor = self.get_cursor() changed = True finally: if changed: self.update() self.setCursor(cursor) def mouseReleaseEvent(self, ev): if ev.button() == Qt.MouseButton.LeftButton: self.selection_state.dragging = self.selection_state.last_drag_pos = None if self.selection_state.current_mode == 'select': r = self.selection_state.rect if r is None or max(r.width(), r.height()) < 3: self.selection_state.reset() else: self.selection_state.current_mode = 'selected' self.selection_state_changed.emit(self.has_selection) elif self.selection_state.current_mode == 'selected' and self.selection_state.rect is not None and self.selection_state.rect.contains( ev.position()): self.setCursor(self.get_cursor()) self.update() def keyPressEvent(self, ev): k = ev.key() if k in (Qt.Key.Key_Left, Qt.Key.Key_Right, Qt.Key.Key_Up, Qt.Key.Key_Down) and self.selection_state.rect is not None and self.has_selection: ev.accept() delta = 10 if ev.modifiers() & Qt.KeyboardModifier.ShiftModifier else 1 x = y = 0 if k in (Qt.Key.Key_Left, Qt.Key.Key_Right): x = delta * (-1 if k == Qt.Key.Key_Left else 1) else: y = delta * (-1 if k == Qt.Key.Key_Up else 1) self.move_selection_rect(x, y) self.update() else: return QWidget.keyPressEvent(self, ev) # }}} # Painting {{{ @painter def draw_background(self, painter): painter.fillRect(self.rect(), self.BACKGROUND) @painter def draw_image_error(self, painter): font = painter.font() font.setPointSize(3 * font.pointSize()) font.setBold(True) painter.setFont(font) painter.setPen(QColor(Qt.GlobalColor.black)) painter.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, _('Not a valid image')) def load_pixmap(self): canvas_size = self.rect().width(), self.rect().height() if self.last_canvas_size != canvas_size: if self.last_canvas_size is not None and self.selection_state.rect is not None: self.selection_state.reset() # TODO: Migrate the selection rect self.last_canvas_size = canvas_size self.current_scaled_pixmap = None if self.current_scaled_pixmap is None: pwidth, pheight = self.last_canvas_size i = self.current_image width, height = i.width(), i.height() scaled, width, height = fit_image(width, height, pwidth, pheight) try: dpr = self.devicePixelRatioF() except AttributeError: dpr = self.devicePixelRatio() if scaled: i = self.current_image.scaled(int(dpr * width), int(dpr * height), transformMode=Qt.TransformationMode.SmoothTransformation) self.current_scaled_pixmap = QPixmap.fromImage(i) self.current_scaled_pixmap.setDevicePixelRatio(dpr) @painter def draw_pixmap(self, painter): p = self.current_scaled_pixmap try: dpr = self.devicePixelRatioF() except AttributeError: dpr = self.devicePixelRatio() width, height = int(p.width()/dpr), int(p.height()/dpr) pwidth, pheight = self.last_canvas_size x = int(abs(pwidth - width)/2.) y = int(abs(pheight - height)/2.) self.target = QRectF(x, y, width, height) painter.drawPixmap(self.target, p, QRectF(p.rect())) @painter def draw_selection_rect(self, painter): cr, sr = self.target, self.selection_state.rect painter.setPen(self.SELECT_PEN) painter.setRenderHint(QPainter.RenderHint.Antialiasing, False) if self.selection_state.current_mode == 'selected': # Shade out areas outside the selection rect for r in ( QRectF(cr.topLeft(), QPointF(sr.left(), cr.bottom())), # left QRectF(QPointF(sr.left(), cr.top()), sr.topRight()), # top QRectF(QPointF(sr.right(), cr.top()), cr.bottomRight()), # right QRectF(sr.bottomLeft(), QPointF(sr.right(), cr.bottom())), # bottom ): painter.fillRect(r, self.SHADE_COLOR) dr = self.get_drag_rect() if self.selection_state.in_selection and dr is not None: # Draw the resize rectangle painter.save() painter.setCompositionMode(QPainter.CompositionMode.RasterOp_SourceAndNotDestination) painter.setClipRect(sr.adjusted(1, 1, -1, -1)) painter.drawRect(dr) painter.restore() # Draw the selection rectangle painter.setCompositionMode(QPainter.CompositionMode.RasterOp_SourceAndNotDestination) painter.drawRect(sr) def paintEvent(self, event): QWidget.paintEvent(self, event) p = QPainter(self) p.setRenderHints(QPainter.RenderHint.Antialiasing | QPainter.RenderHint.SmoothPixmapTransform) try: self.draw_background(p) if self.original_image_data is None: return if not self.is_valid: return self.draw_image_error(p) self.load_pixmap() self.draw_pixmap(p) if self.selection_state.rect is not None: self.draw_selection_rect(p) finally: p.end() # }}} if __name__ == '__main__': app = QApplication([]) with open(sys.argv[-1], 'rb') as f: data = f.read() c = Canvas() c.load_image(data) c.show() app.exec()
29,137
Python
.py
658
33.895137
154
0.592028
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,726
snippets.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/snippets.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' import copy import re import weakref from collections import OrderedDict, namedtuple from itertools import groupby from operator import attrgetter, itemgetter from qt.core import ( QDialog, QDialogButtonBox, QFrame, QGridLayout, QHBoxLayout, QIcon, QLabel, QLineEdit, QListView, QListWidget, QListWidgetItem, QObject, QPushButton, QSize, QStackedLayout, Qt, QTextCursor, QToolButton, QVBoxLayout, QWidget, ) from calibre.constants import ismacos from calibre.gui2 import error_dialog from calibre.gui2.tweak_book.editor import all_text_syntaxes from calibre.gui2.tweak_book.editor.smarts.utils import get_text_before_cursor from calibre.gui2.tweak_book.widgets import Dialog, PlainTextEdit from calibre.utils.config import JSONConfig from calibre.utils.icu import string_length as strlen from calibre.utils.localization import localize_user_manual_link from polyglot.builtins import codepoint_to_chr, iteritems, itervalues def string_length(x): return strlen(str(x)) # Needed on narrow python builds, as subclasses of unicode dont work KEY = Qt.Key.Key_J MODIFIER = Qt.KeyboardModifier.MetaModifier if ismacos else Qt.KeyboardModifier.ControlModifier SnipKey = namedtuple('SnipKey', 'trigger syntaxes') def snip_key(trigger, *syntaxes): if '*' in syntaxes: syntaxes = all_text_syntaxes return SnipKey(trigger, frozenset(syntaxes)) def contains(l1, r1, l2, r2): # True iff (l2, r2) if contained in (l1, r1) return l2 > l1 and r2 < r1 builtin_snippets = { # {{{ snip_key('Lorem', 'html', 'xml'): { 'description': _('Insert filler text'), 'template': '''\ <p>The actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful.</p> <p>Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But.</p> ''', }, snip_key('<<', 'html', 'xml'): { 'description': _('Insert a tag'), 'template': '<$1>${2*}</$1>$3', }, snip_key('<>', 'html', 'xml'): { 'description': _('Insert a self closing tag'), 'template': '<$1/>$2', }, snip_key('<a', 'html'): { 'description': _('Insert a HTML link'), 'template': '<a href="${1:filename}">${2*}</a>$3', }, snip_key('<i', 'html'): { 'description': _('Insert a HTML image'), 'template': '<img src="${1:filename}" alt="${2*:description}" />$3', }, snip_key('<c', 'html'): { 'description': _('Insert a HTML tag with a class'), 'template': '<$1 class="${2:classname}">${3*}</$1>$4', }, } # }}} # Parsing of snippets {{{ escape = unescape = None def escape_funcs(): global escape, unescape if escape is None: escapem = {('\\' + x):codepoint_to_chr(i+1) for i, x in enumerate('\\${}')} escape_pat = re.compile('|'.join(map(re.escape, escapem))) def escape(x): return escape_pat.sub(lambda m: escapem[m.group()], x.replace('\\\\', '\x01')) unescapem = {v:k[1] for k, v in iteritems(escapem)} unescape_pat = re.compile('|'.join(unescapem)) def unescape(x): return unescape_pat.sub(lambda m: unescapem[m.group()], x) return escape, unescape class TabStop(str): def __new__(self, raw, start_offset, tab_stops, is_toplevel=True): if raw.endswith('}'): unescape = escape_funcs()[1] num, default = raw[2:-1].partition(':')[0::2] # Look for tab stops defined in the default text uraw, child_stops = parse_template(unescape(default), start_offset=start_offset, is_toplevel=False, grouped=False) for c in child_stops: c.parent = self tab_stops.extend(child_stops) self = str.__new__(self, uraw) if num.endswith('*'): self.takes_selection = True num = num[:-1] else: self.takes_selection = False self.num = int(num) else: self = str.__new__(self, '') self.num = int(raw[1:]) self.takes_selection = False self.start = start_offset self.is_toplevel = is_toplevel self.is_mirror = False self.parent = None tab_stops.append(self) return self def __repr__(self): return 'TabStop(text=%s num=%d start=%d is_mirror=%s takes_selection=%s is_toplevel=%s)' % ( str.__repr__(self), self.num, self.start, self.is_mirror, self.takes_selection, self.is_toplevel) def parse_template(template, start_offset=0, is_toplevel=True, grouped=True): escape, unescape = escape_funcs() template = escape(template) pos, parts, tab_stops = start_offset, [], [] for part in re.split(r'(\$(?:\d+|\{[^}]+\}))', template): is_tab_stop = part.startswith('$') if is_tab_stop: ts = TabStop(part, pos, tab_stops, is_toplevel=is_toplevel) parts.append(ts) else: parts.append(unescape(part)) pos += string_length(parts[-1]) if grouped: key = attrgetter('num') tab_stops.sort(key=key) ans = OrderedDict() for num, stops in groupby(tab_stops, key): stops = tuple(stops) for ts in stops[1:]: ts.is_mirror = True ans[num] = stops tab_stops = ans return ''.join(parts), tab_stops # }}} _snippets = None user_snippets = JSONConfig('editor_snippets') def snippets(refresh=False): global _snippets if _snippets is None or refresh: _snippets = copy.deepcopy(builtin_snippets) for snip in user_snippets.get('snippets', []): if snip['trigger'] and isinstance(snip['trigger'], str): key = snip_key(snip['trigger'], *snip['syntaxes']) _snippets[key] = {'template':snip['template'], 'description':snip['description']} _snippets = sorted(iteritems(_snippets), key=(lambda key_snip:string_length(key_snip[0].trigger)), reverse=True) return _snippets # Editor integration {{{ class EditorTabStop: def __init__(self, left, tab_stops, editor): self.editor = weakref.ref(editor) tab_stop = tab_stops[0] self.num = tab_stop.num self.is_mirror = tab_stop.is_mirror self.is_deleted = False self.is_toplevel = tab_stop.is_toplevel self.takes_selection = tab_stop.takes_selection self.left = left + tab_stop.start l = string_length(tab_stop) self.right = self.left + l self.mirrors = tuple(EditorTabStop(left, [ts], editor) for ts in tab_stops[1:]) self.ignore_position_update = False self.join_previous_edit = False self.transform = None self.has_transform = self.transform is not None def __enter__(self): self.join_previous_edit = True def __exit__(self, *args): self.join_previous_edit = False def __repr__(self): return 'EditorTabStop(num={!r} text={!r} left={!r} right={!r} is_deleted={!r} mirrors={!r})'.format( self.num, self.text, self.left, self.right, self.is_deleted, self.mirrors) __str__ = __unicode__ = __repr__ def apply_selected_text(self, text): if self.takes_selection and not self.is_deleted: with self: self.text = text for m in self.mirrors: with m: m.text = text @property def text(self): editor = self.editor() if editor is None or self.is_deleted: return '' c = editor.textCursor() c.setPosition(self.left), c.setPosition(self.right, QTextCursor.MoveMode.KeepAnchor) return editor.selected_text_from_cursor(c) @text.setter def text(self, text): editor = self.editor() if editor is None or self.is_deleted: return c = editor.textCursor() c.joinPreviousEditBlock() if self.join_previous_edit else c.beginEditBlock() c.setPosition(self.left), c.setPosition(self.right, QTextCursor.MoveMode.KeepAnchor) c.insertText(text) c.endEditBlock() def set_editor_cursor(self, editor): if not self.is_deleted: c = editor.textCursor() c.setPosition(self.left), c.setPosition(self.right, QTextCursor.MoveMode.KeepAnchor) editor.setTextCursor(c) def contained_in(self, left, right): return contains(left, right, self.left, self.right) def contains(self, left, right): return contains(self.left, self.right, left, right) def update_positions(self, position, chars_removed, chars_added): for m in self.mirrors: m.update_positions(position, chars_removed, chars_added) if position > self.right or self.is_deleted or self.ignore_position_update: return # First handle deletions if chars_removed > 0: if self.contained_in(position, position + chars_removed): self.is_deleted = True return if position <= self.left: self.left = max(self.left - chars_removed, position) if position <= self.right: self.right = max(self.right - chars_removed, position) if chars_added > 0: if position < self.left: self.left += chars_added if position <= self.right: self.right += chars_added class Template(list): def __new__(self, tab_stops): self = list.__new__(self) self.left_most_ts = self.right_most_ts = None self.extend(tab_stops) for c in self: if self.left_most_ts is None or self.left_most_ts.left > c.left: self.left_most_ts = c if self.right_most_ts is None or self.right_most_ts.right <= c.right: self.right_most_ts = c self.has_tab_stops = bool(self) self.active_tab_stop = None return self @property def left_most_position(self): return getattr(self.left_most_ts, 'left', None) @property def right_most_position(self): return getattr(self.right_most_ts, 'right', None) def contains_cursor(self, cursor): if not self.has_tab_stops: return False pos = cursor.position() if self.left_most_position <= pos <= self.right_most_position: return True return False def jump_to_next(self, editor): if self.active_tab_stop is None: self.active_tab_stop = ts = self.find_closest_tab_stop(editor.textCursor().position()) if ts is not None: ts.set_editor_cursor(editor) return ts ts = self.active_tab_stop if not ts.is_deleted: if ts.has_transform: ts.text = ts.transform(ts.text) for m in ts.mirrors: if not m.is_deleted: m.text = ts.text for x in self: if x.num > ts.num and not x.is_deleted: self.active_tab_stop = x x.set_editor_cursor(editor) return x def remains_active(self): if self.active_tab_stop is None: return False ts = self.active_tab_stop for x in self: if x.num > ts.num and not x.is_deleted: return True return bool(ts.mirrors) or ts.has_transform def find_closest_tab_stop(self, position): ans = dist = None for c in self: x = min(abs(c.left - position), abs(c.right - position)) if ans is None or x < dist: dist, ans = x, c return ans def expand_template(editor, trigger, template): c = editor.textCursor() c.beginEditBlock() c.setPosition(c.position()) right = c.position() left = right - string_length(trigger) text, tab_stops = parse_template(template) c.setPosition(left), c.setPosition(right, QTextCursor.MoveMode.KeepAnchor), c.insertText(text) editor_tab_stops = [EditorTabStop(left, ts, editor) for ts in itervalues(tab_stops)] tl = Template(editor_tab_stops) if tl.has_tab_stops: tl.active_tab_stop = ts = editor_tab_stops[0] ts.set_editor_cursor(editor) else: editor.setTextCursor(c) c.endEditBlock() return tl def find_matching_snip(text, syntax=None, snip_func=None): ans_snip = ans_trigger = None for key, snip in (snip_func or snippets)(): if text.endswith(key.trigger) and (syntax in key.syntaxes or syntax is None): ans_snip, ans_trigger = snip, key.trigger break return ans_snip, ans_trigger class SnippetManager(QObject): def __init__(self, editor): QObject.__init__(self, editor) self.active_templates = [] self.last_selected_text = '' editor.document().contentsChange.connect(self.contents_changed) self.snip_func = None def contents_changed(self, position, chars_removed, chars_added): for template in self.active_templates: for ets in template: ets.update_positions(position, chars_removed, chars_added) def get_active_template(self, cursor): remove = [] at = None pos = cursor.position() for template in self.active_templates: if at is None and template.contains_cursor(cursor): at = template elif pos > template.right_most_position or pos < template.left_most_position: remove.append(template) for template in remove: self.active_templates.remove(template) return at def handle_key_press(self, ev): editor = self.parent() if ev.key() == KEY and ev.modifiers() & MODIFIER: at = self.get_active_template(editor.textCursor()) if at is not None: if at.jump_to_next(editor) is None: self.active_templates.remove(at) else: if not at.remains_active(): self.active_templates.remove(at) ev.accept() return True lst, self.last_selected_text = self.last_selected_text, editor.selected_text if self.last_selected_text: editor.textCursor().insertText('') ev.accept() return True c, text = get_text_before_cursor(editor) snip, trigger = find_matching_snip(text, editor.syntax, self.snip_func) if snip is None: error_dialog(self.parent(), _('No snippet found'), _( 'No matching snippet was found'), show=True) self.last_selected_text = self.last_selected_text or lst return True template = expand_template(editor, trigger, snip['template']) if template.has_tab_stops: self.active_templates.append(template) if lst: for ts in template: ts.apply_selected_text(lst) ev.accept() return True return False # }}} # Config {{{ class SnippetTextEdit(PlainTextEdit): def __init__(self, text, parent=None): PlainTextEdit.__init__(self, parent) if text: self.setPlainText(text) self.snippet_manager = SnippetManager(self) def keyPressEvent(self, ev): if self.snippet_manager.handle_key_press(ev): return PlainTextEdit.keyPressEvent(self, ev) class EditSnippet(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QGridLayout(self) def add_row(*args): r = l.rowCount() if len(args) == 1: l.addWidget(args[0], r, 0, 1, 2) else: la = QLabel(args[0]) l.addWidget(la, r, 0, Qt.AlignmentFlag.AlignRight), l.addWidget(args[1], r, 1) la.setBuddy(args[1]) self.heading = la = QLabel('<h2>\xa0') add_row(la) self.helpl = la = QLabel(_('For help with snippets, see the <a href="%s">User Manual</a>') % localize_user_manual_link('https://manual.calibre-ebook.com/snippets.html')) la.setOpenExternalLinks(True) add_row(la) self.name = n = QLineEdit(self) n.setPlaceholderText(_('The name of this snippet')) add_row(_('&Name:'), n) self.trig = t = QLineEdit(self) t.setPlaceholderText(_('The text used to trigger this snippet')) add_row(_('Tri&gger:'), t) self.template = t = PlainTextEdit(self) la.setBuddy(t) add_row(_('&Template:'), t) self.types = t = QListWidget(self) t.setFlow(QListView.Flow.LeftToRight) t.setWrapping(True), t.setResizeMode(QListView.ResizeMode.Adjust), t.setSpacing(5) fm = t.fontMetrics() t.setMaximumHeight(2*(fm.ascent() + fm.descent()) + 25) add_row(_('&File types:'), t) t.setToolTip(_('Which file types this snippet should be active in')) self.frame = f = QFrame(self) f.setFrameShape(QFrame.Shape.HLine) add_row(f) self.test = d = SnippetTextEdit('', self) d.snippet_manager.snip_func = self.snip_func d.setToolTip(_('You can test your snippet here')) d.setMaximumHeight(t.maximumHeight() + 15) add_row(_('T&est:'), d) i = QListWidgetItem(_('All'), t) i.setData(Qt.ItemDataRole.UserRole, '*') i.setCheckState(Qt.CheckState.Checked) i.setFlags(i.flags() | Qt.ItemFlag.ItemIsUserCheckable) for ftype in sorted(all_text_syntaxes): i = QListWidgetItem(ftype, t) i.setData(Qt.ItemDataRole.UserRole, ftype) i.setCheckState(Qt.CheckState.Checked) i.setFlags(i.flags() | Qt.ItemFlag.ItemIsUserCheckable) self.creating_snippet = False def snip_func(self): key = snip_key(self.trig.text(), '*') return ((key, self.snip),) def apply_snip(self, snip, creating_snippet=None): self.creating_snippet = not snip if creating_snippet is None else creating_snippet self.heading.setText('<h2>' + (_('Create a snippet') if self.creating_snippet else _('Edit snippet'))) snip = snip or {} self.name.setText(snip.get('description') or '') self.trig.setText(snip.get('trigger') or '') self.template.setPlainText(snip.get('template') or '') ftypes = snip.get('syntaxes', ()) for i in range(self.types.count()): i = self.types.item(i) ftype = i.data(Qt.ItemDataRole.UserRole) i.setCheckState(Qt.CheckState.Checked if ftype in ftypes else Qt.CheckState.Unchecked) if self.creating_snippet and not ftypes: self.types.item(0).setCheckState(Qt.CheckState.Checked) (self.name if self.creating_snippet else self.template).setFocus(Qt.FocusReason.OtherFocusReason) @property def snip(self): ftypes = [] for i in range(self.types.count()): i = self.types.item(i) if i.checkState() == Qt.CheckState.Checked: ftypes.append(i.data(Qt.ItemDataRole.UserRole)) return {'description':self.name.text().strip(), 'trigger':self.trig.text(), 'template':self.template.toPlainText(), 'syntaxes':ftypes} @snip.setter def snip(self, snip): self.apply_snip(snip) def validate(self): snip = self.snip err = None if not snip['description']: err = _('You must provide a name for this snippet') elif not snip['trigger']: err = _('You must provide a trigger for this snippet') elif not snip['template']: err = _('You must provide a template for this snippet') elif not snip['syntaxes']: err = _('You must specify at least one file type') return err class UserSnippets(Dialog): def __init__(self, parent=None): Dialog.__init__(self, _('Create/edit snippets'), 'snippet-editor', parent=parent) self.setWindowIcon(QIcon.ic('snippets.png')) def setup_ui(self): self.setWindowIcon(QIcon.ic('modified.png')) self.l = l = QVBoxLayout(self) self.stack = s = QStackedLayout() l.addLayout(s), l.addWidget(self.bb) self.listc = c = QWidget(self) s.addWidget(c) c.l = l = QVBoxLayout(c) c.h = h = QHBoxLayout() l.addLayout(h) self.search_bar = sb = QLineEdit(self) sb.setPlaceholderText(_('Search for a snippet')) h.addWidget(sb) self.next_button = b = QPushButton(_('&Next')) b.clicked.connect(self.find_next) h.addWidget(b) c.h2 = h = QHBoxLayout() l.addLayout(h) self.snip_list = sl = QListWidget(self) sl.doubleClicked.connect(self.edit_snippet) h.addWidget(sl) c.l2 = l = QVBoxLayout() h.addLayout(l) self.add_button = b = QToolButton(self) b.setIcon(QIcon.ic('plus.png')), b.setText(_('&Add snippet')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextUnderIcon) b.clicked.connect(self.add_snippet) l.addWidget(b) self.edit_button = b = QToolButton(self) b.setIcon(QIcon.ic('modified.png')), b.setText(_('&Edit snippet')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextUnderIcon) b.clicked.connect(self.edit_snippet) l.addWidget(b) self.add_button = b = QToolButton(self) b.setIcon(QIcon.ic('minus.png')), b.setText(_('&Remove snippet')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextUnderIcon) b.clicked.connect(self.remove_snippet) l.addWidget(b) self.add_button = b = QToolButton(self) b.setIcon(QIcon.ic('config.png')), b.setText(_('Change &built-in')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextUnderIcon) b.clicked.connect(self.change_builtin) l.addWidget(b) for i, snip in enumerate(sorted(user_snippets.get('snippets', []), key=itemgetter('trigger'))): item = self.snip_to_item(snip) if i == 0: self.snip_list.setCurrentItem(item) self.edit_snip = es = EditSnippet(self) self.stack.addWidget(es) def snip_to_text(self, snip): return '{} - {}'.format(snip['trigger'], snip['description']) def snip_to_item(self, snip): i = QListWidgetItem(self.snip_to_text(snip), self.snip_list) i.setData(Qt.ItemDataRole.UserRole, copy.deepcopy(snip)) return i def reject(self): if self.stack.currentIndex() > 0: self.stack.setCurrentIndex(0) return return Dialog.reject(self) def accept(self): if self.stack.currentIndex() > 0: err = self.edit_snip.validate() if err is None: self.stack.setCurrentIndex(0) if self.edit_snip.creating_snippet: item = self.snip_to_item(self.edit_snip.snip) else: item = self.snip_list.currentItem() snip = self.edit_snip.snip item.setText(self.snip_to_text(snip)) item.setData(Qt.ItemDataRole.UserRole, snip) self.snip_list.setCurrentItem(item) self.snip_list.scrollToItem(item) else: error_dialog(self, _('Invalid snippet'), err, show=True) return user_snippets['snippets'] = [self.snip_list.item(i).data(Qt.ItemDataRole.UserRole) for i in range(self.snip_list.count())] snippets(refresh=True) return Dialog.accept(self) def sizeHint(self): return QSize(900, 600) def edit_snippet(self, *args): item = self.snip_list.currentItem() if item is None: return error_dialog(self, _('Cannot edit snippet'), _('No snippet selected'), show=True) self.stack.setCurrentIndex(1) self.edit_snip.snip = item.data(Qt.ItemDataRole.UserRole) def add_snippet(self, *args): self.stack.setCurrentIndex(1) self.edit_snip.snip = None def remove_snippet(self, *args): item = self.snip_list.currentItem() if item is not None: self.snip_list.takeItem(self.snip_list.row(item)) def find_next(self, *args): q = self.search_bar.text().strip() if not q: return matches = self.snip_list.findItems(q, Qt.MatchFlag.MatchContains | Qt.MatchFlag.MatchWrap) if len(matches) < 1: return error_dialog(self, _('No snippets found'), _( 'No snippets found for query: %s') % q, show=True) ci = self.snip_list.currentItem() try: item = matches[(matches.index(ci) + 1) % len(matches)] except Exception: item = matches[0] self.snip_list.setCurrentItem(item) self.snip_list.scrollToItem(item) def change_builtin(self): d = QDialog(self) lw = QListWidget(d) for (trigger, syntaxes), snip in iteritems(builtin_snippets): snip = copy.deepcopy(snip) snip['trigger'], snip['syntaxes'] = trigger, syntaxes i = QListWidgetItem(self.snip_to_text(snip), lw) i.setData(Qt.ItemDataRole.UserRole, snip) d.l = l = QVBoxLayout(d) l.addWidget(QLabel(_('Choose the built-in snippet to modify:'))) l.addWidget(lw) lw.itemDoubleClicked.connect(d.accept) d.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) l.addWidget(bb) bb.accepted.connect(d.accept), bb.rejected.connect(d.reject) if d.exec() == QDialog.DialogCode.Accepted and lw.currentItem() is not None: self.stack.setCurrentIndex(1) self.edit_snip.apply_snip(lw.currentItem().data(Qt.ItemDataRole.UserRole), creating_snippet=True) # }}} if __name__ == '__main__': from calibre.gui2 import Application app = Application([]) d = UserSnippets() d.exec() del app
26,928
Python
.py
626
33.698083
142
0.608272
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,727
themes.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/themes.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' from collections import namedtuple from qt.core import ( QApplication, QBrush, QCheckBox, QColor, QColorDialog, QComboBox, QDialog, QDialogButtonBox, QFont, QFormLayout, QHBoxLayout, QIcon, QLabel, QLineEdit, QPalette, QPixmap, QPushButton, QScrollArea, QSize, QSplitter, Qt, QTextCharFormat, QToolButton, QVBoxLayout, QWidget, pyqtSignal, ) from calibre.gui2 import error_dialog from calibre.gui2.tweak_book import tprefs from calibre.gui2.tweak_book.editor import syntax_text_char_format from calibre.gui2.tweak_book.widgets import Dialog from polyglot.builtins import iteritems underline_styles = {'single', 'dash', 'dot', 'dash_dot', 'dash_dot_dot', 'wave', 'spell'} _default_theme = None def default_theme(): global _default_theme if _default_theme is None: isdark = QApplication.instance().palette().color(QPalette.ColorRole.WindowText).lightness() > 128 _default_theme = 'wombat-dark' if isdark else 'pyte-light' return _default_theme # The solarized themes {{{ SLDX = {'base03':'1c1c1c', 'base02':'262626', 'base01':'585858', 'base00':'626262', 'base0':'808080', 'base1':'8a8a8a', 'base2':'e4e4e4', 'base3':'ffffd7', 'yellow':'af8700', 'orange':'d75f00', 'red':'d70000', 'magenta':'af005f', 'violet':'5f5faf', 'blue':'0087ff', 'cyan':'00afaf', 'green':'5f8700'} # noqa SLD = {'base03':'002b36', 'base02':'073642', 'base01':'586e75', 'base00':'657b83', 'base0':'839496', 'base1':'93a1a1', 'base2':'eee8d5', 'base3':'fdf6e3', 'yellow':'b58900', 'orange':'cb4b16', 'red':'dc322f', 'magenta':'d33682', 'violet':'6c71c4', 'blue':'268bd2', 'cyan':'2aa198', 'green':'859900'} # noqa m = {'base%d'%n:'base%02d'%n for n in range(1, 4)} m.update({'base%02d'%n:'base%d'%n for n in range(1, 4)}) SLL = {m.get(k, k) : v for k, v in iteritems(SLD)} SLLX = {m.get(k, k) : v for k, v in iteritems(SLDX)} SOLARIZED = \ ''' CursorLine bg={base02} CursorColumn bg={base02} ColorColumn bg={base02} HighlightRegion bg={base00} MatchParen bg={base02} fg={magenta} Pmenu fg={base0} bg={base02} PmenuSel fg={base01} bg={base2} Cursor fg={base03} bg={base0} Normal fg={base0} bg={base02} LineNr fg={base01} bg={base02} LineNrC fg={magenta} Visual fg={base01} bg={base03} Comment fg={base01} italic Todo fg={magenta} bold String fg={cyan} Constant fg={cyan} Number fg={cyan} PreProc fg={orange} Identifier fg={blue} Function fg={blue} Type fg={yellow} Statement fg={green} bold Keyword fg={green} Special fg={red} SpecialCharacter bg={base03} Error us=wave uc={red} SpellError us=wave uc={orange} Tooltip fg=black bg=ffffed Link fg={blue} BadLink fg={cyan} us=wave uc={red} DiffDelete bg={base02} fg={red} DiffInsert bg={base02} fg={green} DiffReplace bg={base02} fg={blue} DiffReplaceReplace bg={base03} ''' # }}} THEMES = { 'wombat-dark': # {{{ ''' CursorLine bg={cursor_loc} CursorColumn bg={cursor_loc} ColorColumn bg={cursor_loc} HighlightRegion bg=3d3d3d MatchParen bg=444444 Pmenu fg=f6f3e8 bg=444444 PmenuSel fg=yellow bg={identifier} Tooltip fg=black bg=ffffed Cursor bg=656565 Normal fg=f6f3e8 bg=242424 LineNr fg=857b6f bg=000000 LineNrC fg=yellow Visual fg=black bg=888888 Comment fg={comment} Todo fg=8f8f8f String fg={string} Constant fg={constant} Number fg={constant} PreProc fg={constant} Identifier fg={identifier} Function fg={identifier} Type fg={identifier} Statement fg={keyword} Keyword fg={keyword} Special fg={special} Error us=wave uc=red SpellError us=wave uc=orange SpecialCharacter bg=666666 Link fg=cyan BadLink fg={string} us=wave uc=red DiffDelete bg=341414 fg=642424 DiffInsert bg=143414 fg=246424 DiffReplace bg=141434 fg=242464 DiffReplaceReplace bg=002050 '''.format( cursor_loc='323232', identifier='cae682', comment='99968b', string='95e454', keyword='8ac6f2', constant='e5786d', special='e7f6da'), # }}} 'pyte-light': # {{{ ''' CursorLine bg={cursor_loc} CursorColumn bg={cursor_loc} ColorColumn bg={cursor_loc} HighlightRegion bg=E3F988 MatchParen bg=cfcfcf Pmenu fg=white bg=808080 PmenuSel fg=white bg=808080 Tooltip fg=black bg=ffffed Cursor fg=black bg=b0b4b8 Normal fg=404850 bg=f0f0f0 LineNr fg=white bg=8090a0 LineNrC fg=yellow Visual fg=white bg=8090a0 Comment fg={comment} italic Todo fg={comment} italic bold String fg={string} Constant fg={constant} Number fg={constant} PreProc fg={constant} Identifier fg={identifier} Function fg={identifier} Type fg={identifier} Statement fg={keyword} Keyword fg={keyword} Special fg={special} italic SpecialCharacter bg=afafaf Error us=wave uc=red SpellError us=wave uc=magenta Link fg=blue BadLink fg={string} us=wave uc=red DiffDelete bg=rgb(255,180,200) fg=rgb(200,80,110) DiffInsert bg=rgb(180,255,180) fg=rgb(80,210,80) DiffReplace bg=rgb(206,226,250) fg=rgb(90,130,180) DiffReplaceReplace bg=rgb(180,210,250) '''.format( cursor_loc='F8DE7E', identifier='7b5694', comment='a0b0c0', string='4070a0', keyword='007020', constant='a07040', special='70a0d0'), # }}} 'solarized-x-dark': SOLARIZED.format(**SLDX), 'solarized-dark': SOLARIZED.format(**SLD), 'solarized-light': SOLARIZED.format(**SLL), 'solarized-x-light': SOLARIZED.format(**SLLX), } def read_color(col): if QColor.isValidColor(col): return QBrush(QColor(col)) if col.startswith('rgb('): r, g, b = map(int, (x.strip() for x in col[4:-1].split(','))) return QBrush(QColor(r, g, b)) try: r, g, b = col[0:2], col[2:4], col[4:6] r, g, b = int(r, 16), int(g, 16), int(b, 16) return QBrush(QColor(r, g, b)) except Exception: pass Highlight = namedtuple('Highlight', 'fg bg bold italic underline underline_color') def read_theme(raw): ans = {} for line in raw.splitlines(): line = line.strip() if not line or line.startswith('#'): continue bold = italic = False fg = bg = name = underline = underline_color = None line = line.partition('#')[0] for i, token in enumerate(line.split()): if i == 0: name = token else: if token == 'bold': bold = True elif token == 'italic': italic = True elif '=' in token: prefix, val = token.partition('=')[0::2] if prefix == 'us': underline = val if val in underline_styles else None elif prefix == 'uc': underline_color = read_color(val) elif prefix == 'fg': fg = read_color(val) elif prefix == 'bg': bg = read_color(val) if name is not None: ans[name] = Highlight(fg, bg, bold, italic, underline, underline_color) return ans THEMES = {k:read_theme(raw) for k, raw in iteritems(THEMES)} def u(x): x = {'spell':'SpellCheck', 'dash_dot':'DashDot', 'dash_dot_dot':'DashDotDot'}.get(x, x.capitalize()) if 'Dot' in x: return x + 'Line' return x + 'Underline' underline_styles = {x:getattr(QTextCharFormat.UnderlineStyle, u(x)) for x in underline_styles} def to_highlight(data): data = data.copy() for c in ('fg', 'bg', 'underline_color'): data[c] = read_color(data[c]) if data.get(c, None) is not None else None return Highlight(**data) def read_custom_theme(data): dt = THEMES[default_theme()].copy() dt.update({k:to_highlight(v) for k, v in iteritems(data)}) return dt def get_theme(name): try: return THEMES[name] except KeyError: try: ans = tprefs['custom_themes'][name] except KeyError: return THEMES[default_theme()] else: return read_custom_theme(ans) def highlight_to_char_format(h): ans = syntax_text_char_format() if h.bold: ans.setFontWeight(QFont.Weight.Bold) if h.italic: ans.setFontItalic(True) if h.fg is not None: ans.setForeground(h.fg) if h.bg is not None: ans.setBackground(h.bg) if h.underline: ans.setUnderlineStyle(underline_styles[h.underline]) if h.underline_color is not None: ans.setUnderlineColor(h.underline_color.color()) return ans def theme_color(theme, name, attr): try: return getattr(theme[name], attr).color() except (KeyError, AttributeError): return getattr(THEMES[default_theme()][name], attr).color() def theme_format(theme, name): try: h = theme[name] except KeyError: h = THEMES[default_theme()][name] return highlight_to_char_format(h) def custom_theme_names(): return tuple(tprefs['custom_themes']) def builtin_theme_names(): return tuple(THEMES) def all_theme_names(): return builtin_theme_names() + custom_theme_names() # Custom theme creation/editing {{{ class CreateNewTheme(Dialog): def __init__(self, parent=None): Dialog.__init__(self, _('Create custom theme'), 'custom-theme-create', parent=parent) def setup_ui(self): self.l = l = QFormLayout(self) self.setLayout(l) self._name = n = QLineEdit(self) l.addRow(_('&Name of custom theme:'), n) self.base = b = QComboBox(self) b.addItems(sorted(builtin_theme_names())) l.addRow(_('&Builtin theme to base on:'), b) idx = b.findText(tprefs['editor_theme'] or default_theme()) if idx == -1: idx = b.findText(default_theme()) b.setCurrentIndex(idx) l.addRow(self.bb) @property def theme_name(self): return str(self._name.text()).strip() def accept(self): if not self.theme_name: return error_dialog(self, _('No name specified'), _( 'You must specify a name for your theme'), show=True) if '*' + self.theme_name in custom_theme_names(): return error_dialog(self, _('Name already used'), _( 'A custom theme with the name %s already exists') % self.theme_name, show=True) return Dialog.accept(self) def col_to_string(color): return '%02X%02X%02X' % color.getRgb()[:3] class ColorButton(QPushButton): changed = pyqtSignal() def __init__(self, data, name, text, parent): QPushButton.__init__(self, text, parent) self.ic = QPixmap(self.iconSize()) color = data[name] self.data, self.name = data, name if color is not None: self.current_color = read_color(color).color() self.ic.fill(self.current_color) else: self.ic.fill(Qt.GlobalColor.transparent) self.current_color = color self.update_tooltip() self.setIcon(QIcon(self.ic)) self.clicked.connect(self.choose_color) def clear(self): self.current_color = None self.update_tooltip() self.ic.fill(Qt.GlobalColor.transparent) self.setIcon(QIcon(self.ic)) self.data[self.name] = self.value self.changed.emit() def choose_color(self): col = QColorDialog.getColor(self.current_color or Qt.GlobalColor.black, self, _('Choose color')) if col.isValid(): self.current_color = col self.update_tooltip() self.ic.fill(col) self.setIcon(QIcon(self.ic)) self.data[self.name] = self.value self.changed.emit() def update_tooltip(self): self.setToolTip(_('Red: {0} Green: {1} Blue: {2}').format(*self.current_color.getRgb()[:3]) if self.current_color else _('No color')) @property def value(self): if self.current_color is None: return None return col_to_string(self.current_color) class Bool(QCheckBox): changed = pyqtSignal() def __init__(self, data, key, text, parent): QCheckBox.__init__(self, text, parent) self.data, self.key = data, key self.setChecked(data.get(key, False)) self.stateChanged.connect(self._changed) def _changed(self, state): self.data[self.key] = self.value self.changed.emit() @property def value(self): return self.checkState() == Qt.CheckState.Checked class Property(QWidget): changed = pyqtSignal() def __init__(self, name, data, parent=None): QWidget.__init__(self, parent) self.l = l = QHBoxLayout(self) self.setLayout(l) self.label = QLabel(name) l.addWidget(self.label) self.data = data def create_color_button(key, text): b = ColorButton(data, key, text, self) b.changed.connect(self.changed), l.addWidget(b) bc = QToolButton(self) bc.setIcon(QIcon.ic('clear_left.png')) bc.setToolTip(_('Remove color')) bc.clicked.connect(b.clear) h = QHBoxLayout() h.addWidget(b), h.addWidget(bc) return h for k, text in (('fg', _('&Foreground')), ('bg', _('&Background'))): h = create_color_button(k, text) l.addLayout(h) for k, text in (('bold', _('B&old')), ('italic', _('&Italic'))): w = Bool(data, k, text, self) w.changed.connect(self.changed) l.addWidget(w) self.underline = us = QComboBox(self) us.addItems(sorted(tuple(underline_styles) + ('',))) idx = us.findText(data.get('underline', '') or '') us.setCurrentIndex(max(idx, 0)) us.currentIndexChanged.connect(self.us_changed) self.la = la = QLabel(_('&Underline:')) la.setBuddy(us) h = QHBoxLayout() h.addWidget(la), h.addWidget(us), l.addLayout(h) h = create_color_button('underline_color', _('Color')) l.addLayout(h) l.addStretch(1) def us_changed(self): self.data['underline'] = str(self.underline.currentText()) or None self.changed.emit() # Help text {{{ HELP_TEXT = _('''\ <h2>Creating a custom theme</h2> <p id="attribute" lang="und">You can create a custom syntax highlighting theme, \ with your own colors and font styles. The most important types of highlighting \ rules are described below. Note that not every rule supports every kind of \ customization, for example, changing font or underline styles for the \ <code>Cursor</code> rule does not have any effect as that rule is used only for \ the color of the blinking cursor.</p> <p>As you make changes to your theme on the left, the changes will be reflected live in this panel.</p> <p xml:lang="und"> {Normal} The most important rule. Sets the foreground and background colors for the \ editor as well as the style of "normal" text, that is, text that does not match any special syntax. {Visual} Defines the colors for text selected by the mouse. {CursorLine} Defines the color for the line containing the cursor. {LineNr} Defines the colors for the line numbers on the left. {MatchParen} Defines the colors for matching tags in HTML and matching braces in CSS. {Function} Used for highlighting tags in HTML {Type} Used for highlighting attributes in HTML {Statement} Tag names in HTML {Constant} Namespace prefixes in XML and constants in CSS {SpecialCharacter} Non{endash}breaking{nbsp}spaces/hyphens in HTML {Error} Syntax errors such as <this <> {SpellError} Misspelled words such as <span lang="en">thisword</span> {Comment} Comments like <!-- this one --> </p> <style type="text/css"> /* Some CSS so you can see how the highlighting rules affect it */ p.someclass {{ font-family: serif; font-size: 12px; line-height: 1.2; }} </style> ''') # }}} class ThemeEditor(Dialog): def __init__(self, parent=None): Dialog.__init__(self, _('Create/edit custom theme'), 'custom-theme-editor', parent=parent) def setup_ui(self): self.block_show = False self.properties = [] self.l = l = QVBoxLayout(self) self.setLayout(l) h = QHBoxLayout() l.addLayout(h) self.la = la = QLabel(_('&Edit theme:')) h.addWidget(la) self.theme = t = QComboBox(self) la.setBuddy(t) t.addItems(sorted(custom_theme_names())) t.setMinimumWidth(200) if t.count() > 0: t.setCurrentIndex(0) t.currentIndexChanged.connect(self.show_theme) h.addWidget(t) self.add_button = b = QPushButton(QIcon.ic('plus.png'), _('Add &new theme'), self) b.clicked.connect(self.create_new_theme) h.addWidget(b) self.remove_button = b = QPushButton(QIcon.ic('minus.png'), _('&Remove theme'), self) b.clicked.connect(self.remove_theme) h.addWidget(b) h.addStretch(1) self.scroll = s = QScrollArea(self) self.w = w = QWidget(self) s.setWidget(w), s.setWidgetResizable(True) self.cl = cl = QVBoxLayout() w.setLayout(cl) from calibre.gui2.tweak_book.editor.text import TextEdit self.preview = p = TextEdit(self, expected_geometry=(73, 50)) t = {x: f'<b>{x}</b>' for x in ( 'Normal', 'Visual', 'CursorLine', 'LineNr', 'MatchParen', 'Function', 'Type', 'Statement', 'Constant', 'SpecialCharacter', 'Error', 'SpellError', 'Comment') } t['nbsp'] = '\xa0' t['endash'] = '–' p.load_text(HELP_TEXT.format(**t)) p.setMaximumWidth(p.size_hint.width() + 5) s.setMinimumWidth(600) self.splitter = sp = QSplitter(self) l.addWidget(sp) sp.addWidget(s), sp.addWidget(p) self.bb.clear() self.bb.addButton(QDialogButtonBox.StandardButton.Close) l.addWidget(self.bb) if self.theme.count() > 0: self.show_theme() def update_theme(self, name): data = tprefs['custom_themes'][name] extra = set(data) - set(THEMES[default_theme()]) missing = set(THEMES[default_theme()]) - set(data) for k in extra: data.pop(k) for k in missing: data[k] = dict(THEMES[default_theme()][k]._asdict()) for nk, nv in iteritems(data[k]): if isinstance(nv, QBrush): data[k][nk] = str(nv.color().name()) if extra or missing: tprefs['custom_themes'][name] = data return data def show_theme(self): if self.block_show: return for c in self.properties: c.changed.disconnect() self.cl.removeWidget(c) c.setParent(None) c.deleteLater() self.properties = [] name = str(self.theme.currentText()) if not name: return data = self.update_theme(name) maxw = 0 for k in sorted(data): w = Property(k, data[k], parent=self) w.changed.connect(self.changed) self.properties.append(w) maxw = max(maxw, w.label.sizeHint().width()) self.cl.addWidget(w) for p in self.properties: p.label.setMinimumWidth(maxw), p.label.setMaximumWidth(maxw) self.preview.apply_theme(read_custom_theme(data)) @property def theme_name(self): return str(self.theme.currentText()) def changed(self): name = self.theme_name data = self.update_theme(name) self.preview.apply_theme(read_custom_theme(data)) def create_new_theme(self): d = CreateNewTheme(self) if d.exec() == QDialog.DialogCode.Accepted: name = '*' + d.theme_name base = str(d.base.currentText()) theme = {} for key, val in iteritems(THEMES[base]): theme[key] = {k:col_to_string(v.color()) if isinstance(v, QBrush) else v for k, v in iteritems(val._asdict())} tprefs['custom_themes'][name] = theme tprefs['custom_themes'] = tprefs['custom_themes'] t = self.theme self.block_show = True t.clear(), t.addItems(sorted(custom_theme_names())) t.setCurrentIndex(t.findText(name)) self.block_show = False self.show_theme() def remove_theme(self): name = self.theme_name if name: tprefs['custom_themes'].pop(name, None) tprefs['custom_themes'] = tprefs['custom_themes'] t = self.theme self.block_show = True t.clear(), t.addItems(sorted(custom_theme_names())) if t.count() > 0: t.setCurrentIndex(0) self.block_show = False self.show_theme() def sizeHint(self): g = self.screen().availableSize() return QSize(min(1500, g.width() - 25), 650) # }}} if __name__ == '__main__': from calibre.gui2 import Application app = Application([]) d = ThemeEditor() d.exec() del app
22,074
Python
.py
591
29.8511
308
0.601499
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,728
image.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/image.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' import sys from qt.core import ( QApplication, QCheckBox, QDialog, QDialogButtonBox, QFormLayout, QIcon, QInputDialog, QLabel, QMainWindow, QMenu, QSize, QSpinBox, Qt, QToolButton, pyqtSignal, ) from calibre.gui2 import error_dialog from calibre.gui2.tweak_book import actions, editors, tprefs from calibre.gui2.tweak_book.editor.canvas import Canvas from calibre.startup import connect_lambda from polyglot.builtins import itervalues class ResizeDialog(QDialog): # {{{ def __init__(self, width, height, parent=None): QDialog.__init__(self, parent) self.l = l = QFormLayout(self) self.setLayout(l) self.aspect_ratio = width / float(height) l.addRow(QLabel(_('Choose the new width and height'))) self._width = w = QSpinBox(self) w.setMinimum(1) w.setMaximum(10 * width) w.setValue(width) w.setSuffix(' px') l.addRow(_('&Width:'), w) self._height = h = QSpinBox(self) h.setMinimum(1) h.setMaximum(10 * height) h.setValue(height) h.setSuffix(' px') l.addRow(_('&Height:'), h) connect_lambda(w.valueChanged, self, lambda self: self.keep_ar('width')) connect_lambda(h.valueChanged, self, lambda self: self.keep_ar('height')) self.ar = ar = QCheckBox(_('Keep &aspect ratio')) ar.setChecked(True) l.addRow(ar) self.resize(self.sizeHint()) self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) l.addRow(bb) def keep_ar(self, which): if self.ar.isChecked(): val = getattr(self, which) oval = val / self.aspect_ratio if which == 'width' else val * self.aspect_ratio other = getattr(self, '_height' if which == 'width' else '_width') other.blockSignals(True) other.setValue(int(oval)) other.blockSignals(False) @property def width(self): return self._width.value() @width.setter def width(self, val): self._width.setValue(val) @property def height(self): return self._height.value() @height.setter def height(self, val): self._height.setValue(val) # }}} class Editor(QMainWindow): has_line_numbers = False modification_state_changed = pyqtSignal(object) undo_redo_state_changed = pyqtSignal(object, object) data_changed = pyqtSignal(object) cursor_position_changed = pyqtSignal() # dummy copy_available_state_changed = pyqtSignal(object) def __init__(self, syntax, parent=None): QMainWindow.__init__(self, parent) if parent is None: self.setWindowFlags(Qt.WindowType.Widget) self.is_synced_to_container = False self.syntax = syntax self._is_modified = False self.copy_available = self.cut_available = False self.quality = 90 self.canvas = Canvas(self) self.setCentralWidget(self.canvas) self.create_toolbars() self.canvas.image_changed.connect(self.image_changed) self.canvas.undo_redo_state_changed.connect(self.undo_redo_state_changed) self.canvas.selection_state_changed.connect(self.update_clipboard_actions) @property def is_modified(self): return self._is_modified @is_modified.setter def is_modified(self, val): self._is_modified = val self.modification_state_changed.emit(val) @property def current_editing_state(self): return {} @current_editing_state.setter def current_editing_state(self, val): pass @property def undo_available(self): return self.canvas.undo_action.isEnabled() @property def redo_available(self): return self.canvas.redo_action.isEnabled() @property def current_line(self): return 0 @current_line.setter def current_line(self, val): pass @property def number_of_lines(self): return 0 def pretty_print(self, name): return False def change_document_name(self, newname): pass def get_raw_data(self): return self.canvas.get_image_data(quality=self.quality) @property def data(self): return self.get_raw_data() @data.setter def data(self, val): self.canvas.load_image(val) self._is_modified = False # The image_changed signal will have been triggered causing this editor to be incorrectly marked as modified def replace_data(self, raw, only_if_different=True): self.canvas.load_image(raw, only_if_different=only_if_different) def apply_settings(self, prefs=None, dictionaries_changed=False): pass def go_to_line(self, *args, **kwargs): pass def save_state(self): for bar in self.bars: if bar.isFloating(): return tprefs['image-editor-state'] = bytearray(self.saveState()) def restore_state(self): state = tprefs.get('image-editor-state', None) if state is not None: self.restoreState(state) def set_focus(self): self.canvas.setFocus(Qt.FocusReason.OtherFocusReason) def undo(self): self.canvas.undo_action.trigger() def redo(self): self.canvas.redo_action.trigger() def copy(self): self.canvas.copy() def cut(self): return error_dialog(self, _('Not allowed'), _( 'Cutting of images is not allowed. If you want to delete the image, use' ' the files browser to do it.'), show=True) def paste(self): self.canvas.paste() # Search and replace {{{ def mark_selected_text(self, *args, **kwargs): pass def find(self, *args, **kwargs): return False def replace(self, *args, **kwargs): return False def all_in_marked(self, *args, **kwargs): return 0 @property def selected_text(self): return '' # }}} def image_changed(self, new_image): self.is_synced_to_container = False self._is_modified = True self.copy_available = self.canvas.is_valid self.copy_available_state_changed.emit(self.copy_available) self.data_changed.emit(self) self.modification_state_changed.emit(True) self.fmt_label.setText(' ' + (self.canvas.original_image_format or '').upper()) im = self.canvas.current_image self.size_label.setText('{} x {}{}'.format(im.width(), im.height(), ' px')) def break_cycles(self): self.canvas.break_cycles() self.canvas.image_changed.disconnect() self.canvas.undo_redo_state_changed.disconnect() self.canvas.selection_state_changed.disconnect() self.modification_state_changed.disconnect() self.undo_redo_state_changed.disconnect() self.data_changed.disconnect() self.cursor_position_changed.disconnect() self.copy_available_state_changed.disconnect() def contextMenuEvent(self, ev): ev.ignore() def create_toolbars(self): self.action_bar = b = self.addToolBar(_('File actions tool bar')) b.setObjectName('action_bar') # Needed for saveState for x in ('undo', 'redo'): b.addAction(getattr(self.canvas, '%s_action' % x)) self.edit_bar = b = self.addToolBar(_('Edit actions tool bar')) b.setObjectName('edit-actions-bar') for x in ('copy', 'paste'): ac = actions['editor-%s' % x] setattr(self, 'action_' + x, b.addAction(ac.icon(), x, getattr(self, x))) self.update_clipboard_actions() b.addSeparator() self.action_trim = ac = b.addAction(QIcon.ic('trim.png'), _('Trim image'), self.canvas.trim_image) self.action_rotate = ac = b.addAction(QIcon.ic('rotate-right.png'), _('Rotate image'), self.canvas.rotate_image) self.action_resize = ac = b.addAction(QIcon.ic('resize.png'), _('Resize image'), self.resize_image) b.addSeparator() self.action_filters = ac = b.addAction(QIcon.ic('filter.png'), _('Image filters')) b.widgetForAction(ac).setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup) self.filters_menu = m = QMenu(self) ac.setMenu(m) m.addAction(_('Auto-trim image'), self.canvas.autotrim_image) m.addAction(_('Sharpen image'), self.sharpen_image) m.addAction(_('Blur image'), self.blur_image) m.addAction(_('De-speckle image'), self.canvas.despeckle_image) m.addAction(_('Improve contrast (normalize image)'), self.canvas.normalize_image) m.addAction(_('Make image look like an oil painting'), self.oilify_image) self.info_bar = b = self.addToolBar(_('Image information bar')) b.setObjectName('image_info_bar') self.fmt_label = QLabel('') b.addWidget(self.fmt_label) b.addSeparator() self.size_label = QLabel('') b.addWidget(self.size_label) self.bars = [self.action_bar, self.edit_bar, self.info_bar] for x in self.bars: x.setFloatable(False) x.topLevelChanged.connect(self.toolbar_floated) x.setIconSize(QSize(tprefs['toolbar_icon_size'], tprefs['toolbar_icon_size'])) self.restore_state() def toolbar_floated(self, floating): if not floating: self.save_state() for ed in itervalues(editors): if ed is not self: ed.restore_state() def update_clipboard_actions(self, *args): if self.canvas.has_selection: self.action_copy.setText(_('Copy selected region')) self.action_paste.setText(_('Paste into selected region')) else: self.action_copy.setText(_('Copy image')) self.action_paste.setText(_('Paste image')) def resize_image(self): im = self.canvas.current_image d = ResizeDialog(im.width(), im.height(), self) if d.exec() == QDialog.DialogCode.Accepted: self.canvas.resize_image(d.width, d.height) def sharpen_image(self): val, ok = QInputDialog.getInt(self, _('Sharpen image'), _( 'The standard deviation for the Gaussian sharpen operation (higher means more sharpening)'), value=3, min=1, max=20) if ok: self.canvas.sharpen_image(sigma=val) def blur_image(self): val, ok = QInputDialog.getInt(self, _('Blur image'), _( 'The standard deviation for the Gaussian blur operation (higher means more blurring)'), value=3, min=1, max=20) if ok: self.canvas.blur_image(sigma=val) def oilify_image(self): val, ok = QInputDialog.getDouble(self, _('Oilify image'), _( 'The strength of the operation (higher numbers have larger effects)'), value=4, min=0.1, max=20) if ok: self.canvas.oilify_image(radius=val) def launch_editor(path_to_edit, path_is_raw=False): app = QApplication([]) if path_is_raw: raw = path_to_edit else: with open(path_to_edit, 'rb') as f: raw = f.read() t = Editor('raster_image') t.data = raw t.show() app.exec() if __name__ == '__main__': launch_editor(sys.argv[-1])
11,557
Python
.py
288
32.100694
143
0.634188
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,729
python.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/smarts/python.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' import re from qt.core import Qt from calibre.gui2.tweak_book.editor.smarts import NullSmarts from calibre.gui2.tweak_book.editor.smarts.utils import get_leading_whitespace_on_block as lw from calibre.gui2.tweak_book.editor.smarts.utils import get_text_before_cursor, smart_backspace, smart_home, smart_tab def get_leading_whitespace_on_block(editor, previous=False): return expand_tabs(lw(editor, previous=previous)) tw = 4 # The tab width (hardcoded to the pep8 value) def expand_tabs(text): return text.replace('\t', ' ' * tw) class Smarts(NullSmarts): override_tab_stop_width = tw def __init__(self, *args, **kwargs): NullSmarts.__init__(self, *args, **kwargs) c = re.compile self.escape_scope_pat = c(r'\s+(continue|break|return|pass)(\s|$)') self.dedent_pat = c(r'\s+(else|elif|except)(\(|\s|$)') def handle_key_press(self, ev, editor): key = ev.key() if key in (Qt.Key.Key_Tab, Qt.Key.Key_Backtab): mods = ev.modifiers() if not mods & Qt.KeyboardModifier.ControlModifier and smart_tab(editor, ev): return True elif key == Qt.Key.Key_Backspace and smart_backspace(editor, ev): return True elif key in (Qt.Key.Key_Enter, Qt.Key.Key_Return): ls = get_leading_whitespace_on_block(editor) cursor = editor.textCursor() line = cursor.block().text() if line.rstrip().endswith(':'): ls += ' ' * tw elif self.escape_scope_pat.match(line) is not None: ls = ls[:-tw] cursor.insertText('\n' + ls) editor.setTextCursor(cursor) return True elif key == Qt.Key.Key_Colon: cursor, text = get_text_before_cursor(editor) if self.dedent_pat.search(text) is not None: ls = get_leading_whitespace_on_block(editor) pls = get_leading_whitespace_on_block(editor, previous=True) if ls and ls >= pls: ls = ls[:-tw] text = ls + text.lstrip() + ':' cursor.insertText(text) editor.setTextCursor(cursor) return True if key == Qt.Key.Key_Home and smart_home(editor, ev): return True if __name__ == '__main__': import os from calibre.gui2.tweak_book.editor.widget import launch_editor launch_editor(os.path.abspath(__file__), syntax='python')
2,623
Python
.py
56
36.928571
118
0.603774
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,730
utils.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/smarts/utils.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' from qt.core import Qt, QTextCursor def get_text_around_cursor(editor, before=True): cursor = editor.textCursor() cursor.clearSelection() cursor.movePosition((QTextCursor.MoveOperation.StartOfBlock if before else QTextCursor.MoveOperation.EndOfBlock), QTextCursor.MoveMode.KeepAnchor) text = editor.selected_text_from_cursor(cursor) return cursor, text get_text_before_cursor = get_text_around_cursor def get_text_after_cursor(editor): return get_text_around_cursor(editor, before=False) def is_cursor_on_wrapped_line(editor): cursor = editor.textCursor() cursor.movePosition(QTextCursor.MoveOperation.StartOfLine) sol = cursor.position() cursor.movePosition(QTextCursor.MoveOperation.StartOfBlock) return sol != cursor.position() def get_leading_whitespace_on_block(editor, previous=False): cursor = editor.textCursor() block = cursor.block() if previous: block = block.previous() if block.isValid(): text = block.text() ntext = text.lstrip() return text[:len(text)-len(ntext)] return '' def no_modifiers(ev, *args): mods = ev.modifiers() for mod_mask in args: if mods & mod_mask: return False return True def test_modifiers(ev, *args): mods = ev.modifiers() for mod_mask in args: if not mods & mod_mask: return False return True def smart_home(editor, ev): if no_modifiers(ev, Qt.KeyboardModifier.ControlModifier) and not is_cursor_on_wrapped_line(editor): cursor, text = get_text_before_cursor(editor) cursor = editor.textCursor() mode = QTextCursor.MoveMode.KeepAnchor if test_modifiers(ev, Qt.KeyboardModifier.ShiftModifier) else QTextCursor.MoveMode.MoveAnchor cursor.movePosition(QTextCursor.MoveOperation.StartOfBlock, mode) if text.strip() and text.lstrip() != text: # Move to the start of text cursor.movePosition(QTextCursor.MoveOperation.NextWord, mode) editor.setTextCursor(cursor) return True return False def expand_tabs(text, tw): return text.replace('\t', ' ' * tw) def smart_tab_if_whitespace_only_before_cursor(editor, backwards): cursor, text = get_text_before_cursor(editor) if not text.lstrip(): # cursor is preceded by only whitespace tw = editor.tw text = expand_tabs(text, tw) if backwards: if leading := len(text): new_leading = max(0, leading - tw) extra = new_leading % tw if extra: new_leading += tw - extra cursor.insertText(' ' * new_leading) return True else: spclen = len(text) - (len(text) % tw) + tw cursor.insertText(' ' * spclen) editor.setTextCursor(cursor) return True return False def smart_tab_all_blocks_in_selection(editor, backwards): cursor = editor.textCursor() c = QTextCursor(cursor) c.clearSelection() c.setPosition(cursor.selectionStart()) tab_width = editor.tw changed = False while not c.atEnd() and c.position() <= cursor.selectionEnd(): c.clearSelection() c.movePosition(QTextCursor.MoveOperation.EndOfBlock) c.movePosition(QTextCursor.MoveOperation.StartOfBlock, QTextCursor.MoveMode.KeepAnchor) c.movePosition(QTextCursor.MoveOperation.StartOfBlock) # select leading whitespace while not c.atEnd() and c.document().characterAt(c.position()).isspace(): c.movePosition(QTextCursor.MoveOperation.NextCharacter, QTextCursor.MoveMode.KeepAnchor) text = expand_tabs(editor.selected_text_from_cursor(c), tab_width) leading = len(text) replaced = False if backwards: if leading: new_leading = max(0, leading - tab_width) extra = new_leading % tab_width if extra: new_leading += tab_width - extra replaced = True else: new_leading = leading + tab_width new_leading -= new_leading % tab_width replaced = True if replaced: c.insertText(' ' * new_leading) changed = True c.movePosition(QTextCursor.MoveOperation.NextBlock) c.movePosition(QTextCursor.MoveOperation.StartOfBlock) return changed def smart_tab(editor, ev): cursor = editor.textCursor() backwards = ev.key() == Qt.Key.Key_Backtab or (ev.key() == Qt.Key.Key_Tab and bool(ev.modifiers() & Qt.KeyboardModifier.ShiftModifier)) if cursor.hasSelection(): return smart_tab_all_blocks_in_selection(editor, backwards) return smart_tab_if_whitespace_only_before_cursor(editor, backwards) def smart_backspace(editor, ev): if editor.textCursor().hasSelection(): return False cursor, text = get_text_before_cursor(editor) if text and not text.lstrip(): # cursor is preceded by only whitespace tw = editor.tw text = expand_tabs(text, tw) spclen = max(0, len(text) - (len(text) % tw) - tw) cursor.insertText(' ' * spclen) editor.setTextCursor(cursor) return True return False
5,381
Python
.py
129
33.682171
150
0.658565
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,731
__init__.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/smarts/__init__.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' class NullSmarts: override_tab_stop_width = None def __init__(self, editor): pass def get_extra_selections(self, editor): return () def get_smart_selection(self, editor, update=True): return editor.selected_text def verify_for_spellcheck(self, cursor, highlighter): return False def cursor_position_with_sourceline(self, cursor, for_position_sync=True, use_matched_tag=True): return None, None def goto_sourceline(self, editor, sourceline, tags, attribute=None): return False def get_inner_HTML(self, editor): return None def handle_key_press(self, ev, editor): return False def get_completion_data(self, editor, ev=None): return None
868
Python
.py
23
31.26087
100
0.676294
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,732
html.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/smarts/html.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' import re import sys from contextlib import contextmanager from itertools import chain from operator import itemgetter from css_parser import parseStyle from qt.core import Qt, QTextCursor, QTextEdit from calibre import prepare_string_for_xml, xml_entity_to_unicode from calibre.ebooks.oeb.base import css_text from calibre.ebooks.oeb.polish.container import OEB_DOCS from calibre.ebooks.oeb.polish.utils import BLOCK_TAG_NAMES from calibre.gui2 import error_dialog from calibre.gui2.tweak_book import current_container, tprefs from calibre.gui2.tweak_book.editor.smarts import NullSmarts from calibre.gui2.tweak_book.editor.smarts.utils import ( expand_tabs, get_leading_whitespace_on_block, get_text_after_cursor, get_text_before_cursor, no_modifiers, smart_backspace, smart_home, smart_tab, ) from calibre.gui2.tweak_book.editor.syntax.html import ATTR_END, ATTR_NAME, ATTR_START, ATTR_VALUE from calibre.utils.icu import utf16_length get_offset = itemgetter(0) PARAGRAPH_SEPARATOR = '\u2029' DEFAULT_LINK_TEMPLATE = '<a href="_TARGET_">_TEXT_</a>' class Tag: def __init__(self, start_block, tag_start, end_block, tag_end, self_closing=False): self.start_block, self.end_block = start_block, end_block self.start_offset, self.end_offset = tag_start.offset, tag_end.offset tag = tag_start.name if tag_start.prefix: tag = tag_start.prefix + ':' + tag self.name = tag self.self_closing = self_closing def __repr__(self): return '<{} start_block={} start_offset={} end_block={} end_offset={} self_closing={}>'.format( self.name, self.start_block.blockNumber(), self.start_offset, self.end_block.blockNumber(), self.end_offset, self.self_closing) __str__ = __repr__ def next_tag_boundary(block, offset, forward=True, max_lines=10000): while block.isValid() and max_lines > 0: ud = block.userData() if ud is not None: tags = sorted(ud.tags, key=get_offset, reverse=not forward) for boundary in tags: if forward and boundary.offset > offset: return block, boundary if not forward and boundary.offset < offset: return block, boundary block = block.next() if forward else block.previous() offset = -1 if forward else sys.maxsize max_lines -= 1 return None, None def next_attr_boundary(block, offset, forward=True): while block.isValid(): ud = block.userData() if ud is not None: attributes = sorted(ud.attributes, key=get_offset, reverse=not forward) for boundary in attributes: if forward and boundary.offset >= offset: return block, boundary if not forward and boundary.offset <= offset: return block, boundary block = block.next() if forward else block.previous() offset = -1 if forward else sys.maxsize return None, None def find_closest_containing_tag(block, offset, max_tags=sys.maxsize): ''' Find the closest containing tag. To find it, we search for the first opening tag that does not have a matching closing tag before the specified position. Search through at most max_tags. ''' def prev_tag_boundary(b, o): return next_tag_boundary(b, o, forward=False) block, boundary = prev_tag_boundary(block, offset) if block is None: return None if boundary.is_start: # We are inside a tag already if boundary.closing: return find_closest_containing_tag(block, boundary.offset) eblock, eboundary = next_tag_boundary(block, boundary.offset) if eblock is None or eboundary is None or eboundary.is_start: return None if eboundary.self_closing: return Tag(block, boundary, eblock, eboundary, self_closing=True) return find_closest_containing_tag(eblock, eboundary.offset + 1) stack = [] block, tag_end = block, boundary while block is not None and max_tags > 0: sblock, tag_start = prev_tag_boundary(block, tag_end.offset) if sblock is None or not tag_start.is_start: break if tag_start.closing: # A closing tag of the form </a> stack.append((tag_start.prefix, tag_start.name)) elif tag_end.self_closing: # A self closing tag of the form <a/> pass # Ignore it else: # An opening tag, hurray try: prefix, name = stack.pop() except IndexError: prefix = name = None if (prefix, name) != (tag_start.prefix, tag_start.name): # Either we have an unbalanced opening tag or a syntax error, in # either case terminate return Tag(sblock, tag_start, block, tag_end) block, tag_end = prev_tag_boundary(sblock, tag_start.offset) max_tags -= 1 return None # Could not find a containing tag def find_tag_definition(block, offset): ''' Return the <tag | > definition, if any that (block, offset) is inside. ''' block, boundary = next_tag_boundary(block, offset, forward=False) if not boundary or not boundary.is_start: return None, False tag_start = boundary closing = tag_start.closing tag = tag_start.name if tag_start.prefix: tag = tag_start.prefix + ':' + tag return tag, closing def find_containing_attribute(block, offset): block, boundary = next_attr_boundary(block, offset, forward=False) if block is None: return None if boundary.type is ATTR_NAME or boundary.data is ATTR_END: return None # offset is not inside an attribute value block, boundary = next_attr_boundary(block, boundary.offset - 1, forward=False) if block is not None and boundary.type == ATTR_NAME: return boundary.data return None def find_attribute_in_tag(block, offset, attr_name): ' Return the start of the attribute value as block, offset or None, None if attribute not found ' end_block, boundary = next_tag_boundary(block, offset) if boundary.is_start: return None, None end_offset = boundary.offset end_pos = (end_block.blockNumber(), end_offset) current_block, current_offset = block, offset found_attr = False while True: current_block, boundary = next_attr_boundary(current_block, current_offset) if current_block is None or (current_block.blockNumber(), boundary.offset) > end_pos: return None, None current_offset = boundary.offset if found_attr: if boundary.type is not ATTR_VALUE or boundary.data is not ATTR_START: return None, None return current_block, current_offset else: if boundary.type is ATTR_NAME and boundary.data.lower() == attr_name.lower(): found_attr = True current_offset += 1 def find_end_of_attribute(block, offset): ' Find the end of an attribute that occurs somewhere after the position specified by (block, offset) ' block, boundary = next_attr_boundary(block, offset) if block is None or boundary is None: return None, None if boundary.type is not ATTR_VALUE or boundary.data is not ATTR_END: return None, None return block, boundary.offset def find_closing_tag(tag, max_tags=sys.maxsize): ''' Find the closing tag corresponding to the specified tag. To find it we search for the first closing tag after the specified tag that does not match a previous opening tag. Search through at most max_tags. ''' if tag.self_closing: return None stack = [] block, offset = tag.end_block, tag.end_offset while block.isValid() and max_tags > 0: block, tag_start = next_tag_boundary(block, offset) if block is None or not tag_start.is_start: break endblock, tag_end = next_tag_boundary(block, tag_start.offset) if endblock is None or tag_end.is_start: break if tag_start.closing: try: prefix, name = stack.pop() except IndexError: prefix = name = None if (prefix, name) != (tag_start.prefix, tag_start.name): return Tag(block, tag_start, endblock, tag_end) elif tag_end.self_closing: pass else: stack.append((tag_start.prefix, tag_start.name)) block, offset = endblock, tag_end.offset max_tags -= 1 return None def select_tag(cursor, tag): cursor.setPosition(tag.start_block.position() + tag.start_offset) cursor.setPosition(tag.end_block.position() + tag.end_offset + 1, QTextCursor.MoveMode.KeepAnchor) return cursor.selectedText().replace(PARAGRAPH_SEPARATOR, '\n').rstrip('\0') @contextmanager def edit_block(cursor): cursor.beginEditBlock() try: yield finally: cursor.endEditBlock() def rename_tag(cursor, opening_tag, closing_tag, new_name, insert=False): with edit_block(cursor): text = select_tag(cursor, closing_tag) if insert: text = f'</{new_name}>{text}' else: text = re.sub(r'^<\s*/\s*[a-zA-Z0-9]+', '</%s' % new_name, text) cursor.insertText(text) text = select_tag(cursor, opening_tag) if insert: text += '<%s>' % new_name else: text = re.sub(r'^<\s*[a-zA-Z0-9]+', '<%s' % new_name, text) cursor.insertText(text) def split_tag(cursor, opening_tag, closing_tag): pos = cursor.position() with edit_block(cursor): open_text = select_tag(cursor, opening_tag) open_text = re.sub(r'''\bid\s*=\s*['"].*?['"]''', '', open_text) open_text = re.sub(r'\s+', ' ', open_text) tag_name = re.search(r'<\s*(\S+)', open_text).group(1).lower() is_block = tag_name in BLOCK_TAG_NAMES prefix = '' if is_block: cursor.setPosition(cursor.anchor()) cursor.movePosition(QTextCursor.MoveOperation.StartOfLine, QTextCursor.MoveMode.KeepAnchor) x = cursor.selectedText() if x and not x.strip(): prefix = PARAGRAPH_SEPARATOR + x close_text = select_tag(cursor, closing_tag) cursor.setPosition(pos) cursor.insertText(f'{close_text}{prefix}{open_text}') def ensure_not_within_tag_definition(cursor, forward=True): ''' Ensure the cursor is not inside a tag definition <>. Returns True iff the cursor was moved. ''' block, offset = cursor.block(), cursor.positionInBlock() b, boundary = next_tag_boundary(block, offset, forward=False) if b is None: return False if boundary.is_start: # We are inside a tag if forward: block, boundary = next_tag_boundary(block, max(0, offset-1)) if block is not None: cursor.setPosition(block.position() + boundary.offset + 1) return True else: cursor.setPosition(b.position() + boundary.offset) return True return False def find_closest_containing_block_tag(block, offset, block_tag_names=BLOCK_TAG_NAMES): while True: tag = find_closest_containing_tag(block, offset) if tag is None: break if tag.name in block_tag_names: return tag block, offset = tag.start_block, tag.start_offset def set_style_property(tag, property_name, value, editor): ''' Set a style property, i.e. a CSS property inside the style attribute of the tag. Any existing style attribute is updated or a new attribute is inserted. ''' block, offset = find_attribute_in_tag(tag.start_block, tag.start_offset + 1, 'style') c = editor.textCursor() def css(d): return css_text(d).replace('\n', ' ') if block is None or offset is None: d = parseStyle('') d.setProperty(property_name, value) c.setPosition(tag.end_block.position() + tag.end_offset) c.insertText(' style="%s"' % css(d)) else: c.setPosition(block.position() + offset - 1) end_block, end_offset = find_end_of_attribute(block, offset + 1) if end_block is None: return error_dialog(editor, _('Invalid markup'), _( 'The current block tag has an existing unclosed style attribute. Run the Fix HTML' ' tool first.'), show=True) c.setPosition(end_block.position() + end_offset, QTextCursor.MoveMode.KeepAnchor) d = parseStyle(editor.selected_text_from_cursor(c)[1:-1]) d.setProperty(property_name, value) c.insertText('"%s"' % css(d)) entity_pat = re.compile(r'&(#{0,1}[a-zA-Z0-9]{1,8});$') class Smarts(NullSmarts): def __init__(self, *args, **kwargs): if not hasattr(Smarts, 'regexps_compiled'): Smarts.regexps_compiled = True Smarts.tag_pat = re.compile(r'<[^>]+>') Smarts.closing_tag_pat = re.compile(r'<\s*/[^>]+>') Smarts.closing_pat = re.compile(r'<\s*/') Smarts.self_closing_pat = re.compile(r'/\s*>') Smarts.complete_attr_pat = re.compile(r'''([a-zA-Z0-9_-]+)\s*=\s*(?:'([^']*)|"([^"]*))$''') NullSmarts.__init__(self, *args, **kwargs) self.last_matched_tag = self.last_matched_closing_tag = None def get_extra_selections(self, editor): ans = [] def add_tag(tag): a = QTextEdit.ExtraSelection() a.cursor, a.format = editor.textCursor(), editor.match_paren_format a.cursor.setPosition(tag.start_block.position()), a.cursor.movePosition(QTextCursor.MoveOperation.EndOfBlock, QTextCursor.MoveMode.KeepAnchor) text = str(a.cursor.selectedText()) start_pos = utf16_length(text[:tag.start_offset]) a.cursor.setPosition(tag.end_block.position()), a.cursor.movePosition(QTextCursor.MoveOperation.EndOfBlock, QTextCursor.MoveMode.KeepAnchor) text = str(a.cursor.selectedText()) end_pos = utf16_length(text[:tag.end_offset + 1]) a.cursor.setPosition(tag.start_block.position() + start_pos) a.cursor.setPosition(tag.end_block.position() + end_pos, QTextCursor.MoveMode.KeepAnchor) ans.append(a) c = editor.textCursor() block, offset = c.block(), c.positionInBlock() tag = self.last_matched_tag = find_closest_containing_tag(block, offset, max_tags=2000) self.last_matched_closing_tag = None if tag is not None: add_tag(tag) tag = self.last_matched_closing_tag = find_closing_tag(tag, max_tags=4000) if tag is not None: add_tag(tag) return ans def jump_to_enclosing_tag(self, editor, start=True): editor.highlighter.join() tag = self.last_matched_tag if start else self.last_matched_closing_tag if tag is None: return False c = editor.textCursor() c.setPosition(tag.start_block.position() + tag.start_offset + (1 if start else 2)) editor.setTextCursor(c) return True def select_tag_contents(self, editor): editor.highlighter.join() start = self.last_matched_tag end = self.last_matched_closing_tag if start is None or end is None: return False c = editor.textCursor() c.setPosition(start.start_block.position() + start.end_offset + 1) c.setPosition(end.start_block.position() + end.start_offset, QTextCursor.MoveMode.KeepAnchor) editor.setTextCursor(c) return True def remove_tag(self, editor): editor.highlighter.join() if not self.last_matched_closing_tag and not self.last_matched_tag: return c = editor.textCursor() c.beginEditBlock() def erase_tag(tag): c.setPosition(tag.start_block.position() + tag.start_offset) c.setPosition(tag.end_block.position() + tag.end_offset + 1, QTextCursor.MoveMode.KeepAnchor) c.removeSelectedText() if self.last_matched_closing_tag: erase_tag(self.last_matched_closing_tag) if self.last_matched_tag: erase_tag(self.last_matched_tag) c.endEditBlock() self.last_matched_tag = self.last_matched_closing_tag = None def rename_block_tag(self, editor, new_name): editor.highlighter.join() c = editor.textCursor() block, offset = c.block(), c.positionInBlock() tag = find_closest_containing_block_tag(block, offset) if tag is not None: if tag.name == 'body': ntag = find_closest_containing_block_tag(block, offset + 1) if ntag is not None and ntag.name != 'body': tag = ntag elif offset > 0: ntag = find_closest_containing_block_tag(block, offset - 1) if ntag is not None and ntag.name != 'body': tag = ntag closing_tag = find_closing_tag(tag) if closing_tag is None: return error_dialog(editor, _('Invalid HTML'), _( 'There is an unclosed %s tag. You should run the Fix HTML tool' ' before trying to rename tags.') % tag.name, show=True) rename_tag(c, tag, closing_tag, new_name, insert=tag.name in {'body', 'td', 'th', 'li'}) else: return error_dialog(editor, _('No tag found'), _( 'No suitable block level tag was found to rename'), show=True) def split_tag(self, editor): editor.highlighter.join() c = editor.textCursor() block, offset = c.block(), c.positionInBlock() tag, closing = find_tag_definition(block, offset) if tag is not None: return error_dialog(editor, _('Cursor inside tag'), _( 'Cannot split as the cursor is inside the tag definition'), show=True) tag = find_closest_containing_tag(block, offset) if tag is None: return error_dialog(editor, _('No tag found'), _( 'No suitable tag was found to split'), show=True) closing_tag = find_closing_tag(tag) if closing_tag is None: return error_dialog(editor, _('Invalid HTML'), _( 'There is an unclosed %s tag. You should run the Fix HTML tool' ' before trying to split tags.') % tag.name, show=True) split_tag(c, tag, closing_tag) def get_smart_selection(self, editor, update=True): editor.highlighter.join() cursor = editor.textCursor() if not cursor.hasSelection(): return '' left = min(cursor.anchor(), cursor.position()) right = max(cursor.anchor(), cursor.position()) cursor.setPosition(left) ensure_not_within_tag_definition(cursor) left = cursor.position() cursor.setPosition(right) ensure_not_within_tag_definition(cursor, forward=False) right = cursor.position() cursor.setPosition(left), cursor.setPosition(right, QTextCursor.MoveMode.KeepAnchor) if update: editor.setTextCursor(cursor) return editor.selected_text_from_cursor(cursor) def insert_hyperlink(self, editor, target, text, template=None): template = template or DEFAULT_LINK_TEMPLATE template = template.replace('_TARGET_', prepare_string_for_xml(target, True)) offset = template.find('_TEXT_') template = template.replace('_TEXT_', text or '') editor.highlighter.join() c = editor.textCursor() c.beginEditBlock() if c.hasSelection(): c.insertText('') # delete any existing selected text ensure_not_within_tag_definition(c) p = c.position() + offset c.insertText(template) c.setPosition(p) # ensure cursor is positioned inside the newly created tag editor.setTextCursor(c) c.endEditBlock() def insert_tag(self, editor, name): m = re.match(r'[a-zA-Z0-9:-]+', name) cname = name if m is None else m.group() self.surround_with_custom_tag(editor, f'<{name}>', f'</{cname}>') def surround_with_custom_tag(self, editor, opent, close): editor.highlighter.join() text = self.get_smart_selection(editor, update=True) c = editor.textCursor() pos = min(c.position(), c.anchor()) sellen = abs(c.position() - c.anchor()) c.insertText(f'{opent}{text}{close}') c.setPosition(pos + len(opent)) c.setPosition(c.position() + sellen, QTextCursor.MoveMode.KeepAnchor) editor.setTextCursor(c) def verify_for_spellcheck(self, cursor, highlighter): # Return True iff the cursor is in a location where spelling is # checked (inside a tag or inside a checked attribute) highlighter.join() block = cursor.block() start_pos = cursor.anchor() - block.position() end_pos = cursor.position() - block.position() start_tag, closing = find_tag_definition(block, start_pos) if closing: return False end_tag, closing = find_tag_definition(block, end_pos) if closing: return False if start_tag is None and end_tag is None: # We are in normal text, check that the containing tag is # allowed for spell checking. tag = find_closest_containing_tag(block, start_pos) if tag is not None and highlighter.tag_ok_for_spell(tag.name.split(':')[-1]): return True if start_tag != end_tag: return False # Now we check if we are in an allowed attribute sa = find_containing_attribute(block, start_pos) ea = find_containing_attribute(block, end_pos) if sa == ea and sa in highlighter.spell_attributes: return True return False def cursor_position_with_sourceline(self, cursor, for_position_sync=True, use_matched_tag=True): ''' Return the tag just before the current cursor as a source line number and a list of tags defined on that line up to and including the containing tag. If ``for_position_sync`` is False then the tag *containing* the cursor is returned instead of the tag just before the cursor. Note that finding the containing tag is expensive, so use with care. As an optimization, the last tag matched by get_extra_selections is used, unless use_matched_tag is False. ''' block, offset = cursor.block(), cursor.positionInBlock() if for_position_sync: nblock, boundary = next_tag_boundary(block, offset, forward=False) if boundary is None: return None, None if boundary.is_start: # We are inside a tag, use this tag start_block, start_offset = nblock, boundary.offset else: start_block = None while start_block is None and block.isValid(): ud = block.userData() if ud is not None: for boundary in reversed(ud.tags): if boundary.is_start and not boundary.closing and boundary.offset <= offset: start_block, start_offset = block, boundary.offset break block, offset = block.previous(), sys.maxsize end_block = None if start_block is not None: end_block, boundary = next_tag_boundary(start_block, start_offset) if boundary is None or boundary.is_start: return None, None else: tag = None if use_matched_tag: tag = self.last_matched_tag if tag is None: tag = find_closest_containing_tag(block, offset, max_tags=2000) if tag is None: return None, None start_block, start_offset, end_block = tag.start_block, tag.start_offset, tag.end_block if start_block is None or end_block is None: return None, None sourceline = end_block.blockNumber() + 1 # blockNumber() is zero based ud = start_block.userData() if ud is None: return None, None tags = [t.name for t in ud.tags if (t.is_start and not t.closing and t.offset <= start_offset)] if start_block.blockNumber() != end_block.blockNumber(): # Multiline opening tag, it must be the first tag on the line with the closing > del tags[:-1] return sourceline, tags def goto_sourceline(self, editor, sourceline, tags, attribute=None): ''' Move the cursor to the tag identified by sourceline and tags (a list of tags names on the specified line). If attribute is specified the cursor will be placed at the start of the attribute value. ''' found_tag = False if sourceline is None: return found_tag block = editor.document().findBlockByNumber(sourceline - 1) # blockNumber() is zero based if not block.isValid(): return found_tag editor.highlighter.join() c = editor.textCursor() ud = block.userData() all_tags = [] if ud is None else [t for t in ud.tags if (t.is_start and not t.closing)] tag_names = [t.name for t in all_tags] if all_tags and tag_names[:len(tags)] == tags: c.setPosition(block.position() + all_tags[len(tags)-1].offset) found_tag = True else: c.setPosition(block.position()) if found_tag and attribute is not None: start_offset = c.position() - block.position() nblock, offset = find_attribute_in_tag(block, start_offset, attribute) if nblock is not None: c.setPosition(nblock.position() + offset) editor.setTextCursor(c) return found_tag def get_inner_HTML(self, editor): ''' Select the inner HTML of the current tag. Return a cursor with the inner HTML selected or None. ''' editor.highlighter.join() c = editor.textCursor() block = c.block() offset = c.position() - block.position() nblock, boundary = next_tag_boundary(block, offset) if boundary.is_start: # We are within the contents of a tag already tag = find_closest_containing_tag(block, offset) else: # We are inside a tag definition < | > if boundary.self_closing: return None # self closing tags have no inner html tag = find_closest_containing_tag(nblock, boundary.offset + 1) if tag is None: return None ctag = find_closing_tag(tag) if ctag is None: return None c.setPosition(tag.end_block.position() + tag.end_offset + 1) c.setPosition(ctag.start_block.position() + ctag.start_offset, QTextCursor.MoveMode.KeepAnchor) return c def set_text_alignment(self, editor, value): ''' Set the text-align property on the current block tag(s) ''' editor.highlighter.join() block_tag_names = BLOCK_TAG_NAMES - {'body'} # ignore body since setting text-align globally on body is almost never what is wanted tags = [] c = editor.textCursor() if c.hasSelection(): start, end = min(c.anchor(), c.position()), max(c.anchor(), c.position()) c.setPosition(start) block = c.block() while block.isValid() and block.position() < end: ud = block.userData() if ud is not None: for tb in ud.tags: if tb.is_start and not tb.closing and tb.name.lower() in block_tag_names: nblock, boundary = next_tag_boundary(block, tb.offset) if boundary is not None and not boundary.is_start and not boundary.self_closing: tags.append(Tag(block, tb, nblock, boundary)) block = block.next() if not tags: c = editor.textCursor() block, offset = c.block(), c.positionInBlock() tag = find_closest_containing_block_tag(block, offset, block_tag_names) if tag is None: return error_dialog(editor, _('Not in a block tag'), _( 'Cannot change text alignment as the cursor is not inside a block level tag, such as a &lt;p&gt; or &lt;div&gt; tag.'), show=True) tags = [tag] for tag in reversed(tags): set_style_property(tag, 'text-align', value, editor) def handle_key_press(self, ev, editor): ev_text = ev.text() key = ev.key() is_xml = editor.syntax == 'xml' mods = ev.modifiers() & ( Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.AltModifier | Qt.KeyboardModifier.MetaModifier | Qt.KeyboardModifier.KeypadModifier) shifted_mods = ev.modifiers() & ( Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.AltModifier | Qt.KeyboardModifier.MetaModifier | Qt.KeyboardModifier.KeypadModifier | Qt.KeyboardModifier.ShiftModifier) if tprefs['replace_entities_as_typed'] and ( ';' in ev_text or (key == Qt.Key.Key_Semicolon and no_modifiers(ev, Qt.KeyboardModifier.ControlModifier, Qt.KeyboardModifier.AltModifier)) ): self.replace_possible_entity(editor) return True if key in (Qt.Key.Key_Enter, Qt.Key.Key_Return) and no_modifiers(ev, Qt.KeyboardModifier.ControlModifier, Qt.KeyboardModifier.AltModifier): ls = get_leading_whitespace_on_block(editor) if ls == ' ': ls = '' # Do not consider a single leading space as indentation if is_xml: count = 0 for m in self.tag_pat.finditer(get_text_before_cursor(editor)[1]): text = m.group() if self.closing_pat.search(text) is not None: count -= 1 elif self.self_closing_pat.search(text) is None: count += 1 if self.closing_tag_pat.match(get_text_after_cursor(editor)[1].lstrip()): count -= 1 if count > 0: ls += editor.tw * ' ' editor.textCursor().insertText('\n' + ls) return True if key == Qt.Key.Key_Slash: cursor, text = get_text_before_cursor(editor) if not text.rstrip().endswith('<'): return False text = expand_tabs(text.rstrip()[:-1], editor.tw) pls = get_leading_whitespace_on_block(editor, previous=True) if is_xml and not text.lstrip() and len(text) > 1 and len(text) >= len(pls): # Auto-dedent text = text[:-editor.tw] + '</' cursor.insertText(text) editor.setTextCursor(cursor) self.auto_close_tag(editor) return True if self.auto_close_tag(editor): return True if key == Qt.Key.Key_Home and smart_home(editor, ev): return True if key in (Qt.Key.Key_Tab, Qt.Key.Key_Backtab): if not mods & Qt.KeyboardModifier.ControlModifier and smart_tab(editor, ev): return True if key == Qt.Key.Key_Backspace and smart_backspace(editor, ev): return True if key in (Qt.Key.Key_BraceLeft, Qt.Key.Key_BraceRight): if mods == Qt.KeyboardModifier.ControlModifier: if self.jump_to_enclosing_tag(editor, key == Qt.Key.Key_BraceLeft): return True if key == Qt.Key.Key_T and shifted_mods in ( Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.AltModifier, Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.ShiftModifier): return self.select_tag_contents(editor) return False def replace_possible_entity(self, editor): c = editor.textCursor() c.insertText(';') c.setPosition(c.position() - min(c.positionInBlock(), 10), QTextCursor.MoveMode.KeepAnchor) text = editor.selected_text_from_cursor(c) m = entity_pat.search(text) if m is not None: ent = m.group() repl = xml_entity_to_unicode(m) if repl != ent: c.setPosition(c.position() + m.start(), QTextCursor.MoveMode.KeepAnchor) c.insertText(repl) editor.setTextCursor(c) def auto_close_tag(self, editor): if not tprefs['auto_close_tags']: return False def check_if_in_tag(block, offset=0): if block.isValid(): text = block.text() close_pos = text.find('>', offset) open_pos = text.find('<', offset) if (close_pos > -1 and open_pos == -1) or (close_pos < open_pos): return True return False editor.highlighter.join() c = editor.textCursor() block, offset = c.block(), c.positionInBlock() if check_if_in_tag(block, offset) or check_if_in_tag(block.next()): return False tag = find_closest_containing_tag(block, offset - 1, max_tags=4000) if tag is None: return False c.insertText('/%s>' % tag.name) editor.setTextCursor(c) return True def get_completion_data(self, editor, ev=None): c = editor.textCursor() block, offset = c.block(), c.positionInBlock() oblock, boundary = next_tag_boundary(block, offset, forward=False, max_lines=5) if boundary is None or not boundary.is_start or boundary.closing: # Not inside a opening tag definition return tagname = boundary.name.lower() startpos = oblock.position() + boundary.offset c.setPosition(c.position()), c.setPosition(startpos, QTextCursor.MoveMode.KeepAnchor) text = c.selectedText() m = self.complete_attr_pat.search(text) if m is None: return attr = m.group(1).lower().split(':')[-1] doc_name = editor.completion_doc_name if doc_name and attr in {'href', 'src'}: # A link query = m.group(2) or m.group(3) or '' c = current_container() names_type = {'a':'text_link', 'img':'image', 'image':'image', 'link':'stylesheet'}.get(tagname) idx = query.find('#') if idx > -1 and names_type in (None, 'text_link'): href, query = query[:idx], query[idx+1:] name = c.href_to_name(href) if href else doc_name if c.mime_map.get(name) in OEB_DOCS: return 'complete_anchor', name, query return 'complete_names', (names_type, doc_name, c.root), query def find_text(self, pat, cursor, reverse): from calibre.gui2.tweak_book.text_search import find_text_in_chunks chunks = [] cstart = min(cursor.position(), cursor.anchor()) cend = max(cursor.position(), cursor.anchor()) if reverse: cend -= 1 c = QTextCursor(cursor) c.setPosition(cstart) block = c.block() in_text = find_tag_definition(block, 0)[0] is None if in_text: # Check if we are in comment/PI/etc. pb = block.previous() while pb.isValid(): boundaries = pb.userData().non_tag_structures if boundaries: if boundaries[-1].is_start: in_text = False break pb = pb.previous() def append(text, start): text = text.replace(PARAGRAPH_SEPARATOR, '\n') after = start + len(text) if start <= cend and cstart < after: extra = after - (cend + 1) if extra > 0: text = text[:-extra] extra = cstart - start if extra > 0: text = text[extra:] chunks.append((text, start + max(extra, 0))) while block.isValid() and block.position() <= cend: ud = block.userData() boundaries = sorted(chain(ud.tags, ud.non_tag_structures), key=get_offset) if not boundaries: # Add the whole line if in_text: text = block.text() + '\n' append(text, block.position()) else: start = block.position() c.setPosition(start) for b in boundaries: if in_text: c.setPosition(start + b.offset, QTextCursor.MoveMode.KeepAnchor) if c.hasSelection(): append(c.selectedText(), c.anchor()) in_text = not b.is_start c.setPosition(start + b.offset + 1) if in_text: # Add remaining text in block c.setPosition(block.position() + boundaries[-1].offset + 1) c.movePosition(QTextCursor.MoveOperation.EndOfBlock, QTextCursor.MoveMode.KeepAnchor) if c.hasSelection(): append(c.selectedText() + '\n', c.anchor()) block = block.next() s, e = find_text_in_chunks(pat, chunks) return s != -1 and e != -1, s, e if __name__ == '__main__': # {{{ from calibre.gui2.tweak_book.editor.widget import launch_editor if sys.argv[-1].endswith('.html'): raw = open(sys.argv[-1], 'rb').read().decode('utf-8') else: raw = '''\ <!DOCTYPE html> <html xml:lang="en" lang="en"> <!-- --> <head> <meta charset="utf-8" /> <title>A title with a tag <span> in it, the tag is treated as normal text</title> <style type="text/css"> body { color: green; font-size: 12pt; } </style> <style type="text/css">p.small { font-size: x-small; color:gray }</style> </head id="invalid attribute on closing tag"> <body lang="en_IN"><p: <!-- The start of the actual body text --> <h1 lang="en_US">A heading that should appear in bold, with an <i>italic</i> word</h1> <p>Some text with inline formatting, that is syntax highlighted. A <b>bold</b> word, and an <em>italic</em> word. \ <i>Some italic text with a <b>bold-italic</b> word in </i>the middle.</p> <!-- Let's see what exotic constructs like namespace prefixes and empty attributes look like --> <svg:svg xmlns:svg="http://whatever" /> <input disabled><input disabled /><span attr=<></span> <!-- Non-breaking spaces are rendered differently from normal spaces, so that they stand out --> <p>Some\xa0words\xa0separated\xa0by\xa0non\u2011breaking\xa0spaces and non\u2011breaking hyphens.</p> <p>Some non-BMP unicode text:\U0001f431\U0001f431\U0001f431</p> </body> </html> ''' def callback(ed): import regex ed.find_text(regex.compile('A bold word')) launch_editor(raw, path_is_raw=True, syntax='html', callback=callback) # }}}
39,833
Python
.py
829
37.365501
160
0.603218
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,733
css.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/smarts/css.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' import re from qt.core import Qt, QTextCursor from calibre.gui2.tweak_book import current_container from calibre.gui2.tweak_book.editor.smarts import NullSmarts from calibre.gui2.tweak_book.editor.smarts.utils import ( expand_tabs, get_leading_whitespace_on_block, get_text_before_cursor, no_modifiers, smart_backspace, smart_home, smart_tab, ) def find_rule(raw, rule_address): import tinycss parser = tinycss.make_full_parser() sheet = parser.parse_stylesheet(raw) rules = sheet.rules ans = None, None while rule_address: try: r = rules[rule_address[0]] except IndexError: return None, None else: ans = r.line, r.column rule_address = rule_address[1:] if rule_address: rules = getattr(r, 'rules', ()) return ans class Smarts(NullSmarts): def __init__(self, *args, **kwargs): if not hasattr(Smarts, 'regexps_compiled'): Smarts.regexps_compiled = True Smarts.complete_attr_pat = re.compile(r'''url\s*\(\s*['"]{0,1}([^)]*)$''') NullSmarts.__init__(self, *args, **kwargs) def handle_key_press(self, ev, editor): key = ev.key() if key in (Qt.Key.Key_Enter, Qt.Key.Key_Return) and no_modifiers(ev, Qt.KeyboardModifier.ControlModifier, Qt.KeyboardModifier.AltModifier): ls = get_leading_whitespace_on_block(editor) cursor, text = get_text_before_cursor(editor) if text.rstrip().endswith('{'): ls += ' ' * editor.tw editor.textCursor().insertText('\n' + ls) return True if key == Qt.Key.Key_BraceRight: ls = get_leading_whitespace_on_block(editor) pls = get_leading_whitespace_on_block(editor, previous=True) cursor, text = get_text_before_cursor(editor) if not text.rstrip() and ls >= pls and len(text) > 1: text = expand_tabs(text, editor.tw)[:-editor.tw] cursor.insertText(text + '}') editor.setTextCursor(cursor) return True if key == Qt.Key.Key_Home and smart_home(editor, ev): return True if key in (Qt.Key.Key_Tab, Qt.Key.Key_Backtab): mods = ev.modifiers() if not mods & Qt.KeyboardModifier.ControlModifier and smart_tab(editor, ev): return True if key == Qt.Key.Key_Backspace and smart_backspace(editor, ev): return True return False def get_completion_data(self, editor, ev=None): c = editor.textCursor() c.movePosition(QTextCursor.MoveOperation.StartOfLine, QTextCursor.MoveMode.KeepAnchor) text = c.selectedText() m = self.complete_attr_pat.search(text) if m is None: return query = m.group(1) or '' doc_name = editor.completion_doc_name if doc_name: return 'complete_names', ('css_resource', doc_name, current_container().root), query
3,159
Python
.py
77
32.103896
147
0.612924
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,734
python.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/syntax/python.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' from pygments.lexers import PythonLexer from calibre.gui2.tweak_book.editor.syntax.pygments_highlighter import create_highlighter Highlighter = create_highlighter('PythonHighlighter', PythonLexer) if __name__ == '__main__': import os from calibre.gui2.tweak_book.editor.widget import launch_editor launch_editor(os.path.abspath(__file__), syntax='python')
482
Python
.py
10
45.3
89
0.756989
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,735
xml.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/syntax/xml.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' from calibre.gui2.tweak_book.editor.syntax.html import XMLHighlighter as Highlighter # noqa
203
Python
.py
4
49
92
0.75
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,736
pygments_highlighter.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/syntax/pygments_highlighter.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' import numbers from functools import partial from pygments.lexer import Error, _TokenType from qt.core import QTextBlockUserData from calibre.gui2.tweak_book.editor.syntax.base import SyntaxHighlighter from calibre.gui2.tweak_book.editor.syntax.utils import NULL_FMT, format_for_pygments_token NORMAL = 0 def create_lexer(base_class): ''' Subclass the pygments RegexLexer to lex line by line instead of lexing full text. The statestack at the end of each line is stored in the Qt block state. ''' def get_tokens_unprocessed(self, text, statestack): pos = 0 tokendefs = self._tokens statetokens = tokendefs[statestack[-1]] while True: for rexmatch, action, new_state in statetokens: m = rexmatch(text, pos) if m is not None: if action is not None: if type(action) is _TokenType: yield pos, action, m.group() else: yield from action(self, m) pos = m.end() if new_state is not None: # state transition if isinstance(new_state, tuple): for state in new_state: if state == '#pop': statestack.pop() elif state == '#push': statestack.append(statestack[-1]) else: statestack.append(state) elif isinstance(new_state, numbers.Integral): # pop del statestack[new_state:] elif new_state == '#push': statestack.append(statestack[-1]) else: assert False, "wrong state def: %r" % new_state statetokens = tokendefs[statestack[-1]] break else: try: if text[pos] == '\n': # at EOL, reset state to "root" statestack[:] = ['root'] break yield pos, Error, text[pos] pos += 1 except IndexError: break def lex_a_line(self, state, text, i, formats_map, user_data): ' Get formats for a single block (line) ' statestack = list(state.pygments_stack) if state.pygments_stack is not None else ['root'] # Lex the text using Pygments formats = [] if i > 0: # This should never happen state.pygments_stack = None return [(len(text) - i, formats_map(Error))] try: # Pygments lexers expect newlines at the end of the line for pos, token, txt in self.get_tokens_unprocessed(text + '\n', statestack): if txt not in ('\n', ''): formats.append((len(txt), formats_map(token))) except Exception: import traceback traceback.print_exc() state.pygments_stack = None return [(len(text) - i, formats_map(Error))] state.pygments_stack = statestack return formats name_type = type(base_class.__name__) return type(name_type('Qt'+base_class.__name__), (base_class,), { 'get_tokens_unprocessed': get_tokens_unprocessed, 'lex_a_line':lex_a_line, }) class State: __slots__ = ('parse', 'pygments_stack') def __init__(self): self.parse = NORMAL self.pygments_stack = None def copy(self): s = State() s.pygments_stack = None if self.pygments_stack is None else list(self.pygments_stack) return s def __eq__(self, other): return self.parse == getattr(other, 'parse', -1) and \ self.pygments_stack == getattr(other, 'pygments_stack', False) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return "PythonState(%r)" % self.pygments_stack __str__ = __repr__ class PygmentsUserData(QTextBlockUserData): def __init__(self): QTextBlockUserData.__init__(self) self.state = State() self.doc_name = None def clear(self, state=None, doc_name=None): self.state = State() if state is None else state self.doc_name = doc_name def create_formats(highlighter): cache = {} theme = highlighter.theme.copy() theme[None] = NULL_FMT return partial(format_for_pygments_token, theme, cache) def create_highlighter(name, lexer_class): name_type = type(lexer_class.__name__) return type(name_type(name), (SyntaxHighlighter,), { 'state_map': {NORMAL:create_lexer(lexer_class)().lex_a_line}, 'create_formats_func': create_formats, 'user_data_factory': PygmentsUserData, })
5,171
Python
.py
121
29.785124
97
0.538247
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,737
utils.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/syntax/utils.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' from qt.core import QTextCharFormat NULL_FMT = QTextCharFormat() _pyg_map = None def pygments_map(): global _pyg_map if _pyg_map is None: from pygments.token import Token _pyg_map = { Token: None, Token.Comment: 'Comment', Token.Comment.Preproc: 'PreProc', Token.String: 'String', Token.Number: 'Number', Token.Keyword.Type: 'Type', Token.Keyword: 'Keyword', Token.Name.Builtin: 'Identifier', Token.Operator: 'Statement', Token.Name.Function: 'Function', Token.Literal: 'Constant', Token.Error: 'Error', } return _pyg_map def format_for_pygments_token(theme, cache, token): try: return cache[token] except KeyError: pass pmap = pygments_map() while token is not None: try: name = pmap[token] except KeyError: token = token.parent continue cache[token] = ans = theme[name] return ans cache[token] = ans = NULL_FMT return ans
1,219
Python
.py
40
22.275
71
0.581834
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,738
__init__.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/syntax/__init__.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
112
Python
.py
3
34.666667
61
0.673077
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,739
html.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/syntax/html.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' import re from collections import namedtuple from functools import partial from qt.core import QFont, QTextBlockUserData, QTextCharFormat, QVariant from calibre.ebooks.oeb.polish.spell import html_spell_tags, patterns, xml_spell_tags from calibre.gui2.tweak_book import dictionaries, tprefs, verify_link from calibre.gui2.tweak_book.editor import ( CLASS_ATTRIBUTE_PROPERTY, LINK_PROPERTY, SPELL_LOCALE_PROPERTY, SPELL_PROPERTY, TAG_NAME_PROPERTY, store_locale, syntax_text_char_format, ) from calibre.gui2.tweak_book.editor.syntax.base import SyntaxHighlighter, run_loop from calibre.gui2.tweak_book.editor.syntax.css import CSSState, CSSUserData from calibre.gui2.tweak_book.editor.syntax.css import create_formats as create_css_formats from calibre.gui2.tweak_book.editor.syntax.css import state_map as css_state_map from calibre.spell.break_iterator import split_into_words_and_positions from calibre.spell.dictionary import parse_lang_code from calibre_extensions import html_syntax_highlighter as _speedup from polyglot.builtins import iteritems cdata_tags = frozenset(['title', 'textarea', 'style', 'script', 'xmp', 'iframe', 'noembed', 'noframes', 'noscript']) normal_pat = re.compile(r'[^<>&]+') entity_pat = re.compile(r'&#{0,1}[a-zA-Z0-9]{1,8};') tag_name_pat = re.compile(r'/{0,1}[a-zA-Z0-9:-]+') space_chars = ' \t\r\n\u000c' attribute_name_pat = re.compile(r'''[^%s"'/><=]+''' % space_chars) self_closing_pat = re.compile(r'/\s*>') unquoted_val_pat = re.compile(r'''[^%s'"=<>`]+''' % space_chars) cdata_close_pats = {x:re.compile(r'</%s' % x, flags=re.I) for x in cdata_tags} nbsp_pat = re.compile('[\xa0\u2000-\u200A\u202F\u205F\u3000\u2011-\u2015\uFE58\uFE63\uFF0D]+') # special spaces and hyphens NORMAL = 0 IN_OPENING_TAG = 1 IN_CLOSING_TAG = 2 IN_COMMENT = 3 IN_PI = 4 IN_DOCTYPE = 5 ATTRIBUTE_NAME = 6 ATTRIBUTE_VALUE = 7 SQ_VAL = 8 DQ_VAL = 9 CDATA = 10 CSS = 11 TagStart = namedtuple('TagStart', 'offset prefix name closing is_start') TagEnd = namedtuple('TagEnd', 'offset self_closing is_start') NonTagBoundary = namedtuple('NonTagBoundary', 'offset is_start type') Attr = namedtuple('Attr', 'offset type data') LINK_ATTRS = frozenset(('href', 'src', 'poster', 'xlink:href')) do_spell_check = False def refresh_spell_check_status(): global do_spell_check do_spell_check = tprefs['inline_spell_check'] and hasattr(dictionaries, 'active_user_dictionaries') Tag = _speedup.Tag bold_tags, italic_tags = _speedup.bold_tags, _speedup.italic_tags State = _speedup.State def spell_property(sfmt, locale): s = QTextCharFormat(sfmt) s.setProperty(SPELL_LOCALE_PROPERTY, QVariant(locale)) return s def sanitizing_recognizer(): sanitize = patterns().sanitize_invisible_pat.sub r = dictionaries.recognized def recognized(word, locale=None): word = sanitize('', word).strip() return r(word, locale) return recognized _speedup.init(spell_property, sanitizing_recognizer(), split_into_words_and_positions) del spell_property check_spelling = _speedup.check_spelling def finish_opening_tag(state, cdata_tags): state.parse = NORMAL if state.tag_being_defined is None: return t, state.tag_being_defined = state.tag_being_defined, None state.tags.append(t) state.is_bold = state.is_bold or t.bold state.is_italic = state.is_italic or t.italic state.current_lang = t.lang or state.current_lang if t.name in cdata_tags: state.parse = CSS if t.name == 'style' else CDATA state.sub_parser_state = None def close_tag(state, name): removed_tags = [] for tag in reversed(state.tags): removed_tags.append(tag) if tag.name == name: break else: return # No matching open tag found, ignore the closing tag # Remove all tags up to the matching open tag state.tags = state.tags[:-len(removed_tags)] state.sub_parser_state = None # Check if we should still be bold or italic if state.is_bold: state.is_bold = False for tag in reversed(state.tags): if tag.bold: state.is_bold = True break if state.is_italic: state.is_italic = False for tag in reversed(state.tags): if tag.italic: state.is_italic = True break # Set the current language to the first lang attribute in a still open tag state.current_lang = None for tag in reversed(state.tags): if tag.lang is not None: state.current_lang = tag.lang break class HTMLUserData(QTextBlockUserData): def __init__(self): QTextBlockUserData.__init__(self) self.tags = [] self.attributes = [] self.non_tag_structures = [] self.state = State() self.css_user_data = None self.doc_name = None def clear(self, state=None, doc_name=None): self.tags, self.attributes, self.non_tag_structures = [], [], [] self.state = State() if state is None else state self.doc_name = doc_name @classmethod def tag_ok_for_spell(cls, name): return name not in html_spell_tags class XMLUserData(HTMLUserData): @classmethod def tag_ok_for_spell(cls, name): return name in xml_spell_tags def add_tag_data(user_data, tag): user_data.tags.append(tag) ATTR_NAME, ATTR_VALUE, ATTR_START, ATTR_END = object(), object(), object(), object() def add_attr_data(user_data, data_type, data, offset): user_data.attributes.append(Attr(offset, data_type, data)) def css(state, text, i, formats, user_data): ' Inside a <style> tag ' pat = cdata_close_pats['style'] m = pat.search(text, i) if m is None: css_text = text[i:] else: css_text = text[i:m.start()] ans = [] css_user_data = user_data.css_user_data = user_data.css_user_data or CSSUserData() state.sub_parser_state = css_user_data.state = state.sub_parser_state or CSSState() for j, num, fmt in run_loop(css_user_data, css_state_map, formats['css_sub_formats'], css_text): ans.append((num, fmt)) if m is not None: state.sub_parser_state = None state.parse = IN_CLOSING_TAG add_tag_data(user_data, TagStart(m.start(), '', 'style', True, True)) ans.extend([(2, formats['end_tag']), (len(m.group()) - 2, formats['tag_name'])]) return ans def cdata(state, text, i, formats, user_data): 'CDATA inside tags like <title> or <style>' name = state.tags[-1].name pat = cdata_close_pats[name] m = pat.search(text, i) fmt = formats['title' if name == 'title' else 'special'] if m is None: return [(len(text) - i, fmt)] state.parse = IN_CLOSING_TAG num = m.start() - i add_tag_data(user_data, TagStart(m.start(), '', name, True, True)) return [(num, fmt), (2, formats['end_tag']), (len(m.group()) - 2, formats['tag_name'])] def process_text(state, text, nbsp_format, spell_format, user_data): ans = [] fmt = None if state.is_bold or state.is_italic: fmt = syntax_text_char_format() if state.is_bold: fmt.setFontWeight(QFont.Weight.Bold) if state.is_italic: fmt.setFontItalic(True) last = 0 for m in nbsp_pat.finditer(text): ans.extend([(m.start() - last, fmt), (m.end() - m.start(), nbsp_format)]) last = m.end() if not ans: ans = [(len(text), fmt)] elif last < len(text): ans.append((len(text) - last, fmt)) if do_spell_check and state.tags and user_data.tag_ok_for_spell(state.tags[-1].name): split_ans = [] locale = state.current_lang or dictionaries.default_locale sfmt = QTextCharFormat(spell_format) if fmt is not None: sfmt.merge(fmt) tpos = 0 for tlen, fmt in ans: if fmt is nbsp_format: split_ans.append((tlen, fmt)) else: split_ans.extend(check_spelling(text[tpos:tpos+tlen], tlen, fmt, locale, sfmt, store_locale.enabled)) tpos += tlen ans = split_ans return ans def normal(state, text, i, formats, user_data): ' The normal state in between tags ' ch = text[i] if ch == '<': if text[i:i+4] == '<!--': state.parse, fmt = IN_COMMENT, formats['comment'] user_data.non_tag_structures.append(NonTagBoundary(i, True, IN_COMMENT)) return [(4, fmt)] if text[i:i+2] == '<?': state.parse, fmt = IN_PI, formats['preproc'] user_data.non_tag_structures.append(NonTagBoundary(i, True, IN_PI)) return [(2, fmt)] if text[i:i+2] == '<!' and text[i+2:].lstrip().lower().startswith('doctype'): state.parse, fmt = IN_DOCTYPE, formats['preproc'] user_data.non_tag_structures.append(NonTagBoundary(i, True, IN_DOCTYPE)) return [(2, fmt)] m = tag_name_pat.match(text, i + 1) if m is None: return [(1, formats['<'])] tname = m.group() closing = tname.startswith('/') if closing: tname = tname[1:] if ':' in tname: prefix, name = tname.split(':', 1) else: prefix, name = '', tname if prefix and not name: return [(len(m.group()) + 1, formats['only-prefix'])] ans = [(2 if closing else 1, formats['end_tag' if closing else 'tag'])] if prefix: ans.append((len(prefix)+1, formats['nsprefix'])) ans.append((len(name), formats['tag_name'])) state.parse = IN_CLOSING_TAG if closing else IN_OPENING_TAG add_tag_data(user_data, TagStart(i, prefix, name, closing, True)) if closing: close_tag(state, name) else: state.tag_being_defined = Tag(name) return ans if ch == '&': m = entity_pat.match(text, i) if m is None: return [(1, formats['&'])] return [(len(m.group()), formats['entity'])] if ch == '>': return [(1, formats['>'])] t = normal_pat.search(text, i).group() return process_text(state, t, formats['nbsp'], formats['spell'], user_data) def opening_tag(cdata_tags, state, text, i, formats, user_data): 'An opening tag, like <a>' ch = text[i] if ch in space_chars: return [(1, None)] if ch == '/': m = self_closing_pat.match(text, i) if m is None: return [(1, formats['/'])] state.parse = NORMAL l = len(m.group()) add_tag_data(user_data, TagEnd(i + l - 1, True, False)) return [(l, formats['tag'])] if ch == '>': finish_opening_tag(state, cdata_tags) add_tag_data(user_data, TagEnd(i, False, False)) return [(1, formats['tag'])] m = attribute_name_pat.match(text, i) if m is None: return [(1, formats['?'])] state.parse = ATTRIBUTE_NAME attrname = state.attribute_name = m.group() add_attr_data(user_data, ATTR_NAME, attrname, m.start()) prefix, name = attrname.partition(':')[0::2] if not prefix and not name: return [(len(attrname), formats['?'])] if prefix and name: return [(len(prefix) + 1, formats['nsprefix']), (len(name), formats['attr'])] return [(len(prefix), formats['attr'])] def attribute_name(state, text, i, formats, user_data): ' After attribute name ' ch = text[i] if ch in space_chars: return [(1, None)] if ch == '=': state.parse = ATTRIBUTE_VALUE return [(1, formats['attr'])] # Standalone attribute with no value state.parse = IN_OPENING_TAG state.attribute_name = None return [(0, None)] def attribute_value(state, text, i, formats, user_data): ' After attribute = ' ch = text[i] if ch in space_chars: return [(1, None)] if ch in {'"', "'"}: state.parse = SQ_VAL if ch == "'" else DQ_VAL return [(1, formats['string'])] state.parse = IN_OPENING_TAG state.attribute_name = None m = unquoted_val_pat.match(text, i) if m is None: return [(1, formats['no-attr-value'])] return [(len(m.group()), formats['string'])] def quoted_val(state, text, i, formats, user_data): ' A quoted attribute value ' quote = '"' if state.parse is DQ_VAL else "'" add_attr_data(user_data, ATTR_VALUE, ATTR_START, i) pos = text.find(quote, i) if pos == -1: num = len(text) - i is_link = is_class = False else: num = pos - i + 1 state.parse = IN_OPENING_TAG if state.tag_being_defined is not None and state.attribute_name in ('lang', 'xml:lang'): try: state.tag_being_defined.lang = parse_lang_code(text[i:pos]) except ValueError: pass add_attr_data(user_data, ATTR_VALUE, ATTR_END, i + num) is_link = state.attribute_name in LINK_ATTRS is_class = not is_link and state.attribute_name == 'class' if is_link: if verify_link(text[i:i+num - 1], user_data.doc_name) is False: return [(num - 1, formats['bad_link']), (1, formats['string'])] return [(num - 1, formats['link']), (1, formats['string'])] elif is_class: return [(num - 1, formats['class_attr']), (1, formats['string'])] return [(num, formats['string'])] def closing_tag(state, text, i, formats, user_data): ' A closing tag like </a> ' ch = text[i] if ch in space_chars: return [(1, None)] pos = text.find('>', i) if pos == -1: return [(len(text) - i, formats['bad-closing'])] state.parse = NORMAL num = pos - i + 1 ans = [(1, formats['end_tag'])] if num > 1: ans.insert(0, (num - 1, formats['bad-closing'])) add_tag_data(user_data, TagEnd(pos, False, False)) return ans def in_comment(state, text, i, formats, user_data): ' Comment, processing instruction or doctype ' end = {IN_COMMENT:'-->', IN_PI:'?>'}.get(state.parse, '>') pos = text.find(end, i) fmt = formats['comment' if state.parse is IN_COMMENT else 'preproc'] if pos == -1: num = len(text) - i else: user_data.non_tag_structures.append(NonTagBoundary(pos, False, state.parse)) num = pos - i + len(end) state.parse = NORMAL return [(num, fmt)] state_map = { NORMAL:normal, IN_OPENING_TAG: partial(opening_tag, cdata_tags), IN_CLOSING_TAG: closing_tag, ATTRIBUTE_NAME: attribute_name, ATTRIBUTE_VALUE: attribute_value, CDATA: cdata, CSS: css, } for x in (IN_COMMENT, IN_PI, IN_DOCTYPE): state_map[x] = in_comment for x in (SQ_VAL, DQ_VAL): state_map[x] = quoted_val xml_state_map = state_map.copy() xml_state_map[IN_OPENING_TAG] = partial(opening_tag, set()) def create_formats(highlighter, add_css=True): t = highlighter.theme formats = { 'tag': t['Function'], 'end_tag': t['Function'], 'attr': t['Type'], 'entity': t['Special'], 'error': t['Error'], 'comment': t['Comment'], 'special': t['Special'], 'string': t['String'], 'nsprefix': t['Constant'], 'preproc': t['PreProc'], 'nbsp': t['SpecialCharacter'], 'spell': t['SpellError'], } for name, msg in iteritems({ '<': _('An unescaped < is not allowed. Replace it with &lt;'), '&': _('An unescaped ampersand is not allowed. Replace it with &amp;'), '>': _('An unescaped > is not allowed. Replace it with &gt;'), '/': _('/ not allowed except at the end of the tag'), '?': _('Unknown character'), 'bad-closing': _('A closing tag must contain only the tag name and nothing else'), 'no-attr-value': _('Expecting an attribute value'), 'only-prefix': _('A tag name cannot end with a colon'), }): f = formats[name] = syntax_text_char_format(formats['error']) f.setToolTip(msg) f = formats['title'] = syntax_text_char_format() f.setFontWeight(QFont.Weight.Bold) if add_css: formats['css_sub_formats'] = create_css_formats(highlighter) formats['spell'].setProperty(SPELL_PROPERTY, True) formats['class_attr'] = syntax_text_char_format(t['Special']) formats['class_attr'].setProperty(CLASS_ATTRIBUTE_PROPERTY, True) formats['class_attr'].setToolTip(_('Hold down the Ctrl key and click to open the first matching CSS style rule')) formats['link'] = syntax_text_char_format(t['Link']) formats['link'].setProperty(LINK_PROPERTY, True) formats['link'].setToolTip(_('Hold down the Ctrl key and click to open this link')) formats['bad_link'] = syntax_text_char_format(t['BadLink']) formats['bad_link'].setProperty(LINK_PROPERTY, True) formats['bad_link'].setToolTip(_('This link points to a file that is not present in the book')) formats['tag_name'] = f = syntax_text_char_format(t['Statement']) f.setProperty(TAG_NAME_PROPERTY, True) return formats class Highlighter(SyntaxHighlighter): state_map = state_map create_formats_func = create_formats spell_attributes = ('alt', 'title') user_data_factory = HTMLUserData def tag_ok_for_spell(self, name): return HTMLUserData.tag_ok_for_spell(name) class XMLHighlighter(Highlighter): state_map = xml_state_map spell_attributes = ('opf:file-as',) user_data_factory = XMLUserData def create_formats_func(self): return create_formats(self, add_css=False) def tag_ok_for_spell(self, name): return XMLUserData.tag_ok_for_spell(name) def profile(): import sys from qt.core import QTextDocument from calibre.gui2 import Application from calibre.gui2.tweak_book import set_book_locale from calibre.gui2.tweak_book.editor.themes import get_theme app = Application([]) set_book_locale('en') with open(sys.argv[-2], 'rb') as f: raw = f.read().decode('utf-8') doc = QTextDocument() doc.setPlainText(raw) h = Highlighter() theme = get_theme(tprefs['editor_theme']) h.apply_theme(theme) h.set_document(doc) h.join() import cProfile print('Running profile on', sys.argv[-2]) h.rehighlight() cProfile.runctx('h.join()', {}, {'h':h}, sys.argv[-1]) print('Stats saved to:', sys.argv[-1]) del h del doc del app if __name__ == '__main__': from calibre.gui2.tweak_book.editor.widget import launch_editor launch_editor('''\ <!DOCTYPE html> <html xml:lang="en" lang="en"> <!-- --> <head> <meta charset="utf-8" /> <title>A title with a tag <span> in it, the tag is treated as normal text</title> <style type="text/css"> body { color: green; font-size: 12pt; } </style> <style type="text/css">p.small { font-size: x-small; color:gray }</style> </head id="invalid attribute on closing tag"> <body lang="en_IN"><p: <!-- The start of the actual body text --> <h1 lang="en_US">A heading that should appear in bold, with an <i>italic</i> word</h1> <p>Some text with inline formatting, that is syntax highlighted. A <b>bold</b> word, and an <em>italic</em> word. \ <i>Some italic text with a <b>bold-italic</b> word in </i>the middle.</p> <!-- Let's see what exotic constructs like namespace prefixes and empty attributes look like --> <svg:svg xmlns:svg="http://whatever" /> <input disabled><input disabled /><span attr=<></span> <!-- Non-breaking spaces are rendered differently from normal spaces, so that they stand out --> <p>Some\xa0words\xa0separated\xa0by\xa0non\u2011breaking\xa0spaces and non\u2011breaking hyphens.</p> <p>Some non-BMP unicode text:\U0001f431\U0001f431\U0001f431</p> </body> </html> ''', path_is_raw=True)
20,055
Python
.py
493
34.133874
124
0.624872
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,740
javascript.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/syntax/javascript.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' import re import pygments.unistring as uni from pygments.lexer import RegexLexer, default, include from pygments.token import Comment, Keyword, Name, Number, Operator, Punctuation, String, Text from calibre.gui2.tweak_book.editor.syntax.pygments_highlighter import create_highlighter from calibre.utils.resources import get_path as P from polyglot.builtins import native_string_type JS_IDENT_START = ('(?:[$_' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl') + ']|\\\\u[a-fA-F0-9]{4})') JS_IDENT_PART = ('(?:[$' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl', 'Mn', 'Mc', 'Nd', 'Pc') + '\u200c\u200d]|\\\\u[a-fA-F0-9]{4})') JS_IDENT = JS_IDENT_START + '(?:' + JS_IDENT_PART + ')*' class JavascriptLexer(RegexLexer): """ For JavaScript source code. This is based on the pygments JS highlighter, bu that does not handle multi-line comments in streaming mode, so we had to modify it. """ flags = re.UNICODE | re.MULTILINE tokens = { native_string_type('commentsandwhitespace'): [ (r'\s+', Text), (r'<!--', Comment), (r'//.*?$', Comment.Single), (r'/\*', Comment.Multiline, native_string_type('comment')) ], native_string_type('comment'): [ (r'[^*/]+', Comment.Multiline), (r'\*/', Comment.Multiline, native_string_type('#pop')), (r'[*/]', Comment.Multiline), ], native_string_type('slashstartsregex'): [ include(native_string_type('commentsandwhitespace')), (r'/(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/' r'([gim]+\b|\B)', String.Regex, native_string_type('#pop')), (r'(?=/)', Text, (native_string_type('#pop'), native_string_type('badregex'))), default(native_string_type('#pop')) ], native_string_type('badregex'): [ (r'\n', Text, native_string_type('#pop')) ], native_string_type('root'): [ (r'\A#! ?/.*?\n', Comment), # shebang lines are recognized by node.js (r'^(?=\s|/|<!--)', Text, native_string_type('slashstartsregex')), include(native_string_type('commentsandwhitespace')), (r'\+\+|--|~|&&|\?|:|\|\||\\(?=\n)|' r'(<<|>>>?|==?|!=?|[-<>+*%&|^/])=?', Operator, native_string_type('slashstartsregex')), (r'[{(\[;,]', Punctuation, native_string_type('slashstartsregex')), (r'[})\].]', Punctuation), (r'(for|in|while|do|break|return|continue|switch|case|default|if|else|' r'throw|try|catch|finally|new|delete|typeof|instanceof|void|yield|' r'this)\b', Keyword, native_string_type('slashstartsregex')), (r'(var|let|with|function)\b', Keyword.Declaration, native_string_type('slashstartsregex')), (r'(abstract|boolean|byte|char|class|const|debugger|double|enum|export|' r'extends|final|float|goto|implements|import|int|interface|long|native|' r'package|private|protected|public|short|static|super|synchronized|throws|' r'transient|volatile)\b', Keyword.Reserved), (r'(true|false|null|NaN|Infinity|undefined)\b', Keyword.Constant), (r'(Array|Boolean|Date|Error|Function|Math|netscape|' r'Number|Object|Packages|RegExp|String|sun|decodeURI|' r'decodeURIComponent|encodeURI|encodeURIComponent|' r'Error|eval|isFinite|isNaN|parseFloat|parseInt|document|this|' r'window)\b', Name.Builtin), (JS_IDENT, Name.Other), (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float), (r'0x[0-9a-fA-F]+', Number.Hex), (r'[0-9]+', Number.Integer), (r'"(\\\\|\\"|[^"])*"', String.Double), (r"'(\\\\|\\'|[^'])*'", String.Single), ] } Highlighter = create_highlighter('JavascriptHighlighter', JavascriptLexer) if __name__ == '__main__': from calibre.gui2.tweak_book.editor.widget import launch_editor launch_editor(P('viewer.js'), syntax='javascript')
4,236
Python
.py
79
43.772152
104
0.567463
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,741
base.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/syntax/base.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' from collections import defaultdict, deque from qt.core import QTextBlock, QTextBlockUserData, QTextCursor, QTextFormat, QTextLayout, QTimer from calibre.gui2.widgets import BusyCursor from calibre.utils.icu import utf16_length from polyglot.builtins import iteritems from ..themes import highlight_to_char_format def run_loop(user_data, state_map, formats, text): state = user_data.state i = 0 fix_offsets = utf16_length(text) != len(text) seen_states = defaultdict(set) while i < len(text): orig_i = i seen_states[i].add(state.parse) fmt = state_map[state.parse](state, text, i, formats, user_data) for num, f in fmt: if num > 0: if fix_offsets: # We need to map offsets/lengths from UCS-4 to UTF-16 in # which non-BMP characters are two code points wide yield utf16_length(text[:i]), utf16_length(text[i:i+num]), f else: yield i, num, f i += num if orig_i == i and state.parse in seen_states[i]: # Something went wrong in the syntax highlighter print('Syntax highlighter returned a zero length format, parse state:', state.parse) break class SimpleState: __slots__ = ('parse',) def __init__(self): self.parse = 0 def copy(self): s = SimpleState() s.parse = self.parse return s class SimpleUserData(QTextBlockUserData): def __init__(self): QTextBlockUserData.__init__(self) self.state = SimpleState() self.doc_name = None def clear(self, state=None, doc_name=None): self.state = SimpleState() if state is None else state self.doc_name = doc_name class SyntaxHighlighter: def create_formats_func(highlighter): return {} spell_attributes = () def tag_ok_for_spell(x): return False user_data_factory = SimpleUserData def __init__(self): self.doc = None self.doc_name = None self.requests = deque() self.ignore_requests = False @property def has_requests(self): return bool(self.requests) def apply_theme(self, theme): self.theme = {k:highlight_to_char_format(v) for k, v in iteritems(theme)} self.create_formats() self.rehighlight() def create_formats(self): self.formats = self.create_formats_func() def set_document(self, doc, doc_name=None): old_doc = self.doc if old_doc is not None: old_doc.contentsChange.disconnect(self.reformat_blocks) c = QTextCursor(old_doc) c.beginEditBlock() blk = old_doc.begin() while blk.isValid(): blk.layout().clearFormats() blk = blk.next() c.endEditBlock() self.doc = self.doc_name = None if doc is not None: self.doc = doc self.doc_name = doc_name doc.contentsChange.connect(self.reformat_blocks) self.rehighlight() def rehighlight(self): doc = self.doc if doc is None: return lb = doc.lastBlock() with BusyCursor(): self.reformat_blocks(0, 0, lb.position() + lb.length()) def get_user_data(self, block): ud = block.userData() new_data = False if ud is None: ud = self.user_data_factory() block.setUserData(ud) new_data = True return ud, new_data def reformat_blocks(self, position, removed, added): doc = self.doc if doc is None or self.ignore_requests or not hasattr(self, 'state_map'): return block = doc.findBlock(position) if not block.isValid(): return start_cursor = QTextCursor(block) last_block = doc.findBlock(position + added + (1 if removed > 0 else 0)) if not last_block.isValid(): last_block = doc.lastBlock() end_cursor = QTextCursor(last_block) end_cursor.movePosition(QTextCursor.MoveOperation.EndOfBlock) self.requests.append((start_cursor, end_cursor)) QTimer.singleShot(0, self.do_one_block) def do_one_block(self): try: start_cursor, end_cursor = self.requests[0] except IndexError: return self.ignore_requests = True try: block = start_cursor.block() if not block.isValid(): self.requests.popleft() return formats, force_next_highlight = self.parse_single_block(block) self.apply_format_changes(block, formats) try: self.doc.markContentsDirty(block.position(), block.length()) except AttributeError: self.requests.clear() return ok = start_cursor.movePosition(QTextCursor.MoveOperation.NextBlock) if not ok: self.requests.popleft() return next_block = start_cursor.block() if next_block.position() > end_cursor.position(): if force_next_highlight: end_cursor.setPosition(next_block.position() + 1) else: self.requests.popleft() return finally: self.ignore_requests = False QTimer.singleShot(0, self.do_one_block) def join(self): ''' Blocks until all pending highlighting requests are handled ''' doc = self.doc if doc is None: self.requests.clear() return self.ignore_requests = True try: while self.requests: start_cursor, end_cursor = self.requests.popleft() block = start_cursor.block() last_block = end_cursor.block() if not last_block.isValid(): last_block = doc.lastBlock() end_pos = last_block.position() + last_block.length() force_next_highlight = False while block.isValid() and (force_next_highlight or block.position() < end_pos): formats, force_next_highlight = self.parse_single_block(block) self.apply_format_changes(block, formats) doc.markContentsDirty(block.position(), block.length()) block = block.next() finally: self.ignore_requests = False @property def is_working(self): return bool(self.requests) def parse_single_block(self, block): ud, is_new_ud = self.get_user_data(block) orig_state = ud.state pblock = block.previous() if pblock.isValid(): start_state = pblock.userData() if start_state is None: start_state = self.user_data_factory().state else: start_state = start_state.state.copy() else: start_state = self.user_data_factory().state ud.clear(state=start_state, doc_name=self.doc_name) # Ensure no stale user data lingers formats = [] for i, num, fmt in run_loop(ud, self.state_map, self.formats, str(block.text())): if fmt is not None: r = QTextLayout.FormatRange() r.start, r.length, r.format = i, num, fmt formats.append(r) force_next_highlight = is_new_ud or ud.state != orig_state return formats, force_next_highlight def reformat_block(self, block): if block.isValid(): self.reformat_blocks(block.position(), 0, 1) def apply_format_changes(self, block, formats): layout = block.layout() preedit_start = layout.preeditAreaPosition() preedit_length = len(layout.preeditAreaText()) if preedit_length != 0 and preedit_start != 0: for r in formats: # Adjust range by pre-edit text, if any if r.start >= preedit_start: r.start += preedit_length elif r.start + r.length >= preedit_start: r.length += preedit_length layout.setFormats(formats) def formats_for_line(self, block: QTextBlock, start, length): layout = block.layout() start_in_block = start - block.position() limit = start_in_block + length for f in layout.formats(): if f.start >= start_in_block and f.start < limit and f.format.hasProperty(QTextFormat.Property.BackgroundBrush): yield f
8,779
Python
.py
216
29.777778
124
0.583255
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,742
css.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/editor/syntax/css.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' import re from qt.core import QTextBlockUserData from calibre.gui2.tweak_book import verify_link from calibre.gui2.tweak_book.editor import CSS_PROPERTY, LINK_PROPERTY, syntax_text_char_format from calibre.gui2.tweak_book.editor.syntax.base import SyntaxHighlighter from polyglot.builtins import iteritems space_pat = re.compile(r'[ \n\t\r\f]+') cdo_pat = re.compile(r'/\*') sheet_tokens = [(re.compile(k), v, n) for k, v, n in [ (r'\:[a-zA-Z0-9_-]+', 'pseudo_selector', 'pseudo-selector'), (r'\.[a-zA-Z0-9_-]+', 'class_selector', 'class-selector'), (r'\#[a-zA-Z0-9_-]+', 'id_selector', 'id-selector'), (r'@[a-zA-Z0-9_-]+', 'preproc', 'atrule'), (r'[a-zA-Z0-9_-]+', 'tag', 'tag'), (r'[\$~\^\*!%&\[\]\(\)<>\|+=@:;,./?-]', 'operator', 'operator'), ]] URL_TOKEN = 'url' content_tokens = [(re.compile(k), v, n) for k, v, n in [ (r'url\(.*?\)', 'string', URL_TOKEN), (r'@\S+', 'preproc', 'at-rule'), (r'(azimuth|background-attachment|background-color|' r'background-image|background-position|background-repeat|' r'background|border-bottom-color|border-bottom-style|' r'border-bottom-width|border-left-color|border-left-style|' r'border-left-width|border-right-color|' r'border-right-style|border-right-width|border-right|border-top-color|' r'border-top-style|border-top-width|border-bottom|' r'border-collapse|border-left|border-width|border-color|' r'border-spacing|border-style|border-top|border-box|border|box-sizing|caption-side|' r'clear|clip|color|content-box|content|counter-increment|counter-reset|' r'cue-after|cue-before|cue|cursor|direction|display|' r'elevation|empty-cells|float|font-family|font-size|' r'font-size-adjust|font-stretch|font-style|font-variant|' r'font-weight|font|height|letter-spacing|line-height|panose-1|' r'list-style-type|list-style-image|list-style-position|' r'list-style|margin-bottom|margin-left|margin-right|' r'margin-top|margin|marker-offset|marks|max-height|max-width|' r'min-height|min-width|opacity|orphans|outline|outline-color|' r'outline-style|outline-width|overflow(?:-x|-y)?|padding-bottom|' r'padding-left|padding-right|padding-top|padding|' r'page-break-after|page-break-before|page-break-inside|' r'break-before|break-after|break-inside|' r'pause-after|pause-before|pause|pitch|pitch-range|' r'play-during|position|pre-wrap|pre-line|pre|quotes|richness|right|size|' r'speak-header|speak-numeral|speak-punctuation|speak|' r'speech-rate|stress|table-layout|text-align|text-decoration|' r'text-indent|text-shadow|text-transform|top|unicode-bidi|' r'vertical-align|visibility|voice-family|volume|white-space|' r'widows|width|word-spacing|z-index|bottom|left|' r'above|absolute|always|armenian|aural|auto|avoid|baseline|' r'behind|below|bidi-override|blink|block|bold|bolder|both|' r'capitalize|center-left|center-right|center|circle|' r'cjk-ideographic|close-quote|collapse|condensed|continuous|' r'crop|crosshair|cross|cursive|dashed|decimal-leading-zero|' r'decimal|default|digits|disc|dotted|double|e-resize|embed|' r'extra-condensed|extra-expanded|expanded|fantasy|far-left|' r'far-right|faster|fast|fixed|georgian|groove|hebrew|help|' r'hidden|hide|higher|high|hiragana-iroha|hiragana|icon|' r'inherit|inline-table|inline|inset|inside|invert|italic|' r'justify|katakana-iroha|katakana|landscape|larger|large|' r'left-side|leftwards|level|lighter|line-through|list-item|' r'loud|lower-alpha|lower-greek|lower-roman|lowercase|ltr|' r'lower|low|medium|message-box|middle|mix|monospace|' r'n-resize|narrower|ne-resize|no-close-quote|no-open-quote|' r'no-repeat|none|normal|nowrap|nw-resize|oblique|once|' r'open-quote|outset|outside|overline|pointer|portrait|px|' r'relative|repeat-x|repeat-y|repeat|rgb|ridge|right-side|' r'rightwards|s-resize|sans-serif|scroll|se-resize|' r'semi-condensed|semi-expanded|separate|serif|show|silent|' r'slow|slower|small-caps|small-caption|smaller|small|soft|solid|' r'spell-out|square|static|status-bar|super|sub|sw-resize|' r'table-caption|table-cell|table-column|table-column-group|' r'table-footer-group|table-header-group|' r'table-row-group|table-row|table|text|text-bottom|text-top|thick|thin|' r'transparent|ultra-condensed|ultra-expanded|underline|' r'upper-alpha|upper-latin|upper-roman|uppercase|url|' r'visible|w-resize|wait|wider|x-fast|x-high|x-large|x-loud|' r'x-low|x-small|x-soft|xx-large|xx-small|yes|src)\b', 'keyword', 'keyword'), (r'(indigo|gold|firebrick|indianred|yellow|darkolivegreen|' r'darkseagreen|mediumvioletred|mediumorchid|chartreuse|' r'mediumslateblue|black|springgreen|crimson|lightsalmon|brown|' r'turquoise|olivedrab|cyan|silver|skyblue|gray|darkturquoise|' r'goldenrod|darkgreen|darkviolet|darkgray|lightpink|teal|' r'darkmagenta|lightgoldenrodyellow|lavender|yellowgreen|thistle|' r'violet|navy|orchid|blue|ghostwhite|honeydew|cornflowerblue|' r'darkblue|darkkhaki|mediumpurple|cornsilk|red|bisque|slategray|' r'darkcyan|khaki|wheat|deepskyblue|darkred|steelblue|aliceblue|' r'gainsboro|mediumturquoise|floralwhite|coral|purple|lightgrey|' r'lightcyan|darksalmon|beige|azure|lightsteelblue|oldlace|' r'greenyellow|royalblue|lightseagreen|mistyrose|sienna|' r'lightcoral|orangered|navajowhite|lime|palegreen|burlywood|' r'seashell|mediumspringgreen|fuchsia|papayawhip|blanchedalmond|' r'peru|aquamarine|white|darkslategray|ivory|dodgerblue|' r'lemonchiffon|chocolate|orange|forestgreen|slateblue|olive|' r'mintcream|antiquewhite|darkorange|cadetblue|moccasin|' r'limegreen|saddlebrown|darkslateblue|lightskyblue|deeppink|' r'plum|aqua|darkgoldenrod|maroon|sandybrown|magenta|tan|' r'rosybrown|pink|lightblue|palevioletred|mediumseagreen|' r'dimgray|powderblue|seagreen|snow|mediumblue|midnightblue|' r'paleturquoise|palegoldenrod|whitesmoke|darkorchid|salmon|' r'lightslategray|lawngreen|lightgreen|tomato|hotpink|' r'lightyellow|lavenderblush|linen|mediumaquamarine|green|' r'blueviolet|peachpuff)\b', 'colorname', 'colorname'), (r'\!important', 'preproc', 'important'), (r'\#[a-zA-Z0-9]{1,6}', 'number', 'hexnumber'), (r'[\.-]?[0-9]*[\.]?[0-9]+(em|px|pt|pc|in|mm|cm|ex|q|rem)\b', 'number', 'dimension'), (r'[\.-]?[0-9]*[\.]?[0-9]+%(?=$|[ \n\t\f\r;}{()\[\]])', 'number', 'dimension'), (r'-?[0-9]+', 'number', 'number'), (r'[~\^\*!%&<>\|+=@:,./?-]+', 'operator', 'operator'), (r'[\[\]();]+', 'bracket', 'bracket'), (r'[a-zA-Z_][a-zA-Z0-9_]*', 'identifier', 'ident') ]] NORMAL = 0 IN_COMMENT_NORMAL = 1 IN_SQS = 2 IN_DQS = 3 IN_CONTENT = 4 IN_COMMENT_CONTENT = 5 class CSSState: __slots__ = ('parse', 'blocks') def __init__(self): self.parse = NORMAL self.blocks = 0 def copy(self): s = CSSState() s.parse, s.blocks = self.parse, self.blocks return s def __eq__(self, other): return self.parse == getattr(other, 'parse', -1) and \ self.blocks == getattr(other, 'blocks', -1) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return f"CSSState(parse={self.parse}, blocks={self.blocks})" __str__ = __repr__ class CSSUserData(QTextBlockUserData): def __init__(self): QTextBlockUserData.__init__(self) self.state = CSSState() self.doc_name = None def clear(self, state=None, doc_name=None): self.state = CSSState() if state is None else state self.doc_name = doc_name def normal(state, text, i, formats, user_data): ' The normal state (outside content blocks {})' m = space_pat.match(text, i) if m is not None: return [(len(m.group()), None)] cdo = cdo_pat.match(text, i) if cdo is not None: state.parse = IN_COMMENT_NORMAL return [(len(cdo.group()), formats['comment'])] if text[i] == '"': state.parse = IN_DQS return [(1, formats['string'])] if text[i] == "'": state.parse = IN_SQS return [(1, formats['string'])] if text[i] == '{': state.parse = IN_CONTENT state.blocks += 1 return [(1, formats['bracket'])] for token, fmt, name in sheet_tokens: m = token.match(text, i) if m is not None: return [(len(m.group()), formats[fmt])] return [(len(text) - i, formats['unknown-normal'])] def content(state, text, i, formats, user_data): ' Inside content blocks ' m = space_pat.match(text, i) if m is not None: return [(len(m.group()), None)] cdo = cdo_pat.match(text, i) if cdo is not None: state.parse = IN_COMMENT_CONTENT return [(len(cdo.group()), formats['comment'])] if text[i] == '"': state.parse = IN_DQS return [(1, formats['string'])] if text[i] == "'": state.parse = IN_SQS return [(1, formats['string'])] if text[i] == '}': state.blocks -= 1 state.parse = NORMAL if state.blocks < 1 else IN_CONTENT return [(1, formats['bracket'])] if text[i] == '{': state.blocks += 1 return [(1, formats['bracket'])] for token, fmt, name in content_tokens: m = token.match(text, i) if m is not None: if name is URL_TOKEN: h = 'link' url = m.group() prefix, main, suffix = url[:4], url[4:-1], url[-1] if len(main) > 1 and main[0] in ('"', "'") and main[0] == main[-1]: prefix += main[0] suffix = main[-1] + suffix main = main[1:-1] h = 'bad_link' if verify_link(main, user_data.doc_name) is False else 'link' return [(len(prefix), formats[fmt]), (len(main), formats[h]), (len(suffix), formats[fmt])] return [(len(m.group()), formats[fmt])] return [(len(text) - i, formats['unknown-normal'])] def comment(state, text, i, formats, user_data): ' Inside a comment ' pos = text.find('*/', i) if pos == -1: return [(len(text), formats['comment'])] state.parse = NORMAL if state.parse == IN_COMMENT_NORMAL else IN_CONTENT return [(pos - i + 2, formats['comment'])] def in_string(state, text, i, formats, user_data): 'Inside a string' q = '"' if state.parse == IN_DQS else "'" pos = text.find(q, i) if pos == -1: if text[-1] == '\\': # Multi-line string return [(len(text) - i, formats['string'])] state.parse = (NORMAL if state.blocks < 1 else IN_CONTENT) return [(len(text) - i, formats['unterminated-string'])] state.parse = (NORMAL if state.blocks < 1 else IN_CONTENT) return [(pos - i + len(q), formats['string'])] state_map = { NORMAL:normal, IN_COMMENT_NORMAL: comment, IN_COMMENT_CONTENT: comment, IN_SQS: in_string, IN_DQS: in_string, IN_CONTENT: content, } def create_formats(highlighter): theme = highlighter.theme formats = { 'comment': theme['Comment'], 'error': theme['Error'], 'string': theme['String'], 'colorname': theme['Constant'], 'number': theme['Number'], 'operator': theme['Function'], 'bracket': theme['Special'], 'identifier': theme['Identifier'], 'id_selector': theme['Special'], 'class_selector': theme['Special'], 'pseudo_selector': theme['Special'], 'tag': theme['Identifier'], } for name, msg in iteritems({ 'unknown-normal': _('Invalid text'), 'unterminated-string': _('Unterminated string'), }): f = formats[name] = syntax_text_char_format(formats['error']) f.setToolTip(msg) formats['link'] = syntax_text_char_format(theme['Link']) formats['link'].setToolTip(_('Hold down the Ctrl key and click to open this link')) formats['link'].setProperty(LINK_PROPERTY, True) formats['bad_link'] = syntax_text_char_format(theme['BadLink']) formats['bad_link'].setProperty(LINK_PROPERTY, True) formats['bad_link'].setToolTip(_('This link points to a file that is not present in the book')) formats['preproc'] = f = syntax_text_char_format(theme['PreProc']) f.setProperty(CSS_PROPERTY, True) formats['keyword'] = f = syntax_text_char_format(theme['Keyword']) f.setProperty(CSS_PROPERTY, True) return formats class Highlighter(SyntaxHighlighter): state_map = state_map create_formats_func = create_formats user_data_factory = CSSUserData if __name__ == '__main__': from calibre.gui2.tweak_book.editor.widget import launch_editor launch_editor('''\ @charset "utf-8"; /* A demonstration css sheet */ body { color: green; box-sizing: border-box; font-size: 12pt } div#main > a:hover { background: url("../image.png"); font-family: "A font", sans-serif; } li[rel="mewl"], p.mewl { margin-top: 2% 0 23pt 1em; } ''', path_is_raw=True, syntax='css')
13,240
Python
.py
289
39.792388
106
0.655862
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,743
worker.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/completion/worker.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' from collections import namedtuple from multiprocessing.connection import Pipe from threading import Event, RLock, Thread from calibre.constants import iswindows from calibre.gui2.tweak_book.completion.basic import Request from calibre.gui2.tweak_book.completion.utils import DataError from calibre.utils.ipc import eintr_retry_call from polyglot.queue import Queue COMPLETION_REQUEST = 'completion request' CLEAR_REQUEST = 'clear request' class CompletionWorker(Thread): daemon = True def __init__(self, result_callback=lambda x:x, worker_entry_point='main'): Thread.__init__(self) self.worker_entry_point = worker_entry_point self.start() self.main_queue = Queue() self.result_callback = result_callback self.reap_thread = None self.shutting_down = False self.connected = Event() self.latest_completion_request_id = None self.request_count = 0 self.lock = RLock() def launch_worker_process(self): from calibre.utils.ipc.pool import start_worker control_a, control_b = Pipe() data_a, data_b = Pipe() with control_a, data_a: pass_fds = control_a.fileno(), data_a.fileno() self.worker_process = p = start_worker( 'from {0} import run_main, {1}; run_main({2}, {3}, {1})'.format( self.__class__.__module__, self.worker_entry_point, *pass_fds), pass_fds ) p.stdin.close() self.control_conn = control_b self.data_conn = data_b self.data_thread = t = Thread(name='CWData', target=self.handle_data_requests) t.daemon = True t.start() self.connected.set() def send(self, data, conn=None): conn = conn or self.control_conn try: eintr_retry_call(conn.send, data) except: if not self.shutting_down: raise def recv(self, conn=None): conn = conn or self.control_conn try: return eintr_retry_call(conn.recv) except: if not self.shutting_down: raise def wait_for_connection(self, timeout=None): self.connected.wait(timeout) def handle_data_requests(self): from calibre.gui2.tweak_book.completion.basic import handle_data_request while True: try: req = self.recv(self.data_conn) except EOFError: break except Exception: import traceback traceback.print_exc() break if req is None or self.shutting_down: break result, tb = handle_data_request(req) try: self.send((result, tb), self.data_conn) except EOFError: break except Exception: import traceback traceback.print_exc() break def run(self): self.launch_worker_process() while True: obj = self.main_queue.get() if obj is None: break req_type, req_data = obj try: if req_type is COMPLETION_REQUEST: self.send_completion_request(req_data) elif req_type is CLEAR_REQUEST: self.send(req_data) except EOFError: break except Exception: import traceback traceback.print_exc() def send_completion_request(self, request): self.send(request) result = self.recv() latest_completion_request_id = self.latest_completion_request_id if result is not None and result.request_id == latest_completion_request_id: try: self.result_callback(result) except Exception: import traceback traceback.print_exc() def clear_caches(self, cache_type=None): self.main_queue.put((CLEAR_REQUEST, Request(None, 'clear_caches', cache_type, None))) def queue_completion(self, request_id, completion_type, completion_data, query=None): with self.lock: ccr = Request(request_id, completion_type, completion_data, query) self.latest_completion_request_id = ccr.id self.main_queue.put((COMPLETION_REQUEST, ccr)) def shutdown(self): self.shutting_down = True self.main_queue.put(None) for conn in (getattr(self, 'control_conn', None), getattr(self, 'data_conn', None)): try: conn.close() except Exception: pass p = self.worker_process if p.poll() is None: self.worker_process.terminate() t = self.reap_thread = Thread(target=p.wait) t.daemon = True t.start() def join(self, timeout=0.2): if self.reap_thread is not None: self.reap_thread.join(timeout) if not iswindows and self.worker_process.returncode is None: self.worker_process.kill() return self.worker_process.returncode _completion_worker = None def completion_worker(): global _completion_worker if _completion_worker is None: _completion_worker = CompletionWorker() return _completion_worker def run_main(control_fd, data_fd, func): if iswindows: from multiprocessing.connection import PipeConnection as Connection else: from multiprocessing.connection import Connection with Connection(control_fd) as control_conn, Connection(data_fd) as data_conn: func(control_conn, data_conn) Result = namedtuple('Result', 'request_id ans traceback query') def main(control_conn, data_conn): from calibre.gui2.tweak_book.completion.basic import handle_control_request while True: try: request = eintr_retry_call(control_conn.recv) except (KeyboardInterrupt, EOFError): break if request is None: break try: ans, tb = handle_control_request(request, data_conn), None except DataError as err: ans, tb = None, err.traceback() except Exception: import traceback ans, tb = None, traceback.format_exc() if request.id is not None: result = Result(request.id, ans, tb, request.query) try: eintr_retry_call(control_conn.send, result) except EOFError: break def test_main(control_conn, data_conn): obj = control_conn.recv() dobj = data_conn.recv() control_conn.send((obj, dobj)) def test(): w = CompletionWorker(worker_entry_point='test_main') w.wait_for_connection() w.data_conn.send('got the data') w.send('Hello World!') print(w.recv()) w.shutdown(), w.join()
7,054
Python
.py
184
28.347826
93
0.60313
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,744
basic.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/completion/basic.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' from collections import OrderedDict, namedtuple from threading import Event from qt.core import QObject, Qt, pyqtSignal from calibre import prepare_string_for_xml from calibre.ebooks.oeb.polish.container import OEB_STYLES, name_to_href from calibre.ebooks.oeb.polish.parsing import parse from calibre.ebooks.oeb.polish.report import description_for_anchor from calibre.ebooks.oeb.polish.utils import OEB_FONTS from calibre.gui2 import is_gui_thread from calibre.gui2.tweak_book import current_container, editors from calibre.gui2.tweak_book.completion.utils import DataError, control, data from calibre.utils.icu import numeric_sort_key from calibre.utils.ipc import eintr_retry_call from calibre.utils.matcher import Matcher from polyglot.builtins import iteritems, itervalues Request = namedtuple('Request', 'id type data query') names_cache = {} file_cache = {} @control def clear_caches(cache_type, data_conn): global names_cache, file_cache if cache_type is None: names_cache.clear() file_cache.clear() return if cache_type == 'names': names_cache.clear() elif cache_type.startswith('file:'): name = cache_type.partition(':')[2] file_cache.pop(name, None) if name.lower().endswith('.opf'): names_cache.clear() @data def names_data(request_data): c = current_container() return c.mime_map, {n for n, is_linear in c.spine_names} @data def file_data(name): 'Get the data for name. Returns a unicode string if name is a text document/stylesheet' if name in editors: return editors[name].get_raw_data() return current_container().raw_data(name) def get_data(data_conn, data_type, data=None): eintr_retry_call(data_conn.send, Request(None, data_type, data, None)) result, tb = eintr_retry_call(data_conn.recv) if tb: raise DataError(tb) return result class Name(str): def __new__(self, name, mime_type, spine_names): ans = str.__new__(self, name) ans.mime_type = mime_type ans.in_spine = name in spine_names return ans @control def complete_names(names_data, data_conn): if not names_cache: mime_map, spine_names = get_data(data_conn, 'names_data') names_cache[None] = all_names = frozenset(Name(name, mt, spine_names) for name, mt in iteritems(mime_map)) names_cache['text_link'] = frozenset(n for n in all_names if n.in_spine) names_cache['stylesheet'] = frozenset(n for n in all_names if n.mime_type in OEB_STYLES) names_cache['image'] = frozenset(n for n in all_names if n.mime_type.startswith('image/')) names_cache['font'] = frozenset(n for n in all_names if n.mime_type in OEB_FONTS) names_cache['css_resource'] = names_cache['image'] | names_cache['font'] names_cache['descriptions'] = d = {} for x, desc in iteritems({'text_link':_('Text'), 'stylesheet':_('Stylesheet'), 'image':_('Image'), 'font':_('Font')}): for n in names_cache[x]: d[n] = desc names_type, base, root = names_data quote = (lambda x:x) if base.lower().endswith('.css') else prepare_string_for_xml names = names_cache.get(names_type, names_cache[None]) nmap = {name:name_to_href(name, root, base, quote) for name in names} items = tuple(sorted(frozenset(itervalues(nmap)), key=numeric_sort_key)) d = names_cache['descriptions'].get descriptions = {href:d(name) for name, href in iteritems(nmap)} return items, descriptions, {} def create_anchor_map(root): ans = {} for elem in root.xpath('//*[@id or @name]'): anchor = elem.get('id') or elem.get('name') if anchor and anchor not in ans: ans[anchor] = description_for_anchor(elem) return ans @control def complete_anchor(name, data_conn): if name not in file_cache: data = raw = get_data(data_conn, 'file_data', name) if isinstance(raw, str): try: root = parse(raw, decoder=lambda x:x.decode('utf-8')) except Exception: pass else: data = (root, create_anchor_map(root)) file_cache[name] = data data = file_cache[name] if isinstance(data, tuple) and len(data) > 1 and isinstance(data[1], dict): return tuple(sorted(frozenset(data[1]), key=numeric_sort_key)), data[1], {} _current_matcher = (None, None, None) def handle_control_request(request, data_conn): global _current_matcher ans = control_funcs[request.type](request.data, data_conn) if ans is not None: items, descriptions, matcher_kwargs = ans fingerprint = hash(items) if fingerprint != _current_matcher[0] or matcher_kwargs != _current_matcher[1]: _current_matcher = (fingerprint, matcher_kwargs, Matcher(items, **matcher_kwargs)) if request.query: items = _current_matcher[-1](request.query, limit=50) else: items = OrderedDict((i, ()) for i in _current_matcher[-1].items) ans = items, descriptions return ans class HandleDataRequest(QObject): # Ensure data is obtained in the GUI thread call = pyqtSignal(object, object) def __init__(self): QObject.__init__(self) self.called = Event() self.call.connect(self.run_func, Qt.ConnectionType.QueuedConnection) def run_func(self, func, data): try: self.result, self.tb = func(data), None except Exception: import traceback self.result, self.tb = None, traceback.format_exc() finally: self.called.set() def __call__(self, request): func = data_funcs[request.type] if is_gui_thread(): try: return func(request.data), None except Exception: import traceback return None, traceback.format_exc() self.called.clear() self.call.emit(func, request.data) self.called.wait() try: return self.result, self.tb finally: del self.result, self.tb handle_data_request = HandleDataRequest() control_funcs = {name:func for name, func in iteritems(globals()) if getattr(func, 'function_type', None) == 'control'} data_funcs = {name:func for name, func in iteritems(globals()) if getattr(func, 'function_type', None) == 'data'}
6,527
Python
.py
149
36.885906
126
0.656467
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,745
utils.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/completion/utils.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' def control(func): func.function_type = 'control' return func def data(func): func.function_type = 'data' return func class DataError(Exception): def __init__(self, tb, msg=None): Exception.__init__(self, msg or _('Failed to get completion data')) self.tb = tb def traceback(self): return str(self) + '\n' + self.tb
480
Python
.py
15
27.2
75
0.640351
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,746
popup.py
kovidgoyal_calibre/src/calibre/gui2/tweak_book/completion/popup.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' import textwrap from math import ceil from qt.core import QEvent, QPainter, QPalette, QSize, QStaticText, Qt, QTextCursor, QTextOption, QTimer, QWidget from calibre import prepare_string_for_xml, prints from calibre.gui2 import error_dialog from calibre.gui2.tweak_book.widgets import make_highlighted_text from calibre.utils.icu import string_length from polyglot.builtins import iteritems class ChoosePopupWidget(QWidget): TOP_MARGIN = BOTTOM_MARGIN = 2 SIDE_MARGIN = 4 def __init__(self, parent, max_height=1000): QWidget.__init__(self, parent) self.setFocusPolicy(Qt.FocusPolicy.NoFocus) self.setFocusProxy(parent) self.setVisible(False) self.setMouseTracking(True) self.setCursor(Qt.CursorShape.PointingHandCursor) self.current_results = self.current_size_hint = None self.max_text_length = 0 self.current_index = -1 self.current_top_index = 0 self.max_height = max_height self.text_option = to = QTextOption() to.setWrapMode(QTextOption.WrapMode.NoWrap) to.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter) self.rendered_text_cache = {} parent.installEventFilter(self) self.relayout_timer = t = QTimer(self) t.setSingleShot(True), t.setInterval(25), t.timeout.connect(self.layout) def clear_caches(self): self.rendered_text_cache.clear() self.current_size_hint = None def set_items(self, items, descriptions=None): self.current_results = items self.current_size_hint = None self.descriptions = descriptions or {} self.clear_caches() self.max_text_length = 0 self.current_index = -1 self.current_top_index = 0 if self.current_results: self.max_text_length = max(string_length(text) for text, pos in self.current_results) def get_static_text(self, otext, positions): st = self.rendered_text_cache.get(otext) if st is None: text = (otext or '').ljust(self.max_text_length + 1, '\xa0') text = make_highlighted_text('color: magenta', text, positions) desc = self.descriptions.get(otext) if desc: text += ' - <i>%s</i>' % prepare_string_for_xml(desc) color = self.palette().color(QPalette.ColorRole.Text).name() text = f'<span style="color: {color}">{text}</span>' st = self.rendered_text_cache[otext] = QStaticText(text) st.setTextOption(self.text_option) st.setTextFormat(Qt.TextFormat.RichText) st.prepare(font=self.parent().font()) return st def sizeHint(self): if self.current_size_hint is None: max_width = height = 0 for text, positions in self.current_results: sz = self.get_static_text(text, positions).size() height += int(ceil(sz.height())) + self.BOTTOM_MARGIN max_width = max(max_width, int(ceil(sz.width()))) self.current_size_hint = QSize(max_width + 2 * self.SIDE_MARGIN, height + self.BOTTOM_MARGIN + self.TOP_MARGIN) return self.current_size_hint def iter_visible_items(self): y = self.TOP_MARGIN bottom = self.rect().bottom() for i, (text, positions) in enumerate(self.current_results[self.current_top_index:]): st = self.get_static_text(text, positions) height = self.BOTTOM_MARGIN + int(ceil(st.size().height())) if y + height > bottom: break yield i + self.current_top_index, st, y, height y += height def index_for_y(self, y): for idx, st, top, height in self.iter_visible_items(): if top <= y < top + height: return idx def paintEvent(self, ev): painter = QPainter(self) painter.setClipRect(ev.rect()) pal = self.palette() painter.fillRect(self.rect(), pal.color(QPalette.ColorRole.Text)) crect = self.rect().adjusted(1, 1, -1, -1) painter.fillRect(crect, pal.color(QPalette.ColorRole.Base)) painter.setClipRect(crect) painter.setFont(self.parent().font()) width = self.rect().width() for i, st, y, height in self.iter_visible_items(): painter.save() if i == self.current_index: painter.fillRect(1, y, width, height, pal.color(QPalette.ColorRole.Highlight)) color = pal.color(QPalette.ColorRole.HighlightedText).name() st = QStaticText(st) text = st.text().partition('>')[2] st.setText(f'<span style="color: {color}">{text}') painter.drawStaticText(self.SIDE_MARGIN, y, st) painter.restore() painter.end() if self.current_size_hint is None: QTimer.singleShot(0, self.layout) def layout(self, cursor_rect=None): p = self.parent() if cursor_rect is None: cursor_rect = p.cursorRect().adjusted(0, 0, 0, 2) gutter_width = p.gutter_width vp = p.viewport() above = cursor_rect.top() > vp.height() - cursor_rect.bottom() max_height = min(self.max_height, (cursor_rect.top() if above else vp.height() - cursor_rect.bottom()) - 15) max_width = vp.width() - 25 - gutter_width sz = self.sizeHint() height = min(max_height, sz.height()) width = min(max_width, sz.width()) left = cursor_rect.left() + gutter_width extra = max_width - (width + left) if extra < 0: left += extra top = (cursor_rect.top() - height) if above else cursor_rect.bottom() self.resize(width, height) self.move(left, top) self.update() def ensure_index_visible(self, index): if index < self.current_top_index: self.current_top_index = max(0, index) else: try: i = tuple(self.iter_visible_items())[-1][0] except IndexError: return if i < index: self.current_top_index += index - i def show(self): if self.current_results: self.layout() QWidget.show(self) self.raise_without_focus() def hide(self): QWidget.hide(self) self.relayout_timer.stop() abort = hide def activate_current_result(self): raise NotImplementedError('You must implement this method in a subclass') def handle_keypress(self, ev): key = ev.key() if key == Qt.Key.Key_Escape: self.abort(), ev.accept() return True if key == Qt.Key.Key_Tab and not ev.modifiers() & Qt.KeyboardModifier.ControlModifier: self.choose_next_result(previous=ev.modifiers() & Qt.KeyboardModifier.ShiftModifier) ev.accept() return True if key == Qt.Key.Key_Backtab and not ev.modifiers() & Qt.KeyboardModifier.ControlModifier: self.choose_next_result(previous=ev.modifiers() & Qt.KeyboardModifier.ShiftModifier) return True if key in (Qt.Key.Key_Up, Qt.Key.Key_Down): self.choose_next_result(previous=key == Qt.Key.Key_Up) return True return False def eventFilter(self, obj, ev): if obj is self.parent() and self.isVisible(): etype = ev.type() if etype == QEvent.Type.KeyPress: ret = self.handle_keypress(ev) if ret: ev.accept() return ret elif etype == QEvent.Type.Resize: self.relayout_timer.start() return False def mouseMoveEvent(self, ev): y = ev.pos().y() idx = self.index_for_y(y) if idx is not None and idx != self.current_index: self.current_index = idx self.update() ev.accept() def mouseReleaseEvent(self, ev): y = ev.pos().y() idx = self.index_for_y(y) if idx is not None: self.activate_current_result() self.hide() ev.accept() def choose_next_result(self, previous=False): if self.current_results: if previous: if self.current_index == -1: self.current_index = len(self.current_results) - 1 else: self.current_index -= 1 else: if self.current_index == len(self.current_results) - 1: self.current_index = -1 else: self.current_index += 1 self.ensure_index_visible(self.current_index) self.update() class CompletionPopup(ChoosePopupWidget): def __init__(self, parent, max_height=1000): ChoosePopupWidget.__init__(self, parent, max_height=max_height) self.completion_error_shown = False self.current_query = self.current_completion = None def set_items(self, items, descriptions=None, query=None): self.current_query = query ChoosePopupWidget.set_items(self, tuple(iteritems(items)), descriptions=descriptions) def choose_next_result(self, previous=False): ChoosePopupWidget.choose_next_result(self, previous=previous) self.activate_current_result() def activate_current_result(self): if self.current_completion is not None: c = self.current_completion text = self.current_query if self.current_index == -1 else self.current_results[self.current_index][0] c.insertText(text) chars = string_length(text) c.setPosition(c.position() - chars) c.setPosition(c.position() + chars, QTextCursor.MoveMode.KeepAnchor) def abort(self): ChoosePopupWidget.abort(self) self.current_completion = self.current_query = None def mark_completion(self, editor, query): self.current_completion = c = editor.textCursor() chars = string_length(query or '') c.setPosition(c.position() - chars), c.setPosition(c.position() + chars, QTextCursor.MoveMode.KeepAnchor) self.hide() def handle_result(self, result): if result.traceback: prints(result.traceback) if not self.completion_error_shown: error_dialog(self, _('Completion failed'), _( 'Failed to get completions, click "Show details" for more information.' ' Future errors during completion will be suppressed.'), det_msg=result.traceback, show=True) self.completion_error_shown = True self.hide() return if result.ans is None: self.hide() return items, descriptions = result.ans if not items: self.hide() return self.set_items(items, descriptions, result.query) self.show() if __name__ == '__main__': from calibre.utils.matcher import Matcher def test(editor): c = editor.__c = CompletionPopup(editor.editor, max_height=100) items = 'a ab abc abcd abcde abcdef abcdefg abcdefgh'.split() m = Matcher(items) c.set_items(m('a'), descriptions={x:x for x in items}) QTimer.singleShot(100, c.show) from calibre.gui2.tweak_book.editor.widget import launch_editor raw = textwrap.dedent('''\ Is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure. ''') launch_editor(raw, path_is_raw=True, callback=test)
12,298
Python
.py
270
35.388889
123
0.614704
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,747
catalog_csv_xml.py
kovidgoyal_calibre/src/calibre/gui2/catalog/catalog_csv_xml.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import sys from qt.core import QAbstractItemView, QHBoxLayout, QLabel, QListWidget, QListWidgetItem, QPushButton, Qt, QVBoxLayout, QWidget from calibre.constants import ismacos from calibre.gui2 import gprefs from calibre.gui2.ui import get_gui def get_saved_field_data(name, all_fields): db = get_gui().current_db val = db.new_api.pref('catalog-field-data-for-' + name) if val is None: sort_order = gprefs.get(name + '_db_fields_sort_order', {}) fields = frozenset(gprefs.get(name+'_db_fields', all_fields)) else: sort_order = val['sort_order'] fields = frozenset(val['fields']) return sort_order, fields def set_saved_field_data(name, fields, sort_order): db = get_gui().current_db db.new_api.set_pref('catalog-field-data-for-' + name, {'fields': fields, 'sort_order': sort_order}) gprefs.set(name+'_db_fields', fields) gprefs.set(name + '_db_fields_sort_order', sort_order) class ListWidgetItem(QListWidgetItem): def __init__(self, colname, human_name, position_in_booklist, parent): super().__init__(human_name, parent) self.setData(Qt.ItemDataRole.UserRole, colname) self.position_in_booklist = position_in_booklist def __lt__(self, other): try: return self.position_in_booklist < getattr(other, 'position_in_booklist', sys.maxsize) except TypeError: return False class PluginWidget(QWidget): TITLE = _('CSV/XML options') HELP = _('Options specific to')+' CSV/XML '+_('output') sync_enabled = False formats = {'csv', 'xml'} handles_scrolling = True def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QVBoxLayout(self) self.la = la = QLabel(_('Fields to include in output:')) la.setWordWrap(True) l.addWidget(la) self.db_fields = QListWidget(self) l.addWidget(self.db_fields) self.la2 = la = QLabel(_('Drag and drop to re-arrange fields')) self.db_fields.setDragEnabled(True) self.db_fields.setDragDropMode(QAbstractItemView.DragDropMode.InternalMove) self.db_fields.setDefaultDropAction(Qt.DropAction.CopyAction if ismacos else Qt.DropAction.MoveAction) self.db_fields.setAlternatingRowColors(True) self.db_fields.setObjectName("db_fields") h = QHBoxLayout() l.addLayout(h) h.addWidget(la), h.addStretch(10) self.select_all_button = b = QPushButton(_('Select &all')) b.clicked.connect(self.select_all) h.addWidget(b) self.select_all_button = b = QPushButton(_('Select &none')) b.clicked.connect(self.select_none) h.addWidget(b) self.select_visible_button = b = QPushButton(_('Select &visible')) b.clicked.connect(self.select_visible) b.setToolTip(_('Select the fields currently shown in the book list')) h.addWidget(b) self.order_button = b = QPushButton(_('&Sort by booklist')) b.clicked.connect(self.order_by_booklist) b.setToolTip(_('Sort the fields by their position in the book list')) h.addWidget(b) def select_all(self): for row in range(self.db_fields.count()): item = self.db_fields.item(row) item.setCheckState(Qt.CheckState.Checked) def select_none(self): for row in range(self.db_fields.count()): item = self.db_fields.item(row) item.setCheckState(Qt.CheckState.Unchecked) def select_visible(self): state = get_gui().library_view.get_state() hidden = frozenset(state['hidden_columns']) for row in range(self.db_fields.count()): item = self.db_fields.item(row) field = item.data(Qt.ItemDataRole.UserRole) item.setCheckState(Qt.CheckState.Unchecked if field in hidden else Qt.CheckState.Checked) def order_by_booklist(self): self.db_fields.sortItems() def initialize(self, catalog_name, db): self.name = catalog_name from calibre.library.catalogs import FIELDS db = get_gui().current_db self.all_fields = {x for x in FIELDS if x != 'all'} | set(db.custom_field_keys()) sort_order, fields = get_saved_field_data(self.name, self.all_fields) fm = db.field_metadata def name(x): if x == 'isbn': return 'ISBN' if x == 'library_name': return _('Library name') if x.endswith('_index'): return name(x[:-len('_index')]) + ' ' + _('Number') return fm[x].get('name') or x state = get_gui().library_view.get_state() cpos = state['column_positions'] def key(x): return (sort_order.get(x, 10000), name(x)) self.db_fields.clear() for x in sorted(self.all_fields, key=key): pos = cpos.get(x, sys.maxsize) if x == 'series_index': pos = cpos.get('series', sys.maxsize) ListWidgetItem(x, name(x) + ' (%s)' % x, pos, self.db_fields) if x.startswith('#') and fm[x]['datatype'] == 'series': x += '_index' ListWidgetItem(x, name(x) + ' (%s)' % x, pos, self.db_fields) # Restore the activated fields from last use for x in range(self.db_fields.count()): item = self.db_fields.item(x) item.setCheckState(Qt.CheckState.Checked if str(item.data(Qt.ItemDataRole.UserRole)) in fields else Qt.CheckState.Unchecked) def options(self): # Save the currently activated fields fields, all_fields = [], [] for x in range(self.db_fields.count()): item = self.db_fields.item(x) all_fields.append(str(item.data(Qt.ItemDataRole.UserRole))) if item.checkState() == Qt.CheckState.Checked: fields.append(str(item.data(Qt.ItemDataRole.UserRole))) set_saved_field_data(self.name, fields, {x:i for i, x in enumerate(all_fields)}) # Return a dictionary with current options for this widget if len(fields): return {'fields':fields} else: return {'fields':['all']}
6,363
Python
.py
134
38.567164
136
0.624839
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,748
catalog_bibtex.py
kovidgoyal_calibre/src/calibre/gui2/catalog/catalog_bibtex.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from qt.core import QListWidgetItem, QWidget from calibre.gui2 import gprefs from calibre.gui2.catalog.catalog_bibtex_ui import Ui_Form class PluginWidget(QWidget, Ui_Form): TITLE = _('BibTeX options') HELP = _('Options specific to')+' BibTeX '+_('output') OPTION_FIELDS = [('bib_cit','{authors}{id}'), ('bib_entry', 0), # mixed ('bibfile_enc', 0), # utf-8 ('bibfile_enctag', 0), # strict ('impcit', True), ('addfiles', False), ] sync_enabled = False formats = {'bib'} def __init__(self, parent=None): QWidget.__init__(self, parent) self.setupUi(self) def initialize(self, name, db): # not working properly to update from calibre.library.catalogs import FIELDS self.all_fields = [x for x in FIELDS if x != 'all'] # add custom columns for x in sorted(db.custom_field_keys()): self.all_fields.append(x) if db.field_metadata[x]['datatype'] == 'series': self.all_fields.append(x+'_index') # populate for x in self.all_fields: QListWidgetItem(x, self.db_fields) self.name = name fields = gprefs.get(name+'_db_fields', self.all_fields) # Restore the activated db_fields from last use for x in range(self.db_fields.count()): item = self.db_fields.item(x) item.setSelected(str(item.text()) in fields) self.bibfile_enc.clear() self.bibfile_enc.addItems(['utf-8', 'cp1252', 'ascii/LaTeX']) self.bibfile_enctag.clear() self.bibfile_enctag.addItems(['strict', 'replace', 'ignore', 'backslashreplace']) self.bib_entry.clear() self.bib_entry.addItems(['mixed', 'misc', 'book']) # Update dialog fields from stored options for opt in self.OPTION_FIELDS: opt_value = gprefs.get(self.name + '_' + opt[0], opt[1]) if opt[0] in ['bibfile_enc', 'bibfile_enctag', 'bib_entry']: getattr(self, opt[0]).setCurrentIndex(opt_value) elif opt[0] in ['impcit', 'addfiles'] : getattr(self, opt[0]).setChecked(opt_value) else: getattr(self, opt[0]).setText(opt_value) def options(self): # Save the currently activated fields fields = [] for x in range(self.db_fields.count()): item = self.db_fields.item(x) if item.isSelected(): fields.append(str(item.text())) gprefs.set(self.name+'_db_fields', fields) # Dictionary currently activated fields if len(self.db_fields.selectedItems()): opts_dict = {'fields':[str(i.text()) for i in self.db_fields.selectedItems()]} else: opts_dict = {'fields':['all']} # Save/return the current options # bib_cit stores as text # 'bibfile_enc','bibfile_enctag' stores as int (Indexes) for opt in self.OPTION_FIELDS: if opt[0] in ['bibfile_enc', 'bibfile_enctag', 'bib_entry']: opt_value = getattr(self,opt[0]).currentIndex() elif opt[0] in ['impcit', 'addfiles'] : opt_value = getattr(self, opt[0]).isChecked() else : opt_value = str(getattr(self, opt[0]).text()) gprefs.set(self.name + '_' + opt[0], opt_value) opts_dict[opt[0]] = opt_value return opts_dict
3,696
Python
.py
81
34.888889
90
0.567019
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,749
catalog_epub_mobi.py
kovidgoyal_calibre/src/calibre/gui2/catalog/catalog_epub_mobi.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import re import sys from functools import partial from qt.core import ( QAbstractItemView, QCheckBox, QComboBox, QDoubleSpinBox, QIcon, QInputDialog, QLineEdit, QRadioButton, QSize, QSizePolicy, Qt, QTableWidget, QTableWidgetItem, QTextEdit, QToolButton, QUrl, QVBoxLayout, QWidget, sip, ) from calibre.ebooks.conversion.config import load_defaults from calibre.gui2 import error_dialog, gprefs, open_url, question_dialog from calibre.utils.config import JSONConfig from calibre.utils.icu import sort_key from calibre.utils.localization import localize_user_manual_link from .catalog_epub_mobi_ui import Ui_Form class PluginWidget(QWidget,Ui_Form): TITLE = _('E-book options') HELP = _('Options specific to')+' AZW3/EPUB/MOBI '+_('output') DEBUG = False handles_scrolling = True # Output synced to the connected device? sync_enabled = True # Formats supported by this plugin formats = {'azw3','epub','mobi'} def __init__(self, parent=None): QWidget.__init__(self, parent) self.setupUi(self) self._initControlArrays() self.blocking_all_signals = None self.parent_ref = lambda: None def _initControlArrays(self): # Default values for controls CheckBoxControls = [] ComboBoxControls = [] DoubleSpinBoxControls = [] LineEditControls = [] RadioButtonControls = [] TableWidgetControls = [] TextEditControls = [] for item in self.__dict__: if type(self.__dict__[item]) is QCheckBox: CheckBoxControls.append(self.__dict__[item].objectName()) elif type(self.__dict__[item]) is QComboBox: ComboBoxControls.append(self.__dict__[item].objectName()) elif type(self.__dict__[item]) is QDoubleSpinBox: DoubleSpinBoxControls.append(self.__dict__[item].objectName()) elif type(self.__dict__[item]) is QLineEdit: LineEditControls.append(self.__dict__[item].objectName()) elif type(self.__dict__[item]) is QRadioButton: RadioButtonControls.append(self.__dict__[item].objectName()) elif type(self.__dict__[item]) is QTableWidget: TableWidgetControls.append(self.__dict__[item].objectName()) elif type(self.__dict__[item]) is QTextEdit: TextEditControls.append(self.__dict__[item].objectName()) option_fields = list(zip(CheckBoxControls, [True for i in CheckBoxControls], ['check_box' for i in CheckBoxControls])) option_fields += list(zip(ComboBoxControls, [None for i in ComboBoxControls], ['combo_box' for i in ComboBoxControls])) option_fields += list(zip(RadioButtonControls, [None for i in RadioButtonControls], ['radio_button' for i in RadioButtonControls])) # LineEditControls option_fields += list(zip(['exclude_genre'],[r'\[.+\]|^\+$'],['line_edit'])) # TextEditControls # option_fields += list(zip(['exclude_genre_results'],['excluded genres will appear here'],['text_edit'])) # SpinBoxControls option_fields += list(zip(['thumb_width'],[1.00],['spin_box'])) # Exclusion rules option_fields += list(zip(['exclusion_rules_tw'], [{'ordinal':0, 'enabled':True, 'name':_('Catalogs'), 'field':_('Tags'), 'pattern':'Catalog'},], ['table_widget'])) # Prefix rules option_fields += list(zip(['prefix_rules_tw','prefix_rules_tw'], [{'ordinal':0, 'enabled':True, 'name':_('Read book'), 'field':_('Tags'), 'pattern':'+', 'prefix':'\u2713'}, {'ordinal':1, 'enabled':True, 'name':_('Wishlist item'), 'field':_('Tags'), 'pattern':'Wishlist', 'prefix':'\u00d7'},], ['table_widget','table_widget'])) self.OPTION_FIELDS = option_fields def block_all_signals(self, bool): if self.DEBUG: print("block_all_signals: %s" % bool) self.blocking_all_signals = bool for opt in self.OPTION_FIELDS: c_name, c_def, c_type = opt if c_name in ['exclusion_rules_tw', 'prefix_rules_tw']: continue getattr(self, c_name).blockSignals(bool) def construct_tw_opts_object(self, c_name, opt_value, opts_dict): ''' Build an opts object from the UI settings to pass to the catalog builder Handles two types of rules sets, with and without ['prefix'] field Store processed opts object to opt_dict ''' rule_set = [] for stored_rule in opt_value: rule = stored_rule.copy() # Skip disabled and incomplete rules if not rule['enabled']: continue if not rule['field'] or not rule['pattern']: continue if 'prefix' in rule and rule['prefix'] is None: continue if rule['field'] != _('Tags'): # Look up custom column friendly name rule['field'] = self.eligible_custom_fields[rule['field']]['field'] if rule['pattern'] in [_('any value'),_('any date')]: rule['pattern'] = '.*' elif rule['pattern'] == _('unspecified'): rule['pattern'] = 'None' if 'prefix' in rule: pr = (rule['name'],rule['field'],rule['pattern'],rule['prefix']) else: pr = (rule['name'],rule['field'],rule['pattern']) rule_set.append(pr) opt_value = tuple(rule_set) # Strip off the trailing '_tw' opts_dict[c_name[:-3]] = opt_value def exclude_genre_changed(self): """ Dynamically compute excluded genres. Run exclude_genre regex against selected genre_source_field to show excluded tags. Inputs: current regex genre_source_field Output: self.exclude_genre_results (QLabel): updated to show tags to be excluded as genres """ def _truncated_results(excluded_tags, limit=180): ''' Limit number of genres displayed to avoid dialog explosion ''' start = [] end = [] lower = 0 upper = len(excluded_tags) -1 excluded_tags.sort() while True: if lower > upper: break elif lower == upper: start.append(excluded_tags[lower]) break start.append(excluded_tags[lower]) end.insert(0,excluded_tags[upper]) if len(', '.join(start)) + len(', '.join(end)) > limit: break lower += 1 upper -= 1 if excluded_tags == start + end: return ', '.join(excluded_tags) else: return "{} ... {}".format(', '.join(start), ', '.join(end)) results = _('No genres will be excluded') regex = str(getattr(self, 'exclude_genre').text()).strip() if not regex: self.exclude_genre_results.clear() self.exclude_genre_results.setText(results) return # Populate all_genre_tags from currently source if self.genre_source_field_name == _('Tags'): all_genre_tags = self.db.all_tags() else: all_genre_tags = list(self.db.all_custom(self.db.field_metadata.key_to_label(self.genre_source_field_name))) try: pattern = re.compile(regex) except: results = _("regex error: %s") % sys.exc_info()[1] else: excluded_tags = [] for tag in all_genre_tags: hit = pattern.search(tag) if hit: excluded_tags.append(hit.string) if excluded_tags: if set(excluded_tags) == set(all_genre_tags): results = _("All genres will be excluded") else: results = _truncated_results(excluded_tags) finally: if False and self.DEBUG: print("exclude_genre_changed(): %s" % results) self.exclude_genre_results.clear() self.exclude_genre_results.setText(results) def exclude_genre_reset(self): for default in self.OPTION_FIELDS: if default[0] == 'exclude_genre': self.exclude_genre.setText(default[1]) break def fetch_eligible_custom_fields(self): self.all_custom_fields = self.db.custom_field_keys() custom_fields = {} custom_fields[_('Tags')] = {'field':'tag', 'datatype':'text'} for custom_field in self.all_custom_fields: field_md = self.db.metadata_for_field(custom_field) if field_md['datatype'] in ['bool','composite','datetime','enumeration','text']: custom_fields[field_md['name']] = {'field':custom_field, 'datatype':field_md['datatype']} self.eligible_custom_fields = custom_fields def generate_descriptions_changed(self, enabled): ''' Toggle Description-related controls ''' self.header_note_source_field.setEnabled(enabled) self.include_hr.setEnabled(enabled) self.merge_after.setEnabled(enabled) self.merge_before.setEnabled(enabled) self.merge_source_field.setEnabled(enabled) self.thumb_width.setEnabled(enabled) def generate_genres_changed(self, enabled): ''' Toggle Genres-related controls ''' self.genre_source_field.setEnabled(enabled) def genre_source_field_changed(self,new_index): ''' Process changes in the genre_source_field combo box Update Excluded genres preview ''' new_source = self.genre_source_field.currentText() self.genre_source_field_name = new_source if new_source != _('Tags'): genre_source_spec = self.genre_source_fields[str(new_source)] self.genre_source_field_name = genre_source_spec['field'] self.exclude_genre_changed() def get_format_and_title(self): current_format = None current_title = None parent = self.parent_ref() if parent is not None: current_title = parent.title.text().strip() current_format = parent.format.currentText().strip() return current_format, current_title def header_note_source_field_changed(self,new_index): ''' Process changes in the header_note_source_field combo box ''' new_source = self.header_note_source_field.currentText() self.header_note_source_field_name = new_source if new_source: header_note_source_spec = self.header_note_source_fields[str(new_source)] self.header_note_source_field_name = header_note_source_spec['field'] def initialize(self, name, db): ''' CheckBoxControls (c_type: check_box): ['cross_reference_authors', 'generate_titles','generate_series','generate_genres', 'generate_recently_added','generate_descriptions', 'include_hr'] ComboBoxControls (c_type: combo_box): ['exclude_source_field','genre_source_field', 'header_note_source_field','merge_source_field'] LineEditControls (c_type: line_edit): ['exclude_genre'] RadioButtonControls (c_type: radio_button): ['merge_before','merge_after','generate_new_cover', 'use_existing_cover'] SpinBoxControls (c_type: spin_box): ['thumb_width'] TableWidgetControls (c_type: table_widget): ['exclusion_rules_tw','prefix_rules_tw'] TextEditControls (c_type: text_edit): ['exclude_genre_results'] ''' self.name = name self.db = db self.all_genre_tags = [] self.fetch_eligible_custom_fields() self.populate_combo_boxes() # Update dialog fields from stored options, validating options for combo boxes # Hook all change events to self.settings_changed self.blocking_all_signals = True exclusion_rules = [] prefix_rules = [] for opt in self.OPTION_FIELDS: c_name, c_def, c_type = opt opt_value = gprefs.get(self.name + '_' + c_name, c_def) if c_type in ['check_box']: getattr(self, c_name).setChecked(eval(str(opt_value))) getattr(self, c_name).clicked.connect(partial(self.settings_changed, c_name)) elif c_type in ['combo_box']: if opt_value is None: index = 0 if c_name == 'genre_source_field': index = self.genre_source_field.findText(_('Tags')) else: index = getattr(self,c_name).findText(opt_value) if index == -1: if c_name == 'read_source_field': index = self.read_source_field.findText(_('Tags')) elif c_name == 'genre_source_field': index = self.genre_source_field.findText(_('Tags')) getattr(self,c_name).setCurrentIndex(index) if c_name != 'preset_field': getattr(self, c_name).currentIndexChanged.connect(partial(self.settings_changed, c_name)) elif c_type in ['line_edit']: getattr(self, c_name).setText(opt_value if opt_value else '') getattr(self, c_name).editingFinished.connect(partial(self.settings_changed, c_name)) elif c_type in ['radio_button'] and opt_value is not None: getattr(self, c_name).setChecked(opt_value) getattr(self, c_name).clicked.connect(partial(self.settings_changed, c_name)) elif c_type in ['spin_box']: getattr(self, c_name).setValue(float(opt_value)) getattr(self, c_name).valueChanged.connect(partial(self.settings_changed, c_name)) if c_type == 'table_widget': if c_name == 'exclusion_rules_tw': if opt_value not in exclusion_rules: exclusion_rules.append(opt_value) if c_name == 'prefix_rules_tw': if opt_value not in prefix_rules: prefix_rules.append(opt_value) # Add icon to the reset button, hook textChanged signal self.reset_exclude_genres_tb.setIcon(QIcon.ic('trash.png')) self.reset_exclude_genres_tb.clicked.connect(self.exclude_genre_reset) # Hook textChanged event for exclude_genre QLineEdit self.exclude_genre.textChanged.connect(self.exclude_genre_changed) # Hook Descriptions checkbox for related options, init self.generate_descriptions.clicked.connect(self.generate_descriptions_changed) self.generate_descriptions_changed(self.generate_descriptions.isChecked()) # Init self.merge_source_field_name self.merge_source_field_name = '' cs = str(self.merge_source_field.currentText()) if cs: merge_source_spec = self.merge_source_fields[cs] self.merge_source_field_name = merge_source_spec['field'] # Init self.header_note_source_field_name self.header_note_source_field_name = '' cs = str(self.header_note_source_field.currentText()) if cs: header_note_source_spec = self.header_note_source_fields[cs] self.header_note_source_field_name = header_note_source_spec['field'] # Init self.genre_source_field_name self.genre_source_field_name = _('Tags') cs = str(self.genre_source_field.currentText()) if cs != _('Tags'): genre_source_spec = self.genre_source_fields[cs] self.genre_source_field_name = genre_source_spec['field'] # Hook Genres checkbox self.generate_genres.clicked.connect(self.generate_genres_changed) self.generate_genres_changed(self.generate_genres.isChecked()) # Initialize exclusion rules self.exclusion_rules_table = ExclusionRules(self, self.exclusion_rules_gb, "exclusion_rules_tw", exclusion_rules) # Initialize prefix rules self.prefix_rules_table = PrefixRules(self, self.prefix_rules_gb, "prefix_rules_tw", prefix_rules) # Initialize excluded genres preview self.exclude_genre_changed() # Hook Preset signals self.preset_delete_pb.clicked.connect(self.preset_remove) self.preset_save_pb.clicked.connect(self.preset_save) self.preset_field.currentIndexChanged.connect(self.preset_change) self.blocking_all_signals = False def merge_source_field_changed(self,new_index): ''' Process changes in the merge_source_field combo box ''' new_source = self.merge_source_field.currentText() self.merge_source_field_name = new_source if new_source: merge_source_spec = self.merge_source_fields[str(new_source)] self.merge_source_field_name = merge_source_spec['field'] if not self.merge_before.isChecked() and not self.merge_after.isChecked(): self.merge_after.setChecked(True) self.merge_before.setEnabled(True) self.merge_after.setEnabled(True) self.include_hr.setEnabled(True) else: self.merge_before.setEnabled(False) self.merge_after.setEnabled(False) self.include_hr.setEnabled(False) def options(self): ''' Return, optionally save current options exclude_genre stores literally Section switches store as True/False others store as lists ''' opts_dict = {} prefix_rules_processed = False exclusion_rules_processed = False for opt in self.OPTION_FIELDS: c_name, c_def, c_type = opt if c_name == 'exclusion_rules_tw' and exclusion_rules_processed: continue if c_name == 'prefix_rules_tw' and prefix_rules_processed: continue if c_type in ['check_box', 'radio_button']: opt_value = getattr(self, c_name).isChecked() elif c_type in ['combo_box']: opt_value = str(getattr(self,c_name).currentText()).strip() elif c_type in ['line_edit']: opt_value = str(getattr(self, c_name).text()).strip() elif c_type in ['spin_box']: opt_value = str(getattr(self, c_name).value()) elif c_type in ['table_widget']: if c_name == 'prefix_rules_tw': opt_value = self.prefix_rules_table.get_data() prefix_rules_processed = True if c_name == 'exclusion_rules_tw': opt_value = self.exclusion_rules_table.get_data() exclusion_rules_processed = True # Store UI values to gui.json in config dir gprefs.set(self.name + '_' + c_name, opt_value) # Construct opts object for catalog builder if c_name in ['exclusion_rules_tw','prefix_rules_tw']: self.construct_tw_opts_object(c_name, opt_value, opts_dict) else: opts_dict[c_name] = opt_value # Generate specs for merge_comments, header_note_source_field, genre_source_field checked = '' if self.merge_before.isChecked(): checked = 'before' elif self.merge_after.isChecked(): checked = 'after' include_hr = self.include_hr.isChecked() # Init self.merge_source_field_name self.merge_source_field_name = '' cs = str(self.merge_source_field.currentText()) if cs and cs in self.merge_source_fields: merge_source_spec = self.merge_source_fields[cs] self.merge_source_field_name = merge_source_spec['field'] # Init self.header_note_source_field_name self.header_note_source_field_name = '' cs = str(self.header_note_source_field.currentText()) if cs and cs in self.header_note_source_fields: header_note_source_spec = self.header_note_source_fields[cs] self.header_note_source_field_name = header_note_source_spec['field'] # Init self.genre_source_field_name self.genre_source_field_name = _('Tags') cs = str(self.genre_source_field.currentText()) if cs != _('Tags') and cs and cs in self.genre_source_fields: genre_source_spec = self.genre_source_fields[cs] self.genre_source_field_name = genre_source_spec['field'] opts_dict['merge_comments_rule'] = "%s:%s:%s" % \ (self.merge_source_field_name, checked, include_hr) opts_dict['header_note_source_field'] = self.header_note_source_field_name opts_dict['genre_source_field'] = self.genre_source_field_name # Fix up exclude_genre regex if blank. Assume blank = no exclusions if opts_dict['exclude_genre'] == '': opts_dict['exclude_genre'] = 'a^' # Append the output profile try: opts_dict['output_profile'] = [load_defaults('page_setup')['output_profile']] except: opts_dict['output_profile'] = ['default'] if False and self.DEBUG: print("opts_dict") for opt in sorted(opts_dict.keys(), key=sort_key): print(f" {opt}: {repr(opts_dict[opt])}") return opts_dict def populate_combo_boxes(self): # Custom column types declared in # gui2.preferences.create_custom_column:CreateCustomColumn() # As of 0.7.34: # bool Yes/No # comments Long text, like comments, not shown in tag browser # composite Column built from other columns # datetime Date # enumeration Text, but with a fixed set of permitted values # float Floating point numbers # int Integers # rating Ratings, shown with stars # series Text column for keeping series-like information # text Column shown in the tag browser # *text Comma-separated text, like tags, shown in tag browser # Populate the 'Excluded books' hybrid custom_fields = {} for custom_field in self.all_custom_fields: field_md = self.db.metadata_for_field(custom_field) if field_md['datatype'] in ['bool','composite','datetime','enumeration','text']: custom_fields[field_md['name']] = {'field':custom_field, 'datatype':field_md['datatype']} # Populate the 'Header note' combo box custom_fields = {} for custom_field in self.all_custom_fields: field_md = self.db.metadata_for_field(custom_field) if field_md['datatype'] in ['bool','composite','datetime','enumeration','text']: custom_fields[field_md['name']] = {'field':custom_field, 'datatype':field_md['datatype']} # Blank field first self.header_note_source_field.addItem('') # Add the sorted eligible fields to the combo box for cf in sorted(custom_fields, key=sort_key): self.header_note_source_field.addItem(cf) self.header_note_source_fields = custom_fields self.header_note_source_field.currentIndexChanged.connect(self.header_note_source_field_changed) # Populate the 'Merge with Comments' combo box custom_fields = {} for custom_field in self.all_custom_fields: field_md = self.db.metadata_for_field(custom_field) if field_md['datatype'] in ['text','comments','composite']: custom_fields[field_md['name']] = {'field':custom_field, 'datatype':field_md['datatype']} # Blank field first self.merge_source_field.addItem('') # Add the sorted eligible fields to the combo box for cf in sorted(custom_fields, key=sort_key): self.merge_source_field.addItem(cf) self.merge_source_fields = custom_fields self.merge_source_field.currentIndexChanged.connect(self.merge_source_field_changed) self.merge_before.setEnabled(False) self.merge_after.setEnabled(False) self.include_hr.setEnabled(False) # Populate the 'Genres' combo box custom_fields = {_('Tags'):{'field':None,'datatype':None}} for custom_field in self.all_custom_fields: field_md = self.db.metadata_for_field(custom_field) if field_md['datatype'] in ['text','enumeration']: custom_fields[field_md['name']] = {'field':custom_field, 'datatype':field_md['datatype']} # Add the sorted eligible fields to the combo box for cf in sorted(custom_fields, key=sort_key): self.genre_source_field.addItem(cf) self.genre_source_fields = custom_fields self.genre_source_field.currentIndexChanged.connect(self.genre_source_field_changed) # Populate the Presets combo box self.presets = JSONConfig("catalog_presets") self.preset_field.addItem("") self.preset_field_values = sorted(self.presets, key=sort_key) self.preset_field.addItems(self.preset_field_values) def preset_change(self, idx): ''' Update catalog options from current preset ''' if idx <= 0: return current_preset = self.preset_field.currentText() options = self.presets[current_preset] exclusion_rules = [] prefix_rules = [] self.block_all_signals(True) for opt in self.OPTION_FIELDS: c_name, c_def, c_type = opt if c_name == 'preset_field': continue # Ignore extra entries in options for cli invocation if c_name in options: opt_value = options[c_name] else: continue if c_type in ['check_box']: getattr(self, c_name).setChecked(eval(str(opt_value))) if c_name == 'generate_genres': self.genre_source_field.setEnabled(eval(str(opt_value))) elif c_type in ['combo_box']: if opt_value is None: index = 0 if c_name == 'genre_source_field': index = self.genre_source_field.findText(_('Tags')) else: index = getattr(self,c_name).findText(opt_value) if index == -1: if c_name == 'read_source_field': index = self.read_source_field.findText(_('Tags')) elif c_name == 'genre_source_field': index = self.genre_source_field.findText(_('Tags')) getattr(self,c_name).setCurrentIndex(index) elif c_type in ['line_edit']: getattr(self, c_name).setText(opt_value if opt_value else '') elif c_type in ['radio_button'] and opt_value is not None: getattr(self, c_name).setChecked(opt_value) elif c_type in ['spin_box']: getattr(self, c_name).setValue(float(opt_value)) if c_type == 'table_widget': if c_name == 'exclusion_rules_tw': if opt_value not in exclusion_rules: exclusion_rules.append(opt_value) if c_name == 'prefix_rules_tw': if opt_value not in prefix_rules: prefix_rules.append(opt_value) # Reset exclusion rules self.exclusion_rules_table.clearLayout() self.exclusion_rules_table = ExclusionRules(self, self.exclusion_rules_gb, "exclusion_rules_tw", exclusion_rules) # Reset prefix rules self.prefix_rules_table.clearLayout() self.prefix_rules_table = PrefixRules(self, self.prefix_rules_gb, "prefix_rules_tw", prefix_rules) # Reset excluded genres preview self.exclude_genre_changed() # Reset format and title format = options['format'] title = options['catalog_title'] self.set_format_and_title(format, title) # Reset Descriptions-related enable/disable switches self.generate_descriptions_changed(self.generate_descriptions.isChecked()) self.block_all_signals(False) def preset_remove(self): if self.preset_field.currentIndex() == 0: return if not question_dialog(self, _("Delete saved catalog preset"), _("The selected saved catalog preset will be deleted. " "Are you sure?")): return item_id = self.preset_field.currentIndex() item_name = str(self.preset_field.currentText()) self.preset_field.blockSignals(True) self.preset_field.removeItem(item_id) self.preset_field.blockSignals(False) self.preset_field.setCurrentIndex(0) if item_name in self.presets.keys(): del(self.presets[item_name]) self.presets.commit() def preset_save(self): names = [''] names.extend(self.preset_field_values) try: dex = names.index(self.preset_search_name) except: dex = 0 name = '' while not name: name, ok = QInputDialog.getItem(self, _('Save catalog preset'), _('Preset name:'), names, dex, True) if not ok: return if not name: error_dialog(self, _("Save catalog preset"), _("You must provide a name."), show=True) new = True name = str(name) if name in self.presets.keys(): if not question_dialog(self, _("Save catalog preset"), _("That saved preset already exists and will be overwritten. " "Are you sure?")): return new = False preset = {} prefix_rules_processed = False exclusion_rules_processed = False for opt in self.OPTION_FIELDS: c_name, c_def, c_type = opt if c_name == 'exclusion_rules_tw' and exclusion_rules_processed: continue if c_name == 'prefix_rules_tw' and prefix_rules_processed: continue if c_type in ['check_box', 'radio_button']: opt_value = getattr(self, c_name).isChecked() elif c_type in ['combo_box']: if c_name == 'preset_field': continue opt_value = str(getattr(self,c_name).currentText()).strip() elif c_type in ['line_edit']: opt_value = str(getattr(self, c_name).text()).strip() elif c_type in ['spin_box']: opt_value = str(getattr(self, c_name).value()) elif c_type in ['table_widget']: if c_name == 'prefix_rules_tw': opt_value = self.prefix_rules_table.get_data() prefix_rules_processed = True if c_name == 'exclusion_rules_tw': opt_value = self.exclusion_rules_table.get_data() exclusion_rules_processed = True preset[c_name] = opt_value # Construct cli version of table rules if c_name in ['exclusion_rules_tw','prefix_rules_tw']: self.construct_tw_opts_object(c_name, opt_value, preset) format, title = self.get_format_and_title() preset['format'] = format preset['catalog_title'] = title # Additional items needed for cli invocation # Generate specs for merge_comments, header_note_source_field, genre_source_field checked = '' if self.merge_before.isChecked(): checked = 'before' elif self.merge_after.isChecked(): checked = 'after' include_hr = self.include_hr.isChecked() preset['merge_comments_rule'] = "%s:%s:%s" % \ (self.merge_source_field_name, checked, include_hr) preset['header_note_source_field'] = str(self.header_note_source_field.currentText()) preset['genre_source_field'] = str(self.genre_source_field.currentText()) # Append the current output profile try: preset['output_profile'] = load_defaults('page_setup')['output_profile'] except: preset['output_profile'] = 'default' self.presets[name] = preset self.presets.commit() if new: self.preset_field.blockSignals(True) self.preset_field.clear() self.preset_field.addItem('') self.preset_field_values = sorted(self.presets, key=sort_key) self.preset_field.addItems(self.preset_field_values) self.preset_field.blockSignals(False) self.preset_field.setCurrentIndex(self.preset_field.findText(name)) def set_format_and_title(self, format, title): parent = self.parent_ref() if parent is not None: if format: index = parent.format.findText(format) parent.format.blockSignals(True) parent.format.setCurrentIndex(index) parent.format.blockSignals(False) if title: parent.title.setText(title) def settings_changed(self, source): ''' When anything changes, clear Preset combobox ''' if self.DEBUG: print("settings_changed: %s" % source) self.preset_field.setCurrentIndex(0) def show_help(self): ''' Display help file ''' open_url(QUrl(localize_user_manual_link('https://manual.calibre-ebook.com/catalogs.html'))) class CheckableTableWidgetItem(QTableWidgetItem): ''' Borrowed from kiwidude ''' def __init__(self, checked=False, is_tristate=False): QTableWidgetItem.__init__(self, '') self.setFlags(Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsUserCheckable | Qt.ItemFlag.ItemIsEnabled) if is_tristate: self.setFlags(self.flags() | Qt.ItemFlag.ItemIsTristate) if checked: self.setCheckState(Qt.CheckState.Checked) else: if is_tristate and checked is None: self.setCheckState(Qt.CheckState.PartiallyChecked) else: self.setCheckState(Qt.CheckState.Unchecked) def get_boolean_value(self): ''' Return a boolean value indicating whether checkbox is checked If this is a tristate checkbox, a partially checked value is returned as None ''' if self.checkState() == Qt.CheckState.PartiallyChecked: return None else: return self.checkState() == Qt.CheckState.Checked class NoWheelComboBox(QComboBox): def wheelEvent(self, event): # Disable the mouse wheel on top of the combo box changing selection as plays havoc in a grid event.ignore() class ComboBox(NoWheelComboBox): # Caller is responsible for providing the list in the preferred order def __init__(self, parent, items, selected_text,insert_blank=True): NoWheelComboBox.__init__(self, parent) self.populate_combo(items, selected_text, insert_blank) def populate_combo(self, items, selected_text, insert_blank): if insert_blank: self.addItems(['']) self.addItems(items) if selected_text: idx = self.findText(selected_text) self.setCurrentIndex(idx) else: self.setCurrentIndex(0) class GenericRulesTable(QTableWidget): ''' Generic methods for managing rows in a QTableWidget ''' DEBUG = False MAXIMUM_TABLE_HEIGHT = 113 NAME_FIELD_WIDTH = 225 def __init__(self, parent, parent_gb, object_name, rules): self.parent = parent self.rules = rules self.eligible_custom_fields = parent.eligible_custom_fields self.db = parent.db QTableWidget.__init__(self) self.setObjectName(object_name) self.layout = parent_gb.layout() # Add ourselves to the layout sizePolicy = QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) # sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth()) self.setSizePolicy(sizePolicy) self.setMaximumSize(QSize(16777215, self.MAXIMUM_TABLE_HEIGHT)) self.setColumnCount(0) self.setRowCount(0) self.layout.addWidget(self) self.last_row_selected = self.currentRow() self.last_rows_selected = self.selectionModel().selectedRows() # Add the controls self._init_controls() # Hook check_box changes self.cellChanged.connect(self.enabled_state_changed) def _init_controls(self): # Add the control set vbl = QVBoxLayout() self.move_rule_up_tb = QToolButton() self.move_rule_up_tb.setObjectName("move_rule_up_tb") self.move_rule_up_tb.setToolTip('Move rule up') self.move_rule_up_tb.setIcon(QIcon.ic('arrow-up.png')) self.move_rule_up_tb.clicked.connect(self.move_row_up) vbl.addWidget(self.move_rule_up_tb) self.add_rule_tb = QToolButton() self.add_rule_tb.setObjectName("add_rule_tb") self.add_rule_tb.setToolTip('Add a new rule') self.add_rule_tb.setIcon(QIcon.ic('plus.png')) self.add_rule_tb.clicked.connect(self.add_row) vbl.addWidget(self.add_rule_tb) self.delete_rule_tb = QToolButton() self.delete_rule_tb.setObjectName("delete_rule_tb") self.delete_rule_tb.setToolTip('Delete selected rule') self.delete_rule_tb.setIcon(QIcon.ic('list_remove.png')) self.delete_rule_tb.clicked.connect(self.delete_row) vbl.addWidget(self.delete_rule_tb) self.move_rule_down_tb = QToolButton() self.move_rule_down_tb.setObjectName("move_rule_down_tb") self.move_rule_down_tb.setToolTip('Move rule down') self.move_rule_down_tb.setIcon(QIcon.ic('arrow-down.png')) self.move_rule_down_tb.clicked.connect(self.move_row_down) vbl.addWidget(self.move_rule_down_tb) self.layout.addLayout(vbl) def add_row(self): self.setFocus() row = self.last_row_selected + 1 if self.DEBUG: print("%s:add_row(): at row: %d" % (self.objectName(), row)) self.insertRow(row) self.populate_table_row(row, self.create_blank_row_data()) self.select_and_scroll_to_row(row) self.resizeColumnsToContents() # In case table was empty self.horizontalHeader().setStretchLastSection(True) def clearLayout(self): if self.layout is not None: old_layout = self.layout for child in old_layout.children(): for i in reversed(range(child.count())): if child.itemAt(i).widget() is not None: child.itemAt(i).widget().setParent(None) sip.delete(child) for i in reversed(range(old_layout.count())): if old_layout.itemAt(i).widget() is not None: old_layout.itemAt(i).widget().setParent(None) def delete_row(self): if self.DEBUG: print("%s:delete_row()" % self.objectName()) self.setFocus() rows = self.last_rows_selected if len(rows) == 0: return first = rows[0].row() + 1 last = rows[-1].row() + 1 first_rule_name = str(self.cellWidget(first-1,self.COLUMNS['NAME']['ordinal']).text()).strip() message = _("Are you sure you want to delete '%s'?") % (first_rule_name) if len(rows) > 1: message = _('Are you sure you want to delete rules #%(first)d-%(last)d?') % dict(first=first, last=last) if not question_dialog(self, _('Delete Rule'), message, show_copy_button=False): return first_sel_row = self.currentRow() for selrow in reversed(rows): self.removeRow(selrow.row()) if first_sel_row < self.rowCount(): self.select_and_scroll_to_row(first_sel_row) elif self.rowCount() > 0: self.select_and_scroll_to_row(first_sel_row - 1) def enabled_state_changed(self, row, col): if col in [self.COLUMNS['ENABLED']['ordinal']]: self.select_and_scroll_to_row(row) self.settings_changed("enabled_state_changed") if self.DEBUG: print("%s:enabled_state_changed(): row %d col %d" % (self.objectName(), row, col)) def focusInEvent(self,e): if self.DEBUG: print("%s:focusInEvent()" % self.objectName()) def focusOutEvent(self,e): # Override of QTableWidget method - clear selection when table loses focus self.last_row_selected = self.currentRow() self.last_rows_selected = self.selectionModel().selectedRows() self.clearSelection() if self.DEBUG: print("%s:focusOutEvent(): self.last_row_selected: %d" % (self.objectName(),self.last_row_selected)) def move_row_down(self): self.setFocus() rows = self.last_rows_selected if len(rows) == 0: return last_sel_row = rows[-1].row() if last_sel_row == self.rowCount() - 1: return self.blockSignals(True) for selrow in reversed(rows): dest_row = selrow.row() + 1 src_row = selrow.row() if self.DEBUG: print("%s:move_row_down() %d -> %d" % (self.objectName(),src_row, dest_row)) # Save the contents of the destination row saved_data = self.convert_row_to_data(dest_row) # Remove the destination row self.removeRow(dest_row) # Insert a new row at the original location self.insertRow(src_row) # Populate it with the saved data self.populate_table_row(src_row, saved_data) scroll_to_row = last_sel_row + 1 self.select_and_scroll_to_row(scroll_to_row) self.blockSignals(False) def move_row_up(self): self.setFocus() rows = self.last_rows_selected if len(rows) == 0: return first_sel_row = rows[0].row() if first_sel_row <= 0: return self.blockSignals(True) for selrow in rows: if self.DEBUG: print("%s:move_row_up() %d -> %d" % (self.objectName(),selrow.row(), selrow.row()-1)) # Save the row above saved_data = self.convert_row_to_data(selrow.row() - 1) # Add a row below us with the source data self.insertRow(selrow.row() + 1) self.populate_table_row(selrow.row() + 1, saved_data) # Delete the row above self.removeRow(selrow.row() - 1) scroll_to_row = first_sel_row if scroll_to_row > 0: scroll_to_row = scroll_to_row - 1 self.select_and_scroll_to_row(scroll_to_row) self.blockSignals(False) def populate_table(self): # Format of rules list is different if default values vs retrieved JSON # Hack to normalize list style rules = self.rules if rules and isinstance(rules[0], list): rules = rules[0] self.setFocus() rules = sorted(rules, key=lambda k: k['ordinal']) for row, rule in enumerate(rules): self.insertRow(row) self.select_and_scroll_to_row(row) self.populate_table_row(row, rule) self.selectRow(0) def resize_name(self): self.setColumnWidth(1, self.NAME_FIELD_WIDTH) def rule_name_edited(self): if self.DEBUG: print("%s:rule_name_edited()" % self.objectName()) current_row = self.currentRow() self.cellWidget(current_row,1).home(False) self.select_and_scroll_to_row(current_row) self.settings_changed("rule_name_edited") def select_and_scroll_to_row(self, row): self.setFocus() self.selectRow(row) self.scrollToItem(self.currentItem()) self.last_row_selected = self.currentRow() self.last_rows_selected = self.selectionModel().selectedRows() def settings_changed(self, source): if not self.parent.blocking_all_signals: self.parent.settings_changed(source) def _source_index_changed(self, combo): # Figure out which row we're in for row in range(self.rowCount()): if self.cellWidget(row, self.COLUMNS['FIELD']['ordinal']) is combo: break if self.DEBUG: print("%s:_source_index_changed(): calling source_index_changed with row: %d " % (self.objectName(), row)) self.source_index_changed(combo, row) def source_index_changed(self, combo, row, pattern=''): # Populate the Pattern field based upon the Source field source_field = combo.currentText() if source_field == '': values = [] elif source_field == _('Tags'): values = sorted(self.db.all_tags(), key=sort_key) else: if self.eligible_custom_fields[str(source_field)]['datatype'] in ['enumeration', 'text']: values = self.db.all_custom(self.db.field_metadata.key_to_label( self.eligible_custom_fields[str(source_field)]['field'])) values = sorted(values, key=sort_key) elif self.eligible_custom_fields[str(source_field)]['datatype'] in ['bool']: values = [_('True'),_('False'),_('unspecified')] elif self.eligible_custom_fields[str(source_field)]['datatype'] in ['composite']: values = [_('any value'),_('unspecified')] elif self.eligible_custom_fields[str(source_field)]['datatype'] in ['datetime']: values = [_('any date'),_('unspecified')] values_combo = ComboBox(self, values, pattern) values_combo.currentIndexChanged.connect(partial(self.values_index_changed, values_combo)) self.setCellWidget(row, self.COLUMNS['PATTERN']['ordinal'], values_combo) self.select_and_scroll_to_row(row) self.settings_changed("source_index_changed") def values_index_changed(self, combo): # After edit, select row for row in range(self.rowCount()): if self.cellWidget(row, self.COLUMNS['PATTERN']['ordinal']) is combo: self.select_and_scroll_to_row(row) self.settings_changed("values_index_changed") break if self.DEBUG: print("%s:values_index_changed(): row %d " % (self.objectName(), row)) class ExclusionRules(GenericRulesTable): COLUMNS = {'ENABLED':{'ordinal': 0, 'name': ''}, 'NAME': {'ordinal': 1, 'name': _('Name')}, 'FIELD': {'ordinal': 2, 'name': _('Field')}, 'PATTERN': {'ordinal': 3, 'name': _('Value')},} def __init__(self, parent, parent_gb_hl, object_name, rules): super().__init__(parent, parent_gb_hl, object_name, rules) self.setObjectName("exclusion_rules_table") self._init_table_widget() self._initialize() def _init_table_widget(self): header_labels = [self.COLUMNS[index]['name'] for index in sorted(self.COLUMNS.keys(), key=lambda c: self.COLUMNS[c]['ordinal'])] self.setColumnCount(len(header_labels)) self.setHorizontalHeaderLabels(header_labels) self.setSortingEnabled(False) self.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows) def _initialize(self): self.populate_table() self.resizeColumnsToContents() self.resize_name() self.horizontalHeader().setStretchLastSection(True) self.clearSelection() def convert_row_to_data(self, row): data = self.create_blank_row_data() data['ordinal'] = row data['enabled'] = self.item(row,self.COLUMNS['ENABLED']['ordinal']).checkState() == Qt.CheckState.Checked data['name'] = str(self.cellWidget(row,self.COLUMNS['NAME']['ordinal']).text()).strip() data['field'] = str(self.cellWidget(row,self.COLUMNS['FIELD']['ordinal']).currentText()).strip() data['pattern'] = str(self.cellWidget(row,self.COLUMNS['PATTERN']['ordinal']).currentText()).strip() return data def create_blank_row_data(self): data = {} data['ordinal'] = -1 data['enabled'] = True data['name'] = 'New rule' data['field'] = '' data['pattern'] = '' return data def get_data(self): data_items = [] for row in range(self.rowCount()): data = self.convert_row_to_data(row) data_items.append( {'ordinal':data['ordinal'], 'enabled':data['enabled'], 'name':data['name'], 'field':data['field'], 'pattern':data['pattern']}) return data_items def populate_table_row(self, row, data): def set_rule_name_in_row(row, col, name=''): rule_name = QLineEdit(name) rule_name.home(False) rule_name.editingFinished.connect(self.rule_name_edited) self.setCellWidget(row, col, rule_name) def set_source_field_in_row(row, col, field=''): source_combo = ComboBox(self, sorted(self.eligible_custom_fields.keys(), key=sort_key), field) source_combo.currentIndexChanged.connect(partial(self._source_index_changed, source_combo)) self.setCellWidget(row, col, source_combo) return source_combo # Entry point self.blockSignals(True) # Enabled check_box = CheckableTableWidgetItem(data['enabled']) self.setItem(row, self.COLUMNS['ENABLED']['ordinal'], check_box) # Rule name set_rule_name_in_row(row, self.COLUMNS['NAME']['ordinal'], name=data['name']) # Source field source_combo = set_source_field_in_row(row, self.COLUMNS['FIELD']['ordinal'], field=data['field']) # Pattern # The contents of the Pattern field is driven by the Source field self.source_index_changed(source_combo, row, pattern=data['pattern']) self.blockSignals(False) class PrefixRules(GenericRulesTable): COLUMNS = {'ENABLED':{'ordinal': 0, 'name': ''}, 'NAME': {'ordinal': 1, 'name': _('Name')}, 'PREFIX': {'ordinal': 2, 'name': _('Prefix')}, 'FIELD': {'ordinal': 3, 'name': _('Field')}, 'PATTERN':{'ordinal': 4, 'name': _('Value')},} def __init__(self, parent, parent_gb_hl, object_name, rules): super().__init__(parent, parent_gb_hl, object_name, rules) self.setObjectName("prefix_rules_table") self._init_table_widget() self._initialize() def _init_table_widget(self): header_labels = [self.COLUMNS[index]['name'] for index in sorted(self.COLUMNS.keys(), key=lambda c: self.COLUMNS[c]['ordinal'])] self.setColumnCount(len(header_labels)) self.setHorizontalHeaderLabels(header_labels) self.setSortingEnabled(False) self.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows) def _initialize(self): self.generate_prefix_list() self.populate_table() self.resizeColumnsToContents() self.resize_name() self.horizontalHeader().setStretchLastSection(True) self.clearSelection() def convert_row_to_data(self, row): data = self.create_blank_row_data() data['ordinal'] = row data['enabled'] = self.item(row,self.COLUMNS['ENABLED']['ordinal']).checkState() == Qt.CheckState.Checked data['name'] = str(self.cellWidget(row,self.COLUMNS['NAME']['ordinal']).text()).strip() data['prefix'] = str(self.cellWidget(row,self.COLUMNS['PREFIX']['ordinal']).currentText()).strip() data['field'] = str(self.cellWidget(row,self.COLUMNS['FIELD']['ordinal']).currentText()).strip() data['pattern'] = str(self.cellWidget(row,self.COLUMNS['PATTERN']['ordinal']).currentText()).strip() return data def create_blank_row_data(self): data = {} data['ordinal'] = -1 data['enabled'] = True data['name'] = 'New rule' data['field'] = '' data['pattern'] = '' data['prefix'] = '' return data def generate_prefix_list(self): def prefix_sorter(item): key = item if item[0] == "_": key = 'zzz' + item return key # Create a list of prefixes for user selection raw_prefix_list = [ ('Ampersand', '&'), ('Angle left double', '\u00ab'), ('Angle left', '\u2039'), ('Angle right double', '\u00bb'), ('Angle right', '\u203a'), ('Arrow carriage return', '\u21b5'), ('Arrow double', '\u2194'), ('Arrow down', '\u2193'), ('Arrow left', '\u2190'), ('Arrow right', '\u2192'), ('Arrow up', '\u2191'), ('Asterisk', '*'), ('At sign', '@'), ('Bullet smallest', '\u22c5'), ('Bullet small', '\u00b7'), ('Bullet', '\u2022'), ('Cards clubs', '\u2663'), ('Cards diamonds', '\u2666'), ('Cards hearts', '\u2665'), ('Cards spades', '\u2660'), ('Caret', '^'), ('Checkmark', '\u2713'), ('Copyright circle c', '\u00a9'), ('Copyright circle r', '\u00ae'), ('Copyright trademark', '\u2122'), ('Currency cent', '\u00a2'), ('Currency dollar', '$'), ('Currency euro', '\u20ac'), ('Currency pound', '\u00a3'), ('Currency yen', '\u00a5'), ('Dagger double', '\u2021'), ('Dagger', '\u2020'), ('Degree', '\u00b0'), ('Dots3', '\u2234'), ('Hash', '#'), ('Infinity', '\u221e'), ('Lozenge', '\u25ca'), ('Math divide', '\u00f7'), ('Math empty', '\u2205'), ('Math equals', '='), ('Math minus', '\u2212'), ('Math plus circled', '\u2295'), ('Math times circled', '\u2297'), ('Math times', '\u00d7'), ('Paragraph', '\u00b6'), ('Percent', '%'), ('Plus-or-minus', '\u00b1'), ('Plus', '+'), ('Punctuation colon', ':'), ('Punctuation colon-semi', ';'), ('Punctuation exclamation', '!'), ('Punctuation question', '?'), ('Punctuation period', '.'), ('Punctuation slash back', '\\'), ('Punctuation slash forward', '/'), ('Section', '\u00a7'), ('Tilde', '~'), ('Vertical bar', '|'), ('Vertical bar broken', '\u00a6'), ('_0', '0'), ('_1', '1'), ('_2', '2'), ('_3', '3'), ('_4', '4'), ('_5', '5'), ('_6', '6'), ('_7', '7'), ('_8', '8'), ('_9', '9'), ('_A', 'A'), ('_B', 'B'), ('_C', 'C'), ('_D', 'D'), ('_E', 'E'), ('_F', 'F'), ('_G', 'G'), ('_H', 'H'), ('_I', 'I'), ('_J', 'J'), ('_K', 'K'), ('_L', 'L'), ('_M', 'M'), ('_N', 'N'), ('_O', 'O'), ('_P', 'P'), ('_Q', 'Q'), ('_R', 'R'), ('_S', 'S'), ('_T', 'T'), ('_U', 'U'), ('_V', 'V'), ('_W', 'W'), ('_X', 'X'), ('_Y', 'Y'), ('_Z', 'Z'), ('_a', 'a'), ('_b', 'b'), ('_c', 'c'), ('_d', 'd'), ('_e', 'e'), ('_f', 'f'), ('_g', 'g'), ('_h', 'h'), ('_i', 'i'), ('_j', 'j'), ('_k', 'k'), ('_l', 'l'), ('_m', 'm'), ('_n', 'n'), ('_o', 'o'), ('_p', 'p'), ('_q', 'q'), ('_r', 'r'), ('_s', 's'), ('_t', 't'), ('_u', 'u'), ('_v', 'v'), ('_w', 'w'), ('_x', 'x'), ('_y', 'y'), ('_z', 'z'), ] raw_prefix_list = sorted(raw_prefix_list, key=prefix_sorter) self.prefix_list = [x[1] for x in raw_prefix_list] def get_data(self): data_items = [] for row in range(self.rowCount()): data = self.convert_row_to_data(row) data_items.append( {'ordinal':data['ordinal'], 'enabled':data['enabled'], 'name':data['name'], 'field':data['field'], 'pattern':data['pattern'], 'prefix':data['prefix']}) return data_items def populate_table_row(self, row, data): def set_prefix_field_in_row(row, col, field=''): prefix_combo = ComboBox(self, self.prefix_list, field) prefix_combo.currentIndexChanged.connect(partial(self.settings_changed, 'set_prefix_field_in_row')) self.setCellWidget(row, col, prefix_combo) def set_rule_name_in_row(row, col, name=''): rule_name = QLineEdit(name) rule_name.home(False) rule_name.editingFinished.connect(self.rule_name_edited) self.setCellWidget(row, col, rule_name) def set_source_field_in_row(row, col, field=''): source_combo = ComboBox(self, sorted(self.eligible_custom_fields.keys(), key=sort_key), field) source_combo.currentIndexChanged.connect(partial(self._source_index_changed, source_combo)) self.setCellWidget(row, col, source_combo) return source_combo # Entry point self.blockSignals(True) # Enabled self.setItem(row, self.COLUMNS['ENABLED']['ordinal'], CheckableTableWidgetItem(data['enabled'])) # Rule name set_rule_name_in_row(row, self.COLUMNS['NAME']['ordinal'], name=data['name']) # Prefix set_prefix_field_in_row(row, self.COLUMNS['PREFIX']['ordinal'], field=data['prefix']) # Source field source_combo = set_source_field_in_row(row, self.COLUMNS['FIELD']['ordinal'], field=data['field']) # Pattern # The contents of the Pattern field is driven by the Source field self.source_index_changed(source_combo, row, pattern=data['pattern']) self.blockSignals(False)
60,953
Python
.py
1,317
34.229309
120
0.564368
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,750
ui.py
kovidgoyal_calibre/src/calibre/gui2/tag_browser/ui.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import copy import textwrap from functools import partial from qt.core import ( QAction, QActionGroup, QComboBox, QDialog, QFrame, QHBoxLayout, QIcon, QLabel, QLineEdit, QMenu, QSizePolicy, Qt, QTimer, QToolButton, QVBoxLayout, QWidget, pyqtSignal, ) from calibre.ebooks.metadata import title_sort from calibre.gui2 import config, error_dialog, gprefs, question_dialog, warning_dialog from calibre.gui2.dialogs.edit_authors_dialog import EditAuthorsDialog from calibre.gui2.dialogs.tag_categories import TagCategories from calibre.gui2.dialogs.tag_list_editor import TagListEditor from calibre.gui2.tag_browser.view import TagsView from calibre.gui2.widgets import HistoryLineEdit from calibre.startup import connect_lambda from calibre.utils.icu import sort_key from calibre.utils.localization import ngettext from polyglot.builtins import iteritems class TagBrowserMixin: # {{{ def __init__(self, *args, **kwargs): pass def populate_tb_manage_menu(self, db): self.populate_manage_categories_menu(db, self.alter_tb.manage_menu, add_column_items=False) def populate_manage_categories_menu(self, db, menu, add_column_items=False): from calibre.db.categories import find_categories fm = db.new_api.field_metadata # Get the custom categories cust_cats = [x[0] for x in find_categories(fm) if fm.is_custom_field(x[0])] cust_cats = [c for c in cust_cats if fm[c]['datatype'] != 'composite'] m = menu m.clear() def cat_display_name(x): try: if x == 'series': return ngettext('Series', 'Series', 2) if x == 'user:': return _('User categories') return fm[x]['name'] except Exception: return '' def get_icon(cat_name): icon = self.tags_view.model().category_custom_icons.get(cat_name, None) if not icon: from calibre.library.field_metadata import category_icon_map icon = QIcon.ic(category_icon_map.get(cat_name) or category_icon_map['custom:']) return icon def menu_func(cat_name, item): if cat_name == 'authors': return partial(self.do_author_sort_edit, self, None if item is None else db.new_api.get_item_id('authors', item), select_sort=False) elif cat_name == 'user:': return partial(self.do_edit_user_categories, None) elif cat_name == 'search': return partial(self.do_saved_search_edit, None) else: return partial(self.do_tags_list_edit, item, cat_name) # Check if the current cell is a category. If so, show an action for it # and its items on the current book. current_cat = None idx = self.library_view.currentIndex() if add_column_items else None if idx is not None and idx.isValid(): col = idx.column() model = self.library_view.model() if col in range(0, len(model.column_map)): current_cat = model.column_map[col] if current_cat in ('authors', 'series', 'publisher', 'tags') or current_cat in cust_cats: cdn = cat_display_name(current_cat) or current_cat m.addAction(get_icon(current_cat), cdn.replace('&', '&&'), menu_func(current_cat, None)) proxy_md = db.new_api.get_proxy_metadata(db.id(idx.row())) items = proxy_md.get(current_cat) if isinstance(items, str): items = list((items,)) if items: items_title = _('{category} for current book').format(category=cdn) if len(items) > 4: im = QMenu(items_title, m) im.setIcon(get_icon(current_cat)) m.addMenu(im) else: m.addSection(items_title) im = m for item in sorted(items, key=sort_key): im.addAction(get_icon(current_cat), item, menu_func(current_cat, item)) m.addSection(_('Other categories')) # Standard columns for key in ('authors', 'series', 'publisher', 'tags', 'user:', 'search'): if cat_display_name(key) and key != current_cat: m.addAction(get_icon(key), cat_display_name(key), menu_func(key, None)) # Custom columns if cust_cats: if len(cust_cats) > 5: m = m.addMenu(_('Custom categories')) for cat in sorted(cust_cats, key=lambda v: sort_key(cat_display_name(v))): if cat == current_cat: continue m.addAction(get_icon(cat), cat_display_name(cat).replace('&', '&&'), menu_func(cat, None)) def init_tag_browser_mixin(self, db): self.library_view.model().count_changed_signal.connect(self.tags_view.recount_with_position_based_index) self.tags_view.set_database(db, self.alter_tb) self.tags_view.tags_marked.connect(self.search.set_search_string) self.tags_view.tags_list_edit.connect(self.do_tags_list_edit) self.tags_view.edit_user_category.connect(self.do_edit_user_categories) self.tags_view.delete_user_category.connect(self.do_delete_user_category) self.tags_view.del_item_from_user_cat.connect(self.do_del_item_from_user_cat) self.tags_view.add_subcategory.connect(self.do_add_subcategory) self.tags_view.add_item_to_user_cat.connect(self.do_add_item_to_user_cat) self.tags_view.saved_search_edit.connect(self.do_saved_search_edit) self.tags_view.rebuild_saved_searches.connect(self.do_rebuild_saved_searches) self.tags_view.author_sort_edit.connect(self.do_author_sort_edit) self.tags_view.tag_item_renamed.connect(self.do_field_item_value_changed) self.tags_view.search_item_renamed.connect(self.saved_searches_changed) self.tags_view.drag_drop_finished.connect(self.drag_drop_finished) self.tags_view.restriction_error.connect(self.do_restriction_error, type=Qt.ConnectionType.QueuedConnection) self.tags_view.tag_item_delete.connect(self.do_tag_item_delete) self.tags_view.tag_identifier_delete.connect(self.delete_identifier) self.tags_view.apply_tag_to_selected.connect(self.apply_tag_to_selected) self.populate_tb_manage_menu(db) self.tags_view.model().user_categories_edited.connect(self.user_categories_edited, type=Qt.ConnectionType.QueuedConnection) self.tags_view.model().user_category_added.connect(self.user_categories_edited, type=Qt.ConnectionType.QueuedConnection) self.tags_view.edit_enum_values.connect(self.edit_enum_values) self.tags_view.model().research_required.connect(self.do_gui_research, type=Qt.ConnectionType.QueuedConnection) def do_gui_research(self): self.library_view.model().research() # The count can change if the current search uses in_tag_browser, perhaps in a VL self.library_view.model().count_changed() def user_categories_edited(self): current_row_id = self.library_view.current_id self.library_view.model().refresh(reset=True) self.library_view.model().research(reset=False) self.library_view.current_id = current_row_id # the setter checks for None def do_restriction_error(self, e): error_dialog(self.tags_view, _('Invalid search restriction'), _('The current search restriction is invalid'), det_msg=str(e) if e else '', show=True) def do_add_subcategory(self, on_category_key, new_category_name=None): ''' Add a subcategory to the category 'on_category'. If new_category_name is None, then a default name is shown and the user is offered the opportunity to edit the name. ''' db = self.library_view.model().db m = self.tags_view.model() # Can't add an unnamed pref when empty categories are hidden. There is no # way for the user to see/edit it. if new_category_name is None and m.prefs['tag_browser_hide_empty_categories']: error_dialog(self.tags_view, _('Cannot add subcategory to category'), _("The option 'Preferences -> Look & feel -> Tag browser -> " "Hide empty categories' is enabled, preventing the creation " "of new empty user subcategories because they won't be " "displayed. Either change the option or use the 'Manage " "Categories' dialog to add the subcategories."), show=True) return user_cats = db.new_api.pref('user_categories', {}) # Ensure that the temporary name we will use is not already there i = 0 if new_category_name is not None: new_name = new_category_name.replace('.', '') else: new_name = _('New category').replace('.', '') n = new_name while True: new_cat = on_category_key[1:] + '.' + n if new_cat not in user_cats: break i += 1 n = new_name + str(i) # Add the new category user_cats[new_cat] = [] db.new_api.set_pref('user_categories', user_cats) self.tags_view.recount() db.new_api.clear_search_caches() idx = m.index_for_path(m.find_category_node('@' + new_cat)) self.tags_view.show_item_at_index(idx) # Open the editor on the new item to rename it if new_category_name is None: item = m.get_node(idx) item.use_vl = False item.ignore_vl = True self.tags_view.edit(idx) def do_edit_user_categories(self, on_category=None): ''' Open the User categories editor. ''' db = self.library_view.model().db d = TagCategories(self, db, on_category, book_ids=self.tags_view.model().get_book_ids_to_use()) if d.exec() == QDialog.DialogCode.Accepted: # Order is important. The categories must be removed before setting # the preference because setting the pref recomputes the dynamic categories db.field_metadata.remove_user_categories() db.new_api.set_pref('user_categories', d.categories) db.new_api.refresh_search_locations() self.tags_view.recount() db.new_api.clear_search_caches() self.user_categories_edited() def do_delete_user_category(self, category_name): ''' Delete the User category named category_name. Any leading '@' is removed ''' if category_name.startswith('@'): category_name = category_name[1:] db = self.library_view.model().db user_cats = db.new_api.pref('user_categories', {}) cat_keys = sorted(user_cats.keys(), key=sort_key) has_children = False found = False for k in cat_keys: if k == category_name: found = True has_children = len(user_cats[k]) elif k.startswith(category_name + '.'): has_children = True if not found: return error_dialog(self.tags_view, _('Delete User category'), _('%s is not a User category')%category_name, show=True) if has_children: if not question_dialog(self.tags_view, _('Delete User category'), _('%s contains items. Do you really ' 'want to delete it?')%category_name): return for k in cat_keys: if k == category_name: del user_cats[k] elif k.startswith(category_name + '.'): del user_cats[k] db.new_api.set_pref('user_categories', user_cats) self.tags_view.recount() db.new_api.clear_search_caches() self.user_categories_edited() def do_del_item_from_user_cat(self, user_cat, item_name, item_category): ''' Delete the item (item_name, item_category) from the User category with key user_cat. Any leading '@' characters are removed ''' if user_cat.startswith('@'): user_cat = user_cat[1:] db = self.library_view.model().db user_cats = db.new_api.pref('user_categories', {}) if user_cat not in user_cats: error_dialog(self.tags_view, _('Remove category'), _('User category %s does not exist')%user_cat, show=True) return self.tags_view.model().delete_item_from_user_category(user_cat, item_name, item_category) self.tags_view.recount() db.new_api.clear_search_caches() self.user_categories_edited() def do_add_item_to_user_cat(self, dest_category, src_name, src_category): ''' Add the item src_name in src_category to the User category dest_category. Any leading '@' is removed ''' db = self.library_view.model().db user_cats = db.new_api.pref('user_categories', {}) if dest_category and dest_category.startswith('@'): dest_category = dest_category[1:] if dest_category not in user_cats: return error_dialog(self.tags_view, _('Add to User category'), _('A User category %s does not exist')%dest_category, show=True) # Now add the item to the destination User category add_it = True if src_category == 'news': src_category = 'tags' for tup in user_cats[dest_category]: if src_name == tup[0] and src_category == tup[1]: add_it = False if add_it: user_cats[dest_category].append([src_name, src_category, 0]) db.new_api.set_pref('user_categories', user_cats) self.tags_view.recount() db.new_api.clear_search_caches() self.user_categories_edited() # Keep this for compatibility. It isn't used here but could be used in a plugin def get_book_ids(self, use_virtual_library, db, category): return self.get_book_ids_in_vl_or_selection( ('virtual_library' if use_virtual_library else None), db, category) def get_book_ids_in_vl_or_selection(self, use_what, db, category): if use_what is None: book_ids = None elif use_what == 'virtual_library': book_ids = self.tags_view.model().get_book_ids_to_use() else: book_ids = self.library_view.get_selected_ids() if not book_ids: warning_dialog(self.tags_view, _('No books selected'), _('No books are selected. Showing all items.'), show=True) book_ids = None data = db.new_api.get_categories(book_ids=book_ids) if category in data: result = [(t.id, t.original_name, t.count) for t in data[category] if t.count > 0] else: result = None return result def do_tags_list_edit(self, tag, category, is_first_letter=False): ''' Open the 'manage_X' dialog where X == category. If tag is not None, the dialog will position the editor on that item. ''' db = self.current_db if category == 'series': def key(x): return sort_key(title_sort(x)) else: key = sort_key d = TagListEditor(self, category=category, cat_name=db.field_metadata[category]['name'], tag_to_match=tag, get_book_ids=partial(self.get_book_ids_in_vl_or_selection, db=db, category=category), sorter=key, ttm_is_first_letter=is_first_letter, fm=db.field_metadata[category], link_map=db.new_api.get_link_map(category)) d.exec() if d.result() == QDialog.DialogCode.Accepted: to_rename = d.to_rename # dict of old id to new name to_delete = d.to_delete # list of ids orig_name = d.original_names # dict of id: name if (category in ['tags', 'series', 'publisher'] or db.new_api.field_metadata.is_custom_field(category)): m = self.tags_view.model() for item in to_delete: m.delete_item_from_all_user_categories(orig_name[item], category) for old_id in to_rename: m.rename_item_in_all_user_categories(orig_name[old_id], category, str(to_rename[old_id])) db.new_api.remove_items(category, to_delete) db.new_api.rename_items(category, to_rename, change_index=False) # Must do this at the end so renames and deletes are accounted for db.new_api.set_link_map(category, d.links) # Clean up the library view self.do_field_item_value_changed() self.tags_view.recount() def do_tag_item_delete(self, category, item_id, orig_name, restrict_to_book_ids=None, children=[]): ''' Delete an item from some category. ''' tag_names = [] for child in children: if child.tag.is_editable: tag_names.append(child.tag.original_name) n = '\n '.join(tag_names) if n: n = '%s:\n %s\n%s:\n %s'%(_('Item'), orig_name, _('Children'), n) if n: # Use a new "see this again" name to force the dialog to appear at # least once, thus announcing the new feature. skip_dialog_name = 'tag_item_delete_hierarchical' if restrict_to_book_ids: msg = _('%s and its children will be deleted from books ' 'in the Virtual library. Are you sure?')%orig_name else: msg = _('%s and its children will be deleted from all books. ' 'Are you sure?')%orig_name else: skip_dialog_name='tag_item_delete' if restrict_to_book_ids: msg = _('%s will be deleted from books in the Virtual library. Are you sure?')%orig_name else: msg = _('%s will be deleted from all books. Are you sure?')%orig_name if not question_dialog(self.tags_view, title=_('Delete item'), msg='<p>'+ msg, det_msg=n, skip_dialog_name=skip_dialog_name, skip_dialog_msg=_('Show this confirmation again')): return ids_to_remove = [] if item_id is not None: ids_to_remove.append(item_id) for child in children: if child.tag.is_editable: ids_to_remove.append(child.tag.id) self.current_db.new_api.remove_items(category, ids_to_remove, restrict_to_book_ids=restrict_to_book_ids) if restrict_to_book_ids is None: m = self.tags_view.model() m.delete_item_from_all_user_categories(orig_name, category) # Clean up the library view self.do_field_item_value_changed() self.tags_view.recount() def apply_tag_to_selected(self, field_name, item_name, remove): db = self.current_db.new_api fm = db.field_metadata.get(field_name) if fm is None: return book_ids = self.library_view.get_selected_ids() if not book_ids: return error_dialog(self.library_view, _('No books selected'), _( 'You must select some books to apply {} to').format(item_name), show=True) existing_values = db.all_field_for(field_name, book_ids) series_index_field = None if fm['datatype'] == 'series': series_index_field = field_name + '_index' changes = {} for book_id, existing in iteritems(existing_values): if isinstance(existing, tuple): existing = list(existing) if remove: try: existing.remove(item_name) except ValueError: continue changes[book_id] = existing else: if item_name not in existing: changes[book_id] = existing + [item_name] else: if remove: if existing == item_name: changes[book_id] = None else: if existing != item_name: changes[book_id] = item_name if changes: db.set_field(field_name, changes) if series_index_field is not None: for book_id in changes: si = db.get_next_series_num_for(item_name, field=field_name) db.set_field(series_index_field, {book_id: si}) self.library_view.model().refresh_ids(set(changes), current_row=self.library_view.currentIndex().row()) self.tags_view.recount_with_position_based_index() def delete_identifier(self, name, in_vl): d = self.current_db.new_api changed = False books_to_use = self.tags_view.model().get_book_ids_to_use() if in_vl else d.all_book_ids() ids = d.all_field_for('identifiers', books_to_use) new_ids = {} for id_ in ids: for identifier_type in ids[id_]: if identifier_type == name: new_ids[id_] = copy.copy(ids[id_]) new_ids[id_].pop(name) changed = True if changed: if in_vl: msg = _('The identifier %s will be deleted from books in the ' 'current virtual library. Are you sure?')%name else: msg= _('The identifier %s will be deleted from all books. Are you sure?')%name if not question_dialog(self, title=_('Delete identifier'), msg=msg, skip_dialog_name='tag_browser_delete_identifiers', skip_dialog_msg=_('Show this confirmation again')): return d.set_field('identifiers', new_ids) self.tags_view.recount_with_position_based_index() def edit_enum_values(self, parent, db, key): from calibre.gui2.dialogs.enum_values_edit import EnumValuesEdit d = EnumValuesEdit(parent, db, key) d.exec() def do_field_item_value_changed(self): # Clean up library view and search, which also cleans up book details # get information to redo the selection rows = [r.row() for r in self.library_view.selectionModel().selectedRows()] m = self.library_view.model() ids = [m.id(r) for r in rows] self.tags_view.model().reset_notes_and_link_maps() m.refresh(reset=False) m.research() self.library_view.select_rows(ids) # refreshing the tags view happens at the emit()/call() site do_tag_item_renamed = do_field_item_value_changed # alias for backcompat def do_author_sort_edit(self, parent, id_, select_sort=True, select_link=False, is_first_letter=False, lookup_author=False): ''' Open the manage authors dialog ''' db = self.library_view.model().db get_authors_func = partial(self.get_book_ids_in_vl_or_selection, db=db, category='authors') if lookup_author: for t in get_authors_func(None): if t[1] == id_: id_ = t[0] break editor = EditAuthorsDialog(parent, db, id_, select_sort, select_link, get_authors_func, is_first_letter) if editor.exec() == QDialog.DialogCode.Accepted: # Save and restore the current selections. Note that some changes # will cause sort orders to change, so don't bother with attempting # to restore the position. Restoring the state has the side effect # of refreshing book details. with self.library_view.preserve_state(preserve_hpos=False, preserve_vpos=False): affected_books, id_map = set(), {} db = db.new_api rename_map = {author_id:new_author for author_id, old_author, new_author, new_sort, new_link in editor.result if old_author != new_author} if rename_map: affected_books, id_map = db.rename_items('authors', rename_map) link_map = {id_map.get(author_id, author_id):new_link for author_id, old_author, new_author, new_sort, new_link in editor.result} affected_books |= db.set_link_for_authors(link_map) sort_map = {id_map.get(author_id, author_id):new_sort for author_id, old_author, new_author, new_sort, new_link in editor.result} affected_books |= db.set_sort_for_authors(sort_map) self.library_view.model().refresh_ids(affected_books, current_row=self.library_view.currentIndex().row()) self.do_field_item_value_changed() self.tags_view.recount() def drag_drop_finished(self, ids): self.library_view.model().refresh_ids(ids) def tb_category_visibility(self, category, operation): ''' Hide or show categories in the tag browser. 'category' is the lookup key. Operation can be: - 'show' to show the category in the tag browser - 'hide' to hide the category - 'toggle' to invert its visibility - 'is_visible' returns True if the category is currently visible, False otherwise ''' if category not in self.tags_view.model().categories: raise ValueError(_('change_tb_category_visibility: category %s does not exist') % category) cats = self.tags_view.hidden_categories if operation == 'hide': cats.add(category) elif operation == 'show': cats.discard(category) elif operation == 'toggle': if category in cats: cats.remove(category) else: cats.add(category) elif operation == 'is_visible': return category not in cats else: raise ValueError(_('change_tb_category_visibility: invalid operation %s') % operation) self.library_view.model().db.new_api.set_pref('tag_browser_hidden_categories', list(cats)) self.tags_view.recount() # }}} class FindBox(HistoryLineEdit): # {{{ def keyPressEvent(self, event): k = event.key() if k not in (Qt.Key.Key_Up, Qt.Key.Key_Down): return HistoryLineEdit.keyPressEvent(self, event) self.blockSignals(True) if k == Qt.Key.Key_Down and self.currentIndex() == 0 and not self.lineEdit().text(): self.setCurrentIndex(1), self.setCurrentIndex(0) event.accept() else: HistoryLineEdit.keyPressEvent(self, event) self.blockSignals(False) # }}} class TagBrowserBar(QWidget): # {{{ clear_find = pyqtSignal() def __init__(self, parent): QWidget.__init__(self, parent) self.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred) parent = parent.parent() self.l = l = QHBoxLayout(self) l.setContentsMargins(0, 0, 0, 0) self.alter_tb = parent.alter_tb = b = QToolButton(self) b.setAutoRaise(True) b.setText(_('Configure')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) b.setCursor(Qt.CursorShape.PointingHandCursor) b.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup) b.setToolTip(textwrap.fill(_( 'Change how the Tag browser works, such as,' ' how it is sorted, what happens when you click' ' items, etc.' ))) b.setIcon(QIcon.ic('config.png')) b.m = QMenu(b) b.setMenu(b.m) self.item_search = FindBox(parent) self.item_search.setMinimumContentsLength(5) self.item_search.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon) self.item_search.initialize('tag_browser_search') self.item_search.completer().setCaseSensitivity(Qt.CaseSensitivity.CaseSensitive) self.item_search.setToolTip( _('<p>' 'Search for items in the Tag browser. If the search text begins ' 'with an equals sign (=) then the search is "equals", otherwise ' 'it is "contains". Both the equals and contains searches ignore ' 'case. If the preference <em>Preferences -> Searching -> Unaccented ' 'characters match accented characters ...</em> is checked then a ' '<em>Character variant search</em> is used, where characters ' 'match regardless of accents, and punctuation is significant. See ' '<em>The search interface</em> in the calibre manual for more explanation.' '</p><p>' 'You can limit the search to particular categories using syntax ' "similar to calibre's <em>Search</em>. For example, tags:foo will " 'find foo in tags but not in authors etc.' '</p><p>' 'Entering *foo will collapse all categories before doing the ' 'search.' '</p>')) ac = QAction(parent) parent.addAction(ac) parent.keyboard.register_shortcut('tag browser find box', _('Find in the Tag browser'), default_keys=(), action=ac, group=_('Tag browser')) ac.triggered.connect(self.set_focus_to_find_box) self.search_button = QToolButton() self.search_button.setAutoRaise(True) self.search_button.setCursor(Qt.CursorShape.PointingHandCursor) self.search_button.setIcon(QIcon.ic('search.png')) self.search_button.setToolTip(_('Find the first/next matching item')) ac = QAction(parent) parent.addAction(ac) parent.keyboard.register_shortcut('tag browser find button', _('Find next match'), default_keys=(), action=ac, group=_('Tag browser')) ac.triggered.connect(self.search_button.click) self.toggle_search_button = b = QToolButton(self) le = self.item_search.lineEdit() le.addAction(QIcon.ic('window-close.png'), QLineEdit.ActionPosition.LeadingPosition).triggered.connect(self.close_find_box) b.setText(_('Find')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) b.setCursor(Qt.CursorShape.PointingHandCursor) b.setIcon(QIcon.ic('search.png')) b.setCheckable(True) b.setChecked(gprefs.get('tag browser search box visible', False)) b.setToolTip(_('Find item in the Tag browser')) b.setAutoRaise(True) b.toggled.connect(self.update_searchbar_state) self.update_searchbar_state() def close_find_box(self): self.item_search.setCurrentIndex(0) self.item_search.setCurrentText('') self.toggle_search_button.click() self.clear_find.emit() def set_focus_to_find_box(self): self.toggle_search_button.setChecked(True) self.item_search.setFocus() self.item_search.lineEdit().selectAll() def update_searchbar_state(self): find_shown = self.toggle_search_button.isChecked() self.toggle_search_button.setVisible(not find_shown) l = self.layout() while l.count(): l.takeAt(0) if find_shown: l.addWidget(self.alter_tb) self.alter_tb.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly) l.addWidget(self.item_search, 10) l.addWidget(self.search_button) self.item_search.setFocus(Qt.FocusReason.OtherFocusReason) self.toggle_search_button.setVisible(False) self.search_button.setVisible(True) self.item_search.setVisible(True) else: l.addWidget(self.alter_tb) self.alter_tb.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) l.addStretch(10) l.addStretch(10) l.addWidget(self.toggle_search_button) self.toggle_search_button.setVisible(True) self.search_button.setVisible(False) self.item_search.setVisible(False) # }}} class TagBrowserWidget(QFrame): # {{{ def __init__(self, parent): QFrame.__init__(self, parent) self.setFrameStyle(QFrame.Shape.NoFrame) self._parent = parent self._layout = QVBoxLayout(self) self._layout.setContentsMargins(0,0,0,0) # Set up the find box & button self.tb_bar = tbb = TagBrowserBar(self) tbb.clear_find.connect(self.reset_find) self.alter_tb, self.item_search, self.search_button = tbb.alter_tb, tbb.item_search, tbb.search_button self.toggle_search_button = tbb.toggle_search_button self._layout.addWidget(tbb) self.current_find_position = None self.search_button.clicked.connect(self.find) self.item_search.lineEdit().textEdited.connect(self.find_text_changed) self.item_search.textActivated.connect(self.do_find) # The tags view parent.tags_view = TagsView(parent) self.tags_view = parent.tags_view self._layout.insertWidget(0, parent.tags_view) # Now the floating 'not found' box l = QLabel(self.tags_view) self.not_found_label = l l.setFrameStyle(QFrame.Shape.StyledPanel) l.setAutoFillBackground(True) l.setText('<p><b>'+_('No more matches.</b><p> Click Find again to go to first match')) l.setAlignment(Qt.AlignmentFlag.AlignVCenter) l.setWordWrap(True) l.resize(l.sizeHint()) l.move(10,20) 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.collapse_all_action = ac = QAction(parent) parent.addAction(ac) parent.keyboard.register_shortcut('tag browser collapse all', _('Collapse all'), default_keys=(), action=ac, group=_('Tag browser')) connect_lambda(ac.triggered, self, lambda self: self.tags_view.collapseAll()) # The Configure Tag Browser button l = self.alter_tb ac = QAction(parent) parent.addAction(ac) parent.keyboard.register_shortcut('tag browser alter', _('Configure Tag browser'), default_keys=(), action=ac, group=_('Tag browser')) ac.triggered.connect(l.showMenu) l.m.aboutToShow.connect(self.about_to_show_configure_menu) # Show/hide counts l.m.show_counts_action = ac = l.m.addAction('counts') parent.keyboard.register_shortcut('tag browser toggle counts', _('Toggle counts'), default_keys=(), action=ac, group=_('Tag browser')) ac.triggered.connect(self.toggle_counts) # Show/hide average rating l.m.show_avg_rating_action = ac = l.m.addAction(QIcon.ic('rating.png'), 'avg rating') ac.triggered.connect(self.toggle_avg_rating) parent.keyboard.register_shortcut('tag browser toggle average ratings', _('Toggle average ratings'), default_keys=(), action=ac, group=_('Tag browser')) # Show/hide notes icon l.m.show_notes_icon_action = ac = l.m.addAction(QIcon.ic('notes.png'), 'notes icon') ac.triggered.connect(self.toggle_notes) parent.keyboard.register_shortcut('tag browser toggle notes', _('Toggle notes icons'), default_keys=(), action=ac, group=_('Tag browser')) # Show/hide links icon l.m.show_links_icon_action = ac = l.m.addAction(QIcon.ic('external-link.png'), 'links icon') ac.triggered.connect(self.toggle_links) parent.keyboard.register_shortcut('tag browser toggle links', _('Toggle links icons'), default_keys=(), action=ac, group=_('Tag browser')) # Show/hide empty categories l.m.show_empty_categories_action = ac = l.m.addAction(QIcon.ic('external-link.png'), 'links icon') ac.triggered.connect(self.toggle_show_empty_categories) parent.keyboard.register_shortcut('tag browser show empty categories', _('Show empty categories (columns)'), default_keys=(), action=ac, group=_('Tag browser')) sb = l.m.addAction(QIcon.ic('sort.png'), _('Sort by')) sb.m = l.sort_menu = QMenu(l.m) sb.setMenu(sb.m) sb.bg = QActionGroup(sb) # Must be in the same order as db2.CATEGORY_SORTS for i, x in enumerate((_('Name'), _('Number of books'), _('Average rating'))): a = sb.m.addAction(x) parent.keyboard.register_shortcut( f"tag browser sort by {('notes', 'number of books', 'average rating')[i]}", (_('Sort by name'), _('Sort by number of books'), _('Sort by average rating'))[i], default_keys=(), action=a, group=_('Tag browser')) sb.bg.addAction(a) a.setCheckable(True) if i == 0: a.setChecked(True) sb.setToolTip( _('Set the sort order for entries in the Tag browser')) sb.setStatusTip(sb.toolTip()) ma = l.m.addAction(QIcon.ic('search.png'), _('Search type when selecting multiple items')) ma.m = l.match_menu = QMenu(l.m) ma.setMenu(ma.m) ma.ag = QActionGroup(ma) # Must be in the same order as db2.MATCH_TYPE for i, x in enumerate((_('Match any of the items'), _('Match all of the items'))): a = ma.m.addAction(x) ma.ag.addAction(a) a.setCheckable(True) if i == 0: a.setChecked(True) ma.setToolTip( _('When selecting multiple entries in the Tag browser ' 'match any or all of them')) ma.setStatusTip(ma.toolTip()) mt = l.m.addAction(_('Manage authors, tags, etc.')) mt.setToolTip(_('All of these category managers are available by right-clicking ' 'on items in the Tag browser above')) mt.m = l.manage_menu = QMenu(l.m) mt.setMenu(mt.m) l.m.filter_action = ac = l.m.addAction(QIcon.ic('filter.png'), _('Show only books that have visible categories')) # Give it a (complicated) shortcut so people can discover a shortcut # is possible, I hope without creating collisions. parent.keyboard.register_shortcut('tag browser filter booklist', _('Filter book list'), default_keys=('Ctrl+Alt+Shift+F',), action=ac, group=_('Tag browser')) ac.triggered.connect(self.filter_book_list) ac = QAction(parent) parent.addAction(ac) parent.keyboard.register_shortcut('tag browser toggle item', _("'Click' found item"), default_keys=(), action=ac, group=_('Tag browser')) ac.triggered.connect(self.toggle_item) ac = QAction(parent) parent.addAction(ac) parent.keyboard.register_shortcut('tag browser set focus', _("Give the Tag browser keyboard focus"), default_keys=(), action=ac, group=_('Tag browser')) ac.triggered.connect(self.give_tb_focus) # self.leak_test_timer = QTimer(self) # self.leak_test_timer.timeout.connect(self.test_for_leak) # self.leak_test_timer.start(5000) def about_to_show_configure_menu(self): ac = self.alter_tb.m.show_counts_action p = gprefs['tag_browser_show_counts'] ac.setText(_('Hide counts') if p else _('Show counts')) ac.setIcon(QIcon.ic('minus.png') if p else QIcon.ic('plus.png')) ac = self.alter_tb.m.show_avg_rating_action p = config['show_avg_rating'] ac.setText(_('Hide average rating') if p else _('Show average rating')) ac.setIcon(QIcon.ic('minus.png' if p else 'plus.png')) ac = self.alter_tb.m.show_notes_icon_action p = gprefs['show_notes_in_tag_browser'] ac.setText(_('Hide notes icon') if p else _('Show notes icon')) ac.setIcon(QIcon.ic('minus.png' if p else 'plus.png')) ac = self.alter_tb.m.show_links_icon_action p = gprefs['show_links_in_tag_browser'] ac.setText(_('Hide links icon') if p else _('Show links icon')) ac.setIcon(QIcon.ic('minus.png' if p else 'plus.png')) ac = self.alter_tb.m.show_empty_categories_action p = self.tags_view.model().prefs['tag_browser_hide_empty_categories'] ac.setText(_('Show empty categories (columns)') if p else _('Hide empty categories (columns)')) ac.setIcon(QIcon.ic('plus.png' if p else 'minus.png')) def filter_book_list(self): self.tags_view.model().set_in_tag_browser() self._parent.search.set_search_string('in_tag_browser:true') def toggle_counts(self): gprefs['tag_browser_show_counts'] ^= True self.tags_view.recount_with_position_based_index() def toggle_avg_rating(self): config['show_avg_rating'] ^= True self.tags_view.recount_with_position_based_index() def toggle_notes(self): gprefs['show_notes_in_tag_browser'] ^= True self.tags_view.recount_with_position_based_index() def toggle_links(self): gprefs['show_links_in_tag_browser'] ^= True self.tags_view.recount_with_position_based_index() def toggle_show_empty_categories(self): self.tags_view.model().prefs['tag_browser_hide_empty_categories'] ^= True self.tags_view.recount_with_position_based_index() def save_state(self): gprefs.set('tag browser search box visible', self.toggle_search_button.isChecked()) def toggle_item(self): self.tags_view.toggle_current_index() def give_tb_focus(self, *args): if gprefs['tag_browser_allow_keyboard_focus']: tb = self.tags_view if tb.hasFocus(): self._parent.shift_esc() elif self._parent.current_view() == self._parent.library_view: tb.setFocus() idx = tb.currentIndex() if not idx.isValid(): idx = tb.model().createIndex(0, 0) tb.setCurrentIndex(idx) def set_pane_is_visible(self, to_what): self.tags_view.set_pane_is_visible(to_what) if not to_what: self._parent.shift_esc() def find_text_changed(self, str_): self.current_find_position = None def set_focus_to_find_box(self): self.tb_bar.set_focus_to_find_box() def do_find(self, str_=None): self.current_find_position = None self.find() @property def find_text(self): return str(self.item_search.currentText()).strip() def reset_find(self): model = self.tags_view.model() model.clear_boxed() if model.get_categories_filter(): model.set_categories_filter(None) self.tags_view.recount() self.current_find_position = None def find(self): model = self.tags_view.model() model.clear_boxed() # When a key is specified don't use the auto-collapsing search. # A colon separates the lookup key from the search string. # A leading colon says not to use autocollapsing search but search all keys txt = self.find_text colon = txt.find(':') if colon >= 0: key = self._parent.library_view.model().db.\ field_metadata.search_term_to_field_key(txt[:colon]) if key in self._parent.library_view.model().db.field_metadata: txt = txt[colon+1:] else: key = '' txt = txt[1:] if colon == 0 else txt else: key = None # key is None indicates that no colon was found. # key == '' means either a leading : was found or the key is invalid # At this point the txt might have a leading =, in which case do an # exact match search if (gprefs.get('tag_browser_always_autocollapse', False) and key is None and not txt.startswith('*')): txt = '*' + txt if txt.startswith('*'): self.tags_view.collapseAll() model.set_categories_filter(txt[1:]) self.tags_view.recount() self.current_find_position = None return if model.get_categories_filter(): model.set_categories_filter(None) self.tags_view.recount() self.current_find_position = None if not txt: return self.item_search.lineEdit().blockSignals(True) self.search_button.setFocus(Qt.FocusReason.OtherFocusReason) self.item_search.lineEdit().blockSignals(False) if txt.startswith('='): equals_match = True txt = txt[1:] else: equals_match = False self.current_find_position = \ model.find_item_node(key, txt, self.current_find_position, equals_match=equals_match) if self.current_find_position: self.tags_view.show_item_at_path(self.current_find_position, box=True) elif self.item_search.text(): self.not_found_label.setVisible(True) if self.tags_view.verticalScrollBar().isVisible(): sbw = self.tags_view.verticalScrollBar().width() else: sbw = 0 width = self.width() - 8 - sbw height = self.not_found_label.heightForWidth(width) + 20 self.not_found_label.resize(width, height) self.not_found_label.move(4, 10) self.not_found_label_timer.start(2000) def not_found_label_timer_event(self): self.not_found_label.setVisible(False) def keyPressEvent(self, ev): if ev.key() in (Qt.Key.Key_Enter, Qt.Key.Key_Return) and self.item_search.hasFocus(): self.find() ev.accept() return return QFrame.keyPressEvent(self, ev) # }}}
47,750
Python
.py
959
37.763295
154
0.592643
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,751
__init__.py
kovidgoyal_calibre/src/calibre/gui2/tag_browser/__init__.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en'
149
Python
.py
4
35
58
0.678571
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,752
model.py
kovidgoyal_calibre/src/calibre/gui2/tag_browser/model.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import copy import os import traceback from collections import OrderedDict, namedtuple from qt.core import QAbstractItemModel, QFont, QIcon, QMimeData, QModelIndex, QObject, Qt, pyqtSignal from calibre.constants import config_dir from calibre.db.categories import Tag, category_display_order from calibre.ebooks.metadata import rating_to_stars from calibre.gui2 import config, error_dialog, file_icon_provider, gprefs, question_dialog from calibre.gui2.dialogs.confirm_delete import confirm from calibre.library.field_metadata import category_icon_map from calibre.utils.config import prefs, tweaks from calibre.utils.formatter import EvalFormatter from calibre.utils.icu import collation_order_for_partitioning, contains, lower, primary_contains, primary_strcmp, sort_key, strcmp from calibre.utils.icu import lower as icu_lower from calibre.utils.icu import upper as icu_upper from calibre.utils.serialize import json_dumps, json_loads from polyglot.builtins import iteritems, itervalues TAG_SEARCH_STATES = {'clear': 0, 'mark_plus': 1, 'mark_plusplus': 2, 'mark_minus': 3, 'mark_minusminus': 4} DRAG_IMAGE_ROLE = Qt.ItemDataRole.UserRole + 1000 COUNT_ROLE = DRAG_IMAGE_ROLE + 1 _bf = None def bf(): global _bf if _bf is None: _bf = QFont() _bf.setBold(True) _bf = (_bf) return _bf class TagTreeItem: # {{{ CATEGORY = 0 TAG = 1 ROOT = 2 category_custom_icons = {} file_icon_provider = None def __init__(self, data=None, is_category=False, icon_map=None, parent=None, tooltip=None, category_key=None, temporary=False, is_gst=False): if self.file_icon_provider is None: self.file_icon_provider = TagTreeItem.file_icon_provider = file_icon_provider().icon_from_ext self.parent = parent self.children = [] self.blank = QIcon() self.is_gst = is_gst self.boxed = False self.temporary = False self.can_be_edited = False self.icon_state_map = list(icon_map) if self.parent is not None: self.parent.append(self) if data is None: self.type = self.ROOT else: self.type = self.CATEGORY if is_category else self.TAG if self.type == self.CATEGORY: self.name = data self.py_name = data self.category_key = category_key self.temporary = temporary self.tag = Tag(data, category=category_key, is_editable=category_key not in ['news', 'search', 'identifiers', 'languages'], is_searchable=category_key not in ['search']) elif self.type == self.TAG: self.tag = data self.cached_average_rating = None self.cached_item_count = None self.tooltip = tooltip or '' @property def name_id(self): if self.type == self.CATEGORY: return self.category_key + ':' + self.name elif self.type == self.TAG: return self.tag.original_name return '' def break_cycles(self): del self.parent del self.children def root_node(self): p = self while p.parent.type != self.ROOT: p = p.parent return p def ensure_icon(self): if self.icon_state_map[0] is not None: return if self.type == self.TAG: if self.tag.category == 'formats': fmt = self.tag.original_name.replace('ORIGINAL_', '') cc = self.file_icon_provider(fmt) else: if self.is_gst: cc = self.category_custom_icons.get(self.root_node().category_key, None) elif self.tag.category == 'search' and not self.tag.is_searchable: cc = self.category_custom_icons.get('search_folder:', None) else: cc = self.category_custom_icons.get(self.tag.category, None) elif self.type == self.CATEGORY: cc = self.category_custom_icons.get(self.category_key, None) self.icon_state_map[0] = cc or QIcon() def __str__(self): if self.type == self.ROOT: return 'ROOT' if self.type == self.CATEGORY: return 'CATEGORY(category_key={!r}, name={!r}, num_children={!r}, temp={!r})'.format( self.category_key, self.name, len(self.children), self.temporary) return f'TAG(name={self.tag.name!r}), temp={self.temporary!r})' def row(self): if self.parent is not None: return self.parent.children.index(self) return 0 def append(self, child): child.parent = self self.children.append(child) @property def average_rating(self): if self.type != self.TAG: return 0 if self.tag.category == 'search': return None if not self.tag.is_hierarchical: return self.tag.avg_rating if not self.children: return self.tag.avg_rating # leaf node, avg_rating is correct if self.cached_average_rating is None: raise ValueError('Must compute average rating for tag ' + self.tag.original_name) return self.cached_average_rating @property def item_count(self): if not self.tag.is_hierarchical or not self.children: return self.tag.count if self.cached_item_count is not None: return self.cached_item_count def child_item_set(node): s = node.tag.id_set.copy() for child in node.children: s |= child_item_set(child) return s self.cached_item_count = len(child_item_set(self)) return self.cached_item_count def data(self, role): if role == Qt.ItemDataRole.UserRole: return self if self.type == self.TAG: return self.tag_data(role) if self.type == self.CATEGORY: return self.category_data(role) return None def category_data(self, role): if role == Qt.ItemDataRole.DisplayRole: return self.py_name if role == Qt.ItemDataRole.EditRole: return (self.py_name) if role == Qt.ItemDataRole.DecorationRole: if not self.tag.state: self.ensure_icon() return self.icon_state_map[self.tag.state] if role == Qt.ItemDataRole.FontRole: return bf() if role == Qt.ItemDataRole.ToolTipRole: return self.tooltip if gprefs['tag_browser_show_tooltips'] else None if role == DRAG_IMAGE_ROLE: self.ensure_icon() return self.icon_state_map[0] if role == COUNT_ROLE: return len(self.child_tags()) return None def tag_data(self, role): tag = self.tag if tag.use_sort_as_name: name = tag.sort else: if not tag.is_hierarchical: name = tag.original_name else: name = tag.name if role == Qt.ItemDataRole.DisplayRole: return str(name) if role == Qt.ItemDataRole.EditRole: return (tag.original_name) if role == Qt.ItemDataRole.DecorationRole: if not tag.state: self.ensure_icon() return self.icon_state_map[tag.state] if role == Qt.ItemDataRole.ToolTipRole: if gprefs['tag_browser_show_tooltips']: if self.type == self.TAG and tag.category == 'search': if tag.search_expression is None: return _('{} is not a saved search').format(tag.original_name) return (f'search:{tag.original_name}\n' + _('Search expression:') + ' ' + tag.search_expression) tt = [self.tooltip] if self.tooltip else [] if tag.original_categories: tt.append('{}:{}'.format(','.join(tag.original_categories), tag.original_name)) else: tt.append(f'{tag.category}:{tag.original_name}') ar = self.average_rating if ar: tt.append(_('Average rating for books in this category: %.1f') % ar) elif self.type == self.TAG: if ar is not None: tt.append(_('Books in this category are unrated')) if tag.category != 'search': tt.append(_('Number of books: %s') % self.item_count) from calibre.gui2.ui import get_gui db = get_gui().current_db.new_api link = (None if not db.has_link_map(tag.category) else db.get_link_map(tag.category).get(tag.original_name)) if link: tt.append(_('Link: %s') % link) return '\n'.join(tt) return None if role == DRAG_IMAGE_ROLE: self.ensure_icon() return self.icon_state_map[0] if role == COUNT_ROLE: return self.item_count return None def dump_data(self): fmt = '%s [count=%s%s]' if self.type == self.CATEGORY: return fmt % (self.py_name, len(self.child_tags()), '') tag = self.tag if tag.use_sort_as_name: name = tag.sort else: if not tag.is_hierarchical: name = tag.original_name else: name = tag.name count = self.item_count rating = self.average_rating if rating: rating = ',rating=%.1f' % rating return fmt % (name, count, rating or '') def toggle(self, set_to=None): ''' set_to: None => advance the state, otherwise a value from TAG_SEARCH_STATES ''' tag = self.tag if set_to is None: while True: tag_search_order_graph = gprefs.get('tb_search_order') # JSON dumps converts integer keys to strings, so do it explicitly tag.state = tag_search_order_graph[str(tag.state)] if tag.state == TAG_SEARCH_STATES['mark_plus'] or \ tag.state == TAG_SEARCH_STATES['mark_minus']: if tag.is_searchable: break elif tag.state == TAG_SEARCH_STATES['mark_plusplus'] or\ tag.state == TAG_SEARCH_STATES['mark_minusminus']: if tag.is_searchable and len(self.children) and \ tag.is_hierarchical == '5state': break else: break else: tag.state = set_to def all_children(self): res = [] def recurse(nodes, res): for t in nodes: res.append(t) recurse(t.children, res) recurse(self.children, res) return res def child_tags(self): res = [] def recurse(nodes, res, depth): if depth > 100: return for t in nodes: if t.type != TagTreeItem.CATEGORY: res.append(t) recurse(t.children, res, depth+1) recurse(self.children, res, 1) return res # }}} FL_Interval = namedtuple('FL_Interval', ('first_chr', 'last_chr', 'length')) def rename_only_in_vl_question(parent): return question_dialog(parent, _('Rename in Virtual library'), '<p>' + _('Do you want this rename to apply only to books ' 'in the current Virtual library?') + '</p>', yes_text=_('Yes, apply only in VL'), no_text=_('No, apply in entire library')) class TagsModel(QAbstractItemModel): # {{{ search_item_renamed = pyqtSignal() tag_item_renamed = pyqtSignal() refresh_required = pyqtSignal() research_required = pyqtSignal() restriction_error = pyqtSignal(object) drag_drop_finished = pyqtSignal(object) user_categories_edited = pyqtSignal(object, object) user_category_added = pyqtSignal() show_error_after_event_loop_tick_signal = pyqtSignal(object, object, object) convert_requested = pyqtSignal(object, object) def __init__(self, parent, prefs=gprefs): QAbstractItemModel.__init__(self, parent) self.use_position_based_index_on_next_recount = False self.prefs = prefs self.node_map = {} self.category_nodes = [] self.category_custom_icons = {} for k, v in iteritems(self.prefs['tags_browser_category_icons']): icon = QIcon(os.path.join(config_dir, 'tb_icons', v)) if len(icon.availableSizes()) > 0: self.category_custom_icons[k] = icon self.categories_with_ratings = ['authors', 'series', 'publisher', 'tags'] self.icon_state_map = [None, QIcon.ic('plus.png'), QIcon.ic('plusplus.png'), QIcon.ic('minus.png'), QIcon.ic('minusminus.png')] self.hidden_categories = set() self.search_restriction = None self.filter_categories_by = None self.collapse_model = 'disable' self.row_map = [] self.root_item = self.create_node(icon_map=self.icon_state_map) self.db = None self._build_in_progress = False self.reread_collapse_model({}, rebuild=False) self.show_error_after_event_loop_tick_signal.connect(self.on_show_error_after_event_loop_tick, type=Qt.ConnectionType.QueuedConnection) self.reset_notes_and_link_maps() @property def gui_parent(self): return QObject.parent(self) def rename_user_category_icon(self, old_key, new_key): ''' This is required for user categories because the key (lookup name) changes on rename. We must rename the old icon to use the new key then update the preferences and internal tables. ''' old_icon = self.prefs['tags_browser_category_icons'].get(old_key, None) if old_icon is not None: old_path = os.path.join(config_dir, 'tb_icons', old_icon) _, ext = os.path.splitext(old_path) new_icon = new_key + ext new_path = os.path.join(config_dir, 'tb_icons', new_icon) os.replace(old_path, new_path) self.set_custom_category_icon(new_key, new_path) self.set_custom_category_icon(old_key, None) def set_custom_category_icon(self, key, path): d = self.prefs['tags_browser_category_icons'] if path: d[key] = path self.category_custom_icons[key] = QIcon(os.path.join(config_dir, 'tb_icons', path)) else: if key in d: path = os.path.join(config_dir, 'tb_icons', d[key]) try: os.remove(path) except: pass del d[key] del self.category_custom_icons[key] self.prefs['tags_browser_category_icons'] = d def reread_collapse_model(self, state_map, rebuild=True): if self.prefs['tags_browser_collapse_at'] == 0: self.collapse_model = 'disable' else: self.collapse_model = self.prefs['tags_browser_partition_method'] if rebuild: self.rebuild_node_tree(state_map) def set_database(self, db, hidden_categories=None): self.beginResetModel() hidden_cats = db.new_api.pref('tag_browser_hidden_categories', None) # migrate from config to db prefs if hidden_cats is None: hidden_cats = config['tag_browser_hidden_categories'] self.hidden_categories = set() # strip out any non-existent field keys for cat in hidden_cats: if cat in db.field_metadata: self.hidden_categories.add(cat) db.new_api.set_pref('tag_browser_hidden_categories', list(self.hidden_categories)) if hidden_categories is not None: self.hidden_categories = hidden_categories self.db = db self._run_rebuild() self.endResetModel() def reset_tag_browser(self): self.beginResetModel() hidden_cats = self.db.new_api.pref('tag_browser_hidden_categories', {}) self.hidden_categories = set() # strip out any non-existent field keys for cat in hidden_cats: if cat in self.db.field_metadata: self.hidden_categories.add(cat) self._run_rebuild() self.endResetModel() def _cached_notes_map(self, category): if self.notes_map is None: self.notes_map = {} ans = self.notes_map.get(category) if ans is None: try: self.notes_map[category] = ans = (self.db.new_api.get_all_items_that_have_notes(category), self.db.new_api.get_item_name_map(category)) except Exception: self.notes_map[category] = ans = (frozenset(), {}) return ans def _cached_link_map(self, category): if self.link_map is None: self.link_map = {} ans = self.link_map.get(category) if ans is None: try: self.link_map[category] = ans = self.db.new_api.get_link_map(category) except Exception: self.link_map[category] = ans = {} return ans def category_has_notes(self, category): return bool(self._cached_notes_map(category)[0]) def item_has_note(self, category, item_name): notes_map, item_id_map = self._cached_notes_map(category) return item_id_map.get(item_name) in notes_map def category_has_links(self, category): return bool(self._cached_link_map(category)) def item_has_link(self, category, item_name): return item_name in self._cached_link_map(category) def reset_notes_and_link_maps(self): self.link_map = self.notes_map = None def rebuild_node_tree(self, state_map={}): if self._build_in_progress: print('Tag browser build already in progress') traceback.print_stack() return # traceback.print_stack() # print () self._build_in_progress = True self.beginResetModel() self._run_rebuild(state_map=state_map) self.endResetModel() self._build_in_progress = False def _run_rebuild(self, state_map={}): self.reset_notes_and_link_maps() for node in itervalues(self.node_map): node.break_cycles() del node # Clear reference to node in the current frame self.node_map.clear() self.category_nodes = [] self.hierarchical_categories = {} self.root_item = self.create_node(icon_map=self.icon_state_map) self._rebuild_node_tree(state_map=state_map) def _rebuild_node_tree(self, state_map): # Note that _get_category_nodes can indirectly change the # user_categories dict. data = self._get_category_nodes(config['sort_tags_by']) gst = self.db.new_api.pref('grouped_search_terms', {}) if self.category_custom_icons.get('search_folder:', None) is None: self.category_custom_icons['search_folder:'] = QIcon.ic('folder_saved_search') last_category_node = None category_node_map = {} self.user_category_node_tree = {} # We build the node tree including categories that might later not be # displayed because their items might be in User categories. The resulting # nodes will be reordered later. for i, key in enumerate(self.categories): is_gst = False if key.startswith('@') and key[1:] in gst: tt = _('The grouped search term name is "{0}"').format(key) is_gst = True elif key == 'news': tt = '' else: cust_desc = '' fm = self.db.field_metadata[key] if fm['is_custom']: cust_desc = fm['display'].get('description', '') if cust_desc: cust_desc = '\n' + _('Description:') + ' ' + cust_desc tt = _('The lookup/search name is "{0}"{1}').format(key, cust_desc) if self.category_custom_icons.get(key, None) is None: self.category_custom_icons[key] = QIcon.ic( category_icon_map['gst'] if is_gst else category_icon_map.get( key, (category_icon_map['user:'] if key.startswith('@') else category_icon_map['custom:']))) if key.startswith('@'): path_parts = [p for p in key.split('.')] path = '' last_category_node = self.root_item tree_root = self.user_category_node_tree for i,p in enumerate(path_parts): path += p if path not in category_node_map: node = self.create_node(parent=last_category_node, data=p[1:] if i == 0 else p, is_category=True, is_gst=is_gst, tooltip=tt if path == key else path, category_key=path, icon_map=self.icon_state_map) last_category_node = node category_node_map[path] = node self.category_nodes.append(node) node.can_be_edited = (not is_gst) and (i == (len(path_parts)-1)) if not is_gst: node.tag.is_hierarchical = '5state' tree_root[p] = {} tree_root = tree_root[p] else: last_category_node = category_node_map[path] tree_root = tree_root[p] path += '.' else: node = self.create_node(parent=self.root_item, data=self.categories[key], is_category=True, is_gst=False, tooltip=tt, category_key=key, icon_map=self.icon_state_map) category_node_map[key] = node last_category_node = node self.category_nodes.append(node) self._create_node_tree(data, state_map) def _create_node_tree(self, data, state_map): sort_by = config['sort_tags_by'] eval_formatter = EvalFormatter() intermediate_nodes = {} if data is None: print('_create_node_tree: no data!') traceback.print_stack() return collapse = self.prefs['tags_browser_collapse_at'] collapse_model = self.collapse_model if collapse == 0: collapse_model = 'disable' elif collapse_model != 'disable': if sort_by == 'name': collapse_template = tweaks['categories_collapsed_name_template'] elif sort_by == 'rating': collapse_model = 'partition' collapse_template = tweaks['categories_collapsed_rating_template'] else: collapse_model = 'partition' collapse_template = tweaks['categories_collapsed_popularity_template'] def get_name_components(name): components = [t.strip() for t in name.split('.') if t.strip()] if len(components) == 0 or '.'.join(components) != name: components = [name] return components def process_one_node(category, collapse_model, book_rating_map, state_map): # {{{ collapse_letter = None key = category.category_key is_gst = category.is_gst if key not in data: return # Use old pref if new one doesn't exist if key in self.db.prefs.get('tag_browser_dont_collapse', self.prefs['tag_browser_dont_collapse']): collapse_model = 'disable' cat_len = len(data[key]) if cat_len <= 0: return category_child_map = {} fm = self.db.field_metadata[key] clear_rating = True if key not in self.categories_with_ratings and \ not fm['is_custom'] and \ not fm['kind'] == 'user' \ else False in_uc = fm['kind'] == 'user' and not is_gst tt = key if in_uc else None if collapse_model == 'first letter': # Build a list of 'equal' first letters by noticing changes # in ICU's 'ordinal' for the first letter. In this case, the # first letter can actually be more than one letter long. fl_collapse_when = self.prefs['tags_browser_collapse_fl_at'] fl_collapse = True if fl_collapse_when > 1 else False intervals = [] cl_list = [None] * len(data[key]) last_ordnum = 0 last_c = ' ' last_idx = 0 for idx,tag in enumerate(data[key]): # Deal with items that don't have sorts, such as formats t = tag.sort if tag.sort else tag.name c = icu_upper(t) if t else ' ' ordnum, ordlen = collation_order_for_partitioning(c) if last_ordnum != ordnum: if fl_collapse and idx > 0: intervals.append(FL_Interval(last_c, last_c, idx-last_idx)) last_idx = idx last_c = c[0:ordlen] last_ordnum = ordnum cl_list[idx] = last_c if fl_collapse: intervals.append(FL_Interval(last_c, last_c, len(cl_list)-last_idx)) # Combine together first letter categories that are smaller # than the specified option. We choose which item to combine # by the size of the items before and after, privileging making # smaller categories. Loop through the intervals doing the combine # until nothing changes. Multiple iterations are required because # we might need to combine categories that are already combined. fl_intervals_changed = True null_interval = FL_Interval('', '', 100000000) while fl_intervals_changed and len(intervals) > 1: fl_intervals_changed = False for idx,interval in enumerate(intervals): if interval.length >= fl_collapse_when: continue prev = next_ = null_interval if idx == 0: next_ = intervals[idx+1] else: prev = intervals[idx-1] if idx < len(intervals) - 1: next_ = intervals[idx+1] if prev.length < next_.length: intervals[idx-1] = FL_Interval(prev.first_chr, interval.last_chr, prev.length + interval.length) else: intervals[idx+1] = FL_Interval(interval.first_chr, next_.last_chr, next_.length + interval.length) del intervals[idx] fl_intervals_changed = True break # Now correct the first letter list, entering either the letter # or the range for each item in the category. If we ended up # with only one 'first letter' category then don't combine # letters and revert to basic 'by first letter' if len(intervals) > 1: cur_idx = 0 for interval in intervals: first_chr, last_chr, length = interval for i in range(0, length): if first_chr == last_chr: cl_list[cur_idx] = first_chr else: cl_list[cur_idx] = f'{first_chr} - {last_chr}' cur_idx += 1 top_level_component = 'z' + data[key][0].original_name last_idx = -collapse category_is_hierarchical = self.is_key_a_hierarchical_category(key) for idx,tag in enumerate(data[key]): components = None if clear_rating: tag.avg_rating = None tag.state = state_map.get((tag.name, tag.category), 0) if collapse_model != 'disable' and cat_len > collapse: if collapse_model == 'partition': # Only partition at the top level. This means that we must # not do a break until the outermost component changes. if idx >= last_idx + collapse and \ not tag.original_name.startswith(top_level_component+'.'): if cat_len > idx + collapse: last = idx + collapse - 1 else: last = cat_len - 1 if category_is_hierarchical: ct = copy.copy(data[key][last]) components = get_name_components(ct.original_name) ct.sort = ct.name = components[0] d = {'last': ct} # Do the first node after the last node so that # the components array contains the right values # to be used later ct2 = copy.copy(tag) components = get_name_components(ct2.original_name) ct2.sort = ct2.name = components[0] d['first'] = ct2 else: d = {'first': tag} # Some nodes like formats and identifiers don't # have sort set. Fix that so the template will work if d['first'].sort is None: d['first'].sort = tag.name d['last'] = data[key][last] if d['last'].sort is None: d['last'].sort = data[key][last].name name = eval_formatter.safe_format(collapse_template, d, '##TAG_VIEW##', None) if name.startswith('##TAG_VIEW##'): # Formatter threw an exception. Don't create subnode node_parent = sub_cat = category else: sub_cat = self.create_node(parent=category, data=name, tooltip=None, temporary=True, is_category=True, is_gst=is_gst, category_key=category.category_key, icon_map=self.icon_state_map) sub_cat.tag.is_searchable = False node_parent = sub_cat last_idx = idx # remember where we last partitioned else: node_parent = sub_cat else: # by 'first letter' cl = cl_list[idx] if cl != collapse_letter: collapse_letter = cl sub_cat = self.create_node(parent=category, data=collapse_letter, is_category=True, is_gst=is_gst, tooltip=None, temporary=True, category_key=category.category_key, icon_map=self.icon_state_map) node_parent = sub_cat else: node_parent = category # category display order is important here. The following works # only if all the non-User categories are displayed before the # User categories if category_is_hierarchical or tag.is_hierarchical: components = get_name_components(tag.original_name) else: components = [tag.original_name] if (not tag.is_hierarchical) and (in_uc or (fm['is_custom'] and fm['display'].get('is_names', False)) or not category_is_hierarchical or len(components) == 1): n = self.create_node(parent=node_parent, data=tag, tooltip=tt, is_gst=is_gst, icon_map=self.icon_state_map) category_child_map[tag.name, tag.category] = n else: child_key = key if is_gst else tag.category for i,comp in enumerate(components): if i == 0: child_map = category_child_map top_level_component = comp else: child_map = {(t.tag.name, key if is_gst else t.tag.category): t for t in node_parent.children if t.type != TagTreeItem.CATEGORY} if (comp,child_key) in child_map: node_parent = child_map[(comp,child_key)] t = node_parent.tag t.is_hierarchical = '5state' if tag.category != 'search' else '3state' if tag.id_set is not None and t.id_set is not None: t.id_set = t.id_set | tag.id_set intermediate_nodes[t.original_name,child_key] = t else: if i < len(components)-1: original_name = '.'.join(components[:i+1]) t = intermediate_nodes.get((original_name, child_key), None) if t is None: t = copy.copy(tag) t.original_name = original_name t.count = 0 if key != 'search': # This 'manufactured' intermediate node can # be searched, but cannot be edited. t.is_editable = False else: t.is_searchable = t.is_editable = False t.search_expression = None intermediate_nodes[original_name,child_key] = t else: t = tag if not in_uc: t.original_name = t.name intermediate_nodes[t.original_name,child_key] = t t.is_hierarchical = \ '5state' if t.category != 'search' else '3state' t.name = comp node_parent = self.create_node(parent=node_parent, data=t, is_gst=is_gst, tooltip=tt, icon_map=self.icon_state_map) child_map[(comp, child_key)] = node_parent # Correct the average rating for the node total = count = 0 for book_id in t.id_set: rating = book_rating_map.get(book_id, 0) if rating: total += rating/2.0 count += 1 node_parent.cached_average_rating = float(total)/count if total and count else 0 return # }}} # Build the entire node tree. Note that category_nodes is in field # metadata order so the User categories will be at the end with self.db.new_api.safe_read_lock: # needed as we read from book_value_map for category in self.category_nodes: process_one_node(category, collapse_model, self.db.new_api.fields['rating'].book_value_map, state_map.get(category.category_key, {})) # Fix up the node tree, reordering as needed and deleting undisplayed # nodes. First, remove empty user category subnodes if needed. This is a # recursive process because the hierarchical categories were combined # together in process_one_node (above), which also computes the child # count. if self.prefs['tag_browser_hide_empty_categories']: def process_uc_children(parent, depth): new_children = [] for node in parent.children: if node.type == TagTreeItem.CATEGORY: # I could De Morgan's this but I think it is more # understandable this way if node.category_key.startswith('@') and len(node.children) == 0: pass else: new_children.append(node) process_uc_children(node, depth+1) else: new_children.append(node) parent.children = new_children for node in self.root_item.children: if node.category_key.startswith('@'): process_uc_children(node, 1) # Now check the standard categories and root-level user categories, # removing any hidden categories and if needed, empty categories new_children = [] for node in self.root_item.children: if self.prefs['tag_browser_hide_empty_categories'] and len(node.child_tags()) == 0: continue key = node.category_key if key in self.row_map: if self.hidden_categories: if key in self.hidden_categories: continue found = False for cat in self.hidden_categories: if cat.startswith('@') and key.startswith(cat + '.'): found = True if found: continue new_children.append(node) self.root_item.children = new_children self.root_item.children.sort(key=lambda x: self.row_map.index(x.category_key)) if self.set_in_tag_browser(): self.research_required.emit() def set_in_tag_browser(self): # If the filter isn't set then don't build the list, improving # performance significantly for large libraries or libraries with lots # of categories. This means that in_tag_browser:true with no filter will # return all books. This is incorrect in the rare case where the # category list in the tag browser doesn't contain a category like # authors that by definition matches all books because all books have an # author. If really needed the user can work around this 'error' by # clicking on the categories of interest with the connector set to 'or'. if self.filter_categories_by: id_set = set() for x in (a for a in self.root_item.children if a.category_key != 'search' and not a.is_gst): for t in x.child_tags(): id_set |= t.tag.id_set else: id_set = None changed = self.db.data.get_in_tag_browser() != id_set self.db.data.set_in_tag_browser(id_set) return changed def get_category_editor_data(self, category): for cat in self.root_item.children: if cat.category_key == category: return [(t.tag.id, t.tag.original_name, t.tag.count) for t in cat.child_tags() if t.tag.count > 0] def is_in_user_category(self, index): if not index.isValid(): return False p = self.get_node(index) while p.type != TagTreeItem.CATEGORY: p = p.parent return p.tag.category.startswith('@') def is_key_a_hierarchical_category(self, key): result = self.hierarchical_categories.get(key) if result is None: result = not ( key in ['authors', 'publisher', 'news', 'formats', 'rating'] or key not in self.db.new_api.pref('categories_using_hierarchy', []) or config['sort_tags_by'] != 'name') self.hierarchical_categories[key] = result return result def is_index_on_a_hierarchical_category(self, index): if not index.isValid(): return False p = self.get_node(index) return self.is_key_a_hierarchical_category(p.tag.category) # Drag'n Drop {{{ def mimeTypes(self): return ["application/calibre+from_library", 'application/calibre+from_tag_browser'] def mimeData(self, indexes): data = [] for idx in indexes: if idx.isValid(): # get some useful serializable data node = self.get_node(idx) path = self.path_for_index(idx) if node.type == TagTreeItem.CATEGORY: d = (node.type, node.py_name, node.category_key) else: t = node.tag p = node while p.type != TagTreeItem.CATEGORY: p = p.parent d = (node.type, p.category_key, p.is_gst, t.original_name, t.category, path) data.append(d) else: data.append(None) raw = bytearray(json_dumps(data)) ans = QMimeData() ans.setData('application/calibre+from_tag_browser', raw) return ans def dropMimeData(self, md, action, row, column, parent): fmts = {str(x) for x in md.formats()} if not fmts.intersection(set(self.mimeTypes())): return False if "application/calibre+from_library" in fmts: if action != Qt.DropAction.CopyAction: return False return self.do_drop_from_library(md, action, row, column, parent) elif 'application/calibre+from_tag_browser' in fmts: return self.do_drop_from_tag_browser(md, action, row, column, parent) def do_drop_from_tag_browser(self, md, action, row, column, parent): if not parent.isValid(): return False dest = self.get_node(parent) if not md.hasFormat('application/calibre+from_tag_browser'): return False data = bytes(md.data('application/calibre+from_tag_browser')) src = json_loads(data) if len(src) == 1: # Check to see if this is a hierarchical rename s = src[0] # This check works for both hierarchical and user categories. # We can drag only tag items. if s[0] != TagTreeItem.TAG: return False src_index = self.index_for_path(s[5]) if src_index == parent: # dropped on itself return False src_item = self.get_node(src_index) dest_item = parent.data(Qt.ItemDataRole.UserRole) # Here we do the real work. If src is a tag, src == dest, and src # is hierarchical then we can do a rename. if (src_item.type == TagTreeItem.TAG and src_item.tag.category == dest_item.tag.category and self.is_key_a_hierarchical_category(src_item.tag.category)): key = s[1] # work out the part of the source name to use in the rename # It isn't necessarily a simple name but might be the remaining # levels of the hierarchy part = src_item.tag.original_name.rpartition('.') src_simple_name = part[2] # work out the new prefix, the destination node name if dest.type == TagTreeItem.TAG: new_name = dest_item.tag.original_name + '.' + src_simple_name else: new_name = src_simple_name if self.get_in_vl(): src_item.use_vl = rename_only_in_vl_question(self.gui_parent) else: src_item.use_vl = False self.rename_item(src_item, key, new_name) return True # Should be working with a user category if dest.type != TagTreeItem.CATEGORY: return False return self.move_or_copy_item_to_user_category(src, dest, action) def move_or_copy_item_to_user_category(self, src, dest, action): ''' src is a list of tuples representing items to copy. The tuple is (type, containing category key, category key is global search term, full name, category key, path to node) The type must be TagTreeItem.TAG dest is the TagTreeItem node to receive the items action is Qt.DropAction.CopyAction or Qt.DropAction.MoveAction ''' def process_source_node(user_cats, src_parent, src_parent_is_gst, is_uc, dest_key, idx): ''' Copy/move an item and all its children to the destination ''' copied = False src_name = idx.tag.original_name src_cat = idx.tag.category # delete the item if the source is a User category and action is move if is_uc and not src_parent_is_gst and src_parent in user_cats and \ action == Qt.DropAction.MoveAction: new_cat = [] for tup in user_cats[src_parent]: if src_name == tup[0] and src_cat == tup[1]: continue new_cat.append(list(tup)) user_cats[src_parent] = new_cat else: copied = True # Now add the item to the destination User category add_it = True if not is_uc and src_cat == 'news': src_cat = 'tags' for tup in user_cats[dest_key]: if src_name == tup[0] and src_cat == tup[1]: add_it = False if add_it: user_cats[dest_key].append([src_name, src_cat, 0]) for c in idx.children: copied = process_source_node(user_cats, src_parent, src_parent_is_gst, is_uc, dest_key, c) return copied user_cats = self.db.new_api.pref('user_categories', {}) path = None for s in src: src_parent, src_parent_is_gst = s[1:3] path = s[5] if src_parent.startswith('@'): is_uc = True src_parent = src_parent[1:] else: is_uc = False dest_key = dest.category_key[1:] if dest_key not in user_cats: continue idx = self.index_for_path(path) if idx.isValid(): process_source_node(user_cats, src_parent, src_parent_is_gst, is_uc, dest_key, self.get_node(idx)) self.db.new_api.set_pref('user_categories', user_cats) self.refresh_required.emit() self.user_category_added.emit() return True def do_drop_from_library(self, md, action, row, column, parent): idx = parent if idx.isValid(): node = self.data(idx, Qt.ItemDataRole.UserRole) if node.type == TagTreeItem.TAG: fm = self.db.metadata_for_field(node.tag.category) if node.tag.category in \ ('tags', 'series', 'authors', 'rating', 'publisher', 'languages', 'formats') or \ (fm['is_custom'] and ( fm['datatype'] in ['text', 'rating', 'series', 'enumeration'] or ( fm['datatype'] == 'composite' and fm['display'].get('make_category', False)))): mime = 'application/calibre+from_library' ids = list(map(int, md.data(mime).data().split())) self.handle_drop(node, ids) return True elif node.type == TagTreeItem.CATEGORY: fm_dest = self.db.metadata_for_field(node.category_key) if fm_dest['kind'] == 'user': fm_src = self.db.metadata_for_field(md.column_name) if md.column_name in ['authors', 'publisher', 'series'] or \ (fm_src['is_custom'] and ( fm_src['datatype'] in ['series', 'text', 'enumeration'] and not fm_src['is_multiple'])or (fm_src['datatype'] == 'composite' and fm_src['display'].get('make_category', False))): mime = 'application/calibre+from_library' ids = list(map(int, md.data(mime).data().split())) self.handle_user_category_drop(node, ids, md.column_name) return True return False def handle_user_category_drop(self, on_node, ids, column): categories = self.db.new_api.pref('user_categories', {}) cat_contents = categories.get(on_node.category_key[1:], None) if cat_contents is None: return cat_contents = {(v, c) for v,c,ign in cat_contents} fm_src = self.db.metadata_for_field(column) label = fm_src['label'] for id in ids: if not fm_src['is_custom']: if label == 'authors': value = self.db.authors(id, index_is_id=True) value = [v.replace('|', ',') for v in value.split(',')] elif label == 'publisher': value = self.db.publisher(id, index_is_id=True) elif label == 'series': value = self.db.series(id, index_is_id=True) else: if fm_src['datatype'] != 'composite': value = self.db.get_custom(id, label=label, index_is_id=True) else: value = self.db.get_property(id, loc=fm_src['rec_index'], index_is_id=True) if value: if not isinstance(value, list): value = [value] cat_contents |= {(v, column) for v in value} categories[on_node.category_key[1:]] = [[v, c, 0] for v,c in cat_contents] self.db.new_api.set_pref('user_categories', categories) self.refresh_required.emit() self.user_category_added.emit() def handle_drop_on_format(self, fmt, book_ids): self.convert_requested.emit(book_ids, fmt) def handle_drop(self, on_node, ids): # print 'Dropped ids:', ids, on_node.tag key = on_node.tag.category if key == 'formats': self.handle_drop_on_format(on_node.tag.name, ids) return if (key == 'authors' and len(ids) >= 5): if not confirm('<p>'+_('Changing the authors for several books can ' 'take a while. Are you sure?') + '</p>', 'tag_browser_drop_authors', self.gui_parent): return elif len(ids) > 15: if not confirm('<p>'+_('Changing the metadata for that many books ' 'can take a while. Are you sure?') + '</p>', 'tag_browser_many_changes', self.gui_parent): return fm = self.db.metadata_for_field(key) is_multiple = fm['is_multiple'] val = on_node.tag.original_name for id in ids: mi = self.db.get_metadata(id, index_is_id=True) # Prepare to ignore the author, unless it is changed. Title is # always ignored -- see the call to set_metadata set_authors = False # Author_sort cannot change explicitly. Changing the author might # change it. mi.author_sort = None # Never will change by itself. if key == 'authors': mi.authors = [val] set_authors=True elif fm['datatype'] == 'rating': mi.set(key, len(val) * 2) elif fm['datatype'] == 'series': series_index = self.db.new_api.get_next_series_num_for(val, field=key) if fm['is_custom']: mi.set(key, val, extra=series_index) else: mi.series, mi.series_index = val, series_index elif is_multiple: new_val = mi.get(key, []) if val in new_val: # Fortunately, only one field can change, so the continue # won't break anything continue new_val.append(val) mi.set(key, new_val) else: mi.set(key, val) self.db.set_metadata(id, mi, set_title=False, set_authors=set_authors, commit=False) self.db.commit() self.drag_drop_finished.emit(ids) # }}} def get_in_vl(self): return self.db.data.get_base_restriction() or self.db.data.get_search_restriction() def get_book_ids_to_use(self): if self.db.data.get_base_restriction() or self.db.data.get_search_restriction(): return self.db.search('', return_matches=True, sort_results=False) return None def get_ordered_categories(self, use_defaults=False, pref_data_override=None): if use_defaults: tbo = [] elif pref_data_override: tbo = [k for k,_ in pref_data_override] else: tbo = self.db.new_api.pref('tag_browser_category_order', []) return category_display_order(tbo, list(self.categories.keys())) def _get_category_nodes(self, sort): ''' Called by __init__. Do not directly call this method. ''' self.row_map = [] self.categories = OrderedDict() # Get the categories try: # We must disable the in_tag_browser ids because we want all the # categories that will be filtered later. They might be restricted # by a VL or extra restriction. old_in_tb = self.db.data.get_in_tag_browser() self.db.data.set_in_tag_browser(None) data = self.db.new_api.get_categories(sort=sort, book_ids=self.get_book_ids_to_use(), first_letter_sort=self.collapse_model == 'first letter') self.db.data.set_in_tag_browser(old_in_tb) except Exception as e: traceback.print_exc() data = self.db.new_api.get_categories(sort=sort, first_letter_sort=self.collapse_model == 'first letter') self.restriction_error.emit(str(e)) if self.filter_categories_by: if self.filter_categories_by.startswith('='): use_exact_match = True filter_by = self.filter_categories_by[1:] else: use_exact_match = False filter_by = self.filter_categories_by if prefs['use_primary_find_in_search']: def final_equals(x, y): return primary_strcmp(x, y) == 0 def final_contains(x, y): return primary_contains(x, y) else: def final_equals(x, y): return strcmp(x, y) == 0 def final_contains(filt, txt): return contains(filt, icu_lower(txt)) for category in data.keys(): if use_exact_match: data[category] = [t for t in data[category] if final_equals(t.name, filter_by)] else: data[category] = [t for t in data[category] if final_contains(filter_by, t.name)] # Build a dict of the keys that have data. # Always add user categories so that the constructed hierarchy works. # This means that empty categories will be displayed unless the 'hide # empty categories' box is checked. tb_categories = self.db.field_metadata for category in tb_categories: if category in data or category.startswith('@'): self.categories[category] = tb_categories[category]['name'] # Now build the list of fields in display order. A lot of this is to # maintain compatibility with the tweaks. order_pref = self.db.new_api.pref('tag_browser_category_order', None) if order_pref is not None: # Keys are in order self.row_map = self.get_ordered_categories() else: order = tweaks.get('tag_browser_category_default_sort', 'default') self.row_map = list(self.categories.keys()) if order not in ('default', 'display_name', 'lookup_name'): print('Tweak tag_browser_category_default_sort is not valid. Ignored') order = 'default' if order != 'default': def key_func(val): if order == 'display_name': return icu_lower(self.db.field_metadata[val]['name']) return icu_lower(val[1:] if val.startswith('#') or val.startswith('@') else val) direction = tweaks.get('tag_browser_category_default_sort_direction', 'ascending') if direction not in ('ascending', 'descending'): print('Tweak tag_browser_category_default_sort_direction is not valid. Ignored') direction = 'ascending' self.row_map.sort(key=key_func, reverse=direction == 'descending') try: order = tweaks.get('tag_browser_category_order', {'*':1}) if not isinstance(order, dict): raise TypeError() except: print('Tweak tag_browser_category_order is not valid. Ignored') order = {'*': 1000} defvalue = order.get('*', 1000) self.row_map.sort(key=lambda x: order.get(x, defvalue)) # Migrate the tweak to the new pref. First, make sure the order is valid self.row_map = self.get_ordered_categories(pref_data_override=[[k,None] for k in self.row_map]) self.db.new_api.set_pref('tag_browser_category_order', self.row_map) return data def set_categories_filter(self, txt): if txt: self.filter_categories_by = icu_lower(txt) else: self.filter_categories_by = None def get_categories_filter(self): return self.filter_categories_by def refresh(self, data=None): ''' Here to trap usages of refresh in the old architecture. Can eventually be removed. ''' print('TagsModel: refresh called!') traceback.print_stack() return False def create_node(self, *args, **kwargs): node = TagTreeItem(*args, **kwargs) self.node_map[id(node)] = node node.category_custom_icons = self.category_custom_icons return node def get_node(self, idx): ans = self.node_map.get(idx.internalId(), self.root_item) return ans def createIndex(self, row, column, internal_pointer=None): idx = QAbstractItemModel.createIndex(self, row, column, id(internal_pointer)) return idx def category_row_map(self): return {category.category_key:row for row, category in enumerate(self.root_item.children)} def index_for_category(self, name): for row, category in enumerate(self.root_item.children): if category.category_key == name: return self.index(row, 0, QModelIndex()) def columnCount(self, parent): return 1 def data(self, index, role): if not index.isValid(): return None item = self.get_node(index) return item.data(role) def setData(self, index, value, role=Qt.ItemDataRole.EditRole): if not index.isValid(): return False # set up to reposition at the same item. We can do this except if # working with the last item and that item is deleted, in which case # we position at the parent label val = str(value or '').strip() if not val: return self.show_error_after_event_loop_tick(_('Item is blank'), _('An item cannot be set to nothing. Delete it instead.')) item = self.get_node(index) if item.type == TagTreeItem.CATEGORY and item.category_key.startswith('@'): if val.find('.') >= 0: return self.show_error_after_event_loop_tick(_('Rename User category'), _('You cannot use periods in the name when ' 'renaming User categories')) user_cats = self.db.new_api.pref('user_categories', {}) user_cat_keys_lower = [icu_lower(k) for k in user_cats] ckey = item.category_key[1:] ckey_lower = icu_lower(ckey) dotpos = ckey.rfind('.') if dotpos < 0: nkey = val else: nkey = ckey[:dotpos+1] + val nkey_lower = icu_lower(nkey) if ckey == nkey: self.use_position_based_index_on_next_recount = True return True for c in sorted(list(user_cats.keys()), key=sort_key): if icu_lower(c).startswith(ckey_lower): if len(c) == len(ckey): if strcmp(ckey, nkey) != 0 and \ nkey_lower in user_cat_keys_lower: return self.show_error_after_event_loop_tick(_('Rename User category'), _('The name %s is already used')%nkey) user_cats[nkey] = user_cats[ckey] self.rename_user_category_icon('@' + c, '@' + nkey) del user_cats[ckey] elif c[len(ckey)] == '.': rest = c[len(ckey):] if strcmp(ckey, nkey) != 0 and \ icu_lower(nkey + rest) in user_cat_keys_lower: return self.show_error_after_event_loop_tick(_('Rename User category'), _('The name %s is already used')%(nkey + rest)) user_cats[nkey + rest] = user_cats[ckey + rest] self.rename_user_category_icon('@' + ckey + rest, '@' + nkey + rest) del user_cats[ckey + rest] self.user_categories_edited.emit(user_cats, nkey) # Does a refresh self.use_position_based_index_on_next_recount = True return True key = item.tag.category # make certain we know about the item's category if key not in self.db.field_metadata: return False if key == 'authors': if val.find('&') >= 0: return self.show_error_after_event_loop_tick(_('Invalid author name'), _('Author names cannot contain & characters.')) return False if key == 'search': if val == str(item.data(role) or ''): return True if val in self.db.saved_search_names(): return self.show_error_after_event_loop_tick( _('Duplicate search name'), _('The saved search name %s is already used.')%val) self.use_position_based_index_on_next_recount = True self.db.saved_search_rename(str(item.data(role) or ''), val) item.tag.name = val self.search_item_renamed.emit() # Does a refresh else: self.rename_item(item, key, val) return True def show_error_after_event_loop_tick(self, title, msg, det_msg=''): self.show_error_after_event_loop_tick_signal.emit(title, msg, det_msg) return False def on_show_error_after_event_loop_tick(self, title, msg, details): error_dialog(self.gui_parent, title, msg, det_msg=details, show=True) def rename_item(self, item, key, to_what): def do_one_item(lookup_key, an_item, original_name, new_name, restrict_to_books): self.use_position_based_index_on_next_recount = True self.db.new_api.rename_items(lookup_key, {an_item.tag.id: new_name}, restrict_to_book_ids=restrict_to_books) self.tag_item_renamed.emit() an_item.tag.name = new_name an_item.tag.state = TAG_SEARCH_STATES['clear'] self.use_position_based_index_on_next_recount = True self.add_renamed_item_to_user_categories(lookup_key, original_name, new_name) children = item.all_children() restrict_to_book_ids=self.get_book_ids_to_use() if item.use_vl else None if item.tag.is_editable and len(children) == 0: # Leaf node, just do it. do_one_item(key, item, item.tag.original_name, to_what, restrict_to_book_ids) else: # Middle node of a hierarchy search_name = item.tag.original_name # Clear any search icons on the original tag if item.parent.type == TagTreeItem.TAG: item.parent.tag.state = TAG_SEARCH_STATES['clear'] # It might also be a leaf if item.tag.is_editable: do_one_item(key, item, item.tag.original_name, to_what, restrict_to_book_ids) # Now do the children for child_item in children: from calibre.utils.icu import startswith if (child_item.tag.is_editable and startswith(child_item.tag.original_name, search_name)): new_name = to_what + child_item.tag.original_name[len(search_name):] do_one_item(key, child_item, child_item.tag.original_name, new_name, restrict_to_book_ids) self.clean_items_from_user_categories() self.refresh_required.emit() def rename_item_in_all_user_categories(self, item_name, item_category, new_name): ''' Search all User categories for items named item_name with category item_category and rename them to new_name. The caller must arrange to redisplay the tree as appropriate. ''' user_cats = self.db.new_api.pref('user_categories', {}) for k in user_cats.keys(): ucat = {n:c for n,c,_ in user_cats[k]} # Check if the new name with the same category already exists. If # so, remove the old name because it would be a duplicate. This can # happen if two items in the item_category were renamed to the same # name. if ucat.get(new_name, None) == item_category: if ucat.pop(item_name, None) is not None: # Only update the user_cats when something changes user_cats[k] = list([(n, c, 0) for n, c in ucat.items()]) elif ucat.get(item_name, None) == item_category: # If the old name/item_category exists, rename it to the new # name using del/add del ucat[item_name] ucat[new_name] = item_category user_cats[k] = list([(n, c, 0) for n, c in ucat.items()]) self.db.new_api.set_pref('user_categories', user_cats) def delete_item_from_all_user_categories(self, item_name, item_category): ''' Search all User categories for items named item_name with category item_category and delete them. The caller must arrange to redisplay the tree as appropriate. ''' user_cats = self.db.new_api.pref('user_categories', {}) for cat in user_cats.keys(): self.delete_item_from_user_category(cat, item_name, item_category, user_categories=user_cats) self.db.new_api.set_pref('user_categories', user_cats) def delete_item_from_user_category(self, category, item_name, item_category, user_categories=None): if user_categories is not None: user_cats = user_categories else: user_cats = self.db.new_api.pref('user_categories', {}) new_contents = [] for tup in user_cats[category]: if tup[0] != item_name or tup[1] != item_category: new_contents.append(tup) user_cats[category] = new_contents if user_categories is None: self.db.new_api.set_pref('user_categories', user_cats) def add_renamed_item_to_user_categories(self, lookup_key, original_name, new_name): ''' Add new_name to any user category that contains original name if new_name isn't already there. The original name isn't deleted. This is the first step when renaming user categories that might be in virtual libraries because when finished both names may still exist. You should call clean_items_from_user_categories() when done to remove any keys that no longer exist from all user categories. The caller must arrange to redisplay the tree as appropriate. ''' user_cats = self.db.new_api.pref('user_categories', {}) for cat in user_cats.keys(): found_original = False found_new = False for name,key,_ in user_cats[cat]: if key == lookup_key: if name == original_name: found_original = True if name == new_name: found_new = True if found_original and not found_new: user_cats[cat].append([new_name, lookup_key, 0]) self.db.new_api.set_pref('user_categories', user_cats) def clean_items_from_user_categories(self): ''' Remove any items that no longer exist from user categories. This can happen when renaming items in virtual libraries, where sometimes the old name still exists on some book not in the VL and sometimes it doesn't. The caller must arrange to redisplay the tree as appropriate. ''' user_cats = self.db.new_api.pref('user_categories', {}) cache = self.db.new_api all_cats = {} for cat in user_cats.keys(): new_cat = [] for val, key, _ in user_cats[cat]: datatype = cache.field_metadata.get(key, {}).get('datatype', '*****') if datatype != 'composite': id_ = cache.get_item_id(key, val, case_sensitive=True) if id_ is not None: v = cache.books_for_field(key, id_) if v: new_cat.append([val, key, 0]) if new_cat: all_cats[cat] = new_cat self.db.new_api.set_pref('user_categories', all_cats) def headerData(self, *args): return None def flags(self, index, *args): ans = Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsEditable if index.isValid(): node = self.data(index, Qt.ItemDataRole.UserRole) if node.type == TagTreeItem.TAG: tag = node.tag category = tag.category if (tag.is_editable or tag.is_hierarchical) and category != 'search': ans |= Qt.ItemFlag.ItemIsDragEnabled fm = self.db.metadata_for_field(category) if category in \ ('tags', 'series', 'authors', 'rating', 'publisher', 'languages', 'formats') or \ (fm['is_custom'] and fm['datatype'] in ['text', 'rating', 'series', 'enumeration']): ans |= Qt.ItemFlag.ItemIsDropEnabled else: if node.type != TagTreeItem.CATEGORY or node.category_key != 'formats': ans |= Qt.ItemFlag.ItemIsDropEnabled return ans def supportedDropActions(self): return Qt.DropAction.CopyAction|Qt.DropAction.MoveAction def named_path_for_index(self, index): ans = [] while index.isValid(): node = self.get_node(index) if node is self.root_item: break ans.append(node.name_id) index = self.parent(index) return ans def index_for_named_path(self, named_path): parent = self.root_item ipath = [] path = named_path[:] while path: q = path.pop() for i, c in enumerate(parent.children): if c.name_id == q: ipath.append(i) parent = c break else: break return self.index_for_path(ipath) def path_for_index(self, index): ans = [] while index.isValid(): ans.append(index.row()) index = self.parent(index) ans.reverse() return ans def index_for_path(self, path): parent = QModelIndex() for idx,v in enumerate(path): tparent = self.index(v, 0, parent) if not tparent.isValid(): if v > 0 and idx == len(path) - 1: # Probably the last item went away. Use the one before it tparent = self.index(v-1, 0, parent) if not tparent.isValid(): # Not valid. Use the last valid index break else: # There isn't one before it. Use the last valid index break parent = tparent return parent def index(self, row, column, parent): if not self.hasIndex(row, column, parent): return QModelIndex() if not parent.isValid(): parent_item = self.root_item else: parent_item = self.get_node(parent) try: child_item = parent_item.children[row] except IndexError: return QModelIndex() ans = self.createIndex(row, column, child_item) return ans def parent(self, index): if not index.isValid(): return QModelIndex() child_item = self.get_node(index) parent_item = getattr(child_item, 'parent', None) if parent_item is self.root_item or parent_item is None: return QModelIndex() ans = self.createIndex(parent_item.row(), 0, parent_item) if not ans.isValid(): return QModelIndex() return ans def rowCount(self, parent): if parent.column() > 0: return 0 if not parent.isValid(): parent_item = self.root_item else: parent_item = self.get_node(parent) return len(parent_item.children) def reset_all_states(self, except_=None): update_list = [] def process_tag(tag_item): tag = tag_item.tag if tag is except_: tag_index = self.createIndex(tag_item.row(), 0, tag_item) self.dataChanged.emit(tag_index, tag_index) elif tag.state != 0 or tag in update_list: tag_index = self.createIndex(tag_item.row(), 0, tag_item) tag.state = 0 update_list.append(tag) self.dataChanged.emit(tag_index, tag_index) for t in tag_item.children: process_tag(t) for t in self.root_item.children: process_tag(t) def clear_state(self): self.reset_all_states() def toggle(self, index, exclusive, set_to=None): ''' exclusive: clear all states before applying this one set_to: None => advance the state, otherwise a value from TAG_SEARCH_STATES ''' if not index.isValid(): return False item = self.get_node(index) tag = item.tag if tag.category == 'search' and tag.search_expression is None: return False item.toggle(set_to=set_to) if exclusive: self.reset_all_states(except_=item.tag) self.dataChanged.emit(index, index) return True def tokens(self): ans = [] # Tags can be in the news and the tags categories. However, because of # the desire to use two different icons (tags and news), the nodes are # not shared, which can lead to the possibility of searching twice for # the same tag. The tags_seen set helps us prevent that tags_seen = set() # Tag nodes are in their own category and possibly in User categories. # They will be 'checked' in both places, but we want to put the node # into the search string only once. The nodes_seen set helps us do that nodes_seen = set() stars = rating_to_stars(3, True) node_searches = {TAG_SEARCH_STATES['mark_plus'] : 'true', TAG_SEARCH_STATES['mark_plusplus'] : '.true', TAG_SEARCH_STATES['mark_minus'] : 'false', TAG_SEARCH_STATES['mark_minusminus'] : '.false'} for node in self.category_nodes: if node.tag.state: if node.category_key == "news": if node_searches[node.tag.state] == 'true': ans.append('tags:"=' + _('News') + '"') else: ans.append('( not tags:"=' + _('News') + '")') else: ans.append('%s:%s'%(node.category_key, node_searches[node.tag.state])) key = node.category_key for tag_item in node.all_children(): if tag_item.type == TagTreeItem.CATEGORY: if self.collapse_model == 'first letter' and \ tag_item.temporary and not key.startswith('@') \ and tag_item.tag.state: k = 'author_sort' if key == 'authors' else key letters_seen = {} for subnode in tag_item.children: if subnode.tag.sort: c = subnode.tag.sort[0] if c in r'\.^$[]|()': c = f'\\{c}' letters_seen[c] = True if letters_seen: charclass = ''.join(letters_seen) if k == 'author_sort': expr = r'%s:"""~(^[%s])|(&\s*[%s])"""'%(k, charclass, charclass) elif k == 'series': expr = r'series_sort:"""~^[%s]"""'%(charclass) else: expr = r'%s:"""~^[%s]"""'%(k, charclass) else: expr = r'%s:false'%(k) if node_searches[tag_item.tag.state] == 'true': ans.append(expr) else: ans.append('(not ' + expr + ')') continue tag = tag_item.tag if tag.state != TAG_SEARCH_STATES['clear']: if tag.state == TAG_SEARCH_STATES['mark_minus'] or \ tag.state == TAG_SEARCH_STATES['mark_minusminus']: prefix = 'not ' else: prefix = '' if node.is_gst: category = key else: category = tag.category if key != 'news' else 'tag' add_colon = False if self.db.field_metadata[tag.category]['is_csp']: add_colon = True if tag.name and tag.name[0] in stars: # char is a star or a half. Assume rating rnum = len(tag.name) if tag.name.endswith(stars[-1]): rnum = '%s.5' % (rnum - 1) ans.append('%s%s:%s'%(prefix, category, rnum)) else: name = tag.original_name use_prefix = tag.state in [TAG_SEARCH_STATES['mark_plusplus'], TAG_SEARCH_STATES['mark_minusminus']] if category == 'tags': if name in tags_seen: continue tags_seen.add(name) if tag in nodes_seen: continue nodes_seen.add(tag) n = name.replace(r'"', r'\"') if name.startswith('.'): n = '.' + n ans.append('%s%s:"=%s%s%s"'%(prefix, category, '.' if use_prefix else '', n, ':' if add_colon else '')) return ans def find_item_node(self, key, txt, start_path, equals_match=False): ''' Search for an item (a node) in the tags browser list that matches both the key (exact case-insensitive match) and txt (not equals_match => case-insensitive contains match; equals_match => case_insensitive equal match). Returns the path to the node. Note that paths are to a location (second item, fourth item, 25 item), not to a node. If start_path is None, the search starts with the topmost node. If the tree is changed subsequent to calling this method, the path can easily refer to a different node or no node at all. ''' if not txt: return None txt = lower(txt) if not equals_match else txt self.path_found = None if start_path is None: start_path = [] if prefs['use_primary_find_in_search']: def final_equals(x, y): return primary_strcmp(x, y) == 0 def final_contains(x, y): return primary_contains(x, y) else: def final_equals(x, y): return strcmp(x, y) == 0 def final_contains(filt, txt): return contains(filt, icu_lower(txt)) def process_tag(depth, tag_index, tag_item, start_path): path = self.path_for_index(tag_index) if depth < len(start_path) and path[depth] <= start_path[depth]: return False tag = tag_item.tag if tag is None: return False name = tag.original_name if ((equals_match and final_equals(name, txt)) or (not equals_match and final_contains(txt, name))): self.path_found = path return True for i,c in enumerate(tag_item.children): if process_tag(depth+1, self.createIndex(i, 0, c), c, start_path): return True return False def process_level(depth, category_index, start_path): path = self.path_for_index(category_index) if depth < len(start_path): if path[depth] < start_path[depth]: return False if path[depth] > start_path[depth]: start_path = path my_key = self.get_node(category_index).category_key for j in range(self.rowCount(category_index)): tag_index = self.index(j, 0, category_index) tag_item = self.get_node(tag_index) if tag_item.type == TagTreeItem.CATEGORY: if process_level(depth+1, tag_index, start_path): return True elif not key or strcmp(key, my_key) == 0: if process_tag(depth+1, tag_index, tag_item, start_path): return True return False for i in range(self.rowCount(QModelIndex())): if process_level(0, self.index(i, 0, QModelIndex()), start_path): break return self.path_found def find_category_node(self, key, parent=QModelIndex()): ''' Search for an category node (a top-level node) in the tags browser list that matches the key (exact case-insensitive match). Returns the path to the node. Paths are as in find_item_node. ''' if not key: return None for i in range(self.rowCount(parent)): idx = self.index(i, 0, parent) node = self.get_node(idx) if node.type == TagTreeItem.CATEGORY: ckey = node.category_key if strcmp(ckey, key) == 0: return self.path_for_index(idx) if len(node.children): v = self.find_category_node(key, idx) if v is not None: return v return None def set_boxed(self, idx): tag_item = self.get_node(idx) tag_item.boxed = True self.dataChanged.emit(idx, idx) def clear_boxed(self): ''' Clear all boxes around items. ''' def process_tag(tag_index, tag_item): if tag_item.boxed: tag_item.boxed = False self.dataChanged.emit(tag_index, tag_index) for i,c in enumerate(tag_item.children): process_tag(self.index(i, 0, tag_index), c) def process_level(category_index): for j in range(self.rowCount(category_index)): tag_index = self.index(j, 0, category_index) tag_item = self.get_node(tag_index) if tag_item.boxed: tag_item.boxed = False self.dataChanged.emit(tag_index, tag_index) if tag_item.type == TagTreeItem.CATEGORY: process_level(tag_index) else: process_tag(tag_index, tag_item) for i in range(self.rowCount(QModelIndex())): process_level(self.index(i, 0, QModelIndex())) # }}}
89,657
Python
.py
1,823
33.34723
143
0.520976
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,753
view.py
kovidgoyal_calibre/src/calibre/gui2/tag_browser/view.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os import re import traceback from collections import defaultdict from contextlib import suppress from functools import partial from qt.core import ( QAbstractItemView, QApplication, QBrush, QColor, QCursor, QDialog, QDrag, QFont, QIcon, QLinearGradient, QMenu, QModelIndex, QPalette, QPen, QPoint, QPointF, QRect, QSize, QStyle, QStyledItemDelegate, QStyleOptionViewItem, Qt, QTimer, QToolTip, QTreeView, pyqtSignal, ) from calibre import sanitize_file_name from calibre.constants import config_dir from calibre.ebooks.metadata import rating_to_stars from calibre.gui2 import FunctionDispatcher, choose_files, config, empty_index, gprefs, pixmap_to_data, question_dialog, rating_font, safe_open_url from calibre.gui2.complete2 import EditWithComplete from calibre.gui2.dialogs.edit_category_notes import EditNoteDialog from calibre.gui2.tag_browser.model import COUNT_ROLE, DRAG_IMAGE_ROLE, TAG_SEARCH_STATES, TagsModel, TagTreeItem, rename_only_in_vl_question from calibre.gui2.widgets import EnLineEdit from calibre.utils.icu import sort_key from calibre.utils.serialize import json_loads class TagDelegate(QStyledItemDelegate): # {{{ def __init__(self, tags_view): QStyledItemDelegate.__init__(self, tags_view) self.old_look = False self.rating_pat = re.compile(r'[%s]' % rating_to_stars(3, True)) self.rating_font = QFont(rating_font()) self.tags_view = tags_view self.links_icon = QIcon.ic('external-link.png') self.notes_icon = QIcon.ic('notes.png') self.blank_icon = QIcon() def draw_average_rating(self, item, style, painter, option, widget): rating = item.average_rating if rating is None: return r = style.subElementRect(QStyle.SubElement.SE_ItemViewItemDecoration, option, widget) icon = option.icon painter.save() nr = r.adjusted(0, 0, 0, 0) nr.setBottom(r.bottom()-int(r.height()*(rating/5.0))) painter.setClipRect(nr) bg = option.palette.window() if self.old_look: bg = option.palette.alternateBase() if option.features&QStyleOptionViewItem.ViewItemFeature.Alternate else option.palette.base() painter.fillRect(r, bg) style.proxy().drawPrimitive(QStyle.PrimitiveElement.PE_PanelItemViewItem, option, painter, widget) painter.setOpacity(0.3) icon.paint(painter, r, option.decorationAlignment, QIcon.Mode.Normal, QIcon.State.On) painter.restore() def draw_icon(self, style, painter, option, widget): r = style.subElementRect(QStyle.SubElement.SE_ItemViewItemDecoration, option, widget) icon = option.icon icon.paint(painter, r, option.decorationAlignment, QIcon.Mode.Normal, QIcon.State.On) def text_color(self, hover, palette) -> QColor: if QApplication.instance().is_dark_theme and hover: return QColor(Qt.GlobalColor.black) return palette.color(QPalette.ColorRole.WindowText) def draw_text(self, style, painter, option, widget, index, item): tr = style.subElementRect(QStyle.SubElement.SE_ItemViewItemText, option, widget) text = index.data(Qt.ItemDataRole.DisplayRole) flags = Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft | Qt.TextFlag.TextSingleLine lr = QRect(tr) lr.setRight(lr.right() * 2) text_rec = painter.boundingRect(lr, flags, text) hover = option.state & QStyle.StateFlag.State_MouseOver is_search = (True if item.type == TagTreeItem.TAG and item.tag.category == 'search' else False) pen = painter.pen() pen.setColor(self.text_color(hover, option.palette)) painter.setPen(pen) def render_count(): if not is_search and (hover or gprefs['tag_browser_show_counts']): count = str(index.data(COUNT_ROLE)) width = painter.fontMetrics().boundingRect(count).width() r = QRect(tr) r.setRight(r.right() - 1), r.setLeft(r.right() - width - 4) painter.drawText(r, Qt.AlignmentFlag.AlignCenter | Qt.TextFlag.TextSingleLine, count) tr.setRight(r.left() - 1) else: tr.setRight(tr.right() - 1) if item.type == TagTreeItem.TAG: category = item.tag.category name = item.tag.original_name tv = self.tags_view m = tv._model positions = {'links': (-1, -1), 'notes': (-1, -1)} # The icons fits in a rectangle height/2 + 4 x height/2 + 4. This # ensures they are a 'pleasant' size compared to the text. icon_width = int(tr.height()/2) + 4 def render_link_icon(): icon = self.links_icon if m.item_has_link(category, name) else self.blank_icon r = QRect(tr) r.setRight(r.right() - 1) r.setLeft(r.right() - icon_width) positions['links'] = (r.left(), r.left()+r.width()) icon.paint(painter, r, option.decorationAlignment, QIcon.Mode.Normal, QIcon.State.On) tr.setRight(r.left() - 1) def render_note_icon(): icon = self.notes_icon if m.item_has_note(category, name) else self.blank_icon r = QRect(tr) r.setRight(r.right() - 1) r.setLeft(r.right() - icon_width) positions['notes'] = (r.left(), r.left()+r.width()) icon.paint(painter, r, option.decorationAlignment, QIcon.Mode.Normal, QIcon.State.On) tr.setRight(r.left() - 1) if gprefs['icons_on_right_in_tag_browser']: # Icons go far right, in columns after the counts show_note_icon = gprefs['show_notes_in_tag_browser'] and m.category_has_notes(category) show_link_icon = gprefs['show_links_in_tag_browser'] and m.category_has_links(category) if show_link_icon: render_link_icon() if show_note_icon: render_note_icon() render_count() else: # Icons go after the text to the left of the counts, not in columns show_note_icon = gprefs['show_notes_in_tag_browser'] and m.item_has_note(category, name) show_link_icon = gprefs['show_links_in_tag_browser'] and m.item_has_link(category, name) render_count() # The link icon has a margin of 1 px on each side. Account for # this when computing the width of the icons. If you change the # order of the icons then you must change this calculation w = (int(show_link_icon) * (icon_width + 2)) + (int(show_note_icon) * icon_width) # Leave a 5 px margin between the text and the icon. tr.setWidth(min(tr.width(), text_rec.width() + 5 + w)) if show_link_icon: render_link_icon() if show_note_icon: render_note_icon() tv.category_button_positions[category][name] = positions else: render_count() is_rating = item.type == TagTreeItem.TAG and not self.rating_pat.sub('', text) if is_rating: painter.setFont(self.rating_font) if text_rec.width() > tr.width(): g = QLinearGradient(QPointF(tr.topLeft()), QPointF(tr.topRight())) c = pen.color() g.setColorAt(0, c), g.setColorAt(0.8, c) c = QColor(c) c.setAlpha(0) g.setColorAt(1, c) pen = QPen() pen.setBrush(QBrush(g)) painter.setPen(pen) painter.drawText(tr, flags, text) def paint(self, painter, option, index): QStyledItemDelegate.paint(self, painter, option, empty_index) widget = self.parent() style = QApplication.style() if widget is None else widget.style() self.initStyleOption(option, index) item = index.data(Qt.ItemDataRole.UserRole) self.draw_icon(style, painter, option, widget) painter.save() self.draw_text(style, painter, option, widget, index, item) painter.restore() if item.boxed: r = style.subElementRect(QStyle.SubElement.SE_ItemViewItemFocusRect, option, widget) painter.drawLine(r.bottomLeft(), r.bottomRight()) if item.type == TagTreeItem.TAG and item.tag.state == 0 and config['show_avg_rating']: self.draw_average_rating(item, style, painter, option, widget) def createEditor(self, parent, option, index): item = self.tags_view.model().get_node(index) if not item.ignore_vl: if item.use_vl is None: if self.tags_view.model().get_in_vl(): item.use_vl = rename_only_in_vl_question(self.tags_view) else: item.use_vl = False elif not item.use_vl and self.tags_view.model().get_in_vl(): item.use_vl = not question_dialog(self.tags_view, _('Rename in Virtual library'), '<p>' + _('A Virtual library is active but you are renaming ' 'the item in all books in your library. Is ' 'this really what you want to do?') + '</p>', yes_text=_('Yes, apply in entire library'), no_text=_('No, apply only in Virtual library'), skip_dialog_name='tag_item_rename_in_entire_library') key, completion_data = '', None if item.type == TagTreeItem.CATEGORY: key = item.category_key elif item.type == TagTreeItem.TAG: key = getattr(item.tag, 'category', '') if key: from calibre.gui2.ui import get_gui with suppress(Exception): completion_data = get_gui().current_db.new_api.all_field_names(key) if completion_data: editor = EditWithComplete(parent) editor.set_separator(None) editor.update_items_cache(completion_data) else: editor = EnLineEdit(parent) return editor # }}} class TagsView(QTreeView): # {{{ refresh_required = pyqtSignal() tags_marked = pyqtSignal(object) edit_user_category = pyqtSignal(object) delete_user_category = pyqtSignal(object) del_item_from_user_cat = pyqtSignal(object, object, object) add_item_to_user_cat = pyqtSignal(object, object, object) add_subcategory = pyqtSignal(object) tags_list_edit = pyqtSignal(object, object, object) saved_search_edit = pyqtSignal(object) rebuild_saved_searches = pyqtSignal() author_sort_edit = pyqtSignal(object, object, object, object, object) tag_item_renamed = pyqtSignal() search_item_renamed = pyqtSignal() drag_drop_finished = pyqtSignal(object) restriction_error = pyqtSignal(object) tag_item_delete = pyqtSignal(object, object, object, object, object) tag_identifier_delete = pyqtSignal(object, object) apply_tag_to_selected = pyqtSignal(object, object, object) edit_enum_values = pyqtSignal(object, object, object) def __init__(self, parent=None): QTreeView.__init__(self, parent=None) self.possible_drag_start = None self.setProperty('frame_for_focus', True) self.setMouseTracking(True) self.alter_tb = None self.disable_recounting = False self.setUniformRowHeights(True) self.setIconSize(QSize(20, 20)) self.setTabKeyNavigation(True) self.setAnimated(True) self.setHeaderHidden(True) self.setItemDelegate(TagDelegate(tags_view=self)) self.made_connections = False self.setAcceptDrops(True) self.setDragEnabled(True) self.setDragDropMode(QAbstractItemView.DragDropMode.DragDrop) self.setDropIndicatorShown(True) self.setAutoExpandDelay(500) self.pane_is_visible = False self.search_icon = QIcon.ic('search.png') self.search_copy_icon = QIcon.ic("search_copy_saved.png") self.user_category_icon = QIcon.ic('tb_folder.png') self.edit_metadata_icon = QIcon.ic('edit_input.png') self.delete_icon = QIcon.ic('list_remove.png') self.rename_icon = QIcon.ic('edit-undo.png') self.plus_icon = QIcon.ic('plus.png') self.minus_icon = QIcon.ic('minus.png') # Dict for recording the positions of the fake buttons for category tag # lines. It is recorded per category because we can't guarantee the # order that items are painted. The numbers get updated whenever an item # is painted, which deals with resizing. self.category_button_positions = defaultdict(dict) self._model = TagsModel(self) self._model.search_item_renamed.connect(self.search_item_renamed) self._model.refresh_required.connect(self.refresh_required, type=Qt.ConnectionType.QueuedConnection) self._model.tag_item_renamed.connect(self.tag_item_renamed) self._model.restriction_error.connect(self.restriction_error) self._model.user_categories_edited.connect(self.user_categories_edited, type=Qt.ConnectionType.QueuedConnection) self._model.drag_drop_finished.connect(self.drag_drop_finished) self._model.convert_requested.connect(self.convert_requested) self.set_look_and_feel(first=True) QApplication.instance().palette_changed.connect(self.set_style_sheet, type=Qt.ConnectionType.QueuedConnection) self.marked_change_listener = FunctionDispatcher(self.recount_on_mark_change) def convert_requested(self, book_ids, to_fmt): from calibre.gui2.ui import get_gui get_gui().iactions['Convert Books'].convert_ebooks_to_format(book_ids, to_fmt) def set_style_sheet(self): stylish_tb = ''' QTreeView { background-color: palette(window); color: palette(window-text); border: none; } ''' self.setStyleSheet(''' QTreeView::item { border: 1px solid transparent; padding-top:PADex; padding-bottom:PADex; } '''.replace('PAD', str(gprefs['tag_browser_item_padding'])) + ( '' if gprefs['tag_browser_old_look'] else stylish_tb) + QApplication.instance().palette_manager.tree_view_hover_style() ) self.setProperty('hovered_item_is_highlighted', True) def set_look_and_feel(self, first=False): self.set_style_sheet() self.setAlternatingRowColors(gprefs['tag_browser_old_look']) self.itemDelegate().old_look = gprefs['tag_browser_old_look'] if gprefs['tag_browser_allow_keyboard_focus']: self.setFocusPolicy(Qt.FocusPolicy.StrongFocus) else: self.setFocusPolicy(Qt.FocusPolicy.NoFocus) # Ensure the TB doesn't keep the focus it might already have. When this # method is first called during GUI initialization not everything is # set up, in which case don't try to change the focus. # Note: this process has the side effect of moving the focus to the # library view whenever a look & feel preference is changed. if not first: try: from calibre.gui2.ui import get_gui get_gui().shift_esc() except: traceback.print_exc() @property def hidden_categories(self): return self._model.hidden_categories @property def db(self): return self._model.db @property def collapse_model(self): return self._model.collapse_model def set_pane_is_visible(self, to_what): pv = self.pane_is_visible self.pane_is_visible = to_what if to_what and not pv: self.recount() def get_state(self): state_map = {} expanded_categories = [] hide_empty_categories = self.model().prefs['tag_browser_hide_empty_categories'] crmap = self._model.category_row_map() for category in self._model.category_nodes: if (category.category_key in self.hidden_categories or ( hide_empty_categories and len(category.child_tags()) == 0)): continue row = crmap.get(category.category_key) if row is not None: index = self._model.index(row, 0, QModelIndex()) if self.isExpanded(index): expanded_categories.append(category.category_key) states = [c.tag.state for c in category.child_tags()] names = [(c.tag.name, c.tag.category) for c in category.child_tags()] state_map[category.category_key] = dict(zip(names, states)) return expanded_categories, state_map def reread_collapse_parameters(self): self._model.reread_collapse_model(self.get_state()[1]) def set_database(self, db, alter_tb): self._model.set_database(db) self.alter_tb = alter_tb self.pane_is_visible = True # because TagsModel.set_database did a recount self.setModel(self._model) self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) pop = self.db.CATEGORY_SORTS.index(config['sort_tags_by']) self.alter_tb.sort_menu.actions()[pop].setChecked(True) try: match_pop = self.db.MATCH_TYPE.index(config['match_tags_type']) except ValueError: match_pop = 0 self.alter_tb.match_menu.actions()[match_pop].setChecked(True) if not self.made_connections: self.clicked.connect(self.toggle_on_mouse_click) self.customContextMenuRequested.connect(self.show_context_menu) self.refresh_required.connect(self.recount, type=Qt.ConnectionType.QueuedConnection) self.alter_tb.sort_menu.triggered.connect(self.sort_changed) self.alter_tb.match_menu.triggered.connect(self.match_changed) self.made_connections = True self.refresh_signal_processed = True db.add_listener(self.database_changed) self.expanded.connect(self.item_expanded) self.collapsed.connect(self.collapse_node_and_children) db.data.add_marked_listener(self.marked_change_listener) def keyPressEvent(self, event): def on_last_visible_item(dex, check_children): model = self._model if model.get_node(dex) == model.root_item: # Got to root. There can't be any more children to show return True if check_children and self.isExpanded(dex): # We are on a node with expanded children so there is a node to go to. # We don't check children if we are moving up the parent hierarchy return False parent = model.parent(dex) if dex.row() < model.rowCount(parent) - 1: # Node has more nodes after it return False # Last node. Check the parent for further to see if there are more nodes return on_last_visible_item(parent, False) # I don't see how current_index can ever be not valid, but ... if self.currentIndex().isValid(): key = event.key() if gprefs['tag_browser_allow_keyboard_focus']: if key == Qt.Key.Key_Return and self.state() != QAbstractItemView.State.EditingState: self.toggle_current_index() return # Check if we are moving the focus and we are at the beginning or the # end of the list. The goal is to prevent moving focus away from the # tag browser. if key == Qt.Key.Key_Tab: if not on_last_visible_item(self.currentIndex(), True): QTreeView.keyPressEvent(self, event) return if key == Qt.Key.Key_Backtab: if self.model().get_node(self.currentIndex()) != self._model.root_item.children[0]: QTreeView.keyPressEvent(self, event) return # If this is an edit request, mark the node to request whether to use VLs # As far as I can tell, F2 is used across all platforms if key == Qt.Key.Key_F2: node = self.model().get_node(self.currentIndex()) if node.type == TagTreeItem.TAG: # Saved search nodes don't use the VL test/dialog node.use_vl = None node.ignore_vl = node.tag.category == 'search' else: # Don't open the editor for non-editable items if not node.category_key.startswith('@') or node.is_gst: return # Category nodes don't use the VL test/dialog node.use_vl = False node.ignore_vl = True QTreeView.keyPressEvent(self, event) def database_changed(self, event, ids): if self.refresh_signal_processed: self.refresh_signal_processed = False self.refresh_required.emit() def user_categories_edited(self, user_cats, nkey): state_map = self.get_state()[1] self.db.new_api.set_pref('user_categories', user_cats) self._model.rebuild_node_tree(state_map=state_map) p = self._model.find_category_node('@'+nkey) self.show_item_at_path(p) @property def match_all(self): return (self.alter_tb and self.alter_tb.match_menu.actions()[1].isChecked()) def sort_changed(self, action): for i, ac in enumerate(self.alter_tb.sort_menu.actions()): if ac is action: config.set('sort_tags_by', self.db.CATEGORY_SORTS[i]) self.recount() break def match_changed(self, action): try: for i, ac in enumerate(self.alter_tb.match_menu.actions()): if ac is action: config.set('match_tags_type', self.db.MATCH_TYPE[i]) except: pass def mousePressEvent(self, event): if event.buttons() & Qt.MouseButton.LeftButton: # Record the press point for processing during the clicked signal self.mouse_clicked_point = event.pos() # Only remember a possible drag start if the item is drag enabled dex = self.indexAt(event.pos()) if self._model.flags(dex) & Qt.ItemFlag.ItemIsDragEnabled: self.possible_drag_start = event.pos() else: self.possible_drag_start = None return QTreeView.mousePressEvent(self, event) def mouseMoveEvent(self, event): dex = self.indexAt(event.pos()) if dex.isValid(): self.setCursor(Qt.CursorShape.PointingHandCursor) else: self.unsetCursor() if not event.buttons() & Qt.MouseButton.LeftButton: return if not dex.isValid(): QTreeView.mouseMoveEvent(self, event) return # don't start drag/drop until the mouse has moved a bit. if (self.possible_drag_start is None or (event.pos() - self.possible_drag_start).manhattanLength() < QApplication.startDragDistance()): QTreeView.mouseMoveEvent(self, event) return if not self._model.flags(dex) & Qt.ItemFlag.ItemIsDragEnabled: QTreeView.mouseMoveEvent(self, event) return md = self._model.mimeData([dex]) pixmap = dex.data(DRAG_IMAGE_ROLE).pixmap(self.iconSize()) drag = QDrag(self) drag.setPixmap(pixmap) drag.setMimeData(md) if (self._model.is_in_user_category(dex) or self._model.is_index_on_a_hierarchical_category(dex)): ''' Things break if we specify MoveAction as the default, which is what we want for drag on hierarchical categories. Dragging user categories stops working. Don't know why. To avoid the problem we fix the action in dragMoveEvent. ''' drag.exec(Qt.DropAction.CopyAction|Qt.DropAction.MoveAction, Qt.DropAction.CopyAction) else: drag.exec(Qt.DropAction.CopyAction) def mouseDoubleClickEvent(self, event): # swallow these to avoid toggling and editing at the same time pass @property def search_string(self): tokens = self._model.tokens() joiner = ' and ' if self.match_all else ' or ' return joiner.join(tokens) def click_in_button_range(self, val, category, item_name, kind): range_tuple = self.category_button_positions[category].get(item_name, {}).get(kind) return range_tuple and range_tuple[0] <= val <= range_tuple[1] def toggle_current_index(self): ci = self.currentIndex() if ci.isValid(): self.toggle(ci) def toggle_on_mouse_click(self, index): # Check if one of the link or note icons was clicked. If so, deal with # it here and don't do the real toggle t = self._model.data(index, Qt.UserRole) if t.type == TagTreeItem.TAG: db = self._model.db.new_api category = t.tag.category orig_name = t.tag.original_name x = self.mouse_clicked_point.x() if self.click_in_button_range(x, category, orig_name, 'notes'): from calibre.gui2.dialogs.show_category_note import ShowNoteDialog item_id = db.get_item_id(category, orig_name, case_sensitive=True) if db.notes_for(category, item_id): ShowNoteDialog(category, item_id, db, parent=self).show() return if self.click_in_button_range(x, category, orig_name, 'links'): link = db.get_link_map(category).get(orig_name) if link: safe_open_url(link) return self._toggle(index, None) def toggle(self, index): self._toggle(index, None) def _toggle(self, index, set_to): ''' set_to: if None, advance the state. Otherwise must be one of the values in TAG_SEARCH_STATES ''' exclusive = QApplication.keyboardModifiers() not in (Qt.KeyboardModifier.ControlModifier, Qt.KeyboardModifier.ShiftModifier) if self._model.toggle(index, exclusive, set_to=set_to): # Reset the focus back to TB if it has it before the toggle # Must ask this question before starting the search because # it changes the focus has_focus = self.hasFocus() self.tags_marked.emit(self.search_string) if has_focus and gprefs['tag_browser_allow_keyboard_focus']: # Reset the focus to the TB. Use the singleshot in case # some of searching is done using queued signals. QTimer.singleShot(0, lambda: self.setFocus()) def conditional_clear(self, search_string): if search_string != self.search_string: self.clear() def context_menu_handler(self, action=None, category=None, key=None, index=None, search_state=None, is_first_letter=False, ignore_vl=False, extra=None): if not action: return from calibre.gui2.ui import get_gui try: if action == 'edit_note': if EditNoteDialog(category, extra, self.db).exec() == QDialog.DialogCode.Accepted: get_gui().do_field_item_value_changed() return if action == 'dont_collapse_category': if key not in extra: extra.append(key) self.db.prefs.set('tag_browser_dont_collapse', extra) self.recount() return if action == 'collapse_category': if key in extra: extra.remove(key) self.db.prefs.set('tag_browser_dont_collapse', extra) self.recount() return if action == 'set_icon': try: path = choose_files(self, 'choose_category_icon', _('Change icon for: %s')%key, filters=[ ('Images', ['png', 'gif', 'jpg', 'jpeg'])], all_files=False, select_only_single_file=True) if path: path = path[0] p = QIcon(path).pixmap(QSize(128, 128)) d = os.path.join(config_dir, 'tb_icons') if not os.path.exists(d): os.makedirs(d) with open(os.path.join(d, 'icon_' + sanitize_file_name(key)+'.png'), 'wb') as f: f.write(pixmap_to_data(p, format='PNG')) path = os.path.basename(f.name) self._model.set_custom_category_icon(key, str(path)) self.recount() except: traceback.print_exc() return if action == 'clear_icon': self._model.set_custom_category_icon(key, None) self.recount() return if action == 'edit_item_no_vl': item = self.model().get_node(index) item.use_vl = False item.ignore_vl = ignore_vl self.edit(index) return if action == 'edit_item_in_vl': item = self.model().get_node(index) item.use_vl = True item.ignore_vl = ignore_vl self.edit(index) return if action == 'delete_item_in_vl': tag = index.tag id_ = tag.id if tag.is_editable else None children = index.child_tags() self.tag_item_delete.emit(key, id_, tag.original_name, self.model().get_book_ids_to_use(), children) return if action == 'delete_item_no_vl': tag = index.tag id_ = tag.id if tag.is_editable else None children = index.child_tags() self.tag_item_delete.emit(key, id_, tag.original_name, None, children) return if action == 'delete_identifier': self.tag_identifier_delete.emit(index.tag.name, False) return if action == 'delete_identifier_in_vl': self.tag_identifier_delete.emit(index.tag.name, True) return if action == 'open_editor': self.tags_list_edit.emit(category, key, is_first_letter) return if action == 'manage_categories': self.edit_user_category.emit(category) return if action == 'search': self._toggle(index, set_to=search_state) return if action == "raw_search": get_gui().get_saved_search_text(search_name='search:' + key) return if action == 'add_to_category': tag = index.tag if len(index.children) > 0: for c in index.all_children(): self.add_item_to_user_cat.emit(category, c.tag.original_name, c.tag.category) self.add_item_to_user_cat.emit(category, tag.original_name, tag.category) return if action == 'add_subcategory': self.add_subcategory.emit(key) return if action == 'search_category': self._toggle(index, set_to=search_state) return if action == 'delete_user_category': self.delete_user_category.emit(key) return if action == 'delete_search': if not question_dialog( self, title=_('Delete Saved search'), msg='<p>'+ _('Delete the saved search: {}?').format(key), skip_dialog_name='tb_delete_saved_search', skip_dialog_msg=_('Show this confirmation again') ): return self.model().db.saved_search_delete(key) self.rebuild_saved_searches.emit() return if action == 'delete_item_from_user_category': tag = index.tag if len(index.children) > 0: for c in index.children: self.del_item_from_user_cat.emit(key, c.tag.original_name, c.tag.category) self.del_item_from_user_cat.emit(key, tag.original_name, tag.category) return if action == 'manage_searches': self.saved_search_edit.emit(category) return if action == 'edit_authors': self.author_sort_edit.emit(self, index, False, False, is_first_letter) return if action == 'edit_author_sort': self.author_sort_edit.emit(self, index, True, False, is_first_letter) return if action == 'edit_author_link': self.author_sort_edit.emit(self, index, False, True, False) return if action == 'remove_format': gui = get_gui() gui.iactions['Remove Books'].remove_format_from_selected_books(key) return if action == 'edit_open_with_apps': from calibre.gui2.open_with import edit_programs edit_programs(key, self) return if action == 'add_open_with_apps': from calibre.gui2.open_with import choose_program choose_program(key, self) return reset_filter_categories = True if action == 'hide': self.hidden_categories.add(category) elif action == 'show': self.hidden_categories.discard(category) elif action == 'categorization': changed = self.collapse_model != category self._model.collapse_model = category if changed: reset_filter_categories = False gprefs['tags_browser_partition_method'] = category elif action == 'defaults': self.hidden_categories.clear() elif action == 'add_tag': item = self.model().get_node(index) if item is not None: self.apply_to_selected_books(item) return elif action == 'remove_tag': item = self.model().get_node(index) if item is not None: self.apply_to_selected_books(item, True) return elif action == 'edit_enum': self.edit_enum_values.emit(self, self.db, key) return self.db.new_api.set_pref('tag_browser_hidden_categories', list(self.hidden_categories)) if reset_filter_categories: self._model.set_categories_filter(None) self._model.rebuild_node_tree() except Exception: traceback.print_exc() return def apply_to_selected_books(self, item, remove=False): if item.type != item.TAG: return tag = item.tag if not tag.category or not tag.original_name: return self.apply_tag_to_selected.emit(tag.category, tag.original_name, remove) def show_context_menu(self, point): def display_name(tag): ans = tag.name if tag.category == 'search': n = tag.name if len(n) > 45: n = n[:45] + '...' ans = n elif tag.is_hierarchical and not tag.is_editable: ans = tag.original_name if ans: ans = ans.replace('&', '&&') return ans index = self.indexAt(point) self.context_menu = QMenu(self) added_show_hidden_categories = False key = None def add_show_hidden_categories(): nonlocal added_show_hidden_categories if self.hidden_categories and not added_show_hidden_categories: added_show_hidden_categories = True m = self.context_menu.addMenu(_('Show category')) m.setIcon(QIcon.ic('plus.png')) # The search category can disappear from field_metadata. Perhaps # other dynamic categories can as well. The implication is that # dynamic categories are being removed, but how that would # happen is a mystery. I suspect a plugin is operating on the # "real" field_metadata instead of a copy, thereby changing the # dict used by the rest of calibre. # # As it can happen, to avoid key errors check that a category # exists before offering to unhide it. for col in sorted((c for c in self.hidden_categories if c in self.db.field_metadata), key=lambda x: sort_key(self.db.field_metadata[x]['name'])): ac = m.addAction(self.db.field_metadata[col]['name'], partial(self.context_menu_handler, action='show', category=col)) ic = self.model().category_custom_icons.get(col) if ic: ac.setIcon(QIcon.ic(ic)) m.addSeparator() m.addAction(_('All categories'), partial(self.context_menu_handler, action='defaults')).setIcon(QIcon.ic('plusplus.png')) search_submenu = None if index.isValid(): item = index.data(Qt.ItemDataRole.UserRole) tag = None tag_item = item if item.type == TagTreeItem.TAG: tag = item.tag while item.type != TagTreeItem.CATEGORY: item = item.parent if item.type == TagTreeItem.CATEGORY: if not item.category_key.startswith('@'): while item.parent != self._model.root_item: item = item.parent category = str(item.name or '') key = item.category_key # Verify that we are working with a field that we know something about if key not in self.db.field_metadata: return True fm = self.db.field_metadata[key] # Did the user click on a leaf node? if tag: # If the user right-clicked on an editable item, then offer # the possibility of renaming that item. if (fm['datatype'] != 'composite' and (tag.is_editable or tag.is_hierarchical) and key != 'search'): # Add the 'rename' items to both interior and leaf nodes if fm['datatype'] != 'enumeration': if self.model().get_in_vl(): self.context_menu.addAction(self.rename_icon, _('Rename %s in Virtual library')%display_name(tag), partial(self.context_menu_handler, action='edit_item_in_vl', index=index, category=key)) self.context_menu.addAction(self.rename_icon, _('Rename %s')%display_name(tag), partial(self.context_menu_handler, action='edit_item_no_vl', index=index, category=key)) if key in ('tags', 'series', 'publisher') or \ self._model.db.field_metadata.is_custom_field(key): if self.model().get_in_vl(): self.context_menu.addAction(self.delete_icon, _('Delete %s in Virtual library')%display_name(tag), partial(self.context_menu_handler, action='delete_item_in_vl', key=key, index=tag_item)) self.context_menu.addAction(self.delete_icon, _('Delete %s')%display_name(tag), partial(self.context_menu_handler, action='delete_item_no_vl', key=key, index=tag_item)) if tag.is_editable: if key == 'authors': self.context_menu.addAction(_('Edit sort for %s')%display_name(tag), partial(self.context_menu_handler, action='edit_author_sort', index=tag.id)).setIcon(QIcon.ic('auto_author_sort.png')) self.context_menu.addAction(_('Edit link for %s')%display_name(tag), partial(self.context_menu_handler, action='edit_author_link', index=tag.id)).setIcon(QIcon.ic('insert-link.png')) elif self.db.new_api.has_link_map(key): self.context_menu.addAction(_('Edit link for %s')%display_name(tag), partial(self.context_menu_handler, action='open_editor', category=tag.original_name if tag else None, key=key)) if self.db.new_api.field_supports_notes(key): item_id = self.db.new_api.get_item_id(tag.category, tag.original_name, case_sensitive=True) has_note = self._model.item_has_note(key, tag.original_name) self.context_menu.addAction(self.edit_metadata_icon, (_('Edit note for %s') if has_note else _('Create note for %s'))%display_name(tag), partial(self.context_menu_handler, action='edit_note', index=index, extra=item_id, category=tag.category)) # is_editable is also overloaded to mean 'can be added # to a User category' m = QMenu(_('Add %s to User category')%display_name(tag), self.context_menu) m.setIcon(self.user_category_icon) added = [False] def add_node_tree(tree_dict, m, path): p = path[:] for k in sorted(tree_dict.keys(), key=sort_key): p.append(k) n = k[1:] if k.startswith('@') else k m.addAction(self.user_category_icon, n, partial(self.context_menu_handler, 'add_to_category', category='.'.join(p), index=tag_item)) added[0] = True if len(tree_dict[k]): tm = m.addMenu(self.user_category_icon, _('Children of %s')%n) add_node_tree(tree_dict[k], tm, p) p.pop() add_node_tree(self.model().user_category_node_tree, m, []) if added[0]: self.context_menu.addMenu(m) # is_editable also means the tag can be applied/removed # from selected books if fm['datatype'] != 'rating': m = self.context_menu.addMenu(self.edit_metadata_icon, _('Add/remove %s to selected books')%display_name(tag)) m.addAction(self.plus_icon, _('Add %s to selected books') % display_name(tag), partial(self.context_menu_handler, action='add_tag', index=index)) m.addAction(self.minus_icon, _('Remove %s from selected books') % display_name(tag), partial(self.context_menu_handler, action='remove_tag', index=index)) elif key == 'search' and tag.is_searchable: self.context_menu.addAction(self.rename_icon, _('Rename %s')%display_name(tag), partial(self.context_menu_handler, action='edit_item_no_vl', index=index, ignore_vl=True)) self.context_menu.addAction(self.delete_icon, _('Delete Saved search %s')%display_name(tag), partial(self.context_menu_handler, action='delete_search', key=tag.original_name)) elif key == 'identifiers': if self.model().get_in_vl(): self.context_menu.addAction(self.delete_icon, _('Delete %s in Virtual Library')%display_name(tag), partial(self.context_menu_handler, action='delete_identifier_in_vl', key=key, index=tag_item)) else: self.context_menu.addAction(self.delete_icon, _('Delete %s')%display_name(tag), partial(self.context_menu_handler, action='delete_identifier', key=key, index=tag_item)) if key.startswith('@') and not item.is_gst: self.context_menu.addAction(self.user_category_icon, _('Remove {item} from category: {cat}').format(item=display_name(tag), cat=item.py_name), partial(self.context_menu_handler, action='delete_item_from_user_category', key=key, index=tag_item)) if tag.is_searchable: # Add the search for value items. All leaf nodes are searchable self.context_menu.addSeparator() search_submenu = self.context_menu.addMenu(_('Search for')) search_submenu.setIcon(QIcon.ic('search.png')) search_submenu.addAction(self.search_icon, '%s'%display_name(tag), partial(self.context_menu_handler, action='search', search_state=TAG_SEARCH_STATES['mark_plus'], index=index)) add_child_search = (tag.is_hierarchical == '5state' and len(tag_item.children)) if add_child_search: search_submenu.addAction(self.search_icon, _('%s and its children')%display_name(tag), partial(self.context_menu_handler, action='search', search_state=TAG_SEARCH_STATES['mark_plusplus'], index=index)) search_submenu.addAction(self.search_icon, _('Everything but %s')%display_name(tag), partial(self.context_menu_handler, action='search', search_state=TAG_SEARCH_STATES['mark_minus'], index=index)) if add_child_search: search_submenu.addAction(self.search_icon, _('Everything but %s and its children')%display_name(tag), partial(self.context_menu_handler, action='search', search_state=TAG_SEARCH_STATES['mark_minusminus'], index=index)) if key == 'search': search_submenu.addAction(self.search_copy_icon, _('The saved search expression'), partial(self.context_menu_handler, action='raw_search', key=tag.original_name)) self.context_menu.addSeparator() elif key.startswith('@') and not item.is_gst: if item.can_be_edited: self.context_menu.addAction(self.rename_icon, _('Rename %s')%item.py_name.replace('&', '&&'), partial(self.context_menu_handler, action='edit_item_no_vl', index=index, ignore_vl=True)) self.context_menu.addAction(self.user_category_icon, _('Add sub-category to %s')%item.py_name.replace('&', '&&'), partial(self.context_menu_handler, action='add_subcategory', key=key)) self.context_menu.addAction(self.delete_icon, _('Delete User category %s')%item.py_name.replace('&', '&&'), partial(self.context_menu_handler, action='delete_user_category', key=key)) self.context_menu.addSeparator() # Add searches for temporary first letter nodes if self._model.collapse_model == 'first letter' and \ tag_item.temporary and not key.startswith('@'): self.context_menu.addSeparator() search_submenu = self.context_menu.addMenu(_('Search for')) search_submenu.setIcon(QIcon.ic('search.png')) search_submenu.addAction(self.search_icon, '%s'%display_name(tag_item.tag), partial(self.context_menu_handler, action='search', search_state=TAG_SEARCH_STATES['mark_plus'], index=index)) search_submenu.addAction(self.search_icon, _('Everything but %s')%display_name(tag_item.tag), partial(self.context_menu_handler, action='search', search_state=TAG_SEARCH_STATES['mark_minus'], index=index)) # search by category. Some categories are not searchable, such # as search and news if item.tag.is_searchable: if search_submenu is None: search_submenu = self.context_menu.addMenu(_('Search for')) search_submenu.setIcon(QIcon.ic('search.png')) self.context_menu.addSeparator() else: search_submenu.addSeparator() search_submenu.addAction(self.search_icon, _('Books in category %s')%category, partial(self.context_menu_handler, action='search_category', index=self._model.createIndex(item.row(), 0, item), search_state=TAG_SEARCH_STATES['mark_plus'])) search_submenu.addAction(self.search_icon, _('Books not in category %s')%category, partial(self.context_menu_handler, action='search_category', index=self._model.createIndex(item.row(), 0, item), search_state=TAG_SEARCH_STATES['mark_minus'])) # Offer specific editors for tags/series/publishers/saved searches self.context_menu.addSeparator() if key in ['tags', 'publisher', 'series'] or ( fm['is_custom'] and fm['datatype'] != 'composite'): if tag_item.type == TagTreeItem.CATEGORY and tag_item.temporary: ac = self.context_menu.addAction(_('Manage %s')%category, partial(self.context_menu_handler, action='open_editor', category=tag_item.name, key=key, is_first_letter=True)) else: ac = self.context_menu.addAction(_('Manage %s')%category, partial(self.context_menu_handler, action='open_editor', category=tag.original_name if tag else None, key=key)) ic = self.model().category_custom_icons.get(key) if ic: ac.setIcon(QIcon.ic(ic)) if fm['datatype'] == 'enumeration': self.context_menu.addAction(_('Edit permissible values for %s')%category, partial(self.context_menu_handler, action='edit_enum', key=key)) elif key == 'authors': if tag_item.type == TagTreeItem.CATEGORY: if tag_item.temporary: ac = self.context_menu.addAction(_('Manage %s')%category, partial(self.context_menu_handler, action='edit_authors', index=tag_item.name, is_first_letter=True)) else: ac = self.context_menu.addAction(_('Manage %s')%category, partial(self.context_menu_handler, action='edit_authors')) else: ac = self.context_menu.addAction(_('Manage %s')%category, partial(self.context_menu_handler, action='edit_authors', index=tag.id)) ic = self.model().category_custom_icons.get(key) if ic: ac.setIcon(QIcon.ic(ic)) elif key == 'search': self.context_menu.addAction(_('Manage Saved searches'), partial(self.context_menu_handler, action='manage_searches', category=tag.name if tag else None)) elif key == 'formats' and tag is not None: self.context_menu.addAction(_('Remove the {} format from selected books').format(tag.name), partial(self.context_menu_handler, action='remove_format', key=tag.name)) self.context_menu.addSeparator() self.context_menu.addAction(_('Add other application for %s files') % format(tag.name.upper()), partial(self.context_menu_handler, action='add_open_with_apps', key=tag.name)) self.context_menu.addAction(_('Edit Open with applications for {} files').format(tag.name), partial(self.context_menu_handler, action='edit_open_with_apps', key=tag.name)) # Hide/Show/Restore categories self.context_menu.addSeparator() # Because of the strange way hierarchy works in user categories # where child nodes actually exist we must limit hiding to top- # level categories, which will hide that category and children if not key.startswith('@') or '.' not in key: self.context_menu.addAction(_('Hide category %s') % category.replace('&', '&&'), partial(self.context_menu_handler, action='hide', category=key)).setIcon(QIcon.ic('minus.png')) add_show_hidden_categories() if tag is None: cm = self.context_menu cm.addSeparator() acategory = category.replace('&', '&&') sm = cm.addAction(_('Change {} category icon').format(acategory), partial(self.context_menu_handler, action='set_icon', key=key, category=category)) sm.setIcon(QIcon.ic('icon_choose.png')) sm = cm.addAction(_('Restore {} category default icon').format(acategory), partial(self.context_menu_handler, action='clear_icon', key=key, category=category)) sm.setIcon(QIcon.ic('edit-clear.png')) if key == 'search' and 'search' in self.db.new_api.pref('categories_using_hierarchy', ()): sm = cm.addAction(_('Change Saved searches folder icon'), partial(self.context_menu_handler, action='set_icon', key='search_folder:', category=_('Saved searches folder'))) sm.setIcon(QIcon.ic('icon_choose.png')) sm = cm.addAction(_('Restore Saved searches folder default icon'), partial(self.context_menu_handler, action='clear_icon', key='search_folder:', category=_('Saved searches folder'))) sm.setIcon(QIcon.ic('edit-clear.png')) # Always show the User categories editor self.context_menu.addSeparator() if key.startswith('@') and \ key[1:] in self.db.new_api.pref('user_categories', {}).keys(): self.context_menu.addAction(self.user_category_icon, _('Manage User categories'), partial(self.context_menu_handler, action='manage_categories', category=key[1:])) else: self.context_menu.addAction(self.user_category_icon, _('Manage User categories'), partial(self.context_menu_handler, action='manage_categories', category=None)) if self.hidden_categories: if not self.context_menu.isEmpty(): self.context_menu.addSeparator() add_show_hidden_categories() # partitioning. If partitioning is active, provide a way to turn it on or # off for this category. if gprefs['tags_browser_partition_method'] != 'disable' and key is not None: m = self.context_menu p = self.db.prefs.get('tag_browser_dont_collapse', gprefs['tag_browser_dont_collapse']) if key in p: a = m.addAction(_('Sub-categorize {}').format(category), partial(self.context_menu_handler, action='collapse_category', category=category, key=key, extra=p)) else: a = m.addAction(_("Don't sub-categorize {}").format(category), partial(self.context_menu_handler, action='dont_collapse_category', category=category, key=key, extra=p)) a.setIcon(QIcon.ic('config.png')) # Set the partitioning scheme m = self.context_menu.addMenu(_('Change sub-categorization scheme')) m.setIcon(QIcon.ic('config.png')) da = m.addAction(_('Disable'), partial(self.context_menu_handler, action='categorization', category='disable')) fla = m.addAction(_('By first letter'), partial(self.context_menu_handler, action='categorization', category='first letter')) pa = m.addAction(_('Partition'), partial(self.context_menu_handler, action='categorization', category='partition')) if self.collapse_model == 'disable': da.setCheckable(True) da.setChecked(True) elif self.collapse_model == 'first letter': fla.setCheckable(True) fla.setChecked(True) else: pa.setCheckable(True) pa.setChecked(True) if config['sort_tags_by'] != "name": fla.setEnabled(False) m.hovered.connect(self.collapse_menu_hovered) fla.setToolTip(_('First letter is usable only when sorting by name')) # Apparently one cannot set a tooltip to empty, so use a star and # deal with it in the hover method da.setToolTip('*') pa.setToolTip('*') # Add expand menu items self.context_menu.addSeparator() m = self.context_menu.addMenu(_('Expand or collapse')) try: node_name = self._model.get_node(index).tag.name except AttributeError: pass else: if self.has_children(index) and not self.isExpanded(index): m.addAction(self.plus_icon, _('Expand {0}').format(node_name), partial(self.expand, index)) if self.has_unexpanded_children(index): m.addAction(self.plus_icon, _('Expand {0} and its children').format(node_name), partial(self.expand_node_and_children, index)) # Add menu items to collapse parent nodes idx = index paths = [] while True: # First walk up the node tree getting the displayed names of # expanded parent nodes node = self._model.get_node(idx) if node.type == TagTreeItem.ROOT: break if self.has_children(idx) and self.isExpanded(idx): # leaf nodes don't have children so can't be expanded. # Also the leaf node might be collapsed paths.append((node.tag.name, idx)) idx = self._model.parent(idx) for p in paths: # Now add the menu items m.addAction(self.minus_icon, _("Collapse {0}").format(p[0]), partial(self.collapse_node, p[1])) m.addAction(self.minus_icon, _('Collapse all'), self.collapseAll) # Ask plugins if they have any actions to add to the context menu from calibre.gui2.ui import get_gui first = True for ac in get_gui().iactions.values(): try: for context_action in ac.tag_browser_context_action(index): if first: self.context_menu.addSeparator() first = False self.context_menu.addAction(context_action) except Exception: import traceback traceback.print_exc() if not self.context_menu.isEmpty(): self.context_menu.popup(self.mapToGlobal(point)) return True def has_children(self, idx): return self.model().rowCount(idx) > 0 def collapse_node_and_children(self, idx): self.collapse(idx) for r in range(self.model().rowCount(idx)): self.collapse_node_and_children(idx.child(r, 0)) def collapse_node(self, idx): if not idx.isValid(): return self.collapse_node_and_children(idx) self.setCurrentIndex(idx) self.scrollTo(idx) def expand_node_and_children(self, index): if not index.isValid(): return self.expand(index) for r in range(self.model().rowCount(index)): self.expand_node_and_children(index.child(r, 0)) def has_unexpanded_children(self, index): if not index.isValid(): return False for r in range(self._model.rowCount(index)): dex = index.child(r, 0) if self._model.rowCount(dex) > 0: if not self.isExpanded(dex): return True return self.has_unexpanded_children(dex) return False def collapse_menu_hovered(self, action): tip = action.toolTip() if tip == '*': tip = '' QToolTip.showText(QCursor.pos(), tip) def dragMoveEvent(self, event): QTreeView.dragMoveEvent(self, event) self.setDropIndicatorShown(False) index = self.indexAt(event.pos()) if not index.isValid(): return src_is_tb = event.mimeData().hasFormat('application/calibre+from_tag_browser') item = index.data(Qt.ItemDataRole.UserRole) if item.type == TagTreeItem.ROOT: return if src_is_tb: src_json = json_loads(bytes(event.mimeData().data('application/calibre+from_tag_browser'))) if len(src_json) > 1: # Should never have multiple mimedata from the tag browser return if src_is_tb: src_md = src_json[0] src_item = self._model.get_node(self._model.index_for_path(src_md[5])) # Check if this is an intra-hierarchical-category drag/drop if (src_item.type == TagTreeItem.TAG and src_item.tag.category == item.tag.category and not item.temporary and self._model.is_key_a_hierarchical_category(src_item.tag.category)): event.setDropAction(Qt.DropAction.MoveAction) self.setDropIndicatorShown(True) return # We aren't dropping an item on its own category. Check if the dest is # not a user category and can be dropped on. This covers drops from the # booklist. It is OK to drop onto virtual nodes if item.type == TagTreeItem.TAG and self._model.flags(index) & Qt.ItemFlag.ItemIsDropEnabled: event.setDropAction(Qt.DropAction.CopyAction) self.setDropIndicatorShown(not src_is_tb) return # Now see if we are on a user category and the source can be dropped there if item.type == TagTreeItem.CATEGORY and not item.is_gst: fm_dest = self.db.metadata_for_field(item.category_key) if fm_dest['kind'] == 'user': if src_is_tb: # src_md and src_item are initialized above if event.dropAction() == Qt.DropAction.MoveAction: # can move only from user categories if (src_md[0] == TagTreeItem.TAG and (not src_md[1].startswith('@') or src_md[2])): return # can't copy virtual nodes into a user category if src_item.tag.is_editable: self.setDropIndicatorShown(True) return md = event.mimeData() # Check for drag to user category from the book list. Can handle # only non-multiple columns, except for some unknown reason authors if hasattr(md, 'column_name'): fm_src = self.db.metadata_for_field(md.column_name) if md.column_name in ['authors', 'publisher', 'series'] or \ (fm_src['is_custom'] and ((fm_src['datatype'] in ['series', 'text', 'enumeration'] and not fm_src['is_multiple']) or (fm_src['datatype'] == 'composite' and fm_src['display'].get('make_category', False)))): self.setDropIndicatorShown(True) def clear(self): if self.model(): self.model().clear_state() def is_visible(self, idx): item = idx.data(Qt.ItemDataRole.UserRole) if getattr(item, 'type', None) == TagTreeItem.TAG: idx = idx.parent() return self.isExpanded(idx) def recount_on_mark_change(self, *args): # Let other marked listeners run before we do the recount QTimer.singleShot(0, self.recount) def recount_with_position_based_index(self): self._model.use_position_based_index_on_next_recount = True self.recount() def recount(self, *args): ''' Rebuild the category tree, expand any categories that were expanded, reset the search states, and reselect the current node. ''' if self.disable_recounting or not self.pane_is_visible: return self.refresh_signal_processed = True ci = self.currentIndex() if not ci.isValid(): ci = self.indexAt(QPoint(10, 10)) use_pos = self._model.use_position_based_index_on_next_recount self._model.use_position_based_index_on_next_recount = False if use_pos: path = self._model.path_for_index(ci) if self.is_visible(ci) else None else: path = self._model.named_path_for_index(ci) if self.is_visible(ci) else None expanded_categories, state_map = self.get_state() self._model.rebuild_node_tree(state_map=state_map) self.blockSignals(True) for category in expanded_categories: idx = self._model.index_for_category(category) if idx is not None and idx.isValid(): self.expand(idx) if path is not None: if use_pos: self.show_item_at_path(path) else: index = self._model.index_for_named_path(path) if index.isValid(): self.show_item_at_index(index) self.blockSignals(False) def show_item_at_path(self, path, box=False, position=QAbstractItemView.ScrollHint.PositionAtCenter): ''' Scroll the browser and open categories to show the item referenced by path. If possible, the item is placed in the center. If box=True, a box is drawn around the item. ''' if path: self.show_item_at_index(self._model.index_for_path(path), box=box, position=position) def expand_parent(self, idx): # Needed otherwise Qt sometimes segfaults if the node is buried in a # collapsed, off screen hierarchy. To be safe, we expand from the # outermost in p = self._model.parent(idx) if p.isValid(): self.expand_parent(p) self.expand(idx) def show_item_at_index(self, idx, box=False, position=QAbstractItemView.ScrollHint.PositionAtCenter): if idx.isValid() and idx.data(Qt.ItemDataRole.UserRole) is not self._model.root_item: self.expand_parent(idx) self.setCurrentIndex(idx) self.scrollTo(idx, position) if box: self._model.set_boxed(idx) def item_expanded(self, idx): ''' Called by the expanded signal ''' self.setCurrentIndex(idx) # }}}
73,465
Python
.py
1,378
36.54717
147
0.53853
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,754
develop.py
kovidgoyal_calibre/src/calibre/gui2/tts/develop.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net> from typing import Literal from qt.core import QAction, QKeySequence, QPlainTextEdit, QSize, Qt, QTextCursor, QToolBar from calibre.gui2 import Application from calibre.gui2.main_window import MainWindow from calibre.gui2.tts.manager import TTSManager TEXT = '''\ Demonstration � of DOCX support in calibre This document demonstrates the ability of the calibre DOCX Input plugin to convert the various typographic features in a Microsoft Word (2007 and newer) document. Convert this document to a modern ebook format, such as AZW3 for Kindles or EPUB for other ebook readers, to see it in action. ''' class MainWindow(MainWindow): def __init__(self, text): super().__init__() self.display = d = QPlainTextEdit(self) self.page_count = 1 self.toolbar = tb = QToolBar(self) self.tts = TTSManager(self) self.tts.state_event.connect(self.state_event, type=Qt.ConnectionType.QueuedConnection) self.tts.saying.connect(self.saying) self.addToolBar(tb) self.setCentralWidget(d) d.setPlainText(text) d.setReadOnly(True) self.create_marked_text() self.play_action = pa = QAction('Play') pa.setShortcut(QKeySequence(Qt.Key.Key_Space)) pa.triggered.connect(self.play_triggerred) self.toolbar.addAction(pa) self.stop_action = sa = QAction('Stop') sa.setShortcut(QKeySequence(Qt.Key.Key_Escape)) sa.triggered.connect(self.stop) self.toolbar.addAction(sa) self.faster_action = fa = QAction('Faster') fa.triggered.connect(self.tts.faster) self.toolbar.addAction(fa) self.slower_action = sa = QAction('Slower') self.toolbar.addAction(sa) sa.triggered.connect(self.tts.slower) self.configure_action = ca = QAction('Configure') self.toolbar.addAction(ca) ca.triggered.connect(self.tts.configure) self.reload_action = ra = QAction('Reload') self.toolbar.addAction(ra) ra.triggered.connect(self.tts.test_resume_after_reload) self.resize(self.sizeHint()) def stop(self): self.update_play_action('Play') self.stop_action.setEnabled(False) self.tts.stop() c = self.display.textCursor() c.setPosition(0) self.display.setTextCursor(c) def create_marked_text(self): c = self.display.textCursor() c.setPosition(0) marked_text = [] while True: marked_text.append(c.position()) if not c.movePosition(QTextCursor.MoveOperation.NextWord, QTextCursor.MoveMode.KeepAnchor): break marked_text.append(c.selectedText().replace('\u2029', '\n')) c.setPosition(c.position()) c.setPosition(0) self.marked_text = marked_text self.display.setTextCursor(c) def next_page(self): self.page_count += 1 self.display.setPlainText(f'This is page number {self.page_count}. Pages are turned automatically when the end of a page is reached.') self.create_marked_text() def update_play_action(self, text): self.play_action.setText(text) def state_event(self, ev: Literal['begin', 'end', 'cancel', 'pause', 'resume']): sb = self.statusBar() events = sb.currentMessage().split() events.append(ev) if len(events) > 16: del events[0] self.statusBar().showMessage(' '.join(events)) self.stop_action.setEnabled(ev in ('pause', 'resume', 'begin')) if ev == 'cancel': self.update_play_action('Play') elif ev == 'pause': self.update_play_action('Resume') elif ev in ('resume', 'begin'): self.update_play_action('Pause') elif ev == 'end': if self.play_action.text() == 'Pause': self.next_page() self.update_play_action('Play') self.play_triggerred() def play_triggerred(self): if self.play_action.text() == 'Resume': self.tts.resume() elif self.play_action.text() == 'Pause': self.tts.pause() else: self.tts.speak_marked_text(self.marked_text) def saying(self, first, last): c = self.display.textCursor() c.setPosition(first) if last != first: c.setPosition(last, QTextCursor.MoveMode.KeepAnchor) c.movePosition(QTextCursor.MoveOperation.WordRight, QTextCursor.MoveMode.KeepAnchor) self.display.setTextCursor(c) def sizeHint(self): return QSize(500, 400) def main(): app = Application([]) mw = MainWindow(TEXT) mw.set_exception_handler() mw.show() app.exec() if __name__ == '__main__': main()
4,879
Python
.py
117
33.401709
142
0.643038
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,755
piper.py
kovidgoyal_calibre/src/calibre/gui2/tts/piper.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net> import atexit import io import json import os import re import sys from collections import deque from contextlib import suppress from dataclasses import dataclass from functools import lru_cache from itertools import count from time import monotonic from typing import BinaryIO, Iterable, Iterator from qt.core import ( QAudio, QAudioFormat, QAudioSink, QByteArray, QIODevice, QIODeviceBase, QMediaDevices, QObject, QProcess, Qt, QTextToSpeech, QWidget, pyqtSignal, sip, ) from calibre.constants import cache_dir, is_debugging, iswindows, piper_cmdline from calibre.gui2 import error_dialog from calibre.gui2.tts.types import TTS_EMBEDED_CONFIG, EngineSpecificSettings, Quality, TTSBackend, Voice, widget_parent from calibre.spell.break_iterator import PARAGRAPH_SEPARATOR, split_into_sentences_for_tts from calibre.utils.filenames import ascii_text from calibre.utils.localization import canonicalize_lang, get_lang from calibre.utils.resources import get_path as P HIGH_QUALITY_SAMPLE_RATE = 22050 def debug(*a, **kw): if is_debugging(): if not hasattr(debug, 'first'): debug.first = monotonic() kw['end'] = kw.get('end', '\r\n') print(f'[{monotonic() - debug.first:.2f}]', *a, **kw) def audio_format(audio_rate: int = HIGH_QUALITY_SAMPLE_RATE) -> QAudioFormat: fmt = QAudioFormat() fmt.setSampleFormat(QAudioFormat.SampleFormat.Int16) fmt.setSampleRate(audio_rate) fmt.setChannelConfig(QAudioFormat.ChannelConfig.ChannelConfigMono) return fmt def piper_process_metadata(model_path, config_path, s: EngineSpecificSettings, voice: Voice) -> tuple[int, list[str]]: if not model_path: raise Exception('Could not download voice data') if 'metadata' not in voice.engine_data: with open(config_path) as f: voice.engine_data['metadata'] = json.load(f) audio_rate = voice.engine_data['metadata']['audio']['sample_rate'] length_scale = max(0.1, 1 + -1 * s.rate) # maps -1 to 1 to 2 to 0.1 cmdline = list(piper_cmdline()) + [ '--model', model_path, '--config', config_path, '--output-raw', '--json-input', '--sentence-silence', str(s.sentence_delay), '--length_scale', str(length_scale)] if is_debugging(): cmdline.append('--debug') return audio_rate, cmdline def piper_cache_dir() -> str: return os.path.join(cache_dir(), 'piper-voices') def paths_for_voice(voice: Voice) -> tuple[str, str]: fname = voice.engine_data['model_filename'] model_path = os.path.join(piper_cache_dir(), fname) config_path = os.path.join(os.path.dirname(model_path), fname + '.json') return model_path, config_path def load_voice_metadata() -> tuple[dict[str, Voice], tuple[Voice, ...], dict[str, Voice], dict[str, Voice]]: d = json.loads(P('piper-voices.json', data=True)) ans = [] lang_voices_map = {} _voice_name_map = {} human_voice_name_map = {} downloaded = set() with suppress(OSError): downloaded = set(os.listdir(piper_cache_dir())) for bcp_code, voice_map in d['lang_map'].items(): lang, sep, country = bcp_code.partition('_') lang = canonicalize_lang(lang) or lang voices_for_lang = lang_voices_map.setdefault(lang, []) for voice_name, qual_map in voice_map.items(): best_qual = voice = None for qual, e in qual_map.items(): q = Quality.from_piper_quality(qual) if best_qual is None or q.value < best_qual.value: best_qual = q mf = f'{bcp_code}-{ascii_text(voice_name)}-{qual}.onnx' voice = Voice(bcp_code + ':' + voice_name, lang, country, human_name=voice_name, quality=q, engine_data={ 'model_url': e['model'], 'config_url': e['config'], 'model_filename': mf, 'is_downloaded': mf in downloaded, }) if voice: ans.append(voice) _voice_name_map[voice.name] = human_voice_name_map[voice.human_name] = voice voices_for_lang.append(voice) _voices = tuple(ans) _voice_for_lang = {} for lang, voices in lang_voices_map.items(): voices.sort(key=lambda v: v.quality.value) _voice_for_lang[lang] = voices[0] if lang == 'eng': for v in voices: if v.human_name == 'libritts': _voice_for_lang[lang] = v break return _voice_name_map, _voices, _voice_for_lang, human_voice_name_map def download_voice(voice: Voice, download_even_if_exists: bool = False, parent: QObject | None = None, headless: bool = False) -> tuple[str, str]: model_path, config_path = paths_for_voice(voice) if os.path.exists(model_path) and os.path.exists(config_path): if not download_even_if_exists: return model_path, config_path os.makedirs(os.path.dirname(model_path), exist_ok=True) from calibre.gui2.tts.download import download_resources ok = download_resources(_('Downloading voice for Read aloud'), _('Downloading neural network for the {} voice').format(voice.human_name), { voice.engine_data['model_url']: (model_path, _('Neural network data')), voice.engine_data['config_url']: (config_path, _('Neural network metadata')), }, parent=widget_parent(parent), headless=headless, ) voice.engine_data['is_downloaded'] = bool(ok) return (model_path, config_path) if ok else ('', '') @dataclass class Utterance: id: int start: int length: int payload_size: int left_to_write: QByteArray audio_data: QByteArray started: bool = False synthesized: bool = False UTTERANCE_SEPARATOR = b'\n' class UtteranceAudioQueue(QIODevice): saying = pyqtSignal(int, int) update_status = pyqtSignal() def __init__(self, parent: QObject | None = None): super().__init__(parent) self.utterances: deque[Utterance] = deque() self.current_audio_data = QByteArray() self.audio_state = QAudio.State.IdleState self.utterance_being_played: Utterance | None = None self.open(QIODeviceBase.OpenModeFlag.ReadOnly) def audio_state_changed(self, s: QAudio.State) -> None: debug('Audio state:', s) prev_state, self.audio_state = self.audio_state, s if s == prev_state: return if s == QAudio.State.IdleState and prev_state == QAudio.State.ActiveState: if self.utterance_being_played: debug(f'Utterance {self.utterance_being_played.id} audio output finished') self.utterance_being_played = None self.start_utterance() self.update_status.emit() def add_utterance(self, u: Utterance) -> None: self.utterances.append(u) if not self.utterance_being_played: self.start_utterance() def start_utterance(self): if self.utterances: u = self.utterances.popleft() self.current_audio_data = u.audio_data self.utterance_being_played = u self.readyRead.emit() self.saying.emit(u.start, u.length) def close(self): self.utterances.clear() self.current_audio_data = QByteArray() self.utterance_being_played = None return super().close() def clear(self): self.utterances.clear() self.utterance_being_played = None self.current_audio_data = QByteArray() self.audio_state = QAudio.State.IdleState def atEnd(self) -> bool: return not len(self.current_audio_data) def bytesAvailable(self) -> int: return len(self.current_audio_data) def __bool__(self) -> bool: return bool(self.utterances) or self.utterance_being_played is not None def isSequential(self) -> bool: return True def seek(self, pos): return False def readData(self, maxlen: int) -> QByteArray: if maxlen < 1: debug(f'Audio data sent to output: {maxlen=}') return QByteArray() if maxlen >= len(self.current_audio_data): ans = self.current_audio_data self.current_audio_data = QByteArray() else: ans = self.current_audio_data.first(maxlen) self.current_audio_data = self.current_audio_data.last(len(self.current_audio_data) - maxlen) if len(self.current_audio_data): self.readyRead.emit() debug(f'Audio sent to output: {maxlen=} {len(ans)=}') return ans def split_into_utterances(text: str, counter: count, lang: str = 'en'): for start, sentence in split_into_sentences_for_tts(text, lang): payload = json.dumps({'text': sentence}).encode('utf-8') ba = QByteArray() ba.reserve(len(payload) + 1) ba.append(payload) ba.append(UTTERANCE_SEPARATOR) u = Utterance(id=next(counter), payload_size=len(ba), audio_data=QByteArray(), left_to_write=ba, start=start, length=len(sentence)) debug(f'Utterance created {u.id} {start=}: {sentence!r}') yield u @lru_cache(2) def stderr_pat(): return re.compile(rb'\[piper\] \[([a-zA-Z0-9_]+?)\] (.+)') def detect_end_of_data(data: bytes, callback): lines = data.split(b'\n') for line in lines[:-1]: if m := stderr_pat().search(line): which, payload = m.group(1), m.group(2) if which == b'info': debug(f'[piper-info] {payload.decode("utf-8", "replace")}') if payload.startswith(b'Real-time factor:'): callback(True, None) elif which == b'error': callback(False, payload.decode('utf-8', 'replace')) elif which == b'debug': debug(f'[piper-debug] {payload.decode("utf-8", "replace")}') return lines[-1] class Piper(TTSBackend): engine_name: str = 'piper' filler_char: str = PARAGRAPH_SEPARATOR _synthesis_done = pyqtSignal() def __init__(self, engine_name: str = '', parent: QObject | None = None): super().__init__(parent) self._process: QProcess | None = None self._audio_sink: QAudioSink | None = None self._current_voice: Voice | None = None self._utterances_being_synthesized: deque[Utterance] = deque() self._utterance_counter = count(start=1) self._utterances_being_spoken = UtteranceAudioQueue() self._utterances_being_spoken.saying.connect(self.saying) self._utterances_being_spoken.update_status.connect(self._update_status, type=Qt.ConnectionType.QueuedConnection) self._state = QTextToSpeech.State.Ready self._voices = self._voice_for_lang = None self._last_error = '' self._errors_from_piper: list[str] = [] self._pending_stderr_data = b'' self._synthesis_done.connect(self._utterance_synthesized, type=Qt.ConnectionType.QueuedConnection) atexit.register(self.shutdown) @property def available_voices(self) -> dict[str, tuple[Voice, ...]]: self._load_voice_metadata() return {'': self._voices} def _wait_for_process_to_start(self) -> bool: if not self.process.waitForStarted(): cmdline = [self.process.program()] + self.process.arguments() if self.process.error() is QProcess.ProcessError.TimedOut: self._set_error(f'Timed out waiting for piper process {cmdline} to start') else: self._set_error(f'Failed to start piper process: {cmdline}') return False return True def say(self, text: str) -> None: if self._last_error: return self.stop() if not self._wait_for_process_to_start(): return lang = 'en' if self._current_voice and self._current_voice.language_code: lang = self._current_voice.language_code self._utterances_being_synthesized.extend(split_into_utterances(text, self._utterance_counter, lang)) self._write_current_utterance() def pause(self) -> None: if self._audio_sink is not None: self._audio_sink.suspend() def resume(self) -> None: if self._audio_sink is not None: self._audio_sink.resume() def stop(self) -> None: if self._process is not None: if self._state is not QTextToSpeech.State.Ready or self._utterances_being_synthesized or self._utterances_being_spoken: self.shutdown() # We cannot re-create self.process here as that will cause the # audio device to go to active state which will cause a # speaking event to be generated def shutdown(self) -> None: if self._process is not None: self._audio_sink.stateChanged.disconnect() self._process.readyReadStandardError.disconnect() self._process.bytesWritten.disconnect() self._process.readyReadStandardOutput.disconnect() self._process.stateChanged.disconnect() self._process.kill() self._process.waitForFinished(-1) # this dance is needed otherwise stop() is very slow on Linux self._audio_sink.suspend() self._audio_sink.reset() self._audio_sink.stop() sip.delete(self._audio_sink) sip.delete(self._process) self._process = self._audio_sink = None self._set_state(QTextToSpeech.State.Ready) def reload_after_configure(self) -> None: self.shutdown() @property def state(self) -> QTextToSpeech.State: return self._state def error_message(self) -> str: return self._last_error def _set_state(self, s: QTextToSpeech.State) -> None: if self._state is not s: self._state = s self.state_changed.emit(s) def _set_error(self, msg: str) -> None: self._last_error = msg self._set_state(QTextToSpeech.State.Error) @property def process(self) -> QProcess: if self._process is None: model_path = config_path = '' try: self._load_voice_metadata() s = EngineSpecificSettings.create_from_config(self.engine_name) voice = self._voice_name_map.get(s.voice_name) or self._default_voice model_path, config_path = self._ensure_voice_is_downloaded(voice) except AttributeError as e: raise Exception(str(e)) from e self._current_voice = voice self._utterances_being_spoken.clear() self._utterances_being_synthesized.clear() self._errors_from_piper.clear() self._process = QProcess(self) self._pending_stderr_data = b'' self._set_state(QTextToSpeech.State.Ready) audio_rate, cmdline = piper_process_metadata(model_path, config_path, s, voice) self._process.setProgram(cmdline[0]) self._process.setArguments(cmdline[1:]) debug('Running piper:', cmdline) self._process.readyReadStandardError.connect(self.piper_stderr_available) self._process.readyReadStandardOutput.connect(self.piper_stdout_available) self._process.bytesWritten.connect(self.bytes_written) self._process.stateChanged.connect(self._update_status) fmt = audio_format(audio_rate) dev = None if s.audio_device_id: for q in QMediaDevices.audioOutputs(): if bytes(q.id()) == s.audio_device_id.id: dev = q break if dev: self._audio_sink = QAudioSink(dev, fmt, self) else: self._audio_sink = QAudioSink(fmt, self) if s.volume is not None: self._audio_sink.setVolume(s.volume) # On Windows, the buffer is zero causing data to be discarded. # Ensure we have a nice large buffer on all platforms. # However, on Linux and macOS changing the buffer size causes audio to not # play on some systems or play with a large delay. # See https://www.mobileread.com/forums/showthread.php?t=363881 # and https://www.mobileread.com/forums/showthread.php?t=364225 if iswindows: self._audio_sink.setBufferSize(2 * 1024 * 1024) self._audio_sink.stateChanged.connect(self._utterances_being_spoken.audio_state_changed) self._process.start() self._audio_sink.start(self._utterances_being_spoken) return self._process def piper_stdout_available(self) -> None: if self._utterances_being_synthesized: u = self._utterances_being_synthesized[0] while True: ba = self.process.readAll() if not len(ba): break debug('Synthesized data read:', len(ba), 'bytes') u.audio_data.append(ba) def piper_stderr_available(self) -> None: if self._process is not None: def callback(ok, payload): if ok: if self._utterances_being_synthesized: self._synthesis_done.emit() else: self._errors_from_piper.append(payload.decode('utf-8', 'replace')) data = self._pending_stderr_data + bytes(self._process.readAllStandardError()) self._pending_stderr_data = detect_end_of_data(data, callback) def _utterance_synthesized(self): self.piper_stdout_available() # just in case u = self._utterances_being_synthesized.popleft() u.synthesized = True debug(f'Utterance {u.id} got {len(u.audio_data)} bytes of audio data from piper') if len(u.audio_data): self._utterances_being_spoken.add_utterance(u) self._write_current_utterance() self._update_status() def _update_status(self): if self._process is not None and self._process.state() is QProcess.ProcessState.NotRunning: if self._process.exitStatus() is not QProcess.ExitStatus.NormalExit or self._process.exitCode(): m = '\n'.join(self._errors_from_piper) self._set_error(f'piper process failed with exit code: {self._process.exitCode()} and error messages: {m}') return if self._state is QTextToSpeech.State.Error: return state = self._utterances_being_spoken.audio_state if state is QAudio.State.ActiveState: self._set_state(QTextToSpeech.State.Speaking) elif state is QAudio.State.SuspendedState: self._set_state(QTextToSpeech.State.Paused) elif state is QAudio.State.StoppedState: if self._audio_sink.error() not in (QAudio.Error.NoError, QAudio.Error.UnderrunError): self._set_error(f'Audio playback failed with error: {self._audio_sink.error()}') else: if self._state is not QTextToSpeech.State.Error: self._set_state(QTextToSpeech.State.Ready) elif state is QAudio.State.IdleState: if not self._utterances_being_synthesized and not self._utterances_being_spoken: self._set_state(QTextToSpeech.State.Ready) def bytes_written(self, count: int) -> None: self._write_current_utterance() def _write_current_utterance(self) -> None: if self._utterances_being_synthesized: u = self._utterances_being_synthesized[0] while len(u.left_to_write): written = self.process.write(u.left_to_write) if written < 0: self._set_error('Failed to write to piper process with error: {self.process.errorString()}') break if not u.started and written: u.started = True debug(f'Utterance {u.id} synthesis started') u.left_to_write = u.left_to_write.last(len(u.left_to_write) - written) def audio_sink_state_changed(self, state: QAudio.State) -> None: self._update_status() def _load_voice_metadata(self) -> None: if self._voices is not None: return self._voice_name_map, self._voices, self._voice_for_lang, self.human_voice_name_map = load_voice_metadata() @property def _default_voice(self) -> Voice: self._load_voice_metadata() lang = get_lang() lang = canonicalize_lang(lang) or lang return self._voice_for_lang.get(lang) or self._voice_for_lang['eng'] @property def cache_dir(self) -> str: return piper_cache_dir() def is_voice_downloaded(self, v: Voice) -> bool: if not v or not v.name: v = self._default_voice for path in paths_for_voice(v): if not os.path.exists(path): return False return True def delete_voice(self, v: Voice) -> None: if not v.name: v = self._default_voice for path in paths_for_voice(v): with suppress(FileNotFoundError): os.remove(path) v.engine_data['is_downloaded'] = False def _download_voice(self, voice: Voice, download_even_if_exists: bool = False) -> tuple[str, str]: return download_voice(voice, download_even_if_exists, parent=self, headless=False) def download_voice(self, v: Voice) -> None: if not v.name: v = self._default_voice self._download_voice(v, download_even_if_exists=True) def _ensure_voice_is_downloaded(self, voice: Voice) -> tuple[str, str]: return self._download_voice(voice) def validate_settings(self, s: EngineSpecificSettings, parent: QWidget | None) -> bool: self._load_voice_metadata() voice = self._voice_name_map.get(s.voice_name) or self._default_voice try: m, c = self._ensure_voice_is_downloaded(voice) if not m: error_dialog(parent, _('Failed to download voice'), _('Failed to download the voice: {}').format(voice.human_name), show=True) return False except Exception: import traceback error_dialog(parent, _('Failed to download voice'), _('Failed to download the voice: {}').format(voice.human_name), det_msg=traceback.format_exc(), show=True) return False return True class PiperEmbedded: def __init__(self): self._embedded_settings = EngineSpecificSettings.create_from_config('piper', TTS_EMBEDED_CONFIG) self._voice_name_map, self._voices, self._voice_for_lang, self.human_voice_name_map = load_voice_metadata() lang = get_lang() lang = canonicalize_lang(lang) or lang self._default_voice = self._voice_for_lang.get(lang) or self._voice_for_lang['eng'] self._current_voice = self._process = self._pipe_reader = None self._current_audio_rate = 0 def resolve_voice(self, lang: str, voice_name: str) -> Voice: from calibre.utils.localization import canonicalize_lang, get_lang lang = canonicalize_lang(lang or get_lang() or 'en') pv = self._embedded_settings.preferred_voices or {} if voice_name and voice_name in self.human_voice_name_map: voice = self.human_voice_name_map[voice_name] elif (voice_name := pv.get(lang, '')) and voice_name in self.human_voice_name_map: voice = self.human_voice_name_map[voice_name] else: voice = self._voice_for_lang.get(lang) or self._default_voice return voice def text_to_raw_audio_data( self, texts: Iterable[str], lang: str = '', voice_name: str = '', sample_rate: int = HIGH_QUALITY_SAMPLE_RATE, timeout: float = 10., ) -> Iterator[tuple[bytes, float]]: voice = self.resolve_voice(lang, voice_name) if voice is not self._current_voice: self._current_voice = voice self.shutdown() self.ensure_process_started() piper_done, errors_from_piper = [], [] needs_conversion = sample_rate != self._current_audio_rate if needs_conversion: from calibre_extensions.ffmpeg import resample_raw_audio_16bit def callback(ok, payload): if ok: piper_done.append(True) else: errors_from_piper.append(payload.decode('utf-8', 'replace')) for text in texts: text = text.strip() if not text: yield b'', 0. continue payload = json.dumps({'text': text}).encode('utf-8') self._process.stdin.write(payload) self._process.stdin.write(UTTERANCE_SEPARATOR) self._process.stdin.flush() stderr_data = b'' buf = io.BytesIO() piper_done, errors_from_piper = [], [] def stderr_callback(data: bytes) -> bool: nonlocal stderr_data stderr_data = detect_end_of_data(stderr_data + data, callback) return not piper_done try: self._pipe_reader(buf.write, stderr_callback) except Exception as e: raise Exception(f'Reading output from piper process failed with error: {e} and STDERR: ' + '\n'.join(errors_from_piper)) raw_data = buf.getvalue() if needs_conversion: raw_data = resample_raw_audio_16bit(raw_data, self._current_audio_rate, sample_rate) yield raw_data, duration_of_raw_audio_data(raw_data, sample_rate) def ensure_voices_downloaded(self, specs: Iterable[tuple[str, str]], parent: QObject = None) -> bool: for lang, voice_name in specs: voice = self.resolve_voice(lang, voice_name) m, c = download_voice(voice, parent=parent, headless=parent is None) if not m: return False return True def shutdown(self): if self._process is not None: self._pipe_reader.close() self._pipe_reader = None self._process.stdin.close() self._process.stdout.close() self._process.stderr.close() self._process.kill() self._process.wait() self._process = None __del__ = shutdown def ensure_process_started(self): if self._process is not None: return model_path, config_path = download_voice(self._current_voice, headless=True) self._current_audio_rate, cmdline = piper_process_metadata(model_path, config_path, self._embedded_settings, self._current_voice) import subprocess self._process = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) self._pipe_reader = (ThreadedPipeReader if iswindows else PipeReader)(self._process.stdout, self._process.stderr) class PipeReader: TIMEOUT = 10. # seconds def __init__(self, stdout: BinaryIO, stderr: BinaryIO): self.stdout_fd = stdout.fileno() self.stderr_fd = stderr.fileno() os.set_blocking(self.stdout_fd, False) os.set_blocking(self.stderr_fd, False) def close(self): self.stderr_fd = self.stdout_fd = -1 def __call__(self, stdout_callback, stderr_callback): from select import select out, err = self.stdout_fd, self.stderr_fd readers = out, err buf = memoryview(bytearray(io.DEFAULT_BUFFER_SIZE)) def readall(fd: int) -> bytes: output = io.BytesIO() while True: try: num = os.readv(fd, (buf,)) except BlockingIOError: break else: output.write(buf[:num]) return output.getvalue() def readinto(fd: int, callback) -> None: while True: try: num = os.readv(fd, (buf,)) except BlockingIOError: break else: callback(buf[:num]) while True: r, _, _ = select(readers, (), (), self.TIMEOUT) if not r: raise TimeoutError('Timed out waiting for output from piper process') if out in r: readinto(out, stdout_callback) if err in r: data = readall(err) if not stderr_callback(data): # In case there is new data written to stdout readinto(out, stdout_callback) break class ThreadedPipeReader(PipeReader): def __init__(self, stdout: BinaryIO, stderr: BinaryIO): from queue import Queue from threading import Event, Thread self.shutting_down = Event() self.queue = Queue() Thread(target=self._reader, args=(stdout.fileno(), True), daemon=True).start() Thread(target=self._reader, args=(stderr.fileno(), False), daemon=True).start() def close(self): self.shutting_down.set() def __call__(self, stdout_callback, stderr_callback): from queue import Empty while True: data, is_stdout, err = self.queue.get(True, self.TIMEOUT) if err is not None: raise err if data: if is_stdout: stdout_callback(data) else: if not stderr_callback(data): # in case more data was written to stdout while True: try: data, is_stdout, err = self.queue.get_nowait() except Empty: break if err is not None: raise err if is_stdout: stdout_callback(data) break def _reader(self, pipe_fd: int, is_stdout: bool): while not self.shutting_down.is_set(): try: data = os.read(pipe_fd, io.DEFAULT_BUFFER_SIZE) except OSError as e: if not self.shutting_down.is_set(): self.queue.put((b'', is_stdout, e)) break else: self.queue.put((data, is_stdout, None)) def duration_of_raw_audio_data(data: bytes, sample_rate: int = HIGH_QUALITY_SAMPLE_RATE, bytes_per_sample: int = 2, num_channels: int = 1) -> float: total_num_of_samples = len(data) / bytes_per_sample num_of_samples_per_channel = total_num_of_samples / num_channels return num_of_samples_per_channel / sample_rate # develop {{{ def develop_embedded(): import subprocess from calibre.utils.speedups import ReadOnlyFileBuffer from calibre_extensions.ffmpeg import transcode_single_audio_stream, wav_header_for_pcm_data p = PiperEmbedded() all_data = [b''] sz = 0 for data, duration in p.text_to_raw_audio_data(( 'Hello, good day to you.', 'This is the second sentence.', 'This is the final sentence.' )): print(f'{duration=} {len(data)=}') all_data.append(data) sz += len(data) all_data[0] = wav_header_for_pcm_data(sz, HIGH_QUALITY_SAMPLE_RATE) wav = ReadOnlyFileBuffer(b''.join(all_data), name='tts.wav') m4a = io.BytesIO() m4a.name = 'tts.m4a' transcode_single_audio_stream(wav, m4a) subprocess.run(['mpv', '-'], input=m4a.getvalue()) def develop(): from qt.core import QSocketNotifier from calibre.gui2 import Application app = Application([]) p = Piper() play_started = False def state_changed(s): nonlocal play_started debug('TTS State:', s) if s is QTextToSpeech.State.Error: debug(p.error_message(), file=sys.stderr) app.exit(1) elif s is QTextToSpeech.State.Speaking: play_started = True elif s is QTextToSpeech.State.Ready: if play_started: debug('Quitting on completion') app.quit() def input_ready(): nonlocal play_started q = sys.stdin.buffer.read() if q in (b'\x03', b'\x1b'): app.exit(1) elif q == b' ': if p.state is QTextToSpeech.State.Speaking: p.pause() elif p.state is QTextToSpeech.State.Paused: p.resume() elif q == b'r': debug('Stopping') play_started = False p.stop() p.say(text) text = ( 'First, relatively short sentence. ' 'Second, much longer sentence which hopefully finishes synthesizing before the first finishes speaking. ' 'Third, and final short sentence.' ) # text = f'Hello world{PARAGRAPH_SEPARATOR}.{PARAGRAPH_SEPARATOR}Bye world' def saying(offset, length): debug('Saying:', repr(text[offset:offset+length])) p.state_changed.connect(state_changed) p.saying.connect(saying) if not iswindows: import tty attr = tty.setraw(sys.stdin.fileno()) os.set_blocking(sys.stdin.fileno(), False) sn = QSocketNotifier(sys.stdin.fileno(), QSocketNotifier.Type.Read, p) sn.activated.connect(input_ready) try: p.say(text) app.exec() finally: if not iswindows: import termios termios.tcsetattr(sys.stdout.fileno(), termios.TCSANOW, attr) if __name__ == '__main__': develop() # }}}
34,019
Python
.py
741
35.45614
148
0.605598
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,756
download.py
kovidgoyal_calibre/src/calibre/gui2/tts/download.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net> import os import tempfile from contextlib import suppress from qt.core import ( QDialog, QDialogButtonBox, QFileInfo, QLabel, QNetworkAccessManager, QNetworkReply, QNetworkRequest, QProgressBar, QScrollArea, Qt, QTimeZone, QUrl, QVBoxLayout, QWidget, pyqtSignal, ) from calibre import human_readable from calibre.gui2 import error_dialog from calibre.utils.localization import ngettext class ProgressBar(QWidget): done = pyqtSignal(str) def __init__(self, qurl: QUrl, path: str, nam: QNetworkAccessManager, text: str, parent: QWidget | None): super().__init__(parent) self.l = l = QVBoxLayout(self) self.la = la = QLabel(text) la.setWordWrap(True) l.addWidget(la) self.pb = pb = QProgressBar(self) pb.setTextVisible(True) pb.setMinimum(0), pb.setMaximum(0) l.addWidget(pb) self.qurl = qurl self.desc = text self.path = path self.file_obj = tempfile.NamedTemporaryFile('wb', dir=os.path.dirname(self.path), delete=False) req = QNetworkRequest(qurl) fi = QFileInfo(self.path) if fi.exists(): req.setHeader(QNetworkRequest.KnownHeaders.IfModifiedSinceHeader, fi.lastModified(QTimeZone(QTimeZone.Initialization.UTC))) self.reply = reply = nam.get(req) self.over_reported = False reply.downloadProgress.connect(self.on_download) reply.errorOccurred.connect(self.on_error) reply.finished.connect(self.finished) reply.readyRead.connect(self.data_received) def data_received(self): try: self.file_obj.write(self.reply.readAll()) except Exception as e: self.on_over(_('Failed to write downloaded data with error: {}').format(e)) def on_error(self, ec: QNetworkReply.NetworkError) -> None: self.on_over(_('Failed to write downloaded data with error: {}').format(self.reply.errorString())) def on_over(self, err_msg: str = '') -> None: if self.over_reported: return self.over_reported = True with suppress(Exception): self.file_obj.close() if err_msg: with suppress(OSError): os.remove(self.file_obj.name) else: code = self.reply.attribute(QNetworkRequest.Attribute.HttpStatusCodeAttribute) if code == 200: os.replace(self.file_obj.name, self.path) else: with suppress(OSError): os.remove(self.file_obj.name) if code != 304: # 304 is Not modified err_msg = _('Server replied with unknown HTTP status code: {}').format(code) self.done.emit(err_msg) def on_download(self, received: int, total: int) -> None: if total > 0: self.pb.setMaximum(total) self.pb.setValue(received) t = human_readable(total) r = human_readable(received) self.pb.setFormat(f'%p% {r} of {t}') def finished(self): self.pb.setMaximum(100) self.pb.setValue(100) self.pb.setFormat(_('Download finished')) self.on_over() class DownloadResources(QDialog): def __init__(self, title: str, message: str, urls: dict[str, tuple[str, str]], parent: QWidget | None = None): super().__init__(parent) self.setWindowTitle(title) self.l = l = QVBoxLayout(self) self.la = la = QLabel(message) la.setWordWrap(True) l.addWidget(la) self.scroll_area = sa = QScrollArea(self) sa.setWidgetResizable(True) l.addWidget(sa) self.central = central = QWidget(sa) central.l = QVBoxLayout(central) sa.setWidget(central) self.todo = set() self.bars = [] self.failures = [] self.nam = nam = QNetworkAccessManager(self) for url, (path, desc) in urls.items(): qurl = QUrl(url) self.todo.add(qurl) pb = ProgressBar(qurl, path, nam, desc, self) pb.done.connect(self.on_done, type=Qt.ConnectionType.QueuedConnection) central.l.addWidget(pb) self.bars.append(pb) self.bb = bb = QDialogButtonBox(QDialogButtonBox.Cancel, self) bb.rejected.connect(self.reject) l.addWidget(bb) sz = self.sizeHint() sz.setWidth(max(500, sz.width())) self.resize(sz) def on_done(self, err_msg: str): pb = self.sender() self.todo.discard(pb.qurl) if err_msg: self.failures.append(_('Failed to download {0} with error: {1}').format(pb.desc, err_msg)) if not self.todo: if self.failures: if len(self.failures) == len(self.bars): msg = ngettext(_('Could not download {}.'), _('Could not download any of the resources.'), len(self.bars)).format(self.bars[0].desc) else: msg = _('Could not download some resources.') error_dialog( self, _('Download failed'), msg + ' ' + _('Click "Show details" for more information'), det_msg='\n\n'.join(self.failures), show=True) self.reject() else: self.accept() def reject(self): for pb in self.bars: pb.blockSignals(True) pb.reply.abort() super().reject() def download_resources( title: str, message: str, urls: dict[str, tuple[str, str]], parent: QWidget | None = None, headless: bool = False ) -> bool: if not headless: d = DownloadResources(title, message, urls, parent=parent) return d.exec() == QDialog.DialogCode.Accepted from calibre import browser print(title) print(message) br = browser() for url, (path, name) in urls.items(): print(_('Downloading {}...').format(name)) data = br.open_novisit(url).read() with open(path, 'wb') as f: f.write(data) return True def develop(): from calibre.gui2 import Application app = Application([]) urls = { 'https://huggingface.co/rhasspy/piper-voices/resolve/v1.0.0/en/en_US/lessac/medium/en_US-lessac-medium.onnx': ( '/tmp/model', 'Voice neural network'), 'https://huggingface.co/rhasspy/piper-voices/resolve/v1.0.0/en/en_US/lessac/medium/en_US-lessac-medium.onnx.json': ( '/tmp/config', 'Voice configuration'), } d = DownloadResources('Test download resources', 'Downloading voice data', urls) d.exec() del d del app if __name__ == '__main__': develop()
6,812
Python
.py
173
30.410405
152
0.605928
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,757
config.py
kovidgoyal_calibre/src/calibre/gui2/tts/config.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net> from qt.core import ( QAbstractItemView, QCheckBox, QDialog, QDoubleSpinBox, QFont, QFormLayout, QHBoxLayout, QIcon, QLabel, QLocale, QMediaDevices, QPushButton, QSize, QSlider, QStyle, QStyleOptionViewItem, Qt, QTreeWidget, QTreeWidgetItem, QVBoxLayout, QWidget, pyqtSignal, ) from calibre.gui2.tts.types import ( TTS_EMBEDED_CONFIG, AudioDeviceId, EngineMetadata, EngineSpecificSettings, Voice, available_engines, create_tts_backend, default_engine_name, load_config, ) from calibre.gui2.widgets2 import Dialog, QComboBox class EngineChoice(QWidget): changed = pyqtSignal(str) def __init__(self, parent): super().__init__(parent) self.l = l = QFormLayout(self) self.engine_choice = ec = QComboBox(self) l.addRow(_('Text-to-Speech &engine:'), ec) configured_engine_name = load_config().get('engine', '') am = available_engines() ec.addItem(_('Automatically select (currently {})').format(am[default_engine_name()].human_name), '') for engine_name, metadata in am.items(): ec.addItem(metadata.human_name, engine_name) idx = ec.findData(configured_engine_name) if idx > -1: ec.setCurrentIndex(idx) self.engine_description = la = QLabel(self) la.setWordWrap(True) l.addRow(la) ec.currentIndexChanged.connect(self.current_changed) self.update_description() @property def value(self) -> str: return self.engine_choice.currentData() def current_changed(self): self.changed.emit(self.value) self.update_description() def update_description(self): engine = self.value or default_engine_name() metadata = available_engines()[engine] self.engine_description.setText(metadata.description) class SentenceDelay(QDoubleSpinBox): def __init__(self, parent=None): super().__init__(parent) self.setRange(0., 2.) self.setDecimals(2) self.setSuffix(_(' seconds')) self.setToolTip(_('The number of seconds to pause for at the end of a sentence.')) self.setSpecialValueText(_('no pause')) self.setSingleStep(0.05) @property def val(self) -> str: return max(0.0, self.value()) @val.setter def val(self, v) -> None: self.setValue(float(v)) class FloatSlider(QSlider): def __init__(self, minimum: float = -1, maximum: float = 1, factor: int = 10, parent=None): super().__init__(parent) self.factor = factor self.setRange(int(minimum * factor), int(maximum * factor)) self.setSingleStep(int((self.maximum() - self.minimum()) / (2 * factor))) self.setPageStep(5 * self.singleStep()) self.setTickPosition(QSlider.TickPosition.TicksBelow) self.setOrientation(Qt.Orientation.Horizontal) if maximum - minimum >= 2: self.setTickInterval((self.maximum() - self.minimum()) // 2) else: self.setTickInterval(self.maximum() - self.minimum()) def sizeHint(self) -> QSize: ans = super().sizeHint() ans.setWidth(ans.width() * 2) return ans @property def val(self) -> float: return self.value() / self.factor @val.setter def val(self, v) -> None: self.setValue(int(v * self.factor)) class Volume(QWidget): def __init__(self, parent=None): super().__init__(parent) self.l = l = QFormLayout(self) l.setContentsMargins(0, 0, 0, 0) self.system = e = QCheckBox(_('Use system default volume'), self) l.addRow(e) self.vol = v = FloatSlider(minimum=0, parent=self) l.addRow(_('&Volume of speech:'), v) e.toggled.connect(self.update_state) self.update_state() def update_state(self): self.layout().setRowVisible(self.vol, not self.system.isChecked()) @property def val(self): if self.system.isChecked(): return None return self.vol.val @val.setter def val(self, v): self.system.setChecked(v is None) self.vol.val = 0.5 if v is None else v class Voices(QTreeWidget): voice_changed = pyqtSignal() def __init__(self, parent=None, for_embedding=False): self.for_embedding = for_embedding super().__init__(parent) self.setHeaderHidden(True) self.system_default_voice = Voice() self.currentItemChanged.connect(self.voice_changed) self.normal_font = f = self.font() self.highlight_font = f = QFont(f) f.setBold(True), f.setItalic(True) self.ignore_item_changes = False if self.for_embedding: self.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection) self.itemChanged.connect(self.item_changed) def item_changed(self, item: QTreeWidgetItem, column: int): if column == 0 and self.is_voice_item(item) and not self.ignore_item_changes: if item.checkState(0) == Qt.CheckState.Checked: p = item.parent() if p is not None: for child in (p.child(i) for i in range(p.childCount())): if child is not item and child.checkState(0) == Qt.CheckState.Checked: self.ignore_item_changes = True child.setCheckState(0, Qt.CheckState.Unchecked) self.ignore_item_changes = False def is_voice_item(self, item): return item is not None and isinstance(item.data(0, Qt.ItemDataRole.UserRole), Voice) def mousePressEvent(self, event): item = self.itemAt(event.pos()) if self.for_embedding and self.is_voice_item(item): rect = self.visualItemRect(item) x = event.pos().x() - (rect.x() + self.frameWidth()) option = QStyleOptionViewItem() self.initViewItemOption(option) option.rect = rect option.features |= QStyleOptionViewItem.ViewItemFeature.HasCheckIndicator checkbox_rect = self.style().subElementRect(QStyle.SubElement.SE_ItemViewItemCheckIndicator, option, self) if x > checkbox_rect.width(): item.setCheckState(0, Qt.CheckState.Checked if item.checkState(0) != Qt.CheckState.Checked else Qt.CheckState.Unchecked) super().mousePressEvent(event) def sizeHint(self) -> QSize: return QSize(400, 500) def set_item_downloaded_state(self, ans: QTreeWidgetItem) -> None: voice = ans.data(0, Qt.ItemDataRole.UserRole) if isinstance(voice, Voice): is_downloaded = bool(voice and voice.engine_data and voice.engine_data.get('is_downloaded')) ans.setFont(0, self.highlight_font if is_downloaded else self.normal_font) def set_voices( self, all_voices: tuple[Voice, ...], current_voice: str, engine_metadata: EngineMetadata, preferred_voices: dict[str, str] | None = None ) -> None: self.clear() if self.for_embedding: current_voice = '' preferred_voices = preferred_voices or {} current_item = None def qv(parent, voice): nonlocal current_item text = voice.short_text(engine_metadata) ans = QTreeWidgetItem(parent, [text]) ans.setData(0, Qt.ItemDataRole.UserRole, voice) ans.setToolTip(0, voice.tooltip(engine_metadata)) if self.for_embedding: ans.setFlags(Qt.ItemFlag.ItemIsUserCheckable | Qt.ItemFlag.ItemIsEnabled) ans.setCheckState(0, Qt.CheckState.Unchecked) if current_voice == voice.name: current_item = ans self.set_item_downloaded_state(ans) return ans if not self.for_embedding: qv(self.invisibleRootItem(), self.system_default_voice) vmap = {} for v in all_voices: vmap.setdefault(v.language_code, []).append(v) for vs in vmap.values(): vs.sort(key=lambda v: v.sort_key()) parent_map = {} def lang(langcode): return QLocale.languageToString(QLocale.codeToLanguage(langcode)) for langcode in sorted(vmap, key=lambda lc: lang(lc).lower()): parent = parent_map.get(langcode) if parent is None: parent_map[langcode] = parent = QTreeWidgetItem(self.invisibleRootItem(), [lang(langcode)]) parent.setFlags(parent.flags() & ~Qt.ItemFlag.ItemIsSelectable & ~Qt.ItemFlag.ItemIsUserCheckable) parent.setData(0, Qt.ItemDataRole.UserRole, langcode) for voice in vmap[langcode]: v = qv(parent, voice) if self.for_embedding and voice.name and preferred_voices.get(langcode) == voice.name: v.setCheckState(0, Qt.CheckState.Checked) if current_item is not None: self.setCurrentItem(current_item) @property def val(self) -> str: voice = self.current_voice return voice.name if voice else '' @property def preferred_voices(self) -> dict[str, str] | None: r = self.invisibleRootItem() ans = {} for parent in (r.child(i) for i in range(r.childCount())): langcode = parent.data(0, Qt.ItemDataRole.UserRole) for child in (parent.child(i) for i in range(parent.childCount())): if child.checkState(0) == Qt.CheckState.Checked: voice = child.data(0, Qt.ItemDataRole.UserRole) if voice.name: ans[langcode] = voice.name return ans or None @property def current_voice(self) -> Voice | None: ci = self.currentItem() if ci is not None: ans = ci.data(0, Qt.ItemDataRole.UserRole) if isinstance(ans, Voice): return ans def refresh_current_item(self) -> None: ci = self.currentItem() if self.is_voice_item(ci): self.set_item_downloaded_state(ci) class EngineSpecificConfig(QWidget): voice_changed = pyqtSignal() def __init__(self, parent: QWidget = None, for_embedding: bool = False): super().__init__(parent) self.for_embedding = for_embedding self.engine_name = '' self.l = l = QFormLayout(self) devs = QMediaDevices.audioOutputs() dad = QMediaDevices.defaultAudioOutput() self.all_audio_devices = [AudioDeviceId(bytes(x.id()), x.description()) for x in devs] self.default_audio_device = AudioDeviceId(bytes(dad.id()), dad.description()) self.output_module = om = QComboBox(self) l.addRow(_('&Output module:'), om) self.engine_name = '' om.currentIndexChanged.connect(self.rebuild_voices) self.default_output_modules = {} self.voice_data = {} self.engine_specific_settings = {} self.rate = r = FloatSlider(parent=self) l.addRow(_('&Speed of speech:'), r) self.sentence_delay = d = SentenceDelay(parent=self) l.addRow(_('&Pause after sentence:'), d) self.pitch = p = FloatSlider(parent=self) l.addRow(_('&Pitch of speech:'), p) self.volume = v = Volume(self) l.addRow(v) self.audio_device = ad = QComboBox(self) l.addRow(_('Output a&udio to:'), ad) self.voices = v = Voices(self, self.for_embedding) v.voice_changed.connect(self.voice_changed) la = QLabel(_('Choose &default voice for language:') if self.for_embedding else _('V&oices:')) la.setBuddy(v) l.addRow(la) l.addRow(v) def set_engine(self, engine_name): engine_name = engine_name or default_engine_name() if self.engine_name and self.engine_name != engine_name: self.engine_specific_settings[self.engine_name] = self.as_settings() self.engine_name = engine_name metadata = available_engines()[engine_name] tts = create_tts_backend(force_engine=engine_name) if engine_name not in self.voice_data: self.voice_data[engine_name] = tts.available_voices if self.for_embedding: self.engine_specific_settings[engine_name] = EngineSpecificSettings.create_from_config(engine_name, TTS_EMBEDED_CONFIG) else: self.engine_specific_settings[engine_name] = EngineSpecificSettings.create_from_config(engine_name) self.default_output_modules[engine_name] = tts.default_output_module self.output_module.blockSignals(True) self.output_module.clear() if metadata.has_multiple_output_modules: self.layout().setRowVisible(self.output_module, True) self.output_module.addItem(_('System default (currently {})').format(tts.default_output_module), '') for om in self.voice_data[engine_name]: self.output_module.addItem(om, om) if (idx := self.output_module.findData(self.engine_specific_settings[engine_name].output_module)) > -1: self.output_module.setCurrentIndex(idx) else: self.layout().setRowVisible(self.output_module, False) self.output_module.blockSignals(False) self.layout().setRowVisible(self.sentence_delay, metadata.has_sentence_delay) try: s = self.engine_specific_settings[self.engine_name] except KeyError: return self.rate.val = s.rate if metadata.can_change_pitch: self.pitch.val = s.pitch self.layout().setRowVisible(self.pitch, True) else: self.pitch.val = 0 self.layout().setRowVisible(self.pitch, False) self.layout().setRowVisible(self.pitch, metadata.can_change_pitch) if metadata.can_change_volume and not self.for_embedding: self.layout().setRowVisible(self.volume, True) self.volume.val = s.volume else: self.layout().setRowVisible(self.volume, False) self.volume.val = None if metadata.has_sentence_delay: self.sentence_delay.val = s.sentence_delay self.audio_device.clear() if metadata.allows_choosing_audio_device and not self.for_embedding: self.audio_device.addItem(_('System default (currently {})').format(self.default_audio_device.description), '') for ad in self.all_audio_devices: self.audio_device.addItem(ad.description, ad.id.hex()) if cad := self.engine_specific_settings[engine_name].audio_device_id: if (idx := self.audio_device.findData(cad.id.hex())): self.audio_device.setCurrentIndex(idx) self.layout().setRowVisible(self.audio_device, True) else: self.layout().setRowVisible(self.audio_device, False) self.rebuild_voices() return metadata def rebuild_voices(self): try: s = self.engine_specific_settings[self.engine_name] except KeyError: return metadata = available_engines()[self.engine_name] output_module = self.output_module.currentData() or '' if metadata.has_multiple_output_modules: output_module = output_module or self.default_output_modules[self.engine_name] all_voices = self.voice_data[self.engine_name][output_module] self.voices.set_voices(all_voices, s.voice_name, metadata, s.preferred_voices) def as_settings(self) -> EngineSpecificSettings: ans = EngineSpecificSettings( engine_name=self.engine_name, rate=self.rate.val, pitch=self.pitch.val, volume=self.volume.val) if self.for_embedding: ans = ans._replace(preferred_voices=self.voices.preferred_voices) else: ans = ans._replace(voice_name=self.voices.val) metadata = available_engines()[self.engine_name] if metadata.has_sentence_delay: ans = ans._replace(sentence_delay=self.sentence_delay.val) if metadata.has_multiple_output_modules and self.output_module.currentIndex() > 0: ans = ans._replace(output_module=self.output_module.currentData()) if metadata.allows_choosing_audio_device and self.audio_device.currentIndex() > 0: aid = bytes.fromhex(self.audio_device.currentData()) for ad in self.all_audio_devices: if ad.id == aid: ans = ans._replace(audio_device_id=ad) break return ans def voice_action(self): v = self.voices.current_voice if v is None: return metadata = available_engines()[self.engine_name] if not metadata.has_managed_voices: return tts = create_tts_backend(self.engine_name) if tts.is_voice_downloaded(v): tts.delete_voice(v) else: tts.download_voice(v) def current_voice_is_downloaded(self) -> bool: v = self.voices.current_voice if v is None: return False metadata = available_engines()[self.engine_name] if not metadata.has_managed_voices: return False tts = create_tts_backend(self.engine_name) return tts.is_voice_downloaded(v) class ConfigDialog(Dialog): def __init__(self, parent=None): super().__init__(_('Configure Read aloud'), 'configure-read-aloud2', parent=parent) def setup_ui(self): self.l = l = QVBoxLayout(self) self.engine_choice = ec = EngineChoice(self) self.engine_specific_config = esc = EngineSpecificConfig(self) ec.changed.connect(self.set_engine) esc.voice_changed.connect(self.update_voice_button) l.addWidget(ec) l.addWidget(esc) self.voice_button = b = QPushButton(self) b.clicked.connect(self.voice_action) h = QHBoxLayout() l.addLayout(h) h.addWidget(b), h.addStretch(10), h.addWidget(self.bb) self.initial_engine_choice = ec.value self.set_engine(self.initial_engine_choice) def set_engine(self, engine_name: str) -> None: metadata = self.engine_specific_config.set_engine(engine_name) self.voice_button.setVisible(metadata.has_managed_voices) self.update_voice_button() def update_voice_button(self): b = self.voice_button if self.engine_specific_config.current_voice_is_downloaded(): b.setIcon(QIcon.ic('trash.png')) b.setText(_('Remove downloaded voice')) else: b.setIcon(QIcon.ic('download-metadata.png')) b.setText(_('Download voice')) self.engine_specific_config.voices.refresh_current_item() def voice_action(self): self.engine_specific_config.voice_action() self.update_voice_button() @property def engine_changed(self) -> bool: return self.engine_choice.value != self.initial_engine_choice def accept(self): engine_name = self.engine_choice.value tts = create_tts_backend(engine_name) s = self.engine_specific_config.as_settings() if not tts.validate_settings(s, self): return prefs = load_config() with prefs: if engine_name: prefs['engine'] = engine_name else: prefs.pop('engine', None) s.save_to_config(prefs) super().accept() class EmbeddingConfig(QWidget): def __init__(self, parent=None): super().__init__(parent) self.l = l = QVBoxLayout(self) self.engine_specific_config = esc = EngineSpecificConfig(self, for_embedding=True) l.addWidget(esc) self.engine_specific_config.set_engine('piper') def save_settings(self): s = self.engine_specific_config.as_settings() prefs = load_config(TTS_EMBEDED_CONFIG) with prefs: s.save_to_config(prefs, TTS_EMBEDED_CONFIG) def develop_embedding(): class D(Dialog): def __init__(self, parent=None): super().__init__('Configure Text to speech audio generation', 'configure-tts-embed', parent=parent) def setup_ui(self): self.l = l = QVBoxLayout(self) self.conf = c = EmbeddingConfig(self) l.addWidget(c) l.addWidget(self.bb) from calibre.gui2 import Application app = Application([]) d = D() if d.exec() == QDialog.DialogCode.Accepted: d.conf.save_settings() del d del app def develop(): from calibre.gui2 import Application app = Application([]) d = ConfigDialog() d.exec() del d del app if __name__ == '__main__': develop_embedding()
21,003
Python
.py
480
34.191667
136
0.62478
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,758
speechd.py
kovidgoyal_calibre/src/calibre/gui2/tts/speechd.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net> import atexit from qt.core import QObject, Qt, QTextToSpeech, pyqtSignal from speechd.client import CallbackType, DataMode, Priority, SpawnError, SSIPClient, SSIPCommunicationError from calibre import prepare_string_for_xml from calibre.gui2.tts.types import EngineSpecificSettings, TTSBackend, Voice from calibre.spell.break_iterator import split_into_words_and_positions from calibre.utils.localization import canonicalize_lang MARK_TEMPLATE = '<mark name="{}"/>' def mark_words(text: str, lang: str) -> str: ans = [] pos = 0 def a(x): ans.append(prepare_string_for_xml(x)) for offset, sz in split_into_words_and_positions(text, lang): if offset > pos: a(text[pos:offset]) ans.append(MARK_TEMPLATE.format(f'{offset}:{sz}')) a(text[offset:offset+sz]) pos = offset + sz return ''.join(ans) def wrap_in_ssml(text): return ('<?xml version="1.0"?>\n<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis"><s>' + text + '</s></speak>') class SpeechdTTSBackend(TTSBackend): saying = pyqtSignal(int, int) state_changed = pyqtSignal(QTextToSpeech.State) engine_name = 'speechd' _event_signal = pyqtSignal(object, object) def __init__(self, engine_name: str = '', parent: QObject|None = None): super().__init__(parent) self._last_error = '' self._state = QTextToSpeech.State.Ready self._voices = None self._system_default_output_module = None self._status = {'synthesizing': False, 'paused': False} self._ssip_client: SSIPClient | None = None self._voice_lang = 'en' self._last_mark = self._last_text = '' self._next_cancel_is_for_pause = False self._event_signal.connect(self._update_status, type=Qt.ConnectionType.QueuedConnection) self._apply_settings(EngineSpecificSettings.create_from_config(self.engine_name)) atexit.register(self.shutdown) @property def default_output_module(self) -> str: if self._ensure_state(): return self._system_default_output_module return '' @property def available_voices(self) -> dict[str, tuple[Voice, ...]]: if self._voices is None: try: self._voices = self._get_all_voices_for_all_output_modules() except Exception as e: self._set_error(str(e)) return self._voices or {} def stop(self) -> None: self._last_mark = self._last_text = '' if self._ssip_client is not None: if self._status['paused'] and self._status['synthesizing']: self._status = {'synthesizing': False, 'paused': False} self._set_state(QTextToSpeech.State.Ready) else: try: self._ssip_client.stop() except Exception as e: self._set_error(str(e)) def say(self, text: str) -> None: self.stop() self._speak(mark_words(text, self._voice_lang)) def error_message(self) -> str: return self._last_error def pause(self) -> None: if self._ssip_client is not None and self._status['synthesizing'] and not self._status['paused']: try: self._ssip_client.stop() self._next_cancel_is_for_pause = True except Exception as e: self._set_error(str(e)) def resume(self) -> None: if self._ssip_client is not None and self._status['synthesizing'] and self._status['paused']: text = self._last_text idx = text.find(self._last_mark) if idx > -1: text = text[idx:] self._speak(text) def reload_after_configure(self) -> None: self._apply_settings(EngineSpecificSettings.create_from_config(self.engine_name)) def shutdown(self): if self._ssip_client is not None: try: self._ssip_client.cancel() except Exception: pass try: self._ssip_client.close() except Exception: pass self._ssip_client = None def _set_state(self, s: QTextToSpeech.State) -> None: self._state = s self.state_changed.emit(s) def _set_error(self, msg: str) -> None: self._last_error = msg self._set_state(QTextToSpeech.State.Error) def _create_ssip_client(self) -> bool: try: self._ssip_client = SSIPClient('calibre') self._ssip_client.set_priority(Priority.TEXT) return True except SSIPCommunicationError as err: ex = err.additional_exception() if isinstance(ex, SpawnError): self._set_error(_('Could not find speech-dispatcher on your system. Please install it.')) else: self._set_error(str(err)) except SpawnError: self._set_error(_('Could not find speech-dispatcher on your system. Please install it.')) except Exception as err: self._set_error(str(err)) return False def _ensure_state(self) -> bool: if self._ssip_client is None: if not self._create_ssip_client(): return False if self._system_default_output_module is None: self._system_default_output_module = self._ssip_client.get_output_module() if self._system_default_output_module == '(null)': mods = self._ssip_client.list_output_modules() if not mods: self._set_error(_( 'Speech dispatcher on this system is not configured with any available output modules. Install some output modules first.')) return False self._system_default_output_module = mods[0] return self._set_use_ssml(True) def _set_use_ssml(self, on: bool) -> bool: mode = DataMode.SSML if on else DataMode.TEXT try: self._ssip_client.set_data_mode(mode) return True except SSIPCommunicationError: self._ssip_client.close() self._ssip_client = None self._set_error(_('Failed to set support for SSML to: {}').format(on)) return False def _apply_settings(self, settings: EngineSpecificSettings) -> bool: if not self._ensure_state(): return False try: om = settings.output_module or self._system_default_output_module self._ssip_client.set_output_module(om) if settings.voice_name: for v in self.available_voices[om]: if v.name == settings.voice_name: self._voice_lang = v.language_code break self._ssip_client.set_synthesis_voice(settings.voice_name) else: self._voice_lang = self.available_voices[om][0].language_code self._ssip_client.set_pitch_range(int(max(-1, min(settings.pitch, 1)) * 100)) self._ssip_client.set_rate(int(max(-1, min(settings.rate, 1)) * 100)) if settings.volume is not None: self._ssip_client.set_volume(-100 + int(max(0, min(settings.volume, 1)) * 200)) return True except Exception as e: self._set_error(str(e)) return False def _get_all_voices_for_all_output_modules(self) -> dict[str, Voice]: ans = {} def v(x) -> Voice: name, langcode, variant = x return Voice(name, canonicalize_lang(langcode) or 'und', human_name=name, notes=variant) if self._ensure_state(): om = self._ssip_client.get_output_module() for omq in self._ssip_client.list_output_modules(): self._ssip_client.set_output_module(omq) ans[omq] = tuple(map(v, self._ssip_client.list_synthesis_voices())) self._ssip_client.set_output_module(om) return ans def _update_status(self, callback_type, index_mark=None): event = None if callback_type is CallbackType.INDEX_MARK: pos, sep, length = index_mark.partition(':') self._last_mark = MARK_TEMPLATE.format(index_mark) self.saying.emit(int(pos), int(length)) elif callback_type is CallbackType.BEGIN: self._status = {'synthesizing': True, 'paused': False} self._set_state(QTextToSpeech.State.Speaking) elif callback_type is CallbackType.END: self._status = {'synthesizing': False, 'paused': False} self._set_state(QTextToSpeech.State.Ready) elif callback_type is CallbackType.CANCEL: if self._next_cancel_is_for_pause: self._status = {'synthesizing': True, 'paused': True} self._set_state(QTextToSpeech.State.Paused) self._next_cancel_is_for_pause = False else: self._status = {'synthesizing': False, 'paused': False} self._set_state(QTextToSpeech.State.Ready) return event def _speak_callback(self, callback_type: CallbackType, index_mark=None): self._event_signal.emit(callback_type, index_mark) def _speak(self, text: str) -> None: if self._ensure_state(): self._last_text = text self._last_mark = '' try: self._ssip_client.speak(wrap_in_ssml(text), self._speak_callback) except Exception as e: self._set_error(str(e))
9,737
Python
.py
211
35.132701
148
0.593826
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,759
qt.py
kovidgoyal_calibre/src/calibre/gui2/tts/qt.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net> from qt.core import QMediaDevices, QObject, QTextToSpeech from calibre.gui2.tts.types import EngineSpecificSettings, TTSBackend, Voice, qvoice_to_voice class QtTTSBackend(TTSBackend): def __init__(self, engine_name: str = '', parent: QObject|None = None): super().__init__(parent) self.speaking_text = '' self.last_word_offset = 0 self.last_spoken_word = None self.ignore_tracking_until_state_changes_to_speaking = False self._qt_reload_after_configure(engine_name) @property def available_voices(self) -> dict[str, tuple[Voice, ...]]: if self._voices is None: self._voices = tuple(map(qvoice_to_voice, self.tts.availableVoices())) return {'': self._voices} @property def engine_name(self) -> str: return self.tts.engine() @property def default_output_module(self) -> str: return '' def pause(self) -> None: self.tts.pause() def resume(self) -> None: self.tts.resume() def stop(self) -> None: if self.tts.engine() == 'sapi' and self.tts.state() is QTextToSpeech.State.Speaking: # prevent an occasional crash on stop by re-creating the engine rather than stopping it self.tts.sayingWord.disconnect() self.tts.stateChanged.disconnect() self.tts.pause() self.tts.deleteLater() del self.tts self._qt_reload_after_configure('sapi') self._state_changed(QTextToSpeech.State.Ready) else: self.tts.stop() def say(self, text: str) -> None: self.last_word_offset = 0 self.last_spoken_word = None self.speaking_text = text if self.tts.engine() == 'sapi': self.ignore_tracking_until_state_changes_to_speaking = True self.tts.say(text) def error_message(self) -> str: return self.tts.errorString() def reload_after_configure(self) -> None: self._qt_reload_after_configure(self.engine_name) def _qt_reload_after_configure(self, engine_name: str) -> None: # Bad things happen with more than one QTextToSpeech instance s = {} self._voices = None new_backend = not hasattr(self, 'tts') if engine_name: settings = EngineSpecificSettings.create_from_config(engine_name) if settings.audio_device_id: for x in QMediaDevices.audioOutputs(): if bytes(x.id()) == settings.audio_device_id.id: s['audioDevice'] = x break if new_backend: self.tts = QTextToSpeech(engine_name, s, self) else: self.tts.setEngine(engine_name, s) else: if new_backend: self.tts = QTextToSpeech(self) else: self.tts.setEngine('') engine_name = self.tts.engine() settings = EngineSpecificSettings.create_from_config(engine_name) if settings.audio_device_id: for x in QMediaDevices.audioOutputs(): if bytes(x.id) == settings.audio_device_id.id: s['audioDevice'] = x self.tts = QTextToSpeech(engine_name, s, self) break if new_backend: self.tts.sayingWord.connect(self._saying_word) self.tts.stateChanged.connect(self._state_changed) self.tts.setRate(max(-1, min(float(settings.rate), 1))) self.tts.setPitch(max(-1, min(float(settings.pitch), 1))) if settings.volume is not None: self.tts.setVolume(max(0, min(float(settings.volume), 1))) if settings.voice_name: for v in self.tts.availableVoices(): if v.name() == settings.voice_name: self.tts.setVoice(v) break self._current_settings = settings def _saying_word(self, word: str, utterance_id: int, start: int, length: int) -> None: # print(f'{repr(word)=} {start=} {length=}, {repr(self.speaking_text[start:start+length])=} {self.ignore_tracking_until_state_changes_to_speaking=}') if self.ignore_tracking_until_state_changes_to_speaking: return # Qt's word tracking is broken with non-BMP unicode chars, the # start and length values are totally wrong, so track manually key = word, start, length # Qt sometimes repeats words with windows modern engine at least, for a test case see https://bugs.launchpad.net/calibre/+bug/2080708 if self.last_spoken_word == key: return self.last_spoken_word = key idx = self.speaking_text.find(word, self.last_word_offset) # print(f'{self.last_word_offset=} {idx=}') if idx > -1: self.saying.emit(idx, len(word)) self.last_word_offset = idx + len(word) def _state_changed(self, state: QTextToSpeech.State) -> None: if self.ignore_tracking_until_state_changes_to_speaking and state is QTextToSpeech.State.Speaking: self.ignore_tracking_until_state_changes_to_speaking = False self.state_changed.emit(state)
5,346
Python
.py
112
36.8125
157
0.608054
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,760
manager.py
kovidgoyal_calibre/src/calibre/gui2/tts/manager.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net> from collections import deque from contextlib import contextmanager from typing import TYPE_CHECKING, NamedTuple from qt.core import QApplication, QDialog, QObject, QTextToSpeech, pyqtSignal from calibre.gui2 import error_dialog from calibre.gui2.widgets import BusyCursor if TYPE_CHECKING: from calibre.gui2.tts.types import TTSBackend class Utterance(NamedTuple): text: str index_in_positions: int offset_in_text: int reached_offset: int = 0 class Position(NamedTuple): mark: int offset_in_text: int class Tracker: def __init__(self): self.clear() def clear(self): self.positions: list[Position] = [] self.last_pos = 0 self.queue: deque[Utterance] = deque() def parse_marked_text(self, marked_text, limit = 32 * 1024): self.clear() text = [] text_len = chunk_len = index_in_positions = offset_in_text = 0 def commit(): self.queue.append(Utterance(''.join(text), index_in_positions, offset_in_text)) for x in marked_text: if isinstance(x, int): self.positions.append(Position(x, text_len)) else: text_len += len(x) chunk_len += len(x) text.append(x) if chunk_len > limit: commit() chunk_len = 0 text = [] index_in_positions = max(0, len(self.positions) - 1) offset_in_text = text_len if len(text): commit() self.marked_text = marked_text return self.current_text() def pop_first(self): if self.queue: self.queue.popleft() def current_text(self): if self.queue: return self.queue[0].text return '' def resume(self, filler_char: str = ' '): self.last_pos = 0 if self.queue: self.last_pos = self.queue[0].index_in_positions if self.queue[0].reached_offset: o = self.queue[0].reached_offset # make sure positions remain the same for word tracking self.queue[0] = self.queue[0]._replace(text=(filler_char * o) + self.queue[0].text[o:]) return self.current_text() def boundary_reached(self, start): if self.queue: self.queue[0] = self.queue[0]._replace(reached_offset=start) def mark_word_or_sentence(self, start, length): if not self.queue: return start += self.queue[0].offset_in_text end = start + length matches = [] while self.last_pos < len(self.positions): pos = self.positions[self.last_pos] if start <= pos.offset_in_text < end: matches.append(pos) elif pos.offset_in_text >= end: break self.last_pos += 1 if len(matches): return matches[0].mark, matches[-1].mark return None class ResumeData: is_speaking: bool = True needs_full_resume: bool = False class TTSManager(QObject): state_event = pyqtSignal(str) saying = pyqtSignal(int, int) def __init__(self, parent=None): super().__init__(parent) self._tts: 'TTSBackend' | None = None self.state = QTextToSpeech.State.Ready self.speaking_simple_text = False self.tracker = Tracker() self._resuming_after_configure = False def emit_state_event(self, event: str) -> None: if self._resuming_after_configure: if event == 'begin': event = 'resume' if event in ('resume', 'cancel'): self.state_event.emit(event) self._resuming_after_configure = False else: self.state_event.emit(event) @property def tts(self) -> 'TTSBackend': if self._tts is None: with BusyCursor(): from calibre.gui2.tts.types import create_tts_backend try: self._tts = create_tts_backend() except AttributeError as e: raise Exception(str(e)) from e self._tts.state_changed.connect(self._state_changed) self._tts.saying.connect(self._saying) return self._tts def stop(self) -> None: self.state = QTextToSpeech.State.Ready # so no event is sent to the UI after a stop triggered by the UI self._stop() def _stop(self) -> None: self.speaking_simple_text = False self.tracker.clear() self.tts.stop() def pause(self) -> None: self.tts.pause() def resume(self) -> None: self.tts.resume() def speak_simple_text(self, text: str) -> None: self._stop() self.speaking_simple_text = True self.tts.say(text) def speak_marked_text(self, marked_text): self._stop() self.speaking_simple_text = False self.tts.say(self.tracker.parse_marked_text(marked_text)) @contextmanager def resume_after(self): rd = ResumeData() rd.is_speaking = self._tts is not None and self.state in ( QTextToSpeech.State.Speaking, QTextToSpeech.State.Synthesizing, QTextToSpeech.State.Paused) self._resuming_after_configure = rd.is_speaking if self.state is not QTextToSpeech.State.Paused and rd.is_speaking: self.tts.pause() self.state_event.emit('pause') yield rd if rd.is_speaking: if rd.needs_full_resume: self.tts.say(self.tracker.resume(self.tts.filler_char)) else: self.tts.resume() def change_rate(self, steps: int = 1) -> bool: from calibre.gui2.tts.types import EngineSpecificSettings engine_name = self.tts.engine_name s = EngineSpecificSettings.create_from_config(engine_name) new_rate = max(-1, min(s.rate + 0.2 * steps, 1)) if new_rate != s.rate: s = s._replace(rate=new_rate) s.save_to_config() with self.resume_after() as rd: if self._tts is not None: rd.needs_full_resume = True self.tts.reload_after_configure() return True return False def test_resume_after_reload(self) -> None: with self.resume_after() as rd: if self._tts is not None: rd.needs_full_resume = True self.tts.reload_after_configure() def faster(self) -> None: if not self.change_rate(1): QApplication.instance().beep() def slower(self) -> None: if not self.change_rate(-1): QApplication.instance().beep() def configure(self) -> None: from calibre.gui2.tts.config import ConfigDialog from calibre.gui2.tts.types import widget_parent with self.resume_after() as rd: d = ConfigDialog(parent=widget_parent(self)) if d.exec() == QDialog.DialogCode.Accepted and self._tts is not None: rd.needs_full_resume = True if d.engine_changed: if rd.is_speaking: self.tts.stop() self._tts = None else: self.tts.reload_after_configure() def _state_changed(self, state: QTextToSpeech.State) -> None: prev_state, self.state = self.state, state if state is QTextToSpeech.State.Error: from calibre.gui2.tts.types import widget_parent error_dialog(widget_parent(self), _('Read aloud failed'), self.tts.error_message(), show=True) elif state is QTextToSpeech.State.Paused: self.emit_state_event('pause') elif state is QTextToSpeech.State.Speaking: if prev_state is QTextToSpeech.State.Paused: self.emit_state_event('resume') elif prev_state is QTextToSpeech.State.Ready: self.emit_state_event('begin') elif state is QTextToSpeech.State.Ready: if prev_state in (QTextToSpeech.State.Paused, QTextToSpeech.State.Speaking): if not self.speaking_simple_text: self.emit_state_event('end') elif state is QTextToSpeech.State.Error: self.emit_state_event('cancel') def _saying(self, offset: int, length: int) -> None: if self.speaking_simple_text: return self.tracker.boundary_reached(offset) x = self.tracker.mark_word_or_sentence(offset, length) if x is not None: self.saying.emit(x[0], x[1])
8,780
Python
.py
214
30.38785
112
0.588408
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,761
__init__.py
kovidgoyal_calibre/src/calibre/gui2/tts/__init__.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net>
94
Python
.py
2
46
71
0.76087
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,762
types.py
kovidgoyal_calibre/src/calibre/gui2/tts/types.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net> import os from contextlib import suppress from enum import Enum, auto from functools import lru_cache from typing import Literal, NamedTuple from qt.core import QApplication, QLocale, QObject, QTextToSpeech, QVoice, QWidget, pyqtSignal from calibre.constants import islinux, ismacos, iswindows, piper_cmdline from calibre.utils.config import JSONConfig from calibre.utils.config_base import tweaks from calibre.utils.localization import canonicalize_lang CONFIG_NAME = 'tts' TTS_EMBEDED_CONFIG = 'tts-embedded' # lru_cache doesn't work for this because it returns different results for # load_config() and load_config(CONFIG_NAME) conf_cache = {} def load_config(config_name=CONFIG_NAME) -> JSONConfig: if (ans := conf_cache.get(config_name)) is None: ans = conf_cache[config_name] = JSONConfig(config_name) return ans class TrackingCapability(Enum): NoTracking: int = auto() WordByWord: int = auto() Sentence: int = auto() class EngineMetadata(NamedTuple): name: Literal['winrt', 'darwin', 'sapi', 'flite', 'speechd', 'piper'] human_name: str description: str tracking_capability: TrackingCapability = TrackingCapability.NoTracking allows_choosing_audio_device: bool = True has_multiple_output_modules: bool = False can_synthesize_audio_data: bool = True can_change_pitch: bool = True can_change_volume: bool = True voices_have_quality_metadata: bool = False has_managed_voices: bool = False has_sentence_delay: bool = False class Quality(Enum): High: int = auto() Medium: int = auto() Low: int = auto() ExtraLow: int = auto() @classmethod def from_piper_quality(self, x: str) -> 'Quality': return {'x_low': Quality.ExtraLow, 'low': Quality.Low, 'medium': Quality.Medium, 'high': Quality.High}[x] @property def localized_name(self) -> str: if self is Quality.Medium: return _('Medium quality') if self is Quality.Low: return _('Low quality') if self is Quality.ExtraLow: return _('Extra low quality') return _('High quality') class Voice(NamedTuple): name: str = '' language_code: str = '' country_code: str = '' human_name: str = '' notes: str = '' # variant from speechd voices gender: QVoice.Gender = QVoice.Gender.Unknown age: QVoice.Age = QVoice.Age.Other quality: Quality = Quality.High engine_data: dict[str, str] | None = None @property def basic_name(self) -> str: return self.human_name or self.name or _('System default voice') def short_text(self, m: EngineMetadata) -> str: ans = self.basic_name if self.country_code: territory = QLocale.codeToTerritory(self.country_code) ans += f' ({QLocale.territoryToString(territory)})' if m.voices_have_quality_metadata: ans += f' [{self.quality.localized_name}]' return ans def tooltip(self, m: EngineMetadata) -> str: ans = [] if self.notes: ans.append(self.notes) if self.age is not QVoice.Age.Other: ans.append(_('Age: {}').format(QVoice.ageName(self.age))) if self.gender is not QVoice.Gender.Unknown: ans.append(_('Gender: {}').format(QVoice.genderName(self.gender))) return '\n'.join(ans) def sort_key(self) -> tuple[Quality, str]: return (self.quality.value, self.basic_name.lower()) def qvoice_to_voice(v: QVoice) -> QVoice: lang = canonicalize_lang(QLocale.languageToCode(v.language())) or 'und' country = QLocale.territoryToString(v.locale().territory()) return Voice(v.name(), lang, country, gender=v.gender(), age=v.age()) class AudioDeviceId(NamedTuple): id: bytes description: str class EngineSpecificSettings(NamedTuple): audio_device_id: AudioDeviceId | None = None voice_name: str = '' rate: float = 0 # -1 to 1 0 is normal speech pitch: float = 0 # -1 to 1 0 is normal speech volume: float | None = None # 0 to 1, None is platform default volume output_module: str = '' engine_name: str = '' sentence_delay: float = 0 # seconds >= 0 preferred_voices: dict[str, str] | None = None @classmethod def create_from_prefs(cls, engine_name: str, prefs: dict[str, object]) -> 'EngineSpecificSettings': adev = prefs.get('audio_device_id') audio_device_id = None if adev: with suppress(Exception): aid = bytes.fromhex(adev['id']) description = adev['description'] audio_device_id = AudioDeviceId(aid, description) rate = 0 with suppress(Exception): rate = max(-1, min(float(prefs.get('rate')), 1)) pitch = 0 with suppress(Exception): pitch = max(-1, min(float(prefs.get('pitch')), 1)) volume = None with suppress(Exception): volume = max(0, min(float(prefs.get('volume')), 1)) om = str(prefs.get('output_module', '')) sentence_delay = 0. with suppress(Exception): sentence_delay = max(0, float(prefs.get('sentence_delay'))) with suppress(Exception): preferred_voices = prefs.get('preferred_voices') return EngineSpecificSettings( voice_name=str(prefs.get('voice', '')), output_module=om, sentence_delay=sentence_delay, preferred_voices=preferred_voices, audio_device_id=audio_device_id, rate=rate, pitch=pitch, volume=volume, engine_name=engine_name) @classmethod def create_from_config(cls, engine_name: str, config_name: str = CONFIG_NAME) -> 'EngineSpecificSettings': prefs = load_config(config_name) val = prefs.get('engines', {}).get(engine_name, {}) return cls.create_from_prefs(engine_name, val) @property def as_dict(self) -> dict[str, object]: ans = {} if self.audio_device_id: ans['audio_device_id'] = {'id': self.audio_device_id.id.hex(), 'description': self.audio_device_id.description} if self.voice_name: ans['voice'] = self.voice_name if self.rate: ans['rate'] = self.rate if self.pitch: ans['pitch'] = self.pitch if self.volume is not None: ans['volume'] = self.volume if self.output_module: ans['output_module'] = self.output_module if self.sentence_delay: ans['sentence_delay'] = self.sentence_delay if self.preferred_voices: ans['preferred_voices'] = self.preferred_voices return ans def save_to_config(self, prefs:JSONConfig | None = None, config_name: str = CONFIG_NAME): prefs = load_config(config_name) if prefs is None else prefs val = self.as_dict engines = prefs.get('engines', {}) if not val: engines.pop(self.engine_name, None) else: engines[self.engine_name] = val prefs['engines'] = engines @lru_cache(2) def available_engines() -> dict[str, EngineMetadata]: ans = {} e = QTextToSpeech() def qt_engine_metadata(name: str, human_name: str, desc: str, allows_choosing_audio_device: bool = False) -> EngineMetadata: e.setEngine(name) cap = int(e.engineCapabilities().value) return EngineMetadata(name, human_name, desc, tracking_capability=TrackingCapability.WordByWord if cap & int( QTextToSpeech.Capability.WordByWordProgress.value) else TrackingCapability.NoTracking, allows_choosing_audio_device=allows_choosing_audio_device, can_synthesize_audio_data=bool(cap & int(QTextToSpeech.Capability.Synthesize.value))) for x in QTextToSpeech.availableEngines(): if x == 'winrt': ans[x] = qt_engine_metadata(x, _('Modern Windows Engine'), _( 'The "winrt" engine can track the currently spoken word on screen. Additional voices for it are available from Microsoft.' ), True) elif x == 'darwin': ans[x] = qt_engine_metadata(x, _('macOS Engine'), _( 'The "darwin" engine can track the currently spoken word on screen. Additional voices for it are available from Apple.' )) elif x == 'sapi': ans[x] = qt_engine_metadata(x, _('Legacy Windows Engine'), _( 'The "sapi" engine can track the currently spoken word on screen. It is no longer supported by Microsoft.' )) elif x == 'macos': # this is slated for removal in Qt 6.8 so skip it continue elif x == 'flite': ans[x] = qt_engine_metadata(x, _('The "flite" Engine'), _( 'The "flite" engine can track the currently spoken word on screen.' ), True) elif x == 'speechd': continue if piper_cmdline(): ans['piper'] = EngineMetadata('piper', _('The Piper Neural Engine'), _( 'The "piper" engine can track the currently spoken sentence on screen. It uses a neural network ' 'for natural sounding voices. The neural network is run locally on your computer, it is fairly resource intensive to run.' ), TrackingCapability.Sentence, can_change_pitch=False, voices_have_quality_metadata=True, has_managed_voices=True, has_sentence_delay=True) if islinux: try: from speechd.paths import SPD_SPAWN_CMD except ImportError: pass else: cmd = os.getenv("SPEECHD_CMD", SPD_SPAWN_CMD) if cmd and os.access(cmd, os.X_OK) and os.path.isfile(cmd): ans['speechd'] = EngineMetadata('speechd', _('The Speech Dispatcher Engine'), _( 'The "speechd" engine can usually track the currently spoken word on screen, however, it depends on the' ' underlying output module. The default espeak output module does support it.' ), TrackingCapability.WordByWord, allows_choosing_audio_device=False, has_multiple_output_modules=True) return ans def default_engine_name() -> str: if 'piper' in available_engines(): return 'piper' if iswindows: return 'sapi' if tweaks.get('prefer_winsapi') else 'winrt' if ismacos: return 'darwin' if 'speechd' in available_engines(): return 'speechd' return 'flite' def widget_parent(p: QObject) -> QWidget | None: while p is not None and not isinstance(p, QWidget): p = p.parent() return p class TTSBackend(QObject): saying = pyqtSignal(int, int) # offset, length state_changed = pyqtSignal(QTextToSpeech.State) available_voices: dict[str, tuple[Voice, ...]] = {} engine_name: str = '' default_output_module: str = '' filler_char: str = ' ' def __init__(self, engine_name: str = '', parent: QObject|None = None): super().__init__(parent) def pause(self) -> None: raise NotImplementedError() def resume(self) -> None: raise NotImplementedError() def stop(self) -> None: raise NotImplementedError() def say(self, text: str) -> None: raise NotImplementedError() def error_message(self) -> str: raise NotImplementedError() def reload_after_configure(self) -> None: raise NotImplementedError() def validate_settings(self, s: EngineSpecificSettings, parent: QWidget | None) -> bool: return True def is_voice_downloaded(self, v: Voice) -> bool: return True def delete_voice(self, v: Voice) -> None: pass def download_voice(self, v: Voice) -> None: pass engine_instances: dict[str, TTSBackend] = {} def create_tts_backend(force_engine: str | None = None, config_name: str = CONFIG_NAME) -> TTSBackend: if not available_engines(): raise OSError('There are no available TTS engines. Install a TTS engine before trying to use Read Aloud, such as flite or speech-dispatcher') prefs = load_config(config_name) engine_name = prefs.get('engine', '') if force_engine is None else force_engine engine_name = engine_name or default_engine_name() if engine_name not in available_engines(): engine_name = default_engine_name() if engine_name == 'piper': if engine_name not in engine_instances: from calibre.gui2.tts.piper import Piper engine_instances[engine_name] = Piper(engine_name, QApplication.instance()) ans = engine_instances[engine_name] elif engine_name == 'speechd': if engine_name not in engine_instances: from calibre.gui2.tts.speechd import SpeechdTTSBackend engine_instances[engine_name] = SpeechdTTSBackend(engine_name, QApplication.instance()) ans = engine_instances[engine_name] else: if 'qt' not in engine_instances: # Bad things happen with more than one QTextToSpeech instance from calibre.gui2.tts.qt import QtTTSBackend engine_instances['qt'] = QtTTSBackend(engine_name if engine_name in available_engines() else '', QApplication.instance()) ans = engine_instances['qt'] if ans.engine_name != engine_name: ans._qt_reload_after_configure(engine_name if engine_name in available_engines() else '') return ans
13,477
Python
.py
289
38.564014
149
0.645061
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,763
bookmarks.py
kovidgoyal_calibre/src/calibre/gui2/viewer/bookmarks.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2013, Kovid Goyal <kovid at kovidgoyal.net> import json from operator import itemgetter from qt.core import ( QAbstractItemView, QAction, QComboBox, QGridLayout, QHBoxLayout, QIcon, QInputDialog, QItemSelectionModel, QLabel, QListWidget, QListWidgetItem, QPushButton, Qt, QWidget, pyqtSignal, ) from calibre.gui2 import choose_files, choose_save_file, error_dialog from calibre.gui2.dialogs.confirm_delete import confirm from calibre.gui2.gestures import GestureManager from calibre.gui2.viewer.shortcuts import get_shortcut_for from calibre.gui2.viewer.web_view import vprefs from calibre.utils.date import EPOCH, utcnow from calibre.utils.icu import primary_sort_key from calibre.utils.localization import _ class BookmarksList(QListWidget): changed = pyqtSignal() bookmark_activated = pyqtSignal(object) def __init__(self, parent=None): QListWidget.__init__(self, parent) self.setAlternatingRowColors(True) self.setStyleSheet('QListView::item { padding: 0.5ex }') self.setContextMenuPolicy(Qt.ContextMenuPolicy.ActionsContextMenu) self.ac_edit = ac = QAction(QIcon.ic('edit_input.png'), _('Rename this bookmark'), self) self.addAction(ac) self.ac_delete = ac = QAction(QIcon.ic('trash.png'), _('Remove this bookmark'), self) self.addAction(ac) self.gesture_manager = GestureManager(self) self.setVerticalScrollMode(QAbstractItemView.ScrollMode.ScrollPerPixel) 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 current_non_removed_item(self): ans = self.currentItem() if ans is not None: bm = ans.data(Qt.ItemDataRole.UserRole) if not bm.get('removed'): return ans def keyPressEvent(self, ev): if ev.key() in (Qt.Key.Key_Enter, Qt.Key.Key_Return): i = self.current_non_removed_item if i is not None: self.bookmark_activated.emit(i) ev.accept() return if ev.key() in (Qt.Key.Key_Delete, Qt.Key.Key_Backspace): i = self.current_non_removed_item if i is not None: self.ac_delete.trigger() ev.accept() return return QListWidget.keyPressEvent(self, ev) def activate_related_bookmark(self, delta=1): if not self.count(): return items = [self.item(r) for r in range(self.count())] row = self.currentRow() current_item = items[row] items = [i for i in items if not i.isHidden()] count = len(items) if not count: return row = items.index(current_item) nrow = (row + delta + count) % count self.setCurrentItem(items[nrow]) self.bookmark_activated.emit(self.currentItem()) def next_bookmark(self): self.activate_related_bookmark() def previous_bookmark(self): self.activate_related_bookmark(-1) class BookmarkManager(QWidget): edited = pyqtSignal(object) activated = pyqtSignal(object) create_requested = pyqtSignal() toggle_requested = pyqtSignal() def __init__(self, parent): QWidget.__init__(self, parent) self.l = l = QGridLayout(self) l.setContentsMargins(0, 0, 0, 0) self.setLayout(l) self.toc = parent.toc self.bookmarks_list = bl = BookmarksList(self) bl.itemChanged.connect(self.item_changed) l.addWidget(bl, 0, 0, 1, -1) bl.itemClicked.connect(self.item_activated) bl.bookmark_activated.connect(self.item_activated) bl.changed.connect(lambda : self.edited.emit(self.get_bookmarks())) bl.ac_edit.triggered.connect(self.edit_bookmark) bl.ac_delete.triggered.connect(self.delete_bookmark) self.la = la = QLabel(_( 'Double click to edit the bookmarks')) la.setWordWrap(True) l.addWidget(la, l.rowCount(), 0, 1, -1) self.button_new = b = QPushButton(QIcon.ic('bookmarks.png'), _('&New'), self) b.clicked.connect(self.create_requested) b.setToolTip(_('Create a new bookmark at the current location')) l.addWidget(b) self.button_delete = b = QPushButton(QIcon.ic('trash.png'), _('&Remove'), self) b.setToolTip(_('Remove the currently selected bookmark')) b.clicked.connect(self.delete_bookmark) l.addWidget(b, l.rowCount() - 1, 1) self.button_prev = b = QPushButton(QIcon.ic('back.png'), _('Pre&vious'), self) b.clicked.connect(self.bookmarks_list.previous_bookmark) l.addWidget(b) self.button_next = b = QPushButton(QIcon.ic('forward.png'), _('Nex&t'), self) b.clicked.connect(self.bookmarks_list.next_bookmark) l.addWidget(b, l.rowCount() - 1, 1) la = QLabel(_('&Sort by:')) self.sort_by = sb = QComboBox(self) la.setBuddy(sb) sb.addItem(_('Title'), 'title') sb.addItem(_('Position in book'), 'pos') sb.addItem(_('Date'), 'timestamp') sb.setToolTip(_('Change how the bookmarks are sorted')) i = sb.findData(vprefs['bookmarks_sort']) if i > -1: sb.setCurrentIndex(i) h = QHBoxLayout() h.addWidget(la), h.addWidget(sb, 10) l.addLayout(h, l.rowCount(), 0, 1, 2) sb.currentIndexChanged.connect(self.sort_by_changed) self.button_export = b = QPushButton(_('E&xport'), self) b.clicked.connect(self.export_bookmarks) l.addWidget(b, l.rowCount(), 0) self.button_import = b = QPushButton(_('&Import'), self) b.clicked.connect(self.import_bookmarks) l.addWidget(b, l.rowCount() - 1, 1) def item_activated(self, item): bm = self.item_to_bm(item) self.activated.emit(bm['pos']) @property def current_sort_by(self): return self.sort_by.currentData() def sort_by_changed(self): vprefs['bookmarks_sort'] = self.current_sort_by self.set_bookmarks(self.get_bookmarks()) def set_bookmarks(self, bookmarks=()): csb = self.current_sort_by if csb in ('name', 'title'): def sk(x): return primary_sort_key(x['title']) elif csb == 'timestamp': sk = itemgetter('timestamp') else: from calibre.ebooks.epub.cfi.parse import cfi_sort_key defval = cfi_sort_key('/99999999') def pos_key(b): if b.get('pos_type') == 'epubcfi': return cfi_sort_key(b['pos'], only_path=False) return defval sk = pos_key bookmarks = sorted(bookmarks, key=sk) current_bookmark_id = self.current_bookmark_id self.bookmarks_list.clear() for bm in bookmarks: i = QListWidgetItem(bm['title']) i.setData(Qt.ItemDataRole.ToolTipRole, bm['title']) i.setData(Qt.ItemDataRole.UserRole, self.bm_to_item(bm)) i.setFlags(i.flags() | Qt.ItemFlag.ItemIsEditable) self.bookmarks_list.addItem(i) if bm.get('removed'): i.setHidden(True) for i in range(self.bookmarks_list.count()): item = self.bookmarks_list.item(i) if not item.isHidden(): self.bookmarks_list.setCurrentItem(item, QItemSelectionModel.SelectionFlag.ClearAndSelect) break if current_bookmark_id is not None: self.current_bookmark_id = current_bookmark_id @property def current_bookmark_id(self): item = self.bookmarks_list.currentItem() if item is not None: return item.data(Qt.ItemDataRole.DisplayRole) @current_bookmark_id.setter def current_bookmark_id(self, val): for i, q in enumerate(self): if q['title'] == val: item = self.bookmarks_list.item(i) self.bookmarks_list.setCurrentItem(item, QItemSelectionModel.SelectionFlag.ClearAndSelect) self.bookmarks_list.scrollToItem(item) def set_current_bookmark(self, bm): for i, q in enumerate(self): if bm == q: l = self.bookmarks_list item = l.item(i) l.setCurrentItem(item, QItemSelectionModel.SelectionFlag.ClearAndSelect) l.scrollToItem(item) def __iter__(self): for i in range(self.bookmarks_list.count()): yield self.item_to_bm(self.bookmarks_list.item(i)) def uniqify_bookmark_title(self, base): remove = [] for i in range(self.bookmarks_list.count()): item = self.bookmarks_list.item(i) bm = item.data(Qt.ItemDataRole.UserRole) if bm.get('removed') and bm['title'] == base: remove.append(i) for i in reversed(remove): self.bookmarks_list.takeItem(i) all_titles = {bm['title'] for bm in self.get_bookmarks()} c = 0 q = base while q in all_titles: c += 1 q = f'{base} #{c}' return q def item_changed(self, item): self.bookmarks_list.blockSignals(True) title = str(item.data(Qt.ItemDataRole.DisplayRole)) or _('Unknown') title = self.uniqify_bookmark_title(title) item.setData(Qt.ItemDataRole.DisplayRole, title) item.setData(Qt.ItemDataRole.ToolTipRole, title) bm = item.data(Qt.ItemDataRole.UserRole) bm['title'] = title bm['timestamp'] = utcnow().isoformat() item.setData(Qt.ItemDataRole.UserRole, bm) self.bookmarks_list.blockSignals(False) self.edited.emit(self.get_bookmarks()) def delete_bookmark(self): item = self.bookmarks_list.current_non_removed_item if item is not None: bm = item.data(Qt.ItemDataRole.UserRole) if confirm( _('Are you sure you want to delete the bookmark: {0}?').format(bm['title']), 'delete-bookmark-from-viewer', parent=self, config_set=vprefs ): bm['removed'] = True bm['timestamp'] = utcnow().isoformat() self.bookmarks_list.blockSignals(True) item.setData(Qt.ItemDataRole.UserRole, bm) self.bookmarks_list.blockSignals(False) item.setHidden(True) self.edited.emit(self.get_bookmarks()) def edit_bookmark(self): item = self.bookmarks_list.current_non_removed_item if item is not None: self.bookmarks_list.editItem(item) def bm_to_item(self, bm): return bm.copy() def item_to_bm(self, item): return item.data(Qt.ItemDataRole.UserRole).copy() def get_bookmarks(self): return list(self) def export_bookmarks(self): filename = choose_save_file( self, 'export-viewer-bookmarks', _('Export bookmarks'), filters=[(_('Saved bookmarks'), ['calibre-bookmarks'])], all_files=False, initial_filename='bookmarks.calibre-bookmarks') if filename: bm = [x for x in self.get_bookmarks() if not x.get('removed')] data = json.dumps({'type': 'bookmarks', 'entries': bm}, indent=True) if not isinstance(data, bytes): data = data.encode('utf-8') with open(filename, 'wb') as fileobj: fileobj.write(data) def import_bookmarks(self): files = choose_files(self, 'export-viewer-bookmarks', _('Import bookmarks'), filters=[(_('Saved bookmarks'), ['calibre-bookmarks'])], all_files=False, select_only_single_file=True) if not files: return filename = files[0] imported = None with open(filename, 'rb') as fileobj: imported = json.load(fileobj) def import_old_bookmarks(imported): try: for bm in imported: if 'title' not in bm: return except Exception: return bookmarks = self.get_bookmarks() for bm in imported: if bm['title'] == 'calibre_current_page_bookmark': continue epubcfi = 'epubcfi(/{}/{})'.format((bm['spine'] + 1) * 2, bm['pos'].lstrip('/')) q = {'pos_type': 'epubcfi', 'pos': epubcfi, 'timestamp': EPOCH.isoformat(), 'title': bm['title']} if q not in bookmarks: bookmarks.append(q) self.set_bookmarks(bookmarks) self.edited.emit(self.get_bookmarks()) def import_current_bookmarks(imported): if imported.get('type') != 'bookmarks': return bookmarks = self.get_bookmarks() for bm in imported['entries']: if bm not in bookmarks: bookmarks.append(bm) self.set_bookmarks(bookmarks) self.edited.emit(self.get_bookmarks()) if imported is not None: if isinstance(imported, list): import_old_bookmarks(imported) else: import_current_bookmarks(imported) def create_new_bookmark(self, pos_data): base_default_title = self.toc.model().title_for_current_node or _('Bookmark') all_titles = {bm['title'] for bm in self.get_bookmarks()} c = 0 while True: c += 1 default_title = f'{base_default_title} #{c}' if default_title not in all_titles: break title, ok = QInputDialog.getText(self, _('Add bookmark'), _('Enter title for bookmark:'), text=pos_data.get('selected_text') or default_title) title = str(title).strip() if not ok or not title: return title = self.uniqify_bookmark_title(title) cfi = (pos_data.get('selection_bounds') or {}).get('start') or pos_data['cfi'] if not cfi: error_dialog(self, _('Failed to bookmark'), _('Could not calculate position in book'), show=True) return bm = { 'title': title, 'pos_type': 'epubcfi', 'pos': cfi, 'timestamp': utcnow().isoformat(), } bookmarks = self.get_bookmarks() bookmarks.append(bm) self.set_bookmarks(bookmarks) self.set_current_bookmark(bm) self.edited.emit(bookmarks) def keyPressEvent(self, ev): sc = get_shortcut_for(self, ev) if ev.key() == Qt.Key.Key_Escape or sc == 'toggle_bookmarks': self.toggle_requested.emit() return if sc == 'new_bookmark': self.create_requested.emit() return return QWidget.keyPressEvent(self, ev)
15,101
Python
.py
352
32.588068
133
0.597958
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,764
ui.py
kovidgoyal_calibre/src/calibre/gui2/viewer/ui.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> import json import os import re import sys import time from collections import defaultdict, namedtuple from hashlib import sha256 from threading import Thread from qt.core import ( QApplication, QCursor, QDockWidget, QEvent, QMainWindow, QMenu, QMimeData, QModelIndex, QPixmap, Qt, QTimer, QToolBar, QUrl, QVBoxLayout, QWidget, pyqtSignal, sip, ) from calibre import prints from calibre.constants import ismacos, iswindows from calibre.customize.ui import available_input_formats from calibre.db.annotations import merge_annotations from calibre.gui2 import add_to_recent_docs, choose_files, error_dialog, sanitize_env_vars from calibre.gui2.dialogs.drm_error import DRMErrorMessage from calibre.gui2.image_popup import ImagePopup from calibre.gui2.main_window import MainWindow from calibre.gui2.viewer import get_boss, get_current_book_data, performance_monitor from calibre.gui2.viewer.annotations import AnnotationsSaveWorker, annotations_dir, parse_annotations from calibre.gui2.viewer.bookmarks import BookmarkManager from calibre.gui2.viewer.config import get_session_pref, load_reading_rates, save_reading_rates, vprefs from calibre.gui2.viewer.convert_book import clean_running_workers, prepare_book from calibre.gui2.viewer.highlights import HighlightsPanel from calibre.gui2.viewer.integration import get_book_library_details, load_annotations_map_from_library from calibre.gui2.viewer.lookup import Lookup from calibre.gui2.viewer.overlay import LoadingOverlay from calibre.gui2.viewer.search import SearchPanel from calibre.gui2.viewer.toc import TOC, TOCSearch, TOCView from calibre.gui2.viewer.toolbars import ActionsToolBar from calibre.gui2.viewer.web_view import WebView, get_path_for_name, set_book_path from calibre.startup import connect_lambda from calibre.utils.date import utcnow from calibre.utils.img import image_from_path from calibre.utils.ipc.simple_worker import WorkerError from calibre.utils.localization import _ from polyglot.builtins import as_bytes, as_unicode, iteritems, itervalues def is_float(x): try: float(x) return True except Exception: pass return False def dock_defs(): Dock = namedtuple('Dock', 'name title initial_area allowed_areas') ans = {} def d(title, name, area, allowed=Qt.DockWidgetArea.LeftDockWidgetArea | Qt.DockWidgetArea.RightDockWidgetArea): ans[name] = Dock(name + '-dock', title, area, allowed) d(_('Table of Contents'), 'toc', Qt.DockWidgetArea.LeftDockWidgetArea), d(_('Lookup'), 'lookup', Qt.DockWidgetArea.RightDockWidgetArea), d(_('Bookmarks'), 'bookmarks', Qt.DockWidgetArea.RightDockWidgetArea) d(_('Search'), 'search', Qt.DockWidgetArea.LeftDockWidgetArea) d(_('Inspector'), 'inspector', Qt.DockWidgetArea.RightDockWidgetArea, Qt.DockWidgetArea.AllDockWidgetAreas) d(_('Highlights'), 'highlights', Qt.DockWidgetArea.RightDockWidgetArea) return ans def path_key(path): return sha256(as_bytes(path)).hexdigest() class EbookViewer(MainWindow): msg_from_anotherinstance = pyqtSignal(object) book_preparation_started = pyqtSignal() book_prepared = pyqtSignal(object, object) MAIN_WINDOW_STATE_VERSION = 1 def __init__(self, open_at=None, continue_reading=None, force_reload=False, calibre_book_data=None): MainWindow.__init__(self, None) get_boss(self) self.annotations_saver = None self.calibre_book_data_for_first_book = calibre_book_data self.shutting_down = self.close_forced = self.shutdown_done = False self.force_reload = force_reload connect_lambda(self.book_preparation_started, self, lambda self: self.loading_overlay(_( 'Preparing book for first read, please wait')), type=Qt.ConnectionType.QueuedConnection) self.maximized_at_last_fullscreen = False self.save_pos_timer = t = QTimer(self) t.setSingleShot(True), t.setInterval(3000), t.setTimerType(Qt.TimerType.VeryCoarseTimer) connect_lambda(t.timeout, self, lambda self: self.save_annotations(in_book_file=False)) self.pending_open_at = open_at self.pending_search = None self.base_window_title = _('E-book viewer') self.setDockOptions(QMainWindow.DockOption.AnimatedDocks | QMainWindow.DockOption.AllowTabbedDocks | QMainWindow.DockOption.AllowNestedDocks) self.setWindowTitle(self.base_window_title) self.in_full_screen_mode = None self.image_popup = ImagePopup(self, prefs=vprefs) self.actions_toolbar = at = ActionsToolBar(self) at.open_book_at_path.connect(self.ask_for_open) self.addToolBar(Qt.ToolBarArea.LeftToolBarArea, at) try: os.makedirs(annotations_dir) except OSError: pass self.current_book_data = {} get_current_book_data(self.current_book_data) self.book_prepared.connect(self.load_finished, type=Qt.ConnectionType.QueuedConnection) self.dock_defs = dock_defs() def create_dock(title, name, area, areas=Qt.DockWidgetArea.LeftDockWidgetArea | Qt.DockWidgetArea.RightDockWidgetArea): ans = QDockWidget(title, self) ans.setObjectName(name) self.addDockWidget(area, ans) ans.setVisible(False) ans.visibilityChanged.connect(self.dock_visibility_changed) return ans for dock_def in itervalues(self.dock_defs): setattr(self, '{}_dock'.format(dock_def.name.partition('-')[0]), create_dock( dock_def.title, dock_def.name, dock_def.initial_area, dock_def.allowed_areas)) self.toc_container = w = QWidget(self) w.l = QVBoxLayout(w) self.toc = TOCView(w) self.toc.clicked[QModelIndex].connect(self.toc_clicked) self.toc.searched.connect(self.toc_searched) self.toc_search = TOCSearch(self.toc, parent=w) w.l.addWidget(self.toc), w.l.addWidget(self.toc_search), w.l.setContentsMargins(0, 0, 0, 0) self.toc_dock.setWidget(w) self.search_widget = w = SearchPanel(self) w.search_requested.connect(self.start_search) w.hide_search_panel.connect(self.search_dock.close) w.count_changed.connect(self.search_results_count_changed) w.goto_cfi.connect(self.goto_cfi) self.search_dock.setWidget(w) self.search_dock.visibilityChanged.connect(self.search_widget.visibility_changed) self.lookup_widget = w = Lookup(self) self.lookup_dock.visibilityChanged.connect(self.lookup_widget.visibility_changed) self.lookup_dock.setWidget(w) self.bookmarks_widget = w = BookmarkManager(self) connect_lambda( w.create_requested, self, lambda self: self.web_view.trigger_shortcut('new_bookmark')) w.edited.connect(self.bookmarks_edited) w.activated.connect(self.bookmark_activated) w.toggle_requested.connect(self.toggle_bookmarks) self.bookmarks_dock.setWidget(w) self.highlights_widget = w = HighlightsPanel(self) self.highlights_dock.setWidget(w) w.toggle_requested.connect(self.toggle_highlights) self.web_view = WebView(self) self.web_view.cfi_changed.connect(self.cfi_changed) self.web_view.reload_book.connect(self.reload_book) self.web_view.toggle_toc.connect(self.toggle_toc) self.web_view.show_search.connect(self.show_search) self.web_view.find_next.connect(self.search_widget.find_next_requested) self.search_widget.show_search_result.connect(self.show_search_result) self.web_view.search_result_not_found.connect(self.search_widget.search_result_not_found) self.web_view.search_result_discovered.connect(self.search_widget.search_result_discovered) self.web_view.toggle_bookmarks.connect(self.toggle_bookmarks) self.web_view.toggle_highlights.connect(self.toggle_highlights) self.web_view.new_bookmark.connect(self.bookmarks_widget.create_new_bookmark) self.web_view.toggle_inspector.connect(self.toggle_inspector) self.web_view.toggle_lookup.connect(self.toggle_lookup) self.web_view.quit.connect(self.quit) self.web_view.update_current_toc_nodes.connect(self.toc.update_current_toc_nodes) self.web_view.toggle_full_screen.connect(self.toggle_full_screen) self.web_view.ask_for_open.connect(self.ask_for_open_from_js, type=Qt.ConnectionType.QueuedConnection) self.web_view.selection_changed.connect(self.lookup_widget.selected_text_changed, type=Qt.ConnectionType.QueuedConnection) self.web_view.selection_changed.connect(self.highlights_widget.selected_text_changed, type=Qt.ConnectionType.QueuedConnection) self.web_view.view_image.connect(self.view_image, type=Qt.ConnectionType.QueuedConnection) self.web_view.copy_image.connect(self.copy_image, type=Qt.ConnectionType.QueuedConnection) self.web_view.show_loading_message.connect(self.show_loading_message) self.web_view.show_error.connect(self.show_error) self.web_view.print_book.connect(self.print_book, type=Qt.ConnectionType.QueuedConnection) self.web_view.reset_interface.connect(self.reset_interface, type=Qt.ConnectionType.QueuedConnection) self.web_view.quit.connect(self.quit, type=Qt.ConnectionType.QueuedConnection) self.web_view.shortcuts_changed.connect(self.shortcuts_changed) self.web_view.scrollbar_context_menu.connect(self.scrollbar_context_menu) self.web_view.close_prep_finished.connect(self.close_prep_finished) self.web_view.highlights_changed.connect(self.highlights_changed) self.web_view.update_reading_rates.connect(self.update_reading_rates) self.web_view.edit_book.connect(self.edit_book) self.web_view.content_file_changed.connect(self.content_file_changed) self.actions_toolbar.initialize(self.web_view, self.search_dock.toggleViewAction()) at.update_action_state(False) self.setCentralWidget(self.web_view) self.loading_overlay = LoadingOverlay(self) self.restore_state() self.actions_toolbar.update_visibility() self.dock_visibility_changed() self.highlights_widget.request_highlight_action.connect(self.web_view.highlight_action) self.highlights_widget.web_action.connect(self.web_view.generic_action) self.highlights_widget.notes_edited_signal.connect(self.notes_edited) if continue_reading: self.continue_reading() self.setup_mouse_auto_hide() def shortcuts_changed(self, smap): rmap = defaultdict(list) for k, v in iteritems(smap): rmap[v].append(k) self.actions_toolbar.set_tooltips(rmap) self.highlights_widget.set_tooltips(rmap) def resizeEvent(self, ev): self.loading_overlay.resize(self.size()) return MainWindow.resizeEvent(self, ev) def scrollbar_context_menu(self, x, y, frac): m = QMenu(self) amap = {} def a(text, name): m.addAction(text) amap[text] = name a(_('Scroll here'), 'here') m.addSeparator() a(_('Start of book'), 'start_of_book') a(_('End of book'), 'end_of_book') m.addSeparator() a(_('Previous section'), 'previous_section') a(_('Next section'), 'next_section') m.addSeparator() a(_('Start of current file'), 'start_of_file') a(_('End of current file'), 'end_of_file') m.addSeparator() a(_('Hide this scrollbar'), 'toggle_scrollbar') q = m.exec(QCursor.pos()) if not q: return q = amap[q.text()] if q == 'here': self.web_view.goto_frac(frac) else: self.web_view.trigger_shortcut(q) # IPC {{{ def handle_commandline_arg(self, arg): if arg: if os.path.isfile(arg) and os.access(arg, os.R_OK): self.load_ebook(arg) else: prints('Cannot read from:', arg, file=sys.stderr) def message_from_other_instance(self, msg): try: msg = json.loads(msg) path, open_at = msg except Exception as err: print('Invalid message from other instance', file=sys.stderr) print(err, file=sys.stderr) return self.load_ebook(path, open_at=open_at) self.raise_and_focus() self.activateWindow() # }}} # Fullscreen {{{ def set_full_screen(self, on): if on: self.maximized_at_last_fullscreen = self.isMaximized() if not self.actions_toolbar.visible_in_fullscreen: self.actions_toolbar.setVisible(False) self.showFullScreen() else: self.actions_toolbar.update_visibility() if self.maximized_at_last_fullscreen: self.showMaximized() else: self.showNormal() def changeEvent(self, ev): if ev.type() == QEvent.Type.WindowStateChange: in_full_screen_mode = self.isFullScreen() if self.in_full_screen_mode is None or self.in_full_screen_mode != in_full_screen_mode: self.in_full_screen_mode = in_full_screen_mode self.web_view.notify_full_screen_state_change(self.in_full_screen_mode) return MainWindow.changeEvent(self, ev) def toggle_full_screen(self): self.set_full_screen(not self.isFullScreen()) # }}} # Docks (ToC, Bookmarks, Lookup, etc.) {{{ def toggle_inspector(self): visible = self.inspector_dock.toggleViewAction().isChecked() self.inspector_dock.setVisible(not visible) def toggle_toc(self): is_visible = self.toc_dock.isVisible() self.toc_dock.setVisible(not is_visible) if not is_visible: self.toc.scroll_to_current_toc_node() def show_search_result(self, sr): self.web_view.show_search_result(sr) def show_search(self, text, trigger=False, search_type=None, case_sensitive=None): self.search_dock.setVisible(True) self.search_dock.activateWindow() self.search_dock.raise_and_focus() self.search_widget.focus_input(text, search_type, case_sensitive) if trigger: self.search_widget.trigger() def search_results_count_changed(self, num=-1): if num < 0: tt = _('Search') elif num == 0: tt = _('Search :: no matches') elif num == 1: tt = _('Search :: one match') else: tt = _('Search :: {} matches').format(num) self.search_dock.setWindowTitle(tt) def start_search(self, search_query): name = self.web_view.current_content_file if name: if search_query.is_empty and search_query.text: return error_dialog(self, _('Empty search expression'), _( 'Cannot search for {!r} as it contains only punctuation and spaces.').format(search_query.text), show=True) self.web_view.get_current_cfi(self.search_widget.set_anchor_cfi) self.search_widget.start_search(search_query, name) self.web_view.setFocus(Qt.FocusReason.OtherFocusReason) def toggle_bookmarks(self): is_visible = self.bookmarks_dock.isVisible() self.bookmarks_dock.setVisible(not is_visible) if is_visible: self.web_view.setFocus(Qt.FocusReason.OtherFocusReason) else: self.bookmarks_widget.bookmarks_list.setFocus(Qt.FocusReason.OtherFocusReason) def toggle_highlights(self): is_visible = self.highlights_dock.isVisible() self.highlights_dock.setVisible(not is_visible) if is_visible: self.web_view.setFocus(Qt.FocusReason.OtherFocusReason) else: self.highlights_widget.focus() def toggle_lookup(self, force_show=False): self.lookup_dock.setVisible(force_show or not self.lookup_dock.isVisible()) if force_show and self.lookup_dock.isVisible(): self.lookup_widget.on_forced_show() def check_for_read_aloud(self, where: str): if self.actions_toolbar.toggle_read_aloud_action.isChecked(): error_dialog(self, _('Cannot jump to location'), _( 'The Read aloud feature is active, cannot jump to {}. Close it first.').format(where), show=True) return True return False def toc_clicked(self, index): if self.check_for_read_aloud(_('Table of Contents locations')): return item = self.toc_model.itemFromIndex(index) self.web_view.goto_toc_node(item.node_id) self.force_focus_on_web_view() def force_focus_on_web_view(self): self.activateWindow() self.web_view.setFocus(Qt.FocusReason.OtherFocusReason) def toc_searched(self, index): item = self.toc_model.itemFromIndex(index) self.web_view.goto_toc_node(item.node_id) def bookmarks_edited(self, bookmarks): self.current_book_data['annotations_map']['bookmark'] = bookmarks # annotations will be saved in book file on exit self.save_annotations(in_book_file=False) def goto_cfi(self, cfi, add_to_history=False): self.web_view.goto_cfi(cfi, add_to_history=add_to_history) def bookmark_activated(self, cfi): if self.check_for_read_aloud(_('bookmark')): return self.goto_cfi(cfi, add_to_history=True) def view_image(self, name): path = get_path_for_name(name) if path: pmap = QPixmap() if pmap.load(path): self.image_popup.current_img = pmap self.image_popup.current_url = QUrl.fromLocalFile(path) self.image_popup() else: error_dialog(self, _('Invalid image'), _( "Failed to load the image {}").format(name), show=True) else: error_dialog(self, _('Image not found'), _( "Failed to find the image {}").format(name), show=True) def copy_image(self, name): path = get_path_for_name(name) if not path: return error_dialog(self, _('Image not found'), _( "Failed to find the image {}").format(name), show=True) try: img = image_from_path(path) except Exception: return error_dialog(self, _('Invalid image'), _( "Failed to load the image {}").format(name), show=True) url = QUrl.fromLocalFile(path) md = QMimeData() md.setImageData(img) md.setUrls([url]) QApplication.instance().clipboard().setMimeData(md) def dock_visibility_changed(self): vmap = {dock.objectName().partition('-')[0]: dock.toggleViewAction().isChecked() for dock in self.dock_widgets} self.actions_toolbar.update_dock_actions(vmap) # }}} # Load book {{{ def show_loading_message(self, msg): if msg: self.loading_overlay(msg) self.actions_toolbar.update_action_state(False) else: if not hasattr(self, 'initial_loading_performace_reported'): performance_monitor('loading finished') self.initial_loading_performace_reported = True self.loading_overlay.hide() self.actions_toolbar.update_action_state(True) def content_file_changed(self, fname): if self.pending_search: search, self.pending_search = self.pending_search, None self.show_search(text=search['query'], trigger=True, search_type=search['type'], case_sensitive=search['case_sensitive']) def show_error(self, title, msg, details): self.loading_overlay.hide() error_dialog(self, title, msg, det_msg=details or None, show=True) def print_book(self): if not hasattr(set_book_path, 'pathtoebook'): error_dialog(self, _('Cannot print book'), _( 'No book is currently open'), show=True) return from .printing import print_book print_book(set_book_path.pathtoebook, book_title=self.current_book_data['metadata']['title'], parent=self) @property def dock_widgets(self): return self.findChildren(QDockWidget, options=Qt.FindChildOption.FindDirectChildrenOnly) def reset_interface(self): for dock in self.dock_widgets: dock.setFloating(False) area = self.dock_defs[dock.objectName().partition('-')[0]].initial_area self.removeDockWidget(dock) self.addDockWidget(area, dock) dock.setVisible(False) for toolbar in self.findChildren(QToolBar): toolbar.setVisible(False) self.removeToolBar(toolbar) self.addToolBar(Qt.ToolBarArea.LeftToolBarArea, toolbar) def ask_for_open_from_js(self, path): if path and not os.path.exists(path): self.web_view.remove_recently_opened(path) error_dialog(self, _('Book does not exist'), _( 'Cannot open {} as it no longer exists').format(path), show=True) else: self.ask_for_open(path) def ask_for_open(self, path=None): if path is None: files = choose_files( self, 'ebook viewer open dialog', _('Choose e-book'), [(_('E-books'), available_input_formats())], all_files=False, select_only_single_file=True) if not files: return path = files[0] self.load_ebook(path) def continue_reading(self): rl = vprefs['session_data'].get('standalone_recently_opened') if rl: entry = rl[0] self.load_ebook(entry['pathtoebook']) def load_ebook(self, pathtoebook, open_at=None, reload_book=False): if '.' not in os.path.basename(pathtoebook): pathtoebook = os.path.abspath(os.path.realpath(pathtoebook)) performance_monitor('Load of book started', reset=True) self.actions_toolbar.update_action_state(False) self.web_view.show_home_page_on_ready = False if open_at: self.pending_open_at = open_at self.setWindowTitle(_('Loading book') + f'… — {self.base_window_title}') self.loading_overlay(_('Loading book, please wait')) self.save_annotations() self.save_reading_rates() self.current_book_data = {} get_current_book_data(self.current_book_data) self.search_widget.clear_searches() t = Thread(name='LoadBook', target=self._load_ebook_worker, args=(pathtoebook, open_at, reload_book or self.force_reload)) t.daemon = True t.start() def reload_book(self): if self.current_book_data: self.load_ebook(self.current_book_data['pathtoebook'], reload_book=True) def _load_ebook_worker(self, pathtoebook, open_at, reload_book): try: ans = prepare_book(pathtoebook, force=reload_book, prepare_notify=self.prepare_notify) except WorkerError as e: if not sip.isdeleted(self): self.book_prepared.emit(False, {'exception': e, 'tb': e.orig_tb, 'pathtoebook': pathtoebook}) except Exception as e: import traceback if not sip.isdeleted(self): self.book_prepared.emit(False, {'exception': e, 'tb': traceback.format_exc(), 'pathtoebook': pathtoebook}) else: performance_monitor('prepared emitted') if not sip.isdeleted(self): self.book_prepared.emit(True, {'base': ans, 'pathtoebook': pathtoebook, 'open_at': open_at, 'reloaded': reload_book}) def prepare_notify(self): performance_monitor('preparation started') self.book_preparation_started.emit() def load_finished(self, ok, data): cbd = self.calibre_book_data_for_first_book self.calibre_book_data_for_first_book = None if self.shutting_down: return open_at, self.pending_open_at = self.pending_open_at, None self.pending_search = None self.web_view.clear_caches() if not ok: self.actions_toolbar.update_action_state(False) self.setWindowTitle(self.base_window_title) tb = as_unicode(data['tb'].strip(), errors='replace') tb = re.split(r'^calibre\.gui2\.viewer\.convert_book\.ConversionFailure:\s*', tb, maxsplit=1, flags=re.M)[-1] last_line = tuple(tb.strip().splitlines())[-1] if last_line.startswith('calibre.ebooks.DRMError'): DRMErrorMessage(self).exec() else: error_dialog(self, _('Loading book failed'), _( 'Failed to open the book at {0}. Click "Show details" for more info.').format(data['pathtoebook']), det_msg=tb, show=True) self.loading_overlay.hide() self.web_view.show_home_page() return try: set_book_path(data['base'], data['pathtoebook']) except Exception: if data['reloaded']: raise self.load_ebook(data['pathtoebook'], open_at=data['open_at'], reload_book=True) return if iswindows: try: add_to_recent_docs(data['pathtoebook']) except Exception: import traceback traceback.print_exc() self.current_book_data = data get_current_book_data(self.current_book_data) self.current_book_data['annotations_map'] = defaultdict(list) self.current_book_data['annotations_path_key'] = path_key(data['pathtoebook']) + '.json' self.load_book_data(cbd) self.update_window_title() initial_cfi = self.initial_cfi_for_current_book() initial_position = {'type': 'cfi', 'data': initial_cfi} if initial_cfi else None if open_at: if open_at.startswith('toc:'): initial_toc_node = self.toc_model.node_id_for_text(open_at[len('toc:'):]) initial_position = {'type': 'toc', 'data': initial_toc_node} elif open_at.startswith('toc-href:'): initial_toc_node = self.toc_model.node_id_for_href(open_at[len('toc-href:'):], exact=True) initial_position = {'type': 'toc', 'data': initial_toc_node} elif open_at.startswith('toc-href-contains:'): initial_toc_node = self.toc_model.node_id_for_href(open_at[len('toc-href-contains:'):], exact=False) initial_position = {'type': 'toc', 'data': initial_toc_node} elif open_at.startswith('epubcfi(/'): initial_position = {'type': 'cfi', 'data': open_at} elif open_at.startswith('ref:'): initial_position = {'type': 'ref', 'data': open_at[len('ref:'):]} elif open_at.startswith('search:'): self.pending_search = {'type': 'normal', 'query': open_at[len('search:'):], 'case_sensitive': False} initial_position = {'type': 'bookpos', 'data': 0} elif open_at.startswith('regex:'): self.pending_search = {'type': 'regex', 'query': open_at[len('regex:'):], 'case_sensitive': True} initial_position = {'type': 'bookpos', 'data': 0} elif is_float(open_at): initial_position = {'type': 'bookpos', 'data': float(open_at)} highlights = self.current_book_data['annotations_map']['highlight'] self.highlights_widget.load(highlights) rates = load_reading_rates(self.current_book_data['annotations_path_key']) self.web_view.start_book_load(initial_position=initial_position, highlights=highlights, current_book_data=self.current_book_data, reading_rates=rates) performance_monitor('webview loading requested') def load_book_data(self, calibre_book_data=None): self.current_book_data['book_library_details'] = get_book_library_details(self.current_book_data['pathtoebook']) if calibre_book_data is not None: self.current_book_data['calibre_book_id'] = calibre_book_data['book_id'] self.current_book_data['calibre_book_uuid'] = calibre_book_data['uuid'] self.current_book_data['calibre_book_fmt'] = calibre_book_data['fmt'] self.current_book_data['calibre_library_id'] = calibre_book_data['library_id'] self.load_book_annotations(calibre_book_data) path = os.path.join(self.current_book_data['base'], 'calibre-book-manifest.json') with open(path, 'rb') as f: raw = f.read() self.current_book_data['manifest'] = manifest = json.loads(raw) toc = manifest.get('toc') self.toc_model = TOC(toc) self.toc.setModel(self.toc_model) self.bookmarks_widget.set_bookmarks(self.current_book_data['annotations_map']['bookmark']) self.current_book_data['metadata'] = set_book_path.parsed_metadata self.current_book_data['manifest'] = set_book_path.parsed_manifest def load_book_annotations(self, calibre_book_data=None): amap = self.current_book_data['annotations_map'] path = os.path.join(self.current_book_data['base'], 'calibre-book-annotations.json') if os.path.exists(path): with open(path, 'rb') as f: raw = f.read() merge_annotations(parse_annotations(raw), amap) path = os.path.join(annotations_dir, self.current_book_data['annotations_path_key']) if os.path.exists(path): with open(path, 'rb') as f: raw = f.read() merge_annotations(parse_annotations(raw), amap) if calibre_book_data is None: bld = self.current_book_data['book_library_details'] if bld is not None: lib_amap = load_annotations_map_from_library(bld) sau = get_session_pref('sync_annots_user', default='') if sau: other_amap = load_annotations_map_from_library(bld, user_type='web', user=sau) if other_amap: merge_annotations(other_amap, lib_amap) if lib_amap: for annot_type, annots in iteritems(lib_amap): merge_annotations(annots, amap) else: for annot_type, annots in iteritems(calibre_book_data['annotations_map']): merge_annotations(annots, amap) def update_window_title(self): try: title = self.current_book_data['metadata']['title'] except Exception: title = _('Unknown') book_format = self.current_book_data['manifest']['book_format'] title = f'{title} [{book_format}] — {self.base_window_title}' self.setWindowTitle(title) # }}} # CFI management {{{ def initial_cfi_for_current_book(self): lrp = self.current_book_data['annotations_map']['last-read'] if lrp and get_session_pref('remember_last_read', default=True): lrp = lrp[0] if lrp['pos_type'] == 'epubcfi': return lrp['pos'] def cfi_changed(self, cfi): if not self.current_book_data: return self.current_book_data['annotations_map']['last-read'] = [{ 'pos': cfi, 'pos_type': 'epubcfi', 'timestamp': utcnow().isoformat()}] self.save_pos_timer.start() # }}} # State serialization {{{ def save_annotations(self, in_book_file=True): if not self.current_book_data: return if self.annotations_saver is None: self.annotations_saver = AnnotationsSaveWorker() self.annotations_saver.start() self.annotations_saver.save_annotations( self.current_book_data, in_book_file and get_session_pref('save_annotations_in_ebook', default=True), get_session_pref('sync_annots_user', default='') ) def update_reading_rates(self, rates): if not self.current_book_data: return self.current_book_data['reading_rates'] = rates self.save_reading_rates() def save_reading_rates(self): if not self.current_book_data: return key = self.current_book_data.get('annotations_path_key') rates = self.current_book_data.get('reading_rates') if key and rates: save_reading_rates(key, rates) def highlights_changed(self, highlights): if not self.current_book_data: return amap = self.current_book_data['annotations_map'] amap['highlight'] = highlights self.highlights_widget.refresh(highlights) self.save_annotations() def notes_edited(self, uuid, notes): for h in self.current_book_data['annotations_map']['highlight']: if h.get('uuid') == uuid: h['notes'] = notes h['timestamp'] = utcnow().isoformat() break else: return self.save_annotations() def edit_book(self, file_name, progress_frac, selected_text): import subprocess from calibre.ebooks.oeb.polish.main import SUPPORTED from calibre.utils.ipc.launch import exe_path, macos_edit_book_bundle_path try: path = set_book_path.pathtoebook except AttributeError: return error_dialog(self, _('Cannot edit book'), _( 'No book is currently open'), show=True) fmt = path.rpartition('.')[-1].upper().replace('ORIGINAL_', '') if fmt not in SUPPORTED: return error_dialog(self, _('Cannot edit book'), _( 'The book must be in the %s formats to edit.' '\n\nFirst convert the book to one of these formats.' ) % (_(' or ').join(SUPPORTED)), show=True) exe = 'ebook-edit' if ismacos: exe = os.path.join(macos_edit_book_bundle_path(), exe) else: exe = exe_path(exe) cmd = [exe] if isinstance(exe, str) else list(exe) if selected_text: cmd += ['--select-text', selected_text] from calibre.gui2.widgets import BusyCursor with sanitize_env_vars(): subprocess.Popen(cmd + [path, file_name]) with BusyCursor(): time.sleep(2) def save_state(self): with vprefs: vprefs['main_window_state'] = bytearray(self.saveState(self.MAIN_WINDOW_STATE_VERSION)) self.save_geometry(vprefs, 'main_window_geometry') def restore_state(self): state = vprefs['main_window_state'] if not get_session_pref('remember_window_geometry', default=False) or not self.restore_geometry(vprefs, 'main_window_geometry'): QApplication.instance().ensure_window_on_screen(self) if state: self.restoreState(state, self.MAIN_WINDOW_STATE_VERSION) self.inspector_dock.setVisible(False) if not get_session_pref('restore_docks', True): for dock_def in self.dock_defs.values(): d = getattr(self, '{}_dock'.format(dock_def.name.partition('-')[0])) d.setVisible(False) def quit(self): self.close() def force_close(self): if not self.close_forced: self.close_forced = True self.quit() def close_prep_finished(self, cfi): if cfi: self.cfi_changed(cfi) self.force_close() def closeEvent(self, ev): if self.shutdown_done: return if self.current_book_data and self.web_view.view_is_ready and not self.close_forced: ev.ignore() if not self.shutting_down: self.shutting_down = True QTimer.singleShot(2000, self.force_close) self.web_view.prepare_for_close() return self.shutting_down = True self.search_widget.shutdown() self.web_view.shutdown() try: self.save_state() self.save_annotations() self.save_reading_rates() if self.annotations_saver is not None: self.annotations_saver.shutdown() self.annotations_saver = None except Exception: import traceback traceback.print_exc() clean_running_workers() self.shutdown_done = True return MainWindow.closeEvent(self, ev) # }}} # Auto-hide mouse cursor {{{ def setup_mouse_auto_hide(self): QApplication.instance().installEventFilter(self) self.cursor_hidden = False self.hide_cursor_timer = t = QTimer(self) t.setSingleShot(True), t.setInterval(3000) t.timeout.connect(self.hide_cursor) t.start() def eventFilter(self, obj, ev): et = ev.type() if et == QEvent.Type.MouseMove: if self.cursor_hidden: self.cursor_hidden = False QApplication.instance().restoreOverrideCursor() self.hide_cursor_timer.start() elif et == QEvent.Type.FocusIn: if iswindows and obj and obj.objectName() == 'EbookViewerClassWindow' and self.isFullScreen(): # See https://bugs.launchpad.net/calibre/+bug/1918591 self.web_view.repair_after_fullscreen_switch() return False def hide_cursor(self): if get_session_pref('auto_hide_mouse', True): self.cursor_hidden = True QApplication.instance().setOverrideCursor(Qt.CursorShape.BlankCursor) # }}}
37,953
Python
.py
775
38.997419
158
0.639284
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,765
highlights.py
kovidgoyal_calibre/src/calibre/gui2/viewer/highlights.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> import json import math from collections import defaultdict from functools import lru_cache from itertools import chain from qt.core import ( QAbstractItemView, QColor, QDialog, QDialogButtonBox, QFont, QHBoxLayout, QIcon, QImage, QItemSelectionModel, QKeySequence, QLabel, QListView, QListWidget, QListWidgetItem, QMenu, QPainter, QPainterPath, QPalette, QPixmap, QPushButton, QRect, QSize, QSizePolicy, QStyle, Qt, QTextCursor, QTextEdit, QToolButton, QTreeWidget, QTreeWidgetItem, QVBoxLayout, QWidget, pyqtSignal, ) from calibre.constants import builtin_colors_dark, builtin_colors_light, builtin_decorations from calibre.ebooks.epub.cfi.parse import cfi_sort_key from calibre.gui2 import error_dialog, is_dark_theme, safe_open_url from calibre.gui2.dialogs.confirm_delete import confirm from calibre.gui2.gestures import GestureManager from calibre.gui2.library.annotations import ChapterGroup, Details, render_notes from calibre.gui2.library.annotations import Export as ExportBase from calibre.gui2.viewer import get_boss, link_prefix_for_location_links from calibre.gui2.viewer.config import vprefs from calibre.gui2.viewer.search import SearchInput from calibre.gui2.viewer.shortcuts import get_shortcut_for, index_to_key_sequence from calibre.gui2.widgets2 import Dialog from calibre.utils.localization import _, ngettext from calibre_extensions.progress_indicator import set_no_activate_on_click decoration_cache = {} highlight_role = Qt.ItemDataRole.UserRole section_role = highlight_role + 1 @lru_cache(maxsize=8) def wavy_path(width, height, y_origin): half_height = height / 2 path = QPainterPath() pi2 = math.pi * 2 num = 100 num_waves = 4 wav_limit = num // num_waves sin = math.sin path.reserve(num) for i in range(num): x = width * i / num rads = pi2 * (i % wav_limit) / wav_limit factor = sin(rads) y = y_origin + factor * half_height path.lineTo(x, y) if i else path.moveTo(x, y) return path def compute_style_key(style): return tuple((k, style[k]) for k in sorted(style)) def decoration_for_style(palette, style, icon_size, device_pixel_ratio, is_dark): style_key = (is_dark, icon_size, device_pixel_ratio, compute_style_key(style)) sentinel = object() ans = decoration_cache.get(style_key, sentinel) if ans is not sentinel: return ans ans = None kind = style.get('kind') if kind == 'color': key = 'dark' if is_dark else 'light' val = style.get(key) if val is None: which = style.get('which') val = (builtin_colors_dark if is_dark else builtin_colors_light).get(which) if val is None: val = style.get('background-color') if val is not None: ans = QColor(val) elif kind == 'decoration': which = style.get('which') if which is not None: q = builtin_decorations.get(which) if q is not None: style = q sz = int(math.ceil(icon_size * device_pixel_ratio)) canvas = QImage(sz, sz, QImage.Format.Format_ARGB32) canvas.fill(Qt.GlobalColor.transparent) canvas.setDevicePixelRatio(device_pixel_ratio) p = QPainter(canvas) p.setRenderHint(QPainter.RenderHint.Antialiasing, True) p.setPen(palette.color(QPalette.ColorRole.WindowText)) irect = QRect(0, 0, icon_size, icon_size) adjust = -2 text_rect = p.drawText(irect.adjusted(0, adjust, 0, adjust), Qt.AlignmentFlag.AlignHCenter| Qt.AlignmentFlag.AlignTop, 'a') p.drawRect(irect) fm = p.fontMetrics() pen = p.pen() if 'text-decoration-color' in style: pen.setColor(QColor(style['text-decoration-color'])) lstyle = style.get('text-decoration-style') or 'solid' q = {'dotted': Qt.PenStyle.DotLine, 'dashed': Qt.PenStyle.DashLine, }.get(lstyle) if q is not None: pen.setStyle(q) lw = fm.lineWidth() if lstyle == 'double': lw * 2 pen.setWidth(fm.lineWidth()) q = style.get('text-decoration-line') or 'underline' pos = text_rect.bottom() height = irect.bottom() - pos if q == 'overline': pos = height elif q == 'line-through': pos = text_rect.center().y() - adjust - lw // 2 p.setPen(pen) if lstyle == 'wavy': p.drawPath(wavy_path(icon_size, height, pos)) else: p.drawLine(0, pos, irect.right(), pos) p.end() ans = QPixmap.fromImage(canvas) elif 'background-color' in style: ans = QColor(style['background-color']) decoration_cache[style_key] = ans return ans class SwatchList(QListWidget): def __init__(self, all_styles, selected_styles, parent=None): super().__init__(parent) self.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection) self.setViewMode(QListView.ViewMode.IconMode) icon_size = parent.style().pixelMetric(QStyle.PixelMetric.PM_IconViewIconSize, None, self) self.setIconSize(QSize(icon_size, icon_size)) self.setSpacing(20) dpr = self.devicePixelRatioF() is_dark = is_dark_theme() flags = Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemNeverHasChildren self.itemClicked.connect(self.toggle_item) for s in all_styles: key = compute_style_key(s) dec = decoration_for_style(self.palette(), s, icon_size, dpr, is_dark) i = QListWidgetItem(self) i.setFlags(flags) i.setData(Qt.ItemDataRole.UserRole, s) i.setData(Qt.ItemDataRole.UserRole + 1, key) if dec: i.setData(Qt.ItemDataRole.DecorationRole, dec) i.setCheckState(Qt.CheckState.Checked if selected_styles and key in selected_styles else Qt.CheckState.Unchecked) def toggle_item(self, item): item.setCheckState(Qt.CheckState.Unchecked if item.checkState() == Qt.CheckState.Checked else Qt.CheckState.Checked) @property def selected_styles(self): for i in range(self.count()): item = self.item(i) if item.checkState() == Qt.CheckState.Checked: yield item.data(Qt.ItemDataRole.UserRole + 1) def select_all(self): for i in range(self.count()): self.item(i).setCheckState(Qt.CheckState.Checked) def select_none(self): for i in range(self.count()): self.item(i).setCheckState(Qt.CheckState.Unchecked) class FilterDialog(Dialog): def __init__(self, all_styles, show_only_styles, parent=None): self.all_styles, self.show_only_styles = all_styles, show_only_styles super().__init__(_('Filter shown highlights'), 'filter-highlights', parent=parent) def sizeHint(self): return QSize(500, 400) def setup_ui(self): self.setWindowIcon(QIcon.ic('filter.png')) self.l = l = QVBoxLayout(self) la = QLabel(_('Choose what kinds of highlights will be displayed, below. If none are selected, no filtering is performed.')) la.setWordWrap(True) l.addWidget(la) self.swatches = s = SwatchList(self.all_styles, self.show_only_styles, self) l.addWidget(s) l.addWidget(self.bb) self.bb.addButton(_('Select &all'), QDialogButtonBox.ButtonRole.ActionRole).clicked.connect(s.select_all) self.bb.addButton(_('Select &none'), QDialogButtonBox.ButtonRole.ActionRole).clicked.connect(s.select_none) @property def selected_styles(self): return frozenset(self.swatches.selected_styles) class Export(ExportBase): prefs = vprefs pref_name = 'highlight_export_format' def file_type_data(self): return _('calibre highlights'), 'calibre_highlights' def initial_filename(self): return _('highlights') def exported_data(self): fmt = self.export_format.currentData() if fmt == 'calibre_highlights': return json.dumps({ 'version': 1, 'type': 'calibre_highlights', 'highlights': self.annotations, }, ensure_ascii=False, sort_keys=True, indent=2) lines = [] as_markdown = fmt == 'md' link_prefix = link_prefix_for_location_links() root = ChapterGroup() for a in self.annotations: root.add_annot(a) root.render_as_text(lines, as_markdown, link_prefix) return '\n'.join(lines).strip() class Highlights(QTreeWidget): jump_to_highlight = pyqtSignal(object) current_highlight_changed = pyqtSignal(object) delete_requested = pyqtSignal() edit_requested = pyqtSignal() edit_notes_requested = pyqtSignal() export_selected_requested = pyqtSignal() def __init__(self, parent=None): QTreeWidget.__init__(self, parent) self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.customContextMenuRequested.connect(self.show_context_menu) self.styles_to_show = frozenset() self.default_decoration = QIcon.ic('blank.png') self.setHeaderHidden(True) self.num_of_items = 0 self.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) set_no_activate_on_click(self) self.itemActivated.connect(self.item_activated) self.currentItemChanged.connect(self.current_item_changed) self.uuid_map = {} self.section_font = QFont(self.font()) self.section_font.setItalic(True) self.gesture_manager = GestureManager(self) self.setVerticalScrollMode(QAbstractItemView.ScrollMode.ScrollPerPixel) 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) def show_context_menu(self, point): index = self.indexAt(point) h = index.data(highlight_role) self.context_menu = m = QMenu(self) if h is not None: m.addAction(QIcon.ic('edit_input.png'), _('Modify this highlight'), self.edit_requested.emit) m.addAction(QIcon.ic('modified.png'), _('Edit notes for this highlight'), self.edit_notes_requested.emit) m.addAction(QIcon.ic('trash.png'), ngettext( 'Delete this highlight', 'Delete selected highlights', len(self.selectedItems()) ), self.delete_requested.emit) m.addSeparator() if tuple(self.selected_highlights): m.addAction(QIcon.ic('save.png'), _('Export selected highlights'), self.export_selected_requested.emit) m.addAction(QIcon.ic('plus.png'), _('Expand all'), self.expandAll) m.addAction(QIcon.ic('minus.png'), _('Collapse all'), self.collapseAll) self.context_menu.popup(self.mapToGlobal(point)) return True def current_item_changed(self, current, previous): self.current_highlight_changed.emit(current.data(0, highlight_role) if current is not None else None) def load(self, highlights, preserve_state=False): s = self.style() expanded_chapters = set() if preserve_state: root = self.invisibleRootItem() for i in range(root.childCount()): chapter = root.child(i) if chapter.isExpanded(): expanded_chapters.add(chapter.data(0, section_role)) icon_size = s.pixelMetric(QStyle.PixelMetric.PM_SmallIconSize, None, self) dpr = self.devicePixelRatioF() is_dark = is_dark_theme() self.clear() self.uuid_map = {} highlights = (h for h in highlights if not h.get('removed') and h.get('highlighted_text')) smap = {} repeated_short_titles = defaultdict(set) @lru_cache def tooltip_for(tfam): tooltip = '' if len(tfam) > 1: lines = [] for i, node in enumerate(tfam): lines.append('\xa0\xa0' * i + '➤ ' + node) tooltip = ngettext('Table of Contents section:', 'Table of Contents sections:', len(lines)) tooltip += '\n' + '\n'.join(lines) return tooltip for h in self.sorted_highlights(highlights): tfam = tuple(h.get('toc_family_titles') or ()) if tfam: tsec = tfam[0] lsec = tfam[-1] key = tfam else: tsec = h.get('top_level_section_title') lsec = h.get('lowest_level_section_title') key = (tsec or '', lsec or '') short_title = lsec or tsec or _('Unknown') section = { 'title': short_title, 'tfam': tfam, 'tsec': tsec, 'lsec': lsec, 'items': [], 'tooltip': tooltip_for(tfam), 'key': key, } smap.setdefault(key, section)['items'].append(h) repeated_short_titles[short_title].add(key) for keys in repeated_short_titles.values(): if len(keys) > 1: for key in keys: section = smap[key] if section['tfam']: section['title'] = ' ➤ '.join(tfam) elif section['tsec'] and section['lsec']: section['title'] = ' ➤ '.join((section['tsec'], section['lsec'])) for secnum, (sec_key, sec) in enumerate(smap.items()): section = QTreeWidgetItem([sec['title']], 1) section.setFlags(Qt.ItemFlag.ItemIsEnabled) section.setFont(0, self.section_font) section.setData(0, section_role, sec['key']) if sec['tooltip']: section.setToolTip(0, sec['tooltip']) self.addTopLevelItem(section) section.setExpanded(not preserve_state or sec['key'] in expanded_chapters) for itemnum, h in enumerate(sec['items']): txt = h.get('highlighted_text') txt = txt.replace('\n', ' ') if h.get('notes'): txt = '•' + txt if len(txt) > 100: txt = txt[:100] + '…' item = QTreeWidgetItem(section, [txt], 2) item.setFlags(Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemNeverHasChildren) item.setData(0, highlight_role, h) try: dec = decoration_for_style(self.palette(), h.get('style') or {}, icon_size, dpr, is_dark) except Exception: import traceback traceback.print_exc() dec = None if dec is None: dec = self.default_decoration item.setData(0, Qt.ItemDataRole.DecorationRole, dec) self.uuid_map[h['uuid']] = secnum, itemnum self.num_of_items += 1 self.apply_filters() def sorted_highlights(self, highlights): def_idx = 999999999999999 defval = def_idx, cfi_sort_key('/99999999') def cfi_key(h): cfi = h.get('start_cfi') si = h.get('spine_index', def_idx) return (si, cfi_sort_key(cfi)) if cfi else defval return sorted(highlights, key=cfi_key) def refresh(self, highlights): h = self.current_highlight self.load(highlights, preserve_state=True) if h is not None: idx = self.uuid_map.get(h['uuid']) if idx is not None: sec_idx, item_idx = idx self.set_current_row(sec_idx, item_idx) def iteritems(self): root = self.invisibleRootItem() for i in range(root.childCount()): sec = root.child(i) for k in range(sec.childCount()): yield sec.child(k) def count(self): return self.num_of_items def find_query(self, query): pat = query.regex items = tuple(self.iteritems()) count = len(items) cr = -1 ch = self.current_highlight if ch: q = ch['uuid'] for i, item in enumerate(items): h = item.data(0, highlight_role) if h['uuid'] == q: cr = i if query.backwards: if cr < 0: cr = count indices = chain(range(cr - 1, -1, -1), range(count - 1, cr, -1)) else: if cr < 0: cr = -1 indices = chain(range(cr + 1, count), range(0, cr + 1)) for i in indices: h = items[i].data(0, highlight_role) if pat.search(h['highlighted_text']) is not None or pat.search(h.get('notes') or '') is not None: self.set_current_row(*self.uuid_map[h['uuid']]) return True return False def find_annot_id(self, annot_id): q = self.uuid_map.get(annot_id) if q is not None: self.set_current_row(*q) return True return False def set_current_row(self, sec_idx, item_idx): sec = self.topLevelItem(sec_idx) if sec is not None: item = sec.child(item_idx) if item is not None: self.setCurrentItem(item, 0, QItemSelectionModel.SelectionFlag.ClearAndSelect) return True return False def item_activated(self, item): h = item.data(0, highlight_role) if h is not None: self.jump_to_highlight.emit(h) @property def current_highlight(self): i = self.currentItem() if i is not None: return i.data(0, highlight_role) @property def all_highlights(self): for item in self.iteritems(): yield item.data(0, highlight_role) @property def selected_highlights(self): for item in self.selectedItems(): yield item.data(0, highlight_role) @property def all_highlight_styles(self): seen = set() for h in self.all_highlights: s = h.get('style') if h.get('removed') or h.get('type') != 'highlight' or not s: continue k = compute_style_key(s) if k not in seen: yield s seen.add(k) def apply_filters(self): q = self.styles_to_show for item in self.iteritems(): h = item.data(0, highlight_role) hidden = False if q: skey = compute_style_key(h.get('style', {})) hidden = skey not in q item.setHidden(hidden) root = self.invisibleRootItem() for i in range(root.childCount()): sec = root.child(i) for k in range(sec.childCount()): if not sec.child(k).isHidden(): sec.setHidden(False) break else: sec.setHidden(True) def keyPressEvent(self, ev): if ev.matches(QKeySequence.StandardKey.Delete): self.delete_requested.emit() ev.accept() return if ev.key() == Qt.Key.Key_F2: self.edit_requested.emit() ev.accept() return return super().keyPressEvent(ev) class NotesEditDialog(Dialog): def __init__(self, notes, parent=None): self.initial_notes = notes Dialog.__init__(self, name='edit-notes-highlight', title=_('Edit notes'), parent=parent) def setup_ui(self): l = QVBoxLayout(self) self.qte = qte = QTextEdit(self) qte.setMinimumHeight(400) qte.setMinimumWidth(600) if self.initial_notes: qte.setPlainText(self.initial_notes) qte.moveCursor(QTextCursor.MoveOperation.End) l.addWidget(qte) l.addWidget(self.bb) @property def notes(self): return self.qte.toPlainText().rstrip() class NotesDisplay(Details): notes_edited = pyqtSignal(object) def __init__(self, parent=None): Details.__init__(self, parent) self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Maximum) self.anchorClicked.connect(self.anchor_clicked) self.current_notes = '' def show_notes(self, text=''): text = (text or '').strip() self.setVisible(bool(text)) self.current_notes = text html = '\n'.join(render_notes(text)) self.setHtml('<div><a href="edit://moo">{}</a></div>{}'.format(_('Edit notes'), html)) self.document().setDefaultStyleSheet('a[href] { text-decoration: none }') h = self.document().size().height() + 2 self.setMaximumHeight(int(h)) def anchor_clicked(self, qurl): if qurl.scheme() == 'edit': self.edit_notes() else: safe_open_url(qurl) def edit_notes(self): current_text = self.current_notes d = NotesEditDialog(current_text, self) if d.exec() == QDialog.DialogCode.Accepted and d.notes != current_text: self.notes_edited.emit(d.notes) class HighlightsPanel(QWidget): request_highlight_action = pyqtSignal(object, object) web_action = pyqtSignal(object, object) toggle_requested = pyqtSignal() notes_edited_signal = pyqtSignal(object, object) def __init__(self, parent=None): QWidget.__init__(self, parent) self.setFocusPolicy(Qt.FocusPolicy.NoFocus) self.l = l = QVBoxLayout(self) l.setContentsMargins(0, 0, 0, 0) self.search_input = si = SearchInput(self, 'highlights-search', show_return_button=False) si.do_search.connect(self.search_requested) l.addWidget(si) h = QHBoxLayout() la = QLabel(_('Double click to jump to an entry')) self.filter_button = b = QToolButton(self) b.setIcon(QIcon.ic('filter.png')), b.setToolTip(_('Show only highlights of specific types')) b.clicked.connect(self.change_active_filter) h.addWidget(la), h.addStretch(10), h.addWidget(b) l.addLayout(h) self.highlights = h = Highlights(self) l.addWidget(h) h.jump_to_highlight.connect(self.jump_to_highlight) h.delete_requested.connect(self.remove_highlight) h.edit_requested.connect(self.edit_highlight) h.edit_notes_requested.connect(self.edit_notes) h.current_highlight_changed.connect(self.current_highlight_changed) h.export_selected_requested.connect(self.export_selected) self.load = h.load self.refresh = h.refresh self.h = h = QHBoxLayout() def button(icon, text, tt, target): b = QPushButton(QIcon.ic(icon), text, self) b.setToolTip(tt) b.setFocusPolicy(Qt.FocusPolicy.NoFocus) b.clicked.connect(target) return b self.edit_button = button('edit_input.png', _('Modify'), _('Modify the selected highlight'), self.edit_highlight) self.remove_button = button('trash.png', _('Delete'), _('Delete the selected highlights'), self.remove_highlight) self.export_button = button('save.png', _('Export'), _('Export all highlights'), self.export) h.addWidget(self.edit_button), h.addWidget(self.remove_button), h.addWidget(self.export_button) self.notes_display = nd = NotesDisplay(self) nd.notes_edited.connect(self.notes_edited) l.addWidget(nd) nd.setVisible(False) l.addLayout(h) def change_active_filter(self): d = FilterDialog(self.highlights.all_highlight_styles, self.highlights.styles_to_show, self) if d.exec() == QDialog.DialogCode.Accepted: self.highlights.styles_to_show = d.selected_styles self.highlights.apply_filters() def notes_edited(self, text): h = self.highlights.current_highlight if h is not None: h['notes'] = text self.web_action.emit('set-notes-in-highlight', h) self.notes_edited_signal.emit(h['uuid'], text) def set_tooltips(self, rmap): a = rmap.get('create_annotation') if a: def as_text(idx): return index_to_key_sequence(idx).toString(QKeySequence.SequenceFormat.NativeText) tt = self.add_button.toolTip().partition('[')[0].strip() keys = sorted(filter(None, map(as_text, a))) if keys: self.add_button.setToolTip('{} [{}]'.format(tt, ', '.join(keys))) def search_requested(self, query): if not self.highlights.find_query(query): error_dialog(self, _('No matches'), _( 'No highlights match the search: {}').format(query.text), show=True) def focus(self): self.highlights.setFocus(Qt.FocusReason.OtherFocusReason) def jump_to_highlight(self, highlight): boss = get_boss() if boss.check_for_read_aloud(_('the location of this highlight')): return self.request_highlight_action.emit(highlight['uuid'], 'goto') def current_highlight_changed(self, highlight): nd = self.notes_display if highlight is None or not highlight.get('notes'): nd.show_notes() else: nd.show_notes(highlight['notes']) def no_selected_highlight(self): error_dialog(self, _('No selected highlight'), _( 'No highlight is currently selected'), show=True) def edit_highlight(self): boss = get_boss() if boss.check_for_read_aloud(_('the location of this highlight')): return h = self.highlights.current_highlight if h is None: return self.no_selected_highlight() self.request_highlight_action.emit(h['uuid'], 'edit') def edit_notes(self): self.notes_display.edit_notes() def remove_highlight(self): highlights = tuple(self.highlights.selected_highlights) if not highlights: return self.no_selected_highlight() if confirm( ngettext( 'Are you sure you want to delete this highlight permanently?', 'Are you sure you want to delete all {} highlights permanently?', len(highlights)).format(len(highlights)), 'delete-highlight-from-viewer', parent=self, config_set=vprefs ): for h in highlights: self.request_highlight_action.emit(h['uuid'], 'delete') def export(self): hl = list(self.highlights.all_highlights) if not hl: return error_dialog(self, _('No highlights'), _('This book has no highlights to export'), show=True) Export(hl, self).exec() def export_selected(self): hl = list(self.highlights.selected_highlights) if not hl: return error_dialog(self, _('No highlights'), _('No highlights selected to export'), show=True) Export(hl, self).exec() def selected_text_changed(self, text, annot_id): if annot_id: self.highlights.find_annot_id(annot_id) def keyPressEvent(self, ev): sc = get_shortcut_for(self, ev) if sc == 'toggle_highlights' or ev.key() == Qt.Key.Key_Escape: self.toggle_requested.emit() return super().keyPressEvent(ev)
27,634
Python
.py
643
33.191291
134
0.608941
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,766
config.py
kovidgoyal_calibre/src/calibre/gui2/viewer/config.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> import json import os import tempfile from calibre.constants import cache_dir, config_dir from calibre.utils.config import JSONConfig from calibre.utils.date import isoformat, utcnow from calibre.utils.filenames import atomic_rename vprefs = JSONConfig('viewer-webengine') viewer_config_dir = os.path.join(config_dir, 'viewer') vprefs.defaults['session_data'] = {} vprefs.defaults['local_storage'] = {} vprefs.defaults['main_window_state'] = None vprefs.defaults['main_window_geometry'] = None vprefs.defaults['old_prefs_migrated'] = False vprefs.defaults['bookmarks_sort'] = 'title' vprefs.defaults['highlight_export_format'] = 'txt' vprefs.defaults['auto_update_lookup'] = True def get_session_pref(name, default=None, group='standalone_misc_settings'): sd = vprefs['session_data'] g = sd.get(group, {}) if group else sd return g.get(name, default) def get_pref_group(name): sd = vprefs['session_data'] return sd.get(name) or {} def reading_rates_path(): return os.path.join(cache_dir(), 'viewer-reading-rates.json') def get_existing_reading_rates(): path = reading_rates_path() existing = {} try: with open(path, 'rb') as f: raw = f.read() except OSError: pass else: try: existing = json.loads(raw) except Exception: pass return existing def save_reading_rates(key, rates): existing = get_existing_reading_rates() existing.pop(key, None) existing[key] = rates while len(existing) > 50: expired = next(iter(existing)) del existing[expired] ddata = json.dumps(existing, indent=2).encode('utf-8') path = reading_rates_path() try: with tempfile.NamedTemporaryFile(dir=os.path.dirname(path), delete=False) as f: f.write(ddata) atomic_rename(f.name, path) except Exception: import traceback traceback.print_exc() def load_reading_rates(key): existing = get_existing_reading_rates() return existing.get(key) def expand_profile_user_names(user_names): user_names = set(user_names) sau = get_session_pref('sync_annots_user', default='') if sau: if sau == '*': sau = 'user:' if 'viewer:' in user_names: user_names.add(sau) elif sau in user_names: user_names.add('viewer:') return user_names def load_viewer_profiles(*user_names: str): user_names = expand_profile_user_names(user_names) ans = {} try: with open(os.path.join(viewer_config_dir, 'profiles.json'), 'rb') as f: raw = json.loads(f.read()) except FileNotFoundError: return ans for uname, profiles in raw.items(): if uname in user_names: for profile_name, profile in profiles.items(): if profile_name not in ans or ans[profile_name]['__timestamp__'] <= profile['__timestamp__']: ans[profile_name] = profile return ans def save_viewer_profile(profile_name, profile, *user_names: str): user_names = expand_profile_user_names(user_names) if isinstance(profile, (str, bytes)): profile = json.loads(profile) if isinstance(profile, dict): profile['__timestamp__'] = isoformat(utcnow()) from calibre.gui2.viewer.toolbars import DEFAULT_ACTIONS, current_actions ca = current_actions() s = {} if ca != DEFAULT_ACTIONS: s['toolbar-actions'] = ca if s: profile['__standalone_extra_settings__'] = s try: with open(os.path.join(viewer_config_dir, 'profiles.json'), 'rb') as f: raw = json.loads(f.read()) except FileNotFoundError: raw = {} for name in user_names: if isinstance(profile, dict): raw.setdefault(name, {})[profile_name] = profile else: if name in raw: raw[name].pop(profile_name, None) with open(os.path.join(viewer_config_dir, 'profiles.json'), 'wb') as f: f.write(json.dumps(raw, indent=2, sort_keys=True).encode())
4,184
Python
.py
112
30.8125
109
0.647001
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,767
web_view.py
kovidgoyal_calibre/src/calibre/gui2/viewer/web_view.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> import os import shutil import sys from itertools import count from qt.core import ( QT_VERSION, QApplication, QByteArray, QEvent, QFontDatabase, QFontInfo, QHBoxLayout, QLocale, QMimeData, QPalette, QSize, Qt, QTimer, QUrl, QWidget, pyqtSignal, sip, ) from qt.webengine import ( QWebEnginePage, QWebEngineProfile, QWebEngineScript, QWebEngineSettings, QWebEngineUrlRequestJob, QWebEngineUrlSchemeHandler, QWebEngineView, ) from calibre import as_unicode, prints from calibre.constants import FAKE_HOST, FAKE_PROTOCOL, __version__, in_develop_mode, is_running_from_develop, ismacos, iswindows from calibre.ebooks.metadata.book.base import field_metadata from calibre.ebooks.oeb.polish.utils import guess_type from calibre.gui2 import choose_images, config, error_dialog, safe_open_url from calibre.gui2.viewer import link_prefix_for_location_links, performance_monitor, url_for_book_in_library from calibre.gui2.viewer.config import load_viewer_profiles, save_viewer_profile, viewer_config_dir, vprefs from calibre.gui2.viewer.tts import TTS from calibre.gui2.webengine import RestartingWebEngineView from calibre.srv.code import get_translations_data from calibre.utils.filenames import make_long_path_useable from calibre.utils.localization import _, localize_user_manual_link from calibre.utils.resources import get_path as P from calibre.utils.serialize import json_loads from calibre.utils.shared_file import share_open from calibre.utils.webengine import Bridge, create_script, from_js, insert_scripts, secure_webengine, send_reply, setup_profile, to_js from polyglot.builtins import as_bytes, iteritems from polyglot.functools import lru_cache SANDBOX_HOST = FAKE_HOST.rpartition('.')[0] + '.sandbox' # Override network access to load data from the book {{{ def set_book_path(path, pathtoebook): set_book_path.pathtoebook = pathtoebook set_book_path.path = os.path.abspath(path) set_book_path.metadata = get_data('calibre-book-metadata.json')[0] set_book_path.manifest, set_book_path.manifest_mime = get_data('calibre-book-manifest.json') set_book_path.parsed_metadata = json_loads(set_book_path.metadata) set_book_path.parsed_manifest = json_loads(set_book_path.manifest) def get_manifest(): return getattr(set_book_path, 'parsed_manifest', None) def get_path_for_name(name): bdir = getattr(set_book_path, 'path', None) if bdir is None: return path = os.path.abspath(os.path.join(bdir, name)) if path.startswith(bdir): return path def get_data(name): path = get_path_for_name(name) if path is None: return None, None try: with share_open(path, 'rb') as f: return f.read(), guess_type(name) except OSError as err: prints(f'Failed to read from book file: {name} with error: {as_unicode(err)}') return None, None @lru_cache(maxsize=4) def background_image(encoded_fname=''): if not encoded_fname: img_path = os.path.join(viewer_config_dir, 'bg-image.data') try: with open(img_path, 'rb') as f: data = f.read() mt, data = data.split(b'|', 1) mt = mt.decode() return mt, data except FileNotFoundError: return 'image/jpeg', b'' fname = bytes.fromhex(encoded_fname).decode() img_path = os.path.join(viewer_config_dir, 'background-images', fname) mt = guess_type(fname)[0] or 'image/jpeg' try: with open(make_long_path_useable(img_path), 'rb') as f: return mt, f.read() except FileNotFoundError: if fname.startswith('https://') or fname.startswith('http://'): from calibre import browser br = browser() try: with br.open(fname) as src: data = src.read() except Exception: return mt, b'' with open(make_long_path_useable(img_path), 'wb') as dest: dest.write(data) return mt, data return mt, b'' @lru_cache(maxsize=2) def get_mathjax_dir(): return P('mathjax', allow_user_override=False) def handle_mathjax_request(rq, name): mathjax_dir = get_mathjax_dir() path = os.path.abspath(os.path.join(mathjax_dir, '..', name)) if path.startswith(mathjax_dir): mt = guess_type(name) try: with open(path, 'rb') as f: raw = f.read() except OSError as err: prints(f"Failed to get mathjax file: {name} with error: {err}", file=sys.stderr) rq.fail(QWebEngineUrlRequestJob.Error.RequestFailed) return if name.endswith('/startup.js'): raw = P('pdf-mathjax-loader.js', data=True, allow_user_override=False) + raw send_reply(rq, mt, raw) else: prints(f"Failed to get mathjax file: {name} outside mathjax directory", file=sys.stderr) rq.fail(QWebEngineUrlRequestJob.Error.RequestFailed) class UrlSchemeHandler(QWebEngineUrlSchemeHandler): def __init__(self, parent=None): QWebEngineUrlSchemeHandler.__init__(self, parent) self.allowed_hosts = (FAKE_HOST, SANDBOX_HOST) def requestStarted(self, rq): if bytes(rq.requestMethod()) != b'GET': return self.fail_request(rq, QWebEngineUrlRequestJob.Error.RequestDenied) url = rq.requestUrl() host = url.host() if host not in self.allowed_hosts or url.scheme() != FAKE_PROTOCOL: return self.fail_request(rq) name = url.path()[1:] if host == SANDBOX_HOST and name.partition('/')[0] not in ('book', 'mathjax'): return self.fail_request(rq) if name.startswith('book/'): name = name.partition('/')[2] if name in ('__index__', '__popup__'): send_reply(rq, 'text/html', b'<div>\xa0</div>') return try: data, mime_type = get_data(name) if data is None: rq.fail(QWebEngineUrlRequestJob.Error.UrlNotFound) return data = as_bytes(data) mime_type = { # Prevent warning in console about mimetype of fonts 'application/vnd.ms-opentype':'application/x-font-ttf', 'application/x-font-truetype':'application/x-font-ttf', 'application/font-sfnt': 'application/x-font-ttf', }.get(mime_type, mime_type) if mime_type == 'text/css': mime_type += '; charset=utf-8' send_reply(rq, mime_type, data) except Exception: import traceback traceback.print_exc() return self.fail_request(rq, QWebEngineUrlRequestJob.Error.RequestFailed) elif name == 'manifest': data = b'[' + set_book_path.manifest + b',' + set_book_path.metadata + b']' send_reply(rq, set_book_path.manifest_mime, data) elif name == 'reader-background': mt, data = background_image() send_reply(rq, mt, data) if data else rq.fail(QWebEngineUrlRequestJob.Error.UrlNotFound) elif name.startswith('reader-background-'): encoded_fname = name[len('reader-background-'):] mt, data = background_image(encoded_fname) send_reply(rq, mt, data) if data else rq.fail(QWebEngineUrlRequestJob.Error.UrlNotFound) elif name.startswith('mathjax/'): handle_mathjax_request(rq, name) elif not name: send_reply(rq, 'text/html', viewer_html()) else: return self.fail_request(rq) def fail_request(self, rq, fail_code=None): if fail_code is None: fail_code = QWebEngineUrlRequestJob.Error.UrlNotFound rq.fail(fail_code) prints(f"Blocking FAKE_PROTOCOL request: {rq.requestUrl().toString()} with code: {fail_code}") # }}} def create_profile(): ans = getattr(create_profile, 'ans', None) if ans is None: ans = setup_profile(QWebEngineProfile(QApplication.instance())) osname = 'windows' if iswindows else ('macos' if ismacos else 'linux') # DO NOT change the user agent as it is used to workaround # Qt bugs see workaround_qt_bug() in ajax.pyj ua = f'calibre-viewer {__version__} {osname}' ans.setHttpUserAgent(ua) if is_running_from_develop: from calibre.utils.rapydscript import compile_viewer prints('Compiling viewer code...') compile_viewer() js = P('viewer.js', data=True, allow_user_override=False) translations_json = get_translations_data() or b'null' js = js.replace(b'__TRANSLATIONS_DATA__', translations_json, 1) if in_develop_mode: js = js.replace(b'__IN_DEVELOP_MODE__', b'1') insert_scripts(ans, create_script('viewer.js', js)) url_handler = UrlSchemeHandler(ans) ans.installUrlSchemeHandler(QByteArray(FAKE_PROTOCOL.encode('ascii')), url_handler) s = ans.settings() s.setDefaultTextEncoding('utf-8') s.setAttribute(QWebEngineSettings.WebAttribute.LinksIncludedInFocusChain, False) create_profile.ans = ans return ans class ViewerBridge(Bridge): view_created = from_js(object) on_iframe_ready = from_js() content_file_changed = from_js(object) set_session_data = from_js(object, object) set_local_storage = from_js(object, object) reload_book = from_js() toggle_toc = from_js() toggle_bookmarks = from_js() toggle_highlights = from_js() new_bookmark = from_js(object) toggle_inspector = from_js() toggle_lookup = from_js(object) show_search = from_js(object, object) search_result_not_found = from_js(object) search_result_discovered = from_js(object) find_next = from_js(object) quit = from_js() update_current_toc_nodes = from_js(object) toggle_full_screen = from_js() report_cfi = from_js(object, object) ask_for_open = from_js(object) selection_changed = from_js(object, object) autoscroll_state_changed = from_js(object) read_aloud_state_changed = from_js(object) copy_selection = from_js(object, object) view_image = from_js(object) copy_image = from_js(object) change_background_image = from_js(object) overlay_visibility_changed = from_js(object) reference_mode_changed = from_js(object) show_loading_message = from_js(object) show_error = from_js(object, object, object) export_shortcut_map = from_js(object) print_book = from_js() clear_history = from_js() reset_interface = from_js() quit = from_js() customize_toolbar = from_js() scrollbar_context_menu = from_js(object, object, object) close_prep_finished = from_js(object) highlights_changed = from_js(object) open_url = from_js(object) speak_simple_text = from_js(object) tts = from_js(object, object) edit_book = from_js(object, object, object) show_book_folder = from_js() show_help = from_js(object) update_reading_rates = from_js(object) profile_op = from_js(object, object, object) create_view = to_js() start_book_load = to_js() goto_toc_node = to_js() goto_cfi = to_js() full_screen_state_changed = to_js() get_current_cfi = to_js() show_home_page = to_js() background_image_changed = to_js() goto_frac = to_js() trigger_shortcut = to_js() set_system_palette = to_js() highlight_action = to_js() generic_action = to_js() show_search_result = to_js() prepare_for_close = to_js() repair_after_fullscreen_switch = to_js() viewer_font_size_changed = to_js() tts_event = to_js() profile_response = to_js() def apply_font_settings(page_or_view): s = page_or_view.settings() sd = vprefs['session_data'] fs = sd.get('standalone_font_settings', {}) if fs.get('serif_family'): s.setFontFamily(QWebEngineSettings.FontFamily.SerifFont, fs.get('serif_family')) else: s.resetFontFamily(QWebEngineSettings.FontFamily.SerifFont) if fs.get('sans_family'): s.setFontFamily(QWebEngineSettings.FontFamily.SansSerifFont, fs.get('sans_family')) else: s.resetFontFamily(QWebEngineSettings.FontFamily.SansSerifFont) if fs.get('mono_family'): s.setFontFamily(QWebEngineSettings.FontFamily.FixedFont, fs.get('mono_family')) else: s.resetFontFamily(QWebEngineSettings.FontFamily.FixedFont) sf = fs.get('standard_font') or 'serif' sf = getattr(QWebEngineSettings.FontFamily, {'serif': 'SerifFont', 'sans': 'SansSerifFont', 'mono': 'FixedFont'}[sf]) s.setFontFamily(QWebEngineSettings.FontFamily.StandardFont, s.fontFamily(sf)) old_minimum = s.fontSize(QWebEngineSettings.FontSize.MinimumFontSize) old_base = s.fontSize(QWebEngineSettings.FontSize.DefaultFontSize) old_fixed_base = s.fontSize(QWebEngineSettings.FontSize.DefaultFixedFontSize) mfs = fs.get('minimum_font_size') if mfs is None: s.resetFontSize(QWebEngineSettings.FontSize.MinimumFontSize) else: s.setFontSize(QWebEngineSettings.FontSize.MinimumFontSize, int(mfs)) bfs = sd.get('base_font_size') if bfs is not None: s.setFontSize(QWebEngineSettings.FontSize.DefaultFontSize, int(bfs)) s.setFontSize(QWebEngineSettings.FontSize.DefaultFixedFontSize, int(bfs * 13 / 16)) font_size_changed = (old_minimum, old_base, old_fixed_base) != ( s.fontSize(QWebEngineSettings.FontSize.MinimumFontSize), s.fontSize(QWebEngineSettings.FontSize.DefaultFontSize), s.fontSize(QWebEngineSettings.FontSize.DefaultFixedFontSize) ) if font_size_changed and hasattr(page_or_view, 'execute_when_ready'): page_or_view.execute_when_ready('viewer_font_size_changed') return s class WebPage(QWebEnginePage): def __init__(self, parent): profile = create_profile() QWebEnginePage.__init__(self, profile, parent) profile.setParent(self) secure_webengine(self, for_viewer=True) apply_font_settings(self) self.bridge = ViewerBridge(self) self.bridge.copy_selection.connect(self.trigger_copy) def trigger_copy(self, text, html): if text: md = QMimeData() md.setText(text) if html: md.setHtml(html) QApplication.instance().clipboard().setMimeData(md) def javaScriptConsoleMessage(self, level, msg, linenumber, source_id): prefix = { QWebEnginePage.JavaScriptConsoleMessageLevel.InfoMessageLevel: 'INFO', QWebEnginePage.JavaScriptConsoleMessageLevel.WarningMessageLevel: 'WARNING' }.get(level, 'ERROR') prints(f'{prefix}: {source_id}:{linenumber}: {msg}', file=sys.stderr) try: sys.stderr.flush() except OSError: pass def acceptNavigationRequest(self, url, req_type, is_main_frame): if req_type in (QWebEnginePage.NavigationType.NavigationTypeReload, QWebEnginePage.NavigationType.NavigationTypeBackForward): return True if url.scheme() in (FAKE_PROTOCOL, 'data'): return True if url.scheme() in ('http', 'https', 'calibre') and req_type == QWebEnginePage.NavigationType.NavigationTypeLinkClicked: safe_open_url(url) prints('Blocking navigation request to:', url.toString()) return False def go_to_anchor(self, anchor): self.bridge.go_to_anchor.emit(anchor or '') def runjs(self, src, callback=None): if callback is None: self.runJavaScript(src, QWebEngineScript.ScriptWorldId.ApplicationWorld) else: self.runJavaScript(src, QWebEngineScript.ScriptWorldId.ApplicationWorld, callback) def viewer_html(): ans = getattr(viewer_html, 'ans', None) if ans is None: ans = viewer_html.ans = P('viewer.html', data=True, allow_user_override=False) return ans class Inspector(QWidget): def __init__(self, dock_action, parent=None): QWidget.__init__(self, parent=parent) self.view_to_debug = parent self.view = None self.layout = QHBoxLayout(self) self.layout.setContentsMargins(0, 0, 0, 0) self.dock_action = dock_action QTimer.singleShot(0, self.connect_to_dock) def connect_to_dock(self): ac = self.dock_action ac.toggled.connect(self.visibility_changed) if ac.isChecked(): self.visibility_changed(True) def visibility_changed(self, visible): if visible and self.view is None: self.view = QWebEngineView(self.view_to_debug) setup_profile(self.view.page().profile()) self.view_to_debug.page().setDevToolsPage(self.view.page()) self.layout.addWidget(self.view) def sizeHint(self): return QSize(600, 1200) def system_colors(): app = QApplication.instance() is_dark_theme = app.is_dark_theme pal = app.palette() ans = { 'background': pal.color(QPalette.ColorRole.Base).name(), 'foreground': pal.color(QPalette.ColorRole.Text).name(), } if is_dark_theme: # only override link colors for dark themes # since if the book specifies its own link colors # they will likely work well with light themes ans['link'] = pal.color(QPalette.ColorRole.Link).name() return ans class WebView(RestartingWebEngineView): cfi_changed = pyqtSignal(object) reload_book = pyqtSignal() toggle_toc = pyqtSignal() show_search = pyqtSignal(object, object) search_result_not_found = pyqtSignal(object) search_result_discovered = pyqtSignal(object) find_next = pyqtSignal(object) toggle_bookmarks = pyqtSignal() toggle_highlights = pyqtSignal() new_bookmark = pyqtSignal(object) toggle_inspector = pyqtSignal() toggle_lookup = pyqtSignal(object) quit = pyqtSignal() update_current_toc_nodes = pyqtSignal(object) toggle_full_screen = pyqtSignal() ask_for_open = pyqtSignal(object) selection_changed = pyqtSignal(object, object) autoscroll_state_changed = pyqtSignal(object) read_aloud_state_changed = pyqtSignal(object) view_image = pyqtSignal(object) copy_image = pyqtSignal(object) overlay_visibility_changed = pyqtSignal(object) reference_mode_changed = pyqtSignal(object) show_loading_message = pyqtSignal(object) show_error = pyqtSignal(object, object, object) print_book = pyqtSignal() reset_interface = pyqtSignal() quit = pyqtSignal() customize_toolbar = pyqtSignal() scrollbar_context_menu = pyqtSignal(object, object, object) close_prep_finished = pyqtSignal(object) highlights_changed = pyqtSignal(object) update_reading_rates = pyqtSignal(object) edit_book = pyqtSignal(object, object, object) shortcuts_changed = pyqtSignal(object) paged_mode_changed = pyqtSignal() standalone_misc_settings_changed = pyqtSignal(object) view_created = pyqtSignal(object) content_file_changed = pyqtSignal(str) change_toolbar_actions = pyqtSignal(object) def __init__(self, parent=None): self._host_widget = None self.callback_id_counter = count() self.callback_map = {} self.current_cfi = self.current_content_file = None RestartingWebEngineView.__init__(self, parent) self.tts = TTS(self) self.tts.settings_changed.connect(self.tts_settings_changed) self.tts.event_received.connect(self.tts_event_received) self.dead_renderer_error_shown = False self.render_process_failed.connect(self.render_process_died) w = self.screen().availableSize().width() QApplication.instance().palette_changed.connect(self.palette_changed) self.show_home_page_on_ready = True self._size_hint = QSize(int(w/3), int(w/2)) self._page = WebPage(self) self._page.linkHovered.connect(self.link_hovered) self.view_is_ready = False self.bridge.bridge_ready.connect(self.on_bridge_ready) self.bridge.on_iframe_ready.connect(self.on_iframe_ready) self.bridge.view_created.connect(self.on_view_created) self.bridge.content_file_changed.connect(self.on_content_file_changed) self.bridge.set_session_data.connect(self.set_session_data) self.bridge.set_local_storage.connect(self.set_local_storage) self.bridge.reload_book.connect(self.reload_book) self.bridge.toggle_toc.connect(self.toggle_toc) self.bridge.show_search.connect(self.show_search) self.bridge.search_result_not_found.connect(self.search_result_not_found) self.bridge.search_result_discovered.connect(self.search_result_discovered) self.bridge.find_next.connect(self.find_next) self.bridge.toggle_bookmarks.connect(self.toggle_bookmarks) self.bridge.toggle_highlights.connect(self.toggle_highlights) self.bridge.new_bookmark.connect(self.new_bookmark) self.bridge.toggle_inspector.connect(self.toggle_inspector) self.bridge.toggle_lookup.connect(self.toggle_lookup) self.bridge.quit.connect(self.quit) self.bridge.update_current_toc_nodes.connect(self.update_current_toc_nodes) self.bridge.toggle_full_screen.connect(self.toggle_full_screen) self.bridge.ask_for_open.connect(self.ask_for_open) self.bridge.selection_changed.connect(self.selection_changed) self.bridge.autoscroll_state_changed.connect(self.autoscroll_state_changed) self.bridge.read_aloud_state_changed.connect(self.read_aloud_state_changed) self.bridge.view_image.connect(self.view_image) self.bridge.copy_image.connect(self.copy_image) self.bridge.overlay_visibility_changed.connect(self.overlay_visibility_changed) self.bridge.reference_mode_changed.connect(self.reference_mode_changed) self.bridge.show_loading_message.connect(self.show_loading_message) self.bridge.show_error.connect(self.show_error) self.bridge.print_book.connect(self.print_book) self.bridge.clear_history.connect(self.clear_history) self.bridge.reset_interface.connect(self.reset_interface) self.bridge.quit.connect(self.quit) self.bridge.customize_toolbar.connect(self.customize_toolbar) self.bridge.scrollbar_context_menu.connect(self.scrollbar_context_menu) self.bridge.close_prep_finished.connect(self.close_prep_finished) self.bridge.highlights_changed.connect(self.highlights_changed) self.bridge.update_reading_rates.connect(self.update_reading_rates) self.bridge.profile_op.connect(self.profile_op) self.bridge.edit_book.connect(self.edit_book) self.bridge.show_book_folder.connect(self.show_book_folder) self.bridge.show_help.connect(self.show_help) self.bridge.open_url.connect(safe_open_url) self.bridge.speak_simple_text.connect(self.tts.speak_simple_text) self.bridge.tts.connect(self.tts.action) self.bridge.export_shortcut_map.connect(self.set_shortcut_map) self.shortcut_map = {} self.bridge.report_cfi.connect(self.call_callback) self.bridge.change_background_image.connect(self.change_background_image) self.pending_bridge_ready_actions = {} self.setPage(self._page) self.setAcceptDrops(False) self.setUrl(QUrl(f'{FAKE_PROTOCOL}://{FAKE_HOST}/')) self.urlChanged.connect(self.url_changed) if parent is not None: self.inspector = Inspector(parent.inspector_dock.toggleViewAction(), self) parent.inspector_dock.setWidget(self.inspector) def profile_op(self, which, profile_name, settings): if which == 'all-profiles': vp = load_viewer_profiles('viewer:') self.execute_when_ready('profile_response', 'all-profiles', vp) elif which == 'save-profile': save_viewer_profile(profile_name, settings, 'viewer:') self.execute_when_ready('profile_response', 'save-profile', profile_name) elif which == 'apply-profile': self.execute_when_ready('profile_response', 'apply-profile', settings) elif which == 'request-save': self.execute_when_ready('profile_response', 'request-save', profile_name) elif which == 'apply-profile-to-viewer-ui': toolbar_actions = None s = settings.get('__standalone_extra_settings__', {}) toolbar_actions = s.get('toolbar-actions', None) self.change_toolbar_actions.emit(toolbar_actions) def link_hovered(self, url): if url == 'javascript:void(0)': url = '' self.generic_action('show-status-message', {'text': url}) def shutdown(self): self.tts.shutdown() def set_shortcut_map(self, smap): self.shortcut_map = smap self.shortcuts_changed.emit(smap) def url_changed(self, url): if url.hasFragment(): frag = url.fragment(QUrl.ComponentFormattingOption.FullyDecoded) if frag and frag.startswith('bookpos='): cfi = frag[len('bookpos='):] if cfi: self.current_cfi = cfi self.cfi_changed.emit(cfi) @property def host_widget(self): ans = self._host_widget if ans is not None and not sip.isdeleted(ans): return ans def render_process_died(self): if self.dead_renderer_error_shown: return self.dead_renderer_error_shown = True error_dialog(self, _('Render process crashed'), _( 'The Qt WebEngine Render process has crashed.' ' You should try restarting the viewer.') , show=True) def event(self, event): if event.type() == QEvent.Type.ChildPolished: child = event.child() if 'HostView' in child.metaObject().className(): self._host_widget = child self._host_widget.setFocus(Qt.FocusReason.OtherFocusReason) return QWebEngineView.event(self, event) def sizeHint(self): return self._size_hint def refresh(self): self.pageAction(QWebEnginePage.WebAction.ReloadAndBypassCache).trigger() @property def bridge(self): return self._page.bridge def on_bridge_ready(self): f = QApplication.instance().font() fi = QFontInfo(f) family = f.family() if family in ('.AppleSystemUIFont', 'MS Shell Dlg 2'): family = 'system-ui' ui_data = { 'all_font_families': QFontDatabase.families(), 'ui_font_family': family, 'ui_font_sz': f'{fi.pixelSize()}px', 'show_home_page_on_ready': self.show_home_page_on_ready, 'system_colors': system_colors(), 'QT_VERSION': QT_VERSION, 'short_time_fmt': QLocale.system().timeFormat(QLocale.FormatType.ShortFormat), 'use_roman_numerals_for_series_number': config['use_roman_numerals_for_series_number'], } self.bridge.create_view( vprefs['session_data'], vprefs['local_storage'], field_metadata.all_metadata(), ui_data) performance_monitor('bridge ready') for func, args in iteritems(self.pending_bridge_ready_actions): getattr(self.bridge, func)(*args) def on_iframe_ready(self): performance_monitor('iframe ready') def on_view_created(self, data): self.view_created.emit(data) self.view_is_ready = True def on_content_file_changed(self, data): self.current_content_file = data self.content_file_changed.emit(self.current_content_file) def start_book_load(self, initial_position=None, highlights=None, current_book_data=None, reading_rates=None): key = (set_book_path.path,) book_url = link_prefix_for_location_links(add_open_at=False) book_in_library_url = url_for_book_in_library() self.execute_when_ready( 'start_book_load', key, initial_position, set_book_path.pathtoebook, highlights or [], book_url, reading_rates, book_in_library_url) def execute_when_ready(self, action, *args): if self.bridge.ready: getattr(self.bridge, action)(*args) else: self.pending_bridge_ready_actions[action] = args def goto_toc_node(self, node_id): self.execute_when_ready('goto_toc_node', node_id) def goto_cfi(self, cfi, add_to_history=False): self.execute_when_ready('goto_cfi', cfi, bool(add_to_history)) def notify_full_screen_state_change(self, in_fullscreen_mode): self.execute_when_ready('full_screen_state_changed', in_fullscreen_mode) def set_session_data(self, key, val): fonts_changed = paged_mode_changed = standalone_misc_settings_changed = update_vprefs = False sd = vprefs['session_data'] def change(key, val): nonlocal fonts_changed, paged_mode_changed, standalone_misc_settings_changed, update_vprefs changed = sd.get(key) != val if changed: update_vprefs = True if val is None: sd.pop(key, None) else: sd[key] = val if key in ('standalone_font_settings', 'base_font_size'): fonts_changed = True elif key == 'read_mode': paged_mode_changed = True elif key == 'standalone_misc_settings': standalone_misc_settings_changed = True if isinstance(key, dict): for k, val in key.items(): change(k, val) elif key == '*' and val is None: vprefs['session_data'] = {} fonts_changed = paged_mode_changed = standalone_misc_settings_changed = update_vprefs = True elif key != '*': change(key, val) if update_vprefs: vprefs['session_data'] = sd if fonts_changed: apply_font_settings(self) if paged_mode_changed: self.paged_mode_changed.emit() if standalone_misc_settings_changed: self.standalone_misc_settings_changed.emit(val) def set_local_storage(self, key, val): if key == '*' and val is None: vprefs['local_storage'] = {} elif key != '*': sd = vprefs['local_storage'] sd[key] = val vprefs['local_storage'] = sd def do_callback(self, func_name, callback): cid = str(next(self.callback_id_counter)) self.callback_map[cid] = callback self.execute_when_ready('get_current_cfi', cid) def call_callback(self, request_id, data): callback = self.callback_map.pop(request_id, None) if callback is not None: callback(data) def get_current_cfi(self, callback): self.do_callback('get_current_cfi', callback) def show_home_page(self): self.execute_when_ready('show_home_page') def change_background_image(self, img_id): files = choose_images(self, 'viewer-background-image', _('Choose background image'), formats=['png', 'gif', 'jpg', 'jpeg', 'webp']) if files: img = files[0] d = os.path.join(viewer_config_dir, 'background-images') os.makedirs(d, exist_ok=True) fname = os.path.basename(img) shutil.copyfile(img, os.path.join(d, fname)) background_image.ans = None encoded = fname.encode().hex() self.execute_when_ready('background_image_changed', img_id, f'{FAKE_PROTOCOL}://{FAKE_HOST}/reader-background-{encoded}') def goto_frac(self, frac): self.execute_when_ready('goto_frac', frac) def clear_history(self): self._page.history().clear() def clear_caches(self): self._page.profile().clearHttpCache() def trigger_shortcut(self, which): if which: self.execute_when_ready('trigger_shortcut', which) def show_search_result(self, sr): self.execute_when_ready('show_search_result', sr) def palette_changed(self): self.execute_when_ready('set_system_palette', system_colors()) def prepare_for_close(self): self.execute_when_ready('prepare_for_close') def highlight_action(self, uuid, which): self.execute_when_ready('highlight_action', uuid, which) self.setFocus(Qt.FocusReason.OtherFocusReason) def generic_action(self, which, data): self.execute_when_ready('generic_action', which, data) def tts_event_received(self, which, data): self.execute_when_ready('tts_event', which, data) def tts_settings_changed(self, ui_settings): self.execute_when_ready('tts_event', 'configured', ui_settings) def show_book_folder(self): path = os.path.dirname(os.path.abspath(set_book_path.pathtoebook)) safe_open_url(QUrl.fromLocalFile(path)) def show_help(self, which): if which == 'viewer': safe_open_url(localize_user_manual_link('https://manual.calibre-ebook.com/viewer.html')) def repair_after_fullscreen_switch(self): self.execute_when_ready('repair_after_fullscreen_switch') def remove_recently_opened(self, path=''): self.generic_action('remove-recently-opened', {'path': path})
33,765
Python
.py
730
37.805479
139
0.658074
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,768
control_sleep.py
kovidgoyal_calibre/src/calibre/gui2/viewer/control_sleep.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net> from calibre.constants import ismacos, iswindows if iswindows: from calibre_extensions.winutil import ES_CONTINUOUS, ES_DISPLAY_REQUIRED, ES_SYSTEM_REQUIRED, set_thread_execution_state def prevent_sleep(reason=''): set_thread_execution_state(ES_CONTINUOUS | ES_DISPLAY_REQUIRED | ES_SYSTEM_REQUIRED) return 1 def allow_sleep(cookie): set_thread_execution_state(ES_CONTINUOUS) elif ismacos: from calibre_extensions.cocoa import create_io_pm_assertion, kIOPMAssertionTypeNoDisplaySleep, release_io_pm_assertion def prevent_sleep(reason=''): return create_io_pm_assertion(kIOPMAssertionTypeNoDisplaySleep, reason or 'E-book viewer automated reading in progress') def allow_sleep(cookie): release_io_pm_assertion(cookie) else: def prevent_sleep(reason=''): return 0 def allow_sleep(cookie): pass
984
Python
.py
21
41.238095
128
0.746331
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,769
integration.py
kovidgoyal_calibre/src/calibre/gui2/viewer/integration.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> import os import re def get_book_library_details(absolute_path_to_ebook): from calibre.srv.library_broker import correct_case_of_last_path_component, library_id_from_path absolute_path_to_ebook = os.path.abspath(os.path.expanduser(absolute_path_to_ebook)) base = os.path.dirname(absolute_path_to_ebook) m = re.search(r' \((\d+)\)$', os.path.basename(base)) if m is None: return book_id = int(m.group(1)) library_dir = os.path.dirname(os.path.dirname(base)) corrected_path = correct_case_of_last_path_component(library_dir) library_id = library_id_from_path(corrected_path) dbpath = os.path.join(library_dir, 'metadata.db') dbpath = os.environ.get('CALIBRE_OVERRIDE_DATABASE_PATH') or dbpath if not os.path.exists(dbpath): return return {'dbpath': dbpath, 'book_id': book_id, 'fmt': absolute_path_to_ebook.rpartition('.')[-1].upper(), 'library_id': library_id} def database_has_annotations_support(cursor): return next(cursor.execute('pragma user_version;'))[0] > 23 def load_annotations_map_from_library(book_library_details, user_type='local', user='viewer'): import apsw from calibre.db.backend import Connection, annotations_for_book ans = {} dbpath = book_library_details['dbpath'] try: conn = apsw.Connection(dbpath, flags=apsw.SQLITE_OPEN_READONLY) except Exception: return ans try: conn.setbusytimeout(Connection.BUSY_TIMEOUT) cursor = conn.cursor() if not database_has_annotations_support(cursor): return ans for annot in annotations_for_book( cursor, book_library_details['book_id'], book_library_details['fmt'], user_type=user_type, user=user ): ans.setdefault(annot['type'], []).append(annot) finally: conn.close() return ans def save_annotations_list_to_library(book_library_details, alist, sync_annots_user=''): import apsw from calibre.db.annotations import merge_annotations from calibre.db.backend import Connection, annotations_for_book, save_annotations_for_book from calibre.gui2.viewer.annotations import annotations_as_copied_list dbpath = book_library_details['dbpath'] try: conn = apsw.Connection(dbpath, flags=apsw.SQLITE_OPEN_READWRITE) except Exception: return try: conn.setbusytimeout(Connection.BUSY_TIMEOUT) if not database_has_annotations_support(conn.cursor()): return amap = {} with conn: cursor = conn.cursor() for annot in annotations_for_book(cursor, book_library_details['book_id'], book_library_details['fmt']): amap.setdefault(annot['type'], []).append(annot) merge_annotations((x[0] for x in alist), amap) if sync_annots_user: other_amap = {} for annot in annotations_for_book(cursor, book_library_details['book_id'], book_library_details['fmt'], user_type='web', user=sync_annots_user): other_amap.setdefault(annot['type'], []).append(annot) merge_annotations(amap, other_amap) alist = tuple(annotations_as_copied_list(amap)) save_annotations_for_book(cursor, book_library_details['book_id'], book_library_details['fmt'], alist) if sync_annots_user: alist = tuple(annotations_as_copied_list(other_amap)) save_annotations_for_book(cursor, book_library_details['book_id'], book_library_details['fmt'], alist, user_type='web', user=sync_annots_user) finally: conn.close()
3,739
Python
.py
76
41.157895
160
0.666758
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,770
annotations.py
kovidgoyal_calibre/src/calibre/gui2/viewer/annotations.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> import os from io import BytesIO from operator import itemgetter from threading import Thread from calibre.db.annotations import merge_annot_lists from calibre.gui2.viewer.convert_book import update_book from calibre.gui2.viewer.integration import save_annotations_list_to_library from calibre.gui2.viewer.web_view import viewer_config_dir from calibre.srv.render_book import EPUB_FILE_TYPE_MAGIC from calibre.utils.date import EPOCH from calibre.utils.iso8601 import parse_iso8601 from calibre.utils.serialize import json_dumps, json_loads from calibre.utils.zipfile import safe_replace from polyglot.binary import as_base64_bytes from polyglot.builtins import iteritems from polyglot.queue import Queue annotations_dir = os.path.join(viewer_config_dir, 'annots') parse_annotations = json_loads def annotations_as_copied_list(annots_map): for atype, annots in iteritems(annots_map): for annot in annots: ts = (parse_iso8601(annot['timestamp'], assume_utc=True) - EPOCH).total_seconds() annot = annot.copy() annot['type'] = atype yield annot, ts def annot_list_as_bytes(annots): return json_dumps(tuple(annot for annot, seconds in annots)) def split_lines(chunk, length=80): pos = 0 while pos < len(chunk): yield chunk[pos:pos+length] pos += length def save_annots_to_epub(path, serialized_annots): try: zf = open(path, 'r+b') except OSError: return with zf: serialized_annots = EPUB_FILE_TYPE_MAGIC + b'\n'.join(split_lines(as_base64_bytes(serialized_annots))) safe_replace(zf, 'META-INF/calibre_bookmarks.txt', BytesIO(serialized_annots), add_missing=True) def save_annotations(annotations_list, annotations_path_key, bld, pathtoebook, in_book_file, sync_annots_user): annots = annot_list_as_bytes(annotations_list) with open(os.path.join(annotations_dir, annotations_path_key), 'wb') as f: f.write(annots) if in_book_file and os.access(pathtoebook, os.W_OK): before_stat = os.stat(pathtoebook) save_annots_to_epub(pathtoebook, annots) update_book(pathtoebook, before_stat, {'calibre-book-annotations.json': annots}) if bld: save_annotations_list_to_library(bld, annotations_list, sync_annots_user) class AnnotationsSaveWorker(Thread): def __init__(self): Thread.__init__(self, name='AnnotSaveWorker') self.daemon = True self.queue = Queue() def shutdown(self): if self.is_alive(): self.queue.put(None) self.join() def run(self): while True: x = self.queue.get() if x is None: return annotations_list = x['annotations_list'] annotations_path_key = x['annotations_path_key'] bld = x['book_library_details'] pathtoebook = x['pathtoebook'] in_book_file = x['in_book_file'] sync_annots_user = x['sync_annots_user'] try: save_annotations(annotations_list, annotations_path_key, bld, pathtoebook, in_book_file, sync_annots_user) except Exception: import traceback traceback.print_exc() def save_annotations(self, current_book_data, in_book_file=True, sync_annots_user=''): alist = tuple(annotations_as_copied_list(current_book_data['annotations_map'])) ebp = current_book_data['pathtoebook'] can_save_in_book_file = ebp.lower().endswith('.epub') self.queue.put({ 'annotations_list': alist, 'annotations_path_key': current_book_data['annotations_path_key'], 'book_library_details': current_book_data['book_library_details'], 'pathtoebook': current_book_data['pathtoebook'], 'in_book_file': in_book_file and can_save_in_book_file, 'sync_annots_user': sync_annots_user, }) def find_tests(): import unittest def bm(title, bmid, year=20, first_cfi_number=1): return { 'title': title, 'id': bmid, 'timestamp': f'20{year}-06-29T03:21:48.895323+00:00', 'pos_type': 'epubcfi', 'pos': f'epubcfi(/{first_cfi_number}/4/8)' } def hl(uuid, hlid, year=20, first_cfi_number=1): return { 'uuid': uuid, 'id': hlid, 'timestamp': f'20{year}-06-29T03:21:48.895323+00:00', 'start_cfi': f'epubcfi(/{first_cfi_number}/4/8)' } class AnnotationsTest(unittest.TestCase): def test_merge_annotations(self): for atype in 'bookmark highlight'.split(): f = bm if atype == 'bookmark' else hl a = [f('one', 1, 20, 2), f('two', 2, 20, 4), f('a', 3, 20, 16),] b = [f('one', 10, 30, 2), f('two', 20, 10, 4), f('b', 30, 20, 8),] c = merge_annot_lists(a, b, atype) self.assertEqual(tuple(map(itemgetter('id'), c)), (10, 2, 30, 3)) return unittest.TestLoader().loadTestsFromTestCase(AnnotationsTest)
5,142
Python
.py
110
38.554545
122
0.646154
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,771
overlay.py
kovidgoyal_calibre/src/calibre/gui2/viewer/overlay.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> from qt.core import QFontInfo, QLabel, QPalette, Qt, QVBoxLayout, QWidget from calibre.gui2.progress_indicator import ProgressIndicator class LoadingOverlay(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QVBoxLayout(self) self.pi = ProgressIndicator(self, 96) self.setVisible(False) self.label = QLabel(self) self.label.setText('<i>testing with some long and wrap worthy message that should hopefully still render well') self.label.setTextFormat(Qt.TextFormat.RichText) self.label.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignHCenter) self.label.setWordWrap(True) if parent is None: self.resize(300, 300) else: self.resize(parent.size()) self.setAutoFillBackground(True) pal = self.palette() col = pal.color(QPalette.ColorRole.Window) col.setAlphaF(0.8) pal.setColor(QPalette.ColorRole.Window, col) self.setPalette(pal) self.move(0, 0) f = self.font() f.setBold(True) fm = QFontInfo(f) f.setPixelSize(int(fm.pixelSize() * 1.5)) self.label.setFont(f) l.addStretch(10) l.addWidget(self.pi) l.addWidget(self.label) l.addStretch(10) def __call__(self, msg=''): self.label.setText(msg) self.resize(self.parent().size()) self.move(0, 0) self.setVisible(True) self.raise_() self.setFocus(Qt.FocusReason.OtherFocusReason) self.update() def hide(self): self.parent().web_view.setFocus(Qt.FocusReason.OtherFocusReason) self.pi.stop() return QWidget.hide(self) def showEvent(self, ev): # import time # self.st = time.monotonic() self.pi.start() def hideEvent(self, ev): # import time # print(1111111, time.monotonic() - self.st) self.pi.stop() if __name__ == '__main__': from calibre.gui2 import Application app = Application([]) w = LoadingOverlay() w.show() app.exec()
2,233
Python
.py
61
28.721311
119
0.63287
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,772
search.py
kovidgoyal_calibre/src/calibre/gui2/viewer/search.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> import json from collections import Counter, OrderedDict from html import escape from threading import Thread import regex from qt.core import ( QAbstractItemView, QCheckBox, QComboBox, QFont, QHBoxLayout, QIcon, QLabel, QMenu, Qt, QToolButton, QTreeWidget, QTreeWidgetItem, QVBoxLayout, QWidget, pyqtSignal, ) from calibre.ebooks.conversion.search_replace import REGEX_FLAGS from calibre.gui2 import warning_dialog from calibre.gui2.gestures import GestureManager from calibre.gui2.progress_indicator import ProgressIndicator from calibre.gui2.viewer import get_boss from calibre.gui2.viewer.config import vprefs from calibre.gui2.viewer.web_view import get_data, get_manifest from calibre.gui2.viewer.widgets import ResultsDelegate, SearchBox from calibre.utils.icu import primary_collator_without_punctuation from calibre.utils.localization import _, ngettext from polyglot.builtins import iteritems from polyglot.functools import lru_cache from polyglot.queue import Queue class BusySpinner(QWidget): # {{{ def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QHBoxLayout(self) l.setContentsMargins(0, 0, 0, 0) self.pi = ProgressIndicator(self, 24) l.addWidget(self.pi) self.la = la = QLabel(_('Searching...')) l.addWidget(la) l.addStretch(10) self.is_running = False def start(self): self.setVisible(True) self.pi.start() self.is_running = True def stop(self): self.setVisible(False) self.pi.stop() self.is_running = False # }}} quote_map= {'"':'"“”', "'": "'‘’"} qpat = regex.compile(r'''(['"])''') spat = regex.compile(r'(\s+)') invisible_chars = '(?:[\u00ad\u200c\u200d]{0,1})' SEARCH_RESULT_ROLE = Qt.ItemDataRole.UserRole RESULT_NUMBER_ROLE = SEARCH_RESULT_ROLE + 1 SPINE_IDX_ROLE = RESULT_NUMBER_ROLE + 1 def text_to_regex(text): has_leading = text.lstrip() != text has_trailing = text.rstrip() != text if text and not text.strip(): return r'\s+' ans = [] for wpart in spat.split(text.strip()): if not wpart.strip(): ans.append(r'\s+') else: for part in qpat.split(wpart): r = quote_map.get(part) if r is not None: ans.append('[' + r + ']') else: part = invisible_chars.join(map(regex.escape, part)) ans.append(part) if has_leading: ans.insert(0, r'\s+') if has_trailing: ans.append(r'\s+') return ''.join(ans) def words_and_interval_for_near(expr, default_interval=60): parts = expr.split() words = [] interval = default_interval for q in parts: if q is parts[-1] and q.isdigit(): interval = int(q) else: words.append(text_to_regex(q)) return words, interval class Search: def __init__(self, text, mode, case_sensitive, backwards): self.text, self.mode = text, mode self.case_sensitive = case_sensitive self.backwards = backwards self._regex = self._nsd = None def __eq__(self, other): if not isinstance(other, Search): return False return self.text == other.text and self.mode == other.mode and self.case_sensitive == other.case_sensitive @property def regex_flags(self): flags = REGEX_FLAGS if not self.case_sensitive: flags |= regex.IGNORECASE return flags @property def regex(self): if self._regex is None: expr = self.text if self.mode != 'regex': if self.mode == 'word': words = [] for part in expr.split(): words.append(fr'\b{text_to_regex(part)}\b') expr = r'\s+'.join(words) else: expr = text_to_regex(expr) self._regex = regex.compile(expr, self.regex_flags) return self._regex @property def near_search_data(self): if self._nsd is None: words, interval = words_and_interval_for_near(self.text) interval = max(1, interval) flags = self.regex_flags flags |= regex.DOTALL match_any_word = r'(?:\b(?:' + '|'.join(words) + r')\b)' joiner = '.{1,%d}' % interval full_pat = regex.compile(joiner.join(match_any_word for x in words), flags=flags) word_pats = tuple(regex.compile(rf'\b{x}\b', flags) for x in words) self._nsd = word_pats, full_pat return self._nsd @property def is_empty(self): if not self.text: return True if self.mode in ('normal', 'word') and not regex.sub(r'[\s\p{P}]+', '', self.text): return True return False def __str__(self): from collections import namedtuple s = ('text', 'mode', 'case_sensitive', 'backwards') return str(namedtuple('Search', s)(*tuple(getattr(self, x) for x in s))) class SearchFinished: def __init__(self, search_query): self.search_query = search_query class SearchResult: __slots__ = ( 'search_query', 'before', 'text', 'after', 'q', 'spine_idx', 'index', 'file_name', 'is_hidden', 'offset', 'toc_nodes', 'result_num' ) def __init__(self, search_query, before, text, after, q, name, spine_idx, index, offset, result_num): self.search_query = search_query self.q = q self.result_num = result_num self.before, self.text, self.after = before, text, after self.spine_idx, self.index = spine_idx, index self.file_name = name self.is_hidden = False self.offset = offset try: self.toc_nodes = toc_nodes_for_search_result(self) except Exception: import traceback traceback.print_exc() self.toc_nodes = () @property def for_js(self): return { 'file_name': self.file_name, 'spine_idx': self.spine_idx, 'index': self.index, 'text': self.text, 'before': self.before, 'after': self.after, 'mode': self.search_query.mode, 'q': self.q, 'result_num': self.result_num } def is_result(self, result_from_js): return result_from_js['spine_idx'] == self.spine_idx and self.index == result_from_js['index'] and result_from_js['q'] == self.q def __str__(self): from collections import namedtuple s = self.__slots__[:-1] return str(namedtuple('SearchResult', s)(*tuple(getattr(self, x) for x in s))) @lru_cache(maxsize=None) def searchable_text_for_name(name): ans = [] add_text = ans.append serialized_data = json.loads(get_data(name)[0]) stack = [] a = stack.append removed_tails = [] no_visit = frozenset({'script', 'style', 'title', 'head'}) ignore_text = frozenset({'img', 'math', 'rt', 'rp', 'rtc'}) for child in serialized_data['tree']['c']: if child.get('n') == 'body': a((child, False, False)) # the JS code does not add the tail of body tags to flat text removed_tails.append((child.pop('l', None), child)) text_pos = 0 anchor_offset_map = OrderedDict() while stack: node, text_ignored_in_parent, in_ruby = stack.pop() if isinstance(node, str): if in_ruby: node = node.strip() add_text(node) text_pos += len(node) continue g = node.get name = g('n') text = g('x') tail = g('l') children = g('c') attributes = g('a') if attributes: for x in attributes: if x[0] == 'id': aid = x[1] if aid not in anchor_offset_map: anchor_offset_map[aid] = text_pos if name in no_visit: continue node_in_ruby = in_ruby if not in_ruby and name == 'ruby': in_ruby = True ignore_text_in_node_and_children = text_ignored_in_parent or name in ignore_text if text and not ignore_text_in_node_and_children: if in_ruby: text = text.strip() add_text(text) text_pos += len(text) if tail and not text_ignored_in_parent: a((tail, ignore_text_in_node_and_children, node_in_ruby)) if children: for child in reversed(children): a((child, ignore_text_in_node_and_children, in_ruby)) for (tail, body) in removed_tails: if tail is not None: body['l'] = tail return ''.join(ans), anchor_offset_map @lru_cache(maxsize=2) def get_toc_data(): manifest = get_manifest() or {} spine = manifest.get('spine') or [] spine_toc_map = {name: [] for name in spine} parent_map = {} def process_node(node): items = spine_toc_map.get(node['dest']) if items is not None: items.append(node) children = node.get('children') if children: for child in children: parent_map[id(child)] = node process_node(child) toc = manifest.get('toc') if toc: process_node(toc) return { 'spine': tuple(spine), 'spine_toc_map': spine_toc_map, 'spine_idx_map': {name: idx for idx, name in enumerate(spine)}, 'parent_map': parent_map } class ToCOffsetMap: def __init__(self, toc_nodes=(), offset_map=None, previous_toc_node=None, parent_map=None): self.toc_nodes = toc_nodes self.offset_map = offset_map or {} self.previous_toc_node = previous_toc_node self.parent_map = parent_map or {} def toc_nodes_for_offset(self, offset): matches = [] for node in self.toc_nodes: q = self.offset_map.get(node.get('id')) if q is not None: if q > offset: break matches.append(node) if not matches and self.previous_toc_node is not None: matches.append(self.previous_toc_node) if matches: ancestors = [] node = matches[-1] parent = self.parent_map.get(id(node)) while parent is not None: ancestors.append(parent) parent = self.parent_map.get(id(parent)) if len(ancestors) > 1: ancestors.pop() # root node yield from reversed(ancestors) yield node @lru_cache(maxsize=None) def toc_offset_map_for_name(name): anchor_map = searchable_text_for_name(name)[1] toc_data = get_toc_data() try: idx = toc_data['spine_idx_map'][name] toc_nodes = toc_data['spine_toc_map'][name] except Exception: idx = -1 if idx < 0: return ToCOffsetMap() offset_map = {} for node in toc_nodes: node_id = node.get('id') if node_id is not None: aid = node.get('frag') offset = anchor_map.get(aid, 0) offset_map[node_id] = offset prev_toc_node = None for spine_name in reversed(toc_data['spine'][:idx]): try: ptn = toc_data['spine_toc_map'][spine_name] except Exception: continue if ptn: prev_toc_node = ptn[-1] break return ToCOffsetMap(toc_nodes, offset_map, prev_toc_node, toc_data['parent_map']) def toc_nodes_for_search_result(sr): sidx = sr.spine_idx toc_data = get_toc_data() try: name = toc_data['spine'][sidx] except Exception: return () tmap = toc_offset_map_for_name(name) return tuple(tmap.toc_nodes_for_offset(sr.offset)) def search_in_name(name, search_query, ctx_size=75): raw = searchable_text_for_name(name)[0] if search_query.mode == 'near': word_pats, full_pat = search_query.near_search_data def miter(): for match in full_pat.finditer(raw): text = match.group() for word_pat in word_pats: if not word_pat.search(text): break else: yield match.span() elif search_query.mode == 'regex' or search_query.case_sensitive: def miter(): for match in search_query.regex.finditer(raw): yield match.span() else: spans = [] def miter(): return spans if raw: def a(s, l): return spans.append((s, s + l)) primary_collator_without_punctuation().find_all(search_query.text, raw, a, search_query.mode == 'word') for (start, end) in miter(): before = raw[max(0, start-ctx_size):start] after = raw[end:end+ctx_size] yield before, raw[start:end], after, start class SearchInput(QWidget): # {{{ do_search = pyqtSignal(object) cleared = pyqtSignal() go_back = pyqtSignal() def __init__(self, parent=None, panel_name='search', show_return_button=True): QWidget.__init__(self, parent) self.ignore_search_type_changes = False self.l = l = QVBoxLayout(self) l.setContentsMargins(0, 0, 0, 0) h = QHBoxLayout() h.setContentsMargins(0, 0, 0, 0) l.addLayout(h) self.search_box = sb = SearchBox(self) self.panel_name = panel_name sb.initialize(f'viewer-{panel_name}-panel-expression') sb.item_selected.connect(self.saved_search_selected) sb.history_saved.connect(self.history_saved) sb.history_cleared.connect(self.history_cleared) sb.cleared.connect(self.cleared) sb.lineEdit().returnPressed.connect(self.find_next) h.addWidget(sb) self.next_button = nb = QToolButton(self) h.addWidget(nb) nb.setFocusPolicy(Qt.FocusPolicy.NoFocus) nb.setIcon(QIcon.ic('arrow-down.png')) nb.clicked.connect(self.find_next) nb.setToolTip(_('Find next match')) self.prev_button = nb = QToolButton(self) h.addWidget(nb) nb.setFocusPolicy(Qt.FocusPolicy.NoFocus) nb.setIcon(QIcon.ic('arrow-up.png')) nb.clicked.connect(self.find_previous) nb.setToolTip(_('Find previous match')) h = QHBoxLayout() h.setContentsMargins(0, 0, 0, 0) l.addLayout(h) self.query_type = qt = QComboBox(self) qt.setFocusPolicy(Qt.FocusPolicy.NoFocus) qt.addItem(_('Contains'), 'normal') qt.addItem(_('Whole words'), 'word') qt.addItem(_('Nearby words'), 'near') qt.addItem(_('Regex'), 'regex') qt.setToolTip('<p>' + _( 'Choose the type of search: <ul>' '<li><b>Contains</b> will search for the entered text anywhere. It will ignore punctuation,' ' spaces and accents, unless Case sensitive searching is enabled.' '<li><b>Whole words</b> will search for whole words that equal the entered text. As with' ' "Contains" searches punctuation and accents are ignored.' '<li><b>Nearby words</b> will search for whole words that are near each other in the text.' ' For example: <i>calibre cool</i> will find places in the text where the words <i>calibre</i> and <i>cool</i>' ' occur within 60 characters of each other. To change the number of characters add the number to the end of' ' the list of words, for example: <i>calibre cool awesome 120</i> will search for <i>calibre</i>, <i>cool</i>' ' and <i>awesome</i> within 120 characters of each other.' '<li><b>Regex</b> will interpret the text as a regular expression.' )) qt.setCurrentIndex(qt.findData(vprefs.get(f'viewer-{self.panel_name}-mode', 'normal') or 'normal')) qt.currentIndexChanged.connect(self.save_search_type) h.addWidget(qt) self.case_sensitive = cs = QCheckBox(_('&Case sensitive'), self) cs.setFocusPolicy(Qt.FocusPolicy.NoFocus) cs.setChecked(bool(vprefs.get(f'viewer-{self.panel_name}-case-sensitive', False))) cs.stateChanged.connect(self.save_search_type) h.addWidget(cs) self.return_button = rb = QToolButton(self) rb.setIcon(QIcon.ic('back.png')) rb.setToolTip(_('Go back to where you were before searching')) rb.clicked.connect(self.go_back) h.addWidget(rb) rb.setVisible(show_return_button) def history_saved(self, new_text, history): if new_text: sss = vprefs.get(f'saved-{self.panel_name}-settings') or {} sss[new_text] = {'case_sensitive': self.case_sensitive.isChecked(), 'mode': self.query_type.currentData()} history = frozenset(history) sss = {k: v for k, v in iteritems(sss) if k in history} vprefs[f'saved-{self.panel_name}-settings'] = sss def history_cleared(self): vprefs[f'saved-{self.panel_name}-settings'] = {} def save_search_type(self): text = self.search_box.currentText() if text and not self.ignore_search_type_changes: sss = vprefs.get(f'saved-{self.panel_name}-settings') or {} sss[text] = {'case_sensitive': self.case_sensitive.isChecked(), 'mode': self.query_type.currentData()} vprefs[f'saved-{self.panel_name}-settings'] = sss def saved_search_selected(self): text = self.search_box.currentText() if text: s = (vprefs.get(f'saved-{self.panel_name}-settings') or {}).get(text) if s: self.ignore_search_type_changes = True if 'case_sensitive' in s: self.case_sensitive.setChecked(s['case_sensitive']) if 'mode' in s: idx = self.query_type.findData(s['mode']) if idx > -1: self.query_type.setCurrentIndex(idx) self.ignore_search_type_changes = False self.find_next() def search_query(self, backwards=False): text = self.search_box.currentText() if text: return Search( text, self.query_type.currentData() or 'normal', self.case_sensitive.isChecked(), backwards ) def emit_search(self, backwards=False): boss = get_boss() if boss.check_for_read_aloud(_('the location of this search result')): return vprefs[f'viewer-{self.panel_name}-case-sensitive'] = self.case_sensitive.isChecked() vprefs[f'viewer-{self.panel_name}-mode'] = self.query_type.currentData() sq = self.search_query(backwards) if sq is not None: self.do_search.emit(sq) def find_next(self): self.emit_search() def find_previous(self): self.emit_search(backwards=True) def focus_input(self, text=None, search_type=None, case_sensitive=None): if text and hasattr(text, 'rstrip'): self.search_box.setText(text) if search_type is not None: idx = self.query_type.findData(search_type) if idx < 0: idx = self.query_type.findData('normal') self.query_type.setCurrentIndex(idx) if case_sensitive is not None: self.case_sensitive.setChecked(bool(case_sensitive)) self.search_box.setFocus(Qt.FocusReason.OtherFocusReason) le = self.search_box.lineEdit() le.end(False) le.selectAll() # }}} class Results(QTreeWidget): # {{{ show_search_result = pyqtSignal(object) current_result_changed = pyqtSignal(object) count_changed = pyqtSignal(object) def __init__(self, parent=None): QTreeWidget.__init__(self, parent) self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.customContextMenuRequested.connect(self.show_context_menu) self.setHeaderHidden(True) self.setFocusPolicy(Qt.FocusPolicy.NoFocus) self.delegate = ResultsDelegate(self) self.setItemDelegate(self.delegate) self.itemClicked.connect(self.item_activated) self.blank_icon = QIcon.ic('blank.png') self.not_found_icon = QIcon.ic('dialog_warning.png') self.currentItemChanged.connect(self.current_item_changed) self.section_font = QFont(self.font()) self.section_font.setItalic(True) self.section_map = {} self.search_results = [] self.item_map = {} self.gesture_manager = GestureManager(self) self.setVerticalScrollMode(QAbstractItemView.ScrollMode.ScrollPerPixel) def show_context_menu(self, point): self.context_menu = m = QMenu(self) m.addAction(QIcon.ic('plus.png'), _('Expand all'), self.expandAll) m.addAction(QIcon.ic('minus.png'), _('Collapse all'), self.collapseAll) self.context_menu.popup(self.mapToGlobal(point)) return True 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) def current_item_changed(self, current, previous): if current is not None: r = current.data(0, SEARCH_RESULT_ROLE) if isinstance(r, SearchResult): self.current_result_changed.emit(r) else: self.current_result_changed.emit(None) def add_result(self, result): section_title = _('Unknown') section_id = -1 toc_nodes = getattr(result, 'toc_nodes', ()) or () if toc_nodes: section_title = toc_nodes[-1].get('title') or _('Unknown') section_id = toc_nodes[-1].get('id') if section_id is None: section_id = -1 section_key = section_id section = self.section_map.get(section_key) spine_idx = getattr(result, 'spine_idx', -1) if section is None: section = QTreeWidgetItem([section_title], 1) section.setFlags(Qt.ItemFlag.ItemIsEnabled) section.setFont(0, self.section_font) section.setData(0, SPINE_IDX_ROLE, spine_idx) lines = [] for i, node in enumerate(toc_nodes): lines.append('\xa0\xa0' * i + '➤ ' + (node.get('title') or _('Unknown'))) if lines: tt = ngettext('Table of Contents section:', 'Table of Contents sections:', len(lines)) tt += '\n' + '\n'.join(lines) section.setToolTip(0, tt) self.section_map[section_key] = section for s in range(self.topLevelItemCount()): ti = self.topLevelItem(s) if ti.data(0, SPINE_IDX_ROLE) > spine_idx: self.insertTopLevelItem(s, section) break else: self.addTopLevelItem(section) section.setExpanded(True) item = QTreeWidgetItem(section, [' '], 2) item.setFlags(Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemNeverHasChildren) item.setData(0, SEARCH_RESULT_ROLE, result) item.setData(0, RESULT_NUMBER_ROLE, len(self.search_results)) item.setData(0, SPINE_IDX_ROLE, spine_idx) if isinstance(result, SearchResult): tt = '<p>…' + escape(result.before, False) + '<b>' + escape( result.text, False) + '</b>' + escape(result.after, False) + '…' item.setData(0, Qt.ItemDataRole.ToolTipRole, tt) item.setIcon(0, self.blank_icon) self.item_map[len(self.search_results)] = item self.search_results.append(result) n = self.number_of_results self.count_changed.emit(n) def item_activated(self): boss = get_boss() if boss.check_for_read_aloud(_('the location of this search result')): return i = self.currentItem() if i: sr = i.data(0, SEARCH_RESULT_ROLE) if isinstance(sr, SearchResult): if not sr.is_hidden: self.show_search_result.emit(sr) def find_next(self, previous): if self.number_of_results < 1: return item = self.currentItem() if item is None: return i = int(item.data(0, RESULT_NUMBER_ROLE)) i += -1 if previous else 1 i %= self.number_of_results self.setCurrentItem(self.item_map[i]) self.item_activated() def search_result_not_found(self, sr): for i in range(self.number_of_results): item = self.item_map[i] r = item.data(0, SEARCH_RESULT_ROLE) if r.is_result(sr): r.is_hidden = True item.setIcon(0, self.not_found_icon) break def search_result_discovered(self, sr): q = sr['result_num'] for i in range(self.number_of_results): item = self.item_map[i] r = item.data(0, SEARCH_RESULT_ROLE) if r.result_num == q: self.setCurrentItem(item) @property def current_result_is_hidden(self): item = self.currentItem() if item is not None: sr = item.data(0, SEARCH_RESULT_ROLE) if isinstance(sr, SearchResult) and sr.is_hidden: return True return False @property def number_of_results(self): return len(self.search_results) def clear_all_results(self): self.section_map = {} self.item_map = {} self.search_results = [] self.clear() self.count_changed.emit(-1) def select_first_result(self): if self.number_of_results: item = self.item_map[0] self.setCurrentItem(item) def ensure_current_result_visible(self): item = self.currentItem() if item is not None: self.scrollToItem(item) # }}} class SearchPanel(QWidget): # {{{ search_requested = pyqtSignal(object) results_found = pyqtSignal(object) show_search_result = pyqtSignal(object) count_changed = pyqtSignal(object) hide_search_panel = pyqtSignal() goto_cfi = pyqtSignal(object) def __init__(self, parent=None): QWidget.__init__(self, parent) self.discovery_counter = 0 self.last_hidden_text_warning = None self.current_search = None self.anchor_cfi = None self.l = l = QVBoxLayout(self) l.setContentsMargins(0, 0, 0, 0) self.search_input = si = SearchInput(self) self.searcher = None self.search_tasks = Queue() self.results_found.connect(self.on_result_found, type=Qt.ConnectionType.QueuedConnection) si.do_search.connect(self.search_requested) si.cleared.connect(self.search_cleared) si.go_back.connect(self.go_back) l.addWidget(si) self.results = r = Results(self) r.count_changed.connect(self.count_changed) r.show_search_result.connect(self.do_show_search_result, type=Qt.ConnectionType.QueuedConnection) r.current_result_changed.connect(self.update_hidden_message) l.addWidget(r, 100) self.spinner = s = BusySpinner(self) s.setVisible(False) l.addWidget(s) self.hidden_message = la = QLabel(_('This text is hidden in the book and cannot be displayed')) la.setStyleSheet('QLabel { margin-left: 1ex }') la.setWordWrap(True) la.setVisible(False) l.addWidget(la) def go_back(self): if self.anchor_cfi: self.goto_cfi.emit(self.anchor_cfi) def update_hidden_message(self): self.hidden_message.setVisible(self.results.current_result_is_hidden) def focus_input(self, text=None, search_type=None, case_sensitive=None): self.search_input.focus_input(text, search_type, case_sensitive) def search_cleared(self): self.results.clear_all_results() self.current_search = None def start_search(self, search_query, current_name): if self.current_search is not None and search_query == self.current_search: self.find_next_requested(search_query.backwards) return if self.searcher is None: self.searcher = Thread(name='Searcher', target=self.run_searches) self.searcher.daemon = True self.searcher.start() self.results.clear_all_results() self.hidden_message.setVisible(False) self.spinner.start() self.current_search = search_query self.last_hidden_text_warning = None self.search_tasks.put((search_query, current_name)) self.discovery_counter += 1 def set_anchor_cfi(self, pos_data): self.anchor_cfi = pos_data['cfi'] def run_searches(self): while True: x = self.search_tasks.get() if x is None: break search_query, current_name = x try: manifest = get_manifest() or {} spine = manifest.get('spine', ()) idx_map = {name: i for i, name in enumerate(spine)} spine_idx = idx_map.get(current_name, -1) except Exception: import traceback traceback.print_exc() spine_idx = -1 if spine_idx < 0: self.results_found.emit(SearchFinished(search_query)) continue num_in_spine = len(spine) result_num = 0 for n in range(num_in_spine): idx = (spine_idx + n) % num_in_spine name = spine[idx] counter = Counter() try: for i, result in enumerate(search_in_name(name, search_query)): before, text, after, offset = result q = (before or '')[-15:] + text + (after or '')[:15] result_num += 1 self.results_found.emit(SearchResult(search_query, before, text, after, q, name, idx, counter[q], offset, result_num)) counter[q] += 1 except Exception: import traceback traceback.print_exc() self.results_found.emit(SearchFinished(search_query)) def on_result_found(self, result): if self.current_search is None or result.search_query != self.current_search: return if isinstance(result, SearchFinished): self.spinner.stop() if self.results.number_of_results: self.results.ensure_current_result_visible() else: self.show_no_results_found() self.show_search_result.emit({'on_discovery': True, 'search_finished': True, 'result_num': -1}) return self.results.add_result(result) obj = result.for_js obj['on_discovery'] = self.discovery_counter self.show_search_result.emit(obj) self.update_hidden_message() def visibility_changed(self, visible): if visible: self.focus_input() def clear_searches(self): self.current_search = None self.last_hidden_text_warning = None searchable_text_for_name.cache_clear() toc_offset_map_for_name.cache_clear() get_toc_data.cache_clear() self.spinner.stop() self.results.clear_all_results() def shutdown(self): self.search_tasks.put(None) self.spinner.stop() self.current_search = None self.last_hidden_text_warning = None self.searcher = None def find_next_requested(self, previous): self.results.find_next(previous) def trigger(self): self.search_input.find_next() def do_show_search_result(self, sr): self.show_search_result.emit(sr.for_js) def search_result_not_found(self, sr): self.results.search_result_not_found(sr) self.update_hidden_message() def search_result_discovered(self, sr): self.results.search_result_discovered(sr) def show_no_results_found(self): msg = _('No matches were found for:') warning_dialog(self, _('No matches found'), msg + f' <b>{self.current_search.text}</b>', show=True) def keyPressEvent(self, ev): if ev.key() == Qt.Key.Key_Escape: self.hide_search_panel.emit() ev.accept() return return QWidget.keyPressEvent(self, ev) # }}}
32,902
Python
.py
795
31.568553
142
0.593364
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,773
toc.py
kovidgoyal_calibre/src/calibre/gui2/viewer/toc.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> import re from functools import partial from qt.core import ( QAbstractItemView, QApplication, QEvent, QFont, QHBoxLayout, QIcon, QMenu, QModelIndex, QStandardItem, QStandardItemModel, QStyledItemDelegate, Qt, QToolButton, QToolTip, QTreeView, QWidget, pyqtSignal, ) from calibre.gui2 import error_dialog from calibre.gui2.gestures import GestureManager from calibre.gui2.search_box import SearchBox2 from calibre.utils.icu import primary_contains from calibre.utils.localization import _ class Delegate(QStyledItemDelegate): def helpEvent(self, ev, view, option, index): # Show a tooltip only if the item is truncated if not ev or not view: return False if ev.type() == QEvent.Type.ToolTip: rect = view.visualRect(index) size = self.sizeHint(option, index) if rect.width() < size.width(): tooltip = index.data(Qt.ItemDataRole.DisplayRole) QToolTip.showText(ev.globalPos(), tooltip, view) return True return QStyledItemDelegate.helpEvent(self, ev, view, option, index) class TOCView(QTreeView): searched = pyqtSignal(object) def __init__(self, *args): QTreeView.__init__(self, *args) self.setFocusPolicy(Qt.FocusPolicy.NoFocus) self.delegate = Delegate(self) self.setItemDelegate(self.delegate) self.setMinimumWidth(80) self.header().close() self.setMouseTracking(True) self.set_style_sheet() self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.context_menu = None self.customContextMenuRequested.connect(self.show_context_menu) QApplication.instance().palette_changed.connect(self.set_style_sheet, type=Qt.ConnectionType.QueuedConnection) self.setVerticalScrollMode(QAbstractItemView.ScrollMode.ScrollPerPixel) self.gesture_manager = GestureManager(self) 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) def setModel(self, model): QTreeView.setModel(self, model) model.current_toc_nodes_changed.connect(self.current_toc_nodes_changed, type=Qt.ConnectionType.QueuedConnection) def current_toc_nodes_changed(self, ancestors, nodes): if ancestors: self.auto_expand_indices(ancestors) if nodes: self.scrollTo(nodes[-1].index()) def auto_expand_indices(self, indices): for idx in indices: self.setExpanded(idx, True) def set_style_sheet(self): self.setStyleSheet(''' QTreeView { background-color: palette(window); color: palette(window-text); border: none; } QTreeView::item { border: 1px solid transparent; padding-top:0.5ex; padding-bottom:0.5ex; } ''' + QApplication.instance().palette_manager.tree_view_hover_style()) self.setProperty('hovered_item_is_highlighted', True) def mouseMoveEvent(self, ev): if self.indexAt(ev.pos()).isValid(): self.setCursor(Qt.CursorShape.PointingHandCursor) else: self.unsetCursor() return QTreeView.mouseMoveEvent(self, ev) def expand_tree(self, index): self.expand(index) i = -1 while True: i += 1 child = index.child(i, 0) if not child.isValid(): break self.expand_tree(child) def collapse_at_level(self, index): item = self.model().itemFromIndex(index) for x in self.model().items_at_depth(item.depth): self.collapse(self.model().indexFromItem(x)) def expand_at_level(self, index): item = self.model().itemFromIndex(index) for x in self.model().items_at_depth(item.depth): self.expand(self.model().indexFromItem(x)) def show_context_menu(self, pos): index = self.indexAt(pos) m = QMenu(self) if index.isValid(): m.addAction(QIcon.ic('plus.png'), _('Expand all items under %s') % index.data(), partial(self.expand_tree, index)) m.addSeparator() m.addAction(QIcon.ic('plus.png'), _('Expand all items'), self.expandAll) m.addAction(QIcon.ic('minus.png'), _('Collapse all items'), self.collapseAll) m.addSeparator() if index.isValid(): m.addAction(QIcon.ic('plus.png'), _('Expand all items at the level of {}').format(index.data()), partial(self.expand_at_level, index)) m.addAction(QIcon.ic('minus.png'), _('Collapse all items at the level of {}').format(index.data()), partial(self.collapse_at_level, index)) m.addSeparator() m.addAction(QIcon.ic('edit-copy.png'), _('Copy Table of Contents to clipboard'), self.copy_to_clipboard) self.context_menu = m m.exec(self.mapToGlobal(pos)) def copy_to_clipboard(self): m = self.model() QApplication.clipboard().setText(getattr(m, 'as_plain_text', '')) def update_current_toc_nodes(self, families): self.model().update_current_toc_nodes(families) def scroll_to_current_toc_node(self): try: nodes = self.model().viewed_nodes() except AttributeError: nodes = () if nodes: self.scrollTo(nodes[-1].index()) class TOCSearch(QWidget): def __init__(self, toc_view, parent=None): QWidget.__init__(self, parent) self.toc_view = toc_view self.l = l = QHBoxLayout(self) self.search = s = SearchBox2(self) self.search.setMinimumContentsLength(15) self.search.initialize('viewer_toc_search_history', help_text=_('Search Table of Contents')) self.search.setToolTip(_('Search for text in the Table of Contents')) s.search.connect(self.do_search) self.go = b = QToolButton(self) b.setIcon(QIcon.ic('search.png')) b.clicked.connect(s.do_search) b.setToolTip(_('Find next match')) l.addWidget(s), l.addWidget(b) def do_search(self, text): if not text or not text.strip(): return delta = -1 if QApplication.instance().keyboardModifiers() & Qt.KeyboardModifier.ShiftModifier else 1 index = self.toc_view.model().search(text, delta=delta) if index.isValid(): self.toc_view.scrollTo(index) self.toc_view.searched.emit(index) else: error_dialog(self.toc_view, _('No matches found'), _( 'There are no Table of Contents entries matching: %s') % text, show=True) self.search.search_done(True) class TOCItem(QStandardItem): def __init__(self, toc, depth, all_items, normal_font, emphasis_font, depths, parent=None): text = toc.get('title') or '' self.href = (toc.get('dest') or '') if toc.get('frag'): self.href += '#' + toc['frag'] if text: text = re.sub(r'\s', ' ', text) self.title = text self.parent = parent self.node_id = toc['id'] QStandardItem.__init__(self, text) all_items.append(self) self.normal_font, self.emphasis_font = normal_font, emphasis_font if toc['children']: depths.add(depth + 1) for t in toc['children']: self.appendRow(TOCItem(t, depth+1, all_items, normal_font, emphasis_font, depths, parent=self)) self.setFlags(Qt.ItemFlag.ItemIsEnabled) self.is_current_search_result = False self.depth = depth self.set_being_viewed(False) def set_being_viewed(self, is_being_viewed): self.is_being_viewed = is_being_viewed self.setFont(self.emphasis_font if is_being_viewed else self.normal_font) @property def ancestors(self): parent = self.parent while parent is not None: yield parent parent = parent.parent @classmethod def type(cls): return QStandardItem.ItemType.UserType+10 def set_current_search_result(self, yes): if yes and not self.is_current_search_result: self.setText(self.text() + ' ◄') self.is_current_search_result = True elif not yes and self.is_current_search_result: self.setText(self.text()[:-2]) self.is_current_search_result = False def __repr__(self): indent = ' ' * self.depth return f'{indent}▶ TOC Item: {self.title} ({self.node_id})' def __str__(self): return repr(self) class TOC(QStandardItemModel): current_toc_nodes_changed = pyqtSignal(object, object) def __init__(self, toc=None): QStandardItemModel.__init__(self) self.current_query = {'text':'', 'index':-1, 'items':()} self.all_items = depth_first = [] normal_font = QApplication.instance().font() emphasis_font = QFont(normal_font) emphasis_font.setBold(True), emphasis_font.setItalic(True) self.depths = {0} if toc: for t in toc['children']: self.appendRow(TOCItem(t, 0, depth_first, normal_font, emphasis_font, self.depths)) self.depths = tuple(sorted(self.depths)) self.node_id_map = {x.node_id: x for x in self.all_items} def find_items(self, query): for item in self.all_items: text = item.text() if query and isinstance(query, str): if text and isinstance(text, str) and primary_contains(query, text): yield item else: yield item def items_at_depth(self, depth): for item in self.all_items: if item.depth == depth: yield item def node_id_for_text(self, query): for item in self.find_items(query): return item.node_id def node_id_for_href(self, query, exact=False): for item in self.all_items: href = item.href if (exact and query == href) or (not exact and query in href): return item.node_id def search(self, query, delta=1): cq = self.current_query if cq['items'] and -1 < cq['index'] < len(cq['items']): cq['items'][cq['index']].set_current_search_result(False) if cq['text'] != query: items = tuple(self.find_items(query)) cq.update({'text':query, 'items':items, 'index':-1}) num = len(cq['items']) if num > 0: cq['index'] = (cq['index'] + delta + num) % num item = cq['items'][cq['index']] item.set_current_search_result(True) index = self.indexFromItem(item) return index return QModelIndex() def update_current_toc_nodes(self, current_toc_leaves): viewed_nodes = set() ancestors = {} for node_id in current_toc_leaves: node = self.node_id_map.get(node_id) if node is not None: viewed_nodes.add(node_id) ansc = tuple(node.ancestors) viewed_nodes |= {x.node_id for x in ansc} for x in ansc: ancestors[x.node_id] = x.index() nodes = [] for node in self.all_items: is_being_viewed = node.node_id in viewed_nodes if is_being_viewed: nodes.append(node) if is_being_viewed != node.is_being_viewed: node.set_being_viewed(is_being_viewed) self.current_toc_nodes_changed.emit(tuple(ancestors.values()), nodes) def viewed_nodes(self): return tuple(node for node in self.all_items if node.is_being_viewed) @property def title_for_current_node(self): for node in reversed(self.all_items): if node.is_being_viewed: return node.title @property def as_plain_text(self): lines = [] for item in self.all_items: lines.append(' ' * (4 * item.depth) + (item.title or '')) return '\n'.join(lines)
12,417
Python
.py
295
32.481356
151
0.608652
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,774
__init__.py
kovidgoyal_calibre/src/calibre/gui2/viewer/__init__.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> import sys from time import monotonic_ns from calibre.constants import DEBUG def get_current_book_data(set_val=False): if set_val is not False: setattr(get_current_book_data, 'ans', set_val) return getattr(get_current_book_data, 'ans', {}) def get_boss(set_val=False): if set_val: get_boss.ans = set_val return get_boss.ans def link_prefix_for_location_links(add_open_at=True): cbd = get_current_book_data() link_prefix = library_id = None if 'calibre_library_id' in cbd: library_id = cbd['calibre_library_id'] book_id = cbd['calibre_book_id'] book_fmt = cbd['calibre_book_fmt'] elif cbd.get('book_library_details'): bld = cbd['book_library_details'] book_id = bld['book_id'] book_fmt = bld['fmt'].upper() library_id = bld['library_id'] if library_id: library_id = '_hex_-' + library_id.encode('utf-8').hex() link_prefix = f'calibre://view-book/{library_id}/{book_id}/{book_fmt}' if add_open_at: link_prefix += '?open_at=' return link_prefix def url_for_book_in_library(): cbd = get_current_book_data() ans = library_id = None if 'calibre_library_id' in cbd: library_id = cbd['calibre_library_id'] book_id = cbd['calibre_book_id'] elif cbd.get('book_library_details'): bld = cbd['book_library_details'] book_id = bld['book_id'] library_id = bld['library_id'] if library_id: library_id = '_hex_-' + library_id.encode('utf-8').hex() ans = f'calibre://show-book/{library_id}/{book_id}' return ans class PerformanceMonitor: def __init__(self): self.start_time = monotonic_ns() def __call__(self, desc='', reset=False): if DEBUG: at = monotonic_ns() if reset: self.start_time = at if desc: ts = (at - self.start_time) / 1e9 print(f'[{ts:.3f}] {desc}', file=sys.stderr) performance_monitor = PerformanceMonitor()
2,156
Python
.py
57
30.614035
78
0.605959
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,775
toolbars.py
kovidgoyal_calibre/src/calibre/gui2/viewer/toolbars.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> import os from functools import partial from qt.core import ( QAbstractItemView, QAction, QDialog, QDialogButtonBox, QGroupBox, QHBoxLayout, QIcon, QInputDialog, QKeySequence, QLabel, QListWidget, QListWidgetItem, QMenu, Qt, QToolBar, QToolButton, QVBoxLayout, pyqtSignal, ) from qt.webengine import QWebEnginePage from calibre.constants import ismacos from calibre.gui2 import elided_text from calibre.gui2.viewer.config import get_session_pref from calibre.gui2.viewer.shortcuts import index_to_key_sequence from calibre.gui2.viewer.web_view import set_book_path, vprefs from calibre.gui2.widgets2 import Dialog from calibre.startup import connect_lambda from calibre.utils.icu import primary_sort_key from calibre.utils.localization import _ class Action: __slots__ = ('icon', 'text', 'shortcut_action') def __init__(self, icon=None, text=None, shortcut_action=None): self.icon, self.text, self.shortcut_action = QIcon.ic(icon), text, shortcut_action class Actions: def __init__(self, a): self.__dict__.update(a) self.all_action_names = frozenset(a) def all_actions(): if not hasattr(all_actions, 'ans'): amap = { 'color_scheme': Action('format-fill-color.png', _('Switch color scheme')), 'profiles': Action('auto-reload.png', _('Apply settings from a saved profile')), 'back': Action('back.png', _('Back'), 'back'), 'forward': Action('forward.png', _('Forward'), 'forward'), 'open': Action('document_open.png', _('Open e-book')), 'copy': Action('edit-copy.png', _('Copy to clipboard'), 'copy_to_clipboard'), 'increase_font_size': Action('font_size_larger.png', _('Increase font size'), 'increase_font_size'), 'decrease_font_size': Action('font_size_smaller.png', _('Decrease font size'), 'decrease_font_size'), 'fullscreen': Action('page.png', _('Toggle full screen'), 'toggle_full_screen'), 'next': Action('next.png', _('Next page'), 'next'), 'previous': Action('previous.png', _('Previous page'), 'previous'), 'next_section': Action('arrow-down.png', _('Next section'), 'next_section'), 'previous_section': Action('arrow-up.png', _('Previous section'), 'previous_section'), 'toc': Action('toc.png', _('Table of Contents'), 'toggle_toc'), 'search': Action('search.png', _('Search'), 'toggle_search'), 'bookmarks': Action('bookmarks.png', _('Bookmarks'), 'toggle_bookmarks'), 'inspector': Action('debug.png', _('Inspector'), 'toggle_inspector'), 'reference': Action('reference.png', _('Toggle Reference mode'), 'toggle_reference_mode'), 'autoscroll': Action('auto-scroll.png', _('Toggle auto-scrolling'), 'toggle_autoscroll'), 'lookup': Action('generic-library.png', _('Lookup words'), 'toggle_lookup'), 'chrome': Action('tweaks.png', _('Show viewer controls'), 'show_chrome_force'), 'mode': Action('scroll.png', _('Toggle paged mode'), 'toggle_paged_mode'), 'print': Action('print.png', _('Print book'), 'print'), 'preferences': Action('config.png', _('Preferences'), 'preferences'), 'metadata': Action('metadata.png', _('Show book metadata'), 'metadata'), 'toggle_read_aloud': Action('bullhorn.png', _('Read aloud'), 'toggle_read_aloud'), 'toggle_highlights': Action('highlight_only_on.png', _('Browse highlights in book'), 'toggle_highlights'), 'select_all': Action('edit-select-all.png', _('Select all text in the current file'), 'select_all'), 'edit_book': Action('edit_book.png', _('Edit this book'), 'edit_book'), 'reload_book': Action('view-refresh.png', _('Reload this book'), 'reload_book'), } all_actions.ans = Actions(amap) return all_actions.ans DEFAULT_ACTIONS = ( 'back', 'forward', None, 'open', 'copy', 'increase_font_size', 'decrease_font_size', 'fullscreen', 'color_scheme', None, 'previous', 'next', None, 'toc', 'search', 'bookmarks', 'lookup', 'toggle_highlights', 'chrome', None, 'mode', 'print', 'preferences', 'metadata', 'inspector' ) def current_actions(): ans = vprefs.get('actions-toolbar-actions') if not ans: ans = DEFAULT_ACTIONS return tuple(ans) class ToolBar(QToolBar): def __init__(self, parent=None): QToolBar.__init__(self, parent) self.setWindowTitle(_('Toolbar')) self.shortcut_actions = {} self.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly) self.setVisible(False) self.setAllowedAreas(Qt.ToolBarArea.AllToolBarAreas) self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) def create_shortcut_action(self, name): a = getattr(all_actions(), name) sc = a.shortcut_action a = QAction(a.icon, a.text, self) connect_lambda(a.triggered, self, lambda self: self.action_triggered.emit(sc)) self.shortcut_actions[sc] = a return a class ActionsToolBar(ToolBar): action_triggered = pyqtSignal(object) open_book_at_path = pyqtSignal(object) def __init__(self, parent=None): ToolBar.__init__(self, parent) self.setObjectName('actions_toolbar') self.prevent_sleep_cookie = None self.customContextMenuRequested.connect(self.show_context_menu) def update_action_state(self, book_open): exclude = set(self.web_actions.values()) for ac in self.shortcut_actions.values(): if ac not in exclude: ac.setEnabled(book_open) self.search_action.setEnabled(book_open) self.color_scheme_action.setEnabled(book_open) def show_context_menu(self, pos): m = QMenu(self) a = m.addAction(_('Customize this toolbar')) a.triggered.connect(self.customize) a = m.addAction(_('Hide this toolbar')) a.triggered.connect(self.hide_toolbar) m.exec(self.mapToGlobal(pos)) def hide_toolbar(self): self.web_view.trigger_shortcut('toggle_toolbar') def initialize(self, web_view, toggle_search_action): self.web_view = web_view shortcut_action = self.create_shortcut_action aa = all_actions() self.action_triggered.connect(web_view.trigger_shortcut) page = web_view.page() web_view.paged_mode_changed.connect(self.update_mode_action) web_view.reference_mode_changed.connect(self.update_reference_mode_action) web_view.standalone_misc_settings_changed.connect(self.update_visibility) web_view.autoscroll_state_changed.connect(self.update_autoscroll_action) web_view.read_aloud_state_changed.connect(self.update_read_aloud_action) web_view.customize_toolbar.connect(self.customize, type=Qt.ConnectionType.QueuedConnection) web_view.view_created.connect(self.on_view_created) web_view.change_toolbar_actions.connect(self.change_toolbar_actions) self.web_actions = {} self.back_action = a = shortcut_action('back') a.setEnabled(False) self.web_actions[QWebEnginePage.WebAction.Back] = a page.action(QWebEnginePage.WebAction.Back).changed.connect(self.update_web_action) self.forward_action = a = shortcut_action('forward') a.setEnabled(False) self.web_actions[QWebEnginePage.WebAction.Forward] = a page.action(QWebEnginePage.WebAction.Forward).changed.connect(self.update_web_action) self.select_all_action = a = shortcut_action('select_all') a.setEnabled(False) self.web_actions[QWebEnginePage.WebAction.SelectAll] = a page.action(QWebEnginePage.WebAction.SelectAll).changed.connect(self.update_web_action) self.open_action = a = QAction(aa.open.icon, aa.open.text, self) self.open_menu = m = QMenu(self) a.setMenu(m) m.aboutToShow.connect(self.populate_open_menu) connect_lambda(a.triggered, self, lambda self: self.open_book_at_path.emit(None)) self.copy_action = shortcut_action('copy') self.increase_font_size_action = shortcut_action('increase_font_size') self.decrease_font_size_action = shortcut_action('decrease_font_size') self.fullscreen_action = shortcut_action('fullscreen') self.next_action = shortcut_action('next') self.previous_action = shortcut_action('previous') self.next_section_action = shortcut_action('next_section') self.previous_section_action = shortcut_action('previous_section') self.search_action = a = toggle_search_action a.setText(aa.search.text), a.setIcon(aa.search.icon) self.toc_action = a = shortcut_action('toc') a.setCheckable(True) self.bookmarks_action = a = shortcut_action('bookmarks') a.setCheckable(True) self.reference_action = a = shortcut_action('reference') a.setCheckable(True) self.toggle_highlights_action = self.highlights_action = a = shortcut_action('toggle_highlights') a.setCheckable(True) self.toggle_read_aloud_action = a = shortcut_action('toggle_read_aloud') a.setCheckable(True) self.lookup_action = a = shortcut_action('lookup') a.setCheckable(True) self.inspector_action = a = shortcut_action('inspector') a.setCheckable(True) self.autoscroll_action = a = shortcut_action('autoscroll') a.setCheckable(True) self.update_autoscroll_action(False) self.update_read_aloud_action(False) self.chrome_action = shortcut_action('chrome') self.mode_action = a = shortcut_action('mode') a.setCheckable(True) self.print_action = shortcut_action('print') self.preferences_action = shortcut_action('preferences') self.metadata_action = shortcut_action('metadata') self.edit_book_action = shortcut_action('edit_book') self.reload_book_action = shortcut_action('reload_book') self.update_mode_action() self.color_scheme_action = a = QAction(aa.color_scheme.icon, aa.color_scheme.text, self) self.color_scheme_menu = m = QMenu(self) a.setMenu(m) m.aboutToShow.connect(self.populate_color_scheme_menu) self.profiles_action = a = QAction(aa.profiles.icon, aa.profiles.text, self) self.profiles_menu = m = QMenu(self) a.setMenu(m) m.aboutToShow.connect(self.populate_profiles_menu) self.add_actions() def change_toolbar_actions(self, toolbar_actions): if toolbar_actions is None: vprefs.__delitem__('actions-toolbar-actions') else: vprefs.set('actions-toolbar-actions', toolbar_actions) self.add_actions() def update_web_action(self): a = self.sender() for x, ac in self.web_actions.items(): pa = self.web_view.page().action(x) if a is pa: ac.setEnabled(pa.isEnabled()) break def add_actions(self): self.clear() actions = current_actions() for x in actions: if x is None: self.addSeparator() else: try: self.addAction(getattr(self, f'{x}_action')) except AttributeError: pass for x in (self.color_scheme_action, self.profiles_action): w = self.widgetForAction(x) if w: w.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup) def update_mode_action(self): mode = get_session_pref('read_mode', default='paged', group=None) a = self.mode_action if mode == 'paged': a.setChecked(False) a.setToolTip(_('Switch to flow mode -- where the text is not broken into pages')) else: a.setChecked(True) a.setToolTip(_('Switch to paged mode -- where the text is broken into pages')) def change_sleep_permission(self, disallow_sleep=True): from .control_sleep import allow_sleep, prevent_sleep if disallow_sleep: if self.prevent_sleep_cookie is None: try: self.prevent_sleep_cookie = prevent_sleep() except Exception: import traceback traceback.print_exc() else: if self.prevent_sleep_cookie is not None: try: allow_sleep(self.prevent_sleep_cookie) except Exception: import traceback traceback.print_exc() self.prevent_sleep_cookie = None def update_autoscroll_action(self, active): self.autoscroll_action.setChecked(active) self.autoscroll_action.setToolTip( _('Turn off auto-scrolling') if active else _('Turn on auto-scrolling')) self.change_sleep_permission(active) def update_read_aloud_action(self, active): self.toggle_read_aloud_action.setChecked(active) self.toggle_read_aloud_action.setToolTip( _('Stop reading') if active else _('Read the text of the book aloud')) self.change_sleep_permission(active) def update_reference_mode_action(self, enabled): self.reference_action.setChecked(enabled) def update_dock_actions(self, visibility_map): for k in ('toc', 'bookmarks', 'lookup', 'inspector', 'highlights'): ac = getattr(self, f'{k}_action') ac.setChecked(visibility_map[k]) def set_tooltips(self, rmap): aliases = {'show_chrome_force': 'show_chrome'} def as_text(idx): return index_to_key_sequence(idx).toString(QKeySequence.SequenceFormat.NativeText) def set_it(a, sc): x = rmap.get(sc) if x is not None: keys = sorted(filter(None, map(as_text, x))) if keys: a.setToolTip('{} [{}]'.format(a.text(), ', '.join(keys))) for sc, a in self.shortcut_actions.items(): sc = aliases.get(sc, sc) set_it(a, sc) for a, sc in ((self.forward_action, 'forward'), (self.back_action, 'back'), (self.search_action, 'start_search')): set_it(a, sc) def populate_open_menu(self): m = self.open_menu m.clear() recent = get_session_pref('standalone_recently_opened', group=None, default=()) if recent: for entry in recent: try: path = os.path.abspath(entry['pathtoebook']) except Exception: continue if hasattr(set_book_path, 'pathtoebook') and path == os.path.abspath(set_book_path.pathtoebook): continue if os.path.exists(path): m.addAction('{}\t {}'.format( elided_text(entry['title'], pos='right', width=250), elided_text(os.path.basename(path), width=250))).triggered.connect(partial( self.open_book_at_path.emit, path)) else: self.web_view.remove_recently_opened(path) if len(m.actions()) > 0: m.addSeparator() m.addAction(_('Clear list of recently opened books'), self.clear_recently_opened) def clear_recently_opened(self): self.web_view.remove_recently_opened() def on_view_created(self, data): self.default_color_schemes = data['default_color_schemes'] def populate_profiles_menu(self): from calibre.gui2.viewer.config import load_viewer_profiles m = self.profiles_menu m.clear() self.profiles = load_viewer_profiles('viewer:') self.profiles['__default__'] = {} def a(name, display_name=''): a = m.addAction(display_name or name) a.setObjectName(f'profile-switch-action:{name}') a.triggered.connect(self.profile_switch_triggered) a('__default__', _('Restore settings to defaults')) m.addSeparator() for profile_name in sorted(self.profiles, key=lambda x: x.lower()): if profile_name == '__default__': continue a(profile_name) m.addSeparator() m.addAction(_('Save current settings as a profile')).triggered.connect(self.save_profile) if len(self.profiles) > 1: s = m.addMenu(_('Delete saved profile...')) for pname in self.profiles: if pname != '__default__': a = s.addAction(pname) a.setObjectName(f'profile-delete-action:{pname}') a.triggered.connect(self.profile_delete_triggerred) def profile_switch_triggered(self): key = self.sender().objectName().partition(':')[-1] profile = self.profiles[key] self.web_view.profile_op('apply-profile', key, profile) def profile_delete_triggerred(self): key = self.sender().objectName().partition(':')[-1] from calibre.gui2.viewer.config import save_viewer_profile save_viewer_profile(key, None, 'viewer:') def save_profile(self): name, ok = QInputDialog.getText(self, _('Enter name of profile to create'), _('&Name of profile')) if ok: self.web_view.profile_op('request-save', name, {}) def populate_color_scheme_menu(self): m = self.color_scheme_menu m.clear() ccs = get_session_pref('current_color_scheme', group=None) or '' ucs = get_session_pref('user_color_schemes', group=None) or {} def add_action(key, defns): a = m.addAction(defns[key]['name']) a.setCheckable(True) a.setObjectName(f'color-switch-action:{key}') a.triggered.connect(self.color_switch_triggerred) if key == ccs: a.setChecked(True) for key in sorted(ucs, key=lambda x: primary_sort_key(ucs[x]['name'])): add_action(key, ucs) m.addSeparator() for key in sorted(self.default_color_schemes, key=lambda x: primary_sort_key(self.default_color_schemes[x]['name'])): add_action(key, self.default_color_schemes) def color_switch_triggerred(self): key = self.sender().objectName().partition(':')[-1] self.action_triggered.emit('switch_color_scheme:' + key) def update_visibility(self): self.setVisible(bool(get_session_pref('show_actions_toolbar', default=False))) @property def visible_in_fullscreen(self): return bool(get_session_pref('show_actions_toolbar_in_fullscreen', default=False)) def customize(self): d = ConfigureToolBar(parent=self.parent()) if d.exec() == QDialog.DialogCode.Accepted: self.add_actions() class ActionsList(QListWidget): def __init__(self, actions, parent=None, is_source=True): QListWidget.__init__(self, parent) self.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) self.setDragEnabled(True) self.viewport().setAcceptDrops(True) self.setDropIndicatorShown(True) self.setDragDropMode(QAbstractItemView.DragDropMode.InternalMove) self.setDefaultDropAction(Qt.DropAction.CopyAction if ismacos else Qt.DropAction.MoveAction) self.setMinimumHeight(400) self.is_source = is_source if is_source: actions = self.sort_actions_alphabetically(actions) actions = [None] + actions self.set_names(actions) def sort_actions_alphabetically(self, actions): aa = all_actions() return sorted(actions, key=lambda name: primary_sort_key(getattr(aa, name).text) if name else primary_sort_key('')) def add_item_from_name(self, action): aa = all_actions() if action is None: i = QListWidgetItem('-- {} --'.format(_('Separator')), self) else: try: a = getattr(aa, action) except AttributeError: return i = QListWidgetItem(a.icon, a.text, self) i.setData(Qt.ItemDataRole.UserRole, action) return i def set_names(self, names): self.clear() for name in names: self.add_item_from_name(name) def remove_item(self, item): action = item.data(Qt.ItemDataRole.UserRole) if action is not None or not self.is_source: self.takeItem(self.row(item)) return action def remove_selected(self): ans = [] for item in tuple(self.selectedItems()): ans.append(self.remove_item(item)) return ans def add_names(self, names): for action in names: if action or not self.is_source: self.add_item_from_name(action) if self.is_source: actions = self.sort_actions_alphabetically(self.names) self.set_names(actions) @property def names(self): for i in range(self.count()): item = self.item(i) yield item.data(Qt.ItemDataRole.UserRole) class ConfigureToolBar(Dialog): def __init__(self, parent=None): Dialog.__init__(self, _('Configure the toolbar'), 'configure-viewer-toolbar', parent=parent, prefs=vprefs) def setup_ui(self): acnames = all_actions().all_action_names self.available_actions = ActionsList(acnames - frozenset(current_actions()), parent=self) self.available_actions.itemDoubleClicked.connect(self.add_item) self.current_actions = ActionsList(current_actions(), parent=self, is_source=False) self.current_actions.itemDoubleClicked.connect(self.remove_item) self.l = l = QVBoxLayout(self) self.la = la = QLabel(_('Choose the actions you want on the toolbar.' ' Drag and drop items in the right hand list to re-arrange the toolbar.')) la.setWordWrap(True) l.addWidget(la) self.bv = bv = QVBoxLayout() bv.addStretch(10) self.add_button = b = QToolButton(self) b.setIcon(QIcon.ic('forward.png')), b.setToolTip(_('Add selected actions to the toolbar')) bv.addWidget(b), bv.addStretch(10) b.clicked.connect(self.add_actions) self.remove_button = b = QToolButton(self) b.setIcon(QIcon.ic('back.png')), b.setToolTip(_('Remove selected actions from the toolbar')) b.clicked.connect(self.remove_actions) bv.addWidget(b), bv.addStretch(10) self.h = h = QHBoxLayout() l.addLayout(h) self.lg = lg = QGroupBox(_('A&vailable actions'), self) lg.v = v = QVBoxLayout(lg) v.addWidget(self.available_actions) h.addWidget(lg) self.rg = rg = QGroupBox(_('&Current actions'), self) rg.v = v = QVBoxLayout(rg) v.addWidget(self.current_actions) h.addLayout(bv), h.addWidget(rg) l.addWidget(self.bb) self.rdb = b = self.bb.addButton(_('Restore defaults'), QDialogButtonBox.ButtonRole.ActionRole) b.clicked.connect(self.restore_defaults) def remove_actions(self): names = self.current_actions.remove_selected() self.available_actions.add_names(names) def remove_item(self, item): names = self.current_actions.remove_item(item), self.available_actions.add_names(names) def add_actions(self): names = self.available_actions.remove_selected() self.current_actions.add_names(names) def add_item(self, item): names = self.available_actions.remove_item(item), self.current_actions.add_names(names) def restore_defaults(self): self.current_actions.set_names(DEFAULT_ACTIONS) acnames = all_actions().all_action_names rest = acnames - frozenset(DEFAULT_ACTIONS) rest = [None] + list(rest) self.available_actions.set_names(rest) def accept(self): ans = tuple(self.current_actions.names) if ans == DEFAULT_ACTIONS: vprefs.__delitem__('actions-toolbar-actions') else: vprefs.set('actions-toolbar-actions', ans) return Dialog.accept(self) if __name__ == '__main__': from calibre.gui2 import Application app = Application([]) ConfigureToolBar().exec()
24,570
Python
.py
505
38.936634
125
0.630468
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,776
convert_book.py
kovidgoyal_calibre/src/calibre/gui2/viewer/convert_book.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> import errno import json import os import tempfile import time from hashlib import sha1 from itertools import count from calibre import walk from calibre.constants import cache_dir, iswindows from calibre.ptempfile import TemporaryFile from calibre.srv.render_book import RENDER_VERSION from calibre.utils.filenames import rmtree from calibre.utils.ipc.simple_worker import start_pipe_worker from calibre.utils.lock import ExclusiveFile from calibre.utils.serialize import msgpack_dumps from calibre.utils.short_uuid import uuid4 from polyglot.builtins import as_bytes, as_unicode, iteritems DAY = 24 * 3600 VIEWER_VERSION = 1 td_counter = count() def book_cache_dir(): return getattr(book_cache_dir, 'override', os.path.join(cache_dir(), 'ev2')) def cache_lock(): return ExclusiveFile(os.path.join(book_cache_dir(), 'metadata.json'), timeout=600) def book_hash(path, size, mtime): path = os.path.normcase(os.path.abspath(path)) raw = json.dumps((path, size, mtime, RENDER_VERSION, VIEWER_VERSION)) if not isinstance(raw, bytes): raw = raw.encode('utf-8') return as_unicode(sha1(raw).hexdigest()) def safe_makedirs(path): try: os.makedirs(path) except OSError as err: if err.errno != errno.EEXIST: raise return path def robust_rmtree(x): retries = 2 if iswindows else 1 # retry on windows to get around the idiotic mandatory file locking for i in range(retries): try: try: rmtree(x) except UnicodeDecodeError: rmtree(as_bytes(x)) return True except OSError: time.sleep(0.1) return False def robust_rename(a, b): retries = 20 if iswindows else 1 # retry on windows to get around the idiotic mandatory file locking for i in range(retries): try: os.rename(a, b) return True except OSError: time.sleep(0.1) return False def clear_temp(temp_path): now = time.time() for x in os.listdir(temp_path): x = os.path.join(temp_path, x) mtime = os.path.getmtime(x) if now - mtime > DAY: robust_rmtree(x) def expire_cache(path, instances, max_age): now = time.time() remove = [x for x in instances if now - x['atime'] > max_age and x['status'] == 'finished'] for instance in remove: if robust_rmtree(os.path.join(path, instance['path'])): instances.remove(instance) def expire_old_versions(path, instances): instances = filter(lambda x: x['status'] == 'finished', instances) remove = sorted(instances, key=lambda x: x['atime'], reverse=True)[1:] for instance in remove: if robust_rmtree(os.path.join(path, instance['path'])): yield instance def expire_cache_and_temp(temp_path, finished_path, metadata, max_age, force_expire): now = time.time() if now - metadata['last_clear_at'] < DAY and max_age >= 0 and not force_expire: return clear_temp(temp_path) entries = metadata['entries'] path_key_map = {} for key, instances in tuple(entries.items()): if instances: expire_cache(finished_path, instances, max_age) if not instances: del entries[key] else: for x in instances: book_path = x.get('book_path') if book_path: path_key_map.setdefault(book_path, []).append(key) for keys in path_key_map.values(): instances = [] for key in keys: instances += entries.get(key, []) if len(instances) > 1: removed = tuple(expire_old_versions(finished_path, instances)) if removed: for r in removed: rkey = r['key'] if rkey in entries: try: entries[rkey].remove(r) except ValueError: pass if not entries[rkey]: del entries[rkey] metadata['last_clear_at'] = now def prepare_convert(temp_path, key, st, book_path): tdir = tempfile.mkdtemp(dir=temp_path, prefix=f'c{next(td_counter)}-') now = time.time() return { 'path': os.path.basename(tdir), 'id': uuid4(), 'status': 'working', 'mtime': now, 'atime': now, 'key': key, 'file_mtime': st.st_mtime, 'file_size': st.st_size, 'cache_size': 0, 'book_path': book_path, } class ConversionFailure(ValueError): def __init__(self, book_path, worker_output): self.book_path = book_path self.worker_output = worker_output ValueError.__init__( self, f'Failed to convert book: {book_path} with error:\n{worker_output}') running_workers = [] def clean_running_workers(): for p in running_workers: if p.poll() is None: p.kill() del running_workers[:] def do_convert(path, temp_path, key, instance): tdir = os.path.join(temp_path, instance['path']) p = None try: with TemporaryFile('log.txt') as logpath: with open(logpath, 'w+b') as logf: p = start_pipe_worker('from calibre.srv.render_book import viewer_main; viewer_main()', stdout=logf, stderr=logf) running_workers.append(p) p.stdin.write(msgpack_dumps(( path, tdir, {'size': instance['file_size'], 'mtime': instance['file_mtime'], 'hash': key}, ))) p.stdin.close() if p.wait() != 0: with open(logpath, 'rb') as logf: worker_output = logf.read().decode('utf-8', 'replace') raise ConversionFailure(path, worker_output) finally: try: running_workers.remove(p) except Exception: pass size = 0 for f in walk(tdir): size += os.path.getsize(f) instance['cache_size'] = size def save_metadata(metadata, f): f.seek(0), f.truncate(), f.write(as_bytes(json.dumps(metadata, indent=2))) def prepare_book(path, convert_func=do_convert, max_age=30 * DAY, force=False, prepare_notify=None, force_expire=False): st = os.stat(path) key = book_hash(path, st.st_size, st.st_mtime) finished_path = safe_makedirs(os.path.join(book_cache_dir(), 'f')) temp_path = safe_makedirs(os.path.join(book_cache_dir(), 't')) with cache_lock() as f: try: metadata = json.loads(f.read()) except ValueError: metadata = {'entries': {}, 'last_clear_at': 0} entries = metadata['entries'] instances = entries.setdefault(key, []) for instance in tuple(instances): if instance['status'] == 'finished': if force: robust_rmtree(os.path.join(finished_path, instance['path'])) instances.remove(instance) else: instance['atime'] = time.time() save_metadata(metadata, f) return os.path.join(finished_path, instance['path']) if prepare_notify: prepare_notify() instance = prepare_convert(temp_path, key, st, path) instances.append(instance) save_metadata(metadata, f) convert_func(path, temp_path, key, instance) src_path = os.path.join(temp_path, instance['path']) with cache_lock() as f: ans = tempfile.mkdtemp(dir=finished_path, prefix=f'c{next(td_counter)}-') instance['path'] = os.path.basename(ans) try: metadata = json.loads(f.read()) except ValueError: metadata = {'entries': {}, 'last_clear_at': 0} entries = metadata['entries'] instances = entries.setdefault(key, []) os.rmdir(ans) if not robust_rename(src_path, ans): raise Exception(( 'Failed to rename: "{}" to "{}" probably some software such as an antivirus or file sync program' ' running on your computer has locked the files' ).format(src_path, ans)) instance['status'] = 'finished' for q in instances: if q['id'] == instance['id']: q.update(instance) break expire_cache_and_temp(temp_path, finished_path, metadata, max_age, force_expire) save_metadata(metadata, f) return ans def update_book(path, old_stat, name_data_map=None): old_key = book_hash(path, old_stat.st_size, old_stat.st_mtime) finished_path = safe_makedirs(os.path.join(book_cache_dir(), 'f')) with cache_lock() as f: st = os.stat(path) new_key = book_hash(path, st.st_size, st.st_mtime) if old_key == new_key: return try: metadata = json.loads(f.read()) except ValueError: metadata = {'entries': {}, 'last_clear_at': 0} entries = metadata['entries'] instances = entries.get(old_key) if not instances: return for instance in tuple(instances): if instance['status'] == 'finished': entries.setdefault(new_key, []).append(instance) instances.remove(instance) if not instances: del entries[old_key] instance['file_mtime'] = st.st_mtime instance['file_size'] = st.st_size if name_data_map: for name, data in iteritems(name_data_map): with open(os.path.join(finished_path, instance['path'], name), 'wb') as f2: f2.write(data) save_metadata(metadata, f) return def find_tests(): import unittest class TestViewerCache(unittest.TestCase): ae = unittest.TestCase.assertEqual def setUp(self): self.tdir = tempfile.mkdtemp() book_cache_dir.override = os.path.join(self.tdir, 'ev2') def tearDown(self): rmtree(self.tdir) del book_cache_dir.override def test_viewer_cache(self): def convert_mock(path, temp_path, key, instance): self.ae(instance['status'], 'working') self.ae(instance['key'], key) with open(os.path.join(temp_path, instance['path'], 'sentinel'), 'wb') as f: f.write(b'test') def set_data(x): if not isinstance(x, bytes): x = x.encode('utf-8') with open(book_src, 'wb') as f: f.write(x) book_src = os.path.join(self.tdir, 'book.epub') set_data('a') path = prepare_book(book_src, convert_func=convert_mock) def read(x, mode='r'): with open(x, mode) as f: return f.read() self.ae(read(os.path.join(path, 'sentinel'), 'rb'), b'test') # Test that opening the same book uses the cache second_path = prepare_book(book_src, convert_func=convert_mock) self.ae(path, second_path) # Test that changing the book updates the cache set_data('bc') third_path = prepare_book(book_src, convert_func=convert_mock) self.assertNotEqual(path, third_path) # Test force reload fourth_path = prepare_book(book_src, convert_func=convert_mock) self.ae(third_path, fourth_path) fourth_path = prepare_book(book_src, convert_func=convert_mock, force=True) self.assertNotEqual(third_path, fourth_path) # Test cache expiry set_data('bcd') prepare_book(book_src, convert_func=convert_mock, max_age=-1000) self.ae([], os.listdir(os.path.join(book_cache_dir(), 'f'))) # Test modifying a book and opening it repeatedly leaves only # a single entry for it in the cache opath = prepare_book(book_src, convert_func=convert_mock, force_expire=True) finished_entries = os.listdir(os.path.join(book_cache_dir(), 'f')) self.ae(len(finished_entries), 1) set_data('bcde' * 4096) npath = prepare_book(book_src, convert_func=convert_mock, force_expire=True) new_finished_entries = os.listdir(os.path.join(book_cache_dir(), 'f')) self.ae(len(new_finished_entries), 1) self.assertNotEqual(opath, npath) set_data('bcdef') prepare_book(book_src, convert_func=convert_mock, max_age=-1000, force_expire=True) self.ae([], os.listdir(os.path.join(book_cache_dir(), 'f'))) with cache_lock() as f: metadata = json.loads(f.read()) self.assertEqual(metadata['entries'], {}) # Test updating cached book book_src = os.path.join(self.tdir, 'book2.epub') set_data('bb') path = prepare_book(book_src, convert_func=convert_mock) self.ae(read(os.path.join(path, 'sentinel'), 'rb'), b'test') bs = os.stat(book_src) set_data('cde') update_book(book_src, bs, name_data_map={'sentinel': b'updated'}) self.ae(read(os.path.join(path, 'sentinel'), 'rb'), b'updated') self.ae(1, len(os.listdir(os.path.join(book_cache_dir(), 'f')))) with cache_lock() as f: metadata = json.loads(f.read()) self.ae(len(metadata['entries']), 1) entry = list(metadata['entries'].values())[0] self.ae(len(entry), 1) entry = entry[0] st = os.stat(book_src) self.ae(entry['file_size'], st.st_size) self.ae(entry['file_mtime'], st.st_mtime) return unittest.defaultTestLoader.loadTestsFromTestCase(TestViewerCache)
14,107
Python
.py
328
32.411585
129
0.58029
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,777
printing.py
kovidgoyal_calibre/src/calibre/gui2/viewer/printing.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net> import os import subprocess import sys from threading import Thread from qt.core import ( QCheckBox, QDialog, QDoubleSpinBox, QFormLayout, QHBoxLayout, QIcon, QLabel, QLineEdit, QPageSize, QProgressDialog, QTimer, QToolButton, QVBoxLayout, ) from calibre import sanitize_file_name from calibre.ebooks.conversion.plugins.pdf_output import PAPER_SIZES from calibre.gui2 import Application, choose_save_file, dynamic, elided_text, error_dialog, open_local_file from calibre.gui2.widgets import PaperSizes from calibre.gui2.widgets2 import Dialog from calibre.ptempfile import PersistentTemporaryFile from calibre.utils.config import JSONConfig from calibre.utils.filenames import expanduser from calibre.utils.ipc.simple_worker import start_pipe_worker from calibre.utils.localization import _ from calibre.utils.serialize import msgpack_dumps, msgpack_loads vprefs = JSONConfig('viewer') class PrintDialog(Dialog): OUTPUT_NAME = 'print-to-pdf-choose-file' def __init__(self, book_title, parent=None, prefs=vprefs): self.book_title = book_title self.default_file_name = sanitize_file_name(book_title[:75] + '.pdf') self.paper_size_map = {a:getattr(QPageSize.PageSizeId, a.capitalize()) for a in PAPER_SIZES} Dialog.__init__(self, _('Print to PDF'), 'print-to-pdf', prefs=prefs, parent=parent) def setup_ui(self): self.vl = vl = QVBoxLayout(self) self.l = l = QFormLayout() vl.addLayout(l) l.setContentsMargins(0, 0, 0, 0) l.addRow(QLabel(_('Print %s to a PDF file') % elided_text(self.book_title))) self.h = h = QHBoxLayout() self.file_name = f = QLineEdit(self) val = dynamic.get(self.OUTPUT_NAME, None) if not val: val = expanduser('~') else: val = os.path.dirname(val) f.setText(os.path.abspath(os.path.join(val, self.default_file_name))) self.browse_button = b = QToolButton(self) b.setIcon(QIcon.ic('document_open.png')), b.setToolTip(_('Choose location for PDF file')) b.clicked.connect(self.choose_file) h.addWidget(f), h.addWidget(b) f.setMinimumWidth(350) w = QLabel(_('&File:')) l.addRow(w, h), w.setBuddy(f) self.paper_size = ps = PaperSizes(self) ps.initialize() ps.set_value_for_config = vprefs.get('print-to-pdf-page-size', None) l.addRow(_('Paper &size:'), ps) tmap = { 'left':_('&Left margin:'), 'top':_('&Top margin:'), 'right':_('&Right margin:'), 'bottom':_('&Bottom margin:'), } for edge in 'left top right bottom'.split(): m = QDoubleSpinBox(self) m.setSuffix(' ' + _('inches')) m.setMinimum(0), m.setMaximum(3), m.setSingleStep(0.1) val = vprefs.get('print-to-pdf-%s-margin' % edge, 1) m.setValue(val) setattr(self, '%s_margin' % edge, m) l.addRow(tmap[edge], m) self.pnum = pnum = QCheckBox(_('Add page &number to printed pages'), self) pnum.setChecked(vprefs.get('print-to-pdf-page-numbers', True)) l.addRow(pnum) self.show_file = sf = QCheckBox(_('&Open PDF file after printing'), self) sf.setChecked(vprefs.get('print-to-pdf-show-file', True)) l.addRow(sf) vl.addStretch(10) vl.addWidget(self.bb) @property def data(self): fpath = self.file_name.text().strip() head, tail = os.path.split(fpath) tail = sanitize_file_name(tail) fpath = tail if head: fpath = os.path.join(head, tail) ans = { 'output': fpath, 'paper_size': self.paper_size.get_value_for_config, 'page_numbers':self.pnum.isChecked(), 'show_file':self.show_file.isChecked(), } for edge in 'left top right bottom'.split(): ans['margin_' + edge] = getattr(self, '%s_margin' % edge).value() return ans def choose_file(self): ans = choose_save_file(self, self.OUTPUT_NAME, _('PDF file'), filters=[(_('PDF file'), ['pdf'])], all_files=False, initial_filename=self.default_file_name) if ans: self.file_name.setText(ans) def save_used_values(self): data = self.data vprefs['print-to-pdf-page-size'] = data['paper_size'] vprefs['print-to-pdf-page-numbers'] = data['page_numbers'] vprefs['print-to-pdf-show-file'] = data['show_file'] for edge in 'left top right bottom'.split(): vprefs['print-to-pdf-%s-margin' % edge] = data['margin_' + edge] def accept(self): fname = self.file_name.text().strip() if not fname: return error_dialog(self, _('No filename specified'), _( 'You must specify a filename for the PDF file to generate'), show=True) if not fname.lower().endswith('.pdf'): return error_dialog(self, _('Incorrect filename specified'), _( 'The filename for the PDF file must end with .pdf'), show=True) self.save_used_values() return Dialog.accept(self) class DoPrint(Thread): daemon = True def __init__(self, data): Thread.__init__(self, name='DoPrint') self.data = data self.tb = self.log = None def run(self): try: with PersistentTemporaryFile('print-to-pdf-log.txt') as f: p = self.worker = start_pipe_worker('from calibre.gui2.viewer.printing import do_print; do_print()', stdout=f, stderr=subprocess.STDOUT) p.stdin.write(msgpack_dumps(self.data)), p.stdin.flush(), p.stdin.close() rc = p.wait() if rc != 0: f.seek(0) self.log = f.read().decode('utf-8', 'replace') try: os.remove(f.name) except OSError: pass except Exception: import traceback self.tb = traceback.format_exc() def do_print(): from calibre.customize.ui import plugin_for_input_format stdin = getattr(sys.stdin, 'buffer', sys.stdin) data = msgpack_loads(stdin.read()) ext = data['input'].lower().rpartition('.')[-1] input_plugin = plugin_for_input_format(ext) if input_plugin is None: raise ValueError(f'Not a supported file type: {ext.upper()}') args = ['ebook-convert', data['input'], data['output'], '--paper-size', data['paper_size'], '--pdf-add-toc', '--disable-remove-fake-margins', '--chapter-mark', 'none', '-vv'] if input_plugin.is_image_collection: args.append('--no-process') else: args.append('--disable-font-rescaling') args.append('--page-breaks-before=/') if data['page_numbers']: args.append('--pdf-page-numbers') for edge in 'left top right bottom'.split(): args.append('--pdf-page-margin-' + edge), args.append('%.1f' % (data['margin_' + edge] * 72)) from calibre.ebooks.conversion.cli import main main(args) class Printing(QProgressDialog): def __init__(self, thread, show_file, parent=None): QProgressDialog.__init__(self, _('Printing, this will take a while, please wait...'), _('&Cancel'), 0, 0, parent) self.show_file = show_file self.setWindowTitle(_('Printing...')) self.setWindowIcon(QIcon.ic('print.png')) self.thread = thread self.timer = t = QTimer(self) t.timeout.connect(self.check) self.canceled.connect(self.do_cancel) t.start(100) def check(self): if self.thread.is_alive(): return if self.thread.tb or self.thread.log: error_dialog(self, _('Failed to convert to PDF'), _( 'Failed to generate PDF file, click "Show details" for more information.'), det_msg=self.thread.tb or self.thread.log, show=True) else: if self.show_file: open_local_file(self.thread.data['output']) self.accept() def do_cancel(self): if hasattr(self.thread, 'worker'): try: if self.thread.worker.poll() is None: self.thread.worker.kill() except OSError: import traceback traceback.print_exc() self.timer.stop() self.reject() def print_book(path_to_book, parent=None, book_title=None): book_title = book_title or os.path.splitext(os.path.basename(path_to_book))[0] d = PrintDialog(book_title, parent) if d.exec() == QDialog.DialogCode.Accepted: data = d.data data['input'] = path_to_book t = DoPrint(data) t.start() Printing(t, data['show_file'], parent).exec() if __name__ == '__main__': app = Application([]) print_book(sys.argv[-1]) del app
9,059
Python
.py
213
33.732394
152
0.603382
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,778
shortcuts.py
kovidgoyal_calibre/src/calibre/gui2/viewer/shortcuts.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> from qt.core import QKeySequence, QMainWindow, Qt key_name_to_qt_name = { 'ArrowRight': 'Right', 'ArrowLeft': 'Left', 'ArrowUp': 'Up', 'ArrowDown': 'Down', 'PageUp': 'PgUp', 'PageDown': 'PgDown', } def get_main_window_for(widget): p = widget while p is not None: if isinstance(p, QMainWindow): return p p = p.parent() def index_to_key_sequence(idx): mods = [] for i, x in enumerate(('ALT', 'CTRL', 'META', 'SHIFT')): if idx[i] == 'y': mods.append(x.capitalize()) key = idx[4:] mods.append(key_name_to_qt_name.get(key, key)) return QKeySequence('+'.join(mods)) def key_to_text(key): return QKeySequence(key).toString(QKeySequence.SequenceFormat.PortableText).lower() def ev_to_index(ev): m = ev.modifiers() mods = [] for x in ( Qt.KeyboardModifier.AltModifier, Qt.KeyboardModifier.ControlModifier, Qt.KeyboardModifier.MetaModifier, Qt.KeyboardModifier.ShiftModifier): mods.append('y' if m & x else 'n') return ''.join(mods) + key_to_text(ev.key()) def get_shortcut_for(widget, ev): mw = get_main_window_for(widget) if mw is None: return smap = mw.web_view.shortcut_map idx = ev_to_index(ev) return smap.get(idx)
1,399
Python
.py
42
27.714286
87
0.635417
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,779
widgets.py
kovidgoyal_calibre/src/calibre/gui2/viewer/widgets.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> import re from qt.core import QAction, QFont, QFontMetrics, QPalette, QStyle, QStyledItemDelegate, Qt, pyqtSignal from calibre.gui2 import QT_HIDDEN_CLEAR_ACTION from calibre.gui2.widgets2 import HistoryComboBox from calibre.utils.localization import _ class ResultsDelegate(QStyledItemDelegate): # {{{ add_ellipsis = True emphasize_text = True def result_data(self, result): if not hasattr(result, 'is_hidden'): return None, None, None, None, None return result.is_hidden, result.before, result.text, result.after, False def paint(self, painter, option, index): QStyledItemDelegate.paint(self, painter, option, index) result = index.data(Qt.ItemDataRole.UserRole) is_hidden, result_before, result_text, result_after, show_leading_dot = self.result_data(result) if result_text is None: return painter.save() try: p = option.palette c = QPalette.ColorRole.HighlightedText if option.state & QStyle.StateFlag.State_Selected else QPalette.ColorRole.Text group = (QPalette.ColorGroup.Active if option.state & QStyle.StateFlag.State_Active else QPalette.ColorGroup.Inactive) c = p.color(group, c) painter.setPen(c) font = option.font if self.emphasize_text: emphasis_font = QFont(font) emphasis_font.setBold(True) else: emphasis_font = font flags = Qt.AlignmentFlag.AlignTop | Qt.TextFlag.TextSingleLine | Qt.TextFlag.TextIncludeTrailingSpaces rect = option.rect.adjusted(option.decorationSize.width() + 4 if is_hidden else 0, 0, 0, 0) painter.setClipRect(rect) before = re.sub(r'\s+', ' ', result_before) if show_leading_dot: before = '•' + before before_width = 0 if before: before_width = painter.boundingRect(rect, flags, before).width() after = re.sub(r'\s+', ' ', result_after.rstrip()) after_width = 0 if after: after_width = painter.boundingRect(rect, flags, after).width() ellipsis_width = painter.boundingRect(rect, flags, '...').width() painter.setFont(emphasis_font) text = re.sub(r'\s+', ' ', result_text) match_width = painter.boundingRect(rect, flags, text).width() if match_width >= rect.width() - 3 * ellipsis_width: efm = QFontMetrics(emphasis_font) if show_leading_dot: text = '•' + text text = efm.elidedText(text, Qt.TextElideMode.ElideRight, rect.width()) painter.drawText(rect, flags, text) else: self.draw_match( painter, flags, before, text, after, rect, before_width, match_width, after_width, ellipsis_width, emphasis_font, font) except Exception: import traceback traceback.print_exc() painter.restore() def draw_match(self, painter, flags, before, text, after, rect, before_width, match_width, after_width, ellipsis_width, emphasis_font, normal_font): extra_width = int(rect.width() - match_width) if before_width < after_width: left_width = min(extra_width // 2, before_width) right_width = extra_width - left_width else: right_width = min(extra_width // 2, after_width) left_width = min(before_width, extra_width - right_width) x = rect.left() nfm = QFontMetrics(normal_font) if before_width and left_width: r = rect.adjusted(0, 0, 0, 0) r.setRight(x + left_width) painter.setFont(normal_font) ebefore = nfm.elidedText(before, Qt.TextElideMode.ElideLeft, left_width) if self.add_ellipsis and ebefore == before: ebefore = '…' + before[1:] r.setLeft(x) x += painter.drawText(r, flags, ebefore).width() painter.setFont(emphasis_font) r = rect.adjusted(0, 0, 0, 0) r.setLeft(x) painter.drawText(r, flags, text).width() x += match_width if after_width and right_width: painter.setFont(normal_font) r = rect.adjusted(0, 0, 0, 0) r.setLeft(x) eafter = nfm.elidedText(after, Qt.TextElideMode.ElideRight, right_width) if self.add_ellipsis and eafter == after: eafter = after[:-1] + '…' painter.setFont(normal_font) painter.drawText(r, flags, eafter) # }}} class SearchBox(HistoryComboBox): # {{{ history_saved = pyqtSignal(object, object) history_cleared = pyqtSignal() cleared = pyqtSignal() def __init__(self, parent=None): HistoryComboBox.__init__(self, parent, strip_completion_entries=False) self.lineEdit().setPlaceholderText(_('Search')) self.lineEdit().setClearButtonEnabled(True) ac = self.lineEdit().findChild(QAction, QT_HIDDEN_CLEAR_ACTION) if ac is not None: ac.triggered.connect(self.cleared) def save_history(self): ret = HistoryComboBox.save_history(self) self.history_saved.emit(self.text(), self.history) return ret def clear_history(self): super().clear_history() self.history_cleared.emit() def contextMenuEvent(self, event): menu = self.lineEdit().createStandardContextMenu() menu.addSeparator() menu.addAction(_('Clear search history'), self.clear_history) menu.exec(event.globalPos()) # }}}
5,800
Python
.py
121
37.239669
152
0.614432
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,780
lookup.py
kovidgoyal_calibre/src/calibre/gui2/viewer/lookup.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net> import sys import textwrap from functools import lru_cache from qt.core import ( QAbstractItemView, QApplication, QCheckBox, QComboBox, QDateTime, QDialog, QDialogButtonBox, QFormLayout, QHBoxLayout, QIcon, QLabel, QLineEdit, QListWidget, QListWidgetItem, QNetworkCookie, QPalette, QPushButton, QSize, Qt, QTimer, QUrl, QVBoxLayout, QWidget, pyqtSignal, ) from qt.webengine import QWebEnginePage, QWebEngineProfile, QWebEngineScript, QWebEngineView from calibre import prints, random_user_agent from calibre.ebooks.metadata.sources.search_engines import google_consent_cookies from calibre.gui2 import error_dialog from calibre.gui2.viewer.web_view import apply_font_settings, vprefs from calibre.gui2.widgets2 import Dialog from calibre.utils.localization import _, canonicalize_lang, get_lang, lang_as_iso639_1 from calibre.utils.resources import get_path as P from calibre.utils.webengine import create_script, insert_scripts, secure_webengine, setup_profile @lru_cache def lookup_lang(): ans = canonicalize_lang(get_lang()) if ans: ans = lang_as_iso639_1(ans) or ans return ans special_processors = {} def special_processor(func): special_processors[func.__name__] = func return func @special_processor def google_dictionary(word): ans = f'https://www.google.com/search?q=define:{word}' lang = lookup_lang() if lang: ans += f'#dobc={lang}' return ans vprefs.defaults['lookup_locations'] = [ { 'name': 'Google dictionary', 'url': 'https://www.google.com/search?q=define:{word}', 'special_processor': 'google_dictionary', 'langs': [], }, { 'name': 'Google search', 'url': 'https://www.google.com/search?q={word}', 'langs': [], }, { 'name': 'Wordnik', 'url': 'https://www.wordnik.com/words/{word}', 'langs': ['eng'], }, ] vprefs.defaults['lookup_location'] = 'Google dictionary' class SourceEditor(Dialog): def __init__(self, parent, source_to_edit=None): self.all_names = {x['name'] for x in parent.all_entries} self.initial_name = self.initial_url = None self.langs = [] if source_to_edit is not None: self.langs = source_to_edit['langs'] self.initial_name = source_to_edit['name'] self.initial_url = source_to_edit['url'] Dialog.__init__(self, _('Edit lookup source'), 'viewer-edit-lookup-location', parent=parent) self.resize(self.sizeHint()) def setup_ui(self): self.l = l = QFormLayout(self) self.name_edit = n = QLineEdit(self) n.setPlaceholderText(_('The name of the source')) n.setMinimumWidth(450) l.addRow(_('&Name:'), n) if self.initial_name: n.setText(self.initial_name) n.setReadOnly(True) self.url_edit = u = QLineEdit(self) u.setPlaceholderText(_('The URL template of the source')) u.setMinimumWidth(n.minimumWidth()) l.addRow(_('&URL:'), u) if self.initial_url: u.setText(self.initial_url) la = QLabel(_( 'The URL template must starts with https:// and have {word} in it which will be replaced by the actual query')) la.setWordWrap(True) l.addRow(la) l.addRow(self.bb) if self.initial_name: u.setFocus(Qt.FocusReason.OtherFocusReason) @property def source_name(self): return self.name_edit.text().strip() @property def url(self): return self.url_edit.text().strip() def accept(self): q = self.source_name if not q: return error_dialog(self, _('No name'), _( 'You must specify a name'), show=True) if not self.initial_name and q in self.all_names: return error_dialog(self, _('Name already exists'), _( 'A lookup source with the name {} already exists').format(q), show=True) if not self.url: return error_dialog(self, _('No name'), _( 'You must specify a URL'), show=True) if not self.url.startswith('http://') and not self.url.startswith('https://'): return error_dialog(self, _('Invalid URL'), _( 'The URL must start with https://'), show=True) if '{word}' not in self.url: return error_dialog(self, _('Invalid URL'), _( 'The URL must contain the placeholder {word}'), show=True) return Dialog.accept(self) @property def entry(self): return {'name': self.source_name, 'url': self.url, 'langs': self.langs} class SourcesEditor(Dialog): def __init__(self, parent): Dialog.__init__(self, _('Edit lookup sources'), 'viewer-edit-lookup-locations', parent=parent) def setup_ui(self): self.l = l = QVBoxLayout(self) self.la = la = QLabel(_('Double-click to edit an entry')) la.setWordWrap(True) l.addWidget(la) self.entries = e = QListWidget(self) e.setDragEnabled(True) e.itemDoubleClicked.connect(self.edit_source) e.viewport().setAcceptDrops(True) e.setDropIndicatorShown(True) e.setDragDropMode(QAbstractItemView.DragDropMode.InternalMove) e.setDefaultDropAction(Qt.DropAction.MoveAction) l.addWidget(e) l.addWidget(self.bb) self.build_entries(vprefs['lookup_locations']) self.add_button = b = self.bb.addButton(_('Add'), QDialogButtonBox.ButtonRole.ActionRole) b.setIcon(QIcon.ic('plus.png')) b.clicked.connect(self.add_source) self.remove_button = b = self.bb.addButton(_('Remove'), QDialogButtonBox.ButtonRole.ActionRole) b.setIcon(QIcon.ic('minus.png')) b.clicked.connect(self.remove_source) self.restore_defaults_button = b = self.bb.addButton(_('Restore defaults'), QDialogButtonBox.ButtonRole.ActionRole) b.clicked.connect(self.restore_defaults) def add_entry(self, entry, prepend=False): i = QListWidgetItem(entry['name']) i.setData(Qt.ItemDataRole.UserRole, entry.copy()) self.entries.insertItem(0, i) if prepend else self.entries.addItem(i) def build_entries(self, entries): self.entries.clear() for entry in entries: self.add_entry(entry) def restore_defaults(self): self.build_entries(vprefs.defaults['lookup_locations']) def add_source(self): d = SourceEditor(self) if d.exec() == QDialog.DialogCode.Accepted: self.add_entry(d.entry, prepend=True) def remove_source(self): idx = self.entries.currentRow() if idx > -1: self.entries.takeItem(idx) def edit_source(self, source_item): d = SourceEditor(self, source_item.data(Qt.ItemDataRole.UserRole)) if d.exec() == QDialog.DialogCode.Accepted: source_item.setData(Qt.ItemDataRole.UserRole, d.entry) source_item.setData(Qt.ItemDataRole.DisplayRole, d.name) @property def all_entries(self): return [self.entries.item(r).data(Qt.ItemDataRole.UserRole) for r in range(self.entries.count())] def accept(self): entries = self.all_entries if not entries: return error_dialog(self, _('No sources'), _( 'You must specify at least one lookup source'), show=True) if entries == vprefs.defaults['lookup_locations']: del vprefs['lookup_locations'] else: vprefs['lookup_locations'] = entries return Dialog.accept(self) def create_profile(): ans = getattr(create_profile, 'ans', None) if ans is None: ans = QWebEngineProfile('viewer-lookup', QApplication.instance()) ans.setHttpUserAgent(random_user_agent(allow_ie=False)) setup_profile(ans) js = P('lookup.js', data=True, allow_user_override=False) insert_scripts(ans, create_script('lookup.js', js, injection_point=QWebEngineScript.InjectionPoint.DocumentCreation)) s = ans.settings() s.setDefaultTextEncoding('utf-8') cs = ans.cookieStore() for c in google_consent_cookies(): cookie = QNetworkCookie() cookie.setName(c['name'].encode()) cookie.setValue(c['value'].encode()) cookie.setDomain(c['domain']) cookie.setPath(c['path']) cookie.setSecure(False) cookie.setHttpOnly(False) cookie.setExpirationDate(QDateTime()) cs.setCookie(cookie) create_profile.ans = ans return ans class Page(QWebEnginePage): def javaScriptConsoleMessage(self, level, msg, linenumber, source_id): prefix = { QWebEnginePage.JavaScriptConsoleMessageLevel.InfoMessageLevel: 'INFO', QWebEnginePage.JavaScriptConsoleMessageLevel.WarningMessageLevel: 'WARNING' }.get(level, 'ERROR') if source_id == 'userscript:lookup.js': prints(f'{prefix}: {source_id}:{linenumber}: {msg}', file=sys.stderr) sys.stderr.flush() def zoom_in(self): factor = min(self.zoomFactor() + 0.2, 5) vprefs['lookup_zoom_factor'] = factor self.setZoomFactor(factor) def zoom_out(self): factor = max(0.25, self.zoomFactor() - 0.2) vprefs['lookup_zoom_factor'] = factor self.setZoomFactor(factor) def default_zoom(self): vprefs['lookup_zoom_factor'] = 1 self.setZoomFactor(1) def set_initial_zoom_factor(self): try: self.setZoomFactor(float(vprefs.get('lookup_zoom_factor', 1))) except Exception: pass class View(QWebEngineView): inspect_element = pyqtSignal() def contextMenuEvent(self, ev): menu = self.createStandardContextMenu() menu.addSeparator() menu.addAction(_('Zoom in'), self.page().zoom_in) menu.addAction(_('Zoom out'), self.page().zoom_out) menu.addAction(_('Default zoom'), self.page().default_zoom) menu.addAction(_('Inspect'), self.do_inspect_element) menu.exec(ev.globalPos()) def do_inspect_element(self): self.inspect_element.emit() def set_sync_override(allowed): li = getattr(set_sync_override, 'instance', None) if li is not None: li.set_sync_override(allowed) def blank_html(): msg = _('Double click on a word in the book\'s text to look it up.') html = '<p>' + msg app = QApplication.instance() if app.is_dark_theme: pal = app.palette() bg = pal.color(QPalette.ColorRole.Base).name() fg = pal.color(QPalette.ColorRole.Text).name() html = f'<style> * {{ color: {fg}; background-color: {bg} }} </style>' + html return html class Lookup(QWidget): def __init__(self, parent): QWidget.__init__(self, parent) self.is_visible = False self.selected_text = '' self.current_query = '' self.current_source = '' self.l = l = QVBoxLayout(self) self.h = h = QHBoxLayout() l.addLayout(h) self.debounce_timer = t = QTimer(self) t.setInterval(150), t.timeout.connect(self.update_query) self.source_box = sb = QComboBox(self) self.label = la = QLabel(_('Lookup &in:')) h.addWidget(la), h.addWidget(sb), la.setBuddy(sb) self.view = View(self) self.view.inspect_element.connect(self.show_devtools) self._page = Page(create_profile(), self.view) apply_font_settings(self._page) secure_webengine(self._page, for_viewer=True) self.view.setPage(self._page) self._page.set_initial_zoom_factor() l.addWidget(self.view) self.populate_sources() self.source_box.currentIndexChanged.connect(self.source_changed) self.view.setHtml(blank_html()) self.add_button = b = QPushButton(QIcon.ic('plus.png'), _('Add sources')) b.setToolTip(_('Add more sources at which to lookup words')) b.clicked.connect(self.add_sources) self.refresh_button = rb = QPushButton(QIcon.ic('view-refresh.png'), _('Refresh')) rb.setToolTip(_('Refresh the result to match the currently selected text')) rb.clicked.connect(self.update_query) h = QHBoxLayout() l.addLayout(h) h.addWidget(b), h.addWidget(rb) self.auto_update_query = a = QCheckBox(_('Update on selection change'), self) self.disallow_auto_update = False a.setToolTip(textwrap.fill( _('Automatically update the displayed result when selected text in the book changes. With this disabled' ' the lookup is changed only when clicking the Refresh button.'))) a.setChecked(vprefs['auto_update_lookup']) a.stateChanged.connect(self.auto_update_state_changed) l.addWidget(a) self.update_refresh_button_status() set_sync_override.instance = self def set_sync_override(self, allowed): self.disallow_auto_update = not allowed if self.auto_update_query.isChecked() and allowed: self.update_query() def auto_update_state_changed(self, state): vprefs['auto_update_lookup'] = self.auto_update_query.isChecked() self.update_refresh_button_status() def show_devtools(self): if not hasattr(self, '_devtools_page'): self._devtools_page = QWebEnginePage() self._devtools_view = QWebEngineView(self) self._devtools_view.setPage(self._devtools_page) setup_profile(self._devtools_page.profile()) self._page.setDevToolsPage(self._devtools_page) self._devtools_dialog = d = QDialog(self) d.setWindowTitle('Inspect Lookup page') v = QVBoxLayout(d) v.addWidget(self._devtools_view) d.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) d.bb.rejected.connect(d.reject) v.addWidget(d.bb) d.resize(QSize(800, 600)) d.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False) self._devtools_dialog.show() self._page.triggerAction(QWebEnginePage.WebAction.InspectElement) def add_sources(self): if SourcesEditor(self).exec() == QDialog.DialogCode.Accepted: self.populate_sources() self.source_box.setCurrentIndex(0) self.update_query() def source_changed(self): s = self.source if s is not None: vprefs['lookup_location'] = s['name'] self.update_query() def populate_sources(self): sb = self.source_box sb.clear() sb.blockSignals(True) for item in vprefs['lookup_locations']: sb.addItem(item['name'], item) idx = sb.findText(vprefs['lookup_location'], Qt.MatchFlag.MatchExactly) if idx > -1: sb.setCurrentIndex(idx) sb.blockSignals(False) def visibility_changed(self, is_visible): self.is_visible = is_visible self.update_query() @property def source(self): idx = self.source_box.currentIndex() if idx > -1: return self.source_box.itemData(idx) @property def url_template(self): idx = self.source_box.currentIndex() if idx > -1: return self.source_box.itemData(idx)['url'] @property def special_processor(self): idx = self.source_box.currentIndex() if idx > -1: return special_processors.get(self.source_box.itemData(idx).get('special_processor')) @property def query_is_up_to_date(self): query = self.selected_text or self.current_query return self.current_query == query and self.current_source == self.url_template def update_refresh_button_status(self): b = self.refresh_button b.setVisible(not self.auto_update_query.isChecked()) b.setEnabled(not self.query_is_up_to_date) def update_query(self): self.debounce_timer.stop() query = self.selected_text or self.current_query if self.query_is_up_to_date: return if not self.is_visible or not query: return self.current_source = self.url_template sp = self.special_processor if sp is None: url = self.current_source.format(word=query) else: url = sp(query) self.view.load(QUrl(url)) self.current_query = query self.update_refresh_button_status() def selected_text_changed(self, text, annot_id): already_has_text = bool(self.current_query) self.selected_text = text or '' if not self.disallow_auto_update and (self.auto_update_query.isChecked() or not already_has_text): self.debounce_timer.start() self.update_refresh_button_status() def on_forced_show(self): self.update_query()
17,130
Python
.py
412
33.199029
125
0.635484
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,781
main.py
kovidgoyal_calibre/src/calibre/gui2/viewer/main.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net> import json import os import sys from contextlib import closing from qt.core import QIcon, QObject, Qt, QTimer, pyqtSignal from calibre.constants import VIEWER_APP_UID, islinux from calibre.gui2 import Application, error_dialog, setup_gui_option_parser from calibre.gui2.listener import send_message_in_process from calibre.gui2.viewer.config import get_session_pref, vprefs from calibre.gui2.viewer.ui import EbookViewer, is_float from calibre.ptempfile import reset_base_dir from calibre.utils.config import JSONConfig from calibre.utils.ipc import viewer_socket_address from calibre.utils.localization import _ singleinstance_name = 'calibre_viewer' def migrate_previous_viewer_prefs(): new_prefs = vprefs if new_prefs['old_prefs_migrated']: return old_vprefs = JSONConfig('viewer') old_prefs = JSONConfig('viewer.py') with new_prefs: sd = new_prefs['session_data'] fs = sd.get('standalone_font_settings', {}) for k in ('serif', 'sans', 'mono'): defval = 'Liberation ' + k.capitalize() k += '_family' if old_prefs.get(k) and old_prefs[k] != defval: fs[k] = old_prefs[k] if old_prefs.get('standard_font') in ('serif', 'sans', 'mono'): fs['standard_font'] = old_prefs['standard_font'] if old_prefs.get('minimum_font_size') is not None and old_prefs['minimum_font_size'] != 8: fs['minimum_font_size'] = old_prefs['minimum_font_size'] sd['standalone_font_settings'] = fs ms = sd.get('standalone_misc_settings', {}) ms['remember_window_geometry'] = bool(old_prefs.get('remember_window_size', False)) ms['remember_last_read'] = bool(old_prefs.get('remember_current_page', True)) ms['save_annotations_in_ebook'] = bool(old_prefs.get('copy_bookmarks_to_file', True)) ms['singleinstance'] = bool(old_vprefs.get('singleinstance', False)) sd['standalone_misc_settings'] = ms for k in ('top', 'bottom'): v = old_prefs.get(k + '_margin') if v != 20 and v is not None: sd['margin_' + k] = v v = old_prefs.get('side_margin') if v is not None and v != 40: sd['margin_left'] = sd['margin_right'] = v // 2 if old_prefs.get('user_css'): sd['user_stylesheet'] = old_prefs['user_css'] cps = {'portrait': 0, 'landscape': 0} cp = old_prefs.get('cols_per_screen_portrait') if cp and cp > 1: cps['portrait'] = cp cl = old_prefs.get('cols_per_screen_landscape') if cl and cl > 1: cps['landscape'] = cp if cps['portrait'] or cps['landscape']: sd['columns_per_screen'] = cps if old_vprefs.get('in_paged_mode') is False: sd['read_mode'] = 'flow' new_prefs.set('session_data', sd) new_prefs.set('old_prefs_migrated', True) class EventAccumulator(QObject): got_file = pyqtSignal(object) def __init__(self, parent): QObject.__init__(self, parent) self.events = [] def __call__(self, paths): for path in paths: if os.path.exists(path): self.events.append(path) self.got_file.emit(path) def flush(self): if self.events: self.got_file.emit(self.events[-1]) self.events = [] def send_message_to_viewer_instance(args, open_at): if len(args) > 1: msg = json.dumps((os.path.abspath(args[1]), open_at)) try: send_message_in_process(msg, address=viewer_socket_address()) except Exception as err: error_dialog(None, _('Connecting to E-book viewer failed'), _( 'Unable to connect to existing E-book viewer window, try restarting the viewer.'), det_msg=str(err), show=True) raise SystemExit(1) print('Opened book in existing viewer instance') def option_parser(): from calibre.gui2.main_window import option_parser parser = option_parser(_('''\ %prog [options] file View an e-book. ''')) a = parser.add_option a('--raise-window', default=False, action='store_true', help=_('If specified, the E-book viewer window will try to come to the ' 'front when started.')) a('--full-screen', '--fullscreen', '-f', default=False, action='store_true', help=_('If specified, the E-book viewer window will try to open ' 'full screen when started.')) a('--force-reload', default=False, action='store_true', help=_('Force reload of all opened books')) a('--open-at', default=None, help=_( 'The position at which to open the specified book. The position is ' 'a location or position you can get by using the Go to->Location action in the viewer controls. ' 'Alternately, you can use the form toc:something and it will open ' 'at the location of the first Table of Contents entry that contains ' 'the string "something". The form toc-href:something will match the ' 'href (internal link destination) of toc nodes. The matching is exact. ' 'If you want to match a substring, use the form toc-href-contains:something. ' 'The form ref:something will use Reference mode references. The form search:something will' ' search for something after opening the book. The form regex:something will search' ' for the regular expression something after opening the book.' )) a('--continue', default=False, action='store_true', dest='continue_reading', help=_('Continue reading the last opened book')) a('--new-instance', default=False, action='store_true', help=_( 'Open a new viewer window even when the option to use only a single viewer window is set')) setup_gui_option_parser(parser) return parser def run_gui(app, opts, args, internal_book_data, listener=None): acc = EventAccumulator(app) app.file_event_hook = acc app.load_builtin_fonts() app.setWindowIcon(QIcon.ic('viewer.png')) migrate_previous_viewer_prefs() main = EbookViewer( open_at=opts.open_at, continue_reading=opts.continue_reading, force_reload=opts.force_reload, calibre_book_data=internal_book_data) main.set_exception_handler() if len(args) > 1: acc.events.append(os.path.abspath(args[-1])) acc.got_file.connect(main.handle_commandline_arg) main.show() if listener is not None: listener.message_received.connect(main.message_from_other_instance, type=Qt.ConnectionType.QueuedConnection) QTimer.singleShot(0, acc.flush) if opts.raise_window: main.raise_and_focus() if opts.full_screen: main.set_full_screen(True) app.exec() def main(args=sys.argv): from calibre.utils.webengine import setup_fake_protocol # Ensure viewer can continue to function if GUI is closed os.environ.pop('CALIBRE_WORKER_TEMP_DIR', None) reset_base_dir() setup_fake_protocol() override = 'calibre-ebook-viewer' if islinux else None processed_args = [] internal_book_data = internal_book_data_path = None for arg in args: if arg.startswith('--internal-book-data='): internal_book_data_path = arg.split('=', 1)[1] continue processed_args.append(arg) if internal_book_data_path: try: with open(internal_book_data_path, 'rb') as f: internal_book_data = json.load(f) finally: try: os.remove(internal_book_data_path) except OSError: pass args = processed_args app = Application(args, override_program_name=override, windows_app_uid=VIEWER_APP_UID) from calibre.utils.webengine import setup_default_profile setup_default_profile() parser = option_parser() opts, args = parser.parse_args(args) oat = opts.open_at if oat and not ( oat.startswith('toc:') or oat.startswith('toc-href:') or oat.startswith('toc-href-contains:') or oat.startswith('epubcfi(/') or is_float(oat) or oat.startswith('ref:') or oat.startswith('search:') or oat.startswith('regex:')): raise SystemExit(f'Not a valid --open-at value: {opts.open_at}') if not opts.new_instance and get_session_pref('singleinstance', False): from calibre.gui2.listener import Listener from calibre.utils.lock import SingleInstance with SingleInstance(singleinstance_name) as si: if si: try: listener = Listener(address=viewer_socket_address(), parent=app) listener.start_listening() except Exception as err: error_dialog(None, _('Failed to start listener'), _( 'Could not start the listener used for single instance viewers. Try rebooting your computer.'), det_msg=str(err), show=True) else: with closing(listener): run_gui(app, opts, args, internal_book_data, listener=listener) else: send_message_to_viewer_instance(args, opts.open_at) else: run_gui(app, opts, args, internal_book_data) if __name__ == '__main__': sys.exit(main())
9,450
Python
.py
198
39.131313
141
0.635821
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,782
tts.py
kovidgoyal_calibre/src/calibre/gui2/viewer/tts.py
#!/usr/bin/env python # License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net> from qt.core import QObject, pyqtSignal def set_sync_override(allowed): from calibre.gui2.viewer.lookup import set_sync_override set_sync_override(allowed) class TTS(QObject): event_received = pyqtSignal(object, object) settings_changed = pyqtSignal(object) def __init__(self, parent=None): super().__init__(parent) self._manager = None @property def manager(self): if self._manager is None: from calibre.gui2.tts.manager import TTSManager self._manager = TTSManager(self) self._manager.saying.connect(self.saying) self._manager.state_event.connect(self.state_event) return self._manager def shutdown(self): if self._manager is not None: self._manager.stop() self._manager = None def speak_simple_text(self, text): self.manager.speak_simple_text(text) def action(self, action, data): if action != 'resume_after_configure': # resume_after_configure is not used in new tts backend getattr(self, action)(data) def play(self, data): set_sync_override(False) self.manager.speak_marked_text(data['marked_text']) def pause(self, data): set_sync_override(True) self.manager.pause() def resume(self, data): set_sync_override(False) self.manager.resume() def saying(self, first: int, last: int) -> None: self.event_received.emit('mark', {'first': first, 'last': last}) def state_event(self, name: str): self.event_received.emit(name, None) def stop(self, data): set_sync_override(True) self.manager.stop() def configure(self, data): self.manager.configure() def slower(self, data): self.manager.change_rate(steps=-1) def faster(self, data): self.manager.change_rate(steps=1)
2,001
Python
.py
51
31.568627
103
0.649741
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,783
saving.py
kovidgoyal_calibre/src/calibre/gui2/preferences/saving.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from calibre.gui2 import gprefs from calibre.gui2.preferences import AbortCommit, ConfigWidgetBase, test_widget from calibre.gui2.preferences.saving_ui import Ui_Form from calibre.library.save_to_disk import config from calibre.utils.config import ConfigProxy class ConfigWidget(ConfigWidgetBase, Ui_Form): def genesis(self, gui): self.gui = gui self.proxy = ConfigProxy(config()) r = self.register for x in ('asciiize', 'update_metadata', 'save_cover', 'write_opf', 'replace_whitespace', 'to_lowercase', 'formats', 'timefmt', 'save_extra_files'): r(x, self.proxy) r('show_files_after_save', gprefs) self.save_template.changed_signal.connect(self.changed_signal.emit) def initialize(self): ConfigWidgetBase.initialize(self) self.save_template.blockSignals(True) self.save_template.initialize('save_to_disk', self.proxy['template'], self.proxy.help('template'), self.gui.library_view.model().db.field_metadata) self.save_template.blockSignals(False) def restore_defaults(self): ConfigWidgetBase.restore_defaults(self) self.save_template.set_value(self.proxy.defaults['template']) def commit(self): if not self.save_template.validate(): raise AbortCommit('abort') self.save_template.save_settings(self.proxy, 'template') return ConfigWidgetBase.commit(self) def refresh_gui(self, gui): gui.iactions['Save To Disk'].reread_prefs() # Ensure worker process reads updated settings gui.spare_pool().shutdown() if __name__ == '__main__': from qt.core import QApplication app = QApplication([]) test_widget('Import/Export', 'Saving')
1,933
Python
.py
42
38.738095
96
0.681067
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,784
device_user_defined.py
kovidgoyal_calibre/src/calibre/gui2/preferences/device_user_defined.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import numbers from qt.core import QApplication, QDialog, QDialogButtonBox, QIcon, QMessageBox, QPlainTextEdit, QPushButton, QTimer, QVBoxLayout def step_dialog(parent, title, msg, det_msg=''): d = QMessageBox(parent) d.setWindowTitle(title) d.setText(msg) d.setStandardButtons(QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel) return d.exec() & QMessageBox.StandardButton.Cancel class UserDefinedDevice(QDialog): def __init__(self, parent=None): QDialog.__init__(self, parent) self._layout = QVBoxLayout(self) self.setLayout(self._layout) self.log = QPlainTextEdit(self) self._layout.addWidget(self.log) self.log.setPlainText(_('Getting device information')+'...') self.copy = QPushButton(_('Copy to &clipboard')) self.copy.setDefault(True) self.setWindowTitle(_('User-defined device information')) self.setWindowIcon(QIcon.ic('debug.png')) self.copy.clicked.connect(self.copy_to_clipboard) self.ok = QPushButton('&OK') self.ok.setAutoDefault(False) self.ok.clicked.connect(self.accept) self.bbox = QDialogButtonBox(self) self.bbox.addButton(self.copy, QDialogButtonBox.ButtonRole.ActionRole) self.bbox.addButton(self.ok, QDialogButtonBox.ButtonRole.AcceptRole) self._layout.addWidget(self.bbox) self.resize(750, 500) self.bbox.setEnabled(False) QTimer.singleShot(1000, self.device_info) def device_info(self): try: from calibre.devices import device_info r = step_dialog(self.parent(), _('Device Detection'), _('Ensure your device is disconnected, then press OK')) if r: self.close() return before = device_info() r = step_dialog(self.parent(), _('Device Detection'), _('Ensure your device is connected, then press OK')) if r: self.close() return after = device_info() new_devices = after['device_set'] - before['device_set'] res = '' if len(new_devices) == 1: def fmtid(x): x = x or 0 if isinstance(x, numbers.Integral): x = hex(x) if not x.startswith('0x'): x = '0x' + x return x for d in new_devices: res = _('USB Vendor ID (in hex)') + ': ' + \ fmtid(after['device_details'][d][0]) + '\n' res += _('USB Product ID (in hex)') + ': ' + \ fmtid(after['device_details'][d][1]) + '\n' res += _('USB Revision ID (in hex)') + ': ' + \ fmtid(after['device_details'][d][2]) + '\n' trailer = _( 'Copy these values to the clipboard, paste them into an ' 'editor, then enter them into the USER_DEVICE by ' 'customizing the device plugin in Preferences->Advanced->Plugins. ' 'Remember to also enter the folders where you want the books to ' 'be put. You must restart calibre for your changes ' 'to take effect.\n') self.log.setPlainText(res + '\n\n' + trailer) finally: self.bbox.setEnabled(True) def copy_to_clipboard(self): QApplication.clipboard().setText(self.log.toPlainText()) if __name__ == '__main__': app = QApplication([]) d = UserDefinedDevice() d.exec()
3,864
Python
.py
83
34.192771
129
0.560542
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,785
texture_chooser.py
kovidgoyal_calibre/src/calibre/gui2/preferences/texture_chooser.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' import glob import os import shutil from functools import partial from qt.core import ( QAbstractItemView, QApplication, QDialog, QDialogButtonBox, QIcon, QLabel, QListView, QListWidget, QListWidgetItem, QSize, Qt, QTimer, QVBoxLayout, ) from calibre.constants import config_dir from calibre.gui2 import choose_files, error_dialog from calibre.utils.icu import sort_key from calibre.utils.resources import get_image_path as I def texture_dir(): ans = os.path.join(config_dir, 'textures') if not os.path.exists(ans): os.makedirs(ans) return ans def texture_path(fname): if not fname: return if fname.startswith(':'): return I('textures/%s' % fname[1:]) return os.path.join(texture_dir(), fname) class TextureChooser(QDialog): def __init__(self, parent=None, initial=None): QDialog.__init__(self, parent) self.setWindowTitle(_('Choose a texture')) self.l = l = QVBoxLayout() self.setLayout(l) self.tdir = texture_dir() self.images = il = QListWidget(self) il.itemDoubleClicked.connect(self.accept, type=Qt.ConnectionType.QueuedConnection) il.setIconSize(QSize(256, 256)) il.setViewMode(QListView.ViewMode.IconMode) il.setFlow(QListView.Flow.LeftToRight) il.setSpacing(20) il.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection) il.itemSelectionChanged.connect(self.update_remove_state) l.addWidget(il) self.ad = ad = QLabel(_('The builtin textures come from <a href="{}">subtlepatterns.com</a>.').format( 'https://www.toptal.com/designers/subtlepatterns/')) ad.setOpenExternalLinks(True) ad.setWordWrap(True) l.addWidget(ad) self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) b = self.add_button = bb.addButton(_('Add texture'), QDialogButtonBox.ButtonRole.ActionRole) b.setIcon(QIcon.ic('plus.png')) b.clicked.connect(self.add_texture) b = self.remove_button = bb.addButton(_('Remove texture'), QDialogButtonBox.ButtonRole.ActionRole) b.setIcon(QIcon.ic('minus.png')) b.clicked.connect(self.remove_texture) l.addWidget(bb) images = [{ 'fname': ':'+os.path.basename(x), 'path': x, 'name': ' '.join(map(lambda s: s.capitalize(), os.path.splitext(os.path.basename(x))[0].split('_'))) } for x in glob.glob(I('textures/*.png'))] + [{ 'fname': os.path.basename(x), 'path': x, 'name': os.path.splitext(os.path.basename(x))[0], } for x in glob.glob(os.path.join(self.tdir, '*')) if x.rpartition('.')[-1].lower() in {'jpeg', 'png', 'jpg'}] images.sort(key=lambda x:sort_key(x['name'])) for i in images: self.create_item(i) self.update_remove_state() if initial: existing = {str(i.data(Qt.ItemDataRole.UserRole) or ''):i for i in (self.images.item(c) for c in range(self.images.count()))} item = existing.get(initial, None) if item is not None: item.setSelected(True) QTimer.singleShot(100, partial(il.scrollToItem, item)) self.resize(QSize(950, 650)) def create_item(self, data): x = data i = QListWidgetItem(QIcon(x['path']), x['name'], self.images) i.setData(Qt.ItemDataRole.UserRole, x['fname']) i.setData(Qt.ItemDataRole.UserRole+1, x['path']) return i def update_remove_state(self): removable = bool(self.selected_fname and not self.selected_fname.startswith(':')) self.remove_button.setEnabled(removable) @property def texture(self): return self.selected_fname def add_texture(self): path = choose_files(self, 'choose-texture-image', _('Choose image'), filters=[(_('Images'), ['jpeg', 'jpg', 'png'])], all_files=False, select_only_single_file=True) if not path: return path = path[0] fname = os.path.basename(path) name = fname.rpartition('.')[0] existing = {str(i.data(Qt.ItemDataRole.UserRole) or ''):i for i in (self.images.item(c) for c in range(self.images.count()))} dest = os.path.join(self.tdir, fname) with open(path, 'rb') as s, open(dest, 'wb') as f: shutil.copyfileobj(s, f) if fname in existing: self.takeItem(existing[fname]) data = {'fname': fname, 'path': dest, 'name': name} i = self.create_item(data) i.setSelected(True) self.images.scrollToItem(i) @property def selected_item(self): for x in self.images.selectedItems(): return x @property def selected_fname(self): try: return str(self.selected_item.data(Qt.ItemDataRole.UserRole) or '') except (AttributeError, TypeError): pass def remove_texture(self): if not self.selected_fname: return if self.selected_fname.startswith(':'): return error_dialog(self, _('Cannot remove'), _('Cannot remove builtin textures'), show=True) os.remove(str(self.selected_item.data(Qt.ItemDataRole.UserRole+1) or '')) self.images.takeItem(self.images.row(self.selected_item)) if __name__ == '__main__': app = QApplication([]) # noqa d = TextureChooser() d.exec() print(d.texture)
5,791
Python
.py
141
32.822695
137
0.625089
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,786
ignored_devices.py
kovidgoyal_calibre/src/calibre/gui2/preferences/ignored_devices.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2012, Kovid Goyal <kovid at kovidgoyal.net> import textwrap from qt.core import QIcon, QLabel, QListWidget, QListWidgetItem, QPushButton, Qt, QVBoxLayout from calibre.customize.ui import enable_plugin from calibre.gui2 import gprefs from calibre.gui2.preferences import ConfigWidgetBase, test_widget from polyglot.builtins import iteritems class ConfigWidget(ConfigWidgetBase): restart_critical = False def genesis(self, gui): self.gui = gui self.l = l = QVBoxLayout() self.setLayout(l) self.confirms_reset = False self.la = la = QLabel(_( 'The list of devices that you have asked calibre to ignore. ' 'Uncheck a device to have calibre stop ignoring it.')) la.setWordWrap(True) l.addWidget(la) self.devices = f = QListWidget(self) l.addWidget(f) f.itemChanged.connect(self.changed_signal) f.itemDoubleClicked.connect(self.toggle_item) self.la2 = la = QLabel(_( 'The list of device plugins you have disabled. Uncheck an entry ' 'to enable the plugin. calibre cannot detect devices that are ' 'managed by disabled plugins.')) la.setWordWrap(True) l.addWidget(la) self.device_plugins = f = QListWidget(f) l.addWidget(f) f.itemChanged.connect(self.changed_signal) f.itemDoubleClicked.connect(self.toggle_item) self.reset_confirmations_button = b = QPushButton(_('Reset allowed devices')) b.setToolTip(textwrap.fill(_( 'This will erase the list of devices that calibre knows about' ' causing it to ask you for permission to manage them again,' ' the next time they connect'))) b.clicked.connect(self.reset_confirmations) l.addWidget(b) def reset_confirmations(self): self.confirms_reset = True self.changed_signal.emit() def toggle_item(self, item): item.setCheckState(Qt.CheckState.Checked if item.checkState() == Qt.CheckState.Unchecked else Qt.CheckState.Unchecked) def initialize(self): self.confirms_reset = False self.devices.blockSignals(True) self.devices.clear() for dev in self.gui.device_manager.devices: for d, name in iteritems(dev.get_user_blacklisted_devices()): item = QListWidgetItem('%s [%s]'%(name, d), self.devices) item.setData(Qt.ItemDataRole.UserRole, (dev, d)) item.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsUserCheckable|Qt.ItemFlag.ItemIsSelectable) item.setCheckState(Qt.CheckState.Checked) self.devices.blockSignals(False) self.device_plugins.blockSignals(True) for dev in self.gui.device_manager.disabled_device_plugins: n = dev.get_gui_name() item = QListWidgetItem(n, self.device_plugins) item.setData(Qt.ItemDataRole.UserRole, dev) item.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsUserCheckable|Qt.ItemFlag.ItemIsSelectable) item.setCheckState(Qt.CheckState.Checked) item.setIcon(QIcon.ic('plugins.png')) self.device_plugins.sortItems() self.device_plugins.blockSignals(False) def restore_defaults(self): if self.devices.count() > 0: self.devices.clear() def commit(self): devs = {} for i in range(0, self.devices.count()): e = self.devices.item(i) dev, uid = e.data(Qt.ItemDataRole.UserRole) if dev not in devs: devs[dev] = [] if e.checkState() == Qt.CheckState.Checked: devs[dev].append(uid) for dev, bl in iteritems(devs): dev.set_user_blacklisted_devices(bl) for i in range(self.device_plugins.count()): e = self.device_plugins.item(i) dev = e.data(Qt.ItemDataRole.UserRole) if e.checkState() == Qt.CheckState.Unchecked: enable_plugin(dev) if self.confirms_reset: gprefs['ask_to_manage_device'] = [] return True # Restart required if __name__ == '__main__': from calibre.gui2 import Application app = Application([]) test_widget('Sharing', 'Ignored Devices')
4,381
Python
.py
94
36.882979
117
0.646493
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,787
plugins.py
kovidgoyal_calibre/src/calibre/gui2/preferences/plugins.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os import textwrap from collections import OrderedDict from qt.core import QAbstractItemModel, QAbstractItemView, QBrush, QDialog, QIcon, QItemSelectionModel, QMenu, QModelIndex, Qt from calibre.constants import iswindows from calibre.customize import PluginInstallationType from calibre.customize.ui import NameConflict, add_plugin, disable_plugin, enable_plugin, initialized_plugins, is_disabled, plugin_customization, remove_plugin from calibre.gui2 import choose_files, error_dialog, gprefs, info_dialog, question_dialog from calibre.gui2.dialogs.confirm_delete import confirm from calibre.gui2.preferences import ConfigWidgetBase, test_widget from calibre.gui2.preferences.plugins_ui import Ui_Form from calibre.utils.icu import lower from calibre.utils.search_query_parser import SearchQueryParser from polyglot.builtins import iteritems, itervalues class AdaptSQP(SearchQueryParser): def __init__(self, *args, **kwargs): pass class PluginModel(QAbstractItemModel, AdaptSQP): # {{{ def __init__(self, show_only_user_plugins=False): QAbstractItemModel.__init__(self) SearchQueryParser.__init__(self, ['all']) self.show_only_user_plugins = show_only_user_plugins self.icon = QIcon.ic('plugins.png') p = self.icon.pixmap(64, 64, QIcon.Mode.Disabled, QIcon.State.On) self.disabled_icon = QIcon(p) self._p = p self.populate() def toggle_shown_plugins(self, show_only_user_plugins): self.show_only_user_plugins = show_only_user_plugins self.beginResetModel() self.populate() self.endResetModel() def populate(self): self._data = {} for plugin in initialized_plugins(): if (getattr(plugin, 'installation_type', None) is not PluginInstallationType.EXTERNAL and self.show_only_user_plugins): continue if plugin.type not in self._data: self._data[plugin.type] = [plugin] else: self._data[plugin.type].append(plugin) self.categories = sorted(self._data.keys()) for plugins in self._data.values(): plugins.sort(key=lambda x: x.name.lower()) def universal_set(self): ans = set() for c, category in enumerate(self.categories): ans.add((c, -1)) for p, plugin in enumerate(self._data[category]): ans.add((c, p)) return ans def get_matches(self, location, query, candidates=None): if candidates is None: candidates = self.universal_set() ans = set() if not query: return ans query = lower(query) for c, p in candidates: if p < 0: if query in lower(self.categories[c]): ans.add((c, p)) continue else: try: plugin = self._data[self.categories[c]][p] except: continue if query in lower(plugin.name) or query in lower(plugin.author) or \ query in lower(plugin.description): ans.add((c, p)) return ans def find(self, query): query = query.strip() if not query: return QModelIndex() matches = self.parse(query) if not matches: return QModelIndex() matches = list(sorted(matches)) c, p = matches[0] cat_idx = self.index(c, 0, QModelIndex()) if p == -1: return cat_idx return self.index(p, 0, cat_idx) def find_next(self, idx, query, backwards=False): query = query.strip() if not query: return idx matches = self.parse(query) if not matches: return idx if idx.parent().isValid(): loc = (idx.parent().row(), idx.row()) else: loc = (idx.row(), -1) if loc not in matches: return self.find(query) if len(matches) == 1: return QModelIndex() matches = list(sorted(matches)) i = matches.index(loc) if backwards: ans = i - 1 if i - 1 >= 0 else len(matches)-1 else: ans = i + 1 if i + 1 < len(matches) else 0 ans = matches[ans] return self.index(ans[0], 0, QModelIndex()) if ans[1] < 0 else \ self.index(ans[1], 0, self.index(ans[0], 0, QModelIndex())) def index(self, row, column, parent=QModelIndex()): if not self.hasIndex(row, column, parent): return QModelIndex() if parent.isValid(): return self.createIndex(row, column, 1+parent.row()) else: return self.createIndex(row, column, 0) def parent(self, index): if not index.isValid() or index.internalId() == 0: return QModelIndex() return self.createIndex(index.internalId()-1, 0, 0) def rowCount(self, parent): if not parent.isValid(): return len(self.categories) if parent.internalId() == 0: category = self.categories[parent.row()] return len(self._data[category]) return 0 def columnCount(self, parent): return 1 def index_to_plugin(self, index): category = self.categories[index.parent().row()] return self._data[category][index.row()] def plugin_to_index(self, plugin): for i, category in enumerate(self.categories): parent = self.index(i, 0, QModelIndex()) for j, p in enumerate(self._data[category]): if plugin == p: return self.index(j, 0, parent) return QModelIndex() def plugin_to_index_by_properties(self, plugin): for i, category in enumerate(self.categories): parent = self.index(i, 0, QModelIndex()) for j, p in enumerate(self._data[category]): if plugin.name == p.name and plugin.type == p.type and \ plugin.author == p.author and plugin.version == p.version: return self.index(j, 0, parent) return QModelIndex() def refresh_plugin(self, plugin, rescan=False): if rescan: self.populate() idx = self.plugin_to_index(plugin) self.dataChanged.emit(idx, idx) def flags(self, index): if not index.isValid(): return Qt.ItemFlag.NoItemFlags return Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEnabled def data(self, index, role): if not index.isValid(): return None if index.internalId() == 0: if role == Qt.ItemDataRole.DisplayRole: return self.categories[index.row()] else: plugin = self.index_to_plugin(index) disabled = is_disabled(plugin) if role == Qt.ItemDataRole.DisplayRole: ver = '.'.join(map(str, plugin.version)) desc = '\n'.join(textwrap.wrap(plugin.description, 100)) ans='%s (%s) %s %s\n%s'%(plugin.name, ver, _('by'), plugin.author, desc) c = plugin_customization(plugin) if c and not disabled: ans += _('\nCustomization: ')+c if disabled: ans += _('\n\nThis plugin has been disabled') if plugin.installation_type is PluginInstallationType.SYSTEM: ans += _('\n\nThis plugin is installed system-wide and can not be managed from within calibre') return (ans) if role == Qt.ItemDataRole.DecorationRole: return self.disabled_icon if disabled else self.icon if role == Qt.ItemDataRole.ForegroundRole and disabled: return (QBrush(Qt.GlobalColor.gray)) if role == Qt.ItemDataRole.UserRole: return plugin return None # }}} class ConfigWidget(ConfigWidgetBase, Ui_Form): supports_restoring_to_defaults = False def genesis(self, gui): self.gui = gui self._plugin_model = PluginModel(self.user_installed_plugins.isChecked()) self.plugin_view.setModel(self._plugin_model) self.plugin_view.setStyleSheet( "QTreeView::item { padding-bottom: 10px;}") self.plugin_view.doubleClicked.connect(self.double_clicked) self.toggle_plugin_button.clicked.connect(self.toggle_plugin) self.customize_plugin_button.clicked.connect(self.customize_plugin) self.remove_plugin_button.clicked.connect(self.remove_plugin) self.button_plugin_add.clicked.connect(self.add_plugin) self.button_plugin_updates.clicked.connect(self.update_plugins) self.button_plugin_new.clicked.connect(self.get_plugins) self.search.initialize('plugin_search_history', help_text=_('Search for plugin')) self.search.search.connect(self.find) self.next_button.clicked.connect(self.find_next) self.previous_button.clicked.connect(self.find_previous) self.changed_signal.connect(self.reload_store_plugins) self.user_installed_plugins.stateChanged.connect(self.show_user_installed_plugins) self.plugin_view.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.plugin_view.customContextMenuRequested.connect(self.show_context_menu) def show_context_menu(self, pos): menu = QMenu(self) menu.addAction(QIcon.ic('plus.png'), _('Expand all'), self.plugin_view.expandAll) menu.addAction(QIcon.ic('minus.png'), _('Collapse all'), self.plugin_view.collapseAll) menu.exec(self.plugin_view.mapToGlobal(pos)) def show_user_installed_plugins(self, state): self._plugin_model.toggle_shown_plugins(self.user_installed_plugins.isChecked()) def find(self, query): idx = self._plugin_model.find(query) if not idx.isValid(): return info_dialog(self, _('No matches'), _('Could not find any matching plugins'), show=True, show_copy_button=False) self.highlight_index(idx) def highlight_index(self, idx): self.plugin_view.selectionModel().select(idx, QItemSelectionModel.SelectionFlag.ClearAndSelect) self.plugin_view.setCurrentIndex(idx) self.plugin_view.setFocus(Qt.FocusReason.OtherFocusReason) self.plugin_view.scrollTo(idx, QAbstractItemView.ScrollHint.EnsureVisible) def find_next(self, *args): idx = self.plugin_view.currentIndex() if not idx.isValid(): idx = self._plugin_model.index(0, 0) idx = self._plugin_model.find_next(idx, str(self.search.currentText())) self.highlight_index(idx) def find_previous(self, *args): idx = self.plugin_view.currentIndex() if not idx.isValid(): idx = self._plugin_model.index(0, 0) idx = self._plugin_model.find_next(idx, str(self.search.currentText()), backwards=True) self.highlight_index(idx) def toggle_plugin(self, *args): self.modify_plugin(op='toggle') def double_clicked(self, index): if index.parent().isValid(): self.modify_plugin(op='customize') def customize_plugin(self, *args): self.modify_plugin(op='customize') def remove_plugin(self, *args): self.modify_plugin(op='remove') def add_plugin(self): info = '' if iswindows else ' [.zip %s]'%_('files') path = choose_files(self, 'add a plugin dialog', _('Add plugin'), filters=[(_('Plugins') + info, ['zip'])], all_files=False, select_only_single_file=True) if not path: return path = path[0] if path and os.access(path, os.R_OK) and path.lower().endswith('.zip'): if not question_dialog(self, _('Are you sure?'), '<p>' + _('Installing plugins is a <b>security risk</b>. ' 'Plugins can contain a virus/malware. ' 'Only install it if you got it from a trusted source.' ' Are you sure you want to proceed?'), show_copy_button=False): return from calibre.customize.ui import config installed_plugins = frozenset(config['plugins']) try: plugin = add_plugin(path) except NameConflict as e: return error_dialog(self, _('Already exists'), str(e), show=True) self._plugin_model.beginResetModel() self._plugin_model.populate() self._plugin_model.endResetModel() self.changed_signal.emit() self.check_for_add_to_toolbars(plugin, previously_installed=plugin.name in installed_plugins) from calibre.gui2.dialogs.plugin_updater import notify_on_successful_install do_restart = notify_on_successful_install(self, plugin) idx = self._plugin_model.plugin_to_index_by_properties(plugin) if idx.isValid(): self.highlight_index(idx) if do_restart: self.restart_now.emit() else: error_dialog(self, _('No valid plugin path'), _('%s is not a valid plugin path')%path).exec() def modify_plugin(self, op=''): index = self.plugin_view.currentIndex() if index.isValid(): if not index.parent().isValid(): name = str(index.data() or '') return error_dialog(self, _('Error'), '<p>'+ _('Select an actual plugin under <b>%s</b> to customize')%name, show=True, show_copy_button=False) plugin = self._plugin_model.index_to_plugin(index) if op == 'toggle': if not plugin.can_be_disabled: info_dialog(self, _('Plugin cannot be disabled'), _('Disabling the plugin %s is not allowed')%plugin.name, show=True, show_copy_button=False) return if is_disabled(plugin): enable_plugin(plugin) else: disable_plugin(plugin) self._plugin_model.refresh_plugin(plugin) self.changed_signal.emit() if op == 'customize': if not plugin.is_customizable(): info_dialog(self, _('Plugin not customizable'), _('Plugin: %s does not need customization')%plugin.name).exec() return self.changed_signal.emit() from calibre.customize import InterfaceActionBase if isinstance(plugin, InterfaceActionBase) and not getattr(plugin, 'actual_iaction_plugin_loaded', False): return error_dialog(self, _('Must restart'), _('You must restart calibre before you can' ' configure the <b>%s</b> plugin')%plugin.name, show=True) if plugin.do_user_config(self.gui): self._plugin_model.refresh_plugin(plugin) elif op == 'remove': if not confirm('<p>' + _('Are you sure you want to remove the plugin: %s?')% f'<b>{plugin.name}</b>', 'confirm_plugin_removal_msg', parent=self): return msg = _('Plugin <b>{0}</b> successfully removed. You will have' ' to restart calibre for it to be completely removed.').format(plugin.name) if remove_plugin(plugin): self._plugin_model.beginResetModel() self._plugin_model.populate() self._plugin_model.endResetModel() self.changed_signal.emit() info_dialog(self, _('Success'), msg, show=True, show_copy_button=False) else: error_dialog(self, _('Cannot remove builtin plugin'), plugin.name + _(' cannot be removed. It is a ' 'builtin plugin. Try disabling it instead.')).exec() def get_plugins(self): self.update_plugins(not_installed=True) def update_plugins(self, not_installed=False): from calibre.gui2.dialogs.plugin_updater import FILTER_NOT_INSTALLED, FILTER_UPDATE_AVAILABLE, PluginUpdaterDialog mode = FILTER_NOT_INSTALLED if not_installed else FILTER_UPDATE_AVAILABLE d = PluginUpdaterDialog(self.gui, initial_filter=mode) d.exec() self._plugin_model.beginResetModel() self._plugin_model.populate() self._plugin_model.endResetModel() self.changed_signal.emit() if d.do_restart: self.restart_now.emit() def reload_store_plugins(self): self.gui.load_store_plugins() if 'Store' in self.gui.iactions: self.gui.iactions['Store'].load_menu() def check_for_add_to_toolbars(self, plugin, previously_installed=True): from calibre.customize import EditBookToolPlugin, InterfaceActionBase from calibre.gui2.preferences.toolbar import ConfigWidget if isinstance(plugin, EditBookToolPlugin): return self.check_for_add_to_editor_toolbar(plugin, previously_installed) if not isinstance(plugin, InterfaceActionBase): return all_locations = OrderedDict(ConfigWidget.LOCATIONS) try: plugin_action = plugin.load_actual_plugin(self.gui) except: # Broken plugin, fails to initialize. Given that, it's probably # already configured, so we can just quit. return installed_actions = OrderedDict([ (key, list(gprefs.get('action-layout-'+key, []))) for key in all_locations]) # If this is an update, do nothing if previously_installed: return # If already installed in a GUI container, do nothing for action_names in itervalues(installed_actions): if plugin_action.name in action_names: return allowed_locations = [(key, text) for key, text in iteritems(all_locations) if key not in plugin_action.dont_add_to] if not allowed_locations: return # This plugin doesn't want to live in the GUI from calibre.gui2.dialogs.choose_plugin_toolbars import ChoosePluginToolbarsDialog d = ChoosePluginToolbarsDialog(self, plugin_action, allowed_locations) if d.exec() == QDialog.DialogCode.Accepted: for key, text in d.selected_locations(): installed_actions = list(gprefs.get('action-layout-'+key, [])) installed_actions.append(plugin_action.name) gprefs['action-layout-'+key] = tuple(installed_actions) def check_for_add_to_editor_toolbar(self, plugin, previously_installed): if not previously_installed: from calibre.utils.config import JSONConfig prefs = JSONConfig('newly-installed-editor-plugins') pl = set(prefs.get('newly_installed_plugins', ())) pl.add(plugin.name) prefs['newly_installed_plugins'] = sorted(pl) if __name__ == '__main__': from calibre.gui2 import Application app = Application([]) test_widget('Advanced', 'Plugins')
19,786
Python
.py
410
36.343902
159
0.598716
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,788
template_functions.py
kovidgoyal_calibre/src/calibre/gui2/preferences/template_functions.py
#!/usr/bin/env python # License: GPLv3 Copyright: 2010, Kovid Goyal <kovid at kovidgoyal.net> import copy import json import traceback from qt.core import QDialog, QDialogButtonBox from calibre.gui2 import error_dialog, gprefs, question_dialog, warning_dialog from calibre.gui2.dialogs.template_dialog import TemplateDialog from calibre.gui2.preferences import AbortInitialize, ConfigWidgetBase, test_widget from calibre.gui2.preferences.template_functions_ui import Ui_Form from calibre.gui2.widgets import PythonHighlighter from calibre.utils.formatter_functions import ( StoredObjectType, compile_user_function, compile_user_template_functions, formatter_functions, function_object_type, function_pref_name, load_user_template_functions, ) from calibre.utils.resources import get_path as P from polyglot.builtins import iteritems class ConfigWidget(ConfigWidgetBase, Ui_Form): def genesis(self, gui): self.gui = gui self.db = gui.library_view.model().db help_text = _(''' <p>Here you can add and remove functions used in template processing. A template function is written in Python. It takes information from the book, processes it in some way, then returns a string result. Functions defined here are usable in templates in the same way that builtin functions are usable. The function must be named <b>evaluate</b>, and must have the signature shown below.</p> <p><code>evaluate(self, formatter, kwargs, mi, locals, your parameters) &rarr; returning a Unicode string</code></p> <p>The parameters of the evaluate function are: <ul> <li><b>formatter</b>: the instance of the formatter being used to evaluate the current template. You can use this to do recursive template evaluation.</li> <li><b>kwargs</b>: a dictionary of metadata. Field values are in this dictionary.</li> <li><b>mi</b>: a <i>Metadata</i> instance. Used to get field information. This parameter can be None in some cases, such as when evaluating non-book templates.</li> <li><b>locals</b>: the local variables assigned to by the current template program.</li> <li><b>your parameters</b>: you must supply one or more formal parameters. The number must match the arg count box, unless arg count is -1 (variable number or arguments), in which case the last argument must be *args. Note that when a function is called in basic template mode at least one argument is always passed. It is supplied by the formatter.</li> </ul></p> <p> The following example function checks the value of the field. If the field is not empty, the field's value is returned, otherwise the value EMPTY is returned. <pre> name: my_ifempty arg count: 1 doc: my_ifempty(val) -- return val if it is not empty, otherwise the string 'EMPTY' program code: def evaluate(self, formatter, kwargs, mi, locals, val): if val: return val else: return 'EMPTY'</pre> This function can be called in any of the three template program modes: <ul> <li>single-function mode: {tags:my_ifempty()}</li> <li>template program mode: {tags:'my_ifempty($)'}</li> <li>general program mode: program: my_ifempty(field('tags'))</li> </p> ''') self.textBrowser.setHtml(help_text) self.textBrowser.adjustSize() self.show_hide_help_button.clicked.connect(self.show_hide_help) self.textBrowser_showing = not gprefs.get('template_functions_prefs_tf_show_help', True) self.textBrowser_height = self.textBrowser.height() self.show_hide_help() help_text = _(''' <p> Here you can create, edit (replace), and delete stored templates used in template processing. You use a stored template in another template as if it were a template function, for example 'some_name(arg1, arg2...)'.</p> <p>Stored templates must use General Program Mode or Python Template Mode -- they must begin with the text '{0}' or '{1}'. You retrieve arguments passed to a GPM stored template using the '{2}()' template function, as in '{2}(var1, var2, ...)'. The passed arguments are copied to the named variables. Arguments passed to a Python template are in the '{2}' attribute (a list) of the '{3}' parameter. Arguments are always strings.</p> <p>For example, this stored GPM template checks if any items are in a list, returning '1' if any are found and '' if not.</p> <p> Template name: items_in_list<br> Template contents:<pre> program: arguments(lst='No list argument given', items=''); r = ''; for l in items: if str_in_list(lst, ',', l, '1', '') then r = '1'; break fi rof; r</pre> You call the stored template like this:<pre> program: items_in_list($#genre, 'comics, foo')</pre> See the template language tutorial for more information.</p> </p> ''') self.st_textBrowser.setHtml(help_text.format('program:', 'python:', 'arguments', 'context')) self.st_textBrowser.adjustSize() self.st_show_hide_help_button.clicked.connect(self.st_show_hide_help) self.st_textBrowser_height = self.st_textBrowser.height() self.st_textBrowser_showing = not gprefs.get('template_functions_prefs_st_show_help', True) self.st_show_hide_help() def st_show_hide_help(self): gprefs['template_functions_prefs_st_show_help'] = not self.st_textBrowser_showing if self.st_textBrowser_showing: self.st_textBrowser.setMaximumHeight(self.st_show_hide_help_button.height()) self.st_textBrowser_showing = False self.st_show_hide_help_button.setText(_('Show help')) else: self.st_textBrowser.setMaximumHeight(self.st_textBrowser_height) self.st_textBrowser_showing = True self.st_show_hide_help_button.setText(_('Hide help')) def show_hide_help(self): gprefs['template_functions_prefs_tf_show_help'] = not self.textBrowser_showing if self.textBrowser_showing: self.textBrowser.setMaximumHeight(self.show_hide_help_button.height()) self.textBrowser_showing = False self.show_hide_help_button.setText(_('Show help')) else: self.textBrowser.setMaximumHeight(self.textBrowser_height) self.textBrowser_showing = True self.show_hide_help_button.setText(_('Hide help')) def initialize(self): try: self.builtin_source_dict = json.loads(P('template-functions.json', data=True, allow_user_override=False).decode('utf-8')) except: traceback.print_exc() self.builtin_source_dict = {} self.funcs = {k:v for k,v in formatter_functions().get_functions().items() if v.object_type is StoredObjectType.PythonFunction} self.builtins = formatter_functions().get_builtins_and_aliases() self.st_funcs = {} try: for v in self.db.prefs.get('user_template_functions', []): if function_object_type(v) is not StoredObjectType.PythonFunction: self.st_funcs.update({function_pref_name(v):compile_user_function(*v)}) except: if question_dialog(self, _('Template functions'), _('The template functions saved in the library are corrupt. ' "Do you want to delete them? Answering 'Yes' will delete all " "the functions."), det_msg=traceback.format_exc(), show_copy_button=True): self.db.prefs['user_template_functions'] = [] raise AbortInitialize() self.show_only_user_defined.setChecked(True) self.show_only_user_defined.stateChanged.connect(self.show_only_user_defined_changed) self.build_function_names_box() self.function_name.currentIndexChanged.connect(self.function_index_changed) self.function_name.editTextChanged.connect(self.function_name_edited) self.argument_count.valueChanged.connect(self.enable_replace_button) self.documentation.textChanged.connect(self.enable_replace_button) self.program.textChanged.connect(self.enable_replace_button) self.create_button.clicked.connect(self.create_button_clicked) self.delete_button.clicked.connect(self.delete_button_clicked) self.create_button.setEnabled(False) self.delete_button.setEnabled(False) self.replace_button.setEnabled(False) self.clear_button.clicked.connect(self.clear_button_clicked) self.replace_button.clicked.connect(self.replace_button_clicked) self.program.setTabStopDistance(20) self.highlighter = PythonHighlighter(self.program.document()) self.te_textbox = self.template_editor.textbox self.te_name = self.template_editor.template_name self.st_build_function_names_box() self.te_name.currentIndexChanged.connect(self.st_function_index_changed) self.te_name.editTextChanged.connect(self.st_template_name_edited) self.st_create_button.clicked.connect(self.st_create_button_clicked) self.st_delete_button.clicked.connect(self.st_delete_button_clicked) self.st_create_button.setEnabled(False) self.st_delete_button.setEnabled(False) self.st_replace_button.setEnabled(False) self.st_test_template_button.setEnabled(False) self.st_clear_button.clicked.connect(self.st_clear_button_clicked) self.st_test_template_button.clicked.connect(self.st_test_template) self.st_replace_button.clicked.connect(self.st_replace_button_clicked) self.st_current_program_name = '' self.st_current_program_text = '' self.st_previous_text = '' self.st_first_time = False self.st_button_layout.insertSpacing(0, 90) self.template_editor.new_doc.setFixedHeight(50) # get field metadata and selected books view = self.gui.current_view() rows = view.selectionModel().selectedRows() self.mi = [] if rows: db = view.model().db self.fm = db.field_metadata for row in rows: if row.isValid(): self.mi.append(db.new_api.get_proxy_metadata(db.data.index_to_id(row.row()))) self.template_editor.set_mi(self.mi, self.fm) # Python function tab def show_only_user_defined_changed(self, state): self.build_function_names_box() def enable_replace_button(self): self.replace_button.setEnabled(self.delete_button.isEnabled()) def clear_button_clicked(self): self.build_function_names_box() self.program.clear() self.documentation.clear() self.argument_count.clear() self.create_button.setEnabled(False) self.delete_button.setEnabled(False) def function_type_string(self, name): if name in self.builtins: return ' -- ' + _('Built-in function') else: return ' -- ' + _('User function') def build_function_names_box(self, scroll_to=''): self.function_name.blockSignals(True) if self.show_only_user_defined.isChecked(): func_names = sorted([k for k in self.funcs if k not in self.builtins]) else: func_names = sorted(self.funcs) self.function_name.clear() self.function_name.addItem('') scroll_to_index = 0 for idx,n in enumerate(func_names): self.function_name.addItem(n + self.function_type_string(n)) self.function_name.setItemData(idx+1, n) if scroll_to and n == scroll_to: scroll_to_index = idx+1 self.function_name.setCurrentIndex(0) self.function_name.blockSignals(False) if scroll_to_index: self.function_name.setCurrentIndex(scroll_to_index) if scroll_to not in self.builtins: self.delete_button.setEnabled(True) def delete_button_clicked(self): name = str(self.function_name.itemData(self.function_name.currentIndex())) if name in self.builtins: error_dialog(self.gui, _('Template functions'), _('You cannot delete a built-in function'), show=True) if name in self.funcs: del self.funcs[name] self.changed_signal.emit() self.create_button.setEnabled(True) self.delete_button.setEnabled(False) self.build_function_names_box() self.program.setReadOnly(False) else: error_dialog(self.gui, _('Template functions'), _('Function not defined'), show=True) def check_errors_before_save(self, name, for_replace=False): # Returns True if there is an error if not name: error_dialog(self.gui, _('Template functions'), _('Name cannot be empty'), show=True) return True if not for_replace and name in self.funcs: error_dialog(self.gui, _('Template functions'), _('Name %s already used')%(name,), show=True) return True if name in {function_pref_name(v) for v in self.db.prefs.get('user_template_functions', []) if function_object_type(v) is not StoredObjectType.PythonFunction}: error_dialog(self.gui, _('Template functions'), _('The name {} is already used for stored template').format(name), show=True) return True if self.argument_count.value() == 0: if not question_dialog(self.gui, _('Template functions'), _('Setting argument count to zero means that this ' 'function cannot be used in single function mode. ' 'Is this OK?'), det_msg='', show_copy_button=False, default_yes=False, skip_dialog_name='template_functions_zero_args_warning', skip_dialog_msg='Ask this question again', yes_text=_('Save the function'), no_text=_('Cancel the save')): print('cancelled') return True try: prog = str(self.program.toPlainText()) compile_user_function(name, str(self.documentation.toPlainText()), self.argument_count.value(), prog) except: error_dialog(self.gui, _('Template functions'), _('Exception while compiling function'), show=True, det_msg=traceback.format_exc()) return True return False def create_button_clicked(self, use_name=None, need_error_checks=True): name = use_name if use_name else str(self.function_name.currentText()) name = name.split(' -- ')[0] if need_error_checks and self.check_errors_before_save(name, for_replace=False): return self.changed_signal.emit() try: prog = str(self.program.toPlainText()) cls = compile_user_function(name, str(self.documentation.toPlainText()), self.argument_count.value(), prog) self.funcs[name] = cls self.build_function_names_box(scroll_to=name) except: error_dialog(self.gui, _('Template functions'), _('Exception while compiling function'), show=True, det_msg=traceback.format_exc()) def function_name_edited(self, txt): txt = txt.split(' -- ')[0] if txt not in self.funcs: self.function_name.blockSignals(True) self.function_name.setEditText(txt) self.function_name.blockSignals(False) self.documentation.setReadOnly(False) self.argument_count.setReadOnly(False) self.create_button.setEnabled(True) self.replace_button.setEnabled(False) self.delete_button.setEnabled(False) self.program.setReadOnly(False) def function_index_changed(self, idx): txt = self.function_name.itemData(idx) self.create_button.setEnabled(False) if not txt: self.argument_count.clear() self.documentation.clear() self.documentation.setReadOnly(False) self.argument_count.setReadOnly(False) return func = self.funcs[txt] self.argument_count.setValue(func.arg_count) self.documentation.setText(func.doc) if txt in self.builtins: if hasattr(func, 'program_text') and func.program_text: self.program.setPlainText(func.program_text) elif txt in self.builtin_source_dict: self.program.setPlainText(self.builtin_source_dict[txt]) else: self.program.setPlainText(_('function source code not available')) self.documentation.setReadOnly(True) self.argument_count.setReadOnly(True) self.program.setReadOnly(True) self.delete_button.setEnabled(False) else: self.program.setPlainText(func.program_text) self.delete_button.setEnabled(True) self.program.setReadOnly(False) self.replace_button.setEnabled(False) def replace_button_clicked(self): name = str(self.function_name.itemData(self.function_name.currentIndex())) if self.check_errors_before_save(name, for_replace=True): return self.delete_button_clicked() self.create_button_clicked(use_name=name, need_error_checks=False) def refresh_gui(self, gui): pass # Stored template tab def st_test_template(self): if self.mi: self.st_replace_button_clicked() all_funcs = copy.copy(formatter_functions().get_functions()) for n,f in self.st_funcs.items(): all_funcs[n] = f t = TemplateDialog(self.gui, self.st_previous_text, mi=self.mi, fm=self.fm, text_is_placeholder=self.st_first_time, all_functions=all_funcs) t.setWindowTitle(_('Template tester')) if t.exec() == QDialog.DialogCode.Accepted: self.st_previous_text = t.rule[1] self.st_first_time = False else: error_dialog(self.gui, _('Template functions'), _('Cannot "test" when no books are selected'), show=True) def st_clear_button_clicked(self): self.st_build_function_names_box() self.te_textbox.clear() self.template_editor.new_doc.clear() self.st_create_button.setEnabled(False) self.st_delete_button.setEnabled(False) def st_build_function_names_box(self, scroll_to=''): self.te_name.blockSignals(True) func_names = sorted(self.st_funcs) self.te_name.setMinimumContentsLength(40) self.te_name.clear() self.te_name.addItem('') self.te_name.addItems(func_names) self.te_name.setCurrentIndex(0) self.te_name.blockSignals(False) if scroll_to: idx = self.te_name.findText(scroll_to) if idx >= 0: self.te_name.setCurrentIndex(idx) def st_delete_button_clicked(self): name = str(self.te_name.currentText()) if name in self.st_funcs: del self.st_funcs[name] self.changed_signal.emit() self.st_create_button.setEnabled(True) self.st_delete_button.setEnabled(False) self.st_build_function_names_box() self.te_textbox.setReadOnly(False) self.st_current_program_name = '' else: error_dialog(self.gui, _('Stored templates'), _('Function not defined'), show=True) def st_create_button_clicked(self, use_name=None): self.changed_signal.emit() name = use_name if use_name else str(self.te_name.currentText()) for k,v in formatter_functions().get_functions().items(): if k == name and v.object_type is StoredObjectType.PythonFunction: error_dialog(self.gui, _('Stored templates'), _('The name {} is already used by a template function').format(name), show=True) try: prog = str(self.te_textbox.toPlainText()) if not prog.startswith(('program:', 'python:')): error_dialog(self.gui, _('Stored templates'), _("The stored template must begin with '{0}' or '{1}'").format('program:', 'python:'), show=True) cls = compile_user_function(name, str(self.template_editor.new_doc.toPlainText()), 0, prog) self.st_funcs[name] = cls self.st_build_function_names_box(scroll_to=name) except: error_dialog(self.gui, _('Stored templates'), _('Exception while storing template'), show=True, det_msg=traceback.format_exc()) def st_template_name_edited(self, txt): b = txt in self.st_funcs self.st_create_button.setEnabled(not b) self.st_replace_button.setEnabled(b) self.st_delete_button.setEnabled(b) self.st_test_template_button.setEnabled(b) self.te_textbox.setReadOnly(False) def st_function_index_changed(self, idx): txt = self.te_name.currentText() if self.st_current_program_name: if self.st_current_program_text != self.te_textbox.toPlainText(): box = warning_dialog(self.gui, _('Template functions'), _('Changes to the current template will be lost. OK?'), det_msg='', show=False, show_copy_button=False) box.bb.setStandardButtons(box.bb.standardButtons() | QDialogButtonBox.StandardButton.Cancel) box.det_msg_toggle.setVisible(False) if not box.exec(): self.te_name.blockSignals(True) dex = self.te_name.findText(self.st_current_program_name) self.te_name.setCurrentIndex(dex) self.te_name.blockSignals(False) return self.st_create_button.setEnabled(False) self.st_current_program_name = txt if not txt: self.te_textbox.clear() self.template_editor.new_doc.clear() return func = self.st_funcs[txt] self.st_current_program_text = func.program_text self.template_editor.new_doc.setPlainText(func.doc) self.te_textbox.setPlainText(func.program_text) self.st_template_name_edited(txt) def st_replace_button_clicked(self): name = str(self.te_name.currentText()) self.st_current_program_text = self.te_textbox.toPlainText() self.st_delete_button_clicked() self.st_create_button_clicked(use_name=name) def commit(self): pref_value = [] for name, cls in iteritems(self.funcs): if name not in self.builtins: pref_value.append(cls.to_pref()) for v in self.st_funcs.values(): pref_value.append(v.to_pref()) self.db.new_api.set_pref('user_template_functions', pref_value) funcs = compile_user_template_functions(pref_value) self.db.new_api.set_user_template_functions(funcs) self.gui.library_view.model().refresh() self.gui.library_view.model().research() load_user_template_functions(self.db.library_id, [], funcs) return False if __name__ == '__main__': from calibre.gui2 import Application from calibre.gui2.ui import get_gui from calibre.library import db app = Application([]) app.current_db = db() get_gui.ans = app test_widget('Advanced', 'TemplateFunctions') del app
24,722
Python
.py
497
38.251509
118
0.619184
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,789
look_feel.py
kovidgoyal_calibre/src/calibre/gui2/preferences/look_feel.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import json from collections import defaultdict from functools import partial from threading import Thread from qt.core import ( QAbstractListModel, QApplication, QBrush, QColor, QColorDialog, QComboBox, QDialog, QDialogButtonBox, QFont, QFontDialog, QFontInfo, QFormLayout, QHeaderView, QIcon, QItemSelectionModel, QKeySequence, QLabel, QLineEdit, QListWidgetItem, QPainter, QPixmap, QPushButton, QSize, QSizePolicy, Qt, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, pyqtSignal, ) from calibre import human_readable from calibre.constants import ismacos, iswindows from calibre.db.categories import is_standard_category from calibre.ebooks.metadata.book.render import DEFAULT_AUTHOR_LINK from calibre.ebooks.metadata.sources.prefs import msprefs from calibre.gui2 import ( choose_files, choose_save_file, config, default_author_link, error_dialog, gprefs, icon_resource_manager, open_local_file, qt_app, question_dialog, ) from calibre.gui2.actions.show_quickview import get_quickview_action_plugin from calibre.gui2.book_details import get_field_list from calibre.gui2.custom_column_widgets import get_field_list as em_get_field_list from calibre.gui2.dialogs.quickview import get_qv_field_list from calibre.gui2.dialogs.template_dialog import TemplateDialog from calibre.gui2.library.alternate_views import CM_TO_INCH, auto_height from calibre.gui2.preferences import ConfigWidgetBase, Setting, set_help_tips, test_widget from calibre.gui2.preferences.coloring import EditRules from calibre.gui2.preferences.look_feel_ui import Ui_Form from calibre.gui2.widgets import BusyCursor from calibre.gui2.widgets2 import Dialog from calibre.startup import connect_lambda from calibre.utils.config import prefs from calibre.utils.icu import sort_key from calibre.utils.localization import available_translations, get_lang, get_language from calibre.utils.resources import get_path as P from calibre.utils.resources import set_data from polyglot.builtins import iteritems class DefaultAuthorLink(QWidget): # {{{ changed_signal = pyqtSignal() def __init__(self, parent): QWidget.__init__(self, parent) l = QVBoxLayout(parent) l.addWidget(self) l.setContentsMargins(0, 0, 0, 0) l = QFormLayout(self) l.setContentsMargins(0, 0, 0, 0) l.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow) self.choices = c = QComboBox() c.setMinimumContentsLength(30) for text, data in [ (_('Search for the author on Goodreads'), 'search-goodreads'), (_('Search for the author on Amazon'), 'search-amzn'), (_('Search for the author in your calibre library'), 'search-calibre'), (_('Search for the author on Wikipedia'), 'search-wikipedia'), (_('Search for the author on Google Books'), 'search-google'), (_('Search for the book on Goodreads'), 'search-goodreads-book'), (_('Search for the book on Amazon'), 'search-amzn-book'), (_('Search for the book on Google Books'), 'search-google-book'), (_('Use a custom search URL'), 'url'), ]: c.addItem(text, data) l.addRow(_('Clicking on &author names should:'), c) self.custom_url = u = QLineEdit(self) u.setToolTip(_( 'Enter the URL to search. It should contain the string {0}' '\nwhich will be replaced by the author name. For example,' '\n{1}').format('{author}', 'https://en.wikipedia.org/w/index.php?search={author}')) u.textChanged.connect(self.changed_signal) u.setPlaceholderText(_('Enter the URL')) c.currentIndexChanged.connect(self.current_changed) l.addRow(u) self.current_changed() c.currentIndexChanged.connect(self.changed_signal) @property def value(self): k = self.choices.currentData() if k == 'url': return self.custom_url.text() return k if k != DEFAULT_AUTHOR_LINK else None @value.setter def value(self, val): i = self.choices.findData(val) if i < 0: i = self.choices.findData('url') self.custom_url.setText(val) self.choices.setCurrentIndex(i) def current_changed(self): k = self.choices.currentData() self.custom_url.setVisible(k == 'url') # }}} # IdLinksEditor {{{ class IdLinksRuleEdit(Dialog): def __init__(self, key='', name='', template='', parent=None): title = _('Edit rule') if key else _('Create a new rule') Dialog.__init__(self, title=title, name='id-links-rule-editor', parent=parent) self.key.setText(key), self.nw.setText(name), self.template.setText(template or 'https://example.com/{id}') if self.size().height() < self.sizeHint().height(): self.resize(self.sizeHint()) @property def rule(self): return self.key.text().lower(), self.nw.text(), self.template.text() def setup_ui(self): self.l = l = QFormLayout(self) l.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow) l.addRow(QLabel(_( 'The key of the identifier, for example, in isbn:XXX, the key is "isbn"'))) self.key = k = QLineEdit(self) l.addRow(_('&Key:'), k) l.addRow(QLabel(_( 'The name that will appear in the Book details panel'))) self.nw = n = QLineEdit(self) l.addRow(_('&Name:'), n) la = QLabel(_( 'The template used to create the link.' ' The placeholder {0} in the template will be replaced' ' with the actual identifier value. Use {1} to avoid the value' ' being quoted.').format('{id}', '{id_unquoted}')) la.setWordWrap(True) l.addRow(la) self.template = t = QLineEdit(self) l.addRow(_('&Template:'), t) t.selectAll() t.setFocus(Qt.FocusReason.OtherFocusReason) l.addWidget(self.bb) def accept(self): r = self.rule for i, which in enumerate([_('Key'), _('Name'), _('Template')]): if not r[i]: return error_dialog(self, _('Value needed'), _( 'The %s field cannot be empty') % which, show=True) Dialog.accept(self) class IdLinksEditor(Dialog): def __init__(self, parent=None): Dialog.__init__(self, title=_('Create rules for identifiers'), name='id-links-rules-editor', parent=parent) def setup_ui(self): self.l = l = QVBoxLayout(self) self.la = la = QLabel(_( 'Create rules to convert identifiers into links.')) la.setWordWrap(True) l.addWidget(la) items = [] for k, lx in iteritems(msprefs['id_link_rules']): for n, t in lx: items.append((k, n, t)) items.sort(key=lambda x:sort_key(x[1])) self.table = t = QTableWidget(len(items), 3, self) t.setHorizontalHeaderLabels([_('Key'), _('Name'), _('Template')]) for r, (key, val, template) in enumerate(items): t.setItem(r, 0, QTableWidgetItem(key)) t.setItem(r, 1, QTableWidgetItem(val)) t.setItem(r, 2, QTableWidgetItem(template)) l.addWidget(t) t.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.Stretch) self.cb = b = QPushButton(QIcon.ic('plus.png'), _('&Add rule'), self) connect_lambda(b.clicked, self, lambda self: self.edit_rule()) self.bb.addButton(b, QDialogButtonBox.ButtonRole.ActionRole) self.rb = b = QPushButton(QIcon.ic('minus.png'), _('&Remove rule'), self) connect_lambda(b.clicked, self, lambda self: self.remove_rule()) self.bb.addButton(b, QDialogButtonBox.ButtonRole.ActionRole) self.eb = b = QPushButton(QIcon.ic('modified.png'), _('&Edit rule'), self) connect_lambda(b.clicked, self, lambda self: self.edit_rule(self.table.currentRow())) self.bb.addButton(b, QDialogButtonBox.ButtonRole.ActionRole) l.addWidget(self.bb) def sizeHint(self): return QSize(700, 550) def accept(self): rules = defaultdict(list) for r in range(self.table.rowCount()): def item(c): return self.table.item(r, c).text() rules[item(0)].append([item(1), item(2)]) msprefs['id_link_rules'] = dict(rules) Dialog.accept(self) def edit_rule(self, r=-1): key = name = template = '' if r > -1: key, name, template = map(lambda c: self.table.item(r, c).text(), range(3)) d = IdLinksRuleEdit(key, name, template, self) if d.exec() == QDialog.DialogCode.Accepted: if r < 0: self.table.setRowCount(self.table.rowCount() + 1) r = self.table.rowCount() - 1 rule = d.rule for c in range(3): self.table.setItem(r, c, QTableWidgetItem(rule[c])) self.table.scrollToItem(self.table.item(r, 0)) def remove_rule(self): r = self.table.currentRow() if r > -1: self.table.removeRow(r) # }}} class DisplayedFields(QAbstractListModel): # {{{ def __init__(self, db, parent=None, pref_name=None, category_icons=None): self.pref_name = pref_name or 'book_display_fields' QAbstractListModel.__init__(self, parent) self.fields = [] self.db = db self.changed = False self.category_icons = category_icons def get_field_list(self, use_defaults=False): return get_field_list(self.db.field_metadata, use_defaults=use_defaults, pref_name=self.pref_name) def initialize(self, use_defaults=False): self.beginResetModel() self.fields = [[x[0], x[1]] for x in self.get_field_list(use_defaults=use_defaults)] self.endResetModel() self.changed = True def rowCount(self, *args): return len(self.fields) def data(self, index, role): try: field, visible = self.fields[index.row()] except: return None if role == Qt.ItemDataRole.DisplayRole: name = field try: name = self.db.field_metadata[field]['name'] except: pass if field == 'path': name = _('Folders/path') if not name: return field return f'{name} ({field})' if role == Qt.ItemDataRole.CheckStateRole: return Qt.CheckState.Checked if visible else Qt.CheckState.Unchecked if role == Qt.ItemDataRole.DecorationRole: if self.category_icons: icon = self.category_icons.get(field, None) if icon is not None: return icon if field.startswith('#'): return QIcon.ic('column.png') return None def toggle_all(self, show=True): for i in range(self.rowCount()): idx = self.index(i) if idx.isValid(): self.setData(idx, Qt.CheckState.Checked if show else Qt.CheckState.Unchecked, Qt.ItemDataRole.CheckStateRole) def flags(self, index): ans = QAbstractListModel.flags(self, index) return ans | Qt.ItemFlag.ItemIsUserCheckable def setData(self, index, val, role): ret = False if role == Qt.ItemDataRole.CheckStateRole: self.fields[index.row()][1] = val in (Qt.CheckState.Checked, Qt.CheckState.Checked.value) self.changed = True ret = True self.dataChanged.emit(index, index) return ret def restore_defaults(self): self.initialize(use_defaults=True) def commit(self): if self.changed: self.db.new_api.set_pref(self.pref_name, self.fields) def move(self, idx, delta): row = idx.row() + delta if row >= 0 and row < len(self.fields): t = self.fields[row] self.fields[row] = self.fields[row-delta] self.fields[row-delta] = t self.dataChanged.emit(idx, idx) idx = self.index(row) self.dataChanged.emit(idx, idx) self.changed = True return idx def move_field_up(widget, model): idx = widget.currentIndex() if idx.isValid(): idx = model.move(idx, -1) if idx is not None: sm = widget.selectionModel() sm.select(idx, QItemSelectionModel.SelectionFlag.ClearAndSelect) widget.setCurrentIndex(idx) def move_field_down(widget, model): idx = widget.currentIndex() if idx.isValid(): idx = model.move(idx, 1) if idx is not None: sm = widget.selectionModel() sm.select(idx, QItemSelectionModel.SelectionFlag.ClearAndSelect) widget.setCurrentIndex(idx) # }}} class EMDisplayedFields(DisplayedFields): # {{{ def __init__(self, db, parent=None): DisplayedFields.__init__(self, db, parent) def initialize(self, use_defaults=False, pref_data_override=None): self.beginResetModel() self.fields = [[x[0], x[1]] for x in em_get_field_list(self.db, use_defaults=use_defaults, pref_data_override=pref_data_override)] self.endResetModel() self.changed = True def commit(self): if self.changed: self.db.new_api.set_pref('edit_metadata_custom_columns_to_display', self.fields) # }}} class QVDisplayedFields(DisplayedFields): # {{{ def __init__(self, db, parent=None): DisplayedFields.__init__(self, db, parent) def initialize(self, use_defaults=False): self.beginResetModel() self.fields = [[x[0], x[1]] for x in get_qv_field_list(self.db.field_metadata, use_defaults=use_defaults)] self.endResetModel() self.changed = True def commit(self): if self.changed: self.db.new_api.set_pref('qv_display_fields', self.fields) # }}} class TBDisplayedFields(DisplayedFields): # {{{ # The code in this class depends on the fact that the tag browser is # initialized before this class is instantiated. def __init__(self, db, parent=None, category_icons=None): DisplayedFields.__init__(self, db, parent, category_icons=category_icons) from calibre.gui2.ui import get_gui self.gui = get_gui() def initialize(self, use_defaults=False, pref_data_override=None): tv = self.gui.tags_view cat_ord = tv.model().get_ordered_categories(use_defaults=use_defaults, pref_data_override=pref_data_override) if use_defaults: hc = [] self.changed = True elif pref_data_override: hc = [k for k,v in pref_data_override if not v] self.changed = True else: hc = tv.hidden_categories self.beginResetModel() self.fields = [[x, x not in hc] for x in cat_ord] self.endResetModel() def commit(self): if self.changed: self.db.prefs.set('tag_browser_hidden_categories', [k for k,v in self.fields if not v]) self.db.prefs.set('tag_browser_category_order', [k for k,v in self.fields]) # }}} class TBPartitionedFields(DisplayedFields): # {{{ # The code in this class depends on the fact that the tag browser is # initialized before this class is instantiated. def __init__(self, db, parent=None, category_icons=None): DisplayedFields.__init__(self, db, parent, category_icons=category_icons) from calibre.gui2.ui import get_gui self.gui = get_gui() def initialize(self, use_defaults=False, pref_data_override=None): tv = self.gui.tags_view cats = tv.model().categories ans = [] if use_defaults: ans = [[k, True] for k in cats.keys()] self.changed = True elif pref_data_override: po = {k:v for k,v in pref_data_override} ans = [[k, po.get(k, True)] for k in cats.keys()] self.changed = True else: # Check if setting not migrated yet cats_to_partition = frozenset(self.db.prefs.get('tag_browser_dont_collapse', gprefs.get('tag_browser_dont_collapse')) or ()) for key in cats: ans.append([key, key not in cats_to_partition]) self.beginResetModel() self.fields = ans self.endResetModel() def commit(self): if self.changed: # Migrate to a per-library setting self.db.prefs.set('tag_browser_dont_collapse', [k for k,v in self.fields if not v]) # }}} class TBHierarchicalFields(DisplayedFields): # {{{ # The code in this class depends on the fact that the tag browser is # initialized before this class is instantiated. cant_make_hierarical = {'authors', 'publisher', 'formats', 'news', 'identifiers', 'languages', 'rating'} def __init__(self, db, parent=None, category_icons=None): DisplayedFields.__init__(self, db, parent, category_icons=category_icons) from calibre.gui2.ui import get_gui self.gui = get_gui() def initialize(self, use_defaults=False, pref_data_override=None): tv = self.gui.tags_view cats = [k for k in tv.model().categories.keys() if k not in self.cant_make_hierarical] ans = [] if use_defaults: ans = [[k, False] for k in cats] self.changed = True elif pref_data_override: ph = {k:v for k,v in pref_data_override} ans = [[k, ph.get(k, False)] for k in cats] self.changed = True else: hier_cats = self.db.prefs.get('categories_using_hierarchy') or () for key in cats: ans.append([key, key in hier_cats]) self.beginResetModel() self.fields = ans self.endResetModel() def commit(self): if self.changed: self.db.prefs.set('categories_using_hierarchy', [k for k,v in self.fields if v]) # }}} class BDVerticalCats(DisplayedFields): # {{{ def __init__(self, db, parent=None, category_icons=None): DisplayedFields.__init__(self, db, parent, category_icons=category_icons) from calibre.gui2.ui import get_gui self.gui = get_gui() def initialize(self, use_defaults=False, pref_data_override=None): fm = self.db.field_metadata cats = [k for k in fm if fm[k]['name'] and fm[k]['is_multiple'] and not k.startswith('#')] cats.append('path') cats.extend([k for k in fm if fm[k]['name'] and fm[k]['is_multiple'] and k.startswith('#')]) ans = [] if use_defaults: ans = [[k, False] for k in cats] self.changed = True elif pref_data_override: ph = {k:v for k,v in pref_data_override} ans = [[k, ph.get(k, False)] for k in cats] self.changed = True else: vertical_cats = self.db.prefs.get('book_details_vertical_categories') or () for key in cats: ans.append([key, key in vertical_cats]) self.beginResetModel() self.fields = ans self.endResetModel() def commit(self): if self.changed: self.db.prefs.set('book_details_vertical_categories', [k for k,v in self.fields if v]) # }}} class Background(QWidget): # {{{ def __init__(self, parent): QWidget.__init__(self, parent) self.bcol = QColor(*gprefs['cover_grid_color']) self.btex = gprefs['cover_grid_texture'] self.update_brush() self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) def update_brush(self): self.brush = QBrush(self.bcol) if self.btex: from calibre.gui2.preferences.texture_chooser import texture_path path = texture_path(self.btex) if path: p = QPixmap(path) try: dpr = self.devicePixelRatioF() except AttributeError: dpr = self.devicePixelRatio() p.setDevicePixelRatio(dpr) self.brush.setTexture(p) self.update() def sizeHint(self): return QSize(200, 120) def paintEvent(self, ev): painter = QPainter(self) painter.fillRect(ev.rect(), self.brush) painter.end() # }}} class LanguageSetting(Setting): def commit(self): val = self.get_gui_val() oldval = self.get_config_val() if val != oldval: gprefs.set('last_used_language', oldval) return super().commit() class ConfigWidget(ConfigWidgetBase, Ui_Form): size_calculated = pyqtSignal(object) def genesis(self, gui): self.gui = gui self.ui_style_available = True if not ismacos and not iswindows: self.label_widget_style.setVisible(False) self.opt_ui_style.setVisible(False) self.ui_style_available = False db = gui.library_view.model().db r = self.register try: self.icon_theme_title = icon_resource_manager.user_theme_title except Exception: self.icon_theme_title = _('Default icons') self.icon_theme.setText(_('Icon theme: <b>%s</b>') % self.icon_theme_title) self.commit_icon_theme = None self.icon_theme_button.clicked.connect(self.choose_icon_theme) self.default_author_link = DefaultAuthorLink(self.default_author_link_container) self.default_author_link.changed_signal.connect(self.changed_signal) r('ui_style', gprefs, restart_required=True, choices=[(_('System default'), 'system'), (_('calibre style'), 'calibre')]) r('book_list_tooltips', gprefs) r('dnd_merge', gprefs) r('wrap_toolbar_text', gprefs, restart_required=True) r('show_layout_buttons', gprefs) r('row_numbers_in_book_list', gprefs) r('tag_browser_old_look', gprefs) r('tag_browser_hide_empty_categories', gprefs) r('tag_browser_always_autocollapse', gprefs) r('tag_browser_show_tooltips', gprefs) r('tag_browser_allow_keyboard_focus', gprefs) r('bd_show_cover', gprefs) r('bd_overlay_cover_size', gprefs) r('cover_corner_radius', gprefs) r('cover_corner_radius_unit', gprefs, choices=[(_('Pixels'), 'px'), (_('Percentage'), '%')]) r('cover_grid_width', gprefs) r('cover_grid_height', gprefs) r('cover_grid_cache_size_multiple', gprefs) r('cover_grid_disk_cache_size', gprefs) r('cover_grid_spacing', gprefs) r('cover_grid_show_title', gprefs) r('tag_browser_show_counts', gprefs) r('tag_browser_item_padding', gprefs) r('books_autoscroll_time', gprefs) r('qv_respects_vls', gprefs) r('qv_dclick_changes_column', gprefs) r('qv_retkey_changes_column', gprefs) r('qv_follows_column', gprefs) r('cover_flow_queue_length', config, restart_required=True) r('cover_browser_reflections', gprefs) r('cover_browser_narrow_view_position', gprefs, choices=[(_('Automatic'), 'automatic'), # Automatic must be first (_('On top'), 'on_top'), (_('On right'), 'on_right')]) r('cover_browser_title_template', db.prefs) fm = db.field_metadata r('cover_browser_subtitle_field', db.prefs, choices=[(_('No subtitle'), 'none')] + sorted( (fm[k].get('name'), k) for k in fm.all_field_keys() if fm[k].get('name') )) r('emblem_size', gprefs) r('emblem_position', gprefs, choices=[ (_('Left'), 'left'), (_('Top'), 'top'), (_('Right'), 'right'), (_('Bottom'), 'bottom')]) r('book_list_extra_row_spacing', gprefs) r('booklist_grid', gprefs) r('book_details_comments_heading_pos', gprefs, choices=[ (_('Never'), 'hide'), (_('Above text'), 'above'), (_('Beside text'), 'side')]) self.cover_browser_title_template_button.clicked.connect(self.edit_cb_title_template) self.id_links_button.clicked.connect(self.edit_id_link_rules) def get_esc_lang(l): if l == 'en': return 'English' return get_language(l) lang = get_lang() if lang is None or lang not in available_translations(): lang = 'en' items = [(l, get_esc_lang(l)) for l in available_translations() if l != lang] if lang != 'en': items.append(('en', get_esc_lang('en'))) items.sort(key=lambda x: x[1].lower()) choices = [(y, x) for x, y in items] # Default language is the autodetected one choices = [(get_language(lang), lang)] + choices lul = gprefs.get('last_used_language') if lul and (lul in available_translations() or lul in ('en', 'eng')): choices.insert(1, ((get_language(lul), lul))) r('language', prefs, choices=choices, restart_required=True, setting=LanguageSetting) r('show_avg_rating', config) r('show_links_in_tag_browser', gprefs) r('show_notes_in_tag_browser', gprefs) r('icons_on_right_in_tag_browser', gprefs) r('disable_animations', config) r('systray_icon', config, restart_required=True) r('show_splash_screen', gprefs) r('disable_tray_notification', config) r('use_roman_numerals_for_series_number', config) r('separate_cover_flow', config, restart_required=True) r('cb_fullscreen', gprefs) r('cb_preserve_aspect_ratio', gprefs) r('cb_double_click_to_activate', gprefs) choices = [(_('Off'), 'off'), (_('Small'), 'small'), (_('Medium'), 'medium'), (_('Large'), 'large')] r('toolbar_icon_size', gprefs, choices=choices) choices = [(_('If there is enough room'), 'auto'), (_('Always'), 'always'), (_('Never'), 'never')] r('toolbar_text', gprefs, choices=choices) choices = [(_('Disabled'), 'disable'), (_('By first letter'), 'first letter'), (_('Partitioned'), 'partition')] r('tags_browser_partition_method', gprefs, choices=choices) r('tags_browser_collapse_at', gprefs) r('tags_browser_collapse_fl_at', gprefs) fm = db.field_metadata choices = sorted(((fm[k]['name'], k) for k in fm.displayable_field_keys() if fm[k]['name']), key=lambda x:sort_key(x[0])) r('field_under_covers_in_grid', db.prefs, choices=choices) choices = [(_('Default'), 'default'), (_('Compact metadata'), 'alt1'), (_('All on 1 tab'), 'alt2')] r('edit_metadata_single_layout', gprefs, choices=[(_('Default'), 'default'), (_('Compact metadata'), 'alt1'), (_('All on 1 tab'), 'alt2')]) r('edit_metadata_ignore_display_order', db.prefs) r('edit_metadata_elision_point', gprefs, choices=[(_('Left'), 'left'), (_('Middle'), 'middle'), (_('Right'), 'right')]) r('edit_metadata_elide_labels', gprefs) r('edit_metadata_single_use_2_cols_for_custom_fields', gprefs) r('edit_metadata_bulk_cc_label_length', gprefs) r('edit_metadata_single_cc_label_length', gprefs) r('edit_metadata_templates_only_F2_on_booklist', gprefs) self.current_font = self.initial_font = None self.change_font_button.clicked.connect(self.change_font) self.display_model = DisplayedFields(self.gui.current_db, self.field_display_order) self.display_model.dataChanged.connect(self.changed_signal) self.field_display_order.setModel(self.display_model) mu = partial(move_field_up, self.field_display_order, self.display_model) md = partial(move_field_down, self.field_display_order, self.display_model) self.df_up_button.clicked.connect(mu) self.df_down_button.clicked.connect(md) self.field_display_order.set_movement_functions(mu, md) self.em_display_model = EMDisplayedFields(self.gui.current_db, self.em_display_order) self.em_display_model.dataChanged.connect(self.changed_signal) self.em_display_order.setModel(self.em_display_model) mu = partial(move_field_up, self.em_display_order, self.em_display_model) md = partial(move_field_down, self.em_display_order, self.em_display_model) self.em_display_order.set_movement_functions(mu, md) self.em_up_button.clicked.connect(mu) self.em_down_button.clicked.connect(md) self.em_export_layout_button.clicked.connect(partial(self.export_layout, model=self.em_display_model)) self.em_import_layout_button.clicked.connect(partial(self.import_layout, model=self.em_display_model)) self.em_reset_layout_button.clicked.connect(partial(self.reset_layout, model=self.em_display_model)) self.qv_display_model = QVDisplayedFields(self.gui.current_db, self.qv_display_order) self.qv_display_model.dataChanged.connect(self.changed_signal) self.qv_display_order.setModel(self.qv_display_model) mu = partial(move_field_up, self.qv_display_order, self.qv_display_model) md = partial(move_field_down, self.qv_display_order, self.qv_display_model) self.qv_display_order.set_movement_functions(mu, md) self.qv_up_button.clicked.connect(mu) self.qv_down_button.clicked.connect(md) self.tb_display_model = TBDisplayedFields(self.gui.current_db, self.tb_display_order, category_icons=self.gui.tags_view.model().category_custom_icons) self.tb_display_model.dataChanged.connect(self.changed_signal) self.tb_display_order.setModel(self.tb_display_model) self.tb_reset_layout_button.clicked.connect(partial(self.reset_layout, model=self.tb_display_model)) self.tb_export_layout_button.clicked.connect(partial(self.export_layout, model=self.tb_display_model)) self.tb_import_layout_button.clicked.connect(partial(self.import_layout, model=self.tb_display_model)) self.tb_up_button.clicked.connect(self.tb_up_button_clicked) self.tb_down_button.clicked.connect(self.tb_down_button_clicked) self.tb_display_order.set_movement_functions(self.tb_up_button_clicked, self.tb_down_button_clicked) self.tb_categories_to_part_model = TBPartitionedFields(self.gui.current_db, self.tb_cats_to_partition, category_icons=self.gui.tags_view.model().category_custom_icons) self.tb_categories_to_part_model.dataChanged.connect(self.changed_signal) self.tb_cats_to_partition.setModel(self.tb_categories_to_part_model) self.tb_partition_reset_button.clicked.connect(partial(self.reset_layout, model=self.tb_categories_to_part_model)) self.tb_partition_export_layout_button.clicked.connect(partial(self.export_layout, model=self.tb_categories_to_part_model)) self.tb_partition_import_layout_button.clicked.connect(partial(self.import_layout, model=self.tb_categories_to_part_model)) self.tb_hierarchical_cats_model = TBHierarchicalFields(self.gui.current_db, self.tb_hierarchical_cats, category_icons=self.gui.tags_view.model().category_custom_icons) self.tb_hierarchical_cats_model.dataChanged.connect(self.changed_signal) self.tb_hierarchical_cats.setModel(self.tb_hierarchical_cats_model) self.tb_hierarchy_reset_layout_button.clicked.connect(partial(self.reset_layout, model=self.tb_hierarchical_cats_model)) self.tb_hierarchy_export_layout_button.clicked.connect(partial(self.export_layout, model=self.tb_hierarchical_cats_model)) self.tb_hierarchy_import_layout_button.clicked.connect(partial(self.import_layout, model=self.tb_hierarchical_cats_model)) self.bd_vertical_cats_model = BDVerticalCats(self.gui.current_db, self.tb_hierarchical_cats) self.bd_vertical_cats_model.dataChanged.connect(self.changed_signal) self.bd_vertical_cats.setModel(self.bd_vertical_cats_model) self.fill_tb_search_order_box() self.tb_search_order_up_button.clicked.connect(self.move_tb_search_up) self.tb_search_order_down_button.clicked.connect(self.move_tb_search_down) self.tb_search_order.set_movement_functions(self.move_tb_search_up, self.move_tb_search_down) self.tb_search_order_reset_button.clicked.connect(self.reset_tb_search_order) self.edit_rules = EditRules(self.tabWidget) self.edit_rules.changed.connect(self.changed_signal) self.tabWidget.addTab(self.edit_rules, QIcon.ic('format-fill-color.png'), _('Column &coloring')) self.icon_rules = EditRules(self.tabWidget) self.icon_rules.changed.connect(self.changed_signal) self.tabWidget.addTab(self.icon_rules, QIcon.ic('icon_choose.png'), _('Column &icons')) self.grid_rules = EditRules(self.emblems_tab) self.grid_rules.changed.connect(self.changed_signal) self.emblems_tab.setLayout(QVBoxLayout()) self.emblems_tab.layout().addWidget(self.grid_rules) self.tabWidget.setCurrentIndex(0) self.tabWidget.tabBar().setVisible(False) keys = [QKeySequence('F11', QKeySequence.SequenceFormat.PortableText), QKeySequence( 'Ctrl+Shift+F', QKeySequence.SequenceFormat.PortableText)] keys = [str(x.toString(QKeySequence.SequenceFormat.NativeText)) for x in keys] self.fs_help_msg.setText(self.fs_help_msg.text()%( QKeySequence(QKeySequence.StandardKey.FullScreen).toString(QKeySequence.SequenceFormat.NativeText))) self.size_calculated.connect(self.update_cg_cache_size, type=Qt.ConnectionType.QueuedConnection) self.tabWidget.currentChanged.connect(self.tab_changed) l = self.cg_background_box.layout() self.cg_bg_widget = w = Background(self) l.addWidget(w, 0, 0, 3, 1) self.cover_grid_color_button = b = QPushButton(_('Change &color'), self) b.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) l.addWidget(b, 0, 1) b.clicked.connect(self.change_cover_grid_color) self.cover_grid_texture_button = b = QPushButton(_('Change &background image'), self) b.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) l.addWidget(b, 1, 1) b.clicked.connect(self.change_cover_grid_texture) self.cover_grid_default_appearance_button = b = QPushButton(_('Restore default &appearance'), self) b.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) l.addWidget(b, 2, 1) b.clicked.connect(self.restore_cover_grid_appearance) self.cover_grid_empty_cache.clicked.connect(self.empty_cache) self.cover_grid_open_cache.clicked.connect(self.open_cg_cache) connect_lambda(self.cover_grid_smaller_cover.clicked, self, lambda self: self.resize_cover(True)) connect_lambda(self.cover_grid_larger_cover.clicked, self, lambda self: self.resize_cover(False)) self.cover_grid_reset_size.clicked.connect(self.cg_reset_size) self.opt_cover_grid_disk_cache_size.setMinimum(self.gui.grid_view.thumbnail_cache.min_disk_cache) self.opt_cover_grid_disk_cache_size.setMaximum(self.gui.grid_view.thumbnail_cache.min_disk_cache * 100) self.opt_cover_grid_width.valueChanged.connect(self.update_aspect_ratio) self.opt_cover_grid_height.valueChanged.connect(self.update_aspect_ratio) self.opt_book_details_css.textChanged.connect(self.changed_signal) from calibre.gui2.tweak_book.editor.text import get_highlighter, get_theme self.css_highlighter = get_highlighter('css')() self.css_highlighter.apply_theme(get_theme(None)) self.css_highlighter.set_document(self.opt_book_details_css.document()) for i in range(self.tabWidget.count()): self.sections_view.addItem(QListWidgetItem(self.tabWidget.tabIcon(i), self.tabWidget.tabText(i).replace('&', ''))) self.sections_view.setCurrentRow(self.tabWidget.currentIndex()) self.sections_view.currentRowChanged.connect(self.tabWidget.setCurrentIndex) self.sections_view.setMaximumWidth(self.sections_view.sizeHintForColumn(0) + 16) self.sections_view.setSpacing(4) self.sections_view.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) self.tabWidget.currentWidget().setFocus(Qt.FocusReason.OtherFocusReason) self.opt_ui_style.currentIndexChanged.connect(self.update_color_palette_state) self.opt_gui_layout.addItem(_('Wide'), 'wide') self.opt_gui_layout.addItem(_('Narrow'), 'narrow') self.opt_gui_layout.currentIndexChanged.connect(self.changed_signal) set_help_tips(self.opt_gui_layout, config.help('gui_layout')) self.button_adjust_colors.clicked.connect(self.adjust_colors) def adjust_colors(self): from calibre.gui2.dialogs.palette import PaletteConfig d = PaletteConfig(self) if d.exec() == QDialog.DialogCode.Accepted: d.apply_settings() self.changed_signal.emit() def initial_tab_changed(self): self.sections_view.setCurrentRow(self.tabWidget.currentIndex()) def fill_tb_search_order_box(self): # The tb_search_order is a directed graph of nodes with an arc to the next # node in the sequence. Node 0 (zero) is the start node with the last node # arcing back to node 0. This code linearizes the graph choices = [(1, _('Search for books containing the current item')), (2, _('Search for books containing the current item or its children')), (3, _('Search for books not containing the current item')), (4, _('Search for books not containing the current item or its children'))] icon_map = self.gui.tags_view.model().icon_state_map order = gprefs.get('tb_search_order') self.tb_search_order.clear() node = 0 while True: v = order[str(node)] if v == 0: break item = QListWidgetItem(icon_map[v], choices[v-1][1]) item.setData(Qt.ItemDataRole.UserRole, choices[v-1][0]) self.tb_search_order.addItem(item) node = v def move_tb_search_up(self): idx = self.tb_search_order.currentRow() if idx <= 0: return item = self.tb_search_order.takeItem(idx) self.tb_search_order.insertItem(idx-1, item) self.tb_search_order.setCurrentRow(idx-1) self.changed_signal.emit() def move_tb_search_down(self): idx = self.tb_search_order.currentRow() if idx < 0 or idx == 3: return item = self.tb_search_order.takeItem(idx) self.tb_search_order.insertItem(idx+1, item) self.tb_search_order.setCurrentRow(idx+1) self.changed_signal.emit() def tb_search_order_commit(self): t = {} # Walk the items in the list box building the (node -> node) graph of # the option order node = 0 for i in range(0, 4): v = self.tb_search_order.item(i).data(Qt.ItemDataRole.UserRole) # JSON dumps converts integer keys to strings, so do it explicitly t[str(node)] = v node = v # Add the arc from the last node back to node 0 t[str(node)] = 0 gprefs.set('tb_search_order', t) def reset_tb_search_order(self): gprefs.set('tb_search_order', gprefs.defaults['tb_search_order']) self.fill_tb_search_order_box() self.changed_signal.emit() def update_color_palette_state(self): if self.ui_style_available: enabled = self.opt_ui_style.currentData() == 'calibre' self.button_adjust_colors.setEnabled(enabled) def export_layout(self, model=None): filename = choose_save_file(self, 'em_import_export_field_list', _('Save column list to file'), filters=[(_('Column list'), ['json'])]) if filename: try: with open(filename, 'w') as f: json.dump(model.fields, f, indent=1) except Exception as err: error_dialog(self, _('Export field layout'), _('<p>Could not write field list. Error:<br>%s')%err, show=True) def import_layout(self, model=None): filename = choose_files(self, 'em_import_export_field_list', _('Load column list from file'), filters=[(_('Column list'), ['json'])]) if filename: try: with open(filename[0]) as f: fields = json.load(f) model.initialize(pref_data_override=fields) self.changed_signal.emit() except Exception as err: error_dialog(self, _('Import layout'), _('<p>Could not read field list. Error:<br>%s')%err, show=True) def reset_layout(self, model=None): model.initialize(use_defaults=True) self.changed_signal.emit() def tb_down_button_clicked(self): idx = self.tb_display_order.currentIndex() if idx.isValid(): row = idx.row() model = self.tb_display_model fields = model.fields key = fields[row][0] if not is_standard_category(key): return if row < len(fields) and is_standard_category(fields[row+1][0]): move_field_down(self.tb_display_order, model) def tb_up_button_clicked(self): idx = self.tb_display_order.currentIndex() if idx.isValid(): row = idx.row() model = self.tb_display_model fields = model.fields key = fields[row][0] if not is_standard_category(key): return move_field_up(self.tb_display_order, model) def choose_icon_theme(self): from calibre.gui2.icon_theme import ChooseTheme d = ChooseTheme(self) if d.exec() == QDialog.DialogCode.Accepted: self.commit_icon_theme = d.commit_changes self.icon_theme_title = d.new_theme_title or _('Default icons') self.icon_theme.setText(_('Icon theme: <b>%s</b>') % self.icon_theme_title) self.changed_signal.emit() def edit_id_link_rules(self): if IdLinksEditor(self).exec() == QDialog.DialogCode.Accepted: self.changed_signal.emit() @property def current_cover_size(self): cval = self.opt_cover_grid_height.value() wval = self.opt_cover_grid_width.value() if cval < 0.1: dpi = self.opt_cover_grid_height.logicalDpiY() cval = auto_height(self.opt_cover_grid_height) / dpi / CM_TO_INCH if wval < 0.1: wval = 0.75 * cval return wval, cval def update_aspect_ratio(self, *args): width, height = self.current_cover_size ar = width / height self.cover_grid_aspect_ratio.setText(_('Current aspect ratio (width/height): %.2g') % ar) def resize_cover(self, smaller): wval, cval = self.current_cover_size ar = wval / cval delta = 0.2 * (-1 if smaller else 1) cval += delta cval = max(0, cval) self.opt_cover_grid_height.setValue(cval) self.opt_cover_grid_width.setValue(cval * ar) def cg_reset_size(self): self.opt_cover_grid_width.setValue(0) self.opt_cover_grid_height.setValue(0) def edit_cb_title_template(self): t = TemplateDialog(self, self.opt_cover_browser_title_template.text(), fm=self.gui.current_db.field_metadata) t.setWindowTitle(_('Edit template for caption')) if t.exec(): self.opt_cover_browser_title_template.setText(t.rule[1]) def initialize(self): ConfigWidgetBase.initialize(self) self.default_author_link.value = default_author_link() font = gprefs['font'] if font is not None: font = list(font) font.append(gprefs.get('font_stretch', QFont.Stretch.Unstretched)) self.current_font = self.initial_font = font self.update_font_display() self.display_model.initialize() self.em_display_model.initialize() self.qv_display_model.initialize() self.tb_display_model.initialize() self.tb_categories_to_part_model.initialize() self.tb_hierarchical_cats_model.initialize() self.bd_vertical_cats_model.initialize() db = self.gui.current_db mi = [] try: rows = self.gui.current_view().selectionModel().selectedRows() for row in rows: if row.isValid(): mi.append(db.new_api.get_proxy_metadata(db.data.index_to_id(row.row()))) except: pass self.edit_rules.initialize(db.field_metadata, db.prefs, mi, 'column_color_rules') self.icon_rules.initialize(db.field_metadata, db.prefs, mi, 'column_icon_rules') self.grid_rules.initialize(db.field_metadata, db.prefs, mi, 'cover_grid_icon_rules') self.set_cg_color(gprefs['cover_grid_color']) self.set_cg_texture(gprefs['cover_grid_texture']) self.update_aspect_ratio() self.opt_book_details_css.blockSignals(True) self.opt_book_details_css.setPlainText(P('templates/book_details.css', data=True).decode('utf-8')) self.opt_book_details_css.blockSignals(False) self.tb_focus_label.setVisible(self.opt_tag_browser_allow_keyboard_focus.isChecked()) self.update_color_palette_state() self.opt_gui_layout.setCurrentIndex(0 if self.gui.layout_container.is_wide else 1) set_help_tips(self.opt_cover_browser_narrow_view_position, _( 'This option controls the position of the cover browser when using the Narrow user ' 'interface layout. "Automatic" will place the cover browser on top or on the right ' 'of the book list depending on the aspect ratio of the calibre window. "On top" ' 'places it over the book list, and "On right" places it to the right of the book ' 'list. This option has no effect when using the Wide user interface layout.')) def open_cg_cache(self): open_local_file(self.gui.grid_view.thumbnail_cache.location) def update_cg_cache_size(self, size): self.cover_grid_current_disk_cache.setText( _('Current space used: %s') % human_readable(size)) def tab_changed(self, index): if self.tabWidget.currentWidget() is self.cover_grid_tab: self.show_current_cache_usage() def show_current_cache_usage(self): t = Thread(target=self.calc_cache_size) t.daemon = True t.start() def calc_cache_size(self): self.size_calculated.emit(self.gui.grid_view.thumbnail_cache.current_size) def set_cg_color(self, val): self.cg_bg_widget.bcol = QColor(*val) self.cg_bg_widget.update_brush() def set_cg_texture(self, val): self.cg_bg_widget.btex = val self.cg_bg_widget.update_brush() def empty_cache(self): self.gui.grid_view.thumbnail_cache.empty() self.calc_cache_size() def restore_defaults(self): ConfigWidgetBase.restore_defaults(self) self.default_author_link.value = DEFAULT_AUTHOR_LINK ofont = self.current_font self.current_font = None if ofont is not None: self.changed_signal.emit() self.update_font_display() self.display_model.restore_defaults() self.em_display_model.restore_defaults() self.qv_display_model.restore_defaults() self.bd_vertical_cats_model.restore_defaults() gprefs.set('tb_search_order', gprefs.defaults['tb_search_order']) self.edit_rules.clear() self.icon_rules.clear() self.grid_rules.clear() self.changed_signal.emit() self.set_cg_color(gprefs.defaults['cover_grid_color']) self.set_cg_texture(gprefs.defaults['cover_grid_texture']) self.opt_book_details_css.setPlainText(P('templates/book_details.css', allow_user_override=False, data=True).decode('utf-8')) self.opt_gui_layout.setCurrentIndex(0) def change_cover_grid_color(self): col = QColorDialog.getColor(self.cg_bg_widget.bcol, self.gui, _('Choose background color for the Cover grid')) if col.isValid(): col = tuple(col.getRgb())[:3] self.set_cg_color(col) self.changed_signal.emit() if self.cg_bg_widget.btex: if question_dialog( self, _('Remove background image?'), _('There is currently a background image set, so the color' ' you have chosen will not be visible. Remove the background image?')): self.set_cg_texture(None) def change_cover_grid_texture(self): from calibre.gui2.preferences.texture_chooser import TextureChooser d = TextureChooser(parent=self, initial=self.cg_bg_widget.btex) if d.exec() == QDialog.DialogCode.Accepted: self.set_cg_texture(d.texture) self.changed_signal.emit() def restore_cover_grid_appearance(self): self.set_cg_color(gprefs.defaults['cover_grid_color']) self.set_cg_texture(gprefs.defaults['cover_grid_texture']) self.changed_signal.emit() def build_font_obj(self): font_info = qt_app.original_font if self.current_font is None else self.current_font font = QFont(*(font_info[:4])) font.setStretch(font_info[4]) return font def update_font_display(self): font = self.build_font_obj() fi = QFontInfo(font) name = str(fi.family()) self.font_display.setFont(font) self.font_display.setText(name + ' [%dpt]'%fi.pointSize()) def change_font(self, *args): fd = QFontDialog(self.build_font_obj(), self) if fd.exec() == QDialog.DialogCode.Accepted: font = fd.selectedFont() fi = QFontInfo(font) self.current_font = [str(fi.family()), fi.pointSize(), fi.weight(), fi.italic(), font.stretch()] self.update_font_display() self.changed_signal.emit() def commit(self, *args): with BusyCursor(): rr = ConfigWidgetBase.commit(self, *args) if self.current_font != self.initial_font: gprefs['font'] = (self.current_font[:4] if self.current_font else None) gprefs['font_stretch'] = (self.current_font[4] if self.current_font is not None else QFont.Stretch.Unstretched) QApplication.setFont(self.font_display.font()) rr = True self.display_model.commit() self.em_display_model.commit() self.qv_display_model.commit() self.tb_display_model.commit() self.tb_categories_to_part_model.commit() self.tb_hierarchical_cats_model.commit() self.bd_vertical_cats_model.commit() self.tb_search_order_commit() self.edit_rules.commit(self.gui.current_db.prefs) self.icon_rules.commit(self.gui.current_db.prefs) self.grid_rules.commit(self.gui.current_db.prefs) gprefs['cover_grid_color'] = tuple(self.cg_bg_widget.bcol.getRgb())[:3] gprefs['cover_grid_texture'] = self.cg_bg_widget.btex if self.commit_icon_theme is not None: self.commit_icon_theme() gprefs['default_author_link'] = self.default_author_link.value bcss = self.opt_book_details_css.toPlainText().encode('utf-8') defcss = P('templates/book_details.css', data=True, allow_user_override=False) if defcss == bcss: bcss = None set_data('templates/book_details.css', bcss) self.gui.layout_container.change_layout(self.gui, self.opt_gui_layout.currentIndex() == 0) return rr def refresh_gui(self, gui): gui.book_details.book_info.refresh_css() gui.place_layout_buttons() m = gui.library_view.model() m.update_db_prefs_cache() m.beginResetModel(), m.endResetModel() self.update_font_display() gui.tags_view.set_look_and_feel() gui.tags_view.reread_collapse_parameters() gui.tags_view.model().reset_tag_browser() gui.library_view.refresh_book_details(force=True) gui.library_view.refresh_grid() gui.library_view.refresh_composite_edit() gui.library_view.set_row_header_visibility() gui.cover_flow.setShowReflections(gprefs['cover_browser_reflections']) gui.cover_flow.setPreserveAspectRatio(gprefs['cb_preserve_aspect_ratio']) gui.cover_flow.setActivateOnDoubleClick(gprefs['cb_double_click_to_activate']) gui.update_cover_flow_subtitle_font() gui.cover_flow.template_inited = False for view in 'library memory card_a card_b'.split(): getattr(gui, view + '_view').set_row_header_visibility() gui.library_view.refresh_row_sizing() gui.grid_view.refresh_settings() gui.update_auto_scroll_timeout() qv = get_quickview_action_plugin() if qv: qv.refill_quickview() if __name__ == '__main__': from calibre.gui2 import Application app = Application([]) test_widget('Interface', 'Look & Feel')
54,864
Python
.py
1,107
39.389341
136
0.624536
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,790
keyboard.py
kovidgoyal_calibre/src/calibre/gui2/preferences/keyboard.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from qt.core import QVBoxLayout from calibre.gui2.keyboard import ShortcutConfig from calibre.gui2.preferences import ConfigWidgetBase, test_widget class ConfigWidget(ConfigWidgetBase): def genesis(self, gui): self.gui = gui self.conf_widget = ShortcutConfig(self) self.conf_widget.changed_signal.connect(self.changed_signal) self._layout = l = QVBoxLayout() l.setContentsMargins(0, 0, 0, 0) self.setLayout(l) l.addWidget(self.conf_widget) def initialize(self): ConfigWidgetBase.initialize(self) self.conf_widget.initialize(self.gui.keyboard) def restore_defaults(self): ConfigWidgetBase.restore_defaults(self) self.conf_widget.restore_defaults() def commit(self): self.conf_widget.commit() return ConfigWidgetBase.commit(self) def refresh_gui(self, gui): gui.keyboard.finalize() def highlight_group(self, group_name): self.conf_widget.highlight_group(group_name) if __name__ == '__main__': from calibre.gui2 import Application app = Application([]) test_widget('Advanced', 'Keyboard')
1,300
Python
.py
33
33.242424
68
0.697526
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,791
coloring.py
kovidgoyal_calibre/src/calibre/gui2/preferences/coloring.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import json import os import textwrap from functools import partial from qt.core import ( QAbstractItemView, QAbstractListModel, QApplication, QCheckBox, QComboBox, QDialog, QDialogButtonBox, QDoubleValidator, QFrame, QGridLayout, QHBoxLayout, QIcon, QIntValidator, QItemSelection, QItemSelectionModel, QLabel, QLineEdit, QListView, QListWidget, QListWidgetItem, QPalette, QPushButton, QScrollArea, QSize, QSizePolicy, QSpacerItem, QStandardItem, QStandardItemModel, Qt, QToolButton, QVBoxLayout, QWidget, pyqtSignal, ) from calibre import as_unicode, prepare_string_for_xml, sanitize_file_name from calibre.constants import config_dir from calibre.gui2 import choose_files, choose_save_file, error_dialog, gprefs, info_dialog, open_local_file, pixmap_to_data, question_dialog from calibre.gui2.dialogs.template_dialog import TemplateDialog from calibre.gui2.metadata.single_download import RichTextDelegate from calibre.gui2.preferences import ListViewWithMoveByKeyPress from calibre.gui2.widgets2 import ColorButton, FlowLayout, Separator from calibre.library.coloring import Rule, color_row_key, conditionable_columns, displayable_columns, rule_from_template from calibre.utils.icu import lower, sort_key from calibre.utils.localization import lang_map, ngettext from polyglot.builtins import iteritems all_columns_string = _('All columns') icon_rule_kinds = [(_('icon with text'), 'icon'), (_('icon with no text'), 'icon_only'), (_('composed icons w/text'), 'icon_composed'), (_('composed icons w/no text'), 'icon_only_composed'),] class ConditionEditor(QWidget): # {{{ ACTION_MAP = { 'bool2' : ( (_('is true'), 'is true',), (_('is false'), 'is not true'), ), 'bool' : ( (_('is true'), 'is true',), (_('is not true'), 'is not true'), (_('is false'), 'is false'), (_('is not false'), 'is not false'), (_('is undefined'), 'is undefined'), (_('is defined'), 'is defined'), ), 'ondevice' : ( (_('is true'), 'is set',), (_('is false'), 'is not set'), ), 'identifiers' : ( (_('has id'), 'has id'), (_('does not have id'), 'does not have id'), ), 'int' : ( (_('is equal to'), 'eq'), (_('is less than'), 'lt'), (_('is greater than'), 'gt'), (_('is set'), 'is set'), (_('is not set'), 'is not set') ), 'datetime' : ( (_('is equal to'), 'eq'), (_('is earlier than'), 'lt'), (_('is later than'), 'gt'), (_('is today'), 'is today'), (_('is set'), 'is set'), (_('is not set'), 'is not set'), (_('is more days ago than'), 'older count days'), (_('is fewer days ago than'), 'count_days'), (_('is more days from now than'), 'newer future days'), (_('is fewer days from now than'), 'older future days') ), 'multiple' : ( (_('has'), 'has'), (_('does not have'), 'does not have'), (_('has pattern'), 'has pattern'), (_('does not have pattern'), 'does not have pattern'), (_('is set'), 'is set'), (_('is not set'), 'is not set'), ), 'multiple_no_isset' : ( (_('has'), 'has'), (_('does not have'), 'does not have'), (_('has pattern'), 'has pattern'), (_('does not have pattern'), 'does not have pattern'), ), 'single' : ( (_('is'), 'is'), (_('is not'), 'is not'), (_('contains'), 'contains'), (_('does not contain'), 'does not contain'), (_('matches pattern'), 'matches pattern'), (_('does not match pattern'), 'does not match pattern'), (_('is set'), 'is set'), (_('is not set'), 'is not set'), ), 'single_no_isset' : ( (_('is'), 'is'), (_('is not'), 'is not'), (_('contains'), 'contains'), (_('does not contain'), 'does not contain'), (_('matches pattern'), 'matches pattern'), (_('does not match pattern'), 'does not match pattern'), ), } for x in ('float', 'rating'): ACTION_MAP[x] = ACTION_MAP['int'] def __init__(self, fm, parent=None): QWidget.__init__(self, parent) self.fm = fm self.action_map = self.ACTION_MAP self.l = l = QGridLayout(self) self.setLayout(l) texts = _('If the ___ column ___ value') try: one, two, three = texts.split('___') except: one, two, three = 'If the ', ' column ', ' value ' self.l1 = l1 = QLabel(one) l.addWidget(l1, 0, 0) self.column_box = QComboBox(self) l.addWidget(self.column_box, 0, 1) self.l2 = l2 = QLabel(two) l.addWidget(l2, 0, 2) self.action_box = QComboBox(self) l.addWidget(self.action_box, 0, 3) self.l3 = l3 = QLabel(three) l.addWidget(l3, 0, 4) self.value_box = QLineEdit(self) l.addWidget(self.value_box, 0, 5) self.column_box.addItem('', '') for key in sorted( conditionable_columns(fm), key=lambda key: sort_key(fm[key]['name'])): self.column_box.addItem('{} ({})'.format(fm[key]['name'], key), key) self.column_box.setCurrentIndex(0) self.column_box.currentIndexChanged.connect(self.init_action_box) self.action_box.currentIndexChanged.connect(self.init_value_box) for b in (self.column_box, self.action_box): b.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon) b.setMinimumContentsLength(20) @property def current_col(self): idx = self.column_box.currentIndex() return str(self.column_box.itemData(idx) or '') @current_col.setter def current_col(self, val): for idx in range(self.column_box.count()): c = str(self.column_box.itemData(idx) or '') if c == val: self.column_box.setCurrentIndex(idx) return raise ValueError('Column %r not found'%val) @property def current_action(self): idx = self.action_box.currentIndex() return str(self.action_box.itemData(idx) or '') @current_action.setter def current_action(self, val): for idx in range(self.action_box.count()): c = str(self.action_box.itemData(idx) or '') if c == val: self.action_box.setCurrentIndex(idx) return raise ValueError('Action %r not valid for current column'%val) @property def current_val(self): ans = str(self.value_box.text()).strip() if not self.value_box.isEnabled(): ans = '' if self.current_col == 'languages': rmap = {lower(v):k for k, v in iteritems(lang_map())} ans = rmap.get(lower(ans), ans) return ans @property def condition(self): c, a, v = (self.current_col, self.current_action, self.current_val) if not c or not a: return None return (c, a, v) @condition.setter def condition(self, condition): c, a, v = condition if not v: v = '' v = v.strip() self.current_col = c self.current_action = a self.value_box.setText(v) def init_action_box(self): self.action_box.blockSignals(True) self.action_box.clear() self.action_box.addItem('', '') col = self.current_col if col: m = self.fm[col] dt = m['datatype'] if dt == 'bool': from calibre.gui2.ui import get_gui if not get_gui().current_db.new_api.pref('bools_are_tristate'): dt = 'bool2' if dt in self.action_map: actions = self.action_map[dt] else: if col == 'ondevice': k = 'ondevice' elif col == 'identifiers': k = 'identifiers' elif col == 'authors': k = 'multiple_no_isset' elif col == 'title': k = 'single_no_isset' else: k = 'multiple' if m['is_multiple'] else 'single' actions = self.action_map[k] for text, key in actions: self.action_box.addItem(text, key) self.action_box.setCurrentIndex(0) self.action_box.blockSignals(False) self.init_value_box() def init_value_box(self): self.value_box.setEnabled(True) self.value_box.setText('') self.value_box.setInputMask('') self.value_box.setValidator(None) col = self.current_col if not col: return action = self.current_action if not action: return m = self.fm[col] dt = m['datatype'] tt = '' if col == 'identifiers': tt = _('Enter either an identifier type or an ' 'identifier type and value of the form identifier:value') elif col == 'languages': tt = _('Enter a 3 letter ISO language code, like fra for French' ' or deu for German or eng for English. You can also use' ' the full language name, in which case calibre will try to' ' automatically convert it to the language code.') elif dt in ('int', 'float', 'rating'): tt = _('Enter a number') v = QIntValidator if dt == 'int' else QDoubleValidator self.value_box.setValidator(v(self.value_box)) elif dt == 'datetime': if action == 'count_days': self.value_box.setValidator(QIntValidator(self.value_box)) tt = _('Enter the maximum days old the item can be. Zero is today. ' 'Dates in the future always match') elif action == 'older count days': self.value_box.setValidator(QIntValidator(self.value_box)) tt = _('Enter the minimum days old the item can be. Zero is today. ' 'Dates in the future never match') elif action == 'older future days': self.value_box.setValidator(QIntValidator(self.value_box)) tt = _('Enter the maximum days in the future the item can be. ' 'Zero is today. Dates in the past always match') elif action == 'newer future days': self.value_box.setValidator(QIntValidator(self.value_box)) tt = _('Enter the minimum days in the future the item can be. ' 'Zero is today. Dates in the past never match') else: self.value_box.setInputMask('9999-99-99') tt = _('Enter a date in the format YYYY-MM-DD') else: tt = _('Enter a string.') if 'pattern' in action: tt = _('Enter a regular expression') elif m.get('is_multiple', False): tt += '\n' + _('You can match multiple values by separating' ' them with %s')%m['is_multiple']['ui_to_list'] self.value_box.setToolTip(tt) if action in ('is set', 'is not set', 'is true', 'is false', 'is undefined', 'is today'): self.value_box.setEnabled(False) # }}} class RemoveIconFileDialog(QDialog): # {{{ def __init__(self, parent, icon_file_names, icon_folder): self.files_to_remove = [] QDialog.__init__(self, parent) self.setWindowTitle(_('Remove icons')) self.setWindowFlags(self.windowFlags()&(~Qt.WindowType.WindowContextHelpButtonHint)) l = QVBoxLayout(self) t = QLabel('<p>' + _('Select the icons you wish to remove. The icon files will be ' 'removed when you press OK. There is no undo.') + '</p>') t.setWordWrap(True) t.setTextFormat(Qt.TextFormat.RichText) l.addWidget(t) self.listbox = lw = QListWidget(parent) lw.setSelectionMode(QAbstractItemView.SelectionMode.MultiSelection) for fn in icon_file_names: item = QListWidgetItem(fn) item.setIcon(QIcon(os.path.join(icon_folder, fn))) lw.addItem(item) l.addWidget(lw) self.bb = bb = QDialogButtonBox( QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) l.addWidget(bb) def sizeHint(self): return QSize(700, 600) def accept(self): self.files_to_remove = [item.text() for item in self.listbox.selectedItems()] if not self.files_to_remove: return error_dialog(self, _('No icons selected'), _( 'You must select at least one icon to remove'), show=True) if question_dialog(self, _('Remove icons'), ngettext('One icon will be removed.', '{} icons will be removed.', len(self.files_to_remove) ).format(len(self.files_to_remove)) + ' ' + _('This will prevent any rules that use this icon from working. Are you sure?'), yes_text=_('Yes'), no_text=_('No'), det_msg='\n'.join(self.files_to_remove), skip_dialog_name='remove_icon_confirmation_dialog' ): QDialog.accept(self) # }}} class RuleEditor(QDialog): # {{{ @property def doing_multiple(self): return hasattr(self, 'multiple_icon_cb') and self.multiple_icon_cb.isChecked() def __init__(self, fm, pref_name, parent=None): QDialog.__init__(self, parent) self.fm = fm if pref_name == 'column_color_rules': self.rule_kind = 'color' rule_text = _('column coloring') elif pref_name == 'column_icon_rules': self.rule_kind = 'icon' rule_text = _('column icon') elif pref_name == 'cover_grid_icon_rules': self.rule_kind = 'emblem' rule_text = _('Cover grid emblem') self.setWindowIcon(QIcon.ic('format-fill-color.png')) self.setWindowTitle(_('Create/edit a {0} rule').format(rule_text)) self.l = l = QGridLayout(self) self.setLayout(l) self.l1 = l1 = QLabel(_('Create a {0} rule by' ' filling in the boxes below').format(rule_text)) l.addWidget(l1, 0, 0, 1, 8) self.f1 = QFrame(self) self.f1.setFrameShape(QFrame.Shape.HLine) l.addWidget(self.f1, 1, 0, 1, 8) # self.l2 = l2 = QLabel(_('Add the emblem:') if self.rule_kind == 'emblem' else _('Set the')) # l.addWidget(l2, 2, 0) if self.rule_kind == 'emblem': self.l2 = l2 = QLabel(_('Add the emblem:')) l.addWidget(l2, 2, 0) elif self.rule_kind == 'color': l.addWidget(QLabel(_('Set the color of the column:')), 2, 0) elif self.rule_kind == 'icon': l.addWidget(QLabel(_('Set the:')), 2, 0) self.kind_box = QComboBox(self) for tt, t in icon_rule_kinds: self.kind_box.addItem(tt, t) l.addWidget(self.kind_box, 3, 0) self.kind_box.setToolTip(textwrap.fill(_( 'Choosing icon with text will add an icon to the left of the' ' column content, choosing icon with no text will hide' ' the column content and leave only the icon.' ' If you choose composed icons and multiple rules match, then all the' ' matching icons will be combined, otherwise the icon from the' ' first rule to match will be used.'))) self.l3 = l3 = QLabel(_('of the column:')) l.addWidget(l3, 2, 2) else: pass self.column_box = QComboBox(self) l.addWidget(self.column_box, 3, 0 if self.rule_kind == 'color' else 2) self.l4 = l4 = QLabel(_('to:')) l.addWidget(l4, 2, 5) if self.rule_kind == 'emblem': self.column_box.setVisible(False), l4.setVisible(False) def create_filename_box(): self.filename_box = f = QComboBox() self.filenamebox_view = v = QListView() v.setIconSize(QSize(32, 32)) self.filename_box.setView(v) self.orig_filenamebox_view = f.view() f.setMinimumContentsLength(20), f.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon) self.populate_icon_filenames() if self.rule_kind == 'color': self.color_box = ColorButton(parent=self) self.color_label = QLabel('Sample text Sample text') self.color_label.setTextFormat(Qt.TextFormat.RichText) l.addWidget(self.color_box, 3, 5) l.addWidget(self.color_label, 3, 6) l.addItem(QSpacerItem(10, 10, QSizePolicy.Policy.Expanding), 2, 7) elif self.rule_kind == 'emblem': create_filename_box() self.update_filename_box() self.filename_button = QPushButton(QIcon.ic('document_open.png'), _('&Add new image')) l.addWidget(self.filename_box, 3, 0) l.addWidget(self.filename_button, 3, 2) l.addWidget(QLabel(_('(Images should be square-ish)')), 3, 4) l.setColumnStretch(7, 10) else: create_filename_box() self.multiple_icon_cb = QCheckBox(_('Choose &more than one icon')) l.addWidget(self.multiple_icon_cb, 4, 5) self.update_filename_box() self.multiple_icon_cb.clicked.connect(self.multiple_box_clicked) l.addWidget(self.filename_box, 3, 5) self.filename_button = QPushButton(QIcon.ic('document_open.png'), _('&Add icon')) l.addWidget(self.filename_button, 3, 6) l.addWidget(QLabel(_('(Icons should be square or landscape)')), 4, 6) l.setColumnStretch(7, 10) self.l5 = l5 = QLabel( _('Only if the following conditions are all satisfied:')) l.addWidget(l5, 5, 0, 1, 7) self.scroll_area = sa = QScrollArea(self) sa.setMinimumHeight(300) sa.setMinimumWidth(700) sa.setWidgetResizable(True) l.addWidget(sa, 6, 0, 1, 8) self.add_button = b = QPushButton(QIcon.ic('plus.png'), _('Add &another condition')) l.addWidget(b, 7, 0, 1, 8) b.clicked.connect(self.add_blank_condition) self.l6 = l6 = QLabel(_('You can disable a condition by' ' blanking all of its boxes')) l.addWidget(l6, 8, 0, 1, 8) bbl = QHBoxLayout() self.bb = bb = QDialogButtonBox( QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) if self.rule_kind in ('emblem', 'icon'): theme_button = QPushButton(_('Using icons in light/dark themes')) theme_button.setIcon(QIcon.ic('help.png')) theme_button.clicked.connect(self.show_theme_help) bbl.addWidget(theme_button) bbl.addStretch(10) bbl.addWidget(bb) l.addLayout(bbl, 9, 0, 1, 8) if self.rule_kind != 'color': self.remove_button = b = bb.addButton(_('&Remove icons'), QDialogButtonBox.ButtonRole.ActionRole) b.setIcon(QIcon.ic('minus.png')) b.clicked.connect(self.remove_icon_file_dialog) b.setToolTip('<p>' + _('Remove previously added icons. Note that removing an ' 'icon will cause rules that use it to stop working.') + '</p>') self.conditions_widget = QWidget(self) sa.setWidget(self.conditions_widget) self.conditions_widget.setLayout(QVBoxLayout()) self.conditions_widget.layout().setAlignment(Qt.AlignmentFlag.AlignTop) self.conditions = [] if self.rule_kind == 'color': for b in (self.column_box, ): b.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon) b.setMinimumContentsLength(15) for key in sorted(displayable_columns(fm), key=lambda k: sort_key(fm[k]['name']) if k != color_row_key else b''): if key == color_row_key and self.rule_kind != 'color': continue name = all_columns_string if key == color_row_key else fm[key]['name'] if name: self.column_box.addItem(name + (' (' + key + ')' if key != color_row_key else ''), key) self.column_box.setCurrentIndex(0) if self.rule_kind == 'color': self.color_box.color = '#000' self.update_color_label() self.color_box.color_changed.connect(self.update_color_label) else: self.rule_icon_files = [] self.filename_button.clicked.connect(self.filename_button_clicked) self.resize(self.sizeHint()) def show_theme_help(self): msg = '<p>'+ _( 'You can use different icons in light and dark themes. To do this, ' 'add two icons to the icon list. One of the icons must have either the ' '"plain" name, for example "ok.png", or the themed name, for example ' '"ok-for-light-theme.png". The other icon must have a themed name with ' 'the same prefix, for example "ok-for-dark-theme.png". ' '</p><p>' 'Example: if the light theme icon is named "ok.png" then the dark ' 'theme icon must be named "ok-for-dark-theme.png". If the light ' 'theme icon is named "ok-for-light-theme.png" then the dark theme ' 'icon must be named either ok.png or "ok-for-dark-theme.png".' '</p><p>' 'When defining a rule, use either of the icon names. The correct ' 'icon for the theme will automatically be used, if it exists.' '</p><p>' 'You are not required to change existing rules to use theming. Decide ' 'the theme where the existing icon should be used then add the ' 'other icon with the correct themed name. ' '</p><p>' 'Remember to add both the light and dark theme icons to the list of icons.' ) + '</p>' info_dialog(self, _('Using icons in light/dark themes'), msg, show=True) def multiple_box_clicked(self): self.update_filename_box() self.update_icon_filenames_in_box() @property def icon_folder(self): return os.path.join(config_dir, 'cc_icons') def populate_icon_filenames(self): d = self.icon_folder self.icon_file_names = [] if os.path.exists(d): for icon_file in os.listdir(d): icon_file = lower(icon_file) if os.path.exists(os.path.join(d, icon_file)) and icon_file.endswith('.png'): self.icon_file_names.append(icon_file) self.icon_file_names.sort(key=sort_key) def update_filename_box(self): doing_multiple = self.doing_multiple model = QStandardItemModel() self.filename_box.setModel(model) self.icon_file_names.sort(key=sort_key) if doing_multiple: item = QStandardItem(_('Open to see checkboxes')) item.setIcon(QIcon.ic('blank.png')) else: item = QStandardItem('') item.setFlags(Qt.ItemFlag(0)) model.appendRow(item) for i,filename in enumerate(self.icon_file_names): item = QStandardItem(filename) if doing_multiple: item.setFlags(Qt.ItemFlag.ItemIsUserCheckable | Qt.ItemFlag.ItemIsEnabled) item.setData(Qt.CheckState.Unchecked, Qt.ItemDataRole.CheckStateRole) else: item.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable) icon = QIcon(os.path.join(self.icon_folder, filename)) item.setIcon(icon) model.appendRow(item) def update_color_label(self): pal = QApplication.palette() bg1 = str(pal.color(QPalette.ColorRole.Base).name()) bg2 = str(pal.color(QPalette.ColorRole.AlternateBase).name()) c = self.color_box.color self.color_label.setText(''' <span style="color: {c}; background-color: {bg1}">&nbsp;{st}&nbsp;</span> <span style="color: {c}; background-color: {bg2}">&nbsp;{st}&nbsp;</span> '''.format(c=c, bg1=bg1, bg2=bg2, st=_('Sample text'))) def sanitize_icon_file_name(self, icon_path): n = lower(sanitize_file_name( os.path.splitext( os.path.basename(icon_path))[0]+'.png')) return n.replace("'", '_') def filename_button_clicked(self): try: path = choose_files(self, 'choose_category_icon', _('Select icon'), filters=[ (_('Images'), ['png', 'gif', 'jpg', 'jpeg'])], all_files=False, select_only_single_file=True) if path: icon_path = path[0] icon_name = self.sanitize_icon_file_name(icon_path) if icon_name not in self.icon_file_names: self.icon_file_names.append(icon_name) try: p = QIcon(icon_path).pixmap(QSize(128, 128)) d = self.icon_folder if not os.path.exists(os.path.join(d, icon_name)): if not os.path.exists(d): os.makedirs(d) with open(os.path.join(d, icon_name), 'wb') as f: f.write(pixmap_to_data(p, format='PNG')) except: import traceback traceback.print_exc() self.update_filename_box() if self.doing_multiple: if icon_name not in self.rule_icon_files: self.rule_icon_files.append(icon_name) self.update_icon_filenames_in_box() else: self.filename_box.setCurrentIndex(self.filename_box.findText(icon_name)) self.filename_box.adjustSize() except: import traceback traceback.print_exc() return def get_filenames_from_box(self): if self.doing_multiple: model = self.filename_box.model() fnames = [] for i in range(1, model.rowCount()): item = model.item(i, 0) if item.checkState() == Qt.CheckState.Checked: fnames.append(lower(str(item.text()))) fname = ' : '.join(fnames) else: fname = lower(str(self.filename_box.currentText())) return fname def update_icon_filenames_in_box(self): if self.rule_icon_files: if not self.doing_multiple: idx = self.filename_box.findText(self.rule_icon_files[0]) if idx >= 0: self.filename_box.setCurrentIndex(idx) else: self.filename_box.setCurrentIndex(0) else: model = self.filename_box.model() for icon in self.rule_icon_files: idx = self.filename_box.findText(icon) if idx >= 0: item = model.item(idx) item.setCheckState(Qt.CheckState.Checked) def remove_icon_file_dialog(self): d = RemoveIconFileDialog(self, self.icon_file_names, self.icon_folder) if d.exec() == QDialog.DialogCode.Accepted: if len(d.files_to_remove) > 0: for name in d.files_to_remove: try: os.remove(os.path.join(self.icon_folder, name)) except OSError: pass self.populate_icon_filenames() self.update_filename_box() self.update_icon_filenames_in_box() def add_blank_condition(self): c = ConditionEditor(self.fm, parent=self.conditions_widget) self.conditions.append(c) self.conditions_widget.layout().addWidget(c) def apply_rule(self, kind, col, rule): if kind == 'color': if rule.color: self.color_box.color = rule.color else: if self.rule_kind == 'icon': for i, tup in enumerate(icon_rule_kinds): if kind == tup[1]: self.kind_box.setCurrentIndex(i) break self.rule_icon_files = [ic.strip() for ic in rule.color.split(':')] if len(self.rule_icon_files) > 1: self.multiple_icon_cb.setChecked(True) self.update_filename_box() self.update_icon_filenames_in_box() for i in range(self.column_box.count()): c = str(self.column_box.itemData(i) or '') if col == c: self.column_box.setCurrentIndex(i) break for c in rule.conditions: ce = ConditionEditor(self.fm, parent=self.conditions_widget) self.conditions.append(ce) self.conditions_widget.layout().addWidget(ce) try: ce.condition = c except: import traceback traceback.print_exc() def accept(self): if self.rule_kind != 'color': fname = self.get_filenames_from_box() if not fname: error_dialog(self, _('No icon selected'), _('You must choose an icon for this rule'), show=True) return if self.validate(): QDialog.accept(self) def validate(self): r = Rule(self.fm) for c in self.conditions: condition = c.condition if condition is not None: try: r.add_condition(*condition) except Exception as e: import traceback error_dialog(self, _('Invalid condition'), _('One of the conditions for this rule is' ' invalid: <b>%s</b>')%e, det_msg=traceback.format_exc(), show=True) return False if len(r.conditions) < 1: error_dialog(self, _('No conditions'), _('You must specify at least one non-empty condition' ' for this rule'), show=True) return False return True @property def rule(self): r = Rule(self.fm) if self.rule_kind != 'color': r.color = self.get_filenames_from_box() else: r.color = self.color_box.color idx = self.column_box.currentIndex() col = str(self.column_box.itemData(idx) or '') for c in self.conditions: condition = c.condition if condition is not None: r.add_condition(*condition) if self.rule_kind == 'icon': kind = str(self.kind_box.itemData( self.kind_box.currentIndex()) or '') else: kind = self.rule_kind return kind, col, r # }}} class RulesModel(QAbstractListModel): # {{{ EXIM_VERSION = 1 def load_rule(self, col, template): if col not in self.fm and col != color_row_key: return try: rule = rule_from_template(self.fm, template) except: rule = template return rule def __init__(self, prefs, fm, pref_name, parent=None): QAbstractListModel.__init__(self, parent) self.fm = fm self.pref_name = pref_name if pref_name == 'column_color_rules': self.rule_kind = 'color' rules = list(prefs[pref_name]) self.rules = [] for col, template in rules: rule = self.load_rule(col, template) if rule is not None: self.rules.append(('color', col, rule)) else: self.rule_kind = 'icon' if pref_name == 'column_icon_rules' else 'emblem' rules = list(prefs[pref_name]) self.rules = [] for kind, col, template in rules: rule = self.load_rule(col, template) if rule is not None: self.rules.append((kind, col, rule)) def rowCount(self, *args): return len(self.rules) def data(self, index, role): row = index.row() try: kind, col, rule = self.rules[row] except: return None if role == Qt.ItemDataRole.DisplayRole: if col == color_row_key: col = all_columns_string else: col = self.fm[col]['name'] return self.rule_to_html(kind, col, rule) if role == Qt.ItemDataRole.UserRole: return (kind, col, rule) def add_rule(self, kind, col, rule, selected_row=None): self.beginResetModel() if selected_row: self.rules.insert(selected_row.row(), (kind, col, rule)) else: self.rules.append((kind, col, rule)) self.endResetModel() if selected_row: return self.index(selected_row.row()) return self.index(len(self.rules)-1) def replace_rule(self, index, kind, col, r): self.rules[index.row()] = (kind, col, r) self.dataChanged.emit(index, index) def remove_rule(self, index): self.beginResetModel() self.rules.remove(self.rules[index.row()]) self.endResetModel() def rules_as_list(self, for_export=False): rules = [] for kind, col, r in self.rules: if isinstance(r, Rule): r = r.template if r is not None: if not for_export and kind == 'color': rules.append((col, r)) else: rules.append((kind, col, r)) return rules def import_rules(self, rules): self.beginResetModel() for kind, col, template in rules: if self.pref_name == 'column_color_rules': kind = 'color' rule = self.load_rule(col, template) if rule is not None: self.rules.append((kind, col, rule)) self.endResetModel() def commit(self, prefs): prefs[self.pref_name] = self.rules_as_list() def move(self, idx, delta): row = idx.row() + delta if row >= 0 and row < len(self.rules): self.beginResetModel() t = self.rules.pop(row-delta) self.rules.insert(row, t) # does append if row >= len(rules) self.endResetModel() idx = self.index(row) return idx def clear(self): self.rules = [] self.beginResetModel() self.endResetModel() def rule_to_html(self, kind, col, rule): trans_kind = 'not found' if kind == 'color': trans_kind = _('color') else: for tt, t in icon_rule_kinds: if kind == t: trans_kind = tt break if not isinstance(rule, Rule): if kind == 'color': return _(''' <p>Advanced rule for column <b>%(col)s</b>: <pre>%(rule)s</pre> ''')%dict(col=col, rule=prepare_string_for_xml(rule)) elif self.rule_kind == 'emblem': return _(''' <p>Advanced rule: <pre>%(rule)s</pre> ''')%dict(rule=prepare_string_for_xml(rule)) else: return _(''' <p>Advanced rule: set <b>%(typ)s</b> for column <b>%(col)s</b>: <pre>%(rule)s</pre> ''')%dict(col=col, typ=trans_kind, rule=prepare_string_for_xml(rule)) conditions = [self.condition_to_html(c) for c in rule.conditions] sample = '' if kind != 'color' else ( _('(<span style="color: %s;">sample</span>)') % rule.color) if kind == 'emblem': return _('<p>Add the emblem <b>{0}</b> to the cover if the following conditions are met:</p>' '\n<ul>{1}</ul>').format(rule.color, ''.join(conditions)) return _('''\ <p>Set the <b>%(kind)s</b> of <b>%(col)s</b> to <b>%(color)s</b> %(sample)s if the following conditions are met:</p> <ul>%(rule)s</ul> ''') % dict(kind=trans_kind, col=col, color=rule.color, sample=sample, rule=''.join(conditions)) def condition_to_html(self, condition): col, a, v = condition dt = self.fm[col]['datatype'] c = self.fm[col]['name'] action_name = a if col in ConditionEditor.ACTION_MAP: # look for a column-name-specific label for trans, ac in ConditionEditor.ACTION_MAP[col]: if ac == a: action_name = trans break elif dt in ConditionEditor.ACTION_MAP: # Look for a type-specific label for trans, ac in ConditionEditor.ACTION_MAP[dt]: if ac == a: action_name = trans break else: # Wasn't a type-specific or column-specific label. Look for a text-type for dt in ['single', 'multiple']: for trans, ac in ConditionEditor.ACTION_MAP[dt]: if ac == a: action_name = trans break else: continue break if action_name == Rule.INVALID_CONDITION: return ( _('<li>The condition using column <b>%(col)s</b> is <b>invalid</b>') % dict(col=c)) return ( _('<li>If the <b>%(col)s</b> column <b>%(action)s</b> %(val_label)s<b>%(val)s</b>') % dict( col=c, action=action_name, val=prepare_string_for_xml(v), val_label=_('value: ') if v else '')) # }}} class RulesView(ListViewWithMoveByKeyPress): # {{{ def __init__(self, parent, enable_convert_buttons_function): ListViewWithMoveByKeyPress.__init__(self, parent) self.enable_convert_buttons_function = enable_convert_buttons_function def currentChanged(self, new, prev): if self.model() and new.isValid(): _, _, rule = self.model().data(new, Qt.ItemDataRole.UserRole) self.enable_convert_buttons_function(isinstance(rule, Rule)) return super().currentChanged(new, prev) # }}} class EditRules(QWidget): # {{{ changed = pyqtSignal() def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QGridLayout(self) self.setLayout(l) self.enabled = c = QCheckBox(self) l.addWidget(c, l.rowCount(), 0, 1, 2) c.setVisible(False) c.stateChanged.connect(self.changed) self.l1 = l1 = QLabel('') l1.setWordWrap(True) l.addWidget(l1, l.rowCount(), 0, 1, 2) self.add_button = QPushButton(QIcon.ic('plus.png'), _('&Add rule'), self) self.remove_button = QPushButton(QIcon.ic('minus.png'), _('&Remove rule(s)'), self) self.add_button.clicked.connect(self.add_rule) self.remove_button.clicked.connect(self.remove_rule) l.addWidget(self.add_button, l.rowCount(), 0) l.addWidget(self.remove_button, l.rowCount() - 1, 1) self.g = g = QGridLayout() self.rules_view = RulesView(self, self.do_enable_convert_buttons) self.rules_view.doubleClicked.connect(self.edit_rule) self.rules_view.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) self.rules_view.setAlternatingRowColors(True) self.rtfd = RichTextDelegate(parent=self.rules_view, max_width=400) self.rules_view.setItemDelegate(self.rtfd) g.addWidget(self.rules_view, 0, 0, 2, 1) self.up_button = b = QToolButton(self) b.setIcon(QIcon.ic('arrow-up.png')) b.setToolTip(_('Move the selected rule up')) b.clicked.connect(partial(self.move_rows, moving_up=True)) g.addWidget(b, 0, 1, 1, 1, Qt.AlignmentFlag.AlignTop) self.down_button = b = QToolButton(self) b.setIcon(QIcon.ic('arrow-down.png')) b.setToolTip(_('Move the selected rule down')) b.clicked.connect(partial(self.move_rows, moving_up=False)) self.rules_view.set_movement_functions(partial(self.move_rows, moving_up=True), partial(self.move_rows, moving_up=False)) g.addWidget(b, 1, 1, 1, 1, Qt.AlignmentFlag.AlignBottom) l.addLayout(g, l.rowCount(), 0, 1, 2) l.setRowStretch(l.rowCount() - 1, 10) self.add_advanced_button = b = QPushButton(QIcon.ic('plus.png'), _('Add ad&vanced rule'), self) b.clicked.connect(self.add_advanced) self.hb = hb = FlowLayout() l.addLayout(hb, l.rowCount(), 0, 1, 2) hb.addWidget(b) self.duplicate_rule_button = b = QPushButton(QIcon.ic('edit-copy.png'), _('Du&plicate rule'), self) b.clicked.connect(self.duplicate_rule) b.setEnabled(False) hb.addWidget(b) self.convert_to_advanced_button = b = QPushButton(QIcon.ic('modified.png'), _('Convert to advanced r&ule'), self) b.clicked.connect(self.convert_to_advanced) b.setEnabled(False) hb.addWidget(b) sep = Separator(self, b) hb.addWidget(sep) self.open_icon_folder_button = b = QPushButton(QIcon.ic('icon_choose.png'), _('Open icon folder'), self) b.clicked.connect(self.open_icon_folder) hb.addWidget(b) sep = Separator(self, b) hb.addWidget(sep) self.export_button = b = QPushButton(_('E&xport'), self) b.clicked.connect(self.export_rules) b.setToolTip(_('Export these rules to a file')) hb.addWidget(b) self.import_button = b = QPushButton(_('&Import'), self) b.setToolTip(_('Import rules from a file')) b.clicked.connect(self.import_rules) hb.addWidget(b) def open_icon_folder(self): path = os.path.join(config_dir, 'cc_icons') os.makedirs(path, exist_ok=True) open_local_file(path) def initialize(self, fm, prefs, mi, pref_name): self.pref_name = pref_name self.model = RulesModel(prefs, fm, self.pref_name) self.rules_view.setModel(self.model) self.fm = fm self.mi = mi if pref_name == 'column_color_rules': text = _( 'You can control the color of columns in the' ' book list by creating "rules" that tell calibre' ' what color to use. Click the "Add rule" button below' ' to get started.<p>You can <b>change an existing rule</b> by' ' double clicking it.') elif pref_name == 'column_icon_rules': text = _( 'You can add icons to columns in the' ' book list by creating "rules" that tell calibre' ' what icon to use. Click the "Add rule" button below' ' to get started.<p>You can <b>change an existing rule</b> by' ' double clicking it.') elif pref_name == 'cover_grid_icon_rules': text = _('You can add emblems (small icons) that are displayed on the side of covers' ' in the Cover grid by creating "rules" that tell calibre' ' what image to use. Click the "Add rule" button below' ' to get started.<p>You can <b>change an existing rule</b> by' ' double clicking it.') self.enabled.setVisible(True) self.enabled.setChecked(gprefs['show_emblems']) self.enabled.setText(_('Show &emblems next to the covers')) self.enabled.stateChanged.connect(self.enabled_toggled) self.enabled.setToolTip(_( 'If checked, you can tell calibre to display icons of your choosing' ' next to the covers shown in the Cover grid, controlled by the' ' metadata of the book.')) self.enabled_toggled() self.l1.setText('<p>'+ text) def enabled_toggled(self): enabled = self.enabled.isChecked() for x in ('add_advanced_button', 'rules_view', 'up_button', 'down_button', 'add_button', 'remove_button'): getattr(self, x).setEnabled(enabled) def do_enable_convert_buttons(self, to_what): self.convert_to_advanced_button.setEnabled(to_what) self.duplicate_rule_button.setEnabled(True) def convert_to_advanced(self): sm = self.rules_view.selectionModel() rows = list(sm.selectedRows()) if not rows or len(rows) != 1: error_dialog(self, _('Select one rule'), _('You must select only one rule.'), show=True) return idx = self.rules_view.currentIndex() if idx.isValid(): kind, col, rule = self.model.data(idx, Qt.ItemDataRole.UserRole) if isinstance(rule, Rule): template = '\n'.join( [l for l in rule.template.splitlines() if not l.startswith(Rule.SIGNATURE)]) orig_row = idx.row() self.model.remove_rule(idx) new_idx = self.model.add_rule(kind, col, template) new_idx = self.model.move(new_idx, -(self.model.rowCount() - orig_row - 1)) self.rules_view.setCurrentIndex(new_idx) self.changed.emit() def duplicate_rule(self): sm = self.rules_view.selectionModel() rows = list(sm.selectedRows()) if not rows or len(rows) != 1: error_dialog(self, _('Select one rule'), _('You must select only one rule.'), show=True) return idx = self.rules_view.currentIndex() if idx.isValid(): kind, col, rule = self.model.data(idx, Qt.ItemDataRole.UserRole) orig_row = idx.row() + 1 new_idx = self.model.add_rule(kind, col, rule) new_idx = self.model.move(new_idx, -(self.model.rowCount() - orig_row - 1)) self.rules_view.setCurrentIndex(new_idx) self.changed.emit() def add_rule(self): d = RuleEditor(self.model.fm, self.pref_name) d.add_blank_condition() if d.exec() == QDialog.DialogCode.Accepted: kind, col, r = d.rule if kind and r and col: selected_row = self.get_first_selected_row() idx = self.model.add_rule(kind, col, r, selected_row=selected_row) self.rules_view.scrollTo(idx) self.changed.emit() def add_advanced(self): selected_row = self.get_first_selected_row() if self.pref_name == 'column_color_rules': td = TemplateDialog(self, '', mi=self.mi, fm=self.fm, color_field='') if td.exec() == QDialog.DialogCode.Accepted: col, r = td.rule if r and col: idx = self.model.add_rule('color', col, r, selected_row=selected_row) self.rules_view.scrollTo(idx) self.changed.emit() else: if self.pref_name == 'cover_grid_icon_rules': td = TemplateDialog(self, '', mi=self.mi, fm=self.fm, doing_emblem=True) else: td = TemplateDialog(self, '', mi=self.mi, fm=self.fm, icon_field_key='') if td.exec() == QDialog.DialogCode.Accepted: typ, col, r = td.rule if typ and r and col: idx = self.model.add_rule(typ, col, r, selected_row=selected_row) self.rules_view.scrollTo(idx) self.changed.emit() def edit_rule(self, index): try: kind, col, rule = self.model.data(index, Qt.ItemDataRole.UserRole) except: return if isinstance(rule, Rule): d = RuleEditor(self.model.fm, self.pref_name) d.apply_rule(kind, col, rule) elif self.pref_name == 'column_color_rules': d = TemplateDialog(self, rule, mi=self.mi, fm=self.fm, color_field=col) elif self.pref_name == 'cover_grid_icon_rules': d = TemplateDialog(self, rule, mi=self.mi, fm=self.fm, doing_emblem=True) else: d = TemplateDialog(self, rule, mi=self.mi, fm=self.fm, icon_field_key=col, icon_rule_kind=kind) if d.exec() == QDialog.DialogCode.Accepted: if len(d.rule) == 2: # Convert template dialog rules to a triple d.rule = ('color', d.rule[0], d.rule[1]) kind, col, r = d.rule if kind and r is not None and col: self.model.replace_rule(index, kind, col, r) self.rules_view.scrollTo(index) self.changed.emit() def get_first_selected_row(self): r = self.get_selected_row('', show_error=False) if r: return r[-1] return None def get_selected_row(self, txt, show_error=True): sm = self.rules_view.selectionModel() rows = list(sm.selectedRows()) if not rows: if show_error: error_dialog(self, _('No rule selected'), _('No rule selected for %s.')%txt, show=True) return None return sorted(rows, reverse=True) def remove_rule(self): rows = self.get_selected_row(_('removal')) if rows is not None: for row in rows: self.model.remove_rule(row) self.changed.emit() def move_rows(self, moving_up=True): sm = self.rules_view.selectionModel() rows = sorted(list(sm.selectedRows()), reverse=not moving_up) if rows: if rows[0].row() == (0 if moving_up else self.model.rowCount() - 1): return sm.clear() indices_to_select = [] for idx in rows: if idx.isValid(): idx = self.model.move(idx, -1 if moving_up else 1) if idx is not None: indices_to_select.append(idx) if indices_to_select: new_selections = QItemSelection() for idx in indices_to_select: new_selections.merge(QItemSelection(idx, idx), QItemSelectionModel.SelectionFlag.Select) sm.select(new_selections, QItemSelectionModel.SelectionFlag.Select) self.rules_view.scrollTo(indices_to_select[0]) self.changed.emit() def clear(self): self.model.clear() self.changed.emit() def commit(self, prefs): self.model.commit(prefs) if self.pref_name == 'cover_grid_icon_rules': gprefs['show_emblems'] = self.enabled.isChecked() def export_rules(self): path = choose_save_file(self, 'export-coloring-rules', _('Choose file to export to'), filters=[(_('Rules'), ['rules'])], all_files=False, initial_filename=self.pref_name + '.rules') if path: rules = { 'version': self.model.EXIM_VERSION, 'type': self.model.pref_name, 'rules': self.model.rules_as_list(for_export=True) } data = json.dumps(rules, indent=2) if not isinstance(data, bytes): data = data.encode('utf-8') with open(path, 'wb') as f: f.write(data) def import_rules(self): files = choose_files(self, 'import-coloring-rules', _('Choose file to import from'), filters=[(_('Rules'), ['rules'])], all_files=False, select_only_single_file=True) if files: with open(files[0], 'rb') as f: raw = f.read() try: rules = json.loads(raw) if rules['version'] != self.model.EXIM_VERSION: raise ValueError('Unsupported rules version: {}'.format(rules['version'])) if rules['type'] != self.pref_name: raise ValueError('Rules are not of the correct type') rules = list(rules['rules']) except Exception as e: return error_dialog(self, _('No valid rules found'), _( 'No valid rules were found in {}.').format(files[0]), det_msg=as_unicode(e), show=True) self.model.import_rules(rules) self.changed.emit() # }}} if __name__ == '__main__': from calibre.gui2 import Application app = Application([]) from calibre.library import db db = db() if False: d = RuleEditor(db.field_metadata, 'column_icon_rules') d.add_blank_condition() d.exec() kind, col, r = d.rule print('Column to be colored:', col) print('Template:') print(r.template) else: d = EditRules() d.resize(QSize(800, 600)) d.initialize(db.field_metadata, db.prefs, None, 'column_color_rules') d.show() app.exec() d.commit(db.prefs)
55,192
Python
.py
1,222
32.693944
148
0.545904
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,792
history.py
kovidgoyal_calibre/src/calibre/gui2/preferences/history.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import textwrap from qt.core import QComboBox, Qt from calibre.gui2 import config as gui_conf class HistoryBox(QComboBox): def __init__(self, parent=None): QComboBox.__init__(self, parent) self.setEditable(True) def initialize(self, opt_name, default, help=None): self.opt_name = opt_name self.set_value(default) if help: self.setStatusTip(help) help = '\n'.join(textwrap.wrap(help)) self.setToolTip(help) self.setWhatsThis(help) def set_value(self, val): history = gui_conf[self.opt_name] if val not in history: history.append(val) self.clear() self.addItems(history) self.setCurrentIndex(self.findText(val, Qt.MatchFlag.MatchFixedString)) def save_history(self, opt_name): history = [str(self.itemText(i)) for i in range(self.count())] ct = self.text() if ct not in history: history = [ct] + history gui_conf[opt_name] = history[:10] def text(self): return str(self.currentText()).strip()
1,259
Python
.py
34
29.441176
79
0.628195
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,793
search.py
kovidgoyal_calibre/src/calibre/gui2/preferences/search.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from qt.core import QApplication, QTimer from calibre.gui2 import config, error_dialog, gprefs from calibre.gui2.preferences import AbortCommit, CommaSeparatedList, ConfigWidgetBase, test_widget from calibre.gui2.preferences.search_ui import Ui_Form from calibre.library.caches import set_use_primary_find_in_search from calibre.utils.config import prefs from calibre.utils.icu import lower as icu_lower from calibre.utils.icu import sort_key from polyglot.builtins import iteritems class ConfigWidget(ConfigWidgetBase, Ui_Form): def genesis(self, gui): self.gui = gui db = gui.library_view.model().db self.db = db r = self.register r('search_as_you_type', config) r('highlight_search_matches', config) r('show_highlight_toggle_button', gprefs) r('limit_search_columns', prefs) r('use_primary_find_in_search', prefs) r('search_tool_bar_shows_text', gprefs) r('allow_keyboard_search_in_library_views', gprefs) ossm = self.opt_saved_search_menu_is_hierarchical ossm.setChecked('search' in db.new_api.pref('categories_using_hierarchy', [])) ossm.stateChanged.connect(self.changed_signal) r('case_sensitive', prefs) fl = db.field_metadata.get_search_terms() r('limit_search_columns_to', prefs, setting=CommaSeparatedList, choices=fl) self.clear_history_button.clicked.connect(self.clear_histories) self.opt_use_primary_find_in_search.setToolTip(_( 'Searching will ignore accents on characters as well as punctuation and spaces.\nSo for example: {0} will match {1}').format( 'Penasthumb', 'Peña’s Thumb')) self.gst_explanation.setText('<p>' + _( "<b>Grouped search terms</b> are search names that permit a query to automatically " "search across more than one column. For example, if you create a grouped " "search term <code>allseries</code> with the value " "<code>series, #myseries, #myseries2</code>, then " "the query <code>allseries:adhoc</code> will find 'adhoc' in any of the " "columns <code>series</code>, <code>#myseries</code>, and " "<code>#myseries2</code>.<p> Enter the name of the " "grouped search term in the drop-down box, enter the list of columns " "to search in the value box, then push the Save button. " "<p>Note: Search terms are forced to lower case; <code>MySearch</code> " "and <code>mysearch</code> are the same term. Search terms cannot be " "hierarchical. Periods are not allowed in the term name." "<p>Grouped search terms can show as User categories in the Tag browser " "by adding the grouped search term names to the 'Make User " "categories from' box. Multiple terms are separated by commas. " "These 'automatic user categories' will be populated with items " "from the categories included in the grouped search term. " "<p>Automatic user categories permit you to see all the category items that " "are in the columns contained in the grouped search term. Using the above " "<code>allseries</code> example, the automatic user category " "will contain all the series names in <code>series</code>, " "<code>#myseries</code>, and <code>#myseries2</code>. This " "can be useful to check for duplicates, to find which column contains " "a particular item, or to have hierarchical categories (categories " "that contain categories). " "<p>Note: values from non-category columns such as comments won't appear " "in automatic user categories. ")) self.gst = db.prefs.get('grouped_search_terms', {}).copy() self.orig_gst_keys = list(self.gst.keys()) fm = db.new_api.field_metadata categories = [x for x in fm.keys() if not x.startswith('@') and fm[x]['search_terms']] self.gst_value.update_items_cache(categories) QTimer.singleShot(0, self.fill_gst_box) self.user_category_layout.setContentsMargins(0, 30, 0, 0) self.gst_names.lineEdit().setPlaceholderText( _('Enter new or select existing name')) self.gst_value.lineEdit().setPlaceholderText( _('Enter list of column lookup names to search')) self.category_fields = fl ml = [(_('Match any'), 'match_any'), (_('Match all'), 'match_all')] r('similar_authors_match_kind', db.prefs, choices=ml) r('similar_tags_match_kind', db.prefs, choices=ml) r('similar_series_match_kind', db.prefs, choices=ml) r('similar_publisher_match_kind', db.prefs, choices=ml) self.set_similar_fields(initial=True) self.similar_authors_search_key.currentIndexChanged.connect(self.something_changed) self.similar_tags_search_key.currentIndexChanged.connect(self.something_changed) self.similar_series_search_key.currentIndexChanged.connect(self.something_changed) self.similar_publisher_search_key.currentIndexChanged.connect(self.something_changed) self.gst_delete_button.setEnabled(False) self.gst_save_button.setEnabled(False) self.gst_names.currentIndexChanged.connect(self.gst_index_changed) self.gst_names.editTextChanged.connect(self.gst_text_changed) self.gst_value.textChanged.connect(self.gst_text_changed) self.gst_save_button.clicked.connect(self.gst_save_clicked) self.gst_delete_button.clicked.connect(self.gst_delete_clicked) self.gst_changed = False if db.prefs.get('grouped_search_make_user_categories', None) is None: db.new_api.set_pref('grouped_search_make_user_categories', []) r('grouped_search_make_user_categories', db.prefs, setting=CommaSeparatedList) self.muc_changed = False self.opt_grouped_search_make_user_categories.lineEdit().editingFinished.connect( self.muc_box_changed) def set_similar_fields(self, initial=False): self.set_similar('similar_authors_search_key', initial=initial) self.set_similar('similar_tags_search_key', initial=initial) self.set_similar('similar_series_search_key', initial=initial) self.set_similar('similar_publisher_search_key', initial=initial) def set_similar(self, name, initial=False): field = getattr(self, name) if not initial: val = field.currentText() else: val = self.db.prefs[name] field.blockSignals(True) field.clear() choices = [] choices.extend(self.category_fields) choices.extend(sorted(self.gst.keys(), key=sort_key)) field.addItems(choices) dex = field.findText(val) if dex >= 0: field.setCurrentIndex(dex) else: # The field no longer exists. Try the default dex = field.findText(self.db.prefs.defaults[name]) if dex >= 0: field.setCurrentIndex(dex) else: # The default doesn't exist! Pick the first field in the list field.setCurrentIndex(0) # Emit a changed signal after all the other events have been processed QTimer.singleShot(0, self.changed_signal.emit) field.blockSignals(False) def something_changed(self, dex): self.changed_signal.emit() def muc_box_changed(self): self.muc_changed = True def gst_save_clicked(self): idx = self.gst_names.currentIndex() name = icu_lower(str(self.gst_names.currentText())) if not name: return error_dialog(self.gui, _('Grouped search terms'), _('The search term name cannot be blank'), show=True) if ' ' in name or '.' in name: return error_dialog(self.gui, _('Invalid grouped search name'), _('The grouped search term name cannot contain spaces or periods'), show=True) if idx != 0: orig_name = str(self.gst_names.itemData(idx) or '') else: orig_name = '' if name != orig_name: if name in self.db.field_metadata.get_search_terms() and \ name not in self.orig_gst_keys: return error_dialog(self.gui, _('Grouped search terms'), _('That name is already used for a column or grouped search term'), show=True) if name in [icu_lower(p) for p in self.db.prefs.get('user_categories', {})]: return error_dialog(self.gui, _('Grouped search terms'), _('That name is already used for User category'), show=True) val = [v.strip() for v in str(self.gst_value.text()).split(',') if v.strip()] if not val: return error_dialog(self.gui, _('Grouped search terms'), _('The value box cannot be empty'), show=True) if orig_name and name != orig_name: del self.gst[orig_name] self.gst_changed = True self.gst[name] = val self.fill_gst_box(select=name) self.set_similar_fields(initial=False) self.changed_signal.emit() def gst_delete_clicked(self): if self.gst_names.currentIndex() == 0: return error_dialog(self.gui, _('Grouped search terms'), _('The empty grouped search term cannot be deleted'), show=True) name = str(self.gst_names.currentText()) if name in self.gst: del self.gst[name] self.fill_gst_box(select='') self.changed_signal.emit() self.gst_changed = True self.set_similar_fields(initial=False) def fill_gst_box(self, select=None): terms = sorted(self.gst.keys(), key=sort_key) self.opt_grouped_search_make_user_categories.update_items_cache(terms) self.gst_names.blockSignals(True) self.gst_names.clear() self.gst_names.addItem('', '') for t in terms: self.gst_names.addItem(t, t) self.gst_names.blockSignals(False) if select is not None: if select == '': self.gst_index_changed(0) elif select in terms: self.gst_names.setCurrentIndex(self.gst_names.findText(select)) def gst_text_changed(self): t = self.gst_names.currentText() self.gst_delete_button.setEnabled(len(t) > 0 and t in self.gst) self.gst_save_button.setEnabled(True) def gst_index_changed(self, idx): self.gst_delete_button.setEnabled(idx != 0) self.gst_save_button.setEnabled(False) self.gst_value.blockSignals(True) if idx == 0: self.gst_value.setText('') else: name = str(self.gst_names.itemData(idx) or '') self.gst_value.setText(','.join(self.gst[name])) self.gst_value.blockSignals(False) def commit(self): if self.opt_case_sensitive.isChecked() and self.opt_use_primary_find_in_search.isChecked(): error_dialog(self, _('Incompatible options'), _( 'The option to have un-accented characters match accented characters has no effect' ' if you also turn on case-sensitive searching. So only turn on one of those options'), show=True) raise AbortCommit() ucs = (m.strip() for m in self.opt_grouped_search_make_user_categories.text().split(',') if m.strip()) ucs -= (self.gst.keys()) if ucs: error_dialog(self, _('Missing grouped search terms'), _( 'The option "Make user categories from" contains names that ' "aren't grouped search terms: {}").format(', '.join(sorted(ucs))), show=True) raise AbortCommit() restart = ConfigWidgetBase.commit(self) if self.gst_changed or self.muc_changed: self.db.new_api.set_pref('grouped_search_terms', self.gst) self.db.field_metadata.add_grouped_search_terms(self.gst) self.db.new_api.set_pref('similar_authors_search_key', str(self.similar_authors_search_key.currentText())) self.db.new_api.set_pref('similar_tags_search_key', str(self.similar_tags_search_key.currentText())) self.db.new_api.set_pref('similar_series_search_key', str(self.similar_series_search_key.currentText())) self.db.new_api.set_pref('similar_publisher_search_key', str(self.similar_publisher_search_key.currentText())) cats = set(self.db.new_api.pref('categories_using_hierarchy', [])) if self.opt_saved_search_menu_is_hierarchical.isChecked(): cats.add('search') else: cats.discard('search') self.db.new_api.set_pref('categories_using_hierarchy', list(cats)) return restart def refresh_gui(self, gui): gui.refresh_search_bar_widgets() self.gui.bars_manager.update_bars() gui.current_db.new_api.clear_caches() set_use_primary_find_in_search(prefs['use_primary_find_in_search']) gui.set_highlight_only_button_icon() if self.gst_changed or self.muc_changed: gui.tags_view.model().reset_tag_browser() gui.search.search_as_you_type(config['search_as_you_type']) gui.search.do_search() def clear_histories(self, *args): for key, val in iteritems(config.defaults): if key.endswith('_search_history') and isinstance(val, list): config[key] = [] self.gui.search.clear_history() from calibre.gui2.widgets import history for key in ( 'bulk_edit_search_for', 'bulk_edit_replace_with', 'viewer-highlights-search-panel-expression', 'viewer-search-panel-expression', 'library-fts-search-box', ): history.set('lineedit_history_' + key, []) from calibre.gui2.viewer.config import vprefs for k in ('search', 'highlights'): vprefs.set(f'saved-{k}-settings', {}) from calibre.gui2.ui import get_gui gui = get_gui() if gui is not None: gui.iactions['Full Text Search'].clear_search_history() if __name__ == '__main__': app = QApplication([]) test_widget('Interface', 'Search')
14,545
Python
.py
273
43.091575
137
0.636606
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,794
device_debug.py
kovidgoyal_calibre/src/calibre/gui2/preferences/device_debug.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from qt.core import QApplication, QDialog, QDialogButtonBox, QIcon, QPlainTextEdit, QPushButton, QTimer, QVBoxLayout from calibre.gui2 import error_dialog class DebugDevice(QDialog): def __init__(self, gui, parent=None): QDialog.__init__(self, parent) self.gui = gui self._layout = QVBoxLayout(self) self.setLayout(self._layout) self.log = QPlainTextEdit(self) self._layout.addWidget(self.log) self.log.setPlainText(_('Getting debug information, please wait')+'...') self.copy = QPushButton(_('Copy to &clipboard')) self.copy.setDefault(True) self.setWindowTitle(_('Debug device detection')) self.setWindowIcon(QIcon.ic('debug.png')) self.copy.clicked.connect(self.copy_to_clipboard) self.ok = QPushButton('&OK') self.ok.setAutoDefault(False) self.ok.clicked.connect(self.accept) self.bbox = QDialogButtonBox(self) self.bbox.addButton(self.copy, QDialogButtonBox.ButtonRole.ActionRole) self.bbox.addButton(self.ok, QDialogButtonBox.ButtonRole.AcceptRole) self._layout.addWidget(self.bbox) self.resize(750, 500) self.bbox.setEnabled(False) QTimer.singleShot(1000, self.debug) def debug(self): if self.gui.device_manager.is_device_connected: error_dialog(self, _('Device already detected'), _('A device (%s) is already detected by calibre.' ' If you wish to debug the detection of another device' ', first disconnect this device.')% self.gui.device_manager.connected_device.get_gui_name(), show=True) self.bbox.setEnabled(True) return self.gui.debug_detection(self) def __call__(self, job): if not self.isVisible(): return self.bbox.setEnabled(True) if job.failed: return error_dialog(self, _('Debugging failed'), _('Running debug device detection failed. Click Show ' 'Details for more information.'), det_msg=job.details, show=True) self.log.setPlainText(job.result) def copy_to_clipboard(self): QApplication.clipboard().setText(self.log.toPlainText()) if __name__ == '__main__': app = QApplication([]) d = DebugDevice() d.exec()
2,579
Python
.py
57
35.385965
116
0.625349
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,795
toolbar.py
kovidgoyal_calibre/src/calibre/gui2/preferences/toolbar.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from qt.core import QAbstractItemView, QAbstractListModel, QIcon, QItemSelectionModel, Qt from calibre import force_unicode from calibre.gui2 import error_dialog, gprefs, warning_dialog from calibre.gui2.preferences import AbortCommit, ConfigWidgetBase, test_widget from calibre.gui2.preferences.toolbar_ui import Ui_Form from calibre.startup import connect_lambda from calibre.utils.icu import primary_sort_key def sort_key_for_action(ac): q = getattr(ac, 'action_spec', None) try: q = ac.name if q is None else q[0] return primary_sort_key(force_unicode(q)) except Exception: return primary_sort_key('') class FakeAction: def __init__(self, name, gui_name, icon, tooltip=None, dont_add_to=frozenset(), dont_remove_from=frozenset()): self.name = name self.action_spec = (gui_name, icon, tooltip, None) self.dont_remove_from = dont_remove_from self.dont_add_to = dont_add_to class BaseModel(QAbstractListModel): def name_to_action(self, name, gui): if name == 'Donate': return FakeAction( 'Donate', _('Donate'), 'donate.png', tooltip=_('Donate to support the development of calibre'), dont_add_to=frozenset(['context-menu', 'context-menu-device', 'searchbar'])) if name == 'Location Manager': return FakeAction('Location Manager', _('Location Manager'), 'reader.png', _('Switch between library and device views'), dont_add_to=frozenset(['menubar', 'toolbar', 'toolbar-child', 'context-menu', 'searchbar', 'context-menu-device'])) if name is None: return FakeAction('--- '+('Separator')+' ---', '--- '+_('Separator')+' ---', None, dont_add_to=frozenset(['menubar', 'menubar-device'])) try: return gui.iactions[name] except: return None def rowCount(self, parent): return len(self._data) def data(self, index, role): row = index.row() action = self._data[row].action_spec if role == Qt.ItemDataRole.DisplayRole: text = action[0] text = text.replace('&', '') if text == _('%d books'): text = _('Choose library') return (text) if role == Qt.ItemDataRole.DecorationRole: if hasattr(self._data[row], 'qaction'): icon = self._data[row].qaction.icon() if not icon.isNull(): return (icon) ic = action[1] if ic is None: ic = 'blank.png' return (QIcon.ic(ic)) if role == Qt.ItemDataRole.ToolTipRole and action[2] is not None: return (action[2]) return None def names(self, indexes): rows = [i.row() for i in indexes] ans = [] for i in rows: n = self._data[i].name if n.startswith('---'): n = None ans.append(n) return ans def has_action(self, name): for a in self._data: if a.name == name: return True return False class AllModel(BaseModel): def __init__(self, key, gui): BaseModel.__init__(self) self.gprefs_name = 'action-layout-'+key current = gprefs[self.gprefs_name] self.gui = gui self.key = key self._data = self.get_all_actions(current) def get_all_actions(self, current): all = list(self.gui.iactions.keys()) + ['Donate', 'Location Manager'] all = [x for x in all if x not in current] + [None] all = [self.name_to_action(x, self.gui) for x in all] all = [x for x in all if self.key not in x.dont_add_to] all.sort(key=sort_key_for_action) return all def add(self, names): actions = [] for name in names: if name is None or name.startswith('---'): continue actions.append(self.name_to_action(name, self.gui)) self.beginResetModel() self._data.extend(actions) self._data.sort(key=sort_key_for_action) self.endResetModel() def remove(self, indices, allowed): rows = [i.row() for i in indices] remove = set() for row in rows: ac = self._data[row] if ac.name.startswith('---'): continue if ac.name in allowed: remove.add(row) ndata = [] for i, ac in enumerate(self._data): if i not in remove: ndata.append(ac) self.beginResetModel() self._data = ndata self.endResetModel() def restore_defaults(self): current = gprefs.defaults[self.gprefs_name] self.beginResetModel() self._data = self.get_all_actions(current) self.endResetModel() class CurrentModel(BaseModel): def __init__(self, key, gui): BaseModel.__init__(self) self.gprefs_name = 'action-layout-'+key current = gprefs[self.gprefs_name] self._data = [self.name_to_action(x, gui) for x in current] self._data = [x for x in self._data if x is not None] self.key = key self.gui = gui def move_single(self, idx, delta): row = idx.row() nrow = (row + delta + len(self._data)) % len(self._data) if row + delta < 0: x = self._data.pop(row) self._data.append(x) elif row + delta >= len(self._data): x = self._data.pop(row) self._data.insert(0, x) else: self._data[row], self._data[nrow] = self._data[nrow], self._data[row] def move_many(self, indices, delta): rows = [i.row() for i in indices] items = [self._data[x.row()] for x in indices] self.beginResetModel() indices = sorted(indices, key=lambda i: i.row(), reverse=delta > 0) for item in items: self.move_single(self.index(self._data.index(item)), delta) self.endResetModel() ans = {} for item, row in zip(items, rows): ans[row] = self.index(self._data.index(item)) return ans def add(self, names): actions = [] reject = set() for name in names: ac = self.name_to_action(name, self.gui) if self.key in ac.dont_add_to: reject.add(ac) else: actions.append(ac) self.beginResetModel() self._data.extend(actions) self.endResetModel() return reject def remove(self, indices): rows = [i.row() for i in indices] remove, rejected = set(), set() for row in rows: ac = self._data[row] if self.key in ac.dont_remove_from: rejected.add(ac) continue remove.add(row) ndata = [] for i, ac in enumerate(self._data): if i not in remove: ndata.append(ac) self.beginResetModel() self._data = ndata self.endResetModel() return rejected def commit(self): old = gprefs[self.gprefs_name] new = [] for x in self._data: n = x.name if n.startswith('---'): n = None new.append(n) new = tuple(new) if new != old: defaults = gprefs.defaults[self.gprefs_name] if defaults == new: del gprefs[self.gprefs_name] else: gprefs[self.gprefs_name] = new def restore_defaults(self): current = gprefs.defaults[self.gprefs_name] self.beginResetModel() self._data = [self.name_to_action(x, self.gui) for x in current] self.endResetModel() class ConfigWidget(ConfigWidgetBase, Ui_Form): LOCATIONS = [ ('toolbar', _('The main toolbar')), ('toolbar-device', _('The main toolbar when a device is connected')), ('toolbar-child', _('The optional second toolbar')), ('searchbar', _('The buttons on the search bar')), ('menubar', _('The menubar')), ('menubar-device', _('The menubar when a device is connected')), ('context-menu', _('The context menu for the books in the ' 'calibre library')), ('context-menu-split', _('The context menu for the split book list')), ('context-menu-device', _('The context menu for the books on ' 'the device')), ('context-menu-cover-browser', _('The context menu for the Cover ' 'browser')), ] def genesis(self, gui): self.all_actions.doubleClicked.connect(self.add_single_action) self.current_actions.doubleClicked.connect(self.remove_single_action) self.models = {} self.what.addItem(_('Click to choose toolbar or menu to customize'), 'blank') for key, text in self.LOCATIONS: self.what.addItem(text, key) all_model = AllModel(key, gui) current_model = CurrentModel(key, gui) self.models[key] = (all_model, current_model) self.what.setCurrentIndex(0) self.what.currentIndexChanged.connect(self.what_changed) self.what_changed(0) self.add_action_button.clicked.connect(self.add_action) self.remove_action_button.clicked.connect(self.remove_action) connect_lambda(self.action_up_button.clicked, self, lambda self: self.move(-1)) connect_lambda(self.action_down_button.clicked, self, lambda self: self.move(1)) self.all_actions.setMouseTracking(True) self.current_actions.setMouseTracking(True) self.all_actions.entered.connect(self.all_entered) self.current_actions.entered.connect(self.current_entered) def all_entered(self, index): tt = self.all_actions.model().data(index, Qt.ItemDataRole.ToolTipRole) or '' self.help_text.setText(tt) def current_entered(self, index): tt = self.current_actions.model().data(index, Qt.ItemDataRole.ToolTipRole) or '' self.help_text.setText(tt) def what_changed(self, idx): key = str(self.what.itemData(idx) or '') if key == 'blank': self.actions_widget.setVisible(False) self.spacer_widget.setVisible(True) else: self.actions_widget.setVisible(True) self.spacer_widget.setVisible(False) self.all_actions.setModel(self.models[key][0]) self.current_actions.setModel(self.models[key][1]) def add_action(self, *args): self._add_action(self.all_actions.selectionModel().selectedIndexes()) def add_single_action(self, index): self._add_action([index]) def _add_action(self, indices): names = self.all_actions.model().names(indices) if names: not_added = self.current_actions.model().add(names) ns = {y.name for y in not_added} added = set(names) - ns self.all_actions.model().remove(indices, added) if not_added: warning_dialog(self, _('Cannot add'), _('Cannot add the actions %s to this location') % ','.join([a.action_spec[0] for a in not_added]), show=True) if added: ca = self.current_actions idx = ca.model().index(ca.model().rowCount(None)-1) ca.scrollTo(idx) self.changed_signal.emit() def remove_action(self, *args): self._remove_action(self.current_actions.selectionModel().selectedIndexes()) def remove_single_action(self, index): self._remove_action([index]) def _remove_action(self, indices): names = self.current_actions.model().names(indices) if names: not_removed = self.current_actions.model().remove(indices) ns = {y.name for y in not_removed} removed = set(names) - ns self.all_actions.model().add(removed) if not_removed: warning_dialog(self, _('Cannot remove'), _('Cannot remove the actions %s from this location') % ','.join([a.action_spec[0] for a in not_removed]), show=True) else: self.changed_signal.emit() def move(self, delta, *args): sm = self.current_actions.selectionModel() x = sm.selectedIndexes() if x and len(x): i = sm.currentIndex().row() m = self.current_actions.model() idx_map = m.move_many(x, delta) newci = idx_map.get(i) sm.clear() for idx in idx_map.values(): sm.select(idx, QItemSelectionModel.SelectionFlag.Select) if newci is not None: sm.setCurrentIndex(newci, QItemSelectionModel.SelectionFlag.SelectCurrent) if newci is not None: self.current_actions.scrollTo(newci, QAbstractItemView.ScrollHint.EnsureVisible) self.changed_signal.emit() def commit(self): # Ensure preferences are showing in either the toolbar or # the menubar. pref_in_toolbar = self.models['toolbar'][1].has_action('Preferences') pref_in_menubar = self.models['menubar'][1].has_action('Preferences') lm_in_toolbar = self.models['toolbar-device'][1].has_action('Location Manager') lm_in_menubar = self.models['menubar-device'][1].has_action('Location Manager') if not pref_in_toolbar and not pref_in_menubar: error_dialog(self, _('Preferences missing'), _( 'The Preferences action must be in either the main toolbar or the menubar.'), show=True) raise AbortCommit() if not lm_in_toolbar and not lm_in_menubar: error_dialog(self, _('Location manager missing'), _( 'The Location manager must be in either the main toolbar or the menubar when a device is connected.'), show=True) raise AbortCommit() # Save data. for am, cm in self.models.values(): cm.commit() return False def restore_defaults(self): for am, cm in self.models.values(): cm.restore_defaults() am.restore_defaults() self.changed_signal.emit() def refresh_gui(self, gui): gui.bars_manager.init_bars() gui.bars_manager.update_bars() if __name__ == '__main__': from calibre.gui2 import Application app = Application([]) test_widget('Interface', 'Toolbar')
14,993
Python
.py
350
32.102857
129
0.576638
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,796
save_template.py
kovidgoyal_calibre/src/calibre/gui2/preferences/save_template.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from qt.core import QWidget, pyqtSignal from calibre.gui2 import error_dialog, question_dialog from calibre.gui2.dialogs.template_dialog import TemplateDialog from calibre.gui2.preferences.save_template_ui import Ui_Form from calibre.library.save_to_disk import FORMAT_ARG_DESCS, preprocess_template from calibre.utils.formatter import validation_formatter class SaveTemplate(QWidget, Ui_Form): changed_signal = pyqtSignal() def __init__(self, parent=None): QWidget.__init__(self, parent) Ui_Form.__init__(self) self.setupUi(self) self.orig_help_text = self.help_label.text() def initialize(self, name, default, help, field_metadata): variables = sorted(FORMAT_ARG_DESCS.keys()) if name == 'send_to_device': self.help_label.setText(self.orig_help_text + ' ' + _( 'This setting can be overridden for <b>individual devices</b>,' ' by clicking the device icon and choosing "Configure this device".')) rows = [] for var in variables: rows.append('<tr><td>%s</td><td>&nbsp;</td><td>%s</td></tr>'% (var, FORMAT_ARG_DESCS[var])) rows.append('<tr><td>%s&nbsp;</td><td>&nbsp;</td><td>%s</td></tr>'%( _('Any custom field'), _('The lookup name of any custom field (these names begin with "#").'))) table = '<table>%s</table>'%('\n'.join(rows)) self.template_variables.setText(table) self.field_metadata = field_metadata self.opt_template.initialize(name+'_template_history', default, help) self.opt_template.editTextChanged.connect(self.changed) self.opt_template.currentIndexChanged.connect(self.changed) self.option_name = name self.open_editor.clicked.connect(self.do_open_editor) def do_open_editor(self): # Try to get selected books from calibre.gui2.ui import get_gui db = get_gui().current_db view = get_gui().library_view mi = tuple(map(db.new_api.get_proxy_metadata, view.get_selected_ids()[:10])) if not mi: error_dialog(self, _('Must select books'), _('One or more books must be selected so the template ' 'editor can show the template results'), show=True) return t = TemplateDialog(self, self.opt_template.text(), fm=self.field_metadata, mi=mi) t.setWindowTitle(_('Edit template')) if t.exec(): self.opt_template.set_value(t.rule[1]) def changed(self, *args): self.changed_signal.emit() def validate(self): ''' Do a syntax check on the format string. Doing a semantic check (verifying that the fields exist) is not useful in the presence of custom fields, because they may or may not exist. ''' tmpl = preprocess_template(self.opt_template.text()) # Allow PTM or GPM templates without checking if tmpl.startswith(('program:', 'python:')): return True try: t = validation_formatter.validate(tmpl) if t.find(validation_formatter._validation_string) < 0: return question_dialog(self, _('Constant template'), _('The template contains no {fields}, so all ' 'books will have the same name. Is this OK?')) except Exception as err: error_dialog(self, _('Invalid template'), '<p>'+_('The template %s is invalid:')%tmpl + '<br>'+str(err), show=True) return False return True def set_value(self, val): self.opt_template.set_value(val) def save_settings(self, config, name): val = str(self.opt_template.text()) config.set(name, val) self.opt_template.save_history(self.option_name+'_template_history')
4,081
Python
.py
84
38.714286
89
0.615018
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,797
plugboard.py
kovidgoyal_calibre/src/calibre/gui2/preferences/plugboard.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import copy from collections import defaultdict from qt.core import QComboBox, QListWidgetItem, Qt from calibre.customize.ui import device_plugins, disabled_device_plugins, is_disabled, metadata_writers from calibre.gui2 import error_dialog, question_dialog, warning_dialog from calibre.gui2.device import device_name_for_plugboards from calibre.gui2.dialogs.template_line_editor import TemplateLineEditor from calibre.gui2.email import plugboard_email_formats, plugboard_email_value from calibre.gui2.preferences import ConfigWidgetBase, test_widget from calibre.gui2.preferences.plugboard_ui import Ui_Form from calibre.library.save_to_disk import find_plugboard, plugboard_any_device_value, plugboard_any_format_value, plugboard_save_to_disk_value from calibre.srv.content import plugboard_content_server_formats, plugboard_content_server_value from calibre.utils.formatter import validation_formatter class ConfigWidget(ConfigWidgetBase, Ui_Form): def genesis(self, gui): self.gui = gui self.db = gui.library_view.model().db def initialize(self): ConfigWidgetBase.initialize(self) self.current_plugboards = copy.deepcopy(self.db.prefs.get('plugboards',{})) self.current_device = None self.current_format = None if self.gui.device_manager.connected_device is not None: self.device_label.setText(_('Device currently connected: ') + self.gui.device_manager.connected_device.__class__.__name__) else: self.device_label.setText(_('Device currently connected: None')) self.devices = ['', 'APPLE', 'FOLDER_DEVICE'] self.disabled_devices = [] self.device_to_formats_map = {} for device in device_plugins(): n = device_name_for_plugboards(device) self.device_to_formats_map[n] = set(device.settings().format_map) if getattr(device, 'CAN_DO_DEVICE_DB_PLUGBOARD', False): self.device_to_formats_map[n].add('device_db') if n not in self.devices: self.devices.append(n) for device in disabled_device_plugins(): n = device_name_for_plugboards(device) if n not in self.disabled_devices: self.disabled_devices.append(n) self.devices.sort(key=lambda x: x.lower()) self.devices.insert(1, plugboard_save_to_disk_value) self.devices.insert(1, plugboard_content_server_value) self.device_to_formats_map[plugboard_content_server_value] = \ plugboard_content_server_formats self.devices.insert(1, plugboard_email_value) self.device_to_formats_map[plugboard_email_value] = \ plugboard_email_formats self.devices.insert(1, plugboard_any_device_value) self.new_device.addItems(self.devices) self.formats = [''] self.format_to_writers_map = defaultdict(list) for w in metadata_writers(): for f in w.file_types: if f not in self.formats: self.formats.append(f) self.format_to_writers_map[f].append(w) self.formats.append('device_db') self.formats.sort() self.formats.insert(1, plugboard_any_format_value) self.new_format.addItems(self.formats) self.dest_fields = ['', 'authors', 'author_sort', 'language', 'publisher', 'series', 'series_index', 'tags', 'title', 'title_sort', 'comments'] self.source_widgets = [] self.dest_widgets = [] for i in range(0, len(self.dest_fields)-1): w = TemplateLineEditor(self) self.source_widgets.append(w) self.fields_layout.addWidget(w, 5+i, 0, 1, 1) w = QComboBox(self) self.dest_widgets.append(w) self.fields_layout.addWidget(w, 5+i, 1, 1, 1) self.edit_device.currentIndexChanged.connect(self.edit_device_changed) self.edit_format.currentIndexChanged.connect(self.edit_format_changed) self.new_device.currentIndexChanged.connect(self.new_device_changed) self.new_format.currentIndexChanged.connect(self.new_format_changed) self.existing_plugboards.itemClicked.connect(self.existing_pb_clicked) self.ok_button.clicked.connect(self.ok_clicked) self.del_button.clicked.connect(self.del_clicked) self.refilling = False self.refill_all_boxes() def clear_fields(self, edit_boxes=False, new_boxes=False): self.ok_button.setEnabled(False) self.del_button.setEnabled(False) for w in self.source_widgets: w.clear() for w in self.dest_widgets: w.clear() if edit_boxes: self.edit_device.setCurrentIndex(0) self.edit_format.setCurrentIndex(0) if new_boxes: self.new_device.setCurrentIndex(0) self.new_format.setCurrentIndex(0) def set_fields(self): self.ok_button.setEnabled(True) self.del_button.setEnabled(True) for w in self.source_widgets: w.clear() for w in self.dest_widgets: w.addItems(self.dest_fields) def set_field(self, i, src, dst): self.source_widgets[i].setText(src) idx = self.dest_fields.index(dst) self.dest_widgets[i].setCurrentIndex(idx) def edit_device_changed(self, idx): txt = self.edit_device.currentText() self.current_device = None if txt == '': self.clear_fields(new_boxes=False) return self.clear_fields(new_boxes=True) self.current_device = str(txt) fpb = self.current_plugboards.get(self.current_format, None) if fpb is None: print('edit_device_changed: none format!') return dpb = fpb.get(self.current_device, None) if dpb is None: print('edit_device_changed: none device!') return self.set_fields() for i,op in enumerate(dpb): self.set_field(i, op[0], op[1]) self.ok_button.setEnabled(True) self.del_button.setEnabled(True) def edit_format_changed(self, idx): txt = self.edit_format.currentText() self.edit_device.setCurrentIndex(0) self.current_device = None self.current_format = None if txt == '': self.clear_fields(new_boxes=False) return self.clear_fields(new_boxes=True) txt = str(txt) fpb = self.current_plugboards.get(txt, None) if fpb is None: print('edit_format_changed: none editable format!') return self.current_format = txt self.check_if_writer_disabled(txt) devices = [''] for d in fpb: devices.append(d) self.edit_device.clear() self.edit_device.addItems(devices) def check_if_writer_disabled(self, format_name): if format_name in ['device_db', plugboard_any_format_value]: return show_message = True for writer in self.format_to_writers_map[format_name]: if not is_disabled(writer): show_message = False if show_message: warning_dialog(self, '', _('That format has no metadata writers enabled. A plugboard ' 'will probably have no effect.'), show=True) def new_device_changed(self, idx): txt = self.new_device.currentText() self.current_device = None if txt == '': self.clear_fields(edit_boxes=False) return self.clear_fields(edit_boxes=True) self.current_device = str(txt) if self.current_format in self.current_plugboards and \ self.current_device in self.current_plugboards[self.current_format]: error_dialog(self, '', _('That format and device already has a plugboard.'), show=True) self.new_device.setCurrentIndex(0) return # If we have a specific format/device combination, check if a more # general combination matches. if self.current_format != plugboard_any_format_value and \ self.current_device != plugboard_any_device_value: if find_plugboard(self.current_device, self.current_format, self.current_plugboards): if not question_dialog(self.gui, _('Possibly override plugboard?'), _('A more general plugboard already exists for ' 'that format and device. ' 'Are you sure you want to add the new plugboard?')): self.new_device.setCurrentIndex(0) return # If we have a specific format, check if we are adding a possibly- # covered plugboard if self.current_format != plugboard_any_format_value: if self.current_format in self.current_plugboards: if self.current_device == plugboard_any_device_value: if not question_dialog(self.gui, _('Add possibly overridden plugboard?'), _('More specific device plugboards exist for ' 'that format. ' 'Are you sure you want to add the new plugboard?')): self.new_device.setCurrentIndex(0) return # We are adding an 'any format' entry. Check if we are adding a specific # device and if so, does some other plugboard match that device. elif self.current_device != plugboard_any_device_value: for fmt in self.current_plugboards: if find_plugboard(self.current_device, fmt, self.current_plugboards): if not question_dialog(self.gui, _('Really add plugboard?'), _('A different plugboard matches that format and ' 'device combination. ' 'Are you sure you want to add the new plugboard?')): self.new_device.setCurrentIndex(0) return # We are adding an any format/any device entry, which will be overridden # by any other entry. Ask if such entries exist. elif len(self.current_plugboards): if not question_dialog(self.gui, _('Add possibly overridden plugboard?'), _('More specific format and device plugboards ' 'already exist. ' 'Are you sure you want to add the new plugboard?')): self.new_device.setCurrentIndex(0) return if self.current_format != plugboard_any_format_value and \ self.current_device in self.device_to_formats_map: allowable_formats = self.device_to_formats_map[self.current_device] if self.current_format not in allowable_formats: error_dialog(self, '', _('The {0} device does not support the {1} format.'). format(self.current_device, self.current_format), show=True) self.new_device.setCurrentIndex(0) return if self.current_format == plugboard_any_format_value and \ self.current_device == plugboard_content_server_value: warning_dialog(self, '', _('The {0} device supports only the {1} format(s).'). format(plugboard_content_server_value, ', '.join(plugboard_content_server_formats)), show=True) self.set_fields() def new_format_changed(self, idx): txt = self.new_format.currentText() self.current_format = None self.current_device = None self.new_device.setCurrentIndex(0) if txt: self.clear_fields(edit_boxes=True) self.current_format = str(txt) self.check_if_writer_disabled(self.current_format) else: self.clear_fields(edit_boxes=False) def ok_clicked(self): pb = [] comments_in_dests = False for i in range(0, len(self.source_widgets)): s = str(self.source_widgets[i].text()) if s: d = self.dest_widgets[i].currentIndex() if d != 0: try: validation_formatter.validate(s) except Exception as err: error_dialog(self, _('Invalid template'), '<p>'+_('The template %s is invalid:')%s + '<br>'+str(err), show=True) return pb.append((s, self.dest_fields[d])) comments_in_dests = comments_in_dests or self.dest_fields[d] == 'comments' else: error_dialog(self, _('Invalid destination'), '<p>'+_('The destination field cannot be blank'), show=True) return if len(pb) == 0: if self.current_format in self.current_plugboards: fpb = self.current_plugboards[self.current_format] if self.current_device in fpb: del fpb[self.current_device] if len(fpb) == 0: del self.current_plugboards[self.current_format] else: if comments_in_dests and not question_dialog(self.gui, _('Plugboard modifies comments'), _('This plugboard modifies the comments metadata. ' 'If the comments are set to invalid HTML, it could cause problems on the device. ' 'Are you sure you wish to save this plugboard?' ), skip_dialog_name='plugboard_comments_in_dests' ): return if self.current_format not in self.current_plugboards: self.current_plugboards[self.current_format] = {} fpb = self.current_plugboards[self.current_format] fpb[self.current_device] = pb self.changed_signal.emit() self.refill_all_boxes() def del_clicked(self): if self.current_format in self.current_plugboards: fpb = self.current_plugboards[self.current_format] if self.current_device in fpb: del fpb[self.current_device] if len(fpb) == 0: del self.current_plugboards[self.current_format] self.changed_signal.emit() self.refill_all_boxes() def existing_pb_clicked(self, qitem): item = qitem.data(Qt.ItemDataRole.UserRole) if (qitem.flags() & Qt.ItemFlag.ItemIsEnabled): self.edit_format.setCurrentIndex(self.edit_format.findText(item[0])) self.edit_device.setCurrentIndex(self.edit_device.findText(item[1])) else: warning_dialog(self, '', _('The {0} device plugin is disabled.').format(item[1]), show=True) def refill_all_boxes(self): if self.refilling: return self.refilling = True self.current_device = None self.current_format = None self.clear_fields(new_boxes=True) self.edit_format.clear() self.edit_format.addItem('') for format_ in self.current_plugboards: self.edit_format.addItem(format_) self.edit_format.setCurrentIndex(0) self.edit_device.clear() self.ok_button.setEnabled(False) self.del_button.setEnabled(False) self.existing_plugboards.clear() for f in self.formats: if f not in self.current_plugboards: continue for d in sorted(self.devices + self.disabled_devices, key=lambda x:x.lower()): if d not in self.current_plugboards[f]: continue ops = [] for op in self.current_plugboards[f][d]: ops.append('([' + op[0] + '] -> ' + op[1] + ')') txt = '%s:%s = %s\n'%(f, d, ', '.join(ops)) item = QListWidgetItem(txt) item.setData(Qt.ItemDataRole.UserRole, (f, d)) if d in self.disabled_devices: item.setFlags(item.flags() & ~Qt.ItemFlag.ItemIsEnabled) self.existing_plugboards.addItem(item) self.refilling = False def restore_defaults(self): ConfigWidgetBase.restore_defaults(self) self.current_plugboards = {} self.refill_all_boxes() self.changed_signal.emit() def commit(self): self.db.new_api.set_pref('plugboards', self.current_plugboards) return ConfigWidgetBase.commit(self) def refresh_gui(self, gui): pass if __name__ == '__main__': from qt.core import QApplication app = QApplication([]) test_widget('Import/Export', 'Plugboard')
17,530
Python
.py
363
35.192837
141
0.584642
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,798
__init__.py
kovidgoyal_calibre/src/calibre/gui2/preferences/__init__.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import textwrap from qt.core import ( QAbstractSpinBox, QApplication, QCheckBox, QComboBox, QDialog, QDialogButtonBox, QEvent, QIcon, QLineEdit, QListView, QListWidget, Qt, QTableWidget, QVBoxLayout, QWidget, pyqtSignal, ) from calibre.customize.ui import preferences_plugins from calibre.gui2.complete2 import EditWithComplete from calibre.gui2.widgets import HistoryLineEdit from calibre.utils.config import ConfigProxy from polyglot.builtins import string_or_bytes class AbortCommit(Exception): pass class AbortInitialize(Exception): pass class ConfigWidgetInterface: ''' This class defines the interface that all widgets displayed in the Preferences dialog must implement. See :class:`ConfigWidgetBase` for a base class that implements this interface and defines various convenience methods as well. ''' #: This signal must be emitted whenever the user changes a value in this #: widget changed_signal = None #: Set to True iff the :meth:`restore_to_defaults` method is implemented. supports_restoring_to_defaults = True #: The tooltip for the "Restore defaults" button restore_defaults_desc = _('Restore settings to default values. ' 'You have to click Apply to actually save the default settings.') #: If True the Preferences dialog will not allow the user to set any more #: preferences. Only has effect if :meth:`commit` returns True. restart_critical = False def genesis(self, gui): ''' Called once before the widget is displayed, should perform any necessary setup. :param gui: The main calibre graphical user interface ''' raise NotImplementedError() def initialize(self): ''' Should set all config values to their initial values (the values stored in the config files). A "return" statement is optional. Return False if the dialog is not to be shown. ''' raise NotImplementedError() def restore_defaults(self): ''' Should set all config values to their defaults. ''' pass def commit(self): ''' Save any changed settings. Return True if the changes require a restart, False otherwise. Raise an :class:`AbortCommit` exception to indicate that an error occurred. You are responsible for giving the user feedback about what the error is and how to correct it. ''' return False def refresh_gui(self, gui): ''' Called once after this widget is committed. Responsible for causing the gui to reread any changed settings. Note that by default the GUI re-initializes various elements anyway, so most widgets won't need to use this method. ''' pass def initial_tab_changed(self): ''' Called if the initially displayed tab is changed before the widget is shown, but after it is initialized. ''' pass def set_help_tips(gui_obj, tt): if tt: if not str(gui_obj.whatsThis()): gui_obj.setWhatsThis(tt) if not str(gui_obj.statusTip()): gui_obj.setStatusTip(tt) tt = '\n'.join(textwrap.wrap(tt, 70)) gui_obj.setToolTip(tt) class Setting: CHOICES_SEARCH_FLAGS = Qt.MatchFlag.MatchExactly | Qt.MatchFlag.MatchCaseSensitive def __init__(self, name, config_obj, widget, gui_name=None, empty_string_is_None=True, choices=None, restart_required=False): self.name, self.gui_name = name, gui_name self.empty_string_is_None = empty_string_is_None self.restart_required = restart_required self.choices = choices if gui_name is None: self.gui_name = 'opt_'+name self.config_obj = config_obj self.gui_obj = getattr(widget, self.gui_name) self.widget = widget if isinstance(self.gui_obj, QCheckBox): self.datatype = 'bool' self.gui_obj.stateChanged.connect(self.changed) elif isinstance(self.gui_obj, QAbstractSpinBox): self.datatype = 'number' self.gui_obj.valueChanged.connect(self.changed) elif isinstance(self.gui_obj, (QLineEdit, HistoryLineEdit)): self.datatype = 'string' self.gui_obj.textChanged.connect(self.changed) if isinstance(self.gui_obj, HistoryLineEdit): self.gui_obj.initialize('preferences_setting_' + self.name) elif isinstance(self.gui_obj, QComboBox): self.datatype = 'choice' self.gui_obj.editTextChanged.connect(self.changed) self.gui_obj.currentIndexChanged.connect(self.changed) else: raise ValueError('Unknown data type %s' % self.gui_obj.__class__) if isinstance(self.config_obj, ConfigProxy) and \ not str(self.gui_obj.toolTip()): h = self.config_obj.help(self.name) if h: self.gui_obj.setToolTip(h) tt = str(self.gui_obj.toolTip()) set_help_tips(self.gui_obj, tt) def changed(self, *args): self.widget.changed_signal.emit() def initialize(self): self.gui_obj.blockSignals(True) if self.datatype == 'choice': choices = self.choices or [] if isinstance(self.gui_obj, EditWithComplete): self.gui_obj.all_items = choices else: self.gui_obj.clear() for x in choices: if isinstance(x, string_or_bytes): x = (x, x) self.gui_obj.addItem(x[0], (x[1])) self.set_gui_val(self.get_config_val(default=False)) self.gui_obj.blockSignals(False) self.initial_value = self.get_gui_val() def commit(self): val = self.get_gui_val() oldval = self.get_config_val() changed = val != oldval if changed: self.set_config_val(self.get_gui_val()) return changed and self.restart_required def restore_defaults(self): self.set_gui_val(self.get_config_val(default=True)) def get_config_val(self, default=False): if default: val = self.config_obj.defaults[self.name] else: val = self.config_obj[self.name] return val def set_config_val(self, val): self.config_obj[self.name] = val def set_gui_val(self, val): if self.datatype == 'bool': self.gui_obj.setChecked(bool(val)) elif self.datatype == 'number': self.gui_obj.setValue(val) elif self.datatype == 'string': self.gui_obj.setText(val if val else '') elif self.datatype == 'choice': if isinstance(self.gui_obj, EditWithComplete): self.gui_obj.setText(val) else: idx = self.gui_obj.findData((val), role=Qt.ItemDataRole.UserRole, flags=self.CHOICES_SEARCH_FLAGS) if idx == -1: idx = 0 self.gui_obj.setCurrentIndex(idx) def get_gui_val(self): if self.datatype == 'bool': val = bool(self.gui_obj.isChecked()) elif self.datatype == 'number': val = self.gui_obj.value() elif self.datatype == 'string': val = str(self.gui_obj.text()).strip() if self.empty_string_is_None and not val: val = None elif self.datatype == 'choice': if isinstance(self.gui_obj, EditWithComplete): val = str(self.gui_obj.text()) else: idx = self.gui_obj.currentIndex() if idx < 0: idx = 0 val = str(self.gui_obj.itemData(idx) or '') return val class CommaSeparatedList(Setting): def set_gui_val(self, val): x = '' if val: x = ', '.join(val) self.gui_obj.setText(x) def get_gui_val(self): val = str(self.gui_obj.text()).strip() ans = [] if val: ans = [x.strip() for x in val.split(',')] ans = [x for x in ans if x] return ans class ConfigWidgetBase(QWidget, ConfigWidgetInterface): ''' Base class that contains code to easily add standard config widgets like checkboxes, combo boxes, text fields and so on. See the :meth:`register` method. This class automatically handles change notification, resetting to default, translation between gui objects and config objects, etc. for registered settings. If your config widget inherits from this class but includes setting that are not registered, you should override the :class:`ConfigWidgetInterface` methods and call the base class methods inside the overrides. ''' changed_signal = pyqtSignal() restart_now = pyqtSignal() supports_restoring_to_defaults = True restart_critical = False def __init__(self, parent=None): QWidget.__init__(self, parent) if hasattr(self, 'setupUi'): self.setupUi(self) self.settings = {} def register(self, name, config_obj, gui_name=None, choices=None, restart_required=False, empty_string_is_None=True, setting=Setting): ''' Register a setting. :param name: The setting name :param config_obj: The config object that reads/writes the setting :param gui_name: The name of the GUI object that presents an interface to change the setting. By default it is assumed to be ``'opt_' + name``. :param choices: If this setting is a multiple choice (combobox) based setting, the list of choices. The list is a list of two element tuples of the form: ``[(gui name, value), ...]`` :param setting: The class responsible for managing this setting. The default class handles almost all cases, so this param is rarely used. ''' setting = setting(name, config_obj, self, gui_name=gui_name, choices=choices, restart_required=restart_required, empty_string_is_None=empty_string_is_None) return self.register_setting(setting) def register_setting(self, setting): self.settings[setting.name] = setting return setting def initialize(self): for setting in self.settings.values(): setting.initialize() def commit(self, *args): restart_required = False for setting in self.settings.values(): rr = setting.commit() if rr: restart_required = True return restart_required def restore_defaults(self, *args): for setting in self.settings.values(): setting.restore_defaults() def get_plugin(category, name): for plugin in preferences_plugins(): if plugin.category == category and plugin.name == name: return plugin raise ValueError( 'No Preferences Plugin with category: %s and name: %s found' % (category, name)) class ConfigDialog(QDialog): def set_widget(self, w): self.w = w def accept(self): try: self.restart_required = self.w.commit() except AbortCommit: return QDialog.accept(self) def init_gui(): from calibre.gui2.main import option_parser from calibre.gui2.ui import Main from calibre.library import db parser = option_parser() opts, args = parser.parse_args([]) actions = tuple(Main.create_application_menubar()) db = db() gui = Main(opts) gui.initialize(db.library_path, db, actions, show_gui=False) return gui def show_config_widget(category, name, gui=None, show_restart_msg=False, parent=None, never_shutdown=False): ''' Show the preferences plugin identified by category and name :param gui: gui instance, if None a hidden gui is created :param show_restart_msg: If True and the preferences plugin indicates a restart is required, show a message box telling the user to restart :param parent: The parent of the displayed dialog :return: True iff a restart is required for the changes made by the user to take effect ''' from calibre.gui2 import gprefs pl = get_plugin(category, name) d = ConfigDialog(parent) d.resize(750, 550) conf_name = 'config_widget_dialog_geometry_%s_%s'%(category, name) d.setWindowTitle(_('Configure ') + pl.gui_name) d.setWindowIcon(QIcon.ic('config.png')) bb = QDialogButtonBox(d) bb.setStandardButtons(QDialogButtonBox.StandardButton.Apply|QDialogButtonBox.StandardButton.Cancel|QDialogButtonBox.StandardButton.RestoreDefaults) bb.accepted.connect(d.accept) bb.rejected.connect(d.reject) w = pl.create_widget(d) d.set_widget(w) bb.button(QDialogButtonBox.StandardButton.RestoreDefaults).clicked.connect(w.restore_defaults) bb.button(QDialogButtonBox.StandardButton.RestoreDefaults).setEnabled(w.supports_restoring_to_defaults) bb.button(QDialogButtonBox.StandardButton.Apply).setEnabled(False) bb.button(QDialogButtonBox.StandardButton.Apply).clicked.connect(d.accept) def onchange(): b = bb.button(QDialogButtonBox.StandardButton.Apply) b.setEnabled(True) b.setDefault(True) b.setAutoDefault(True) w.changed_signal.connect(onchange) bb.button(QDialogButtonBox.StandardButton.Cancel).setFocus(Qt.FocusReason.OtherFocusReason) l = QVBoxLayout() d.setLayout(l) l.addWidget(w) l.addWidget(bb) mygui = gui is None if gui is None: gui = init_gui() mygui = True w.genesis(gui) w.initialize() d.restore_geometry(gprefs, conf_name) d.exec() d.save_geometry(gprefs, conf_name) rr = getattr(d, 'restart_required', False) if show_restart_msg and rr: from calibre.gui2 import warning_dialog warning_dialog(gui, 'Restart required', 'Restart required', show=True) if mygui and not never_shutdown: gui.shutdown() return rr class ListViewWithMoveByKeyPress(QListView): def set_movement_functions(self, up_function, down_function): self.up_function = up_function self.down_function = down_function def event(self, event): if (event.type() == QEvent.KeyPress and QApplication.keyboardModifiers() == Qt.KeyboardModifier.ControlModifier): if event.key() == Qt.Key.Key_Up: self.up_function() elif event.key() == Qt.Key.Key_Down: self.down_function() return True return QListView.event(self, event) class ListWidgetWithMoveByKeyPress(QListWidget): def set_movement_functions(self, up_function, down_function): self.up_function = up_function self.down_function = down_function def event(self, event): if (event.type() == QEvent.KeyPress and QApplication.keyboardModifiers() == Qt.KeyboardModifier.ControlModifier): if event.key() == Qt.Key.Key_Up: self.up_function() elif event.key() == Qt.Key.Key_Down: self.down_function() return True return QListWidget.event(self, event) class TableWidgetWithMoveByKeyPress(QTableWidget): def set_movement_functions(self, up_function, down_function): self.up_function = up_function self.down_function = down_function def event(self, event): if (event.type() == QEvent.KeyPress and QApplication.keyboardModifiers() == Qt.KeyboardModifier.ControlModifier): if event.key() == Qt.Key.Key_Up: self.up_function() elif event.key() == Qt.Key.Key_Down: self.down_function() return True return QTableWidget.event(self, event) # Testing {{{ def test_widget(category, name, gui=None): show_config_widget(category, name, gui=gui, show_restart_msg=True) def test_all(): from qt.core import QApplication app = QApplication([]) app gui = init_gui() for plugin in preferences_plugins(): test_widget(plugin.category, plugin.name, gui=gui) gui.shutdown() if __name__ == '__main__': test_all() # }}}
16,663
Python
.py
408
32.156863
151
0.639181
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)
26,799
create_custom_column.py
kovidgoyal_calibre/src/calibre/gui2/preferences/create_custom_column.py
#!/usr/bin/env python __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid at kovidgoyal.net>' '''Dialog to create a new custom column''' import copy import re from enum import Enum from functools import partial from qt.core import ( QCheckBox, QColor, QComboBox, QDialog, QDialogButtonBox, QGridLayout, QGroupBox, QHBoxLayout, QIcon, QLabel, QLineEdit, QRadioButton, QSpinBox, Qt, QVBoxLayout, QWidget, ) from calibre.gui2 import error_dialog from calibre.gui2.dialogs.template_line_editor import TemplateLineEditor from calibre.utils.date import UNDEFINED_DATE, parse_date from calibre.utils.localization import ngettext from polyglot.builtins import iteritems class CreateCustomColumn(QDialog): # Note: in this class, we are treating is_multiple as the boolean that # custom_columns expects to find in its structure. It does not use the dict column_types = dict(enumerate(( { 'datatype':'text', 'text':_('Text, column shown in the Tag browser'), 'is_multiple':False }, { 'datatype':'*text', 'text':_('Comma separated text, like tags, shown in the Tag browser'), 'is_multiple':True }, { 'datatype':'comments', 'text':_('Long text, like comments, not shown in the Tag browser'), 'is_multiple':False }, { 'datatype':'series', 'text':_('Text column for keeping series-like information'), 'is_multiple':False }, { 'datatype':'enumeration', 'text':_('Text, but with a fixed set of permitted values'), 'is_multiple':False }, { 'datatype':'datetime', 'text':_('Date'), 'is_multiple':False }, { 'datatype':'float', 'text':_('Floating point numbers'), 'is_multiple':False }, { 'datatype':'int', 'text':_('Integers'), 'is_multiple':False }, { 'datatype':'rating', 'text':_('Ratings, shown with stars'), 'is_multiple':False }, { 'datatype':'bool', 'text':_('Yes/No'), 'is_multiple':False }, { 'datatype':'composite', 'text':_('Column built from other columns'), 'is_multiple':False }, { 'datatype':'*composite', 'text':_('Column built from other columns, behaves like tags'), 'is_multiple':True }, ))) column_types_map = {k['datatype']:idx for idx, k in iteritems(column_types)} def __init__(self, gui, caller, current_key, standard_colheads, freeze_lookup_name=False): QDialog.__init__(self, gui) self.orig_column_number = -1 self.gui = gui self.setup_ui() self.setWindowTitle(_('Create a custom column')) self.heading_label.setText('<b>' + _('Create a custom column')) # Remove help icon on title bar icon = self.windowIcon() self.setWindowFlags(self.windowFlags()&(~Qt.WindowType.WindowContextHelpButtonHint)) self.setWindowIcon(icon) self.simple_error = partial(error_dialog, self, show=True, show_copy_button=False) for sort_by in [_('Text'), _('Number'), _('Date'), _('Yes/No')]: self.composite_sort_by.addItem(sort_by) self.caller = caller self.caller.cc_column_key = None self.editing_col = current_key is not None self.standard_colheads = standard_colheads self.column_type_box.setMaxVisibleItems(len(self.column_types)) for t in self.column_types: self.column_type_box.addItem(self.column_types[t]['text']) self.column_type_box.currentIndexChanged.connect(self.datatype_changed) self.composite_in_comments_box.stateChanged.connect(self.composite_show_in_comments_clicked) if not self.editing_col: self.datatype_changed() self.exec() return self.setWindowTitle(_('Edit custom column')) self.heading_label.setText('<b>' + _('Edit custom column')) self.shortcuts.setVisible(False) col = current_key if col not in caller.custcols: self.simple_error('', _('The selected column is not a user-defined column')) return c = caller.custcols[col] self.column_name_box.setText(c['label']) if freeze_lookup_name: self.column_name_box.setEnabled(False) self.column_heading_box.setText(c['name']) self.column_heading_box.setFocus() ct = c['datatype'] if c['is_multiple']: ct = '*' + ct self.orig_column_number = c['colnum'] self.orig_column_name = col column_numbers = dict(map(lambda x:(self.column_types[x]['datatype'], x), self.column_types)) self.column_type_box.setCurrentIndex(column_numbers[ct]) self.column_type_box.setEnabled(False) self.datatype_changed() if ct == 'datetime': if c['display'].get('date_format', None): self.format_box.setText(c['display'].get('date_format', '')) elif ct in ['composite', '*composite']: self.composite_box.setText(c['display'].get('composite_template', '')) self.store_template_value_in_opf.setChecked(c['display'].get('composite_store_template_value_in_opf', True)) if c['display'].get('composite_show_in_comments', ''): self.composite_in_comments_box.setChecked(True) idx = max(0, self.composite_heading_position.findData(c['display'].get('heading_position', 'hide'))) self.composite_heading_position.setCurrentIndex(idx) else: self.composite_in_comments_box.setChecked(False) sb = c['display'].get('composite_sort', 'text') vals = ['text', 'number', 'date', 'bool'] if sb in vals: sb = vals.index(sb) else: sb = 0 self.composite_sort_by.setCurrentIndex(sb) self.composite_make_category.setChecked( c['display'].get('make_category', False)) self.composite_contains_html.setChecked( c['display'].get('contains_html', False)) elif ct == 'enumeration': self.enum_box.setText(','.join(c['display'].get('enum_values', []))) self.enum_colors.setText(','.join(c['display'].get('enum_colors', []))) elif ct in ['int', 'float']: if c['display'].get('number_format', None): self.format_box.setText(c['display'].get('number_format', '')) elif ct == 'comments': idx = max(0, self.comments_heading_position.findData(c['display'].get('heading_position', 'hide'))) self.comments_heading_position.setCurrentIndex(idx) idx = max(0, self.comments_type.findData(c['display'].get('interpret_as', 'html'))) self.comments_type.setCurrentIndex(idx) elif ct == 'rating': self.allow_half_stars.setChecked(bool(c['display'].get('allow_half_stars', False))) elif ct == 'bool': icon = bool(c['display'].get('bools_show_icons', True)) txt = bool(c['display'].get('bools_show_text', False)) if icon and txt: self.bool_show_both_button.click() elif icon: self.bool_show_icon_button.click() else: self.bool_show_text_button.click() # Default values dv = c['display'].get('default_value', None) if dv is not None: if ct == 'bool': self.default_value.setText(_('Yes') if dv else _('No')) elif ct == 'datetime': self.default_value.setText(_('Now') if dv == 'now' else dv) elif ct == 'rating': if self.allow_half_stars.isChecked(): self.default_value.setText(str(dv/2)) else: self.default_value.setText(str(dv//2)) elif ct in ('int', 'float'): self.default_value.setText(str(dv)) elif ct not in ('composite', '*composite'): self.default_value.setText(dv) if ct in ['text', 'composite', 'enumeration']: self.use_decorations.setChecked(c['display'].get('use_decorations', False)) elif ct == '*text': self.is_names.setChecked(c['display'].get('is_names', False)) self.description_box.setText(c['display'].get('description', '')) self.decimals_box.setValue(min(9, max(1, int(c['display'].get('decimals', 2))))) all_colors = [str(s) for s in list(QColor.colorNames())] self.enum_colors_label.setToolTip('<p>' + ', '.join(all_colors) + '</p>') self.exec() def shortcut_activated(self, url): # {{{ which = str(url).split(':')[-1] self.column_type_box.setCurrentIndex({ 'yesno': self.column_types_map['bool'], 'tags' : self.column_types_map['*text'], 'series': self.column_types_map['series'], 'rating': self.column_types_map['rating'], 'people': self.column_types_map['*text'], 'text': self.column_types_map['comments'], }.get(which, self.column_types_map['composite'])) self.column_name_box.setText(which) self.column_heading_box.setText({ 'isbn':'ISBN', 'formats':_('Formats'), 'yesno':_('Yes/No'), 'tags': _('My Tags'), 'series': _('My Series'), 'rating': _('My Rating'), 'people': _('People'), 'text': _('My Title'), }[which]) self.is_names.setChecked(which == 'people') if self.composite_box.isVisible(): self.composite_box.setText( { 'isbn': '{identifiers:select(isbn)}', 'formats': "{:'re(approximate_formats(), ',', ', ')'}", }[which]) self.composite_sort_by.setCurrentIndex(0) if which == 'text': self.comments_heading_position.setCurrentIndex(self.comments_heading_position.findData('side')) self.comments_type.setCurrentIndex(self.comments_type.findData('short-text')) # }}} def setup_ui(self): # {{{ self.setWindowModality(Qt.WindowModality.ApplicationModal) self.setWindowIcon(QIcon.ic('column.png')) self.vl = l = QVBoxLayout(self) self.heading_label = la = QLabel('') l.addWidget(la) self.shortcuts = s = QLabel('') s.setWordWrap(True) s.linkActivated.connect(self.shortcut_activated) text = '<p>'+_('Quick create:') for col, name in [('isbn', _('ISBN')), ('formats', _('Formats')), ('yesno', _('Yes/No')), ('tags', _('Tags')), ('series', ngettext('Series', 'Series', 1)), ('rating', _('Rating')), ('people', _("Names")), ('text', _('Short text'))]: text += ' <a href="col:%s">%s</a>,'%(col, name) text = text[:-1] s.setText(text) l.addWidget(s) self.g = g = QGridLayout() l.addLayout(g) l.addStretch(10) bbl = QHBoxLayout() txt = QLabel(_('Pressing OK will require restarting calibre even if nothing was changed')) txt.setWordWrap(True) bbl.addWidget(txt) bbl.addStretch(1) self.button_box = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel, self) bb.accepted.connect(self.accept), bb.rejected.connect(self.reject) bbl.addWidget(bb) l.addLayout(bbl) def add_row(text, widget): if text is None: f = g.addWidget if isinstance(widget, QWidget) else g.addLayout f(widget, g.rowCount(), 0, 1, -1) return row = g.rowCount() la = QLabel(text) g.addWidget(la, row, 0, 1, 1) if isinstance(widget, QWidget): la.setBuddy(widget) g.addWidget(widget, row, 1, 1, 1) else: widget.setContentsMargins(0, 0, 0, 0) g.addLayout(widget, row, 1, 1, 1) for i in range(widget.count()): w = widget.itemAt(i).widget() if isinstance(w, QWidget): la.setBuddy(w) break return la # Lookup name self.column_name_box = cnb = QLineEdit(self) cnb.setToolTip(_("Used for searching the column. Must contain only digits and lower case letters.")) add_row(_("&Lookup name:"), cnb) # Heading self.column_heading_box = chb = QLineEdit(self) chb.setToolTip(_("Column heading in the library view and category name in the Tag browser")) add_row(_("Column &heading:"), chb) # Column Type h = QHBoxLayout() self.column_type_box = ctb = QComboBox(self) ctb.setMinimumWidth(70) ctb.setToolTip(_("What kind of information will be kept in the column.")) h.addWidget(ctb) self.use_decorations = ud = QCheckBox(_("Show &checkmarks"), self) ud.setToolTip(_("Show check marks in the GUI. Values of 'yes', 'checked', and 'true'\n" "will show a green check. Values of 'no', 'unchecked', and 'false' will show a red X.\n" "Everything else will show nothing. Note that the values of 'true' and 'false' don't\n" "follow calibre's language settings and are always in English.")) h.addWidget(ud) self.is_names = ins = QCheckBox(_("Contains names"), self) ins.setToolTip('<p>' + _('Check this box if this column contains names, ' 'like the authors column. If checked, the item separator will be an ampersand ' '(&) instead of a comma (,), sorting will be done using a computed value ' 'that respects the author sort tweaks (for example converting "Firstname ' 'Lastname" into "Lastname, Firstname"), and item order will be ' 'preserved.')+'</p>') h.addWidget(ins) add_row(_("&Column type:"), h) # Description self.description_box = d = QLineEdit(self) d.setToolTip(_("Optional text describing what this column is for")) add_row(_("D&escription:"), d) # bool formatting h1 = QHBoxLayout() def add_bool_radio_button(txt): b = QRadioButton(txt) b.clicked.connect(partial(self.bool_radio_button_clicked, b)) h1.addWidget(b) return b self.bool_show_icon_button = add_bool_radio_button(_('&Icon')) self.bool_show_icon_button.setChecked(True) self.bool_show_text_button = add_bool_radio_button(_('&Text')) self.bool_show_both_button = add_bool_radio_button(_('&Both')) self.bool_button_group = QGroupBox() self.bool_button_group.setFocusPolicy(Qt.FocusPolicy.StrongFocus) self.bool_button_group.setLayout(h1) h = QHBoxLayout() h.addWidget(self.bool_button_group) self.bool_button_group_label = la = QLabel(_('Choose whether an icon, text, or both is shown in the book list')) la.setWordWrap(True) h.addWidget(la) h.setStretch(1, 10) self.bool_show_label = add_row(_('&Show:'), h) # Date/number formatting h = QHBoxLayout() self.format_box = fb = QLineEdit(self) h.addWidget(fb) self.format_default_label = la = QLabel('') la.setOpenExternalLinks(True), la.setWordWrap(True) h.addWidget(la) self.format_label = add_row('', h) # Float number of decimal digits h = QHBoxLayout() self.decimals_box = fb = QSpinBox(self) fb.setRange(1, 9) fb.setValue(2) h.addWidget(fb) self.decimals_default_label = la = QLabel(_( 'Control the number of decimal digits you can enter when editing this column')) la.setWordWrap(True) h.addWidget(la) self.decimals_label = add_row(_('Decimals when &editing:'), h) # Template self.composite_box = cb = TemplateLineEditor(self) self.composite_default_label = cdl = QLabel(_("Default: (nothing)")) cb.setToolTip(_("Field template. Uses the same syntax as save templates.")) cdl.setToolTip(_("Similar to save templates. For example, %s") % "{title} {isbn}") h = QHBoxLayout() h.addWidget(cb), h.addWidget(cdl) self.composite_label = add_row(_("&Template:"), h) # Comments properties self.comments_heading_position = ct = QComboBox(self) for k, text in ( ('hide', _('No heading')), ('above', _('Show heading above the text')), ('side', _('Show heading to the side of the text')) ): ct.addItem(text, k) ct.setToolTip('<p>' + _('Choose whether or not the column heading is shown in the Book ' 'details panel and, if shown, where. Setting this to ' "'Show heading to the side of the text' moves the information " "from displayed with other comments to displayed with the " "non-comments columns.") + '</p>') self.comments_heading_position_label = add_row(_('Heading position:'), ct) self.comments_type = ct = QComboBox(self) for k, text in ( ('html', 'HTML'), ('short-text', _('Short text, like a title')), ('long-text', _('Plain text')), ('markdown', _('Plain text formatted using Markdown')) ): ct.addItem(text, k) ct.setToolTip(_('Choose how the data in this column is interpreted.\n' 'This controls how the data is displayed in the Book details panel\n' 'and how it is edited.')) self.comments_type_label = add_row(_('Interpret this column as:') + ' ', ct) # Values for enum type self.enum_box = eb = QLineEdit(self) eb.setToolTip(_( "A comma-separated list of permitted values. The empty value is always\n" "included, and is the default. For example, the list 'one,two,three' has\n" "four values, the first of them being the empty value.")) self.enum_default_label = add_row(_("&Values:"), eb) self.enum_colors = ec = QLineEdit(self) ec.setToolTip(_("A list of color names to use when displaying an item. The\n" "list must be empty or contain a color for each value.")) self.enum_colors_label = add_row(_('Colors:'), ec) # Rating allow half stars self.allow_half_stars = ahs = QCheckBox(_('Allow half stars')) ahs.setToolTip(_('Allow half star ratings, for example: ') + '★★★⯨') add_row(None, ahs) # Composite display properties l = QHBoxLayout() self.composite_sort_by_label = la = QLabel(_("&Sort/search column by")) self.composite_sort_by = csb = QComboBox(self) la.setBuddy(csb), csb.setToolTip(_("How this column should handled in the GUI when sorting and searching")) l.addWidget(la), l.addWidget(csb) self.composite_make_category = cmc = QCheckBox(_("Show in Tag browser")) cmc.setToolTip(_("If checked, this column will appear in the Tag browser as a category")) l.addWidget(cmc) self.composite_contains_html = cch = QCheckBox(_("Show as HTML in Book details")) cch.setToolTip('<p>' + _( 'If checked, this column will be displayed as HTML in ' 'Book details and the Content server. This can be used to ' 'construct links with the template language. For example, ' 'the template ' '<pre>&lt;big&gt;&lt;b&gt;{title}&lt;/b&gt;&lt;/big&gt;' '{series:| [|}{series_index:| [|]]}</pre>' 'will create a field displaying the title in bold large ' 'characters, along with the series, for example <br>"<big><b>' 'An Oblique Approach</b></big> [Belisarius [1]]". The template ' '<pre>&lt;a href="https://www.beam-ebooks.de/ebook/{identifiers' ':select(beam)}"&gt;Beam book&lt;/a&gt;</pre> ' 'will generate a link to the book on the Beam e-books site.') + '</p>') l.addWidget(cch) l.addStretch() add_row(None, l) l = QHBoxLayout() self.composite_in_comments_box = cmc = QCheckBox(_("Show with comments in Book details")) cmc.setToolTip('<p>' + _('If you check this box then the column contents ' 'will show in the Comments section in the Book details. ' 'You can indicate whether not to have a header or ' 'to put a header above the column. If you want a ' "header beside the data, don't check this box. " 'If this box is checked then the output of the ' 'column template must be plain text or html.') + '</p>') l.addWidget(cmc) self.composite_heading_position = chp = QComboBox(self) for k, text in ( ('hide', _('No heading')), ('above', _('Show heading above the text')) # we don't offer 'side' because that is what you get if you don't # check the box. ): chp.addItem(text, k) chp.setToolTip(_('Choose whether or not the column heading is shown in the Book\n' 'details panel and, if shown, where')) self.composite_heading_position_label = la = QLabel(_('Column heading:')) l.addWidget(la), l.addWidget(chp) l.addStretch() add_row(None, l) l = QHBoxLayout() self.store_template_value_in_opf = cmc = QCheckBox(_("Store this column's value in an OPF")) cmc.setToolTip('<p>' + _('If you check this box then the result of ' "evaluating this column's template will be stored in the backup OPF " 'stored in the library. The same is true when sending to a device, ' 'assuming the format has an OPF. One reason to uncheck this box is ' 'that the column contains large images.') + '</p>') l.addWidget(cmc) l.addStretch() add_row(None, l) # Default value self.default_value = dv = QLineEdit(self) dv.setToolTip('<p>' + _('Default value when a new book is added to the ' 'library. For Date columns enter the word "Now", or the date as ' 'yyyy-mm-dd. For Yes/No columns enter "Yes" or "No". For Text with ' 'a fixed set of values enter one of the permitted values. For ' 'Rating columns enter a number between 0 and 5.') + '</p>') self.default_value_label = add_row(_('&Default value:'), dv) self.resize(self.sizeHint()) # }}} def bool_radio_button_clicked(self, button, clicked): if clicked: self.bool_button_group.setFocusProxy(button) def composite_show_in_comments_clicked(self, state): if state == Qt.CheckState.Checked.value: # state is passed as an int self.composite_sort_by.setEnabled(False) self.composite_sort_by_label.setEnabled(False) self.composite_make_category.setEnabled(False) self.composite_contains_html.setEnabled(False) self.composite_heading_position.setEnabled(True) self.composite_heading_position_label.setEnabled(True) self.composite_heading_position.setCurrentIndex(0) else: self.composite_sort_by.setEnabled(True) self.composite_sort_by_label.setEnabled(True) self.composite_make_category.setEnabled(True) self.composite_contains_html.setEnabled(True) self.composite_heading_position.setEnabled(False) self.composite_heading_position_label.setEnabled(False) self.composite_heading_position.setCurrentIndex(0) def datatype_changed(self, *args): try: col_type = self.column_types[self.column_type_box.currentIndex()]['datatype'] except: col_type = None needs_format = col_type in ('datetime', 'int', 'float') for x in ('box', 'default_label', 'label'): getattr(self, 'format_'+x).setVisible(needs_format) getattr(self, 'decimals_'+x).setVisible(col_type == 'float') if needs_format: if col_type == 'datetime': l, dl = _('&Format for dates:'), _('Default: dd MMM yyyy.') self.format_box.setToolTip(_( '<p>Date format.</p>' '<p>The formatting codes are:' '<ul>' '<li>d : the day as number without a leading zero (1 to 31)</li>' '<li>dd : the day as number with a leading zero (01 to 31)</li>' '<li>ddd : the abbreviated localized day name (e.g. "Mon" to "Sun").</li>' '<li>dddd : the long localized day name (e.g. "Monday" to "Sunday").</li>' '<li>M : the <b>month</b> as number without a leading zero (1 to 12).</li>' '<li>MM : the <b>month</b> as number with a leading zero (01 to 12)</li>' '<li>MMM : the abbreviated localized <b>month</b> name (e.g. "Jan" to "Dec").</li>' '<li>MMMM : the long localized <b>month</b> name (e.g. "January" to "December").</li>' '<li>yy : the year as two digit number (00 to 99).</li>' '<li>yyyy : the year as four digit number.</li>' '<li>h : the hours without a leading 0 (0 to 11 or 0 to 23, depending on am/pm)</li>' '<li>hh : the hours with a leading 0 (00 to 11 or 00 to 23, depending on am/pm)</li>' '<li>m : the <b>minutes</b> without a leading 0 (0 to 59)</li>' '<li>mm : the <b>minutes</b> with a leading 0 (00 to 59)</li>' '<li>s : the seconds without a leading 0 (0 to 59)</li>' '<li>ss : the seconds with a leading 0 (00 to 59)</li>' '<li>ap : use a 12-hour clock instead of a 24-hour clock, with "ap" replaced by the localized string for am or pm</li>' '<li>AP : use a 12-hour clock instead of a 24-hour clock, with "AP" replaced by the localized string for AM or PM</li>' '<li>iso : the date with time and timezone. Must be the only format present</li>' '</ul></p>' "<p>For example:\n" "<ul>\n" "<li>ddd, d MMM yyyy gives Mon, 5 Jan 2010</li>\n" "<li>dd MMMM yy gives 05 January 10</li>\n" "</ul> ")) else: l, dl = _('&Format for numbers:'), ( '<p>' + _('Default: Not formatted. For format language details see' ' <a href="https://docs.python.org/library/string.html#format-string-syntax">the Python documentation</a>')) if col_type == 'int': self.format_box.setToolTip('<p>' + _( 'Examples: The format <code>{0:0>4d}</code> ' 'gives a 4-digit number with leading zeros. The format ' '<code>{0:d}&nbsp;days</code> prints the number then the word "days"')+ '</p>') else: self.format_box.setToolTip('<p>' + _( 'Examples: The format <code>{0:.1f}</code> gives a floating ' 'point number with 1 digit after the decimal point. The format ' '<code>Price:&nbsp;$&nbsp;{0:,.2f}</code> prints ' '"Price&nbsp;$&nbsp;" then displays the number with 2 digits ' 'after the decimal point and thousands separated by commas.') + '</p>' ) self.format_label.setText(l), self.format_default_label.setText(dl) for x in ('in_comments_box', 'heading_position', 'heading_position_label'): getattr(self, 'composite_'+x).setVisible(col_type == 'composite') for x in ('box', 'default_label', 'label', 'sort_by', 'sort_by_label', 'make_category', 'contains_html'): getattr(self, 'composite_'+x).setVisible(col_type in ('composite', '*composite')) self.composite_heading_position.setEnabled(False) self.store_template_value_in_opf.setVisible(col_type == 'composite') for x in ('box', 'default_label', 'colors', 'colors_label'): getattr(self, 'enum_'+x).setVisible(col_type == 'enumeration') for x in ('value_label', 'value'): getattr(self, 'default_'+x).setVisible(col_type not in ['composite', '*composite']) self.use_decorations.setVisible(col_type in ['text', 'composite', 'enumeration']) self.is_names.setVisible(col_type == '*text') is_comments = col_type == 'comments' self.comments_heading_position.setVisible(is_comments) self.comments_heading_position_label.setVisible(is_comments) self.comments_type.setVisible(is_comments) self.comments_type_label.setVisible(is_comments) self.allow_half_stars.setVisible(col_type == 'rating') is_bool = col_type == 'bool' self.bool_button_group.setVisible(is_bool) self.bool_button_group_label.setVisible(is_bool) self.bool_show_label.setVisible(is_bool) def accept(self): col = str(self.column_name_box.text()).strip() if not col: return self.simple_error('', _('No lookup name was provided')) if col.startswith('#'): col = col[1:] if re.match(r'^\w*$', col) is None or not col[0].isalpha() or col.lower() != col: return self.simple_error('', _('The lookup name must contain only ' 'lower case letters, digits and underscores, and start with a letter')) if col.endswith('_index'): return self.simple_error('', _('Lookup names cannot end with _index, ' 'because these names are reserved for the index of a series column.')) col_heading = str(self.column_heading_box.text()).strip() coldef = self.column_types[self.column_type_box.currentIndex()] col_type = coldef['datatype'] if col_type[0] == '*': col_type = col_type[1:] is_multiple = True else: is_multiple = False if not col_heading: return self.simple_error('', _('No column heading was provided')) db = self.gui.library_view.model().db key = db.field_metadata.custom_field_prefix+col cc = self.caller.custcols if key in cc and (not self.editing_col or cc[key]['colnum'] != self.orig_column_number): return self.simple_error('', _('The lookup name %s is already used')%col) bad_head = False for cc in self.caller.custcols.values(): if cc['name'] == col_heading and cc['colnum'] != self.orig_column_number: bad_head = True break for t in self.standard_colheads: if self.standard_colheads[t] == col_heading: bad_head = True if bad_head: return self.simple_error('', _('The heading %s is already used')%col_heading) display_dict = {} default_val = (str(self.default_value.text()).strip() if col_type != 'composite' else None) if col_type == 'datetime': if str(self.format_box.text()).strip(): display_dict = {'date_format':str(self.format_box.text()).strip()} else: display_dict = {'date_format': None} if default_val: if default_val == _('Now'): display_dict['default_value'] = 'now' else: try: tv = parse_date(default_val) except: tv = UNDEFINED_DATE if tv == UNDEFINED_DATE: return self.simple_error(_('Invalid default value'), _('The default value must be "Now" or a date')) display_dict['default_value'] = default_val elif col_type == 'composite': if not str(self.composite_box.text()).strip(): return self.simple_error('', _('You must enter a template for ' 'composite columns')) if self.composite_in_comments_box.isChecked(): display_dict = {'composite_template':str(self.composite_box.text()).strip(), 'heading_position': self.composite_heading_position.currentData(), 'composite_show_in_comments': True, } else: display_dict = {'composite_template':str(self.composite_box.text()).strip(), 'composite_sort': ['text', 'number', 'date', 'bool'] [self.composite_sort_by.currentIndex()], 'make_category': self.composite_make_category.isChecked(), 'contains_html': self.composite_contains_html.isChecked(), 'composite_show_in_comments': False, } display_dict['composite_store_template_value_in_opf'] = self.store_template_value_in_opf.isChecked() elif col_type == 'enumeration': if not str(self.enum_box.text()).strip(): return self.simple_error('', _('You must enter at least one ' 'value for enumeration columns')) l = [v.strip() for v in str(self.enum_box.text()).split(',') if v.strip()] l_lower = [v.lower() for v in l] for i,v in enumerate(l_lower): if v in l_lower[i+1:]: return self.simple_error('', _('The value "{0}" is in the ' 'list more than once, perhaps with different case').format(l[i])) c = str(self.enum_colors.text()) if c: c = [v.strip() for v in str(self.enum_colors.text()).split(',')] else: c = [] if len(c) != 0 and len(c) != len(l): return self.simple_error('', _('The colors box must be empty or ' 'contain the same number of items as the value box')) for tc in c: if tc not in QColor.colorNames() and not re.match("#(?:[0-9a-f]{3}){1,4}",tc,re.I): return self.simple_error('', _('The color {0} is unknown').format(tc)) display_dict = {'enum_values': l, 'enum_colors': c} if default_val: if default_val not in l: return self.simple_error(_('Invalid default value'), _('The default value must be one of the permitted values')) display_dict['default_value'] = default_val elif col_type == 'text' and is_multiple: display_dict = {'is_names': self.is_names.isChecked()} elif col_type in ['int', 'float']: if str(self.format_box.text()).strip(): display_dict = {'number_format':str(self.format_box.text()).strip()} else: display_dict = {'number_format': None} if col_type == 'float': display_dict['decimals'] = int(self.decimals_box.value()) if default_val: try: if col_type == 'int': msg = _('The default value must be an integer') tv = int(default_val) display_dict['default_value'] = tv else: msg = _('The default value must be a real number') tv = float(default_val) display_dict['default_value'] = tv except: return self.simple_error(_('Invalid default value'), msg) elif col_type == 'comments': display_dict['heading_position'] = str(self.comments_heading_position.currentData()) display_dict['interpret_as'] = str(self.comments_type.currentData()) elif col_type == 'rating': half_stars = bool(self.allow_half_stars.isChecked()) display_dict['allow_half_stars'] = half_stars if default_val: try: tv = int((float(default_val) if half_stars else int(default_val)) * 2) except: tv = -1 if tv < 0 or tv > 10: if half_stars: return self.simple_error(_('Invalid default value'), _('The default value must be a real number between 0 and 5.0')) else: return self.simple_error(_('Invalid default value'), _('The default value must be an integer between 0 and 5')) display_dict['default_value'] = tv elif col_type == 'bool': if default_val: tv = {_('Yes'): True, _('No'): False}.get(default_val, None) if tv is None: return self.simple_error(_('Invalid default value'), _('The default value must be "Yes" or "No"')) display_dict['default_value'] = tv show_icon = bool(self.bool_show_icon_button.isChecked()) or bool(self.bool_show_both_button.isChecked()) show_text = bool(self.bool_show_text_button.isChecked()) or bool(self.bool_show_both_button.isChecked()) display_dict['bools_show_text'] = show_text display_dict['bools_show_icons'] = show_icon if col_type in ['text', 'composite', 'enumeration'] and not is_multiple: display_dict['use_decorations'] = self.use_decorations.checkState() == Qt.CheckState.Checked if default_val and 'default_value' not in display_dict: display_dict['default_value'] = default_val display_dict['description'] = self.description_box.text().strip() if not self.editing_col: self.caller.custcols[key] = { 'label':col, 'name':col_heading, 'datatype':col_type, 'display':display_dict, 'normalized':None, 'colnum':None, 'is_multiple':is_multiple, } self.caller.cc_column_key = key else: cc = self.caller.custcols[self.orig_column_name] cc['label'] = col cc['name'] = col_heading # Remove any previous default value cc['display'].pop('default_value', None) cc['display'].update(display_dict) cc['*edited'] = True cc['*must_restart'] = True self.caller.cc_column_key = key QDialog.accept(self) def reject(self): QDialog.reject(self) class CreateNewCustomColumn: """ Provide an API to create new custom columns. Usage: from calibre.gui2.preferences.create_custom_column import CreateNewCustomColumn creator = CreateNewCustomColumn(gui) if creator.must_restart(): ... else: result = creator.create_column(....) if result[0] == creator.Result.COLUMN_ADDED: The parameter 'gui' passed when creating a class instance is the main calibre gui (calibre.gui2.ui.get_gui()) Use the create_column(...) method to open a dialog to create a new custom column with given lookup_name, column_heading, datatype, and is_multiple. You can create as many columns as you wish with a single instance of the CreateNewCustomColumn class. Subsequent class instances will refuse to create columns until calibre is restarted, as will calibre Preferences. The lookup name must begin with a '#'. All remaining characters must be lower case letters, digits or underscores. The character after the '#' must be a letter. The lookup name must not end with the suffix '_index'. The datatype must be one of calibre's custom column types: 'bool', 'comments', 'composite', 'datetime', 'enumeration', 'float', 'int', 'rating', 'series', or 'text'. The datatype can't be changed in the dialog. is_multiple tells calibre that the column contains multiple values -- is tags-like. The value True is allowed only for 'composite' and 'text' types. If generate_unused_lookup_name is False then the provided lookup_name and column_heading must not already exist. If generate_unused_lookup_name is True then if necessary the method will add the suffix '_n' to the provided lookup_name to allocate an unused lookup_name, where 'n' is an integer. The same processing is applied to column_heading to make it is unique, using the same suffix used for the lookup name if possible. In either case the user can change the column heading in the dialog. Set freeze_lookup_name to False if you want to allow the user choose a different lookup name. The user will not be allowed to choose the lookup name of an existing column. The provided lookup_name and column_heading either must not exist or generate_unused_lookup_name must be True, regardless of the value of freeze_lookup_name. The 'display' parameter is used to pass item- and type-specific information for the column. It is a dict. The easiest way to see the current values for 'display' for a particular column is to create a column like you want then look for the lookup name in the file metadata_db_prefs_backup.json. You must restart calibre twice after creating a new column before its information will appear in that file. The key:value pairs for each type are as follows. Note that this list might be incorrect. As said above, the best way to get current values is to create a similar column and look at the values in 'display'. all types: 'default_value': a string representation of the default value for the column. Permitted values are type specific 'description': a string containing the column's description comments columns: 'heading_position': a string specifying where a comment heading goes: hide, above, side 'interpret_as': a string specifying the comment's purpose: html, short-text, long-text, markdown composite columns: 'composite_template': a string containing the template for the composite column 'composite_sort': a string specifying how the composite is to be sorted 'make_category': True or False -- whether the column is shown in the tag browser 'contains_html': True or False -- whether the column is interpreted as HTML 'use_decorations': True or False -- should check marks be displayed datetime columns: 'date_format': a string specifying the display format enumerated columns 'enum_values': a string containing comma-separated valid values for an enumeration 'enum_colors': a string containing comma-separated colors for an enumeration 'use_decorations': True or False -- should check marks be displayed float columns: 'decimals': the number of decimal digits to allow when editing (int). Range: 1 - 9 float and int columns: 'number_format': the format to apply when displaying the column rating columns: 'allow_half_stars': True or False -- are half-stars allowed text columns: 'is_names': True or False -- whether the items are comma or ampersand separated 'use_decorations': True or False -- should check marks be displayed This method returns a tuple (Result.enum_value, message). If tuple[0] is Result.COLUMN_ADDED then the message is the lookup name including the '#'. Otherwise it is a potentially localized error message. You or the user must restart calibre for the column(s) to be actually added. Result.EXCEPTION_RAISED is returned if the create dialog raises an exception. This can happen if the display contains illegal values, for example a string where a boolean is required. The string is the exception text. Run calibre in debug mode to see the entire traceback. The method returns Result.MUST_RESTART if further calibre configuration has been blocked. You can check for this situation in advance by calling must_restart(). """ class Result(Enum): COLUMN_ADDED = 0 CANCELED = 1 INVALID_KEY = 2 DUPLICATE_KEY = 3 DUPLICATE_HEADING = 4 INVALID_TYPE = 5 INVALID_IS_MULTIPLE = 6 INVALID_DISPLAY = 7 EXCEPTION_RAISED = 8 MUST_RESTART = 9 COLUMN_EDITED = 11 def __init__(self, gui): self.gui = gui self.restart_required = gui.must_restart_before_config self.db = db = self.gui.library_view.model().db self.custcols = copy.deepcopy(db.field_metadata.custom_field_metadata()) # Get the largest internal column number so we can be sure that we can # detect duplicates. self.created_count = max((x['colnum'] for x in self.custcols.values()), default=0) + 1 def create_column(self, lookup_name, column_heading, datatype, is_multiple, display={}, generate_unused_lookup_name=False, freeze_lookup_name=True): """ See the class documentation for more information.""" if self.restart_required: return (self.Result.MUST_RESTART, _("You must restart calibre before making any more changes")) if not lookup_name.startswith('#'): return (self.Result.INVALID_KEY, _("The lookup name must begin with a '#'")) suffix_number = 1 if lookup_name in self.custcols: if not generate_unused_lookup_name: return (self.Result.DUPLICATE_KEY, _("The custom column %s already exists") % lookup_name) for suffix_number in range(suffix_number, 100000): nk = '%s_%d'%(lookup_name, suffix_number) if nk not in self.custcols: lookup_name = nk break if column_heading: headings = {v['name'] for v in self.custcols.values()} if column_heading in headings: if not generate_unused_lookup_name: return (self.Result.DUPLICATE_HEADING, _("The column heading %s already exists") % column_heading) for i in range(suffix_number, 100000): nh = '%s_%d'%(column_heading, i) if nh not in headings: column_heading = nh break else: column_heading = lookup_name if datatype not in CreateCustomColumn.column_types_map: return (self.Result.INVALID_TYPE, _("The custom column type %s doesn't exist") % datatype) if is_multiple and '*' + datatype not in CreateCustomColumn.column_types_map: return (self.Result.INVALID_IS_MULTIPLE, _("You cannot specify is_multiple for the datatype %s") % datatype) if not isinstance(display, dict): return (self.Result.INVALID_DISPLAY, _("The display parameter must be a Python dictionary")) self.created_count += 1 self.custcols[lookup_name] = { 'label': lookup_name, 'name': column_heading, 'datatype': datatype, 'display': display, 'normalized': None, 'colnum': self.created_count, 'is_multiple': is_multiple, } return self._create_or_edit_column(lookup_name, freeze_lookup_name=freeze_lookup_name, operation='create') def edit_existing_column(self, lookup_name): if lookup_name not in self.custcols: return self.Result.INVALID_KEY return self._create_or_edit_column(lookup_name, freeze_lookup_name=False, operation='edit') def _create_or_edit_column(self, lookup_name, freeze_lookup_name, operation=None): try: dialog = CreateCustomColumn(self.gui, self, lookup_name, self.gui.library_view.model().orig_headers, freeze_lookup_name=freeze_lookup_name) if dialog.result() == QDialog.DialogCode.Accepted and self.cc_column_key is not None: cc = self.custcols[lookup_name] if operation == 'create': self.db.create_custom_column( label=cc['label'], name=cc['name'], datatype=cc['datatype'], is_multiple=bool(cc['is_multiple']), display=cc['display']) self.gui.must_restart_before_config = True return (self.Result.COLUMN_ADDED, self.cc_column_key) # editing/viewing if operation == 'edit': self.db.set_custom_column_metadata(cc['colnum'], name=cc['name'], label=cc['label'], display=cc['display'], notify=False) if '*must_restart' in cc: self.gui.must_restart_before_config = True return (self.Result.COLUMN_EDITED, self.cc_column_key) return (self.Result.CANCELED, self.cc_column_key) except Exception as e: import traceback traceback.print_exc() self.custcols.pop(lookup_name, None) return (self.Result.EXCEPTION_RAISED, str(e)) self.custcols.pop(lookup_name, None) return (self.Result.CANCELED, _('Canceled')) def current_columns(self): """ Return the currently defined custom columns Return the currently defined custom columns including the ones that haven't yet been created. It is a dict of dicts defined as follows: custcols[lookup_name] = { 'label': lookup_name, 'name': column_heading, 'datatype': datatype, 'display': display, 'normalized': None, 'colnum': an integer used internally, 'is_multiple': is_multiple, } Columns that already exist will have additional attributes that this class doesn't use. See calibre.library.field_metadata.add_custom_field() for the complete list. """ # deepcopy to prevent users from changing it. The new MappingProxyType # isn't enough because only the top-level dict is immutable, not the # items in the dict. return copy.deepcopy(self.custcols) def current_headings(self): """ Return the currently defined column headings Return the column headings including the ones that haven't yet been created. It is a dict. The key is the heading, the value is the lookup name having that heading. """ return {v['name']:('#' + v['label']) for v in self.custcols.values()} def must_restart(self): """Return true if calibre must be restarted before new columns can be added.""" return self.restart_required
52,977
Python
.py
1,007
39.619662
141
0.569586
kovidgoyal/calibre
19,243
2,250
4
GPL-3.0
9/5/2024, 5:13:50 PM (Europe/Amsterdam)