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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
27,000 | template_dialog.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/template_dialog.py | #!/usr/bin/env python
__copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net'
__docformat__ = 'restructuredtext en'
__license__ = 'GPL v3'
import json
import os
import re
import sys
import traceback
from functools import partial
from qt.core import (
QAbstractItemView,
QApplication,
QColor,
QComboBox,
QCursor,
QDialog,
QDialogButtonBox,
QFont,
QFontDatabase,
QFontInfo,
QFontMetrics,
QIcon,
QLineEdit,
QPalette,
QSize,
QSyntaxHighlighter,
Qt,
QTableWidget,
QTableWidgetItem,
QTextCharFormat,
QTextOption,
QToolButton,
QVBoxLayout,
pyqtSignal,
)
from calibre import sanitize_file_name
from calibre.constants import config_dir
from calibre.ebooks.metadata.book.base import Metadata
from calibre.ebooks.metadata.book.formatter import SafeFormat
from calibre.gui2 import choose_files, choose_save_file, error_dialog, gprefs, pixmap_to_data, question_dialog
from calibre.gui2.dialogs.template_dialog_ui import Ui_TemplateDialog
from calibre.library.coloring import color_row_key, displayable_columns
from calibre.utils.config_base import tweaks
from calibre.utils.date import DEFAULT_DATE
from calibre.utils.formatter import PythonTemplateContext, StopException
from calibre.utils.formatter_functions import StoredObjectType, formatter_functions
from calibre.utils.icu import lower as icu_lower
from calibre.utils.icu import sort_key
from calibre.utils.localization import localize_user_manual_link, ngettext
from calibre.utils.resources import get_path as P
class ParenPosition:
def __init__(self, block, pos, paren):
self.block = block
self.pos = pos
self.paren = paren
self.highlight = False
def set_highlight(self, to_what):
self.highlight = to_what
class TemplateHighlighter(QSyntaxHighlighter):
# Code in this class is liberally borrowed from gui2.widgets.PythonHighlighter
BN_FACTOR = 1000
KEYWORDS_GPM = ['if', 'then', 'else', 'elif', 'fi', 'for', 'rof',
'separator', 'break', 'continue', 'return', 'in', 'inlist',
'inlist_field', 'def', 'fed', 'limit']
KEYWORDS_PYTHON = ["and", "as", "assert", "break", "class", "continue", "def",
"del", "elif", "else", "except", "exec", "finally", "for", "from",
"global", "if", "import", "in", "is", "lambda", "not", "or",
"pass", "print", "raise", "return", "try", "while", "with",
"yield"]
BUILTINS_PYTHON = ["abs", "all", "any", "basestring", "bool", "callable", "chr",
"classmethod", "cmp", "compile", "complex", "delattr", "dict",
"dir", "divmod", "enumerate", "eval", "execfile", "exit", "file",
"filter", "float", "frozenset", "getattr", "globals", "hasattr",
"hex", "id", "int", "isinstance", "issubclass", "iter", "len",
"list", "locals", "long", "map", "max", "min", "object", "oct",
"open", "ord", "pow", "property", "range", "reduce", "repr",
"reversed", "round", "set", "setattr", "slice", "sorted",
"staticmethod", "str", "sum", "super", "tuple", "type", "unichr",
"unicode", "vars", "xrange", "zip"]
CONSTANTS_PYTHON = ["False", "True", "None", "NotImplemented", "Ellipsis"]
def __init__(self, parent=None, builtin_functions=None):
super().__init__(parent)
self.initialize_formats()
self.initialize_rules(builtin_functions, for_python=False)
self.regenerate_paren_positions()
self.highlighted_paren = False
def initialize_rules(self, builtin_functions, for_python=False):
self.for_python = for_python
r = []
def a(a, b):
r.append((re.compile(a), b))
if not for_python:
a(r"\b[a-zA-Z]\w*\b(?!\(|\s+\()"
r"|\$+#?[a-zA-Z]\w*",
"identifier")
a(r"^program:", "keymode")
a("|".join([r"\b%s\b" % keyword for keyword in self.KEYWORDS_GPM]), "keyword")
a("|".join([r"\b%s\b" % builtin for builtin in
(builtin_functions if builtin_functions else
formatter_functions().get_builtins())]),
"builtin")
a(r"""(?<!:)'[^']*'|"[^"]*\"""", "string")
else:
a(r"^python:", "keymode")
a("|".join([r"\b%s\b" % keyword for keyword in self.KEYWORDS_PYTHON]), "keyword")
a("|".join([r"\b%s\b" % builtin for builtin in self.BUILTINS_PYTHON]), "builtin")
a("|".join([r"\b%s\b" % constant for constant in self.CONSTANTS_PYTHON]), "constant")
a(r"\bPyQt6\b|\bqt.core\b|\bQt?[A-Z][a-z]\w+\b", "pyqt")
a(r"@\w+(\.\w+)?\b", "decorator")
stringRe = r'''(["'])(?:(?!\1)[^\\]|\\.)*\1'''
a(stringRe, "string")
self.stringRe = re.compile(stringRe)
self.checkTripleInStringRe = re.compile(r"""((?:"|'){3}).*?\1""")
self.tripleSingleRe = re.compile(r"""'''(?!")""")
self.tripleDoubleRe = re.compile(r'''"""(?!')''')
a(
r"\b[+-]?[0-9]+[lL]?\b"
r"|\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b"
r"|\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b",
"number")
a(r'\(', "lparen")
a(r'\)', "rparen")
self.Rules = tuple(r)
def initialize_formats(self):
font_name = gprefs.get('gpm_template_editor_font', None)
size = gprefs['gpm_template_editor_font_size']
if font_name is None:
font = QFont()
font.setFixedPitch(True)
font.setPointSize(size)
font_name = font.family()
config = self.Config = {}
config["fontfamily"] = font_name
app_palette = QApplication.instance().palette()
is_dark = QApplication.instance().is_dark_theme
all_formats = (
# name, color, bold, italic
("normal", None, False, False),
("keyword", app_palette.color(QPalette.ColorRole.Link).name(), True, False),
("builtin", app_palette.color(QPalette.ColorRole.Link).name(), False, False),
("constant", app_palette.color(QPalette.ColorRole.Link).name(), False, False),
("identifier", None, False, True),
("comment", '#00c700' if is_dark else "#007F00", False, True),
("string", '#b6b600' if is_dark else "#808000", False, False),
("number", '#d96d00' if is_dark else "#924900", False, False),
("decorator", "#FF8000", False, True),
("pyqt", None, False, False),
("lparen", None, True, True),
("rparen", None, True, True))
for name, color, bold, italic in all_formats:
config["%sfontcolor" % name] = color
config["%sfontbold" % name] = bold
config["%sfontitalic" % name] = italic
base_format = QTextCharFormat()
base_format.setFontFamilies([config["fontfamily"]])
config["fontsize"] = size
base_format.setFontPointSize(config["fontsize"])
self.Formats = {}
for name, color, bold, italic in all_formats:
format_ = QTextCharFormat(base_format)
color = config["%sfontcolor" % name]
if color:
format_.setForeground(QColor(color))
if config["%sfontbold" % name]:
format_.setFontWeight(QFont.Weight.Bold)
format_.setFontItalic(config["%sfontitalic" % name])
self.Formats[name] = format_
def find_paren(self, bn, pos):
dex = bn * self.BN_FACTOR + pos
return self.paren_pos_map.get(dex, None)
def replace_strings_with_dash(self, mo):
found = mo.group(0)
return '-' * len(found)
def highlightBlock(self, text):
NORMAL, TRIPLESINGLE, TRIPLEDOUBLE = range(3)
bn = self.currentBlock().blockNumber()
textLength = len(text)
self.setFormat(0, textLength, self.Formats["normal"])
if not text:
pass
elif text[0] == "#":
self.setFormat(0, textLength, self.Formats["comment"])
return
for regex, format_ in self.Rules:
for m in regex.finditer(text):
i, length = m.start(), m.end() - m.start()
if format_ in ['lparen', 'rparen']:
pp = self.find_paren(bn, i)
if pp and pp.highlight:
self.setFormat(i, length, self.Formats[format_])
elif format_ == 'keymode':
if bn > 0 and i == 0:
continue
self.setFormat(i, length, self.Formats['keyword'])
else:
self.setFormat(i, length, self.Formats[format_])
# Deal with comments not at the beginning of the line.
if self.for_python and '#' in text:
# Remove any strings from the text before we check for '#'. This way
# we avoid thinking a # inside a string starts a comment.
t = re.sub(self.stringRe, self.replace_strings_with_dash, text)
sharp_pos = t.find('#')
if sharp_pos >= 0: # Do we still have a #?
self.setFormat(sharp_pos, len(text), self.Formats["comment"])
self.setCurrentBlockState(NORMAL)
if self.for_python and self.checkTripleInStringRe.search(text) is None:
# This is fooled by triple quotes inside single quoted strings
for m, state in (
(self.tripleSingleRe.search(text), TRIPLESINGLE),
(self.tripleDoubleRe.search(text), TRIPLEDOUBLE)
):
i = -1 if m is None else m.start()
if self.previousBlockState() == state:
if i == -1:
i = len(text)
self.setCurrentBlockState(state)
self.setFormat(0, i + 3, self.Formats["string"])
elif i > -1:
self.setCurrentBlockState(state)
self.setFormat(i, len(text), self.Formats["string"])
if self.generate_paren_positions:
t = str(text)
i = 0
found_quote = False
while i < len(t):
c = t[i]
if c == ':':
# Deal with the funky syntax of template program mode.
# This won't work if there are more than one template
# expression in the document.
if not found_quote and i+1 < len(t) and t[i+1] == "'":
i += 2
elif c in ["'", '"']:
found_quote = True
i += 1
j = t[i:].find(c)
if j < 0:
i = len(t)
else:
i = i + j
elif c in ('(', ')'):
pp = ParenPosition(bn, i, c)
self.paren_positions.append(pp)
self.paren_pos_map[bn*self.BN_FACTOR+i] = pp
i += 1
def rehighlight(self):
QApplication.setOverrideCursor(QCursor(Qt.CursorShape.WaitCursor))
super().rehighlight()
QApplication.restoreOverrideCursor()
def check_cursor_pos(self, chr_, block, pos_in_block):
paren_pos = -1
for i, pp in enumerate(self.paren_positions):
pp.set_highlight(False)
if pp.block == block and pp.pos == pos_in_block:
paren_pos = i
if chr_ not in ('(', ')'):
if self.highlighted_paren:
self.rehighlight()
self.highlighted_paren = False
return
if paren_pos >= 0:
stack = 0
if chr_ == '(':
list_ = self.paren_positions[paren_pos+1:]
else:
list_ = reversed(self.paren_positions[0:paren_pos])
for pp in list_:
if pp.paren == chr_:
stack += 1
elif stack:
stack -= 1
else:
pp.set_highlight(True)
self.paren_positions[paren_pos].set_highlight(True)
break
self.highlighted_paren = True
self.rehighlight()
def regenerate_paren_positions(self):
self.generate_paren_positions = True
self.paren_positions = []
self.paren_pos_map = {}
self.rehighlight()
self.generate_paren_positions = False
translate_table = str.maketrans({
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
'\\': '\\\\',
})
class TemplateDialog(QDialog, Ui_TemplateDialog):
tester_closed = pyqtSignal(object, object)
def setWindowTitle(self, title, dialog_number=None):
if dialog_number is None:
title = _('{title} (only one template dialog allowed)').format(title=title)
else:
title = _('{title} dialog number {number} (multiple template dialogs allowed)').format(
title=title, number=dialog_number)
super().setWindowTitle(title)
def __init__(self, parent, text, mi=None, fm=None, color_field=None,
icon_field_key=None, icon_rule_kind=None, doing_emblem=False,
text_is_placeholder=False, dialog_is_st_editor=False,
global_vars=None, all_functions=None, builtin_functions=None,
python_context_object=None, dialog_number=None):
# If dialog_number isn't None then we want separate non-modal windows
# that don't stay on top of the main dialog. This lets Alt-Tab work to
# switch between them. dialog_number must be set only by the template
# tester, not the rules dialogs etc that depend on modality.
if dialog_number is None:
QDialog.__init__(self, parent, flags=Qt.WindowType.Dialog)
else:
QDialog.__init__(self, None, flags=Qt.WindowType.Window)
self.raise_and_focus() # Not needed on windows but here just in case
Ui_TemplateDialog.__init__(self)
self.setupUi(self)
self.setWindowIcon(self.windowIcon())
self.dialog_number = dialog_number
self.coloring = color_field is not None
self.iconing = icon_field_key is not None
self.embleming = doing_emblem
self.dialog_is_st_editor = dialog_is_st_editor
self.global_vars = global_vars or {}
self.python_context_object = python_context_object or PythonTemplateContext()
cols = []
self.fm = fm
if fm is not None:
for key in sorted(displayable_columns(fm),
key=lambda k: sort_key(fm[k]['name'] if k != color_row_key else 0)):
if key == color_row_key and not self.coloring:
continue
from calibre.gui2.preferences.coloring import all_columns_string
name = all_columns_string if key == color_row_key else fm[key]['name']
if name:
cols.append((name, key))
self.color_layout.setVisible(False)
self.icon_layout.setVisible(False)
if self.coloring:
self.color_layout.setVisible(True)
for n1, k1 in cols:
self.colored_field.addItem(n1 +
(' (' + k1 + ')' if k1 != color_row_key else ''), k1)
self.colored_field.setCurrentIndex(self.colored_field.findData(color_field))
elif self.iconing or self.embleming:
self.icon_layout.setVisible(True)
self.icon_select_layout.setContentsMargins(0, 0, 0, 0)
if self.embleming:
self.icon_kind_label.setVisible(False)
self.icon_kind.setVisible(False)
self.icon_chooser_label.setVisible(False)
self.icon_field.setVisible(False)
for n1, k1 in cols:
self.icon_field.addItem(f'{n1} ({k1})', k1)
self.icon_file_names = []
d = os.path.join(config_dir, 'cc_icons')
if os.path.exists(d):
for icon_file in os.listdir(d):
icon_file = icu_lower(icon_file)
if os.path.exists(os.path.join(d, icon_file)):
if icon_file.endswith('.png'):
self.icon_file_names.append(icon_file)
self.icon_file_names.sort(key=sort_key)
self.update_filename_box()
if self.iconing:
dex = 0
from calibre.gui2.preferences.coloring import icon_rule_kinds
for i,tup in enumerate(icon_rule_kinds):
txt,val = tup
self.icon_kind.addItem(txt, userData=(val))
if val == icon_rule_kind:
dex = i
self.icon_kind.setCurrentIndex(dex)
self.icon_field.setCurrentIndex(self.icon_field.findData(icon_field_key))
self.setup_saved_template_editor(not dialog_is_st_editor, dialog_is_st_editor)
self.all_functions = all_functions if all_functions else formatter_functions().get_functions()
self.builtins = (builtin_functions if builtin_functions else
formatter_functions().get_builtins_and_aliases())
# Set up the breakpoint bar
s = gprefs.get('template_editor_break_on_print', False)
self.go_button.setEnabled(s)
self.remove_all_button.setEnabled(s)
self.set_all_button.setEnabled(s)
self.toggle_button.setEnabled(s)
self.breakpoint_line_box.setEnabled(s)
self.breakpoint_line_box_label.setEnabled(s)
self.break_box.setChecked(s)
self.break_box.stateChanged.connect(self.break_box_changed)
self.go_button.clicked.connect(self.go_button_pressed)
# Set up the display table
self.table_column_widths = None
try:
self.table_column_widths = gprefs.get(self.geometry_string('template_editor_table_widths'), None)
except:
pass
self.set_mi(mi, fm)
self.last_text = ''
self.highlighting_gpm = True
self.highlighter = TemplateHighlighter(self.textbox.document(), builtin_functions=self.builtins)
self.textbox.cursorPositionChanged.connect(self.text_cursor_changed)
self.textbox.textChanged.connect(self.textbox_changed)
self.set_editor_font()
self.documentation.setReadOnly(True)
self.source_code.setReadOnly(True)
if text is not None:
if text_is_placeholder:
self.textbox.setPlaceholderText(text)
self.textbox.clear()
text = ''
else:
self.textbox.setPlainText(text)
else:
text = ''
self.original_text = text
self.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setText(_('&OK'))
self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setText(_('&Cancel'))
self.color_copy_button.clicked.connect(self.color_to_clipboard)
self.filename_button.clicked.connect(self.filename_button_clicked)
self.icon_copy_button.clicked.connect(self.icon_to_clipboard)
try:
with open(P('template-functions.json'), 'rb') as f:
self.builtin_source_dict = json.load(f, encoding='utf-8')
except:
self.builtin_source_dict = {}
func_names = sorted(self.all_functions)
self.function.clear()
self.function.addItem('')
for f in func_names:
self.function.addItem('{} -- {}'.format(f,
self.function_type_string(f, longform=False)), f)
self.function.setCurrentIndex(0)
self.function.currentIndexChanged.connect(self.function_changed)
self.rule = (None, '')
tt = _('Template language tutorial')
self.template_tutorial.setText(
'<a href="{}">{}</a>'.format(
localize_user_manual_link('https://manual.calibre-ebook.com/template_lang.html'), tt))
tt = _('Template function reference')
self.template_func_reference.setText(
'<a href="{}">{}</a>'.format(
localize_user_manual_link('https://manual.calibre-ebook.com/generated/en/template_ref.html'), tt))
self.textbox.setFocus()
self.set_up_font_boxes()
self.toggle_button.clicked.connect(self.toggle_button_pressed)
self.remove_all_button.clicked.connect(self.remove_all_button_pressed)
self.set_all_button.clicked.connect(self.set_all_button_pressed)
self.load_button.clicked.connect(self.load_template_from_file)
self.save_button.clicked.connect(self.save_template)
self.set_word_wrap(gprefs.get('gpm_template_editor_word_wrap_mode', True))
self.textbox.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.textbox.customContextMenuRequested.connect(self.show_context_menu)
# Now geometry
self.restore_geometry(gprefs, self.geometry_string('template_editor_dialog_geometry'))
def geometry_string(self, txt):
if self.dialog_number is None or self.dialog_number == 0:
return txt
return txt + '_' + str(self.dialog_number)
def setup_saved_template_editor(self, show_buttonbox, show_doc_and_name):
self.buttonBox.setVisible(show_buttonbox)
self.new_doc_label.setVisible(show_doc_and_name)
self.new_doc.setVisible(show_doc_and_name)
self.template_name_label.setVisible(show_doc_and_name)
self.template_name.setVisible(show_doc_and_name)
def set_mi(self, mi, fm):
'''
This sets the metadata for the test result books table. It doesn't reset
the contents of the field selectors for editing rules.
'''
self.fm = fm
from calibre.gui2.ui import get_gui
if mi:
if not isinstance(mi, (tuple, list)):
mi = (mi, )
else:
mi = Metadata(_('Title'), [_('Author')])
mi.author_sort = _('Author Sort')
mi.series = ngettext('Series', 'Series', 1)
mi.series_index = 3
mi.rating = 4.0
mi.tags = [_('Tag 1'), _('Tag 2')]
mi.languages = ['eng']
mi.id = -1
if self.fm is not None:
mi.set_all_user_metadata(self.fm.custom_field_metadata())
else:
# No field metadata. Grab a copy from the current library so
# that we can validate any custom column names. The values for
# the columns will all be empty, which in some very unusual
# cases might cause formatter errors. We can live with that.
fm = get_gui().current_db.new_api.field_metadata
mi.set_all_user_metadata(fm.custom_field_metadata())
for col in mi.get_all_user_metadata(False):
if fm[col]['datatype'] == 'datetime':
mi.set(col, DEFAULT_DATE)
elif fm[col]['datatype'] in ('int', 'float', 'rating'):
mi.set(col, 2)
elif fm[col]['datatype'] == 'bool':
mi.set(col, False)
elif fm[col]['is_multiple']:
mi.set(col, [col])
else:
mi.set(col, col, 1)
mi = (mi, )
self.mi = mi
tv = self.template_value
tv.setColumnCount(3)
tv.setHorizontalHeaderLabels((_('Book title'), '', _('Template value')))
tv.horizontalHeader().setStretchLastSection(True)
tv.horizontalHeader().sectionResized.connect(self.table_column_resized)
tv.setRowCount(len(mi))
# Set the height of the table
h = tv.rowHeight(0) * min(len(mi), 5)
h += 2 * tv.frameWidth() + tv.horizontalHeader().height()
tv.setMinimumHeight(h)
tv.setMaximumHeight(h)
# Set the size of the title column
if self.table_column_widths:
tv.setColumnWidth(0, self.table_column_widths[0])
else:
tv.setColumnWidth(0, tv.fontMetrics().averageCharWidth() * 10)
tv.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
tv.setRowCount(len(mi))
# Use our own widget to get rid of elision. setTextElideMode() doesn't work
for r in range(0, len(mi)):
w = QLineEdit(tv)
w.setReadOnly(True)
w.setText(mi[r].title)
tv.setCellWidget(r, 0, w)
tb = QToolButton()
tb.setContentsMargins(0, 0, 0, 0)
tb.setIcon(QIcon.ic("edit_input.png"))
tb.setToolTip(_('Open Edit metadata on this book'))
tb.clicked.connect(partial(self.metadata_button_clicked, r))
tb.setEnabled(mi[r].get('id', -1) >= 0)
tv.setCellWidget(r, 1, tb)
w = QLineEdit(tv)
w.setReadOnly(True)
tv.setCellWidget(r, 2, w)
tv.resizeColumnToContents(1)
self.set_waiting_message()
def metadata_button_clicked(self, row):
# Get the booklist row number for the book
mi = self.mi[row]
id_ = mi.get('id', -1)
if id_ > 0:
from calibre.gui2.ui import get_gui
db = get_gui().current_db
try:
idx = db.data.id_to_index(id_)
em = get_gui().iactions['Edit Metadata']
from calibre.gui2.library.views import PreserveViewState
with PreserveViewState(get_gui().current_view(), require_selected_ids=False):
with em.different_parent(self):
em.edit_metadata_for([idx], [id_], bulk=False)
except Exception:
pass
new_mi = []
for mi in self.mi:
try:
pmi = db.new_api.get_proxy_metadata(mi.get('id'))
except Exception:
pmi = None
new_mi.append(pmi)
self.set_mi(new_mi, self.fm)
if not self.break_box.isChecked():
self.display_values(str(self.textbox.toPlainText()))
def set_waiting_message(self):
if self.break_box.isChecked():
for i in range(len(self.mi)):
self.template_value.cellWidget(i, 2).setText('')
self.template_value.cellWidget(0, 2).setText(
_("*** Breakpoints are enabled. Waiting for the 'Go' button to be pressed"))
def show_context_menu(self, point):
m = self.textbox.createStandardContextMenu()
m.addSeparator()
word_wrapping = gprefs['gpm_template_editor_word_wrap_mode']
if word_wrapping:
ca = m.addAction(_('Disable word wrap'))
ca.setIcon(QIcon.ic('list_remove.png'))
else:
ca = m.addAction(_('Enable word wrap'))
ca.setIcon(QIcon.ic('ok.png'))
ca.triggered.connect(partial(self.set_word_wrap, not word_wrapping))
m.addSeparator()
ca = m.addAction(_('Add Python template definition text'))
ca.triggered.connect(self.add_python_template_header_text)
m.addSeparator()
ca = m.addAction(_('Load template from the Template tester'))
m.addSeparator()
ca.triggered.connect(self.load_last_template_text)
ca = m.addAction(_('Load template from file'))
ca.setIcon(QIcon.ic('document_open.png'))
ca.triggered.connect(self.load_template_from_file)
ca = m.addAction(_('Save template to file'))
ca.setIcon(QIcon.ic('save.png'))
ca.triggered.connect(self.save_template)
m.exec(self.textbox.mapToGlobal(point))
def add_python_template_header_text(self):
self.textbox.setPlainText('''python:
def evaluate(book, context):
\t# book is a calibre metadata object
\t# context is an instance of calibre.utils.formatter.PythonTemplateContext,
\t# which currently contains the following attributes:
\t# db: a calibre legacy database object.
\t# globals: the template global variable dictionary.
\t# arguments: is a list of arguments if the template is called by a GPM template, otherwise None.
\t# funcs: used to call Built-in/User functions and Stored GPM/Python templates.
\t# Example: context.funcs.list_re_group()
\t# your Python code goes here
\treturn 'a string'
''')
def set_word_wrap(self, to_what):
gprefs['gpm_template_editor_word_wrap_mode'] = to_what
self.textbox.setWordWrapMode(QTextOption.WrapMode.WordWrap if to_what else QTextOption.WrapMode.NoWrap)
def load_last_template_text(self):
from calibre.customize.ui import find_plugin
tt = find_plugin('Template Tester')
if tt and tt.actual_plugin_:
self.textbox.setPlainText(tt.actual_plugin_.last_template_text())
else:
# I don't think we can get here, but just in case ...
self.textbox.setPlainText(_('No Template tester text is available'))
def load_template_from_file(self):
filename = choose_files(self, 'template_dialog_save_templates',
_('Load template from file'),
filters=[
(_('Template file'), ['txt'])
], select_only_single_file=True)
if filename:
with open(filename[0]) as f:
self.textbox.setPlainText(f.read())
def save_template(self):
filename = choose_save_file(self, 'template_dialog_save_templates',
_('Save template to file'),
filters=[
(_('Template file'), ['txt'])
])
if filename:
with open(filename, 'w') as f:
f.write(str(self.textbox.toPlainText()))
def get_current_font(self):
font_name = gprefs.get('gpm_template_editor_font', None)
size = gprefs['gpm_template_editor_font_size']
if font_name is None:
font = QFont()
font.setFixedPitch(True)
font.setPointSize(size)
else:
font = QFont(font_name, pointSize=size)
return font
def set_editor_font(self):
font = self.get_current_font()
fm = QFontMetrics(font)
chars = tweaks['template_editor_tab_stop_width']
w = fm.averageCharWidth() * chars
self.textbox.setTabStopDistance(w)
self.source_code.setTabStopDistance(w)
self.textbox.setFont(font)
self.highlighter.initialize_formats()
self.highlighter.rehighlight()
def set_up_font_boxes(self):
font = self.get_current_font()
self.font_box.setWritingSystem(QFontDatabase.WritingSystem.Latin)
self.font_box.setCurrentFont(font)
self.font_box.setEditable(False)
gprefs['gpm_template_editor_font'] = str(font.family())
self.font_size_box.setValue(font.pointSize())
self.font_box.currentFontChanged.connect(self.font_changed)
self.font_size_box.valueChanged.connect(self.font_size_changed)
def font_changed(self, font):
fi = QFontInfo(font)
gprefs['gpm_template_editor_font'] = str(fi.family())
self.set_editor_font()
def font_size_changed(self, toWhat):
gprefs['gpm_template_editor_font_size'] = toWhat
self.set_editor_font()
def break_box_changed(self, new_state):
gprefs['template_editor_break_on_print'] = new_state != 0
self.go_button.setEnabled(new_state != 0)
self.remove_all_button.setEnabled(new_state != 0)
self.set_all_button.setEnabled(new_state != 0)
self.toggle_button.setEnabled(new_state != 0)
self.breakpoint_line_box.setEnabled(new_state != 0)
self.breakpoint_line_box_label.setEnabled(new_state != 0)
if new_state == 0:
self.display_values(str(self.textbox.toPlainText()))
else:
self.set_waiting_message()
def go_button_pressed(self):
self.display_values(str(self.textbox.toPlainText()))
def remove_all_button_pressed(self):
self.textbox.set_clicked_line_numbers(set())
def set_all_button_pressed(self):
self.textbox.set_clicked_line_numbers({i for i in range(1, self.textbox.blockCount()+1)})
def toggle_button_pressed(self):
ln = self.breakpoint_line_box.value()
if ln > self.textbox.blockCount():
return
cln = self.textbox.clicked_line_numbers
if ln:
if ln in self.textbox.clicked_line_numbers:
cln.discard(ln)
else:
cln.add(ln)
self.textbox.set_clicked_line_numbers(cln)
def break_reporter(self, txt, val, locals_={}, line_number=0):
l = self.template_value.selectionModel().selectedRows()
mi_to_use = self.mi[0 if len(l) == 0 else l[0].row()]
if self.break_box.isChecked():
if line_number is None or line_number not in self.textbox.clicked_line_numbers:
return
self.break_reporter_dialog = BreakReporter(self, mi_to_use,
txt, val, locals_, line_number)
if not self.break_reporter_dialog.exec():
raise StopException()
def filename_button_clicked(self):
try:
path = choose_files(self, 'choose_category_icon',
_('Select icon'), filters=[
('Images', ['png', 'gif', 'jpg', 'jpeg'])],
all_files=False, select_only_single_file=True)
if path:
icon_path = path[0]
icon_name = sanitize_file_name(
os.path.splitext(
os.path.basename(icon_path))[0]+'.png')
if icon_name not in self.icon_file_names:
self.icon_file_names.append(icon_name)
self.update_filename_box()
try:
p = QIcon(icon_path).pixmap(QSize(128, 128))
d = os.path.join(config_dir, 'cc_icons')
if not os.path.exists(os.path.join(d, icon_name)):
if not os.path.exists(d):
os.makedirs(d)
with open(os.path.join(d, icon_name), 'wb') as f:
f.write(pixmap_to_data(p, format='PNG'))
except:
traceback.print_exc()
self.icon_files.setCurrentIndex(self.icon_files.findText(icon_name))
self.icon_files.adjustSize()
except:
traceback.print_exc()
return
def update_filename_box(self):
self.icon_files.clear()
self.icon_file_names.sort(key=sort_key)
self.icon_files.addItem('')
self.icon_files.addItems(self.icon_file_names)
for i,filename in enumerate(self.icon_file_names):
icon = QIcon(os.path.join(config_dir, 'cc_icons', filename))
self.icon_files.setItemIcon(i+1, icon)
def color_to_clipboard(self):
app = QApplication.instance()
c = app.clipboard()
c.setText(str(self.color_name.color))
def icon_to_clipboard(self):
app = QApplication.instance()
c = app.clipboard()
c.setText(str(self.icon_files.currentText()))
@property
def is_python(self):
return self.textbox.toPlainText().startswith('python:')
def textbox_changed(self):
cur_text = str(self.textbox.toPlainText())
if self.is_python:
if self.highlighting_gpm is True:
self.highlighter.initialize_rules(self.builtins, True)
self.highlighting_gpm = False
self.break_box.setEnabled(True)
elif not self.highlighting_gpm:
self.highlighter.initialize_rules(self.builtins, False)
self.highlighting_gpm = True
self.break_box.setEnabled(True)
if self.last_text != cur_text:
self.last_text = cur_text
self.highlighter.regenerate_paren_positions()
self.text_cursor_changed()
if not self.break_box.isChecked():
self.display_values(cur_text)
else:
self.set_waiting_message()
def trace_lines(self, frame, event, arg):
if event != 'line':
return
# Only respond to events in the "string" which is the template
if frame.f_code.co_filename != '<string>':
return
# Check that there is a breakpoint at the line
if frame.f_lineno not in self.textbox.clicked_line_numbers:
return
l = self.template_value.selectionModel().selectedRows()
mi_to_use = self.mi[0 if len(l) == 0 else l[0].row()]
self.break_reporter_dialog = PythonBreakReporter(self, mi_to_use, frame)
if not self.break_reporter_dialog.exec():
raise StopException()
def trace_calls(self, frame, event, arg):
if event != 'call':
return
# If this is the "string" file (the template), return the trace_lines function
if frame.f_code.co_filename == '<string>':
return self.trace_lines
return None
def display_values(self, txt):
tv = self.template_value
l = self.template_value.selectionModel().selectedRows()
break_on_mi = 0 if len(l) == 0 else l[0].row()
for r,mi in enumerate(self.mi):
w = tv.cellWidget(r, 0)
w.setText(mi.title)
w.setCursorPosition(0)
if self.break_box.isChecked() and r == break_on_mi and self.is_python:
sys.settrace(self.trace_calls)
else:
sys.settrace(None)
try:
v = SafeFormat().safe_format(txt, mi, _('EXCEPTION:'),
mi, global_vars=self.global_vars,
template_functions=self.all_functions,
break_reporter=self.break_reporter if r == break_on_mi else None,
python_context_object=self.python_context_object)
w = tv.cellWidget(r, 2)
w.setText(v.translate(translate_table))
w.setCursorPosition(0)
finally:
sys.settrace(None)
def text_cursor_changed(self):
cursor = self.textbox.textCursor()
position = cursor.position()
t = str(self.textbox.toPlainText())
if position > 0 and position <= len(t):
block_number = cursor.blockNumber()
pos_in_block = cursor.positionInBlock() - 1
self.highlighter.check_cursor_pos(t[position-1], block_number,
pos_in_block)
def function_type_string(self, name, longform=True):
if self.all_functions[name].object_type is StoredObjectType.PythonFunction:
if name in self.builtins:
return (_('Built-in template function') if longform else
_('Built-in function'))
return (_('User defined Python template function') if longform else
_('User function'))
elif self.all_functions[name].object_type is StoredObjectType.StoredPythonTemplate:
return (_('Stored user defined Python template') if longform else _('Stored template'))
return (_('Stored user defined GPM template') if longform else _('Stored template'))
def function_changed(self, toWhat):
name = str(self.function.itemData(toWhat))
self.source_code.clear()
self.documentation.clear()
self.func_type.clear()
if name in self.all_functions:
self.documentation.setPlainText(self.all_functions[name].doc)
if name in self.builtins and name in self.builtin_source_dict:
self.source_code.setPlainText(self.builtin_source_dict[name])
else:
self.source_code.setPlainText(self.all_functions[name].program_text)
self.func_type.setText(self.function_type_string(name, longform=True))
def table_column_resized(self, col, old, new):
self.table_column_widths = []
for c in range(0, self.template_value.columnCount()):
self.table_column_widths.append(self.template_value.columnWidth(c))
def save_geometry(self):
gprefs[self.geometry_string('template_editor_table_widths')] = self.table_column_widths
super().save_geometry(gprefs, self.geometry_string('template_editor_dialog_geometry'))
def keyPressEvent(self, ev):
if ev.key() == Qt.Key.Key_Escape:
# Check about ESC to avoid killing the dialog by mistake
if self.textbox.toPlainText() != self.original_text:
r = question_dialog(self, _('Discard changes?'),
_('Do you really want to close this dialog, discarding any changes?'))
if not r:
return
QDialog.keyPressEvent(self, ev)
def accept(self):
txt = str(self.textbox.toPlainText()).rstrip()
if (self.coloring or self.iconing or self.embleming) and not txt:
error_dialog(self, _('No template provided'),
_('The template box cannot be empty'), show=True)
return
if self.coloring:
if self.colored_field.currentIndex() == -1:
error_dialog(self, _('No column chosen'),
_('You must specify a column to be colored'), show=True)
return
self.rule = (str(self.colored_field.itemData(
self.colored_field.currentIndex()) or ''), txt)
elif self.iconing:
if self.icon_field.currentIndex() == -1:
error_dialog(self, _('No column chosen'),
_('You must specify the column where the icons are applied'), show=True)
return
rt = str(self.icon_kind.itemData(self.icon_kind.currentIndex()) or '')
self.rule = (rt,
str(self.icon_field.itemData(
self.icon_field.currentIndex()) or ''),
txt)
elif self.embleming:
self.rule = ('icon', 'title', txt)
else:
self.rule = ('', txt)
self.save_geometry()
QDialog.accept(self)
if self.dialog_number is not None:
self.tester_closed.emit(txt, self.dialog_number)
def reject(self):
self.save_geometry()
QDialog.reject(self)
if self.dialog_is_st_editor:
parent = self.parent()
while True:
if hasattr(parent, 'reject'):
parent.reject()
break
parent = parent.parent()
if parent is None:
break
if self.dialog_number is not None:
self.tester_closed.emit(None, self.dialog_number)
class BreakReporterItem(QTableWidgetItem):
def __init__(self, txt):
super().__init__(txt.translate(translate_table) if txt else txt)
self.setFlags(self.flags() & ~(Qt.ItemFlag.ItemIsEditable))
class BreakReporterBase(QDialog):
def setup_ui(self, mi, line_number, locals_, leading_rows):
self.mi = mi
self.leading_rows = leading_rows
self.setModal(True)
l = QVBoxLayout(self)
t = self.table = QTableWidget(self)
t.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
t.setColumnCount(2)
t.setHorizontalHeaderLabels((_('Name'), _('Value')))
t.setRowCount(leading_rows)
l.addWidget(t)
self.table_column_widths = None
try:
self.table_column_widths = \
gprefs.get('template_editor_break_table_widths', None)
t.setColumnWidth(0, self.table_column_widths[0])
except:
t.setColumnWidth(0, t.fontMetrics().averageCharWidth() * 20)
t.horizontalHeader().sectionResized.connect(self.table_column_resized)
t.horizontalHeader().setStretchLastSection(True)
bb = QDialogButtonBox()
b = bb.addButton(_('&Continue'), QDialogButtonBox.ButtonRole.AcceptRole)
b.setIcon(QIcon.ic('sync-right.png'))
b.setToolTip(_('Continue running the template'))
b.setDefault(True)
l.addWidget(bb)
b = bb.addButton(_('&Stop'), QDialogButtonBox.ButtonRole.RejectRole)
b.setIcon(QIcon.ic('list_remove.png'))
b.setToolTip(_('Stop running the template'))
l.addWidget(bb)
bb.accepted.connect(self.accept)
bb.rejected.connect(self.reject)
self.setLayout(l)
self.setWindowTitle(_('Break: line {0}, book {1}').format(line_number, self.mi.title))
self.mi_combo = QComboBox()
t.setCellWidget(leading_rows-1, 0, self.mi_combo)
self.mi_combo.addItems(self.get_field_keys())
self.mi_combo.setToolTip('Choose a book metadata field to display')
self.mi_combo.currentTextChanged.connect(self.get_field_value)
self.mi_combo.setCurrentIndex(self.mi_combo.findText('title'))
self.restore_geometry(gprefs, 'template_editor_break_geometry')
self.setup_locals(locals_)
def setup_locals(self, locals_):
raise NotImplementedError
def add_local_line(self, locals, row, key):
itm = BreakReporterItem(key)
itm.setToolTip(_('A variable in the template'))
self.table.setItem(row, 0, itm)
itm = BreakReporterItem(repr(locals[key]))
itm.setToolTip(_('The value of the variable'))
self.table.setItem(row, 1, itm)
def get_field_value(self, field):
val = self.displayable_field_value(self.mi, field)
self.table.setItem(self.leading_rows-1, 1, BreakReporterItem(val))
def displayable_field_value(self, mi, field):
raise NotImplementedError
def table_column_resized(self, col, old, new):
self.table_column_widths = []
for c in range(0, self.table.columnCount()):
self.table_column_widths.append(self.table.columnWidth(c))
def get_field_keys(self):
from calibre.gui2.ui import get_gui
keys = set(get_gui().current_db.new_api.field_metadata.displayable_field_keys())
keys.discard('sort')
keys.discard('timestamp')
keys.add('title_sort')
keys.add('date')
return sorted(keys)
def save_geometry(self):
super().save_geometry(gprefs, 'template_editor_break_geometry')
gprefs['template_editor_break_table_widths'] = self.table_column_widths
def reject(self):
self.save_geometry()
QDialog.reject(self)
def accept(self):
self.save_geometry()
QDialog.accept(self)
class BreakReporter(BreakReporterBase):
def __init__(self, parent, mi, op_label, op_value, locals_, line_number):
super().__init__(parent)
self.setup_ui(mi, line_number, locals_, leading_rows=2)
self.table.setItem(0, 0, BreakReporterItem(op_label))
self.table.item(0,0).setToolTip(_('The name of the template language operation'))
self.table.setItem(0, 1, BreakReporterItem(op_value))
def setup_locals(self, locals):
local_names = sorted(locals.keys())
rows = len(local_names)
self.table.setRowCount(rows+2)
for i,k in enumerate(local_names, start=2):
self.add_local_line(locals, i, k)
def displayable_field_value(self, mi, field):
return self.mi.format_field('timestamp' if field == 'date' else field)[1]
class PythonBreakReporter(BreakReporterBase):
def __init__(self, parent, mi, frame):
super().__init__(parent)
self.frame = frame
line_number = frame.f_lineno
locals = frame.f_locals
self.setup_ui(mi, line_number, locals, leading_rows=1)
def setup_locals(self, locals):
locals = self.frame.f_locals
local_names = sorted(k for k in locals.keys() if k not in ('book', 'context'))
rows = len(local_names)
self.table.setRowCount(rows+1)
for i,k in enumerate(local_names, start=1):
if k in ('book', 'context'):
continue
self.add_local_line(locals, i, k)
def displayable_field_value(self, mi, field):
return repr(self.mi.get('timestamp' if field == 'date' else field))
class EmbeddedTemplateDialog(TemplateDialog):
def __init__(self, parent):
TemplateDialog.__init__(self, parent, _('A General Program Mode Template'), text_is_placeholder=True,
dialog_is_st_editor=True)
self.setParent(parent)
self.setWindowFlags(Qt.WindowType.Widget)
if __name__ == '__main__':
from calibre.gui2 import Application
app = Application([])
from calibre.ebooks.metadata.book.base import field_metadata
d = TemplateDialog(None, '{title}', fm=field_metadata)
d.exec()
del app
| 49,542 | Python | .py | 1,044 | 35.617816 | 114 | 0.582765 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,001 | exim.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/exim.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
import os
import stat
from functools import partial
from threading import Event, Thread
from qt.core import (
QAbstractItemView,
QDialog,
QDialogButtonBox,
QFrame,
QGridLayout,
QIcon,
QLabel,
QLineEdit,
QListWidget,
QListWidgetItem,
QProgressBar,
QPushButton,
QScrollArea,
QSize,
QStackedLayout,
Qt,
QVBoxLayout,
QWidget,
pyqtSignal,
)
from calibre import as_unicode, human_readable
from calibre.constants import iswindows
from calibre.db.legacy import LibraryDatabase
from calibre.gui2 import choose_dir, error_dialog, question_dialog
from calibre.gui2.widgets2 import Dialog
from calibre.startup import connect_lambda
from calibre.utils.exim import Importer, all_known_libraries, export, import_data
from calibre.utils.icu import numeric_sort_key
def disk_usage(path_to_dir, abort=None):
stack = [path_to_dir]
ans = 0
while stack:
bdir = stack.pop()
try:
for child in os.listdir(bdir):
cpath = os.path.join(bdir, child)
if abort is not None and abort.is_set():
return -1
r = os.lstat(cpath)
if stat.S_ISDIR(r.st_mode):
stack.append(cpath)
ans += r.st_size
except OSError:
pass
return ans
class ImportLocation(QWidget):
def __init__(self, lpath, parent=None):
QWidget.__init__(self, parent)
self.l = l = QGridLayout(self)
self.la = la = QLabel(_('Previous location: ') + lpath)
la.setWordWrap(True)
self.lpath = lpath
l.addWidget(la, 0, 0, 1, -1)
self.le = le = QLineEdit(self)
le.setPlaceholderText(_('Location to import this library to'))
l.addWidget(le, 1, 0)
self.b = b = QPushButton(QIcon.ic('document_open.png'), _('Select &folder'), self)
b.clicked.connect(self.select_folder)
l.addWidget(b, 1, 1)
self.lpath = lpath
def select_folder(self):
path = choose_dir(self, 'select-folder-for-imported-library', _('Choose a folder for this library'))
if path is not None:
self.le.setText(path)
@property
def path(self):
return self.le.text().strip()
class RunAction(QDialog):
update_current_signal = pyqtSignal(object, object, object)
update_overall_signal = pyqtSignal(object, object, object)
finish_signal = pyqtSignal()
def __init__(self, title, err_msg, action, parent=None):
QDialog.__init__(self, parent)
self.setWindowTitle(_('Working, please wait...'))
self.title, self.action, self.tb, self.err_msg = title, action, None, err_msg
self.abort = Event()
self.setup_ui()
t = Thread(name='ExImWorker', target=self.run_action)
t.daemon = True
t.start()
def setup_ui(self):
self.l = l = QGridLayout(self)
self.bb = QDialogButtonBox(self)
self.bb.setStandardButtons(QDialogButtonBox.StandardButton.Cancel)
self.bb.rejected.connect(self.reject)
self.la1 = la = QLabel('<h2>' + self.title)
l.addWidget(la, 0, 0, 1, -1)
self.la2 = la = QLabel(_('Total:'))
l.addWidget(la, l.rowCount(), 0)
self.overall = p = QProgressBar(self)
p.setMinimum(0), p.setValue(0), p.setMaximum(0)
p.setMinimumWidth(450)
l.addWidget(p, l.rowCount()-1, 1)
self.omsg = la = QLabel(self)
la.setMaximumWidth(450)
l.addWidget(la, l.rowCount(), 1)
self.la3 = la = QLabel(_('Current:'))
l.addWidget(la, l.rowCount(), 0)
self.current = p = QProgressBar(self)
p.setMinimum(0), p.setValue(0), p.setMaximum(0)
l.addWidget(p, l.rowCount()-1, 1)
self.cmsg = la = QLabel(self)
la.setMaximumWidth(450)
l.addWidget(la, l.rowCount(), 1)
l.addWidget(self.bb, l.rowCount(), 0, 1, -1)
self.update_current_signal.connect(self.update_current, type=Qt.ConnectionType.QueuedConnection)
self.update_overall_signal.connect(self.update_overall, type=Qt.ConnectionType.QueuedConnection)
self.finish_signal.connect(self.finish_processing, type=Qt.ConnectionType.QueuedConnection)
def update_overall(self, msg, count, total):
self.overall.setMaximum(total), self.overall.setValue(count)
self.omsg.setText(msg)
def update_current(self, msg, count, total):
self.current.setMaximum(total), self.current.setValue(count)
self.cmsg.setText(msg)
def reject(self):
self.abort.set()
self.bb.button(QDialogButtonBox.StandardButton.Cancel).setEnabled(False)
def finish_processing(self):
if self.abort.is_set():
return QDialog.reject(self)
if self.tb is not None:
error_dialog(self, _('Failed'), self.err_msg + ' ' + _('Click "Show details" for more information.'),
det_msg=self.tb, show=True)
self.accept()
def run_action(self):
try:
self.action(abort=self.abort, progress1=self.update_overall_signal.emit, progress2=self.update_current_signal.emit)
except Exception:
import traceback
self.tb = traceback.format_exc()
self.finish_signal.emit()
class EximDialog(Dialog):
update_disk_usage = pyqtSignal(object, object)
def __init__(self, parent=None, initial_panel=None):
self.initial_panel = initial_panel
self.abort_disk_usage = Event()
self.restart_needed = False
Dialog.__init__(self, _('Export/import all calibre data'), 'exim-calibre', parent=parent)
def sizeHint(self):
return QSize(800, 600)
def setup_ui(self):
self.l = l = QVBoxLayout(self)
self.stack = s = QStackedLayout()
l.addLayout(s)
l.addWidget(self.bb)
self.welcome = w = QWidget(self)
s.addWidget(w)
w.l = l = QVBoxLayout(w)
w.la = la = QLabel('<p>' + _(
'You can export all calibre data, including your books, settings and plugins'
' into a single folder. Then, you can use this tool to re-import all that'
' data into a different calibre install, for example, on another computer.') + '<p>' +
_(
'This is a simple way to move your calibre installation with all its data to'
' a new computer, or to replicate your current setup on a second computer.'
))
la.setWordWrap(True)
l.addWidget(la)
l.addSpacing(20)
self.exp_button = b = QPushButton(_('&Export all your calibre data'))
connect_lambda(b.clicked, self, lambda self: self.show_panel('export'))
l.addWidget(b), l.addSpacing(20)
self.imp_button = b = QPushButton(_('&Import previously exported data'))
connect_lambda(b.clicked, self, lambda self: self.show_panel('import'))
l.addWidget(b), l.addStretch(20)
self.setup_export_panel()
self.setup_import_panel()
self.show_panel(self.initial_panel)
def export_lib_text(self, lpath, size=None):
return _('{0} [Size: {1}]\nin {2}').format(
os.path.basename(lpath), ('' if size < 0 else human_readable(size))
if size is not None else _('Calculating...'), os.path.dirname(lpath))
def setup_export_panel(self):
self.export_panel = w = QWidget(self)
self.stack.addWidget(w)
w.l = l = QVBoxLayout(w)
w.la = la = QLabel(_('Select which libraries you want to export below'))
la.setWordWrap(True), l.addWidget(la)
self.lib_list = ll = QListWidget(self)
l.addWidget(ll)
ll.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
ll.setStyleSheet('QListView::item { padding: 5px }')
ll.setAlternatingRowColors(True)
lpaths = all_known_libraries()
for lpath in sorted(lpaths, key=lambda x:numeric_sort_key(os.path.basename(x))):
i = QListWidgetItem(self.export_lib_text(lpath), ll)
i.setData(Qt.ItemDataRole.UserRole, lpath)
i.setData(Qt.ItemDataRole.UserRole+1, lpaths[lpath])
i.setIcon(QIcon.ic('lt.png'))
i.setSelected(True)
self.update_disk_usage.connect((
lambda i, sz: self.lib_list.item(i).setText(self.export_lib_text(
self.lib_list.item(i).data(Qt.ItemDataRole.UserRole), sz))), type=Qt.ConnectionType.QueuedConnection)
def get_lib_sizes(self):
for i in range(self.lib_list.count()):
path = self.lib_list.item(i).data(Qt.ItemDataRole.UserRole)
try:
sz = disk_usage(path, abort=self.abort_disk_usage)
except Exception:
import traceback
traceback.print_exc()
self.update_disk_usage.emit(i, sz)
def setup_import_panel(self):
self.import_panel = w = QWidget(self)
self.stack.addWidget(w)
w.stack = s = QStackedLayout(w)
self.ig = w = QWidget()
s.addWidget(w)
w.l = l = QVBoxLayout(w)
w.la = la = QLabel(_('Specify the folder containing the previously exported calibre data that you'
' wish to import.'))
la.setWordWrap(True)
l.addWidget(la)
self.export_dir_button = b = QPushButton(QIcon.ic('document_open.png'), _('Choose &folder'), self)
b.clicked.connect(self.select_import_folder)
l.addWidget(b), l.addStretch()
self.select_libraries_panel = w = QScrollArea(self)
w.setWidgetResizable(True)
s.addWidget(w)
self.slp = w = QWidget(self)
self.select_libraries_panel.setWidget(w)
w.l = l = QVBoxLayout(w)
w.la = la = QLabel(_('Specify locations for the libraries you want to import. A location must be an empty folder'
' on your computer. If you leave any blank, those libraries will not be imported.'))
la.setWordWrap(True)
l.addWidget(la)
def select_import_folder(self):
path = choose_dir(self, 'choose-export-folder-for-import', _('Select folder with exported data'))
if path is None:
return
if not question_dialog(self, _('Are you sure?'), _(
'Importing calibre data means all libraries, settings, plugins, etc will be imported. This is'
' a security risk, only proceed if the data you are importing was previously generated by you, using the calibre'
' export functionality.'
)):
return
try:
self.importer = Importer(path)
except Exception as e:
import traceback
return error_dialog(self, _('Not valid'), _(
'The folder {0} is not valid: {1}').format(path, as_unicode(e)), det_msg=traceback.format_exc(), show=True)
self.setup_select_libraries_panel()
self.import_panel.stack.setCurrentIndex(1)
def setup_select_libraries_panel(self):
self.imported_lib_widgets = []
self.frames = []
l = self.slp.layout()
for lpath in sorted(self.importer.metadata['libraries'], key=lambda x:numeric_sort_key(os.path.basename(x))):
f = QFrame(self)
self.frames.append(f)
l.addWidget(f)
f.setFrameShape(QFrame.Shape.HLine)
w = ImportLocation(lpath, self.slp)
l.addWidget(w)
self.imported_lib_widgets.append(w)
l.addStretch()
def validate_import(self):
from calibre.gui2.ui import get_gui
g = get_gui()
if g is not None:
if g.iactions['Connect Share'].content_server_is_running:
error_dialog(self, _('Content server running'), _(
'Cannot import while the Content server is running, shut it down first by clicking the'
' "Connect/share" button on the calibre toolbar'), show=True)
return False
if self.import_panel.stack.currentIndex() == 0:
error_dialog(self, _('No folder selected'), _(
'You must select a folder containing the previously exported data that you wish to import'), show=True)
return False
else:
blanks = []
for w in self.imported_lib_widgets:
newloc = w.path
if not newloc:
blanks.append(w.lpath)
continue
if iswindows and len(newloc) > LibraryDatabase.WINDOWS_LIBRARY_PATH_LIMIT:
error_dialog(self, _('Too long'),
_('Path to library ({0}) too long. It must be less than'
' {1} characters.').format(newloc, LibraryDatabase.WINDOWS_LIBRARY_PATH_LIMIT), show=True)
return False
if not os.path.isdir(newloc):
error_dialog(self, _('Not a folder'), _('%s is not a folder')%newloc, show=True)
return False
if os.listdir(newloc):
error_dialog(self, _('Folder not empty'), _('%s is not an empty folder')%newloc, show=True)
return False
if blanks:
if len(blanks) == len(self.imported_lib_widgets):
error_dialog(self, _('No libraries selected'), _(
'You must specify the location for at least one library'), show=True)
return False
if not question_dialog(self, _('Some libraries ignored'), _(
'You have chosen not to import some libraries. Proceed anyway?')):
return False
return True
def show_panel(self, which):
self.validate = self.run_action = lambda : True
if which is None:
self.bb.setStandardButtons(QDialogButtonBox.StandardButton.Cancel)
else:
if which == 'export':
self.validate = self.validate_export
self.run_action = self.run_export_action
t = Thread(name='GetLibSizes', target=self.get_lib_sizes)
t.daemon = True
t.start()
else:
self.validate = self.validate_import
self.run_action = self.run_import_action
self.bb.setStandardButtons(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
self.stack.setCurrentIndex({'export':1, 'import':2}.get(which, 0))
def validate_export(self):
path = choose_dir(self, 'export-calibre-dir', _('Choose a folder to export to'))
if not path:
return False
if os.listdir(path):
error_dialog(self, _('Export folder not empty'), _(
'The folder you choose to export the data to must be empty.'), show=True)
return False
self.export_dir = path
return True
def run_export_action(self):
from calibre.gui2.ui import get_gui
library_paths = {i.data(Qt.ItemDataRole.UserRole):i.data(Qt.ItemDataRole.UserRole+1) for i in self.lib_list.selectedItems()}
dbmap = {}
gui = get_gui()
if gui is not None:
db = gui.current_db
dbmap[db.library_path] = db.new_api
return RunAction(_('Exporting all calibre data...'), _(
'Failed to export data.'), partial(export, self.export_dir, library_paths=library_paths, dbmap=dbmap),
parent=self).exec() == QDialog.DialogCode.Accepted
def run_import_action(self):
library_path_map = {}
for w in self.imported_lib_widgets:
if w.path:
library_path_map[w.lpath] = w.path
return RunAction(_('Importing all calibre data...'), _(
'Failed to import data.'), partial(import_data, self.importer, library_path_map), parent=self).exec() == QDialog.DialogCode.Accepted
def accept(self):
if not self.validate():
return
self.abort_disk_usage.set()
if self.run_action():
self.restart_needed = self.stack.currentIndex() == 2
Dialog.accept(self)
def reject(self):
self.abort_disk_usage.set()
Dialog.reject(self)
if __name__ == '__main__':
from calibre.gui2 import Application
app = Application([])
d = EximDialog(initial_panel='import')
d.exec()
del app
| 16,571 | Python | .py | 364 | 35.313187 | 144 | 0.607907 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,002 | conversion_error.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/conversion_error.py | __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
from qt.core import QDialog
from calibre.gui2.dialogs.conversion_error_ui import Ui_ConversionErrorDialog
class ConversionErrorDialog(QDialog, Ui_ConversionErrorDialog):
def __init__(self, window, title, html, show=False):
QDialog.__init__(self, window)
Ui_ConversionErrorDialog.__init__(self)
self.setupUi(self)
self.setWindowTitle(title)
self.set_message(html)
if show:
self.show()
def set_message(self, html):
self.text.setHtml('<html><body>%s</body></html'%(html,))
| 639 | Python | .py | 15 | 36.133333 | 77 | 0.673139 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,003 | custom_recipes.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/custom_recipes.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>'
import os
import re
import textwrap
import time
from qt.core import (
QAbstractListModel,
QDialog,
QDialogButtonBox,
QFormLayout,
QGroupBox,
QHBoxLayout,
QIcon,
QItemSelectionModel,
QLabel,
QLineEdit,
QListView,
QListWidget,
QListWidgetItem,
QPushButton,
QSize,
QSizePolicy,
QSortFilterProxyModel,
QSpinBox,
QStackedWidget,
Qt,
QToolButton,
QTreeView,
QVBoxLayout,
QWidget,
pyqtSignal,
)
from calibre.gui2 import choose_files, choose_save_file, error_dialog, open_local_file
from calibre.gui2.dialogs.confirm_delete import confirm as confirm_delete
from calibre.gui2.search_box import SearchBox2
from calibre.gui2.tweak_book.editor.text import TextEdit
from calibre.gui2.widgets2 import Dialog
from calibre.utils.localization import localize_user_manual_link
from calibre.web.feeds.recipes import compile_recipe, custom_recipes
from calibre.web.feeds.recipes.collection import get_builtin_recipe_by_id
from polyglot.builtins import as_bytes, as_unicode, iteritems
def is_basic_recipe(src):
return re.search(r'^class BasicUserRecipe', src, flags=re.MULTILINE) is not None
class CustomRecipeModel(QAbstractListModel): # {{{
def __init__(self, recipe_model):
QAbstractListModel.__init__(self)
self.recipe_model = recipe_model
def title(self, index):
row = index.row()
if row > -1 and row < self.rowCount():
return self.recipe_model.custom_recipe_collection[row].get('title', '')
def urn(self, index):
row = index.row()
if row > -1 and row < self.rowCount():
return self.recipe_model.custom_recipe_collection[row].get('id')
def has_title(self, title):
for x in self.recipe_model.custom_recipe_collection:
if x.get('title', False) == title:
return True
return False
def script(self, index):
row = index.row()
if row > -1 and row < self.rowCount():
urn = self.recipe_model.custom_recipe_collection[row].get('id')
return self.recipe_model.get_recipe(urn)
def rowCount(self, *args):
try:
return len(self.recipe_model.custom_recipe_collection)
except Exception:
return 0
def data(self, index, role):
if role == Qt.ItemDataRole.DisplayRole:
return self.title(index)
def update(self, row, title, script):
if row > -1 and row < self.rowCount():
urn = self.recipe_model.custom_recipe_collection[row].get('id')
self.beginResetModel()
self.recipe_model.update_custom_recipe(urn, title, script)
self.endResetModel()
def replace_many_by_title(self, scriptmap):
script_urn_map = {}
for title, script in iteritems(scriptmap):
urn = None
for x in self.recipe_model.custom_recipe_collection:
if x.get('title', False) == title:
urn = x.get('id')
if urn is not None:
script_urn_map.update({urn: (title, script)})
if script_urn_map:
self.beginResetModel()
self.recipe_model.update_custom_recipes(script_urn_map)
self.endResetModel()
def add(self, title, script):
all_urns = {x.get('id') for x in self.recipe_model.custom_recipe_collection}
self.beginResetModel()
self.recipe_model.add_custom_recipe(title, script)
self.endResetModel()
new_urns = {x.get('id') for x in self.recipe_model.custom_recipe_collection} - all_urns
if new_urns:
urn = tuple(new_urns)[0]
for row, item in enumerate(self.recipe_model.custom_recipe_collection):
if item.get('id') == urn:
return row
return 0
def add_many(self, scriptmap):
self.beginResetModel()
self.recipe_model.add_custom_recipes(scriptmap)
self.endResetModel()
def remove(self, rows):
urns = []
for r in rows:
try:
urn = self.recipe_model.custom_recipe_collection[r].get('id')
urns.append(urn)
except:
pass
self.beginResetModel()
self.recipe_model.remove_custom_recipes(urns)
self.endResetModel()
# }}}
def py3_repr(x):
ans = repr(x)
if isinstance(x, bytes) and not ans.startswith('b'):
ans = 'b' + ans
if isinstance(x, str) and ans.startswith('u'):
ans = ans[1:]
return ans
def options_to_recipe_source(title, oldest_article, max_articles_per_feed, feeds):
classname = 'BasicUserRecipe%d' % int(time.time())
title = str(title).strip() or classname
indent = ' ' * 8
if feeds:
if len(feeds[0]) == 1:
feeds = '\n'.join(f'{indent}{py3_repr(url)},' for url in feeds)
else:
feeds = '\n'.join(f'{indent}({py3_repr(title)}, {py3_repr(url)}),' for title, url in feeds)
else:
feeds = ''
if feeds:
feeds = 'feeds = [\n%s\n ]' % feeds
src = textwrap.dedent('''\
#!/usr/bin/env python
# vim:fileencoding=utf-8
from calibre.web.feeds.news import {base}
class {classname}({base}):
title = {title}
oldest_article = {oldest_article}
max_articles_per_feed = {max_articles_per_feed}
auto_cleanup = True
{feeds}''').format(
classname=classname, title=py3_repr(title), oldest_article=oldest_article, feeds=feeds,
max_articles_per_feed=max_articles_per_feed, base='AutomaticNewsRecipe')
return src
class RecipeList(QWidget): # {{{
edit_recipe = pyqtSignal(object, object)
def __init__(self, parent, model):
QWidget.__init__(self, parent)
self.l = l = QHBoxLayout(self)
self.view = v = QListView(self)
v.doubleClicked.connect(self.item_activated)
v.setModel(CustomRecipeModel(model))
l.addWidget(v)
self.stacks = s = QStackedWidget(self)
l.addWidget(s, stretch=10, alignment=Qt.AlignmentFlag.AlignTop)
self.first_msg = la = QLabel(_(
'Create a new news source by clicking one of the buttons below'))
la.setWordWrap(True)
s.addWidget(la)
self.w = w = QWidget(self)
w.l = l = QVBoxLayout(w)
l.setContentsMargins(0, 0, 0, 0)
s.addWidget(w)
self.title = la = QLabel(w)
la.setAlignment(Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop)
l.addWidget(la)
l.setSpacing(20)
self.edit_button = b = QPushButton(QIcon.ic('modified.png'), _('&Edit this recipe'), w)
b.setSizePolicy(QSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed))
b.clicked.connect(self.edit_requested)
l.addWidget(b)
self.remove_button = b = QPushButton(QIcon.ic('list_remove.png'), _('&Remove this recipe'), w)
b.clicked.connect(self.remove)
b.setSizePolicy(QSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed))
l.addWidget(b)
self.export_button = b = QPushButton(QIcon.ic('save.png'), _('S&ave recipe as file'), w)
b.setSizePolicy(QSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed))
b.clicked.connect(self.save_recipe)
l.addWidget(b)
self.download_button = b = QPushButton(QIcon.ic('download-metadata.png'), _('&Download this recipe'), w)
b.clicked.connect(self.download)
b.setSizePolicy(QSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed))
l.addWidget(b)
self.select_row()
v.selectionModel().currentRowChanged.connect(self.recipe_selected)
def select_row(self, row=0):
v = self.view
if v.model().rowCount() > 0:
idx = v.model().index(row)
if idx.isValid():
v.selectionModel().select(idx, QItemSelectionModel.SelectionFlag.ClearAndSelect)
v.setCurrentIndex(idx)
self.recipe_selected(idx)
def add(self, title, src):
row = self.model.add(title, src)
self.select_row(row)
def update(self, row, title, src):
self.model.update(row, title, src)
self.select_row(row)
@property
def model(self):
return self.view.model()
def recipe_selected(self, cur, prev=None):
if cur.isValid():
self.stacks.setCurrentIndex(1)
self.title.setText('<h2 style="text-align:center">%s</h2>' % self.model.title(cur))
else:
self.stacks.setCurrentIndex(0)
def edit_requested(self):
idx = self.view.currentIndex()
if idx.isValid():
src = self.model.script(idx)
if src is not None:
self.edit_recipe.emit(idx.row(), src)
def save_recipe(self):
idx = self.view.currentIndex()
if idx.isValid():
src = self.model.script(idx)
if src is not None:
path = choose_save_file(
self, 'save-custom-recipe', _('Save recipe'),
filters=[(_('Recipes'), ['recipe'])],
all_files=False,
initial_filename=f'{self.model.title(idx)}.recipe'
)
if path:
with open(path, 'wb') as f:
f.write(as_bytes(src))
def item_activated(self, idx):
if idx.isValid():
src = self.model.script(idx)
if src is not None:
self.edit_recipe.emit(idx.row(), src)
def remove(self):
idx = self.view.currentIndex()
if idx.isValid():
if confirm_delete(_('Are you sure you want to permanently remove this recipe?'), 'remove-custom-recipe', parent=self):
self.model.remove((idx.row(),))
self.select_row()
if self.model.rowCount() == 0:
self.stacks.setCurrentIndex(0)
def download(self):
idx = self.view.currentIndex()
if idx.isValid():
urn = self.model.urn(idx)
title = self.model.title(idx)
from calibre.gui2.ui import get_gui
gui = get_gui()
gui.iactions['Fetch News'].download_custom_recipe(title, urn)
def has_title(self, title):
return self.model.has_title(title)
def add_many(self, script_map):
self.model.add_many(script_map)
self.select_row()
def replace_many_by_title(self, script_map):
self.model.replace_many_by_title(script_map)
self.select_row()
# }}}
class BasicRecipe(QWidget): # {{{
def __init__(self, parent):
QWidget.__init__(self, parent)
self.l = l = QFormLayout(self)
l.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow)
self.hm = hm = QLabel(_(
'Create a basic news recipe, by adding RSS feeds to it.\n'
'For some news sources, you will have to use the "Switch to advanced mode" '
'button below to further customize the fetch process.'))
hm.setWordWrap(True)
l.addRow(hm)
self.title = t = QLineEdit(self)
l.addRow(_('Recipe &title:'), t)
t.setStyleSheet('QLineEdit { font-weight: bold }')
self.oldest_article = o = QSpinBox(self)
o.setSuffix(' ' + _('day(s)'))
o.setToolTip(_("The oldest article to download"))
o.setMinimum(1), o.setMaximum(36500)
l.addRow(_('&Oldest article:'), o)
self.max_articles = m = QSpinBox(self)
m.setMinimum(5), m.setMaximum(100)
m.setToolTip(_("Maximum number of articles to download per feed."))
l.addRow(_("&Max. number of articles per feed:"), m)
self.fg = fg = QGroupBox(self)
fg.setTitle(_("Feeds in recipe"))
self.feeds = f = QListWidget(self)
fg.h = QHBoxLayout(fg)
fg.h.addWidget(f)
fg.l = QVBoxLayout()
self.up_button = b = QToolButton(self)
b.setIcon(QIcon.ic('arrow-up.png'))
b.setToolTip(_('Move selected feed up'))
fg.l.addWidget(b)
b.clicked.connect(self.move_up)
self.remove_button = b = QToolButton(self)
b.setIcon(QIcon.ic('list_remove.png'))
b.setToolTip(_('Remove selected feed'))
fg.l.addWidget(b)
b.clicked.connect(self.remove_feed)
self.down_button = b = QToolButton(self)
b.setIcon(QIcon.ic('arrow-down.png'))
b.setToolTip(_('Move selected feed down'))
fg.l.addWidget(b)
b.clicked.connect(self.move_down)
fg.h.addLayout(fg.l)
l.addRow(fg)
self.afg = afg = QGroupBox(self)
afg.setTitle(_('Add feed to recipe'))
afg.l = QFormLayout(afg)
afg.l.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow)
self.feed_title = ft = QLineEdit(self)
afg.l.addRow(_('&Feed title:'), ft)
self.feed_url = fu = QLineEdit(self)
afg.l.addRow(_('Feed &URL:'), fu)
self.afb = b = QPushButton(QIcon.ic('plus.png'), _('&Add feed'), self)
b.setToolTip(_('Add this feed to the recipe'))
b.clicked.connect(self.add_feed)
afg.l.addRow(b)
l.addRow(afg)
def move_up(self):
items = self.feeds.selectedItems()
if items:
row = self.feeds.row(items[0])
if row > 0:
self.feeds.insertItem(row - 1, self.feeds.takeItem(row))
self.feeds.setCurrentItem(items[0])
def move_down(self):
items = self.feeds.selectedItems()
if items:
row = self.feeds.row(items[0])
if row < self.feeds.count() - 1:
self.feeds.insertItem(row + 1, self.feeds.takeItem(row))
self.feeds.setCurrentItem(items[0])
def remove_feed(self):
for item in self.feeds.selectedItems():
self.feeds.takeItem(self.feeds.row(item))
def add_feed(self):
title = self.feed_title.text().strip()
if not title:
return error_dialog(self, _('No feed title'), _(
'You must specify a title for the feed'), show=True)
url = self.feed_url.text().strip()
if not title:
return error_dialog(self, _('No feed URL'), _(
'You must specify a URL for the feed'), show=True)
QListWidgetItem(f'{title} - {url}', self.feeds).setData(Qt.ItemDataRole.UserRole, (title, url))
self.feed_title.clear(), self.feed_url.clear()
def validate(self):
title = self.title.text().strip()
if not title:
error_dialog(self, _('Title required'), _(
'You must give your news source a title'), show=True)
return False
if self.feeds.count() < 1:
error_dialog(self, _('Feed required'), _(
'You must add at least one feed to your news source'), show=True)
return False
try:
compile_recipe(self.recipe_source)
except Exception as err:
error_dialog(self, _('Invalid recipe'), _(
'Failed to compile the recipe, with syntax error: %s' % err), show=True)
return False
return True
@property
def recipe_source(self):
title = self.title.text().strip()
feeds = [self.feeds.item(i).data(Qt.ItemDataRole.UserRole) for i in range(self.feeds.count())]
return options_to_recipe_source(title, self.oldest_article.value(), self.max_articles.value(), feeds)
@recipe_source.setter
def recipe_source(self, src):
self.feeds.clear()
self.feed_title.clear()
self.feed_url.clear()
if src is None:
self.title.setText(_('My news source'))
self.oldest_article.setValue(7)
self.max_articles.setValue(100)
else:
recipe = compile_recipe(src)
self.title.setText(recipe.title)
self.oldest_article.setValue(recipe.oldest_article)
self.max_articles.setValue(recipe.max_articles_per_feed)
for x in (recipe.feeds or ()):
title, url = ('', x) if len(x) == 1 else x
QListWidgetItem(f'{title} - {url}', self.feeds).setData(Qt.ItemDataRole.UserRole, (title, url))
# }}}
class AdvancedRecipe(QWidget): # {{{
def __init__(self, parent):
QWidget.__init__(self, parent)
self.l = l = QVBoxLayout(self)
self.la = la = QLabel(_(
'For help with writing advanced news recipes, see the <a href="%s">User Manual</a>'
) % localize_user_manual_link('https://manual.calibre-ebook.com/news.html'))
la.setOpenExternalLinks(True)
l.addWidget(la)
self.editor = TextEdit(self)
l.addWidget(self.editor)
def validate(self):
src = self.recipe_source
try:
compile_recipe(src)
except Exception as err:
error_dialog(self, _('Invalid recipe'), _(
'Failed to compile the recipe, with syntax error: %s' % err), show=True)
return False
return True
@property
def recipe_source(self):
return self.editor.toPlainText()
@recipe_source.setter
def recipe_source(self, src):
self.editor.load_text(src, syntax='python', doc_name='<recipe>')
def sizeHint(self):
return QSize(800, 500)
# }}}
class ChooseBuiltinRecipeModel(QSortFilterProxyModel):
def filterAcceptsRow(self, source_row, source_parent):
idx = self.sourceModel().index(source_row, 0, source_parent)
urn = idx.data(Qt.ItemDataRole.UserRole)
if not urn or urn in ('::category::0', '::category::1'):
return False
return True
class ChooseBuiltinRecipe(Dialog): # {{{
def __init__(self, recipe_model, parent=None):
self.recipe_model = recipe_model
Dialog.__init__(self, _("Choose builtin recipe"), 'choose-builtin-recipe', parent=parent)
def setup_ui(self):
self.l = l = QVBoxLayout(self)
self.recipes = r = QTreeView(self)
r.setAnimated(True)
r.setHeaderHidden(True)
self.model = ChooseBuiltinRecipeModel(self)
self.model.setSourceModel(self.recipe_model)
r.setModel(self.model)
r.doubleClicked.connect(self.accept)
self.search = s = SearchBox2(self)
self.search.initialize('scheduler_search_history')
self.search.setMinimumContentsLength(15)
self.search.search.connect(self.recipe_model.search)
self.recipe_model.searched.connect(self.search.search_done, type=Qt.ConnectionType.QueuedConnection)
self.recipe_model.searched.connect(self.search_done)
self.go_button = b = QToolButton(self)
b.setText(_("Go"))
b.clicked.connect(self.search.do_search)
h = QHBoxLayout()
h.addWidget(s), h.addWidget(b)
l.addLayout(h)
l.addWidget(self.recipes)
l.addWidget(self.bb)
self.search.setFocus(Qt.FocusReason.OtherFocusReason)
def search_done(self, *args):
if self.recipe_model.showing_count < 10:
self.recipes.expandAll()
def sizeHint(self):
return QSize(600, 450)
@property
def selected_recipe(self):
for idx in self.recipes.selectedIndexes():
urn = idx.data(Qt.ItemDataRole.UserRole)
if urn and not urn.startswith('::category::'):
return urn
def accept(self):
if not self.selected_recipe:
return error_dialog(self, _('Choose recipe'), _(
'You must choose a recipe to customize first'), show=True)
return Dialog.accept(self)
# }}}
class CustomRecipes(Dialog):
def __init__(self, recipe_model, parent=None):
self.recipe_model = recipe_model
Dialog.__init__(self, _("Add custom news source"), 'add-custom-news-source', parent=parent)
def setup_ui(self):
self.l = l = QVBoxLayout(self)
self.stack = s = QStackedWidget(self)
l.addWidget(s)
self.recipe_list = rl = RecipeList(self, self.recipe_model)
rl.edit_recipe.connect(self.edit_recipe)
s.addWidget(rl)
self.basic_recipe = br = BasicRecipe(self)
s.addWidget(br)
self.advanced_recipe = ar = AdvancedRecipe(self)
s.addWidget(ar)
l.addWidget(self.bb)
self.list_actions = []
def la(*args):
return self.list_actions.append(args)
la('plus.png', _('&New recipe'), _('Create a new recipe from scratch'), self.add_recipe)
la('news.png', _('Customize &builtin recipe'), _('Customize a builtin news download source'), self.customize_recipe)
la('document_open.png', _('Load recipe from &file'), _('Load a recipe from a file'), self.load_recipe)
la('mimetypes/dir.png', _('&Show recipe files'), _('Show the folder containing all recipe files'), self.show_recipe_files)
la('mimetypes/opml.png', _('Import &OPML'), _(
"Import a collection of RSS feeds in OPML format\n"
"Many RSS readers can export their subscribed RSS feeds\n"
"in OPML format"), self.import_opml)
s.currentChanged.connect(self.update_button_box)
self.update_button_box()
def update_button_box(self, index=0):
bb = self.bb
bb.clear()
if index == 0:
bb.setStandardButtons(QDialogButtonBox.StandardButton.Close)
for icon, text, tooltip, receiver in self.list_actions:
b = bb.addButton(text, QDialogButtonBox.ButtonRole.ActionRole)
b.setIcon(QIcon.ic(icon)), b.setToolTip(tooltip)
b.clicked.connect(receiver)
else:
bb.setStandardButtons(QDialogButtonBox.StandardButton.Cancel | QDialogButtonBox.StandardButton.Save)
if self.stack.currentIndex() == 1:
text = _('S&witch to advanced mode')
tooltip = _('Edit this recipe in advanced mode')
receiver = self.switch_to_advanced
b = bb.addButton(text, QDialogButtonBox.ButtonRole.ActionRole)
b.setToolTip(tooltip)
b.clicked.connect(receiver)
def accept(self):
idx = self.stack.currentIndex()
if idx > 0:
self.editing_finished()
return
Dialog.accept(self)
def reject(self):
idx = self.stack.currentIndex()
if idx > 0:
if confirm_delete(_('Are you sure? Any unsaved changes will be lost.'), 'confirm-cancel-edit-custom-recipe'):
self.stack.setCurrentIndex(0)
return
Dialog.reject(self)
def sizeHint(self):
sh = Dialog.sizeHint(self)
return QSize(max(sh.width(), 900), 600)
def show_recipe_files(self):
bdir = os.path.dirname(custom_recipes.file_path)
if not os.path.exists(bdir):
return error_dialog(self, _('No recipes'),
_('No custom recipes created.'), show=True)
open_local_file(bdir)
def add_recipe(self):
self.editing_row = None
self.basic_recipe.recipe_source = None
self.stack.setCurrentIndex(1)
def edit_recipe(self, row, src):
self.editing_row = row
if is_basic_recipe(src):
self.basic_recipe.recipe_source = src
self.stack.setCurrentIndex(1)
else:
self.advanced_recipe.recipe_source = src
self.stack.setCurrentIndex(2)
def editing_finished(self):
w = self.stack.currentWidget()
if not w.validate():
return
src = w.recipe_source
if not isinstance(src, bytes):
src = src.encode('utf-8')
recipe = compile_recipe(src)
row = self.editing_row
if row is None:
# Adding a new recipe
self.recipe_list.add(recipe.title, src)
else:
self.recipe_list.update(row, recipe.title, src)
self.stack.setCurrentIndex(0)
def customize_recipe(self):
d = ChooseBuiltinRecipe(self.recipe_model, self)
if d.exec() != QDialog.DialogCode.Accepted:
return
id_ = d.selected_recipe
if not id_:
return
src = get_builtin_recipe_by_id(id_, download_recipe=True)
if src is None:
raise Exception('Something weird happened')
src = as_unicode(src)
self.edit_recipe(None, src)
def load_recipe(self):
files = choose_files(self, 'recipe loader dialog',
_('Choose a recipe file'),
filters=[(_('Recipes'), ['py', 'recipe'])],
all_files=False, select_only_single_file=True)
if files:
path = files[0]
try:
with open(path, 'rb') as f:
src = f.read().decode('utf-8')
except Exception as err:
error_dialog(self, _('Invalid input'),
_('<p>Could not create recipe. Error:<br>%s')%err, show=True)
return
self.edit_recipe(None, src)
def import_opml(self):
from calibre.gui2.dialogs.opml import ImportOPML
d = ImportOPML(parent=self)
if d.exec() != QDialog.DialogCode.Accepted:
return
oldest_article, max_articles_per_feed, replace_existing = d.oldest_article, d.articles_per_feed, d.replace_existing
failed_recipes, replace_recipes, add_recipes = {}, {}, {}
for group in d.recipes:
title = base_title = group.title or _('Unknown')
if not replace_existing:
c = 0
while self.recipe_list.has_title(title):
c += 1
title = '%s %d' % (base_title, c)
try:
src = options_to_recipe_source(title, oldest_article, max_articles_per_feed, group.feeds)
compile_recipe(src)
except Exception:
import traceback
failed_recipes[title] = traceback.format_exc()
continue
if replace_existing and self.recipe_list.has_title(title):
replace_recipes[title] = src
else:
add_recipes[title] = src
if add_recipes:
self.recipe_list.add_many(add_recipes)
if replace_recipes:
self.recipe_list.replace_many_by_title(replace_recipes)
if failed_recipes:
det_msg = '\n'.join(f'{title}\n{tb}\n' for title, tb in iteritems(failed_recipes))
error_dialog(self, _('Failed to create recipes'), _(
'Failed to create some recipes, click "Show details" for details'), show=True,
det_msg=det_msg)
def switch_to_advanced(self):
src = self.basic_recipe.recipe_source
src = src.replace('AutomaticNewsRecipe', 'BasicNewsRecipe')
src = src.replace('BasicUserRecipe', 'AdvancedUserRecipe')
self.advanced_recipe.recipe_source = src
self.stack.setCurrentIndex(2)
if __name__ == '__main__':
from calibre.gui2 import Application
from calibre.web.feeds.recipes.model import RecipeModel
app = Application([])
CustomRecipes(RecipeModel()).exec()
del app
| 27,487 | Python | .py | 646 | 32.763158 | 130 | 0.603435 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,004 | tag_list_editor_table_widget.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/tag_list_editor_table_widget.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2008, Kovid Goyal <kovid at kovidgoyal.net>
from qt.core import Qt, QTableWidget, pyqtSignal
class TleTableWidget(QTableWidget):
delete_pressed = pyqtSignal()
def __init__(self, parent=None):
QTableWidget.__init__(self, parent=parent)
def keyPressEvent(self, event):
if event.key() == Qt.Key.Key_Delete:
self.delete_pressed.emit()
event.accept()
return
return QTableWidget.keyPressEvent(self, event)
| 528 | Python | .py | 13 | 33.615385 | 71 | 0.675835 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,005 | tag_editor.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/tag_editor.py | __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
from qt.core import QAbstractItemView, QDialog, QSortFilterProxyModel, QStringListModel, Qt
from calibre.constants import islinux
from calibre.gui2 import error_dialog, gprefs, question_dialog
from calibre.gui2.dialogs.confirm_delete import confirm
from calibre.gui2.dialogs.tag_editor_ui import Ui_TagEditor
from calibre.startup import connect_lambda
from calibre.utils.icu import sort_key
class TagEditor(QDialog, Ui_TagEditor):
def __init__(self, window, db, id_=None, key=None, current_tags=None):
QDialog.__init__(self, window)
Ui_TagEditor.__init__(self)
self.setupUi(self)
self.db = db
self.sep = ','
self.is_names = False
if key:
# Assume that if given a key then it is a custom column
try:
fm = db.field_metadata[key]
self.is_names = fm['display'].get('is_names', False)
if self.is_names:
self.sep = '&'
self.setWindowTitle(self.windowTitle() + ': ' + fm['name'])
except Exception:
pass
key = db.field_metadata.key_to_label(key)
else:
self.setWindowTitle(self.windowTitle() + ': ' + db.field_metadata['tags']['name'])
if self.sep == '&':
self.add_tag_input.setToolTip('<p>' +
_('If the item you want is not in the available list, '
'you can add it here. Accepts an ampersand-separated '
'list of items. The items will be applied to '
'the book.') + '</p>')
else:
self.add_tag_input.setToolTip('<p>' +
_('If the item you want is not in the available list, '
'you can add it here. Accepts a comma-separated '
'list of items. The items will be applied to '
'the book.') + '</p>')
self.key = key
self.index = db.row(id_) if id_ is not None else None
if self.index is not None:
if key is None:
tags = self.db.tags(self.index)
if tags:
tags = [tag.strip() for tag in tags.split(',') if tag.strip()]
else:
tags = self.db.get_custom(self.index, label=key)
else:
tags = []
if current_tags is not None:
tags = sorted(set(current_tags), key=sort_key)
if tags:
if not self.is_names:
tags.sort(key=sort_key)
else:
tags = []
self.applied_model = QStringListModel(tags)
p = QSortFilterProxyModel()
p.setFilterCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
p.setSourceModel(self.applied_model)
self.applied_tags.setModel(p)
if self.is_names:
self.applied_tags.setDragDropMode(QAbstractItemView.DragDropMode.InternalMove)
self.applied_tags.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
if key:
all_tags = [tag for tag in self.db.all_custom(label=key)]
else:
all_tags = [tag for tag in self.db.all_tags()]
all_tags = sorted(set(all_tags) - set(tags), key=sort_key)
self.all_tags_model = QStringListModel(all_tags)
p = QSortFilterProxyModel()
p.setFilterCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
p.setSourceModel(self.all_tags_model)
self.available_tags.setModel(p)
connect_lambda(self.apply_button.clicked, self, lambda self: self.apply_tags())
connect_lambda(self.unapply_button.clicked, self, lambda self: self.unapply_tags())
self.add_tag_button.clicked.connect(self.add_tag)
connect_lambda(self.delete_button.clicked, self, lambda self: self.delete_tags())
self.add_tag_input.returnPressed[()].connect(self.add_tag)
# add the handlers for the filter input fields
connect_lambda(self.available_filter_input.textChanged, self, lambda self, text: self.filter_tags(text))
connect_lambda(self.applied_filter_input.textChanged, self, lambda self, text: self.filter_tags(text, which='applied_tags'))
# Restore the focus to the last input box used (typed into)
for x in ('add_tag_input', 'available_filter_input', 'applied_filter_input'):
ibox = getattr(self, x)
ibox.setObjectName(x)
connect_lambda(ibox.textChanged, self, lambda self: self.edit_box_changed(self.sender().objectName()))
getattr(self, gprefs.get('tag_editor_last_filter', 'add_tag_input')).setFocus()
self.available_tags.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
self.applied_tags.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
if islinux:
self.available_tags.doubleClicked.connect(self.apply_tags)
self.applied_tags.doubleClicked.connect(self.unapply_tags)
else:
self.available_tags.activated.connect(self.apply_tags)
self.applied_tags.activated.connect(self.unapply_tags)
self.restore_geometry(gprefs, 'tag_editor_geometry')
def edit_box_changed(self, which):
gprefs['tag_editor_last_filter'] = which
def delete_tags(self):
confirms, deletes = [], []
row_indices = list(self.available_tags.selectionModel().selectedRows())
if not row_indices:
error_dialog(self, _('No tags selected'), _('You must select at least one tag from the list of Available tags.')).exec()
return
if not confirm(
_('Deleting tags is done immediately and there is no undo.'),
'tag_editor_delete'):
return
pos = self.available_tags.verticalScrollBar().value()
for ri in row_indices:
tag = ri.data()
used = self.db.is_tag_used(tag) \
if self.key is None else \
self.db.is_item_used_in_multiple(tag, label=self.key)
if used:
confirms.append(ri)
else:
deletes.append(ri)
if confirms:
ct = ', '.join(item.data() for item in confirms)
if question_dialog(self, _('Are your sure?'),
'<p>'+_('The following tags are used by one or more books. '
'Are you certain you want to delete them?')+'<br>'+ct):
deletes += confirms
for item in sorted(deletes, key=lambda r: r.row(), reverse=True):
tag = item.data()
if self.key is None:
self.db.delete_tag(tag)
else:
bks = self.db.delete_item_from_multiple(tag, label=self.key)
self.db.refresh_ids(bks)
self.available_tags.model().removeRows(item.row(), 1)
self.available_tags.verticalScrollBar().setValue(pos)
def apply_tags(self, item=None):
row_indices = list(self.available_tags.selectionModel().selectedRows())
row_indices.sort(key=lambda r: r.row(), reverse=True)
if not row_indices:
text = self.available_filter_input.text()
if text and text.strip():
self.add_tag_input.setText(text)
self.add_tag_input.setFocus(Qt.FocusReason.OtherFocusReason)
return
pos = self.available_tags.verticalScrollBar().value()
tags = self._get_applied_tags_box_contents()
for item in row_indices:
tag = item.data()
tags.append(tag)
self.available_tags.model().removeRows(item.row(), 1)
self.available_tags.verticalScrollBar().setValue(pos)
if not self.is_names:
tags.sort(key=sort_key)
self.applied_model.setStringList(tags)
def _get_applied_tags_box_contents(self):
return list(self.applied_model.stringList())
def unapply_tags(self, item=None):
row_indices = list(self.applied_tags.selectionModel().selectedRows())
tags = [r.data() for r in row_indices]
row_indices.sort(key=lambda r: r.row(), reverse=True)
for item in row_indices:
self.applied_model.removeRows(item.row(), 1)
all_tags = self.all_tags_model.stringList() + tags
all_tags.sort(key=sort_key)
self.all_tags_model.setStringList(all_tags)
def add_tag(self):
tags = str(self.add_tag_input.text()).split(self.sep)
tags_in_box = self._get_applied_tags_box_contents()
for tag in tags:
tag = tag.strip()
if not tag:
continue
if self.all_tags_model.rowCount():
for index in self.all_tags_model.match(self.all_tags_model.index(0), Qt.ItemDataRole.DisplayRole, tag, -1,
Qt.MatchFlag.MatchFixedString | Qt.MatchFlag.MatchCaseSensitive | Qt.MatchFlag.MatchWrap):
self.all_tags_model.removeRow(index.row())
if tag not in tags_in_box:
tags_in_box.append(tag)
if not self.is_names:
tags_in_box.sort(key=sort_key)
self.applied_model.setStringList(tags_in_box)
self.add_tag_input.setText('')
def filter_tags(self, filter_value, which='available_tags'):
collection = getattr(self, which)
collection.model().setFilterFixedString(filter_value or '')
def accept(self):
if self.add_tag_input.text().strip():
self.add_tag()
self.tags = self._get_applied_tags_box_contents()
self.save_state()
return QDialog.accept(self)
def reject(self):
self.save_state()
return QDialog.reject(self)
def save_state(self):
self.save_geometry(gprefs, 'tag_editor_geometry')
if __name__ == '__main__':
from calibre.gui2 import Application
from calibre.library import db
db = db()
app = Application([])
d = TagEditor(None, db, current_tags='a b c'.split())
if d.exec() == QDialog.DialogCode.Accepted:
print(d.tags)
| 10,200 | Python | .py | 207 | 37.850242 | 142 | 0.605741 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,006 | template_dialog_code_widget.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/template_dialog_code_widget.py | '''
Created on 26 Mar 2021
@author: Charles Haley
Based on classes in calibre.gui2.tweak_book.editor
License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
'''
from qt.core import QFont, QPainter, QPalette, QPlainTextEdit, QRect, Qt, QTextCursor, QTextEdit, QTextFormat
from calibre.gui2.tweak_book.editor.text import LineNumbers
from calibre.gui2.tweak_book.editor.themes import get_theme, theme_color
class LineNumberArea(LineNumbers):
def mouseDoubleClickEvent(self, event):
super().mousePressEvent(event)
self.parent().line_area_doubleclick_event(event)
class CodeEditor(QPlainTextEdit):
def __init__(self, parent):
QPlainTextEdit.__init__(self, parent)
# Use the default theme from the book editor
theme = get_theme(None)
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_area = LineNumberArea(self)
self.blockCountChanged.connect(self.update_line_number_area_width)
self.updateRequest.connect(self.update_line_number_area)
self.cursorPositionChanged.connect(self.highlight_cursor_line)
self.update_line_number_area_width(0)
self.highlight_cursor_line()
self.clicked_line_numbers = set()
def highlight_cursor_line(self):
sel = QTextEdit.ExtraSelection()
# Don't highlight if no text so that the placeholder text shows
if not (self.blockCount() == 1 and len(self.toPlainText().strip()) == 0):
sel.format.setBackground(self.palette().alternateBase())
sel.format.setProperty(QTextFormat.Property.FullWidthSelection, True)
sel.cursor = self.textCursor()
sel.cursor.clearSelection()
self.setExtraSelections([sel,])
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):
# get largest width of digits
fm = self.fontMetrics()
self.number_width = max(map(lambda x:fm.horizontalAdvance(str(x)), range(10)))
digits = 1
limit = max(1, self.blockCount())
while limit >= 10:
limit /= 10
digits += 1
return self.number_width * (digits+1)
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 line_area_doubleclick_event(self, event):
# remember that the result of the divide will be zero-based
line = event.y()//self.fontMetrics().height() + 1 + self.firstVisibleBlock().blockNumber()
if line in self.clicked_line_numbers:
self.clicked_line_numbers.discard(line)
else:
self.clicked_line_numbers.add(line)
self.update(self.line_number_area.geometry())
def number_of_lines(self):
return self.blockCount()
def set_clicked_line_numbers(self, new_set):
self.clicked_line_numbers = new_set
self.update(self.line_number_area.geometry())
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():
set_bold = False
set_italic = False
if current == num:
set_bold = True
if num+1 in self.clicked_line_numbers:
set_italic = True
painter.save()
if set_bold or set_italic:
f = QFont(self.font())
if set_bold:
f.setBold(set_bold)
painter.setPen(self.line_number_palette.color(QPalette.ColorRole.BrightText))
f.setItalic(set_italic)
painter.setFont(f)
else:
painter.setFont(self.font())
painter.drawText(0, top, self.line_number_area.width() - 5, self.fontMetrics().height(),
Qt.AlignmentFlag.AlignRight, str(num + 1))
painter.restore()
block = block.next()
top = bottom
bottom = top + int(self.blockBoundingRect(block).height())
num += 1
def keyPressEvent(self, ev):
if ev.key() == Qt.Key.Key_Insert:
self.setOverwriteMode(self.overwriteMode() ^ True)
ev.accept()
return
key = ev.key()
if key == Qt.Key_Tab or key == Qt.Key_Backtab:
'''
Handle indenting usingTab and Shift Tab. This is remarkably
difficult because of the way Qt represents the edit buffer.
Selections represent the start and end as character positions in the
buffer. To convert a position into a line number we must get the
block number containing that position. You so this by setting a
cursor to that position.
To get the text of a line we must convert the line number (the
block number) to a block and then fetch the text from that.
To change text we must create a cursor that selects all the text on
the line. Because cursors use document positions, not block numbers
or blocks, we must convert line numbers to blocks then get the
position of the first character of the block. We then "extend" the
selection to the end by computing the end position: the start + the
length of the text on the line. We then uses that cursor to
"insert" the new text, which magically replaces the selected text.
'''
# Get the position of the start and end of the selection.
cursor = self.textCursor()
start_position = cursor.selectionStart()
end_position = cursor.selectionEnd()
# Now convert positions into block (line) numbers
cursor.setPosition(start_position)
start_block = cursor.block().blockNumber()
cursor.setPosition(end_position)
end_block = cursor.block().blockNumber()
def select_block(block_number, curs):
# Note the side effect: 'curs' is changed to select the line
blk = self.document().findBlockByNumber(block_number)
txt = blk.text()
pos = blk.position()
curs.setPosition(pos)
curs.setPosition(pos+len(txt), QTextCursor.MoveMode.KeepAnchor)
return txt
# Check if there is a selection. If not then only Shift-Tab is valid
if start_position == end_position:
if key == Qt.Key_Backtab:
txt = select_block(start_block, cursor)
if txt.startswith('\t'):
# This works because of the side effect in select_block()
cursor.insertText(txt[1:])
cursor.setPosition(start_position-1)
self.setTextCursor(cursor)
ev.accept()
else:
QPlainTextEdit.keyPressEvent(self, ev)
return
# There is a selection so both Tab and Shift-Tab do indenting operations
for bn in range(start_block, end_block+1):
txt = select_block(bn, cursor)
if key == Qt.Key_Backtab:
if txt.startswith('\t'):
cursor.insertText(txt[1:])
if bn == start_block:
start_position -= 1
end_position -= 1
else:
cursor.insertText('\t' + txt)
if bn == start_block:
start_position += 1
end_position += 1
# Restore the selection, adjusted for the added or deleted tabs
cursor.setPosition(start_position)
cursor.setPosition(end_position, QTextCursor.MoveMode.KeepAnchor)
self.setTextCursor(cursor)
ev.accept()
return
QPlainTextEdit.keyPressEvent(self, ev)
| 9,443 | Python | .py | 185 | 38.27027 | 109 | 0.601886 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,007 | plugin_updater.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/plugin_updater.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2011, Grant Drake <grant.drake@gmail.com>'
__docformat__ = 'restructuredtext en'
import datetime
import re
import traceback
from qt.core import (
QAbstractItemView,
QAbstractTableModel,
QAction,
QBrush,
QComboBox,
QDialog,
QDialogButtonBox,
QFont,
QFrame,
QHBoxLayout,
QIcon,
QLabel,
QLineEdit,
QModelIndex,
QSize,
QSortFilterProxyModel,
Qt,
QTableView,
QUrl,
QVBoxLayout,
)
from calibre import prints
from calibre.constants import DEBUG, __appname__, __version__, ismacos, iswindows, numeric_version
from calibre.customize import PluginInstallationType
from calibre.customize.ui import NameConflict, add_plugin, disable_plugin, enable_plugin, has_external_plugins, initialized_plugins, is_disabled, remove_plugin
from calibre.gui2 import error_dialog, gprefs, info_dialog, open_url, question_dialog
from calibre.gui2.preferences.plugins import ConfigWidget
from calibre.utils.date import UNDEFINED_DATE, format_date
from calibre.utils.https import get_https_resource_securely
from calibre.utils.icu import lower as icu_lower
from polyglot.builtins import itervalues
SERVER = 'https://code.calibre-ebook.com/plugins/'
INDEX_URL = '%splugins.json.bz2' % SERVER
FILTER_ALL = 0
FILTER_INSTALLED = 1
FILTER_UPDATE_AVAILABLE = 2
FILTER_NOT_INSTALLED = 3
def get_plugin_updates_available(raise_error=False):
'''
API exposed to read whether there are updates available for any
of the installed user plugins.
Returns None if no updates found
Returns list(DisplayPlugin) of plugins installed that have a new version
'''
if not has_external_plugins():
return None
display_plugins = read_available_plugins(raise_error=raise_error)
if display_plugins:
update_plugins = list(filter(filter_upgradeable_plugins, display_plugins))
if len(update_plugins) > 0:
return update_plugins
return None
def filter_upgradeable_plugins(display_plugin):
return display_plugin.installation_type is PluginInstallationType.EXTERNAL \
and display_plugin.is_upgrade_available()
def filter_not_installed_plugins(display_plugin):
return not display_plugin.is_installed()
def read_available_plugins(raise_error=False):
import bz2
import json
display_plugins = []
try:
raw = get_https_resource_securely(INDEX_URL)
if not raw:
return
raw = json.loads(bz2.decompress(raw))
except:
if raise_error:
raise
traceback.print_exc()
return
for plugin in itervalues(raw):
try:
display_plugin = DisplayPlugin(plugin)
get_installed_plugin_status(display_plugin)
display_plugins.append(display_plugin)
except:
if DEBUG:
prints('======= Plugin Parse Error =======')
traceback.print_exc()
import pprint
pprint.pprint(plugin)
display_plugins = sorted(display_plugins, key=lambda k: k.name)
return display_plugins
def get_installed_plugin_status(display_plugin):
display_plugin.installed_version = None
display_plugin.plugin = None
for plugin in initialized_plugins():
if plugin.name == display_plugin.qname \
and plugin.installation_type is not PluginInstallationType.BUILTIN:
display_plugin.plugin = plugin
display_plugin.installed_version = plugin.version
break
if display_plugin.uninstall_plugins:
# Plugin requires a specific plugin name to be uninstalled first
# This could occur when a plugin is renamed (Kindle Collections)
# or multiple plugins deprecated into a newly named one.
# Check whether user has the previous version(s) installed
plugins_to_remove = list(display_plugin.uninstall_plugins)
for plugin_to_uninstall in plugins_to_remove:
found = False
for plugin in initialized_plugins():
if plugin.name == plugin_to_uninstall:
found = True
break
if not found:
display_plugin.uninstall_plugins.remove(plugin_to_uninstall)
class ImageTitleLayout(QHBoxLayout):
'''
A reusable layout widget displaying an image followed by a title
'''
def __init__(self, parent, icon_name, title):
QHBoxLayout.__init__(self)
title_font = QFont()
title_font.setPointSize(16)
title_image_label = QLabel(parent)
ic = QIcon.ic(icon_name)
if ic.isNull():
error_dialog(parent, _('Restart required'),
_('You must restart calibre before using this plugin!'), show=True)
else:
title_image_label.setPixmap(ic.pixmap(32, 32))
title_image_label.setMaximumSize(32, 32)
title_image_label.setScaledContents(True)
self.addWidget(title_image_label)
shelf_label = QLabel(title, parent)
shelf_label.setFont(title_font)
self.addWidget(shelf_label)
self.insertStretch(-1)
class SizePersistedDialog(QDialog):
'''
This dialog is a base class for any dialogs that want their size/position
restored when they are next opened.
'''
initial_extra_size = QSize(0, 0)
def __init__(self, parent, unique_pref_name):
QDialog.__init__(self, parent)
self.unique_pref_name = unique_pref_name
self.finished.connect(self.dialog_closing)
def sizeHint(self):
ans = super().sizeHint()
return ans + self.initial_extra_size
def resize_dialog(self):
self.restore_geometry(gprefs, self.unique_pref_name)
def dialog_closing(self, result):
self.save_geometry(gprefs, self.unique_pref_name)
class PluginFilterComboBox(QComboBox):
def __init__(self, parent):
QComboBox.__init__(self, parent)
items = [_('All'), _('Installed'), _('Update available'), _('Not installed')]
self.addItems(items)
class DisplayPlugin:
def __init__(self, plugin):
self.name = plugin['index_name']
self.qname = plugin.get('name', self.name)
self.forum_link = plugin['thread_url']
self.zip_url = SERVER + plugin['file']
self.installed_version = None
self.description = plugin['description']
self.donation_link = plugin['donate']
self.available_version = tuple(plugin['version'])
self.release_date = datetime.datetime(*tuple(map(int, re.split(r'\D', plugin['last_modified'])))[:6]).date()
self.calibre_required_version = tuple(plugin['minimum_calibre_version'])
self.author = plugin['author']
self.platforms = plugin['supported_platforms']
self.uninstall_plugins = plugin['uninstall'] or []
self.has_changelog = plugin['history']
self.is_deprecated = plugin['deprecated']
self.installation_type = PluginInstallationType.EXTERNAL
def is_disabled(self):
if self.plugin is None:
return False
return is_disabled(self.plugin)
def is_installed(self):
return self.installed_version is not None
def name_matches_filter(self, filter_text):
# filter_text is already lowercase @set_filter_text
return filter_text in icu_lower(self.name) # case-insensitive filtering
def is_upgrade_available(self):
if isinstance(self.installed_version, str):
return True
return self.is_installed() and (self.installed_version < self.available_version or self.is_deprecated)
def is_valid_platform(self):
if iswindows:
return 'windows' in self.platforms
if ismacos:
return 'osx' in self.platforms
return 'linux' in self.platforms
def is_valid_calibre(self):
return numeric_version >= self.calibre_required_version
def is_valid_to_install(self):
return self.is_valid_platform() and self.is_valid_calibre() and not self.is_deprecated
class DisplayPluginSortFilterModel(QSortFilterProxyModel):
def __init__(self, parent):
QSortFilterProxyModel.__init__(self, parent)
self.setSortRole(Qt.ItemDataRole.UserRole)
self.setSortCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
self.filter_criteria = FILTER_ALL
self.filter_text = ""
def filterAcceptsRow(self, sourceRow, sourceParent):
index = self.sourceModel().index(sourceRow, 0, sourceParent)
display_plugin = self.sourceModel().display_plugins[index.row()]
if self.filter_criteria == FILTER_ALL:
return not (display_plugin.is_deprecated and not display_plugin.is_installed()) and display_plugin.name_matches_filter(self.filter_text)
if self.filter_criteria == FILTER_INSTALLED:
return display_plugin.is_installed() and display_plugin.name_matches_filter(self.filter_text)
if self.filter_criteria == FILTER_UPDATE_AVAILABLE:
return display_plugin.is_upgrade_available() and display_plugin.name_matches_filter(self.filter_text)
if self.filter_criteria == FILTER_NOT_INSTALLED:
return not display_plugin.is_installed() and not display_plugin.is_deprecated and display_plugin.name_matches_filter(self.filter_text)
return False
def set_filter_criteria(self, filter_value):
self.filter_criteria = filter_value
self.invalidateFilter()
def set_filter_text(self, filter_text_value):
self.filter_text = icu_lower(str(filter_text_value))
self.invalidateFilter()
class DisplayPluginModel(QAbstractTableModel):
def __init__(self, display_plugins):
QAbstractTableModel.__init__(self)
self.display_plugins = display_plugins
self.headers = list(map(str, [_('Plugin name'), _('Donate'), _('Status'), _('Installed'),
_('Available'), _('Released'), _('calibre'), _('Author')]))
def rowCount(self, *args):
return len(self.display_plugins)
def columnCount(self, *args):
return len(self.headers)
def headerData(self, section, orientation, role):
if role == Qt.ItemDataRole.DisplayRole and orientation == Qt.Orientation.Horizontal:
return self.headers[section]
return None
def data(self, index, role):
if not index.isValid():
return None
row, col = index.row(), index.column()
if row < 0 or row >= self.rowCount():
return None
display_plugin = self.display_plugins[row]
if role in [Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.UserRole]:
if col == 0:
return display_plugin.name
if col == 1:
if display_plugin.donation_link:
return _('PayPal')
if col == 2:
return self._get_status(display_plugin)
if col == 3:
return self._get_display_version(display_plugin.installed_version)
if col == 4:
return self._get_display_version(display_plugin.available_version)
if col == 5:
if role == Qt.ItemDataRole.UserRole:
return self._get_display_release_date(display_plugin.release_date, 'yyyyMMdd')
else:
return self._get_display_release_date(display_plugin.release_date)
if col == 6:
return self._get_display_version(display_plugin.calibre_required_version)
if col == 7:
return display_plugin.author
elif role == Qt.ItemDataRole.DecorationRole:
if col == 0:
return self._get_status_icon(display_plugin)
if col == 1:
if display_plugin.donation_link:
return QIcon.ic('donate.png')
elif role == Qt.ItemDataRole.ToolTipRole:
if col == 1 and display_plugin.donation_link:
return _('This plugin is FREE but you can reward the developer for their effort\n'
'by donating to them via PayPal.\n\n'
'Right-click and choose Donate to reward: ')+display_plugin.author
else:
return self._get_status_tooltip(display_plugin)
elif role == Qt.ItemDataRole.ForegroundRole:
if col != 1: # Never change colour of the donation column
if display_plugin.is_deprecated:
return QBrush(Qt.GlobalColor.blue)
if display_plugin.is_disabled():
return QBrush(Qt.GlobalColor.gray)
return None
def plugin_to_index(self, display_plugin):
for i, p in enumerate(self.display_plugins):
if display_plugin == p:
return self.index(i, 0, QModelIndex())
return QModelIndex()
def refresh_plugin(self, display_plugin):
idx = self.plugin_to_index(display_plugin)
self.dataChanged.emit(idx, idx)
def _get_display_release_date(self, date_value, format='dd MMM yyyy'):
if date_value and date_value != UNDEFINED_DATE:
return format_date(date_value, format)
return None
def _get_display_version(self, version):
if version is None:
return ''
return '.'.join([str(v) for v in list(version)])
def _get_status(self, display_plugin):
if not display_plugin.is_valid_platform():
return _('Platform unavailable')
if not display_plugin.is_valid_calibre():
return _('calibre upgrade required')
if display_plugin.is_installed():
if display_plugin.is_deprecated:
return _('Plugin deprecated')
elif display_plugin.is_upgrade_available():
return _('New version available')
else:
return _('Latest version installed')
return _('Not installed')
def _get_status_icon(self, display_plugin):
if display_plugin.is_deprecated:
icon_name = 'plugin_deprecated.png'
elif display_plugin.is_disabled():
if display_plugin.is_upgrade_available():
if display_plugin.is_valid_to_install():
icon_name = 'plugin_disabled_valid.png'
else:
icon_name = 'plugin_disabled_invalid.png'
else:
icon_name = 'plugin_disabled_ok.png'
elif display_plugin.is_installed():
if display_plugin.is_upgrade_available():
if display_plugin.is_valid_to_install():
icon_name = 'plugin_upgrade_valid.png'
else:
icon_name = 'plugin_upgrade_invalid.png'
else:
icon_name = 'plugin_upgrade_ok.png'
else: # A plugin available not currently installed
if display_plugin.is_valid_to_install():
icon_name = 'plugin_new_valid.png'
else:
icon_name = 'plugin_new_invalid.png'
return QIcon.ic('plugins/' + icon_name)
def _get_status_tooltip(self, display_plugin):
if display_plugin.is_deprecated:
return (_('This plugin has been deprecated and should be uninstalled')+'\n\n'+
_('Right-click to see more options'))
if not display_plugin.is_valid_platform():
return (_('This plugin can only be installed on: %s') %
', '.join(display_plugin.platforms)+'\n\n'+
_('Right-click to see more options'))
if numeric_version < display_plugin.calibre_required_version:
return (_('You must upgrade to at least calibre %s before installing this plugin') %
self._get_display_version(display_plugin.calibre_required_version)+'\n\n'+
_('Right-click to see more options'))
if display_plugin.installed_version is None:
return (_('You can install this plugin')+'\n\n'+
_('Right-click to see more options'))
try:
if display_plugin.installed_version < display_plugin.available_version:
return (_('A new version of this plugin is available')+'\n\n'+
_('Right-click to see more options'))
except Exception:
return (_('A new version of this plugin is available')+'\n\n'+
_('Right-click to see more options'))
return (_('This plugin is installed and up-to-date')+'\n\n'+
_('Right-click to see more options'))
def notify_on_successful_install(parent, plugin):
d = info_dialog(parent, _('Success'),
_('Plugin <b>{0}</b> successfully installed under <b>'
'{1}</b>. You may have to restart calibre '
'for the plugin to take effect.').format(plugin.name, plugin.type),
show_copy_button=False)
b = d.bb.addButton(_('&Restart calibre now'), QDialogButtonBox.ButtonRole.AcceptRole)
b.setIcon(QIcon.ic('lt.png'))
d.do_restart = False
def rf():
d.do_restart = True
b.clicked.connect(rf)
d.set_details('')
d.exec()
b.clicked.disconnect()
return d.do_restart
class PluginUpdaterDialog(SizePersistedDialog):
initial_extra_size = QSize(350, 100)
forum_label_text = _('Plugin homepage')
def __init__(self, gui, initial_filter=FILTER_UPDATE_AVAILABLE):
SizePersistedDialog.__init__(self, gui, 'Plugin Updater plugin:plugin updater dialog')
self.gui = gui
self.forum_link = None
self.zip_url = None
self.model = None
self.do_restart = False
self._initialize_controls()
self._create_context_menu()
try:
display_plugins = read_available_plugins(raise_error=True)
except Exception:
display_plugins = []
import traceback
error_dialog(self.gui, _('Update Check Failed'),
_('Unable to reach the plugin index page.'),
det_msg=traceback.format_exc(), show=True)
if display_plugins:
self.model = DisplayPluginModel(display_plugins)
self.proxy_model = DisplayPluginSortFilterModel(self)
self.proxy_model.setSourceModel(self.model)
self.plugin_view.setModel(self.proxy_model)
self.plugin_view.resizeColumnsToContents()
self.plugin_view.selectionModel().currentRowChanged.connect(self._plugin_current_changed)
self.plugin_view.doubleClicked.connect(self.install_button.click)
self.filter_combo.setCurrentIndex(initial_filter)
self._select_and_focus_view()
else:
self.filter_combo.setEnabled(False)
# Cause our dialog size to be restored from prefs or created on first usage
self.resize_dialog()
def _initialize_controls(self):
self.setWindowTitle(_('User plugins'))
self.setWindowIcon(QIcon.ic('plugins/plugin_updater.png'))
layout = QVBoxLayout(self)
self.setLayout(layout)
title_layout = ImageTitleLayout(self, 'plugins/plugin_updater.png',
_('User plugins'))
layout.addLayout(title_layout)
header_layout = QHBoxLayout()
layout.addLayout(header_layout)
self.filter_combo = PluginFilterComboBox(self)
self.filter_combo.setMinimumContentsLength(20)
self.filter_combo.currentIndexChanged.connect(self._filter_combo_changed)
la = QLabel(_('Filter list of &plugins')+':', self)
la.setBuddy(self.filter_combo)
header_layout.addWidget(la)
header_layout.addWidget(self.filter_combo)
header_layout.addStretch(10)
# filter plugins by name
la = QLabel(_('Filter by &name')+':', self)
header_layout.addWidget(la)
self.filter_by_name_lineedit = QLineEdit(self)
la.setBuddy(self.filter_by_name_lineedit)
self.filter_by_name_lineedit.setText("")
self.filter_by_name_lineedit.textChanged.connect(self._filter_name_lineedit_changed)
header_layout.addWidget(self.filter_by_name_lineedit)
self.plugin_view = QTableView(self)
self.plugin_view.horizontalHeader().setStretchLastSection(True)
self.plugin_view.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
self.plugin_view.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
self.plugin_view.setAlternatingRowColors(True)
self.plugin_view.setSortingEnabled(True)
self.plugin_view.setIconSize(QSize(28, 28))
layout.addWidget(self.plugin_view)
details_layout = QHBoxLayout()
layout.addLayout(details_layout)
forum_label = self.forum_label = QLabel('')
forum_label.setTextInteractionFlags(Qt.TextInteractionFlag.LinksAccessibleByMouse | Qt.TextInteractionFlag.LinksAccessibleByKeyboard)
forum_label.linkActivated.connect(self._forum_label_activated)
details_layout.addWidget(QLabel(_('Description')+':', self), 0, Qt.AlignmentFlag.AlignLeft)
details_layout.addWidget(forum_label, 1, Qt.AlignmentFlag.AlignRight)
self.description = QLabel(self)
self.description.setFrameStyle(QFrame.Shape.Panel | QFrame.Shadow.Sunken)
self.description.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft)
self.description.setMinimumHeight(40)
self.description.setWordWrap(True)
layout.addWidget(self.description)
self.button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
self.button_box.rejected.connect(self.reject)
self.finished.connect(self._finished)
self.install_button = self.button_box.addButton(_('&Install'), QDialogButtonBox.ButtonRole.AcceptRole)
self.install_button.setToolTip(_('Install the selected plugin'))
self.install_button.clicked.connect(self._install_clicked)
self.install_button.setEnabled(False)
self.configure_button = self.button_box.addButton(' '+_('&Customize plugin ')+' ', QDialogButtonBox.ButtonRole.ResetRole)
self.configure_button.setToolTip(_('Customize the options for this plugin'))
self.configure_button.clicked.connect(self._configure_clicked)
self.configure_button.setEnabled(False)
layout.addWidget(self.button_box)
def update_forum_label(self):
txt = ''
if self.forum_link:
txt = f'<a href="{self.forum_link}">{self.forum_label_text}</a>'
self.forum_label.setText(txt)
def _create_context_menu(self):
self.plugin_view.setContextMenuPolicy(Qt.ContextMenuPolicy.ActionsContextMenu)
self.install_action = QAction(QIcon.ic('plugins/plugin_upgrade_ok.png'), _('&Install'), self)
self.install_action.setToolTip(_('Install the selected plugin'))
self.install_action.triggered.connect(self._install_clicked)
self.install_action.setEnabled(False)
self.plugin_view.addAction(self.install_action)
self.forum_action = QAction(QIcon.ic('plugins/mobileread.png'), _('Plugin &forum thread'), self)
self.forum_action.triggered.connect(self._forum_label_activated)
self.forum_action.setEnabled(False)
self.plugin_view.addAction(self.forum_action)
sep1 = QAction(self)
sep1.setSeparator(True)
self.plugin_view.addAction(sep1)
self.toggle_enabled_action = QAction(_('Enable/&disable plugin'), self)
self.toggle_enabled_action.setToolTip(_('Enable or disable this plugin'))
self.toggle_enabled_action.triggered.connect(self._toggle_enabled_clicked)
self.toggle_enabled_action.setEnabled(False)
self.plugin_view.addAction(self.toggle_enabled_action)
self.uninstall_action = QAction(_('&Remove plugin'), self)
self.uninstall_action.setToolTip(_('Uninstall the selected plugin'))
self.uninstall_action.triggered.connect(self._uninstall_clicked)
self.uninstall_action.setEnabled(False)
self.plugin_view.addAction(self.uninstall_action)
sep2 = QAction(self)
sep2.setSeparator(True)
self.plugin_view.addAction(sep2)
self.donate_enabled_action = QAction(QIcon.ic('donate.png'), _('Donate to developer'), self)
self.donate_enabled_action.setToolTip(_('Donate to the developer of this plugin'))
self.donate_enabled_action.triggered.connect(self._donate_clicked)
self.donate_enabled_action.setEnabled(False)
self.plugin_view.addAction(self.donate_enabled_action)
sep3 = QAction(self)
sep3.setSeparator(True)
self.plugin_view.addAction(sep3)
self.configure_action = QAction(QIcon.ic('config.png'), _('&Customize plugin'), self)
self.configure_action.setToolTip(_('Customize the options for this plugin'))
self.configure_action.triggered.connect(self._configure_clicked)
self.configure_action.setEnabled(False)
self.plugin_view.addAction(self.configure_action)
def _finished(self, *args):
if self.model:
update_plugins = list(filter(filter_upgradeable_plugins, self.model.display_plugins))
self.gui.recalc_update_label(len(update_plugins))
def _plugin_current_changed(self, current, previous):
if current.isValid():
actual_idx = self.proxy_model.mapToSource(current)
display_plugin = self.model.display_plugins[actual_idx.row()]
self.description.setText(display_plugin.description)
self.forum_link = display_plugin.forum_link
self.zip_url = display_plugin.zip_url
self.forum_action.setEnabled(bool(self.forum_link))
self.install_button.setEnabled(display_plugin.is_valid_to_install())
self.install_action.setEnabled(self.install_button.isEnabled())
self.uninstall_action.setEnabled(display_plugin.is_installed())
self.configure_button.setEnabled(display_plugin.is_installed())
self.configure_action.setEnabled(self.configure_button.isEnabled())
self.toggle_enabled_action.setEnabled(display_plugin.is_installed())
self.donate_enabled_action.setEnabled(bool(display_plugin.donation_link))
else:
self.description.setText('')
self.forum_link = None
self.zip_url = None
self.forum_action.setEnabled(False)
self.install_button.setEnabled(False)
self.install_action.setEnabled(False)
self.uninstall_action.setEnabled(False)
self.configure_button.setEnabled(False)
self.configure_action.setEnabled(False)
self.toggle_enabled_action.setEnabled(False)
self.donate_enabled_action.setEnabled(False)
self.update_forum_label()
def _donate_clicked(self):
plugin = self._selected_display_plugin()
if plugin and plugin.donation_link:
open_url(QUrl(plugin.donation_link))
def _select_and_focus_view(self, change_selection=True):
if change_selection and self.plugin_view.model().rowCount() > 0:
self.plugin_view.selectRow(0)
else:
idx = self.plugin_view.selectionModel().currentIndex()
self._plugin_current_changed(idx, 0)
self.plugin_view.setFocus()
def _filter_combo_changed(self, idx):
self.filter_by_name_lineedit.setText("") # clear the name filter text when a different group was selected
self.proxy_model.set_filter_criteria(idx)
if idx == FILTER_NOT_INSTALLED:
self.plugin_view.sortByColumn(5, Qt.SortOrder.DescendingOrder)
else:
self.plugin_view.sortByColumn(0, Qt.SortOrder.AscendingOrder)
self._select_and_focus_view()
def _filter_name_lineedit_changed(self, text):
self.proxy_model.set_filter_text(text) # set the filter text for filterAcceptsRow
def _forum_label_activated(self):
if self.forum_link:
open_url(QUrl(self.forum_link))
def _selected_display_plugin(self):
idx = self.plugin_view.selectionModel().currentIndex()
actual_idx = self.proxy_model.mapToSource(idx)
return self.model.display_plugins[actual_idx.row()]
def _uninstall_plugin(self, name_to_remove):
if DEBUG:
prints('Removing plugin: ', name_to_remove)
remove_plugin(name_to_remove)
# Make sure that any other plugins that required this plugin
# to be uninstalled first have the requirement removed
for display_plugin in self.model.display_plugins:
# Make sure we update the status and display of the
# plugin we just uninstalled
if name_to_remove in display_plugin.uninstall_plugins:
if DEBUG:
prints('Removing uninstall dependency for: ', display_plugin.name)
display_plugin.uninstall_plugins.remove(name_to_remove)
if display_plugin.qname == name_to_remove:
if DEBUG:
prints('Resetting plugin to uninstalled status: ', display_plugin.name)
display_plugin.installed_version = None
display_plugin.plugin = None
display_plugin.uninstall_plugins = []
if self.proxy_model.filter_criteria not in [FILTER_INSTALLED, FILTER_UPDATE_AVAILABLE]:
self.model.refresh_plugin(display_plugin)
def _uninstall_clicked(self):
display_plugin = self._selected_display_plugin()
if not question_dialog(self, _('Are you sure?'), '<p>'+
_('Are you sure you want to uninstall the <b>%s</b> plugin?')%display_plugin.name,
show_copy_button=False):
return
self._uninstall_plugin(display_plugin.qname)
if self.proxy_model.filter_criteria in [FILTER_INSTALLED, FILTER_UPDATE_AVAILABLE]:
self.model.beginResetModel(), self.model.endResetModel()
self._select_and_focus_view()
else:
self._select_and_focus_view(change_selection=False)
def _install_clicked(self):
display_plugin = self._selected_display_plugin()
if not question_dialog(self, _('Install %s')%display_plugin.name, '<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
if display_plugin.uninstall_plugins:
uninstall_names = list(display_plugin.uninstall_plugins)
if DEBUG:
prints('Uninstalling plugin: ', ', '.join(uninstall_names))
for name_to_remove in uninstall_names:
self._uninstall_plugin(name_to_remove)
plugin_zip_url = display_plugin.zip_url
if DEBUG:
prints('Downloading plugin ZIP attachment: ', plugin_zip_url)
self.gui.status_bar.showMessage(_('Downloading plugin ZIP attachment: %s') % plugin_zip_url)
zip_path = self._download_zip(plugin_zip_url)
if DEBUG:
prints('Installing plugin: ', zip_path)
self.gui.status_bar.showMessage(_('Installing plugin: %s') % zip_path)
do_restart = False
try:
from calibre.customize.ui import config
installed_plugins = frozenset(config['plugins'])
try:
plugin = add_plugin(zip_path)
except NameConflict as e:
return error_dialog(self.gui, _('Already exists'),
str(e), show=True)
# Check for any toolbars to add to.
widget = ConfigWidget(self.gui)
widget.gui = self.gui
widget.check_for_add_to_toolbars(plugin, previously_installed=plugin.name in installed_plugins)
self.gui.status_bar.showMessage(_('Plugin installed: %s') % display_plugin.name)
do_restart = notify_on_successful_install(self.gui, plugin)
display_plugin.plugin = plugin
# We cannot read the 'actual' version information as the plugin will not be loaded yet
display_plugin.installed_version = display_plugin.available_version
except:
if DEBUG:
prints('ERROR occurred while installing plugin: %s'%display_plugin.name)
traceback.print_exc()
error_dialog(self.gui, _('Install plugin failed'),
_('A problem occurred while installing this plugin.'
' This plugin will now be uninstalled.'
' Please post the error message in details below into'
' the forum thread for this plugin and restart calibre.'),
det_msg=traceback.format_exc(), show=True)
if DEBUG:
prints('Due to error now uninstalling plugin: %s'%display_plugin.name)
remove_plugin(display_plugin.name)
display_plugin.plugin = None
display_plugin.uninstall_plugins = []
if self.proxy_model.filter_criteria in [FILTER_NOT_INSTALLED, FILTER_UPDATE_AVAILABLE]:
self.model.beginResetModel(), self.model.endResetModel()
self._select_and_focus_view()
else:
self.model.refresh_plugin(display_plugin)
self._select_and_focus_view(change_selection=False)
if do_restart:
self.do_restart = True
self.accept()
def _configure_clicked(self):
display_plugin = self._selected_display_plugin()
plugin = display_plugin.plugin
if not plugin.is_customizable():
return info_dialog(self, _('Plugin not customizable'),
_('Plugin: %s does not need customization')%plugin.name, show=True)
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)
plugin.do_user_config(self.parent())
def _toggle_enabled_clicked(self):
display_plugin = self._selected_display_plugin()
plugin = display_plugin.plugin
if not plugin.can_be_disabled:
return error_dialog(self,_('Plugin cannot be disabled'),
_('The plugin: %s cannot be disabled')%plugin.name, show=True)
if is_disabled(plugin):
enable_plugin(plugin)
else:
disable_plugin(plugin)
self.model.refresh_plugin(display_plugin)
def _download_zip(self, plugin_zip_url):
from calibre.ptempfile import PersistentTemporaryFile
raw = get_https_resource_securely(plugin_zip_url, headers={'User-Agent':f'{__appname__} {__version__}'})
with PersistentTemporaryFile('.zip') as pt:
pt.write(raw)
return pt.name
| 35,498 | Python | .py | 707 | 39.622348 | 159 | 0.643372 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,008 | trim_image.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/trim_image.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import os
import sys
from qt.core import (
QCheckBox,
QDialog,
QDialogButtonBox,
QDoubleSpinBox,
QFormLayout,
QHBoxLayout,
QIcon,
QKeySequence,
QLabel,
QSize,
QSpinBox,
Qt,
QToolBar,
QVBoxLayout,
)
from calibre.gui2 import gprefs
from calibre.gui2.tweak_book.editor.canvas import Canvas
def reduce_to_ratio(w, h, r):
h = min(h, w / r)
w = r * h
return int(round(w)), int(round(h))
class Region(QDialog):
ignore_value_changes = False
def __init__(self, parent, width, height, max_width, max_height):
super().__init__(parent)
self.setWindowTitle(_('Set size of selected area'))
self.l = l = QFormLayout(self)
l.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
self.width_input = w = QSpinBox(self)
w.setRange(20, max_width), w.setSuffix(' px'), w.setValue(width)
w.valueChanged.connect(self.value_changed)
l.addRow(_('&Width:'), w)
self.height_input = h = QSpinBox(self)
h.setRange(20, max_height), h.setSuffix(' px'), h.setValue(height)
h.valueChanged.connect(self.value_changed)
l.addRow(_('&Height:'), h)
self.ratio_input = r = QDoubleSpinBox(self)
r.setRange(0.0, 5.00), r.setDecimals(2), r.setValue(max_width/max_height), r.setSingleStep(0.01)
r.setToolTip(_('For example, use 0.75 for kindle devices.'))
self.m_width = max_width
self.m_height = max_height
r.valueChanged.connect(self.aspect_changed)
l.addRow(_('&Aspect ratio:'), r)
self.const_aspect = ca = QCheckBox(_('Keep the ratio of width to height fixed'))
ca.toggled.connect(self.const_aspect_toggled)
l.addRow(ca)
k = QKeySequence('alt+1', QKeySequence.SequenceFormat.PortableText).toString(QKeySequence.SequenceFormat.NativeText).partition('+')[0]
la = QLabel('<p>'+_('Note that holding down the {} key while dragging the selection handles'
' will resize the selection while preserving its aspect ratio.').format(k))
la.setWordWrap(True)
la.setMinimumWidth(400)
l.addRow(la)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel, self)
bb.accepted.connect(self.accept)
bb.rejected.connect(self.reject)
l.addRow(bb)
self.resize(self.sizeHint())
self.current_aspect = width / height
self.ratio_input.setEnabled(not self.const_aspect.isChecked())
def aspect_changed(self):
inp = float(self.ratio_input.value())
if inp > 0 and inp != round(self.m_width/self.m_height, 2):
rw, rh = reduce_to_ratio(self.m_width, self.m_height, inp)
self.width_input.setValue(rw)
self.height_input.setValue(rh)
else:
self.width_input.setValue(self.m_width)
self.height_input.setValue(self.m_height)
def const_aspect_toggled(self):
self.ratio_input.setEnabled(not self.const_aspect.isChecked())
if self.const_aspect.isChecked():
self.current_aspect = self.width_input.value() / self.height_input.value()
def value_changed(self):
if self.ignore_value_changes or not self.const_aspect.isChecked():
return
src = self.sender()
self.ignore_value_changes = True
if src is self.height_input:
self.width_input.setValue(int(self.current_aspect * self.height_input.value()))
else:
self.height_input.setValue(int(self.width_input.value() / self.current_aspect))
self.ignore_value_changes = False
@property
def selection_size(self):
return self.width_input.value(), self.height_input.value()
class TrimImage(QDialog):
def __init__(self, img_data, parent=None):
QDialog.__init__(self, parent)
self.l = l = QVBoxLayout(self)
self.setWindowTitle(_('Trim Image'))
self.bar = b = QToolBar(self)
l.addWidget(b)
b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
b.setIconSize(QSize(32, 32))
self.msg = la = QLabel('\xa0' + _(
'Select a region by dragging with your mouse, and then click trim'))
self.msg_txt = self.msg.text()
self.sz = QLabel('')
self.canvas = c = Canvas(self)
c.image_changed.connect(self.image_changed)
c.load_image(img_data)
self.undo_action = u = c.undo_action
u.setShortcut(QKeySequence(QKeySequence.StandardKey.Undo))
self.redo_action = r = c.redo_action
r.setShortcut(QKeySequence(QKeySequence.StandardKey.Redo))
self.trim_action = ac = self.bar.addAction(QIcon.ic('trim.png'), _('&Trim'), self.do_trim)
ac.setShortcut(QKeySequence('Ctrl+T'))
ac.setToolTip('{} [{}]'.format(_('Trim image by removing borders outside the selected region'),
ac.shortcut().toString(QKeySequence.SequenceFormat.NativeText)))
ac.setEnabled(False)
self.size_selection = ac = self.bar.addAction(QIcon.ic('resize.png'), _('&Region'), self.do_region)
ac.setToolTip(_('Specify a selection region size using numbers to allow for precise control'))
c.selection_state_changed.connect(self.selection_changed)
c.selection_area_changed.connect(self.selection_area_changed)
l.addWidget(c)
self.bar.addAction(self.trim_action)
self.bar.addSeparator()
self.bar.addAction(u)
self.bar.addAction(r)
self.bar.addSeparator()
self.bar.addWidget(la)
self.bar.addSeparator()
self.bar.addWidget(self.sz)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
bb.accepted.connect(self.accept)
bb.rejected.connect(self.reject)
h = QHBoxLayout()
l.addLayout(h)
self.tr_sz = QLabel('')
h.addWidget(self.tr_sz)
h.addStretch(10)
h.addWidget(bb)
self.restore_geometry(gprefs, 'image-trim-dialog-geometry')
self.setWindowIcon(self.trim_action.icon())
self.image_data = None
def sizeHint(self):
return QSize(900, 600)
def do_region(self):
rect = self.canvas.selection_rect_in_image_coords
d = Region(self, int(rect.width()), int(rect.height()), self.canvas.current_image.width(), self.canvas.current_image.height())
if d.exec() == QDialog.DialogCode.Accepted:
width, height = d.selection_size
self.canvas.set_selection_size_in_image_coords(width, height)
def do_trim(self):
self.canvas.trim_image()
self.selection_changed(False)
def selection_changed(self, has_selection):
self.trim_action.setEnabled(has_selection)
self.msg.setText(_('Adjust selection by dragging corners') if has_selection else self.msg_txt)
def selection_area_changed(self, rect):
if rect:
x, y, w, h = map(int, self.canvas.rect_for_trim())
text = f'{int(w)}x{int(h)}'
text = _('Size: {0}px Aspect ratio: {1:.3g}').format(text, w / h)
else:
text = ''
self.tr_sz.setText(text)
def image_changed(self, qimage):
self.sz.setText('\xa0' + _('Size: {0}x{1}px').format(qimage.width(), qimage.height()))
def cleanup(self):
self.canvas.break_cycles()
self.save_geometry(gprefs, 'image-trim-dialog-geometry')
def accept(self):
if self.trim_action.isEnabled():
self.trim_action.trigger()
if self.canvas.is_modified:
self.image_data = self.canvas.get_image_data()
self.cleanup()
QDialog.accept(self)
def reject(self):
self.cleanup()
QDialog.reject(self)
if __name__ == '__main__':
from calibre.gui2 import Application
app = Application([])
fname = sys.argv[-1]
with open(fname, 'rb') as f:
data = f.read()
d = TrimImage(data)
if d.exec() == QDialog.DialogCode.Accepted and d.image_data is not None:
b, ext = os.path.splitext(fname)
fname = b + '-trimmed' + ext
with open(fname, 'wb') as f:
f.write(d.image_data)
print('Trimmed image written to', fname)
| 8,477 | Python | .py | 191 | 35.95288 | 142 | 0.638148 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,009 | edit_category_notes.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/edit_category_notes.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2023, Kovid Goyal <kovid at kovidgoyal.net>
import os
import sys
from typing import NamedTuple
from qt.core import (
QButtonGroup,
QByteArray,
QDialog,
QDialogButtonBox,
QFormLayout,
QHBoxLayout,
QIcon,
QLabel,
QLineEdit,
QPixmap,
QPushButton,
QRadioButton,
QSize,
QSpinBox,
Qt,
QTextDocument,
QTextFrameFormat,
QTextImageFormat,
QUrl,
QVBoxLayout,
QWidget,
pyqtSlot,
)
from calibre import fit_image, sanitize_file_name
from calibre.db.constants import RESOURCE_URL_SCHEME
from calibre.db.notes.connect import hash_data
from calibre.db.notes.exim import export_note, import_note
from calibre.gui2 import Application, choose_files, choose_images, choose_save_file, error_dialog
from calibre.gui2.comments_editor import OBJECT_REPLACEMENT_CHAR, Editor, EditorWidget
from calibre.gui2.widgets import ImageView
from calibre.gui2.widgets2 import Dialog
from calibre.utils.short_uuid import uuid4
IMAGE_EXTENSIONS = 'png', 'jpeg', 'jpg', 'gif', 'svg', 'webp'
class AskLink(Dialog): # {{{
def __init__(self, initial_name='', parent=None):
super().__init__(_('Create link'), 'create-link-for-notes', parent=parent)
self.setWindowIcon(QIcon.ic('insert-link.png'))
if initial_name:
self.name_edit.setText(initial_name)
def setup_ui(self):
self.v = v = QVBoxLayout(self)
self.f = f = QFormLayout()
f.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow)
v.addLayout(f)
v.addWidget(self.bb)
self.url_edit = u = QLineEdit(self)
u.setPlaceholderText(_('The URL for this link'))
u.setMinimumWidth(400)
f.addRow(_('&URL:'), u)
self.name_edit = n = QLineEdit(self)
n.setPlaceholderText(_('The name (optional) for this link'))
f.addRow(_('&Name:'), n)
self.url_edit.setFocus(Qt.FocusReason.OtherFocusReason)
@property
def link_name(self):
return self.name_edit.text().strip()
@property
def url(self):
return self.url_edit.text().strip()
# }}}
# Images {{{
class ImageResource(NamedTuple):
name: str
digest: str
path: str = ''
data: bytes = b''
from_db: bool = False
class AskImage(Dialog):
def __init__(self, local_images, db, parent=None):
self.local_images = local_images
self.db = db
self.current_digest = ''
super().__init__(_('Insert image'), 'insert-image-for-notes', parent=parent)
self.setWindowIcon(QIcon.ic('view-image.png'))
def setup_ui(self):
self.v = v = QVBoxLayout(self)
self.h = h = QHBoxLayout()
v.addLayout(h)
v.addWidget(self.bb)
self.image_preview = ip = ImageView(self, 'insert-image-for-notes-preview', True)
ip.cover_changed.connect(self.image_pasted_or_dropped)
ip.draw_empty_border = True
h.addWidget(ip)
self.vr = vr = QVBoxLayout()
h.addLayout(vr)
self.la = la = QLabel(_('Choose an image:'))
vr.addWidget(la)
self.name_edit = ne = QLineEdit(self)
ne.setPlaceholderText(_('Filename for the image'))
vr.addWidget(ne)
self.hb = hb = QHBoxLayout()
vr.addLayout(hb)
self.add_file_button = b = QPushButton(QIcon.ic('document_open.png'), _('Choose image &file'), self)
b.clicked.connect(self.add_file)
hb.addWidget(b)
self.paste_button = b = QPushButton(QIcon.ic('edit-paste.png'), _('&Paste from clipboard'), self)
b.clicked.connect(self.paste_image)
hb.addWidget(b)
self.la2 = la = QLabel(_('Place image:'))
vr.addWidget(la)
self.hr = hr = QHBoxLayout()
vr.addLayout(hr)
self.image_layout_group = bg = QButtonGroup(self)
self.float_left = r = QRadioButton(_('Float &left'))
bg.addButton(r), hr.addWidget(r)
self.inline = r = QRadioButton(_('Inline'))
bg.addButton(r), hr.addWidget(r)
self.float_right = r = QRadioButton(_('Float &right'))
bg.addButton(r), hr.addWidget(r)
self.inline.setChecked(True)
self.la2 = la = QLabel(_('Shrink image to fit within:'))
vr.addWidget(la)
self.hr2 = h = QHBoxLayout()
vr.addLayout(h)
la = QLabel(_('&Width:'))
h.addWidget(la)
self.width = w = QSpinBox(self)
w.setRange(0, 10000), w.setSuffix(' px')
h.addWidget(w), la.setBuddy(w)
w.setSpecialValueText(' ')
la = QLabel(_('&Height:'))
h.addWidget(la)
self.height = w = QSpinBox(self)
w.setRange(0, 10000), w.setSuffix(' px')
h.addWidget(w), la.setBuddy(w)
w.setSpecialValueText(' ')
h.addStretch(10)
vr.addStretch(10)
self.add_file_button.setFocus(Qt.FocusReason.OtherFocusReason)
def image_pasted_or_dropped(self, cover_data):
digest = hash_data(cover_data)
if digest in self.local_images:
ir = self.local_images[digest]
else:
self.local_images[digest] = ir = ImageResource('unnamed.png', digest, data=cover_data)
self.name_edit.setText(ir.name)
self.current_digest = digest
def add_file(self):
files = choose_images(self, 'choose-image-for-notes', _('Choose image'), formats=IMAGE_EXTENSIONS)
if files:
with open(files[0], 'rb') as f:
data = f.read()
digest = hash_data(data)
p = QPixmap()
if not p.loadFromData(data) or p.isNull():
return error_dialog(self, _('Bad image'), _(
'Failed to render the image in {}').format(files[0]), show=True)
ir = ImageResource(os.path.basename(files[0]), digest, path=files[0])
self.local_images[digest] = ir
self.image_preview.set_pixmap(p)
self.name_edit.setText(ir.name)
self.current_digest = digest
self.bb.setFocus(Qt.FocusReason.OtherFocusReason)
def paste_image(self):
if not self.image_preview.paste_from_clipboard():
return error_dialog(self, _('Could not paste'), _(
'No image is present in the system clipboard'), show=True)
@property
def image_layout(self) -> 'QTextFrameFormat.Position':
b = self.image_layout_group.checkedButton()
if b is self.inline:
return QTextFrameFormat.Position.InFlow
if b is self.float_left:
return QTextFrameFormat.Position.FloatLeft
return QTextFrameFormat.Position.FloatRight
@property
def image_size(self) -> tuple[int, int]:
s = self.image_preview.pixmap().size()
return s.width(), s.height()
@property
def bounding_size(self) -> tuple[int, int]:
return (self.width.value() or sys.maxsize), (self.height.value() or sys.maxsize)
# }}}
class NoteEditorWidget(EditorWidget):
insert_images_separately = True
db = field = item_id = item_val = None
images = None
can_store_images = True
def resource_digest_from_qurl(self, qurl):
alg = qurl.host()
digest = qurl.path()[1:]
return f'{alg}:{digest}'
def get_resource(self, digest):
ir = self.images.get(digest)
if ir is not None:
if ir.data:
return {'name': ir.name, 'data': ir.data}
elif ir.path:
with open(ir.path, 'rb') as f:
return {'name': ir.name, 'data': f.read()}
return self.db.get_notes_resource(digest)
def add_resource(self, path_or_data, name):
if isinstance(path_or_data, str):
with open(path_or_data, 'rb') as f:
data = f.read()
else:
data = path_or_data
digest = hash_data(data)
ir = ImageResource(name, digest, data=data)
self.images[digest] = ir
return digest
@pyqtSlot(int, 'QUrl', result='QVariant')
def loadResource(self, rtype, qurl):
if self.db is None or self.images is None or qurl.scheme() != RESOURCE_URL_SCHEME or int(rtype) != int(QTextDocument.ResourceType.ImageResource):
return
digest = self.resource_digest_from_qurl(qurl)
ans = self.get_resource(digest)
if ans is not None:
r = QByteArray(ans['data'])
self.document().addResource(rtype, qurl, r) # cache the resource
return r
def commit_downloaded_image(self, data, suggested_filename):
digest = hash_data(data)
if digest in self.images:
ir = self.images[digest]
else:
self.images[digest] = ir = ImageResource(suggested_filename, digest, data=data)
alg, digest = ir.digest.split(':', 1)
return RESOURCE_URL_SCHEME + f'://{alg}/{digest}?placement={uuid4()}'
def get_html_callback(self, root, text):
self.searchable_text = text.replace(OBJECT_REPLACEMENT_CHAR, '')
self.referenced_resources = set()
for fmt in self.document().allFormats():
if fmt.isImageFormat():
qurl = QUrl(fmt.toImageFormat().name())
if qurl.scheme() == RESOURCE_URL_SCHEME:
digest = self.resource_digest_from_qurl(qurl)
self.referenced_resources.add(digest)
def ask_link(self):
c = self.textCursor()
selected_text = c.selection().toPlainText().replace('\n', ' ')
d = AskLink(selected_text, parent=self)
if d.exec() == QDialog.DialogCode.Accepted:
return d.url, d.link_name, False
return '', '', False
def do_insert_image(self):
# See https://bugreports.qt.io/browse/QTBUG-118537
# for why we cant have a nice margin for floating images
d = AskImage(self.images, self.db)
if d.exec() == QDialog.DialogCode.Accepted and d.current_digest:
ir = self.images[d.current_digest]
self.focus_self()
c = self.textCursor()
fmt = QTextImageFormat()
alg, digest = ir.digest.split(':', 1)
fmt.setName(RESOURCE_URL_SCHEME + f'://{alg}/{digest}?placement={uuid4()}')
page_width, page_height = d.bounding_size
w, h = d.image_size
resized, nw, nh = fit_image(w, h, page_width, page_height)
if resized:
fmt.setWidth(nw)
fmt.setHeight(nh)
c.insertImage(fmt, d.image_layout)
class NoteEditor(Editor):
editor_class = NoteEditorWidget
def get_doc(self):
self.editor.referenced_resources = set()
self.editor.searchable_text = ''
idx = self.tabs.currentIndex()
self.tabs.setCurrentIndex(0)
html = self.editor.html
self.tabs.setCurrentIndex(idx)
return html, self.editor.searchable_text, self.editor.referenced_resources, self.editor.images.values()
def export_note(self):
html = self.get_doc()[0]
return export_note(html, self.editor.get_resource)
def import_note(self, path_to_html_file):
self.editor.images = {}
self.editor.setPlainText('')
with open(path_to_html_file, 'rb') as f:
html, _, _ = import_note(f.read(), os.path.dirname(os.path.abspath(path_to_html_file)), self.editor.add_resource)
self.editor.html = html
class EditNoteWidget(QWidget):
def __init__(self, db, field, item_id, item_val, parent=None):
super().__init__(parent)
self.l = l = QVBoxLayout(self)
l.setContentsMargins(0, 0, 0, 0)
self.editor = e = NoteEditor(self, toolbar_prefs_name='edit-notes-for-category-ce')
e.editor.db, e.editor.field, e.editor.item_id, e.editor.item_val = db, field, item_id, item_val
e.editor.images = {}
l.addWidget(e)
e.html = db.notes_for(field, item_id) or ''
def sizeHint(self):
return QSize(800, 600)
def commit(self):
doc, searchable_text, resources, resources_to_add = self.editor.get_doc()
s = self.editor.editor
for ir in resources_to_add:
s.db.add_notes_resource(ir.data or ir.path, ir.name)
s.db.set_notes_for(s.field, s.item_id, doc, searchable_text, resources)
return True
class EditNoteDialog(Dialog):
def __init__(self, field, item_id, db, parent=None):
self.db = db.new_api
self.field, self.item_id = field, item_id
self.item_val = self.db.get_item_name(field, item_id)
super().__init__(_('Edit notes for {}').format(self.item_val), 'edit-notes-for-category', parent=parent)
self.setWindowIcon(QIcon.ic('notes.png'))
def setup_ui(self):
self.l = l = QVBoxLayout(self)
self.edit_note_widget = EditNoteWidget(self.db, self.field, self.item_id, self.item_val, self)
l.addWidget(self.edit_note_widget)
self.bb.addButton(_('E&xport'), QDialogButtonBox.ButtonRole.ActionRole).clicked.connect(self.export_note)
self.bb.addButton(_('&Import'), QDialogButtonBox.ButtonRole.ActionRole).clicked.connect(self.import_note)
l.addWidget(self.bb)
def export_note(self):
dest = choose_save_file(self, 'save-exported-note', _('Export note to a file'), filters=[(_('HTML files'), ['html'])],
initial_filename=f'{sanitize_file_name(self.item_val)}.html', all_files=False)
if dest:
html = self.edit_note_widget.editor.export_note()
with open(dest, 'wb') as f:
f.write(html.encode('utf-8'))
def import_note(self):
dest = choose_files(self, 'load-imported-note', _('Import note from a file'), filters=[(_('HTML files'), ['html'])],
all_files=False, select_only_single_file=True)
if dest:
self.edit_note_widget.editor.import_note(dest[0])
def sizeHint(self):
return QSize(800, 620)
def accept(self):
if self.edit_note_widget.commit():
super().accept()
def develop_edit_note():
from calibre.library import db as dbc
app = Application([])
d = EditNoteDialog('authors', 1, dbc(os.path.expanduser('~/test library')))
d.exec()
del d, app
def develop_ask_image():
app = Application([])
from calibre.library import db as dbc
d = AskImage({},dbc(os.path.expanduser('~/test library')))
d.exec()
del d, app
if __name__ == '__main__':
develop_edit_note()
# develop_ask_image()
| 14,572 | Python | .py | 343 | 33.900875 | 153 | 0.616656 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,010 | choose_format.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/choose_format.py | __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
from functools import partial
from qt.core import QDialog, QDialogButtonBox, QHBoxLayout, QIcon, QLabel, QListWidget, QListWidgetItem, QMenu, QModelIndex, QPushButton, QSize, QVBoxLayout
from calibre.gui2 import file_icon_provider
from calibre.startup import connect_lambda
class ChooseFormatDialog(QDialog):
def __init__(self, window, msg, formats, show_open_with=False):
QDialog.__init__(self, window)
self.resize(507, 377)
self.setWindowIcon(QIcon.ic("mimetypes/unknown.png"))
self.setWindowTitle(_('Choose format'))
self.l = l = QVBoxLayout(self)
self.msg = QLabel(msg)
l.addWidget(self.msg)
self.formats = QListWidget(self)
self.formats.setIconSize(QSize(64, 64))
self.formats.activated[QModelIndex].connect(self.activated_slot)
l.addWidget(self.formats)
self.h = h = QHBoxLayout()
h.setContentsMargins(0, 0, 0, 0)
l.addLayout(h)
if show_open_with:
self.owb = QPushButton(_('&Open with...'), self)
self.formats.currentRowChanged.connect(self.update_open_with_button)
h.addWidget(self.owb)
self.own = QMenu(self.owb.text())
self.owb.setMenu(self.own)
self.own.aboutToShow.connect(self.populate_open_with)
self.buttonBox = bb = QDialogButtonBox(self)
bb.setStandardButtons(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel)
bb.accepted.connect(self.accept), bb.rejected.connect(self.reject)
h.addStretch(10), h.addWidget(self.buttonBox)
formats = list(formats)
for format in formats:
self.formats.addItem(QListWidgetItem(file_icon_provider().icon_from_ext(format.lower()),
format.upper()))
self._formats = formats
self.formats.setCurrentRow(0)
self._format = self.open_with_format = None
if show_open_with:
self.populate_open_with()
self.update_open_with_button()
def populate_open_with(self):
from calibre.gui2.open_with import edit_programs, populate_menu
menu = self.own
menu.clear()
fmt = self._formats[self.formats.currentRow()]
def connect_action(ac, entry):
connect_lambda(ac.triggered, self, lambda self: self.open_with(entry))
populate_menu(menu, connect_action, fmt)
if len(menu.actions()) == 0:
menu.addAction(_('Open %s with...') % fmt.upper(), self.choose_open_with)
else:
menu.addSeparator()
menu.addAction(_('Add other application for %s files...') % fmt.upper(), self.choose_open_with)
menu.addAction(_('Edit "Open with" applications...'), partial(edit_programs, fmt, self))
def update_open_with_button(self):
fmt = self._formats[self.formats.currentRow()]
self.owb.setText(_('Open %s with...') % fmt)
def open_with(self, entry):
self.open_with_format = (self._formats[self.formats.currentRow()], entry)
self.accept()
def choose_open_with(self):
from calibre.gui2.open_with import choose_program
fmt = self._formats[self.formats.currentRow()]
entry = choose_program(fmt, self)
if entry is not None:
self.open_with(entry)
def book_converted(self, book_id, fmt):
fmt = fmt.upper()
if fmt not in self._formats:
self._formats.append(fmt)
self.formats.addItem(QListWidgetItem(
file_icon_provider().icon_from_ext(fmt.lower()), fmt.upper()))
def activated_slot(self, *args):
self.accept()
def format(self):
return self._format
def accept(self):
self._format = self._formats[self.formats.currentRow()]
return QDialog.accept(self)
if __name__ == '__main__':
from calibre.gui2 import Application
app = Application([])
d = ChooseFormatDialog(None, 'Testing choose format', ['epub', 'mobi', 'docx'], show_open_with=True)
d.exec()
print(d._format)
del app
| 4,197 | Python | .py | 89 | 38.022472 | 156 | 0.638787 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,011 | duplicates.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/duplicates.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os.path
from qt.core import QApplication, QDialog, QDialogButtonBox, QFont, QGridLayout, QIcon, QLabel, Qt, QTreeWidget, QTreeWidgetItem
from calibre.ebooks.metadata import authors_to_string
from calibre.gui2 import gprefs
from calibre.utils.icu import primary_sort_key
from calibre.utils.localization import ngettext
class DuplicatesQuestion(QDialog):
def __init__(self, db, duplicates, parent=None):
QDialog.__init__(self, parent)
self.l = l = QGridLayout()
self.setLayout(l)
t = ngettext('Duplicate found', 'duplicates found', len(duplicates))
if len(duplicates) > 1:
t = '%d %s' % (len(duplicates), t)
self.setWindowTitle(t)
self.i = i = QIcon.ic('dialog_question.png')
self.setWindowIcon(i)
self.l1 = l1 = QLabel()
self.l2 = l2 = QLabel(_(
'Books with the same titles as the following already '
'exist in calibre. Select which books you want added anyway.'))
l2.setWordWrap(True)
l1.setPixmap(i.pixmap(128, 128))
l.addWidget(l1, 0, 0)
l.addWidget(l2, 0, 1)
self.dup_list = dl = QTreeWidget(self)
l.addWidget(dl, 1, 0, 1, 2)
dl.setHeaderHidden(True)
dl.addTopLevelItems(list(self.process_duplicates(db, duplicates)))
dl.expandAll()
dl.setIndentation(30)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel)
bb.accepted.connect(self.accept)
bb.rejected.connect(self.reject)
l.addWidget(bb, 2, 0, 1, 2)
l.setColumnStretch(1, 10)
self.ab = ab = bb.addButton(_('Select &all'), QDialogButtonBox.ButtonRole.ActionRole)
ab.clicked.connect(self.select_all), ab.setIcon(QIcon.ic('plus.png'))
self.nb = ab = bb.addButton(_('Select &none'), QDialogButtonBox.ButtonRole.ActionRole)
ab.clicked.connect(self.select_none), ab.setIcon(QIcon.ic('minus.png'))
self.cb = cb = bb.addButton(_('&Copy to clipboard'), QDialogButtonBox.ButtonRole.ActionRole)
cb.setIcon(QIcon.ic('edit-copy.png'))
cb.clicked.connect(self.copy_to_clipboard)
self.resize(self.sizeHint())
self.restore_geometry(gprefs, 'duplicates-question-dialog-geometry')
self.exec()
def copy_to_clipboard(self):
QApplication.clipboard().setText(self.as_text)
def select_all(self):
for i in range(self.dup_list.topLevelItemCount()):
x = self.dup_list.topLevelItem(i)
x.setCheckState(0, Qt.CheckState.Checked)
def select_none(self):
for i in range(self.dup_list.topLevelItemCount()):
x = self.dup_list.topLevelItem(i)
x.setCheckState(0, Qt.CheckState.Unchecked)
def reject(self):
self.save_geometry()
self.select_none()
QDialog.reject(self)
def accept(self):
self.save_geometry()
QDialog.accept(self)
def save_geometry(self):
super().save_geometry(gprefs, 'duplicates-question-dialog-geometry')
def process_duplicates(self, db, duplicates):
ta = _('%(title)s by %(author)s [%(formats)s]')
bf = QFont(self.dup_list.font())
bf.setBold(True)
itf = QFont(self.dup_list.font())
itf.setItalic(True)
for mi, cover, formats in duplicates:
# formats is a list of file paths
# Grab just the extension and display to the user
# Based only off the file name, no file type tests are done.
incoming_formats = ', '.join(os.path.splitext(path)[-1].replace('.', '').upper() for path in formats)
item = QTreeWidgetItem([ta%dict(
title=mi.title, author=mi.format_field('authors')[1],
formats=incoming_formats)] , 0)
item.setCheckState(0, Qt.CheckState.Checked)
item.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsUserCheckable)
item.setData(0, Qt.ItemDataRole.FontRole, bf)
item.setData(0, Qt.ItemDataRole.UserRole, (mi, cover, formats))
matching_books = db.books_with_same_title(mi)
def add_child(text):
c = QTreeWidgetItem([text], 1)
c.setFlags(Qt.ItemFlag.ItemIsEnabled)
item.addChild(c)
return c
add_child(_('Already in calibre:')).setData(0, Qt.ItemDataRole.FontRole, itf)
author_text = {}
for book_id in matching_books:
author_text[book_id] = authors_to_string([a.replace('|', ',') for a in (db.authors(book_id,
index_is_id=True) or '').split(',')])
def key(x):
return primary_sort_key(str(author_text[x]))
for book_id in sorted(matching_books, key=key):
add_child(ta%dict(
title=db.title(book_id, index_is_id=True),
author=author_text[book_id],
formats=db.formats(book_id, index_is_id=True,
verify_formats=False)))
add_child('')
yield item
@property
def duplicates(self):
for i in range(self.dup_list.topLevelItemCount()):
x = self.dup_list.topLevelItem(i)
if x.checkState(0) == Qt.CheckState.Checked:
yield x.data(0, Qt.ItemDataRole.UserRole)
@property
def as_text(self):
entries = []
for i in range(self.dup_list.topLevelItemCount()):
x = self.dup_list.topLevelItem(i)
check = '✓' if x.checkState(0) == Qt.CheckState.Checked else '✗'
title = f'{check} {str(x.text(0))}'
dups = []
for child in (x.child(j) for j in range(x.childCount())):
dups.append('\t' + str(child.text(0)))
entries.append(title + '\n' + '\n'.join(dups))
return '\n\n'.join(entries)
if __name__ == '__main__':
from calibre.ebooks.metadata.book.base import Metadata as M
from calibre.library import db
app = QApplication([])
db = db()
d = DuplicatesQuestion(db, [(M('Life of Pi', ['Yann Martel']), None, None),
(M('Heirs of the blade', ['Adrian Tchaikovsky']), None, None)])
print(tuple(d.duplicates))
| 6,477 | Python | .py | 134 | 37.947761 | 128 | 0.608117 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,012 | delete_matching_from_device.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/delete_matching_from_device.py | #!/usr/bin/env python
__copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net'
__docformat__ = 'restructuredtext en'
__license__ = 'GPL v3'
from qt.core import QAbstractItemView, QDialog, Qt, QTableWidgetItem
from calibre import strftime
from calibre.ebooks.metadata import authors_to_sort_string, authors_to_string, title_sort
from calibre.gui2.dialogs.delete_matching_from_device_ui import Ui_DeleteMatchingFromDeviceDialog
from calibre.utils.date import UNDEFINED_DATE
class tableItem(QTableWidgetItem):
def __init__(self, text):
QTableWidgetItem.__init__(self, text)
self.setFlags(Qt.ItemFlag.ItemIsEnabled)
self.sort = text.lower()
def __ge__(self, other):
return self.sort >= other.sort
def __lt__(self, other):
return self.sort < other.sort
class centeredTableItem(tableItem):
def __init__(self, text):
tableItem.__init__(self, text)
self.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
class titleTableItem(tableItem):
def __init__(self, text):
tableItem.__init__(self, text)
self.sort = title_sort(text.lower())
class authorTableItem(tableItem):
def __init__(self, book):
tableItem.__init__(self, authors_to_string(book.authors))
if book.author_sort is not None:
self.sort = book.author_sort.lower()
else:
self.sort = authors_to_sort_string(book.authors).lower()
class dateTableItem(tableItem):
def __init__(self, date):
if date is not None:
tableItem.__init__(self, strftime('%x', date))
self.sort = date
else:
tableItem.__init__(self, '')
self.sort = UNDEFINED_DATE
class DeleteMatchingFromDeviceDialog(QDialog, Ui_DeleteMatchingFromDeviceDialog):
def __init__(self, parent, items):
QDialog.__init__(self, parent)
Ui_DeleteMatchingFromDeviceDialog.__init__(self)
self.setupUi(self)
self.explanation.setText('<p>'+_('All checked books will be '
'<b>permanently deleted</b> from your '
'device. Please verify the list.')+'</p>')
self.buttonBox.accepted.connect(self.accepted)
self.buttonBox.rejected.connect(self.rejected)
self.table.cellClicked.connect(self.cell_clicked)
self.table.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection)
self.table.setColumnCount(7)
self.table.setHorizontalHeaderLabels(
['', _('Location'), _('Title'), _('Author'),
_('Date'), _('Format'), _('Path')])
rows = 0
for card in items:
rows += len(items[card][1])
self.table.setRowCount(rows)
row = 0
for card in items:
(model,books) = items[card]
for (id,book) in books:
item = QTableWidgetItem()
item.setFlags(Qt.ItemFlag.ItemIsUserCheckable|Qt.ItemFlag.ItemIsEnabled)
item.setCheckState(Qt.CheckState.Checked)
item.setData(Qt.ItemDataRole.UserRole, (model, id, book.path))
self.table.setItem(row, 0, item)
self.table.setItem(row, 1, tableItem(card))
self.table.setItem(row, 2, titleTableItem(book.title))
self.table.setItem(row, 3, authorTableItem(book))
self.table.setItem(row, 4, dateTableItem(book.datetime))
self.table.setItem(row, 5, centeredTableItem(book.path.rpartition('.')[2]))
self.table.setItem(row, 6, tableItem(book.path))
row += 1
self.table.setCurrentCell(0, 1)
self.table.resizeColumnsToContents()
self.table.setSortingEnabled(True)
self.table.sortByColumn(2, Qt.SortOrder.AscendingOrder)
self.table.setCurrentCell(0, 1)
def cell_clicked(self, row, col):
if col == 0:
self.table.setCurrentCell(row, 1)
def accepted(self):
self.result = []
for row in range(self.table.rowCount()):
if self.table.item(row, 0).checkState() == Qt.CheckState.Unchecked:
continue
(model, id, path) = self.table.item(row, 0).data(Qt.ItemDataRole.UserRole)
path = str(path)
self.result.append((model, id, path))
return
| 4,401 | Python | .py | 94 | 36.340426 | 97 | 0.617757 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,013 | template_dialog_box_layout.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/template_dialog_box_layout.py | '''
Created on 20 Jan 2021
@author: Charles Haley
'''
from qt.core import QBoxLayout
class BoxLayout(QBoxLayout):
def __init__(self):
QBoxLayout.__init__(self, QBoxLayout.Direction.TopToBottom)
| 211 | Python | .py | 8 | 23.25 | 67 | 0.732323 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,014 | confirm_delete.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/confirm_delete.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net'
__docformat__ = 'restructuredtext en'
from qt.core import QCheckBox, QDialog, QDialogButtonBox, QHBoxLayout, QIcon, QLabel, QMenu, Qt, QVBoxLayout
from calibre import confirm_config_name
from calibre.gui2 import dynamic
from calibre.gui2.dialogs.message_box import Icon
class Dialog(QDialog):
def __init__(
self, msg, name, parent, config_set=dynamic, icon='dialog_warning.png',
title=None, confirm_msg=None, show_cancel_button=True, extra_button=None,
extra_button_choices=None
):
QDialog.__init__(self, parent)
self.setWindowTitle(title or _("Are you sure?"))
self.setWindowIcon(QIcon.ic(icon))
self.l = l = QVBoxLayout(self)
self.h = h = QHBoxLayout()
l.addLayout(h)
self.icon_widget = Icon(self)
self.icon_widget.set_icon(QIcon.ic(icon))
self.msg = m = QLabel(self)
m.setOpenExternalLinks(True)
m.setMinimumWidth(350), m.setWordWrap(True), m.setObjectName("msg")
m.setMaximumHeight(400)
m.setText(msg)
h.addWidget(self.icon_widget), h.addSpacing(10), h.addWidget(m)
self.again = a = QCheckBox((confirm_msg or _("&Show this warning again")), self)
a.setChecked(True), a.setObjectName("again")
a.stateChanged.connect(self.toggle)
l.addWidget(a)
if show_cancel_button:
buttons = QDialogButtonBox.StandardButton.Yes | QDialogButtonBox.StandardButton.No
standard_button = QDialogButtonBox.StandardButton.Yes
else:
buttons = QDialogButtonBox.StandardButton.Ok
standard_button = QDialogButtonBox.StandardButton.Ok
self.buttonBox = bb = QDialogButtonBox(buttons, self)
bb.setObjectName("buttonBox")
bb.setFocus(Qt.FocusReason.OtherFocusReason)
bb.accepted.connect(self.accept), bb.rejected.connect(self.reject)
self.extra_button_clicked = False
self.extra_button_choice = None
if extra_button:
b = bb.addButton(extra_button, QDialogButtonBox.ButtonRole.AcceptRole)
if extra_button_choices:
m = QMenu()
b.setMenu(m)
for acname, text in extra_button_choices.items():
ac = m.addAction(text)
ac.setObjectName(acname)
ac.triggered.connect(self.on_extra_choice_click)
else:
b.clicked.connect(self.on_extra_button_click)
l.addWidget(bb)
self.name = name
self.config_set = config_set
self.resize(self.sizeHint())
bb.button(standard_button).setFocus(Qt.FocusReason.OtherFocusReason)
def on_extra_button_click(self):
self.extra_button_clicked = True
def on_extra_choice_click(self):
ac = self.sender()
self.extra_button_choice = ac.objectName()
self.accept()
def toggle(self, *args):
self.config_set[confirm_config_name(self.name)] = self.again.isChecked()
def confirm(
msg, name, parent=None, pixmap='dialog_warning.png', title=None,
show_cancel_button=True, confirm_msg=None, config_set=None, extra_button=None, extra_button_choices=None
):
config_set = config_set or dynamic
if not config_set.get(confirm_config_name(name), True):
if extra_button:
if extra_button_choices:
return True, None
return True, False
return True
d = Dialog(msg, name, parent, config_set=config_set, icon=pixmap, extra_button=extra_button,
title=title, confirm_msg=confirm_msg, show_cancel_button=show_cancel_button, extra_button_choices=extra_button_choices)
ret = d.exec() == QDialog.DialogCode.Accepted
if extra_button:
if extra_button_choices:
ret = ret, d.extra_button_choice
else:
ret = ret, d.extra_button_clicked
return ret
| 4,010 | Python | .py | 88 | 36.5 | 134 | 0.652319 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,015 | search.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/search.py | __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
import copy
import re
from datetime import date
from qt.core import (
QComboBox,
QDialog,
QDialogButtonBox,
QFormLayout,
QFrame,
QGroupBox,
QHBoxLayout,
QIcon,
QLabel,
QLineEdit,
QPushButton,
QRadioButton,
QSize,
QSpinBox,
Qt,
QTabWidget,
QToolButton,
QVBoxLayout,
QWidget,
)
from calibre import strftime
from calibre.gui2 import gprefs
from calibre.gui2.complete2 import EditWithComplete
from calibre.library.caches import CONTAINS_MATCH, EQUALS_MATCH, REGEXP_MATCH
from calibre.startup import connect_lambda
from calibre.utils.config import tweaks
from calibre.utils.date import now
from calibre.utils.icu import sort_key
from calibre.utils.localization import localize_user_manual_link
box_values = {}
last_matchkind = CONTAINS_MATCH
# UI {{{
def init_dateop(cb):
for op, desc in [
('=', _('equal to')),
('<', _('before')),
('>', _('after')),
('<=', _('before or equal to')),
('>=', _('after or equal to')),
('s', _('is set')),
('u', _('is unset')),
]:
cb.addItem(desc, op)
def current_dateop(cb):
return str(cb.itemData(cb.currentIndex()) or '')
def create_msg_label(self):
self.frame = f = QFrame(self)
f.setFrameShape(QFrame.Shape.StyledPanel)
f.setFrameShadow(QFrame.Shadow.Raised)
f.l = l = QVBoxLayout(f)
f.um_label = la = QLabel(_(
"<p>You can also perform other kinds of advanced searches, for example checking"
' for books that have no covers, combining multiple search expression using Boolean'
' operators and so on. See <a href=\"%s\">The search interface</a> for more information.'
) % localize_user_manual_link('https://manual.calibre-ebook.com/gui.html#the-search-interface'))
la.setMinimumSize(QSize(150, 0))
la.setWordWrap(True)
la.setOpenExternalLinks(True)
l.addWidget(la)
return f
def create_match_kind(self):
self.cmk_label = la = QLabel(_("What &kind of match to use:"))
self.matchkind = m = QComboBox(self)
la.setBuddy(m)
m.addItems([
_("Contains: the word or phrase matches anywhere in the metadata field"),
_("Equals: the word or phrase must match the entire metadata field"),
_("Regular expression: the expression must match anywhere in the metadata field"),
_("Character variant: 'contains' with accents ignored and punctuation significant")
])
l = QHBoxLayout()
l.addWidget(la), l.addWidget(m)
return l
def create_button_box(self):
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
self.clear_button = bb.addButton(_('&Clear'), QDialogButtonBox.ButtonRole.ResetRole)
self.clear_button.clicked.connect(self.clear_button_pushed)
bb.accepted.connect(self.accept)
bb.rejected.connect(self.reject)
return bb
def create_adv_tab(self):
self.adv_tab = w = QWidget(self.tab_widget)
self.tab_widget.addTab(w, _("A&dvanced search"))
w.g1 = QGroupBox(_("Find entries that have..."), w)
w.g2 = QGroupBox(_("But don't show entries that have..."), w)
w.l = l = QVBoxLayout(w)
l.addWidget(w.g1), l.addWidget(w.g2), l.addStretch(10)
w.g1.l = l = QFormLayout(w.g1)
l.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
for key, text in (
('all', _("A&ll these words:")),
('phrase', _("&This exact phrase:")),
('any', _("O&ne or more of these words:")),
):
le = QLineEdit(w)
le.setClearButtonEnabled(True)
setattr(self, key, le)
l.addRow(text, le)
w.g2.l = l = QFormLayout(w.g2)
l.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
self.none = le = QLineEdit(w)
le.setClearButtonEnabled(True)
l.addRow(_("Any of these &unwanted words:"), le)
def create_simple_tab(self, db):
self.simple_tab = w = QWidget(self.tab_widget)
self.tab_widget.addTab(w, _("Titl&e/author/series..."))
w.l = l = QFormLayout(w)
l.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
self.title_box = le = QLineEdit(w)
le.setClearButtonEnabled(True)
le.setObjectName('title_box')
le.setPlaceholderText(_('The title to search for'))
l.addRow(_('&Title:'), le)
self.authors_box = le = EditWithComplete(self)
le.lineEdit().setPlaceholderText(_('The author to search for'))
le.setObjectName('authors_box')
le.setEditText('')
le.set_separator('&')
le.set_space_before_sep(True)
le.set_add_separator(tweaks['authors_completer_append_separator'])
le.update_items_cache(db.new_api.all_field_names('authors'))
l.addRow(_('&Author:'), le)
self.series_box = le = EditWithComplete(self)
le.lineEdit().setPlaceholderText(_('The series to search for'))
le.setObjectName('series_box')
le.set_separator(None)
le.update_items_cache(db.new_api.all_field_names('series'))
le.show_initial_value('')
l.addRow(_('&Series:'), le)
self.tags_box = le = EditWithComplete(self)
le.setObjectName('tags_box')
le.lineEdit().setPlaceholderText(_('The tags to search for'))
self.tags_box.update_items_cache(db.new_api.all_field_names('tags'))
l.addRow(_('Ta&gs:'), le)
searchables = sorted(db.field_metadata.searchable_fields(),
key=lambda x: sort_key(x if x[0] != '#' else x[1:]))
self.general_combo = QComboBox(w)
self.general_combo.addItems(searchables)
self.box_last_values = copy.deepcopy(box_values)
self.general_box = le = QLineEdit(self)
le.setClearButtonEnabled(True)
le.setObjectName('general_box')
l.addRow(self.general_combo, le)
if self.box_last_values:
for k,v in self.box_last_values.items():
if k == 'general_index':
continue
getattr(self, k).setText(v)
self.general_combo.setCurrentIndex(
self.general_combo.findText(self.box_last_values['general_index']))
def toggle_date_conditions_visibility(self):
dcl = self.date_tab.date_condition_layouts
op = current_dateop(self.dateop_date)
visible = op not in 'su'
for l in dcl:
for i in range(l.count()):
x = l.itemAt(i)
w = x.widget()
if w is not None:
w.setVisible(visible)
def create_date_tab(self, db):
self.date_tab = w = QWidget(self.tab_widget)
w.date_condition_layouts = dcl = []
self.tab_widget.addTab(w, _("&Date search"))
w.l = l = QVBoxLayout(w)
def a(w):
h.addWidget(w)
return w
def add(text, w):
w.la = la = QLabel(text)
h.addWidget(la), h.addWidget(w)
la.setBuddy(w)
return w
w.h1 = h = QHBoxLayout()
l.addLayout(h)
self.date_field = df = add(_("&Search the"), QComboBox(w))
vals = [((v['search_terms'] or [k])[0], v['name'] or k)
for k, v in db.field_metadata.iter_items()
if v.get('datatype', None) == 'datetime' or
(v.get('datatype', None) == 'composite' and
v.get('display', {}).get('composite_sort', None) == 'date')]
for k, v in sorted(vals, key=lambda k_v: sort_key(k_v[1])):
df.addItem(v, k)
h.addWidget(df)
self.dateop_date = dd = add(_("date column for books whose &date is "), QComboBox(w))
init_dateop(dd)
connect_lambda(dd.currentIndexChanged, self, toggle_date_conditions_visibility)
w.la3 = la = QLabel('...')
h.addWidget(la)
h.addStretch(10)
w.h2 = h = QHBoxLayout()
dcl.append(h)
l.addLayout(h)
self.sel_date = a(QRadioButton(_('&year'), w))
self.date_year = dy = a(QSpinBox(w))
dy.setRange(102, 10000)
dy.setValue(now().year)
self.date_month = dm = add(_('mo&nth'), QComboBox(w))
for val, text in [(0, '')] + [(i, strftime('%B', date(2010, i, 1).timetuple())) for i in range(1, 13)]:
dm.addItem(text, val)
self.date_day = dd = add(_('&day'), QSpinBox(w))
dd.setRange(0, 31)
dd.setSpecialValueText(' \xa0')
h.addStretch(10)
w.h3 = h = QHBoxLayout()
dcl.append(h)
l.addLayout(h)
self.sel_daysago = a(QRadioButton('', w))
self.date_daysago = da = a(QSpinBox(w))
da.setRange(0, 9999999)
self.date_ago_type = dt = a(QComboBox(w))
dt.addItems([_('days'), _('weeks'), _('months'), _('years')])
w.la4 = a(QLabel(' ' + _('ago')))
h.addStretch(10)
w.h4 = h = QHBoxLayout()
l.addLayout(h)
dcl.append(h)
self.sel_human = a(QRadioButton('', w))
self.date_human = dh = a(QComboBox(w))
for val, text in [('today', _('Today')), ('yesterday', _('Yesterday')), ('thismonth', _('This month'))]:
dh.addItem(text, val)
connect_lambda(self.date_year.valueChanged, self, lambda self: self.sel_date.setChecked(True))
connect_lambda(self.date_month.currentIndexChanged, self, lambda self: self.sel_date.setChecked(True))
connect_lambda(self.date_day.valueChanged, self, lambda self: self.sel_date.setChecked(True))
connect_lambda(self.date_daysago.valueChanged, self, lambda self: self.sel_daysago.setChecked(True))
connect_lambda(self.date_human.currentIndexChanged, self, lambda self: self.sel_human.setChecked(True))
self.sel_date.setChecked(True)
h.addStretch(10)
l.addStretch(10)
toggle_date_conditions_visibility(self)
def create_template_tab(self):
self.simple_tab = w = QWidget(self.tab_widget)
self.tab_widget.addTab(w, _("&Template search"))
w.l = l = QFormLayout(w)
l.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
self.template_value_box = le = QLineEdit(w)
le.setClearButtonEnabled(True)
le.setObjectName('template_value_box')
le.setPlaceholderText(_('The value to search for'))
le.setToolTip('<p>' +
_("You can use the search specifications described "
"in the calibre documentation. For example, with Number "
"comparisons you can use the relational operators like '>=' etc. "
"With Text comparisons you can use contains (T), exact (=T), "
"or regular expression matches (~T), where T is your text. "
"With Date you can use 'today', 'yesterday', etc. When checking for "
"Set use 'true' or 'yes'. When checking for Not set use 'false' "
"or 'no'") + '</p>')
l.addRow(_('Template &value:'), le)
self.template_test_type_box = le = QComboBox(w)
le.setObjectName('template_test_type_box')
for op, desc in [
('t', _('Text')),
('d', _('Date')),
('n', _('Number')),
('b', _('Set/Not set'))]:
le.addItem(desc, op)
le.setToolTip(_('How the template result will be compared to the value'))
l.addRow(_('C&omparison type:'), le)
from calibre.gui2.dialogs.template_line_editor import TemplateLineEditor
self.template_program_box = le = TemplateLineEditor(self.tab_widget)
le.setObjectName('template_program_box')
le.setPlaceholderText(_('The template that generates the value'))
le.setToolTip('<p>' +
_('Right click to open a template editor. <br>'
'Technical note: the set of book ids already matched by '
'previous search terms in the search expression is passed '
'to the template in the global variables dictionary with the '
'key "{0}". You can use the set to limit any work the '
'template does to the set of books already matched, possibly '
'improving performance.'
).format('_candidates') + '</p>')
lo = QHBoxLayout()
lo.addWidget(le)
self.edit_template_button = tb = QToolButton()
tb.setIcon(QIcon.ic("edit_input.png"))
tb.setToolTip(_('Open template editor'))
lo.addWidget(tb)
self.template_layout_label = tll = QLabel(_('&Template:'))
tll.setBuddy(le)
l.addRow(tll, lo)
self.copy_current_template_search_button = le = QPushButton(_('&Copy the current search into the boxes'))
le.setObjectName('copy_current_template_search_button')
le.setToolTip(_('Use this button to retrieve and edit the current search'))
l.addRow('', le)
def setup_ui(self, db):
self.setWindowTitle(_("Advanced search"))
self.setWindowIcon(QIcon.ic('search.png'))
self.l = l = QVBoxLayout(self)
self.h = h = QHBoxLayout()
self.v = v = QVBoxLayout()
l.addLayout(h)
h.addLayout(v)
h.addWidget(create_msg_label(self))
l.addWidget(create_button_box(self))
v.addLayout(create_match_kind(self))
self.tab_widget = tw = QTabWidget(self)
v.addWidget(tw)
create_adv_tab(self)
create_simple_tab(self, db)
create_date_tab(self, db)
create_template_tab(self)
# }}}
class SearchDialog(QDialog):
mc = ''
def __init__(self, parent, db):
QDialog.__init__(self, parent)
setup_ui(self, db)
# Get metadata of some of the selected books to give to the template
# dialog to help test the template
from calibre.gui2.ui import get_gui
view = get_gui().library_view
rows = view.selectionModel().selectedRows()[0:10] # Maximum of 10 books
mi = [db.new_api.get_proxy_metadata(db.data.index_to_id(x.row())) for x in rows]
self.template_program_box.set_mi(mi)
current_tab = gprefs.get('advanced search dialog current tab', 0)
self.tab_widget.setCurrentIndex(current_tab)
if current_tab == 1:
self.matchkind.setCurrentIndex(last_matchkind)
focused_field = gprefs.get('advanced_search_simple_tab_focused_field', 'title_box')
w = getattr(self, focused_field, None)
if w is not None:
w.setFocus(Qt.FocusReason.OtherFocusReason)
elif current_tab == 3:
self.template_program_box.setText(
gprefs.get('advanced_search_template_tab_program_field', ''))
self.template_value_box.setText(
gprefs.get('advanced_search_template_tab_value_field', ''))
self.template_test_type_box.setCurrentIndex(
int(gprefs.get('advanced_search_template_tab_test_field', '0')))
self.current_search_text = get_gui().search.current_text
if self.current_search_text.startswith('template:'):
self.current_search_text = self.current_search_text[len('template:'):]
if self.current_search_text.startswith('"""'):
self.current_search_text = self.current_search_text[3:-3]
elif self.current_search_text.startswith('"'):
# This is a hack to try to compensate for template searches
# that were surrounded with quotes not docstrings. If there is
# escaping in the quoted string it won't be right because the
# final output will be docstring encoded.
self.current_search_text = self.current_search_text[1:-1]
self.copy_current_template_search_button.setEnabled(True)
else:
self.copy_current_template_search_button.setEnabled(False)
self.copy_current_template_search_button.clicked.connect(self.retrieve_template_search)
self.edit_template_button.clicked.connect(lambda:self.template_program_box.open_editor())
self.resize(self.sizeHint())
def retrieve_template_search(self):
template, sep, query = re.split('#@#:([tdnb]):', self.current_search_text, flags=re.IGNORECASE)
self.template_value_box.setText(query)
cb = self.template_test_type_box
for idx in range(0, cb.count()):
if sep == str(cb.itemData(idx)):
cb.setCurrentIndex(idx)
break
self.template_program_box.setText(template)
def save_state(self):
gprefs['advanced search dialog current tab'] = \
self.tab_widget.currentIndex()
if self.tab_widget.currentIndex() == 1:
fw = self.tab_widget.focusWidget()
if fw:
gprefs.set('advanced_search_simple_tab_focused_field', fw.objectName())
elif self.tab_widget.currentIndex() == 3:
gprefs.set('advanced_search_template_tab_program_field',
str(self.template_program_box.text()))
gprefs.set('advanced_search_template_tab_value_field',
str(self.template_value_box.text()))
gprefs.set('advanced_search_template_tab_test_field',
str(self.template_test_type_box.currentIndex()))
def accept(self):
self.save_state()
return QDialog.accept(self)
def reject(self):
self.save_state()
return QDialog.reject(self)
def clear_button_pushed(self):
w = self.tab_widget.currentWidget()
for c in w.findChildren(QComboBox):
c.setCurrentIndex(0)
if w is self.date_tab:
for c in w.findChildren(QSpinBox):
c.setValue(c.minimum())
self.sel_date.setChecked(True)
self.date_year.setValue(now().year)
else:
for c in w.findChildren(QLineEdit):
c.setText('')
for c in w.findChildren(EditWithComplete):
c.setText('')
def tokens(self, raw):
phrases = re.findall(r'\s*".*?"\s*', raw)
for f in phrases:
raw = raw.replace(f, ' ')
phrases = [t.strip('" ') for t in phrases]
return ['"' + self.mc + t + '"' for t in phrases + [r.strip() for r in raw.split()]]
def search_string(self):
i = self.tab_widget.currentIndex()
return (self.adv_search_string, self.box_search_string,
self.date_search_string, self.template_search_string)[i]()
def template_search_string(self):
template = str(self.template_program_box.text())
value = str(self.template_value_box.text())
cb = self.template_test_type_box
op = str(cb.itemData(cb.currentIndex()))
l = f'{template}#@#:{op}:{value}'
# Use docstring quoting (super-quoting) to avoid problems with escaping
return 'template:"""' + l + '"""'
def date_search_string(self):
field = str(self.date_field.itemData(self.date_field.currentIndex()) or '')
op = current_dateop(self.dateop_date)
if op in 'su':
return f'{field}:{"true" if op == "s" else "false"}'
prefix = f'{field}:{op}'
if self.sel_date.isChecked():
ans = f'{prefix}{self.date_year.value()}'
m = self.date_month.itemData(self.date_month.currentIndex())
if m > 0:
ans += '-%s' % m
d = self.date_day.value()
if d > 0:
ans += '-%s' % d
return ans
if self.sel_daysago.isChecked():
val = self.date_daysago.value()
val *= {0:1, 1:7, 2:30, 3:365}[self.date_ago_type.currentIndex()]
return f'{prefix}{val}daysago'
return '{}{}'.format(prefix, str(self.date_human.itemData(self.date_human.currentIndex()) or ''))
def adv_search_string(self):
mk = self.matchkind.currentIndex()
if mk == CONTAINS_MATCH:
self.mc = ''
elif mk == EQUALS_MATCH:
self.mc = '='
elif mk == REGEXP_MATCH:
self.mc = '~'
else:
self.mc = '^'
all, any, phrase, none = map(lambda x: str(x.text()),
(self.all, self.any, self.phrase, self.none))
all, any, none = map(self.tokens, (all, any, none))
phrase = phrase.strip()
all = ' and '.join(all)
any = ' or '.join(any)
none = ' and not '.join(none)
ans = ''
if phrase:
ans += '"%s"'%phrase
if all:
ans += (' and ' if ans else '') + all
if none:
ans += (' and not ' if ans else 'not ') + none
if any:
if ans:
ans += ' and (' + any + ')'
else:
ans = any
return ans
def token(self):
txt = str(self.text.text()).strip()
if txt:
if self.negate.isChecked():
txt = '!'+txt
tok = self.FIELDS[str(self.field.currentText())]+txt
if re.search(r'\s', tok):
tok = '"%s"'%tok
return tok
def box_search_string(self):
mk = self.matchkind.currentIndex()
if mk == CONTAINS_MATCH:
self.mc = ''
elif mk == EQUALS_MATCH:
self.mc = '='
elif mk == REGEXP_MATCH:
self.mc = '~'
else:
self.mc = '^'
ans = []
self.box_last_values = {}
title = str(self.title_box.text()).strip()
self.box_last_values['title_box'] = title
if title:
ans.append('title:"' + self.mc + title + '"')
author = str(self.authors_box.text()).strip()
self.box_last_values['authors_box'] = author
if author:
ans.append('author:"' + self.mc + author + '"')
series = str(self.series_box.text()).strip()
self.box_last_values['series_box'] = series
if series:
ans.append('series:"' + self.mc + series + '"')
tags = str(self.tags_box.text())
self.box_last_values['tags_box'] = tags
tags = [t.strip() for t in tags.split(',') if t.strip()]
if tags:
tags = ['tags:"' + self.mc + t + '"' for t in tags]
ans.append('(' + ' or '.join(tags) + ')')
general = str(self.general_box.text())
self.box_last_values['general_box'] = general
general_index = str(self.general_combo.currentText())
self.box_last_values['general_index'] = general_index
global box_values
global last_matchkind
box_values = copy.deepcopy(self.box_last_values)
last_matchkind = mk
if general:
ans.append(str(self.general_combo.currentText()) + ':"' +
self.mc + general + '"')
if ans:
return ' and '.join(ans)
return ''
if __name__ == '__main__':
from calibre.library import db
db = db()
from calibre.gui2 import Application
app = Application([])
d = SearchDialog(None, db)
d.exec()
print(d.search_string())
| 22,708 | Python | .py | 525 | 34.710476 | 112 | 0.606069 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,016 | saved_search_editor.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/saved_search_editor.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2008, Kovid Goyal <kovid at kovidgoyal.net>
from qt.core import QDialog, QDialogButtonBox, QFormLayout, QIcon, QLabel, QLineEdit, QListWidget, QPlainTextEdit, Qt, QVBoxLayout
from calibre import prepare_string_for_xml
from calibre.gui2 import error_dialog
from calibre.gui2.dialogs.confirm_delete import confirm
from calibre.gui2.widgets2 import Dialog
from calibre.utils.icu import lower as icu_lower
from calibre.utils.icu import sort_key
def commit_searches(searches):
from calibre.gui2.ui import get_gui
db = get_gui().current_db
db.saved_search_set_all(searches)
class AddSavedSearch(Dialog):
def __init__(self, parent=None, search=None, commit_changes=True, label=None, validate=None):
self.initial_search = search
self.validate = validate
self.label = label
self.commit_changes = commit_changes
Dialog.__init__(
self, _('Add a new Saved search'), 'add-saved-search', parent)
from calibre.gui2.ui import get_gui
db = get_gui().current_db
self.searches = {}
for name in db.saved_search_names():
self.searches[name] = db.saved_search_lookup(name)
self.search_names = {icu_lower(n):n for n in db.saved_search_names()}
def setup_ui(self):
self.l = l = QFormLayout(self)
l.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
self.la = la = QLabel(self.label or _(
'You can create a <i>Saved search</i>, for frequently used searches here.'
' The search will be visible under <i>Saved searches</i> in the Tag browser,'
' using the name that you specify here.'))
la.setWordWrap(True)
l.addRow(la)
self.sname = n = QLineEdit(self)
l.addRow(_('&Name:'), n)
n.setPlaceholderText(_('The Saved search name'))
self.search = s = QPlainTextEdit(self)
s.setMinimumWidth(400)
l.addRow(_('&Search:'), s)
s.setPlaceholderText(_('The search expression'))
if self.initial_search:
s.setPlainText(self.initial_search)
n.setFocus(Qt.FocusReason.OtherFocusReason)
l.addRow(self.bb)
def accept(self):
name = self.sname.text().strip()
if not name:
return error_dialog(
self,
_('No search name'),
_('You must specify a name for the Saved search'),
show=True)
expression = self.search.toPlainText().strip()
if not expression:
return error_dialog(
self,
_('No search expression'),
_('You must specify a search expression for the Saved search'),
show=True)
self.accepted_data = name, expression
if self.validate is not None:
err = self.validate(name, expression)
if err:
return error_dialog(self, _('Invalid saved search'), err, show=True)
Dialog.accept(self)
if self.commit_changes:
if icu_lower(name) in self.search_names:
self.searches.pop(self.search_names[icu_lower(name)], None)
self.searches[name] = expression
commit_searches(self.searches)
class SavedSearchEditor(Dialog):
def __init__(self, parent, initial_search=None):
self.initial_search = initial_search
Dialog.__init__(
self, _('Manage Saved searches'), 'manage-saved-searches', parent)
def setup_ui(self):
from calibre.gui2.ui import get_gui
db = get_gui().current_db
self.l = l = QVBoxLayout(self)
b = self.bb.addButton(_('&Add search'), QDialogButtonBox.ButtonRole.ActionRole)
b.setIcon(QIcon.ic('search_add_saved.png'))
b.clicked.connect(self.add_search)
b = self.bb.addButton(_('&Remove search'), QDialogButtonBox.ButtonRole.ActionRole)
b.setIcon(QIcon.ic('search_delete_saved.png'))
b.clicked.connect(self.del_search)
b = self.bb.addButton(_('&Edit search'), QDialogButtonBox.ButtonRole.ActionRole)
b.setIcon(QIcon.ic('modified.png'))
b.clicked.connect(self.edit_search)
self.slist = QListWidget(self)
self.slist.setStyleSheet('QListView::item { padding: 3px }')
self.slist.activated.connect(self.edit_search)
self.slist.setAlternatingRowColors(True)
self.searches = {name: db.saved_search_lookup(name) for name in db.saved_search_names()}
self.populate_search_list()
if self.initial_search is not None and self.initial_search in self.searches:
self.select_search(self.initial_search)
elif self.searches:
self.slist.setCurrentRow(0)
self.slist.currentItemChanged.connect(self.current_index_changed)
l.addWidget(self.slist)
self.desc = la = QLabel('\xa0')
la.setWordWrap(True)
l.addWidget(la)
l.addWidget(self.bb)
self.current_index_changed(self.slist.currentItem())
self.setMinimumHeight(500)
self.setMinimumWidth(600)
@property
def current_search_name(self):
i = self.slist.currentItem()
if i is not None:
ans = i.text()
if ans in self.searches:
return ans
def keyPressEvent(self, ev):
if ev.key() == Qt.Key.Key_Delete:
self.del_search()
return
return Dialog.keyPressEvent(self, ev)
def populate_search_list(self):
self.slist.clear()
for name in sorted(self.searches.keys(), key=sort_key):
self.slist.addItem(name)
def add_search(self):
d = AddSavedSearch(parent=self, commit_changes=False, validate=self.validate_add)
if d.exec() != QDialog.DialogCode.Accepted:
return
name, expression = d.accepted_data
self.searches[name] = expression
self.populate_search_list()
self.select_search(name)
def del_search(self):
n = self.current_search_name
if n is not None:
if not confirm(
'<p>' + _(
'The current saved search will be '
'<b>permanently deleted</b>. Are you sure?') + '</p>',
'saved_search_editor_delete', self):
return
self.slist.takeItem(self.slist.currentRow())
del self.searches[n]
def edit_search(self):
n = self.current_search_name
if not n:
return
d = AddSavedSearch(parent=self, commit_changes=False,
label=_('Edit the name and/or expression below.'),
validate=self.validate_edit)
d.setWindowTitle(_('Edit saved search'))
d.sname.setText(n)
d.search.setPlainText(self.searches[n])
if d.exec() != QDialog.DialogCode.Accepted:
return
name, expression = d.accepted_data
self.slist.currentItem().setText(name)
del self.searches[n]
self.searches[name] = expression
self.current_index_changed(self.slist.currentItem())
def duplicate_msg(self, name):
return _('A saved search with the name {} already exists. Choose another name').format(name)
def validate_edit(self, name, expression):
q = self.current_search_name
if icu_lower(name) in {icu_lower(n) for n in self.searches if n != q}:
return self.duplicate_msg(name)
def validate_add(self, name, expression):
if icu_lower(name) in {icu_lower(n) for n in self.searches}:
return self.duplicate_msg(name)
def select_search(self, name):
items = self.slist.findItems(name, Qt.MatchFlag.MatchFixedString | Qt.MatchFlag.MatchCaseSensitive)
if items:
self.slist.setCurrentItem(items[0])
def current_index_changed(self, item):
n = self.current_search_name
if n:
t = self.searches[n]
else:
t = ''
self.desc.setText('<p><b>{}</b>: '.format(_('Search expression')) + prepare_string_for_xml(t))
def accept(self):
commit_searches(self.searches)
Dialog.accept(self)
| 8,260 | Python | .py | 185 | 34.805405 | 130 | 0.623181 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,017 | select_formats.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/select_formats.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from qt.core import QAbstractItemView, QAbstractListModel, QApplication, QDialog, QDialogButtonBox, QLabel, QListView, QSize, Qt, QVBoxLayout
from calibre.gui2 import file_icon_provider
class Formats(QAbstractListModel):
def __init__(self, fmt_count):
QAbstractListModel.__init__(self)
self.fmts = sorted(set(fmt_count))
self.counts = fmt_count
self.fi = file_icon_provider()
def rowCount(self, parent):
return len(self.fmts)
def data(self, index, role):
row = index.row()
if role == Qt.ItemDataRole.DisplayRole:
fmt = self.fmts[row]
count = self.counts[fmt]
return ('%s [%d]'%(fmt.upper(), count))
if role == Qt.ItemDataRole.DecorationRole:
return (self.fi.icon_from_ext(self.fmts[row].lower()))
if role == Qt.ItemDataRole.ToolTipRole:
fmt = self.fmts[row]
count = self.counts[fmt]
return _('There is one book with the {} format').format(fmt.upper()) if count == 1 else _(
'There are {count} books with the {fmt} format').format(
count=count, fmt=fmt.upper())
return None
def flags(self, index):
return Qt.ItemFlag.ItemIsSelectable|Qt.ItemFlag.ItemIsEnabled
def fmt(self, idx):
return self.fmts[idx.row()]
class SelectFormats(QDialog):
def __init__(self, fmt_count, msg, single=False, parent=None, exclude=False):
QDialog.__init__(self, parent)
self._l = QVBoxLayout(self)
self.single_fmt = single
self.setLayout(self._l)
self.setWindowTitle(_('Choose formats'))
self._m = QLabel(msg)
self._m.setWordWrap(True)
self._l.addWidget(self._m)
self.formats = Formats(fmt_count)
self.fview = QListView(self)
self.fview.doubleClicked.connect(self.double_clicked,
type=Qt.ConnectionType.QueuedConnection)
if exclude:
self.fview.setStyleSheet(f'QListView {{ background-color: {QApplication.instance().emphasis_window_background_color} }}')
self._l.addWidget(self.fview)
self.fview.setModel(self.formats)
self.fview.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection if single else
QAbstractItemView.SelectionMode.MultiSelection)
self.bbox = \
QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel,
Qt.Orientation.Horizontal, self)
self._l.addWidget(self.bbox)
self.bbox.accepted.connect(self.accept)
self.bbox.rejected.connect(self.reject)
self.fview.setIconSize(QSize(48, 48))
self.fview.setSpacing(2)
self.resize(350, 500)
self.selected_formats = set()
def accept(self, *args):
for idx in self.fview.selectedIndexes():
self.selected_formats.add(self.formats.fmt(idx))
QDialog.accept(self, *args)
def double_clicked(self, index):
if self.single_fmt:
self.accept()
if __name__ == '__main__':
from calibre.gui2 import Application
app = Application([])
d = SelectFormats(['epub', 'lrf', 'lit', 'mobi'], 'Choose a format')
d.exec()
print(d.selected_formats)
| 3,441 | Python | .py | 76 | 36.381579 | 141 | 0.641256 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,018 | enum_values_edit.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/enum_values_edit.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2020, Charles Haley
from qt.core import (
QAbstractItemView,
QColor,
QComboBox,
QDialog,
QDialogButtonBox,
QGridLayout,
QHeaderView,
QIcon,
Qt,
QTableWidget,
QTableWidgetItem,
QToolButton,
QVBoxLayout,
)
from calibre.gui2 import error_dialog, gprefs
class EnumValuesEdit(QDialog):
def __init__(self, parent, db, key):
QDialog.__init__(self, parent)
self.setWindowTitle(_('Edit permissible values for {0}').format(key))
self.db = db
l = QGridLayout()
bbox = QVBoxLayout()
bbox.addStretch(10)
self.del_button = QToolButton()
self.del_button.setIcon(QIcon.ic('trash.png'))
self.del_button.setToolTip(_('Remove the currently selected value'))
self.ins_button = QToolButton()
self.ins_button.setIcon(QIcon.ic('plus.png'))
self.ins_button.setToolTip(_('Add a new permissible value'))
self.move_up_button= QToolButton()
self.move_up_button.setIcon(QIcon.ic('arrow-up.png'))
self.move_down_button= QToolButton()
self.move_down_button.setIcon(QIcon.ic('arrow-down.png'))
bbox.addWidget(self.del_button)
bbox.addStretch(1)
bbox.addWidget(self.ins_button)
bbox.addStretch(1)
bbox.addWidget(self.move_up_button)
bbox.addStretch(1)
bbox.addWidget(self.move_down_button)
bbox.addStretch(10)
l.addItem(bbox, 0, 0)
self.del_button.clicked.connect(self.del_line)
self.all_colors = {str(s) for s in list(QColor.colorNames())}
tl = QVBoxLayout()
l.addItem(tl, 0, 1)
self.table = t = QTableWidget(parent)
t.setColumnCount(2)
t.setRowCount(1)
t.setHorizontalHeaderLabels([_('Value'), _('Color')])
t.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
tl.addWidget(t)
self.key = key
self.fm = fm = db.field_metadata[key]
permitted_values = fm.get('display', {}).get('enum_values', '')
colors = fm.get('display', {}).get('enum_colors', '')
t.setRowCount(len(permitted_values))
for i,v in enumerate(permitted_values):
self.make_name_item(i, v)
c = self.make_color_combobox(i, -1)
if colors:
c.setCurrentIndex(c.findText(colors[i]))
else:
c.setCurrentIndex(0)
t.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
self.setLayout(l)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
bb.accepted.connect(self.accept)
bb.rejected.connect(self.reject)
l.addWidget(bb, 1, 0, 1, 2)
self.ins_button.clicked.connect(self.ins_button_clicked)
self.move_down_button.clicked.connect(self.move_down_clicked)
self.move_up_button.clicked.connect(self.move_up_clicked)
self.restore_geometry(gprefs, 'enum-values-edit-geometry')
def sizeHint(self):
sz = QDialog.sizeHint(self)
sz.setWidth(max(sz.width(), 600))
sz.setHeight(max(sz.height(), 400))
return sz
def make_name_item(self, row, txt):
it = QTableWidgetItem(txt)
it.setData(Qt.ItemDataRole.UserRole, txt)
it.setCheckState(Qt.CheckState.Unchecked)
it.setToolTip('<p>' + _('Check the box if you change the value and want it renamed in books where it is used') + '</p>')
self.table.setItem(row, 0, it)
def make_color_combobox(self, row, dex):
c = QComboBox(self)
c.addItem('')
c.addItems(QColor.colorNames())
c.setToolTip('<p>' + _('Selects the color of the text when displayed in the book list. '
'Either all rows must have a color or no rows have a color') + '</p>')
self.table.setCellWidget(row, 1, c)
if dex >= 0:
c.setCurrentIndex(dex)
return c
def move_up_clicked(self):
row = self.table.currentRow()
if row < 0:
error_dialog(self, _('Select a cell'),
_('Select a cell before clicking the button'), show=True)
return
if row == 0:
return
self.move_row(row, -1)
def move_row(self, row, direction):
t = self.table.takeItem(row, 0)
c = self.table.cellWidget(row, 1).currentIndex()
self.table.removeRow(row)
row += direction
self.table.insertRow(row)
self.table.setItem(row, 0, t)
self.make_color_combobox(row, c)
self.table.setCurrentCell(row, 0)
def move_down_clicked(self):
row = self.table.currentRow()
if row < 0:
error_dialog(self, _('Select a cell'),
_('Select a cell before clicking the button'), show=True)
return
if row >= self.table.rowCount() - 1:
return
self.move_row(row, 1)
def del_line(self):
if self.table.currentRow() >= 0:
self.table.removeRow(self.table.currentRow())
def ins_button_clicked(self):
row = self.table.currentRow()
if row < 0:
error_dialog(self, _('Select a cell'),
_('Select a cell before clicking the button'), show=True)
return
self.table.insertRow(row)
self.make_name_item(row, '')
self.make_color_combobox(row, -1)
def save_geometry(self):
super().save_geometry(gprefs, 'enum-values-edit-geometry')
def accept(self):
disp = self.fm['display']
values = []
colors = []
id_map = {}
for i in range(0, self.table.rowCount()):
it = self.table.item(i, 0)
v = str(it.text())
if not v:
error_dialog(self, _('Empty value'),
_('Empty values are not allowed'), show=True)
return
ov = str(it.data(Qt.ItemDataRole.UserRole))
if v != ov and it.checkState() == Qt.CheckState.Checked:
fid = self.db.new_api.get_item_id(self.key, ov)
id_map[fid] = v
values.append(v)
c = str(self.table.cellWidget(i, 1).currentText())
if c:
colors.append(c)
l_lower = [v.lower() for v in values]
for i,v in enumerate(l_lower):
if v in l_lower[i+1:]:
error_dialog(self, _('Duplicate value'),
_('The value "{0}" is in the list more than '
'once, perhaps with different case').format(values[i]),
show=True)
return
if colors and len(colors) != len(values):
error_dialog(self, _('Invalid colors specification'), _(
'Either all values or no values must have colors'), show=True)
return
disp['enum_values'] = values
disp['enum_colors'] = colors
self.db.set_custom_column_metadata(self.fm['colnum'], display=disp,
update_last_modified=True)
if id_map:
self.db.new_api.rename_items(self.key, id_map)
self.save_geometry()
return QDialog.accept(self)
def reject(self):
self.save_geometry()
return QDialog.reject(self)
| 7,518 | Python | .py | 182 | 30.681319 | 128 | 0.579444 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,019 | confirm_delete_location.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/confirm_delete_location.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net' \
'2010, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from qt.core import QDialog, QHBoxLayout, QIcon, QLabel, QPushButton, QSizePolicy, Qt, QVBoxLayout
from calibre.startup import connect_lambda
class Dialog(QDialog):
def __init__(self, msg, name, parent, icon='dialog_warning.png'):
super().__init__(parent)
ic = QIcon.ic(icon)
self.setWindowIcon(ic)
self.l = l = QVBoxLayout(self)
h = QHBoxLayout()
la = QLabel(self)
sp = QSizePolicy(QSizePolicy.Policy.Maximum, QSizePolicy.Policy.Preferred)
sp.setHorizontalStretch(0), sp.setVerticalStretch(0)
sp.setHeightForWidth(la.sizePolicy().hasHeightForWidth())
la.setSizePolicy(sp)
la.setPixmap(ic.pixmap(ic.availableSizes()[0]))
h.addWidget(la)
la = QLabel(msg)
h.addWidget(la)
la.setWordWrap(True)
l.addLayout(h)
h = QHBoxLayout()
l.addLayout(h)
self.button_lib = b = QPushButton(QIcon.ic('lt.png'), _('&Library'), self)
h.addWidget(b)
self.button_device = b = QPushButton(QIcon.ic('reader.png'), _('&Device'), self)
h.addWidget(b)
self.button_both = b = QPushButton(QIcon.ic('trash.png'), _('Library &and device'), self)
h.addWidget(b)
h.addStretch(10)
self.button_cancel = b = QPushButton(QIcon.ic('window-close.png'), _('&Cancel'), self)
h.addWidget(b)
self.loc = None
self.name = name
self.button_cancel.setFocus(Qt.FocusReason.OtherFocusReason)
connect_lambda(self.button_lib.clicked, self, lambda self: self.set_loc('lib'))
connect_lambda(self.button_device.clicked, self, lambda self: self.set_loc('dev'))
connect_lambda(self.button_both.clicked, self, lambda self: self.set_loc('both'))
connect_lambda(self.button_cancel.clicked, self, lambda self: self.reject())
self.resize(self.sizeHint())
def set_loc(self, loc):
self.loc = loc
self.accept()
def choice(self):
return self.loc
def break_cycles(self):
for x in ('lib', 'device', 'both'):
b = getattr(self, 'button_'+x)
try:
b.clicked.disconnect()
except:
pass
def confirm_location(msg, name, parent=None, pixmap='dialog_warning.png'):
d = Dialog(msg, name, parent, icon=pixmap)
ret = d.exec()
d.break_cycles()
return d.choice() if ret == QDialog.DialogCode.Accepted else None
if __name__ == '__main__':
from calibre.gui2 import Application
app = Application([])
confirm_location('testing this dialog', 'test dialog')
| 2,814 | Python | .py | 65 | 35.292308 | 98 | 0.629481 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,020 | __init__.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/__init__.py | __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
'''Various dialogs used in the GUI'''
| 126 | Python | .py | 3 | 40.666667 | 61 | 0.663934 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,021 | scheduler.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/scheduler.py | __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net'
__docformat__ = 'restructuredtext en'
'''
Scheduler for automated recipe downloads
'''
import calendar
import textwrap
from collections import OrderedDict
from contextlib import suppress
from datetime import timedelta
from qt.core import (
QAction,
QCheckBox,
QDialog,
QDialogButtonBox,
QDoubleSpinBox,
QFormLayout,
QFrame,
QGridLayout,
QGroupBox,
QHBoxLayout,
QIcon,
QLabel,
QLineEdit,
QMenu,
QObject,
QPushButton,
QRadioButton,
QRecursiveMutex,
QSize,
QSizePolicy,
QSpacerItem,
QSpinBox,
QStackedWidget,
Qt,
QTabWidget,
QTime,
QTimeEdit,
QTimer,
QToolButton,
QTreeView,
QVBoxLayout,
QWidget,
pyqtSignal,
)
from calibre import force_unicode
from calibre.gui2 import config as gconf
from calibre.gui2 import error_dialog, gprefs
from calibre.gui2.search_box import SearchBox2
from calibre.utils.date import utcnow
from calibre.utils.localization import canonicalize_lang, get_lang
from calibre.utils.network import internet_connected
from calibre.web.feeds.recipes.model import RecipeModel
from polyglot.builtins import iteritems
def convert_day_time_schedule(val):
day_of_week, hour, minute = val
if day_of_week == -1:
return (tuple(range(7)), hour, minute)
return ((day_of_week,), hour, minute)
class RecipesView(QTreeView):
item_activated = pyqtSignal(object)
def __init__(self, parent):
QTreeView.__init__(self, parent)
self.setAnimated(True)
self.setHeaderHidden(True)
self.setObjectName('recipes')
self.setExpandsOnDoubleClick(True)
self.doubleClicked.connect(self.double_clicked)
self.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Expanding)
def double_clicked(self, index):
self.item_activated.emit(index)
def currentChanged(self, current, previous):
QTreeView.currentChanged(self, current, previous)
self.parent().current_changed(current, previous)
# Time/date widgets {{{
class Base(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.l = QGridLayout()
self.setLayout(self.l)
self.setToolTip(textwrap.dedent(self.HELP))
class DaysOfWeek(Base):
HELP = _('''\
Download this periodical every week on the specified days after
the specified time. For example, if you choose: Monday after
9:00 AM, then the periodical will be download every Monday as
soon after 9:00 AM as possible.
''')
def __init__(self, parent=None):
Base.__init__(self, parent)
self.days = [QCheckBox(force_unicode(calendar.day_abbr[d]),
self) for d in range(7)]
for i, cb in enumerate(self.days):
row = i % 2
col = i // 2
self.l.addWidget(cb, row, col, 1, 1)
self.time = QTimeEdit(self)
self.time.setDisplayFormat('hh:mm AP')
if canonicalize_lang(get_lang()) in {'deu', 'nds'}:
self.time.setDisplayFormat('HH:mm')
self.hl = QHBoxLayout()
self.l1 = QLabel(_('&Download after:'))
self.l1.setBuddy(self.time)
self.hl.addWidget(self.l1)
self.hl.addWidget(self.time)
self.l.addLayout(self.hl, 1, 3, 1, 1)
self.initialize()
def initialize(self, typ=None, val=None):
if typ is None:
typ = 'day/time'
val = (-1, 6, 0)
if typ == 'day/time':
val = convert_day_time_schedule(val)
days_of_week, hour, minute = val
for i, d in enumerate(self.days):
d.setChecked(i in days_of_week)
self.time.setTime(QTime(hour, minute))
@property
def schedule(self):
days_of_week = tuple(i for i, d in enumerate(self.days) if
d.isChecked())
t = self.time.time()
hour, minute = t.hour(), t.minute()
return 'days_of_week', (days_of_week, int(hour), int(minute))
class DaysOfMonth(Base):
HELP = _('''\
Download this periodical every month, on the specified days.
The download will happen as soon after the specified time as
possible on the specified days of each month. For example,
if you choose the 1st and the 15th after 9:00 AM, the
periodical will be downloaded on the 1st and 15th of every
month, as soon after 9:00 AM as possible.
''')
def __init__(self, parent=None):
Base.__init__(self, parent)
self.l1 = QLabel(_('&Days of the month:'))
self.days = QLineEdit(self)
self.days.setToolTip(_('Comma separated list of days of the month.'
' For example: 1, 15'))
self.l1.setBuddy(self.days)
self.l2 = QLabel(_('Download &after:'))
self.time = QTimeEdit(self)
self.time.setDisplayFormat('hh:mm AP')
self.l2.setBuddy(self.time)
self.l.addWidget(self.l1, 0, 0, 1, 1)
self.l.addWidget(self.days, 0, 1, 1, 1)
self.l.addWidget(self.l2, 1, 0, 1, 1)
self.l.addWidget(self.time, 1, 1, 1, 1)
def initialize(self, typ=None, val=None):
if val is None:
val = ((1,), 6, 0)
days_of_month, hour, minute = val
self.days.setText(', '.join(map(str, map(int, days_of_month))))
self.time.setTime(QTime(hour, minute))
@property
def schedule(self):
parts = [x.strip() for x in str(self.days.text()).split(',') if
x.strip()]
try:
days_of_month = tuple(map(int, parts))
except:
days_of_month = (1,)
if not days_of_month:
days_of_month = (1,)
t = self.time.time()
hour, minute = t.hour(), t.minute()
return 'days_of_month', (days_of_month, int(hour), int(minute))
class EveryXDays(Base):
HELP = _('''\
Download this periodical every x days. For example, if you
choose 30 days, the periodical will be downloaded every 30
days. Note that you can set periods of less than a day, like
0.1 days to download a periodical more than once a day.
''')
def __init__(self, parent=None):
Base.__init__(self, parent)
self.l1 = QLabel(_('&Download every:'))
self.interval = QDoubleSpinBox(self)
self.interval.setMinimum(0.04)
self.interval.setSpecialValueText(_('every hour'))
self.interval.setMaximum(1000.0)
self.interval.setValue(31.0)
self.interval.setSuffix(' ' + _('days'))
self.interval.setSingleStep(1.0)
self.interval.setDecimals(2)
self.l1.setBuddy(self.interval)
self.l2 = QLabel(_('Note: You can set intervals of less than a day,'
' by typing the value manually.'))
self.l2.setWordWrap(True)
self.l.addWidget(self.l1, 0, 0, 1, 1)
self.l.addWidget(self.interval, 0, 1, 1, 1)
self.l.addWidget(self.l2, 1, 0, 1, -1)
def initialize(self, typ=None, val=None):
if val is None:
val = 31.0
self.interval.setValue(val)
@property
def schedule(self):
schedule = self.interval.value()
return 'interval', schedule
# }}}
class SchedulerDialog(QDialog):
SCHEDULE_TYPES = OrderedDict([
('days_of_week', DaysOfWeek),
('days_of_month', DaysOfMonth),
('every_x_days', EveryXDays),
])
download = pyqtSignal(object)
def __init__(self, recipe_model, parent=None):
QDialog.__init__(self, parent)
self.commit_on_change = True
self.previous_urn = None
self.setWindowIcon(QIcon.ic('scheduler.png'))
self.l = l = QGridLayout(self)
# Left panel
self.h = h = QHBoxLayout()
l.addLayout(h, 0, 0, 1, 1)
self.search = s = SearchBox2(self)
self.search.initialize('scheduler_search_history')
self.search.setMinimumContentsLength(15)
self.go_button = b = QToolButton(self)
b.setText(_("Go"))
b.clicked.connect(self.search.do_search)
h.addWidget(s), h.addWidget(b)
self.recipes = RecipesView(self)
l.addWidget(self.recipes, 1, 0, 2, 1)
self.recipe_model = recipe_model
self.recipe_model.do_refresh()
self.recipes.setModel(self.recipe_model)
self.recipes.setFocus(Qt.FocusReason.OtherFocusReason)
self.recipes.item_activated.connect(self.download_clicked)
self.setWindowTitle(_("Schedule news download [{} sources]").format(self.recipe_model.showing_count))
self.search.search.connect(self.recipe_model.search)
self.recipe_model.searched.connect(self.search.search_done, type=Qt.ConnectionType.QueuedConnection)
self.recipe_model.searched.connect(self.search_done)
# Right Panel
self.scroll_area_contents = sac = QWidget(self)
self.l.addWidget(sac, 0, 1, 2, 1)
sac.v = v = QVBoxLayout(sac)
v.setContentsMargins(0, 0, 0, 0)
self.detail_box = QTabWidget(self)
self.detail_box.setVisible(False)
self.detail_box.setCurrentIndex(0)
v.addWidget(self.detail_box)
v.addItem(QSpacerItem(20, 40, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Expanding))
# First Tab (scheduling)
self.tab = QWidget()
self.detail_box.addTab(self.tab, _("&Schedule"))
self.tab.v = vt = QVBoxLayout(self.tab)
self.blurb = la = QLabel('blurb')
la.setWordWrap(True), la.setOpenExternalLinks(True)
vt.addWidget(la)
self.frame = f = QFrame(self.tab)
vt.addWidget(f)
f.setFrameShape(QFrame.Shape.StyledPanel)
f.setFrameShadow(QFrame.Shadow.Raised)
f.v = vf = QVBoxLayout(f)
self.schedule = s = QCheckBox(_("&Schedule for download:"), f)
self.schedule.stateChanged[int].connect(self.toggle_schedule_info)
vf.addWidget(s)
f.h = h = QHBoxLayout()
vf.addLayout(h)
self.days_of_week = QRadioButton(_("&Days of week"), f)
self.days_of_month = QRadioButton(_("Da&ys of month"), f)
self.every_x_days = QRadioButton(_("Every &x days"), f)
self.days_of_week.setChecked(True)
h.addWidget(self.days_of_week), h.addWidget(self.days_of_month), h.addWidget(self.every_x_days)
self.schedule_stack = ss = QStackedWidget(f)
self.schedule_widgets = []
for key in reversed(self.SCHEDULE_TYPES):
self.schedule_widgets.insert(0, self.SCHEDULE_TYPES[key](self))
self.schedule_stack.insertWidget(0, self.schedule_widgets[0])
vf.addWidget(ss)
self.last_downloaded = la = QLabel(f)
la.setWordWrap(True)
vf.addWidget(la)
self.rla = la = QLabel(_("For the scheduling to work, you must leave calibre running."))
la.setWordWrap(True)
vf.addWidget(la)
self.account = acc = QGroupBox(self.tab)
acc.setTitle(_("&Account"))
vt.addWidget(acc)
acc.g = g = QGridLayout(acc)
acc.unla = la = QLabel(_("&Username:"))
self.username = un = QLineEdit(self)
la.setBuddy(un)
g.addWidget(la), g.addWidget(un, 0, 1)
acc.pwla = la = QLabel(_("&Password:"))
self.password = pw = QLineEdit(self)
pw.setEchoMode(QLineEdit.EchoMode.Password), la.setBuddy(pw)
g.addWidget(la), g.addWidget(pw, 1, 1)
self.show_password = spw = QCheckBox(_("&Show password"), self.account)
spw.stateChanged[int].connect(self.set_pw_echo_mode)
g.addWidget(spw, 2, 0, 1, 2)
for b, c in iteritems(self.SCHEDULE_TYPES):
b = getattr(self, b)
b.toggled.connect(self.schedule_type_selected)
b.setToolTip(textwrap.dedent(c.HELP))
# Second tab (advanced settings)
self.tab2 = t2 = QWidget()
self.detail_box.addTab(self.tab2, _("&Advanced"))
self.tab2.g = g = QFormLayout(t2)
g.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
self.add_title_tag = tt = QCheckBox(_("Add &title as tag"), t2)
g.addRow(tt)
self.custom_tags = ct = QLineEdit(self)
g.addRow(_("&Extra tags:"), ct)
self.keep_issues = ki = QSpinBox(t2)
tt.toggled['bool'].connect(self.keep_issues.setEnabled)
ki.setMaximum(100000)
ki.setToolTip(_(
"<p>When set, this option will cause calibre to keep, at most, the specified number of issues"
" of this periodical. Every time a new issue is downloaded, the oldest one is deleted, if the"
" total is larger than this number.\n<p>Note that this feature only works if you have the"
" option to add the title as tag checked, above.\n<p>Also, the setting for deleting periodicals"
" older than a number of days, below, takes priority over this setting."))
ki.setSpecialValueText(_("all issues")), ki.setSuffix(_(" issues"))
g.addRow(_("&Keep at most:"), ki)
self.recipe_specific_widgets = {}
# Bottom area
self.hb = h = QHBoxLayout()
self.l.addLayout(h, 2, 1, 1, 1)
self.labt = la = QLabel(_("Delete downloaded &news older than:"))
self.old_news = on = QSpinBox(self)
on.setToolTip(_(
"<p>Delete downloaded news older than the specified number of days. Set to zero to disable.\n"
"<p>You can also control the maximum number of issues of a specific periodical that are kept"
" by clicking the Advanced tab for that periodical above."))
on.setSpecialValueText(_("never delete")), on.setSuffix(_(" days"))
on.setMaximum(1000), la.setBuddy(on)
on.setValue(gconf['oldest_news'])
h.addWidget(la), h.addWidget(on)
self.download_all_button = b = QPushButton(QIcon.ic('news.png'), _("Download &all scheduled"), self)
b.setToolTip(_("Download all scheduled news sources at once"))
b.clicked.connect(self.download_all_clicked)
self.l.addWidget(b, 3, 0, 1, 1)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel, self)
bb.accepted.connect(self.accept), bb.rejected.connect(self.reject)
self.download_button = b = bb.addButton(_('&Download now'), QDialogButtonBox.ButtonRole.ActionRole)
b.setIcon(QIcon.ic('arrow-down.png')), b.setVisible(False)
b.clicked.connect(self.download_clicked)
self.l.addWidget(bb, 3, 1, 1, 1)
self.restore_geometry(gprefs, 'scheduler_dialog_geometry')
def sizeHint(self):
return QSize(800, 600)
def set_pw_echo_mode(self, state):
self.password.setEchoMode(QLineEdit.EchoMode.Normal
if Qt.CheckState(state) == Qt.CheckState.Checked else QLineEdit.EchoMode.Password)
def schedule_type_selected(self, *args):
for i, st in enumerate(self.SCHEDULE_TYPES):
if getattr(self, st).isChecked():
self.schedule_stack.setCurrentIndex(i)
break
def keyPressEvent(self, ev):
if ev.key() not in (Qt.Key.Key_Enter, Qt.Key.Key_Return):
return QDialog.keyPressEvent(self, ev)
def break_cycles(self):
try:
self.recipe_model.searched.disconnect(self.search_done)
self.recipe_model.searched.disconnect(self.search.search_done)
self.search.search.disconnect()
self.download.disconnect()
except:
pass
self.recipe_model = None
def search_done(self, *args):
if self.recipe_model.showing_count < 20:
self.recipes.expandAll()
def toggle_schedule_info(self, *args):
enabled = self.schedule.isChecked()
for x in self.SCHEDULE_TYPES:
getattr(self, x).setEnabled(enabled)
self.schedule_stack.setEnabled(enabled)
self.last_downloaded.setVisible(enabled)
def current_changed(self, current, previous):
if self.previous_urn is not None:
self.commit(urn=self.previous_urn)
self.previous_urn = None
urn = self.current_urn
if urn is not None:
self.initialize_detail_box(urn)
self.recipes.scrollTo(current)
def accept(self):
if not self.commit():
return False
self.save_geometry(gprefs, 'scheduler_dialog_geometry')
return QDialog.accept(self)
def reject(self):
self.save_geometry(gprefs, 'scheduler_dialog_geometry')
return QDialog.reject(self)
def download_clicked(self, *args):
self.commit()
if self.commit() and self.current_urn:
self.download.emit(self.current_urn)
def download_all_clicked(self, *args):
if self.commit() and self.commit():
self.download.emit(None)
@property
def current_urn(self):
current = self.recipes.currentIndex()
if current.isValid():
return getattr(current.internalPointer(), 'urn', None)
def commit(self, urn=None):
urn = self.current_urn if urn is None else urn
if not self.detail_box.isVisible() or urn is None:
return True
if self.account.isVisible():
un, pw = map(str, (self.username.text(), self.password.text()))
un, pw = un.strip(), pw.strip()
if not un and not pw and self.schedule.isChecked():
if not getattr(self, 'subscription_optional', False):
error_dialog(self, _('Need username and password'),
_('You must provide a username and/or password to '
'use this news source.'), show=True)
return False
if un or pw:
self.recipe_model.set_account_info(urn, un, pw)
else:
self.recipe_model.clear_account_info(urn)
if self.schedule.isChecked():
schedule_type, schedule = \
self.schedule_stack.currentWidget().schedule
self.recipe_model.schedule_recipe(urn, schedule_type, schedule)
else:
self.recipe_model.un_schedule_recipe(urn)
add_title_tag = self.add_title_tag.isChecked()
keep_issues = '0'
if self.keep_issues.isEnabled():
keep_issues = str(self.keep_issues.value())
custom_tags = str(self.custom_tags.text()).strip()
custom_tags = [x.strip() for x in custom_tags.split(',')]
from calibre.web.feeds.recipes.collection import RecipeCustomization
recipe_specific_options = None
if self.recipe_specific_widgets:
recipe_specific_options = {name: w.text().strip() for name, w in self.recipe_specific_widgets.items() if w.text().strip()}
self.recipe_model.customize_recipe(urn, RecipeCustomization(add_title_tag, custom_tags, keep_issues, recipe_specific_options))
return True
def initialize_detail_box(self, urn):
self.previous_urn = urn
self.detail_box.setVisible(True)
self.download_button.setVisible(True)
self.detail_box.setCurrentIndex(0)
recipe = self.recipe_model.recipe_from_urn(urn)
try:
schedule_info = self.recipe_model.schedule_info_from_urn(urn)
except:
# Happens if user does something stupid like unchecking all the
# days of the week
schedule_info = None
account_info = self.recipe_model.account_info_from_urn(urn)
customize_info = self.recipe_model.get_customize_info(urn)
ns = recipe.get('needs_subscription', '')
self.account.setVisible(ns in ('yes', 'optional'))
self.subscription_optional = ns == 'optional'
act = _('Account')
act2 = _('(optional)') if self.subscription_optional else \
_('(required)')
self.account.setTitle(act+' '+act2)
un = pw = ''
if account_info is not None:
un, pw = account_info[:2]
if not un:
un = ''
if not pw:
pw = ''
self.username.setText(un)
self.password.setText(pw)
self.show_password.setChecked(False)
self.blurb.setText('''
<p>
<b>%(title)s</b><br>
%(cb)s %(author)s<br/>
%(description)s
</p>
'''%dict(title=recipe.get('title'), cb=_('Created by: '),
author=recipe.get('author', _('Unknown')),
description=recipe.get('description', '')))
self.download_button.setToolTip(
_('Download %s now')%recipe.get('title'))
scheduled = schedule_info is not None
self.schedule.setChecked(scheduled)
self.toggle_schedule_info()
self.last_downloaded.setText(_('Last downloaded: never'))
ld_text = _('never')
if scheduled:
typ, sch, last_downloaded = schedule_info
d = utcnow() - last_downloaded
def hm(x):
return (x-x%3600)//3600, (x%3600 - (x%3600)%60)//60
hours, minutes = hm(d.seconds)
tm = _('%(days)d days, %(hours)d hours'
' and %(mins)d minutes ago')%dict(
days=d.days, hours=hours, mins=minutes)
if d < timedelta(days=366):
ld_text = tm
else:
typ, sch = 'day/time', (-1, 6, 0)
sch_widget = {'day/time': 0, 'days_of_week': 0, 'days_of_month':1,
'interval':2}[typ]
rb = getattr(self, list(self.SCHEDULE_TYPES)[sch_widget])
rb.setChecked(True)
self.schedule_stack.setCurrentIndex(sch_widget)
self.schedule_stack.currentWidget().initialize(typ, sch)
self.add_title_tag.setChecked(customize_info.add_title_tag)
self.custom_tags.setText(', '.join(customize_info.custom_tags))
self.last_downloaded.setText(_('Last downloaded:') + ' ' + ld_text)
self.keep_issues.setValue(customize_info.keep_issues)
self.keep_issues.setEnabled(self.add_title_tag.isChecked())
g = self.tab2.layout()
for x in self.recipe_specific_widgets.values():
g.removeRow(x)
self.recipe_specific_widgets = {}
raw = recipe.get('options')
if raw:
import json
rsom = json.loads(raw)
rso = customize_info.recipe_specific_options
for name, metadata in rsom.items():
w = QLineEdit(self)
if 'default' in metadata:
w.setPlaceholderText(_('Default if unspecified: {}').format(metadata['default']))
w.setClearButtonEnabled(True)
w.setText(str(rso.get(name, '')).strip())
w.setToolTip(str(metadata.get('long', '')))
title = '&' + str(metadata.get('short') or name).replace('&', '&&') + ':'
g.addRow(title, w)
self.recipe_specific_widgets[name] = w
class Scheduler(QObject):
INTERVAL = 1 # minutes
delete_old_news = pyqtSignal(object)
start_recipe_fetch = pyqtSignal(object)
def __init__(self, parent):
QObject.__init__(self, parent)
self.internet_connection_failed = False
self._parent = parent
self.no_internet_msg = _('Cannot download news as no internet connection '
'is active')
self.no_internet_dialog = d = error_dialog(self._parent,
self.no_internet_msg, _('No internet connection'),
show_copy_button=False)
d.setModal(False)
self.recipe_model = RecipeModel()
self.lock = QRecursiveMutex()
self.download_queue = set()
self.news_menu = QMenu()
self.news_icon = QIcon.ic('news.png')
self.scheduler_action = QAction(QIcon.ic('scheduler.png'), _('Schedule news download'), self)
self.news_menu.addAction(self.scheduler_action)
self.scheduler_action.triggered[bool].connect(self.show_dialog)
self.cac = QAction(QIcon.ic('user_profile.png'), _('Add or edit a custom news source'), self)
self.cac.triggered[bool].connect(self.customize_feeds)
self.news_menu.addAction(self.cac)
self.news_menu.addSeparator()
self.all_action = self.news_menu.addAction(
QIcon.ic('download-metadata.png'),
_('Download all scheduled news sources'),
self.download_all_scheduled)
self.timer = QTimer(self)
self.timer.start(int(self.INTERVAL * 60 * 1000))
self.timer.timeout.connect(self.check)
self.oldest = gconf['oldest_news']
QTimer.singleShot(5 * 1000, self.oldest_check)
@property
def db(self):
from calibre.gui2.ui import get_gui
gui = get_gui()
with suppress(AttributeError):
ans = gui.current_db
if not ans.new_api.is_doing_rebuild_or_vacuum:
return ans
def oldest_check(self):
if self.oldest > 0:
delta = timedelta(days=self.oldest)
db = self.db
if db is None:
QTimer.singleShot(5 * 1000, self.oldest_check)
return
try:
ids = list(db.tags_older_than(_('News'),
delta, must_have_authors=['calibre']))
except:
# Happens if library is being switched
ids = []
if ids:
if ids:
self.delete_old_news.emit(ids)
QTimer.singleShot(60 * 60 * 1000, self.oldest_check)
def show_dialog(self, *args):
self.lock.lock()
try:
d = SchedulerDialog(self.recipe_model)
d.download.connect(self.download_clicked)
d.exec()
gconf['oldest_news'] = self.oldest = d.old_news.value()
d.break_cycles()
finally:
self.lock.unlock()
def customize_feeds(self, *args):
from calibre.gui2.dialogs.custom_recipes import CustomRecipes
d = CustomRecipes(self.recipe_model, self._parent)
try:
d.exec()
finally:
d.deleteLater()
def do_download(self, urn):
self.lock.lock()
try:
account_info = self.recipe_model.get_account_info(urn)
customize_info = self.recipe_model.get_customize_info(urn)
recipe = self.recipe_model.recipe_from_urn(urn)
un = pw = None
if account_info is not None:
un, pw = account_info
arg = {
'username': un,
'password': pw,
'add_title_tag':customize_info.add_title_tag,
'custom_tags':customize_info.custom_tags,
'title':recipe.get('title',''),
'urn':urn,
'keep_issues':str(customize_info.keep_issues),
'recipe_specific_options': customize_info.recipe_specific_options,
}
self.download_queue.add(urn)
self.start_recipe_fetch.emit(arg)
finally:
self.lock.unlock()
def recipe_downloaded(self, arg):
self.lock.lock()
try:
self.recipe_model.update_last_downloaded(arg['urn'])
self.download_queue.remove(arg['urn'])
finally:
self.lock.unlock()
def recipe_download_failed(self, arg):
self.lock.lock()
try:
self.recipe_model.update_last_downloaded(arg['urn'])
self.download_queue.remove(arg['urn'])
finally:
self.lock.unlock()
def download_clicked(self, urn):
if urn is not None:
return self.download(urn)
for urn in self.recipe_model.scheduled_urns():
if not self.download(urn):
break
def download_all_scheduled(self):
self.download_clicked(None)
def has_internet_connection(self):
if not internet_connected():
if not self.internet_connection_failed:
self.internet_connection_failed = True
if self._parent.is_minimized_to_tray:
self._parent.status_bar.show_message(self.no_internet_msg,
5000)
elif not self.no_internet_dialog.isVisible():
self.no_internet_dialog.show()
return False
self.internet_connection_failed = False
if self.no_internet_dialog.isVisible():
self.no_internet_dialog.hide()
return True
def download(self, urn):
self.lock.lock()
if not self.has_internet_connection():
return False
doit = urn not in self.download_queue
self.lock.unlock()
if doit:
self.do_download(urn)
return True
def check(self):
recipes = self.recipe_model.get_to_be_downloaded_recipes()
for urn in recipes:
if not self.download(urn):
# No internet connection, we will try again in a minute
break
if __name__ == '__main__':
from calibre.gui2 import Application
app = Application([])
d = SchedulerDialog(RecipeModel())
d.exec()
del app
| 29,527 | Python | .py | 685 | 33.112409 | 134 | 0.603548 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,022 | drm_error.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/drm_error.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from qt.core import QDialog
from calibre.gui2.dialogs.drm_error_ui import Ui_Dialog
from calibre.utils.localization import localize_website_link
class DRMErrorMessage(QDialog, Ui_Dialog):
def __init__(self, parent=None, title=None):
QDialog.__init__(self, parent)
self.setupUi(self)
msg = _('<p>This book is locked by <b>DRM</b>. To learn more about DRM'
' and why you cannot read or convert this book in calibre,'
' <a href="{0}">click here</a>.'
' </p>').format(localize_website_link('https://manual.calibre-ebook.com/drm.html'))
if title is not None:
msg = '<h2>%s</h2>%s'%(title, msg)
self.msg.setText(msg)
self.resize(self.sizeHint())
if __name__ == '__main__':
from calibre.gui2 import Application
app = Application([])
d = DRMErrorMessage(title='testing title')
d.exec()
del d
| 1,070 | Python | .py | 25 | 36.12 | 99 | 0.631884 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,023 | progress.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/progress.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, QFont, QFontMetrics, QHBoxLayout, QIcon, QLabel, QProgressBar, QSize, Qt, QVBoxLayout, pyqtSignal
from calibre.gui2 import elided_text, question_dialog
from calibre.gui2.progress_indicator import ProgressIndicator
class ProgressDialog(QDialog):
canceled_signal = pyqtSignal()
def __init__(self, title, msg='\u00a0', min=0, max=99, parent=None, cancelable=True, icon=None, cancel_confirm_msg=''):
QDialog.__init__(self, parent)
self.cancel_confirm_msg = cancel_confirm_msg
if icon is None:
self.l = l = QVBoxLayout(self)
else:
self.h = h = QHBoxLayout(self)
self.icon = i = QLabel(self)
if not isinstance(icon, QIcon):
icon = QIcon.ic(icon)
i.setPixmap(icon.pixmap(64))
h.addWidget(i, alignment=Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignHCenter)
self.l = l = QVBoxLayout()
h.addLayout(l)
self.setWindowIcon(icon)
self.title_label = t = QLabel(title)
self.setWindowTitle(title)
t.setStyleSheet('QLabel { font-weight: bold }'), t.setAlignment(Qt.AlignmentFlag.AlignCenter), t.setTextFormat(Qt.TextFormat.PlainText)
l.addWidget(t)
self.bar = b = QProgressBar(self)
b.setMinimum(min), b.setMaximum(max), b.setValue(min)
l.addWidget(b)
self.message = m = QLabel(self)
fm = QFontMetrics(self.font())
m.setAlignment(Qt.AlignmentFlag.AlignCenter), m.setMinimumWidth(fm.averageCharWidth() * 80), m.setTextFormat(Qt.TextFormat.PlainText)
l.addWidget(m)
self.msg = msg
self.button_box = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Abort, self)
bb.rejected.connect(self._canceled)
l.addWidget(bb)
self.setWindowModality(Qt.WindowModality.ApplicationModal)
self.canceled = False
if not cancelable:
bb.setVisible(False)
self.cancelable = cancelable
self.resize(self.sizeHint())
def set_msg(self, msg=''):
self.msg = msg
def set_value(self, val):
self.value = val
@property
def value(self):
return self.bar.value()
@value.setter
def value(self, val):
self.bar.setValue(val)
def set_min(self, min):
self.min = min
def set_max(self, max):
self.max = max
@property
def max(self):
return self.bar.maximum()
@max.setter
def max(self, val):
self.bar.setMaximum(val)
@property
def min(self):
return self.bar.minimum()
@min.setter
def min(self, val):
self.bar.setMinimum(val)
@property
def title(self):
return self.title_label.text()
@title.setter
def title(self, val):
self.title_label.setText(str(val or ''))
@property
def msg(self):
return self.message.text()
@msg.setter
def msg(self, val):
val = str(val or '')
self.message.setText(elided_text(val, self.font(), self.message.minimumWidth()-10))
def _canceled(self, *args):
if self.cancel_confirm_msg:
if not question_dialog(
self, _('Are you sure?'), self.cancel_confirm_msg, override_icon='dialog_warning.png',
yes_text=_('Yes, abort'), no_text=_('No, keep copying')
):
return
self.canceled = True
self.button_box.setDisabled(True)
self.title = _('Aborting...')
self.canceled_signal.emit()
def reject(self):
if not self.cancelable:
return
QDialog.reject(self)
def keyPressEvent(self, ev):
if ev.key() == Qt.Key.Key_Escape:
if self.cancelable:
self._canceled()
else:
QDialog.keyPressEvent(self, ev)
class BlockingBusy(QDialog):
def __init__(self, msg, parent=None, window_title=_('Working')):
QDialog.__init__(self, parent)
self._layout = QVBoxLayout()
self.setLayout(self._layout)
self.msg = QLabel(msg)
# self.msg.setWordWrap(True)
self.font = QFont()
self.font.setPointSize(self.font.pointSize() + 8)
self.msg.setFont(self.font)
self.pi = ProgressIndicator(self)
self.pi.setDisplaySize(QSize(100, 100))
self._layout.addWidget(self.pi, 0, Qt.AlignmentFlag.AlignHCenter)
self._layout.addSpacing(15)
self._layout.addWidget(self.msg, 0, Qt.AlignmentFlag.AlignHCenter)
self.start()
self.setWindowTitle(window_title)
self.resize(self.sizeHint())
def start(self):
self.pi.startAnimation()
def stop(self):
self.pi.stopAnimation()
def accept(self):
self.stop()
return QDialog.accept(self)
def reject(self):
pass # Cannot cancel this dialog
if __name__ == '__main__':
from qt.core import QTimer
app = QApplication([])
d = ProgressDialog('A title', 'A message', icon='lt.png')
d.show(), d.canceled_signal.connect(app.quit)
QTimer.singleShot(1000, lambda : (setattr(d, 'value', 10), setattr(d, 'msg', ('A message ' * 100))))
app.exec()
| 5,393 | Python | .py | 139 | 30.510791 | 158 | 0.624592 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,024 | catalog.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/catalog.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import importlib
import os
import sys
import weakref
from qt.core import QDialog, QDialogButtonBox, QScrollArea, QSize
from calibre.customize import PluginInstallationType
from calibre.customize.ui import catalog_plugins, config
from calibre.gui2 import dynamic, info_dialog
from calibre.gui2.dialogs.catalog_ui import Ui_Dialog
class Catalog(QDialog, Ui_Dialog):
''' Catalog Dialog builder'''
def __init__(self, parent, dbspec, ids, db):
import re
from PyQt6.uic import compileUi
from calibre import prints as info
QDialog.__init__(self, parent)
self.setupUi(self)
self.dbspec, self.ids = dbspec, ids
# Display the number of books we've been passed
self.count.setText(str(self.count.text()).format(len(ids)))
# Display the last-used title
self.title.setText(dynamic.get('catalog_last_used_title',
_('My books')))
self.fmts, self.widgets = [], []
for plugin in catalog_plugins():
if plugin.name in config['disabled_plugins']:
continue
name = plugin.name.lower().replace(' ', '_')
if getattr(plugin, 'installation_type', None) is PluginInstallationType.BUILTIN:
try:
catalog_widget = importlib.import_module('calibre.gui2.catalog.'+name)
pw = catalog_widget.PluginWidget()
pw.parent_ref = weakref.ref(self)
pw.initialize(name, db)
pw.ICON = 'forward.png'
self.widgets.append(pw)
[self.fmts.append([file_type.upper(), pw.sync_enabled,pw]) for file_type in plugin.file_types]
except ImportError:
info("ImportError initializing %s" % name)
continue
else:
# Load dynamic tab
form = os.path.join(plugin.resources_path,'%s.ui' % name)
klass = os.path.join(plugin.resources_path,'%s.py' % name)
compiled_form = os.path.join(plugin.resources_path,'%s_ui.py' % name)
if os.path.exists(form) and os.path.exists(klass):
# info("Adding widget for user-installed Catalog plugin %s" % plugin.name)
# Compile the .ui form provided in plugin.zip
if not os.path.exists(compiled_form):
from polyglot.io import PolyglotStringIO
# info('\tCompiling form', form)
buf = PolyglotStringIO()
compileUi(form, buf)
dat = buf.getvalue()
dat = re.compile(r'QtGui.QApplication.translate\(.+?,\s+"(.+?)(?<!\\)",.+?\)',
re.DOTALL).sub(r'_("\1")', dat)
open(compiled_form, 'wb').write(dat.encode('utf-8'))
# Import the dynamic PluginWidget() from .py file provided in plugin.zip
try:
sys.path.insert(0, plugin.resources_path)
catalog_widget = importlib.import_module(name)
pw = catalog_widget.PluginWidget()
pw.initialize(name)
pw.ICON = 'forward.png'
self.widgets.append(pw)
[self.fmts.append([file_type.upper(), pw.sync_enabled,pw]) for file_type in plugin.file_types]
except ImportError:
info("ImportError with %s" % name)
continue
finally:
sys.path.remove(plugin.resources_path)
else:
info("No dynamic tab resources found for %s" % name)
self.widgets = sorted(self.widgets, key=lambda x: x.TITLE)
# Generate a sorted list of installed catalog formats/sync_enabled pairs
fmts = sorted(x[0] for x in self.fmts)
self.sync_enabled_formats = []
for fmt in self.fmts:
if fmt[1]:
self.sync_enabled_formats.append(fmt[0])
# Callbacks when format, title changes
self.format.currentIndexChanged.connect(self.format_changed)
self.format.currentIndexChanged.connect(self.settings_changed)
self.title.editingFinished.connect(self.settings_changed)
# Add the installed catalog format list to the format QComboBox
self.format.blockSignals(True)
self.format.addItems(fmts)
pref = dynamic.get('catalog_preferred_format', 'CSV')
idx = self.format.findText(pref)
if idx > -1:
self.format.setCurrentIndex(idx)
self.format.blockSignals(False)
if self.sync.isEnabled():
self.sync.setChecked(dynamic.get('catalog_sync_to_device', True))
self.add_to_library.setChecked(dynamic.get('catalog_add_to_library', True))
self.format.currentIndexChanged.connect(self.show_plugin_tab)
self.buttonBox.button(QDialogButtonBox.StandardButton.Apply).clicked.connect(self.apply)
self.buttonBox.button(QDialogButtonBox.StandardButton.Help).clicked.connect(self.help)
self.show_plugin_tab(None)
self.restore_geometry(dynamic, 'catalog_window_geom')
g = self.screen().availableSize()
self.setMaximumWidth(g.width() - 50)
self.setMaximumHeight(g.height() - 50)
def sizeHint(self):
geom = self.screen().availableSize()
nh, nw = max(300, geom.height()-50), max(400, geom.width()-70)
return QSize(nw, nh)
@property
def options_widget(self):
ans = self.tabs.widget(1)
if isinstance(ans, QScrollArea):
ans = ans.widget()
return ans
def show_plugin_tab(self, idx):
cf = str(self.format.currentText()).lower()
while self.tabs.count() > 1:
self.tabs.removeTab(1)
for pw in self.widgets:
if cf in pw.formats:
if getattr(pw, 'handles_scrolling', False):
self.tabs.addTab(pw, pw.TITLE)
else:
self.sw__mem = s = QScrollArea(self)
s.setWidget(pw), s.setWidgetResizable(True)
self.tabs.addTab(s, pw.TITLE)
break
if hasattr(self.options_widget, 'show_help'):
self.buttonBox.button(QDialogButtonBox.StandardButton.Help).setVisible(True)
else:
self.buttonBox.button(QDialogButtonBox.StandardButton.Help).setVisible(False)
def format_changed(self, idx):
cf = str(self.format.currentText())
if cf in self.sync_enabled_formats:
self.sync.setEnabled(True)
else:
self.sync.setDisabled(True)
self.sync.setChecked(False)
def settings_changed(self):
'''
When title/format change, invalidate Preset in E-book options tab
'''
cf = str(self.format.currentText()).lower()
if cf in ('azw3', 'epub', 'mobi') and hasattr(self.options_widget, 'settings_changed'):
self.options_widget.settings_changed("title/format")
@property
def fmt_options(self):
ans = {}
if self.tabs.count() > 1:
w = self.options_widget
ans = w.options()
return ans
def save_catalog_settings(self):
self.catalog_format = str(self.format.currentText())
dynamic.set('catalog_preferred_format', self.catalog_format)
self.catalog_title = str(self.title.text())
dynamic.set('catalog_last_used_title', self.catalog_title)
self.catalog_sync = bool(self.sync.isChecked())
dynamic.set('catalog_sync_to_device', self.catalog_sync)
self.save_geometry(dynamic, 'catalog_window_geom')
dynamic.set('catalog_add_to_library', self.add_to_library.isChecked())
def apply(self, *args):
# Store current values without building catalog
self.save_catalog_settings()
if self.tabs.count() > 1:
self.options_widget.options()
def accept(self):
self.save_catalog_settings()
return QDialog.accept(self)
def help(self):
'''
To add help functionality for a specific format:
In gui2.catalog.catalog_<format>.py, add the following:
from calibre.gui2 import open_url
from qt.core import QUrl
In the PluginWidget() class, add this method:
def show_help(self):
url = 'file:///' + P('catalog/help_<format>.html')
open_url(QUrl(url))
Create the help file at resources/catalog/help_<format>.html
'''
if self.tabs.count() > 1 and hasattr(self.options_widget,'show_help'):
try:
self.options_widget.show_help()
except:
info_dialog(self, _('No help available'),
_('No help available for this output format.'),
show_copy_button=False,
show=True)
def reject(self):
self.save_geometry(dynamic, 'catalog_window_geom')
QDialog.reject(self)
| 9,365 | Python | .py | 195 | 35.430769 | 118 | 0.587662 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,025 | book_info.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/book_info.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2008, Kovid Goyal <kovid at kovidgoyal.net>
import textwrap
from enum import IntEnum
from qt.core import (
QAction,
QApplication,
QBrush,
QCheckBox,
QDialog,
QDialogButtonBox,
QGridLayout,
QHBoxLayout,
QIcon,
QKeySequence,
QLabel,
QListView,
QModelIndex,
QPalette,
QPixmap,
QPushButton,
QShortcut,
QSize,
QSplitter,
Qt,
QTimer,
QToolButton,
QVBoxLayout,
QWidget,
pyqtSignal,
)
from calibre import fit_image
from calibre.db.constants import RESOURCE_URL_SCHEME
from calibre.gui2 import BOOK_DETAILS_DISPLAY_DEBOUNCE_DELAY, NO_URL_FORMATTING, gprefs
from calibre.gui2.book_details import DropMixin, create_open_cover_with_menu, details_context_menu_event, render_html, resolved_css, set_html
from calibre.gui2.ui import get_gui
from calibre.gui2.widgets import CoverView
from calibre.gui2.widgets2 import Dialog, HTMLDisplay
from calibre.startup import connect_lambda
class Cover(CoverView):
open_with_requested = pyqtSignal(object)
choose_open_with_requested = pyqtSignal()
copy_to_clipboard_requested = pyqtSignal()
def __init__(self, parent, show_size=False):
CoverView.__init__(self, parent, show_size=show_size)
def copy_to_clipboard(self):
self.copy_to_clipboard_requested.emit()
def build_context_menu(self):
ans = CoverView.build_context_menu(self)
create_open_cover_with_menu(self, ans)
return ans
def open_with(self, entry):
self.open_with_requested.emit(entry)
def choose_open_with(self):
self.choose_open_with_requested.emit()
def mouseDoubleClickEvent(self, ev):
ev.accept()
self.open_with_requested.emit(None)
def set_marked(self, marked):
if marked:
marked_brush = QBrush(Qt.GlobalColor.darkGray if QApplication.instance().is_dark_theme else Qt.GlobalColor.lightGray)
self.set_background(marked_brush)
else:
self.set_background()
class Configure(Dialog):
def __init__(self, db, parent=None):
self.db = db
Dialog.__init__(self, _('Configure the Book details window'), 'book-details-popup-conf', parent)
def setup_ui(self):
from calibre.gui2.preferences.look_feel import DisplayedFields, move_field_down, move_field_up
self.l = QVBoxLayout(self)
self.field_display_order = fdo = QListView(self)
self.model = DisplayedFields(self.db, fdo, pref_name='popup_book_display_fields')
self.model.initialize()
fdo.setModel(self.model)
fdo.setAlternatingRowColors(True)
del self.db
self.l.addWidget(QLabel(_('Select displayed metadata')))
h = QHBoxLayout()
h.addWidget(fdo)
v = QVBoxLayout()
self.mub = b = QToolButton(self)
connect_lambda(b.clicked, self, lambda self: move_field_up(fdo, self.model))
b.setIcon(QIcon.ic('arrow-up.png'))
b.setToolTip(_('Move the selected field up'))
v.addWidget(b), v.addStretch(10)
self.mud = b = QToolButton(self)
b.setIcon(QIcon.ic('arrow-down.png'))
b.setToolTip(_('Move the selected field down'))
connect_lambda(b.clicked, self, lambda self: move_field_down(fdo, self.model))
v.addWidget(b)
h.addLayout(v)
self.l.addLayout(h)
txt = QLabel('<p>' + _(
'Note: <b>comments</b>-like columns will always be displayed at '
'the end unless their "Heading position" is "Show heading to the side"')+'</p>')
txt.setWordWrap(True)
self.l.addWidget(txt)
b = self.bb.addButton(_('Restore &defaults'), QDialogButtonBox.ButtonRole.ActionRole)
b.clicked.connect(self.restore_defaults)
b = self.bb.addButton(_('Select &all'), QDialogButtonBox.ButtonRole.ActionRole)
b.clicked.connect(self.select_all)
b = self.bb.addButton(_('Select &none'), QDialogButtonBox.ButtonRole.ActionRole)
b.clicked.connect(self.select_none)
self.l.addWidget(self.bb)
self.setMinimumHeight(500)
def select_all(self):
self.model.toggle_all(True)
def select_none(self):
self.model.toggle_all(False)
def restore_defaults(self):
self.model.initialize(use_defaults=True)
def accept(self):
self.model.commit()
return Dialog.accept(self)
class Details(HTMLDisplay):
notes_resource_scheme = RESOURCE_URL_SCHEME
def __init__(self, book_info, parent=None, allow_context_menu=True, is_locked=False):
HTMLDisplay.__init__(self, parent)
self.book_info = book_info
self.edit_metadata = getattr(parent, 'edit_metadata', None)
self.setDefaultStyleSheet(resolved_css())
self.allow_context_menu = allow_context_menu
self.is_locked = is_locked
def get_base_qurl(self):
return getattr(self.book_info, 'base_url_for_current_book', None)
def sizeHint(self):
return QSize(350, 350)
def contextMenuEvent(self, ev):
if self.allow_context_menu:
details_context_menu_event(self, ev, self.book_info,
edit_metadata=None if self.is_locked else self.edit_metadata)
class DialogNumbers(IntEnum):
Slaved = 0
Locked = 1
DetailsLink = 2
class BookInfo(QDialog, DropMixin):
closed = pyqtSignal(object)
open_cover_with = pyqtSignal(object, object)
def __init__(self, parent, view, row, link_delegate, dialog_number=None,
library_id=None, library_path=None, book_id=None):
QDialog.__init__(self, parent)
DropMixin.__init__(self)
self.files_dropped.connect(self.on_files_dropped)
self.remote_file_dropped.connect(self.on_remote_file_dropped)
self.dialog_number = dialog_number
self.library_id = library_id
self.marked = None
self.gui = parent
self.splitter = QSplitter(self)
self._l = l = QVBoxLayout(self)
self.setLayout(l)
l.addWidget(self.splitter)
self.setAcceptDrops(True)
self.cover = Cover(self, show_size=gprefs['bd_overlay_cover_size'])
self.cover.copy_to_clipboard_requested.connect(self.copy_cover_to_clipboard)
self.cover.resizeEvent = self.cover_view_resized
self.cover.cover_changed.connect(self.cover_changed)
self.cover.open_with_requested.connect(self.open_with)
self.cover.choose_open_with_requested.connect(self.choose_open_with)
self.cover_pixmap = None
self.cover.sizeHint = self.details_size_hint
self.splitter.addWidget(self.cover)
self.details = Details(parent.book_details.book_info, self,
allow_context_menu=library_path is None,
is_locked = dialog_number == DialogNumbers.Locked)
self.details.anchor_clicked.connect(self.on_link_clicked)
self.link_delegate = link_delegate
self.details.setAttribute(Qt.WidgetAttribute.WA_OpaquePaintEvent, False)
palette = self.details.palette()
self.details.setAcceptDrops(False)
palette.setBrush(QPalette.ColorRole.Base, Qt.GlobalColor.transparent)
self.details.setPalette(palette)
self.c = QWidget(self)
self.c.l = l2 = QGridLayout(self.c)
l2.setContentsMargins(0, 0, 0, 0)
self.c.setLayout(l2)
l2.addWidget(self.details, 0, 0, 1, -1)
self.splitter.addWidget(self.c)
self.fit_cover = QCheckBox(_('Fit &cover within view'), self)
self.fit_cover.setChecked(gprefs.get('book_info_dialog_fit_cover', True))
self.hl = hl = QHBoxLayout()
hl.setContentsMargins(0, 0, 0, 0)
l2.addLayout(hl, l2.rowCount(), 0, 1, -1)
hl.addWidget(self.fit_cover), hl.addStretch()
if self.dialog_number == DialogNumbers.Slaved:
self.previous_button = QPushButton(QIcon.ic('previous.png'), _('&Previous'), self)
self.previous_button.clicked.connect(self.previous)
l2.addWidget(self.previous_button, l2.rowCount(), 0)
self.next_button = QPushButton(QIcon.ic('next.png'), _('&Next'), self)
self.next_button.clicked.connect(self.next)
l2.addWidget(self.next_button, l2.rowCount() - 1, 1)
self.ns = QShortcut(QKeySequence('Alt+Right'), self)
self.ns.activated.connect(self.next)
self.ps = QShortcut(QKeySequence('Alt+Left'), self)
self.ps.activated.connect(self.previous)
self.next_button.setToolTip(_('Next [%s]')%
str(self.ns.key().toString(QKeySequence.SequenceFormat.NativeText)))
self.previous_button.setToolTip(_('Previous [%s]')%
str(self.ps.key().toString(QKeySequence.SequenceFormat.NativeText)))
self.path_to_book = None
self.current_row = None
self.slave_connected = False
self.slave_debounce_timer = t = QTimer(self)
t.setInterval(BOOK_DETAILS_DISPLAY_DEBOUNCE_DELAY)
t.setSingleShot(True)
t.timeout.connect(self._debounce_refresh)
if library_path is not None:
self.view = None
db = get_gui().library_broker.get_library(library_path)
dbn = db.new_api
if not dbn.has_id(book_id):
raise ValueError(_("Book {} doesn't exist").format(book_id))
mi = dbn.get_metadata(book_id, get_cover=False)
mi.cover_data = [None, dbn.cover(book_id, as_image=True)]
mi.path = None
mi.format_files = dict()
mi.formats = list()
mi.marked = ''
mi.field_metadata = db.field_metadata
mi.external_library_path = library_path
self.refresh(row, mi)
else:
self.view = view
if dialog_number == DialogNumbers.Slaved:
self.slave_connected = True
self.view.model().new_bookdisplay_data.connect(self.slave)
if book_id:
db = get_gui().current_db
dbn = db.new_api
mi = dbn.get_metadata(book_id, get_cover=False)
mi.cover_data = [None, dbn.cover(book_id, as_image=True)]
mi.path = dbn._field_for('path', book_id)
mi.format_files = dbn.format_files(book_id)
mi.marked = db.data.get_marked(book_id)
mi.field_metadata = db.field_metadata
self.refresh(row, mi)
else:
self.refresh(row)
ema = get_gui().iactions['Edit Metadata'].menuless_qaction
a = self.ema = QAction('edit metadata', self)
a.setShortcut(ema.shortcut())
self.addAction(a)
a.triggered.connect(self.edit_metadata)
vb = get_gui().iactions['View'].menuless_qaction
a = self.vba = QAction('view book', self)
a.setShortcut(vb.shortcut())
a.triggered.connect(self.view_book)
self.addAction(a)
self.clabel = QLabel('<div style="text-align: right"><a href="calibre:conf" title="{}" style="text-decoration: none">{}</a>'.format(
_('Configure this view'), _('Configure')))
self.clabel.linkActivated.connect(self.configure)
hl.addWidget(self.clabel)
self.fit_cover.stateChanged.connect(self.toggle_cover_fit)
self.restore_geometry(gprefs, self.geometry_string('book_info_dialog_geometry'))
try:
self.splitter.restoreState(gprefs.get(self.geometry_string('book_info_dialog_splitter_state')))
except Exception:
pass
def on_files_dropped(self, event, paths):
gui = get_gui()
gui.iactions['Add Books'].files_dropped_on_book(event, paths)
def on_remote_file_dropped(self, event, url):
gui = get_gui()
gui.iactions['Add Books'].remote_file_dropped_on_book(event, url)
def geometry_string(self, txt):
if self.dialog_number is None or self.dialog_number == DialogNumbers.Slaved:
return txt
return txt + '_' + str(int(self.dialog_number))
def sizeHint(self):
try:
geom = self.screen().availableSize()
screen_height = geom.height() - 100
screen_width = geom.width() - 100
return QSize(max(int(screen_width/2), 700), screen_height)
except Exception:
return QSize(800, 600)
def view_book(self):
if self.current_row is not None:
book_id = self.view.model().id(self.current_row)
get_gui().iactions['View']._view_calibre_books((book_id,))
def edit_metadata(self):
if self.current_row is not None:
book_id = self.view.model().id(self.current_row)
em = get_gui().iactions['Edit Metadata']
with em.different_parent(self):
em.edit_metadata_for([self.current_row], [book_id], bulk=False)
def configure(self):
d = Configure(get_gui().current_db, self)
if d.exec() == QDialog.DialogCode.Accepted:
if self.current_row is not None:
mi = self.view.model().get_book_display_info(self.current_row)
if mi is not None:
self.refresh(self.current_row, mi=mi)
def on_link_clicked(self, qurl):
link = str(qurl.toString(NO_URL_FORMATTING))
self.link_delegate(link, self)
def done(self, r):
self.save_geometry(gprefs, self.geometry_string('book_info_dialog_geometry'))
gprefs[self.geometry_string('book_info_dialog_splitter_state')] = bytearray(self.splitter.saveState())
ret = QDialog.done(self, r)
if self.slave_connected:
self.view.model().new_bookdisplay_data.disconnect(self.slave)
self.slave_debounce_timer.stop() # OK if it isn't running
self.view = self.link_delegate = self.gui = None
self.closed.emit(self)
return ret
def cover_changed(self, data):
if self.current_row is not None:
id_ = self.view.model().id(self.current_row)
self.view.model().db.set_cover(id_, data)
self.gui.refresh_cover_browser()
ci = self.view.currentIndex()
if ci.isValid():
self.view.model().current_changed(ci, ci)
def details_size_hint(self):
return QSize(350, 550)
def toggle_cover_fit(self, state):
gprefs.set('book_info_dialog_fit_cover', self.fit_cover.isChecked())
self.resize_cover()
def cover_view_resized(self, event):
QTimer.singleShot(1, self.resize_cover)
def slave(self, mi):
self._mi_for_debounce = mi
self.slave_debounce_timer.start() # start() will automatically reset the timer if it was already running
def _debounce_refresh(self):
mi, self._mi_for_debounce = self._mi_for_debounce, None
self.refresh(mi.row_number, mi)
def move(self, delta=1):
idx = self.view.currentIndex()
if idx.isValid():
m = self.view.model()
ni = m.index(idx.row() + delta, idx.column())
if ni.isValid():
if self.view.isVisible():
self.view.scrollTo(ni)
self.view.setCurrentIndex(ni)
def next(self):
self.move()
def previous(self):
self.move(-1)
def resize_cover(self):
if self.cover_pixmap is None:
self.cover.set_marked(self.marked)
return
pixmap = self.cover_pixmap
if self.fit_cover.isChecked() and not pixmap.isNull():
scaled, new_width, new_height = fit_image(pixmap.width(),
pixmap.height(), self.cover.size().width()-10,
self.cover.size().height()-10)
if scaled:
try:
dpr = self.devicePixelRatioF()
except AttributeError:
dpr = self.devicePixelRatio()
pixmap = pixmap.scaled(int(dpr * new_width), int(dpr * new_height),
Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
pixmap.setDevicePixelRatio(dpr)
self.cover.set_pixmap(pixmap)
self.cover.set_marked(self.marked)
self.update_cover_tooltip()
def copy_cover_to_clipboard(self):
if self.cover_pixmap is not None:
QApplication.instance().clipboard().setPixmap(self.cover_pixmap)
def update_cover_tooltip(self):
tt = ''
if self.marked:
tt += _('This book is marked') if self.marked in {True, 'true'} else _(
'This book is marked as: %s') % self.marked
tt += '\n\n'
if self.path_to_book is not None:
tt += textwrap.fill(_('Path: {}').format(self.path_to_book))
tt += '\n\n'
if self.cover_pixmap is not None:
sz = self.cover_pixmap.size()
tt += _('Cover size: %(width)d x %(height)d pixels')%dict(width=sz.width(), height=sz.height())
self.cover.setToolTip(tt)
self.cover.pixmap_size = sz.width(), sz.height()
def refresh(self, row, mi=None):
if isinstance(row, QModelIndex):
row = row.row()
if row == self.current_row and mi is None:
return
mi = self.view.model().get_book_display_info(row) if mi is None else mi
if mi is None:
# Indicates books was deleted from library, or row numbers have
# changed
return
if self.dialog_number == DialogNumbers.Slaved:
self.previous_button.setEnabled(False if row == 0 else True)
self.next_button.setEnabled(False if row == self.view.model().rowCount(QModelIndex())-1 else True)
self.setWindowTitle(mi.title + ' ' + _('(the current book)'))
elif self.library_id is not None:
self.setWindowTitle(mi.title + ' ' + _('(from {})').format(self.library_id))
else:
self.setWindowTitle(mi.title + ' ' + _('(will not change)'))
self.current_row = row
self.cover_pixmap = QPixmap.fromImage(mi.cover_data[1])
self.path_to_book = getattr(mi, 'path', None)
try:
dpr = self.devicePixelRatioF()
except AttributeError:
dpr = self.devicePixelRatio()
self.cover_pixmap.setDevicePixelRatio(dpr)
self.marked = mi.marked
self.resize_cover()
html = render_html(mi, True, self, pref_name='popup_book_display_fields')[0]
set_html(mi, html, self.details)
self.update_cover_tooltip()
def open_with(self, entry):
id_ = self.view.model().id(self.current_row)
self.open_cover_with.emit(id_, entry)
def choose_open_with(self):
from calibre.gui2.open_with import choose_program
entry = choose_program('cover_image', self)
if entry is not None:
self.open_with(entry)
if __name__ == '__main__':
from calibre.gui2 import Application
from calibre.library import db
app = Application([])
app.current_db = db()
get_gui.ans = app
d = Configure(app.current_db)
d.exec()
del d
del app
| 19,313 | Python | .py | 427 | 35.477752 | 144 | 0.622535 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,026 | add_from_isbn.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/add_from_isbn.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os
from qt.core import QApplication, QCheckBox, QDialog, QDialogButtonBox, QHBoxLayout, QIcon, QLabel, QLineEdit, QPlainTextEdit, QPushButton, Qt, QVBoxLayout
from calibre.constants import iswindows
from calibre.ebooks.metadata import check_isbn
from calibre.gui2 import error_dialog, gprefs, question_dialog
class AddFromISBN(QDialog):
def __init__(self, parent=None):
QDialog.__init__(self, parent)
self.setup_ui()
path = 'C:\\Users\\kovid\\e-books\\some_book.epub' if iswindows else \
'/Users/kovid/e-books/some_book.epub'
self.label.setText(str(self.label.text())%path)
self.isbns = []
self.books = []
self.set_tags = []
def setup_ui(self):
self.resize(678, 430)
self.setWindowTitle(_("Add books by ISBN"))
self.setWindowIcon(QIcon.ic('add_book.png'))
self.l = l = QVBoxLayout(self)
self.h = h = QHBoxLayout()
l.addLayout(h)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel, self)
bb.button(QDialogButtonBox.StandardButton.Ok).setText(_('&OK'))
l.addWidget(bb), bb.accepted.connect(self.accept), bb.rejected.connect(self.reject)
self.ll = l = QVBoxLayout()
h.addLayout(l)
self.isbn_box = i = QPlainTextEdit(self)
i.setFocus(Qt.FocusReason.OtherFocusReason)
l.addWidget(i)
self.paste_button = b = QPushButton(_("&Paste from clipboard"), self)
l.addWidget(b), b.clicked.connect(self.paste)
self.lll = l = QVBoxLayout()
h.addLayout(l)
self.label = la = QLabel(_(
"<p>Enter a list of ISBNs in the box to the left, one per line. calibre will automatically"
" create entries for books based on the ISBN and download metadata and covers for them.</p>\n"
"<p>Any invalid ISBNs in the list will be ignored.</p>\n"
"<p>You can also specify a file that will be added with each ISBN. To do this enter the full"
" path to the file after a <code>>></code>. For example:</p>\n"
"<p><code>9788842915232 >> %s</code></p>"
"<p>To use identifiers other than ISBN use key:value syntax, For example:</p>\n"
"<p><code>amazon:B001JK9C72</code></p>"
), self)
l.addWidget(la), la.setWordWrap(True)
l.addSpacing(20)
self.la2 = la = QLabel(_("&Tags to set on created book entries:"), self)
l.addWidget(la)
self.add_tags = le = QLineEdit(self)
le.setText(', '.join(gprefs.get('add from ISBN tags', [])))
la.setBuddy(le)
l.addWidget(le)
self._check_for_existing = ce = QCheckBox(_('Check for books with the same ISBN already in library'), self)
ce.setChecked(gprefs.get('add from ISBN dup check', False))
l.addWidget(ce)
l.addStretch(10)
def paste(self, *args):
app = QApplication.instance()
c = app.clipboard()
txt = str(c.text()).strip()
if txt:
old = str(self.isbn_box.toPlainText()).strip()
new = old + '\n' + txt
self.isbn_box.setPlainText(new)
@property
def check_for_existing(self):
return self._check_for_existing.isChecked()
def accept(self, *args):
tags = str(self.add_tags.text()).strip().split(',')
tags = list(filter(None, [x.strip() for x in tags]))
gprefs['add from ISBN tags'] = tags
gprefs['add from ISBN dup check'] = self.check_for_existing
self.set_tags = tags
bad = set()
for line in str(self.isbn_box.toPlainText()).strip().splitlines():
line = line.strip()
if not line:
continue
parts = line.split('>>')
if len(parts) > 2:
parts = [parts[0] + '>>'.join(parts[1:])]
parts = [x.strip() for x in parts]
if not parts[0]:
continue
if ':' in parts[0]:
prefix, val = parts[0].partition(':')[::2]
else:
prefix, val = 'isbn', parts[0]
path = None
if len(parts) > 1 and parts[1] and os.access(parts[1], os.R_OK) and os.path.isfile(parts[1]):
path = parts[1]
if prefix == 'isbn':
isbn = check_isbn(parts[0])
if isbn is not None:
isbn = isbn.upper()
if isbn not in self.isbns:
self.isbns.append(isbn)
self.books.append({'isbn': isbn, 'path': path, '': 'isbn'})
else:
bad.add(parts[0])
else:
if prefix != 'path':
self.books.append({prefix: val, 'path': path, '':prefix})
if bad:
if self.books:
if not question_dialog(self, _('Some invalid ISBNs'),
_('Some of the ISBNs you entered were invalid. They will'
' be ignored. Click "Show details" to see which ones.'
' Do you want to proceed?'), det_msg='\n'.join(bad),
show_copy_button=True):
return
else:
return error_dialog(self, _('All invalid ISBNs'),
_('All the ISBNs you entered were invalid. No books'
' can be added.'), show=True)
QDialog.accept(self, *args)
| 5,679 | Python | .py | 120 | 35.816667 | 155 | 0.563154 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,027 | add_empty_book.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/add_empty_book.py | #!/usr/bin/env python
__copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net'
__docformat__ = 'restructuredtext en'
__license__ = 'GPL v3'
from qt.core import QApplication, QCheckBox, QComboBox, QDialog, QDialogButtonBox, QGridLayout, QIcon, QLabel, QLineEdit, QSpinBox, QToolButton
from calibre.ebooks.metadata import string_to_authors
from calibre.gui2 import gprefs
from calibre.gui2.complete2 import EditWithComplete
from calibre.utils.config import tweaks
class AddEmptyBookDialog(QDialog):
def __init__(self, parent, db, author, series=None, title=None, dup_title=None):
QDialog.__init__(self, parent)
self.db = db
self.setWindowTitle(_('How many empty books?'))
self._layout = QGridLayout(self)
self.setLayout(self._layout)
self.qty_label = QLabel(_('How many empty books should be added?'))
self._layout.addWidget(self.qty_label, 0, 0, 1, 2)
self.qty_spinbox = QSpinBox(self)
self.qty_spinbox.setRange(1, 10000)
self.qty_spinbox.setValue(1)
self._layout.addWidget(self.qty_spinbox, 1, 0, 1, 2)
self.author_label = QLabel(_('Set the author of the new books to:'))
self._layout.addWidget(self.author_label, 2, 0, 1, 2)
self.authors_combo = EditWithComplete(self)
self.authors_combo.setSizeAdjustPolicy(
QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
self.authors_combo.setEditable(True)
self._layout.addWidget(self.authors_combo, 3, 0, 1, 1)
self.initialize_authors(db, author)
self.clear_button = QToolButton(self)
self.clear_button.setIcon(QIcon.ic('trash.png'))
self.clear_button.setToolTip(_('Reset author to Unknown'))
self.clear_button.clicked.connect(self.reset_author)
self._layout.addWidget(self.clear_button, 3, 1, 1, 1)
self.series_label = QLabel(_('Set the series of the new books to:'))
self._layout.addWidget(self.series_label, 4, 0, 1, 2)
self.series_combo = EditWithComplete(self)
self.series_combo.setSizeAdjustPolicy(
QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
self.series_combo.setEditable(True)
self._layout.addWidget(self.series_combo, 5, 0, 1, 1)
self.initialize_series(db, series)
self.sclear_button = QToolButton(self)
self.sclear_button.setIcon(QIcon.ic('trash.png'))
self.sclear_button.setToolTip(_('Reset series'))
self.sclear_button.clicked.connect(self.reset_series)
self._layout.addWidget(self.sclear_button, 5, 1, 1, 1)
self.title_label = QLabel(_('Set the title of the new books to:'))
self._layout.addWidget(self.title_label, 6, 0, 1, 2)
self.title_edit = QLineEdit(self)
self.title_edit.setText(title or '')
self._layout.addWidget(self.title_edit, 7, 0, 1, 1)
self.tclear_button = QToolButton(self)
self.tclear_button.setIcon(QIcon.ic('trash.png'))
self.tclear_button.setToolTip(_('Reset title'))
self.tclear_button.clicked.connect(self.title_edit.clear)
self._layout.addWidget(self.tclear_button, 7, 1, 1, 1)
self.format_label = QLabel(_('Also create an empty e-book in format:'))
self._layout.addWidget(self.format_label, 8, 0, 1, 2)
c = self.format_value = QComboBox(self)
from calibre.ebooks.oeb.polish.create import valid_empty_formats
possible_formats = [''] + sorted(x.upper() for x in valid_empty_formats)
c.addItems(possible_formats)
c.setToolTip(_('Also create an empty book format file that you can subsequently edit'))
if gprefs.get('create_empty_epub_file', False):
# Migration of the check box
gprefs.set('create_empty_format_file', 'epub')
del gprefs['create_empty_epub_file']
use_format = gprefs.get('create_empty_format_file', '').upper()
try:
c.setCurrentIndex(possible_formats.index(use_format))
except Exception:
pass
self._layout.addWidget(c, 9, 0, 1, 1)
self.copy_formats = cf = QCheckBox(_('Also copy book &formats when duplicating a book'), self)
cf.setToolTip(_(
'Also copy all e-book files into the newly created duplicate'
' books.'))
cf.setChecked(gprefs.get('create_empty_copy_dup_formats', False))
self._layout.addWidget(cf, 10, 0, 1, -1)
button_box = self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
self._layout.addWidget(button_box, 11, 0, 1, -1)
if dup_title:
self.dup_button = b = button_box.addButton(_('&Duplicate current book'), QDialogButtonBox.ButtonRole.ActionRole)
b.clicked.connect(self.do_duplicate_book)
b.setIcon(QIcon.ic('edit-copy.png'))
b.setToolTip(_(
'Make the new empty book records exact duplicates\n'
'of the current book "%s", with all metadata identical'
) % dup_title)
self.resize(self.sizeHint())
self.duplicate_current_book = False
def do_duplicate_book(self):
self.duplicate_current_book = True
self.accept()
def accept(self):
self.save_settings()
return QDialog.accept(self)
def save_settings(self):
gprefs['create_empty_format_file'] = self.format_value.currentText().lower()
gprefs['create_empty_copy_dup_formats'] = self.copy_formats.isChecked()
def reject(self):
self.save_settings()
return QDialog.reject(self)
def reset_author(self, *args):
self.authors_combo.setEditText(_('Unknown'))
def reset_series(self):
self.series_combo.setEditText('')
def initialize_authors(self, db, author):
au = author
if not au:
au = _('Unknown')
self.authors_combo.show_initial_value(au.replace('|', ','))
self.authors_combo.set_separator('&')
self.authors_combo.set_space_before_sep(True)
self.authors_combo.set_add_separator(tweaks['authors_completer_append_separator'])
self.authors_combo.update_items_cache(db.all_author_names())
def initialize_series(self, db, series):
self.series_combo.show_initial_value(series or '')
self.series_combo.update_items_cache(db.all_series_names())
self.series_combo.set_separator(None)
@property
def qty_to_add(self):
return self.qty_spinbox.value()
@property
def selected_authors(self):
return string_to_authors(str(self.authors_combo.text()))
@property
def selected_series(self):
return str(self.series_combo.text())
@property
def selected_title(self):
return self.title_edit.text().strip()
if __name__ == '__main__':
from calibre.library import db
db = db()
app = QApplication([])
d = AddEmptyBookDialog(None, db, 'Test Author')
d.exec()
| 7,132 | Python | .py | 142 | 41.598592 | 143 | 0.659617 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,028 | palette.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/palette.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net>
import json
import textwrap
from contextlib import suppress
from qt.core import (
QCheckBox,
QComboBox,
QDialog,
QHBoxLayout,
QIcon,
QLabel,
QPalette,
QPushButton,
QScrollArea,
QSize,
QSizePolicy,
QTabWidget,
QVBoxLayout,
QWidget,
pyqtSignal,
)
from calibre.gui2 import Application, choose_files, choose_save_file, gprefs
from calibre.gui2.palette import default_dark_palette, default_light_palette, is_foreground_color, palette_colors, palette_from_dict
from calibre.gui2.widgets2 import ColorButton, Dialog
class Color(QWidget):
changed = pyqtSignal()
def __init__(self, key: str, desc: str, parent: 'PaletteColors', palette: QPalette, default_palette: QPalette, mode_name: str, group=''):
super().__init__(parent)
self.key = key
self.setting_key = (key + '-' + group) if group else key
self.mode_name = mode_name
self.default_palette = default_palette
self.color_key = QPalette.ColorGroup.Disabled if group == 'disabled' else QPalette.ColorGroup.Active, getattr(QPalette.ColorRole, key)
self.initial_color = palette.color(*self.color_key)
self.l = l = QHBoxLayout(self)
self.button = b = ColorButton(self.initial_color.name(), self)
b.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Preferred)
b.color_changed.connect(self.color_changed)
l.addWidget(b)
self.la = la = QLabel(desc)
la.setBuddy(b)
l.addWidget(la)
def restore_defaults(self):
self.button.color = self.default_palette.color(*self.color_key).name()
def apply_from_palette(self, p):
self.button.color = p.color(*self.color_key).name()
def color_changed(self):
self.changed.emit()
self.la.setStyleSheet('QLabel { font-style: italic }')
@property
def value(self):
ans = self.button.color
if ans != self.default_palette.color(*self.color_key):
return ans
@value.setter
def value(self, val):
if val is None:
self.restore_defaults()
else:
self.button.color = val
class PaletteColors(QWidget):
def __init__(self, palette: QPalette, default_palette: QPalette, mode_name: str, parent=None):
super().__init__(parent)
self.link_colors = {}
self.mode_name = mode_name
self.foreground_colors = {}
self.background_colors = {}
self.default_palette = default_palette
for key, desc in palette_colors().items():
if is_foreground_color(key):
self.foreground_colors[key] = desc
elif 'Link' in key:
self.link_colors[key] = desc
else:
self.background_colors[key] = desc
self.l = l = QVBoxLayout(self)
self.colors = []
def header(text):
ans = QLabel(text)
f = ans.font()
f.setBold(True)
ans.setFont(f)
return ans
def c(x, desc, group=''):
w = Color(x, desc, self, palette, default_palette, mode_name, group=group)
l.addWidget(w)
self.colors.append(w)
l.addWidget(header(_('Background colors')))
for x, desc in self.background_colors.items():
c(x, desc)
l.addWidget(header(_('Foreground (text) colors')))
for x, desc in self.foreground_colors.items():
c(x, desc)
l.addWidget(header(_('Foreground (text) colors when disabled')))
for x, desc in self.foreground_colors.items():
c(x, desc, group='disabled')
l.addWidget(header(_('Link colors')))
for x, desc in self.link_colors.items():
c(x, desc)
def apply_settings_from_palette(self, p):
for w in self.colors:
w.apply_from_palette(p)
@property
def value(self):
ans = {}
for w in self.colors:
v = w.value
if v is not None:
ans[w.setting_key] = w.value
return ans
@value.setter
def value(self, serialized):
for w in self.colors:
w.value = serialized.get(w.setting_key)
def restore_defaults(self):
for w in self.colors:
w.restore_defaults()
class PaletteWidget(QWidget):
def __init__(self, mode_name='light', parent=None):
super().__init__(parent)
self.mode_name = mode_name
self.mode_title = {'dark': _('dark'), 'light': _('light')}[mode_name]
self.l = l = QVBoxLayout(self)
self.la = la = QLabel(_('These colors will be used for the calibre interface when calibre is in "{}" mode.'
' You can adjust individual colors below by enabling the "Use a custom color scheme" setting.').format(self.mode_title))
l.addWidget(la)
la.setWordWrap(True)
h = QHBoxLayout()
self.use_custom = uc = QCheckBox(_('Use a &custom color scheme'))
uc.setChecked(bool(gprefs[f'{mode_name}_palette_name']))
uc.toggled.connect(self.use_custom_toggled)
self.import_system_button = b = QPushButton(_('Import &system colors'))
b.setToolTip(textwrap.fill(_('Set the custom colors to colors queried from the system.'
' Note that this will use colors from whatever the current system palette is, dark or light.')))
b.clicked.connect(self.import_system_colors)
h.addWidget(uc), h.addStretch(10), h.addWidget(b)
l.addLayout(h)
pdata = gprefs[f'{mode_name}_palettes'].get('__current__', {})
default_palette = palette = default_dark_palette() if mode_name == 'dark' else default_light_palette()
with suppress(Exception):
palette = palette_from_dict(pdata, default_palette)
self.sa = sa = QScrollArea(self)
l.addWidget(sa)
self.palette_colors = pc = PaletteColors(palette, default_palette, mode_name, self)
sa.setWidget(pc)
self.use_custom_toggled()
def import_system_colors(self):
import subprocess
from calibre.gui2.palette import unserialize_palette
from calibre.startup import get_debug_executable
raw = subprocess.check_output(get_debug_executable() + [
'--command', 'from qt.core import QApplication; from calibre.gui2.palette import *; app = QApplication([]);'
'import sys; sys.stdout.buffer.write(serialize_palette(app.palette()))'])
p = QPalette()
unserialize_palette(p, raw)
self.palette_colors.apply_settings_from_palette(p)
def sizeHint(self):
return QSize(800, 600)
def use_custom_toggled(self):
enabled = self.use_custom.isChecked()
for w in (self.palette_colors, self.import_system_button):
w.setEnabled(enabled)
def serialized_colors(self):
return self.palette_colors.value
def apply_settings(self):
val = self.palette_colors.value
v = gprefs[f'{self.mode_name}_palettes']
v['__current__'] = val
gprefs[f'{self.mode_name}_palettes'] = v
gprefs[f'{self.mode_name}_palette_name'] = '__current__' if self.use_custom.isChecked() else ''
def restore_defaults(self):
self.use_custom.setChecked(False)
self.palette_colors.restore_defaults()
def serialize(self):
return {'use_custom': self.use_custom.isChecked(), 'palette': self.palette_colors.value}
def unserialize(self, val):
self.use_custom.setChecked(bool(val['use_custom']))
self.palette_colors.value = val['palette']
class PaletteConfig(Dialog):
def __init__(self, parent=None):
super().__init__(_('Customize the colors used by calibre'), 'customize-palette', parent=parent)
def setup_ui(self):
self.l = l = QVBoxLayout(self)
app = Application.instance()
if not app.palette_manager.using_calibre_style:
self.wla = la = QLabel('<p>' + _('<b>WARNING:</b> You have configured calibre to use "System" user interface style.'
' The settings below will be ignored unless you switch back to using the "calibre" interface style.'))
la.setWordWrap(True)
l.addWidget(la)
h = QHBoxLayout()
self.la = la = QLabel(_('Color &palette'))
self.palette = p = QComboBox(self)
p.addItem(_('System default'), 'system')
p.addItem(_('Light'), 'light')
p.addItem(_('Dark'), 'dark')
idx = p.findData(gprefs['color_palette'])
p.setCurrentIndex(idx)
la.setBuddy(p)
h.addWidget(la), h.addWidget(p)
tt = textwrap.fill(_(
'The style of colors to use, either light or dark. By default, the system setting for light/dark is used.'
' This means that calibre will change from light to dark and vice versa as the system changes colors.'
))
la.setToolTip(tt), p.setToolTip(tt)
l.addLayout(h)
self.tabs = tabs = QTabWidget(self)
l.addWidget(tabs)
self.light_tab = lt = PaletteWidget(parent=self)
tabs.addTab(lt, _('&Light mode colors'))
self.dark_tab = dt = PaletteWidget('dark', parent=self)
tabs.addTab(dt, _('&Dark mode colors'))
h = QHBoxLayout()
self.rd = b = QPushButton(QIcon.ic('clear_left.png'), _('Restore &defaults'))
b.clicked.connect(self.restore_defaults)
h.addWidget(b)
self.ib = b = QPushButton(QIcon(), _('&Import'))
b.clicked.connect(self.import_colors)
b.setToolTip(_('Import previously exported color scheme from a file'))
h.addWidget(b)
self.ib = b = QPushButton(QIcon(), _('E&xport'))
b.clicked.connect(self.export_colors)
b.setToolTip(_('Export current colors as a file'))
h.addWidget(b)
h.addStretch(10), h.addWidget(self.bb)
l.addLayout(h)
def import_colors(self):
files = choose_files(self, 'import-calibre-palette', _('Choose file to import from'),
filters=[(_('calibre Palette'), ['calibre-palette'])], all_files=False, select_only_single_file=True)
if files:
with open(files[0], 'rb') as f:
data = json.loads(f.read())
self.dark_tab.unserialize(data['dark'])
self.light_tab.unserialize(data['light'])
def export_colors(self):
data = {'dark': self.dark_tab.serialize(), 'light': self.light_tab.serialize()}
dest = choose_save_file(self, 'export-calibre-palette', _('Choose file to export to'),
filters=[(_('calibre Palette'), ['calibre-palette'])], all_files=False, initial_filename='mycolors.calibre-palette')
if dest:
with open(dest, 'wb') as f:
f.write(json.dumps(data, indent=2, sort_keys=True).encode('utf-8'))
def apply_settings(self):
with gprefs:
gprefs['color_palette'] = str(self.palette.currentData())
self.light_tab.apply_settings()
self.dark_tab.apply_settings()
Application.instance().palette_manager.refresh_palette()
def restore_defaults(self):
self.light_tab.restore_defaults()
self.dark_tab.restore_defaults()
if __name__ == '__main__':
app = Application([])
d = PaletteConfig()
if d.exec() == QDialog.DialogCode.Accepted:
d.apply_settings()
del d
del app
| 11,579 | Python | .py | 257 | 35.906615 | 152 | 0.617801 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,029 | device_category_editor.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/device_category_editor.py | __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
from qt.core import QDialog, QListWidgetItem, Qt
from calibre.gui2 import error_dialog, question_dialog
from calibre.gui2.dialogs.device_category_editor_ui import Ui_DeviceCategoryEditor
class ListWidgetItem(QListWidgetItem):
def __init__(self, txt):
QListWidgetItem.__init__(self, txt)
self.initial_value = txt
self.current_value = txt
self.previous_value = txt
def data(self, role):
if role == Qt.ItemDataRole.DisplayRole:
if self.initial_value != self.current_value:
return _('%(curr)s (was %(initial)s)')%dict(
curr=self.current_value, initial=self.initial_value)
else:
return self.current_value
elif role == Qt.ItemDataRole.EditRole:
return self.current_value
else:
return QListWidgetItem.data(self, role)
def setData(self, role, data):
if role == Qt.ItemDataRole.EditRole:
self.previous_value = self.current_value
self.current_value = data
QListWidgetItem.setData(self, role, data)
def text(self):
return self.current_value
def initial_text(self):
return self.initial_value
def previous_text(self):
return self.previous_value
def setText(self, txt):
self.current_value = txt
QListWidgetItem.setText(txt)
class DeviceCategoryEditor(QDialog, Ui_DeviceCategoryEditor):
def __init__(self, window, tag_to_match, data, key):
QDialog.__init__(self, window)
Ui_DeviceCategoryEditor.__init__(self)
self.setupUi(self)
# Remove help icon on title bar
icon = self.windowIcon()
self.setWindowFlags(self.windowFlags()&(~Qt.WindowType.WindowContextHelpButtonHint))
self.setWindowIcon(icon)
self.to_rename = {}
self.to_delete = set()
self.original_names = {}
self.all_tags = {}
for k,v in data:
self.all_tags[v] = k
self.original_names[k] = v
for tag in sorted(self.all_tags.keys(), key=key):
item = ListWidgetItem(tag)
item.setData(Qt.ItemDataRole.UserRole, self.all_tags[tag])
item.setFlags(item.flags() | Qt.ItemFlag.ItemIsEditable)
self.available_tags.addItem(item)
if tag_to_match is not None:
items = self.available_tags.findItems(tag_to_match, Qt.MatchFlag.MatchExactly)
if len(items) == 1:
self.available_tags.setCurrentItem(items[0])
self.delete_button.clicked.connect(self.delete_tags)
self.rename_button.clicked.connect(self.rename_tag)
self.available_tags.itemDoubleClicked.connect(self._rename_tag)
self.available_tags.itemChanged.connect(self.finish_editing)
def finish_editing(self, item):
if not item.text():
error_dialog(self, _('Item is blank'),
_('An item cannot be set to nothing. Delete it instead.')).exec()
item.setText(item.previous_text())
return
if item.text() != item.initial_text():
id_ = int(item.data(Qt.ItemDataRole.UserRole))
self.to_rename[id_] = str(item.text())
def rename_tag(self):
item = self.available_tags.currentItem()
self._rename_tag(item)
def _rename_tag(self, item):
if item is None:
error_dialog(self, _('No item selected'),
_('You must select one item from the list of available items.')).exec()
return
self.available_tags.editItem(item)
def delete_tags(self):
deletes = self.available_tags.selectedItems()
if not deletes:
error_dialog(self, _('No items selected'),
_('You must select at least one item from the list.')).exec()
return
ct = ', '.join([str(item.text()) for item in deletes])
if not question_dialog(self, _('Are you sure?'),
'<p>'+_('Are you sure you want to delete the following items?')+'<br>'+ct):
return
row = self.available_tags.row(deletes[0])
for item in deletes:
id = int(item.data(Qt.ItemDataRole.UserRole))
self.to_delete.add(id)
self.available_tags.takeItem(self.available_tags.row(item))
if row >= self.available_tags.count():
row = self.available_tags.count() - 1
if row >= 0:
self.available_tags.scrollToItem(self.available_tags.item(row))
| 4,641 | Python | .py | 102 | 35.196078 | 96 | 0.613818 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,030 | tag_list_editor.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/tag_list_editor.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2008, Kovid Goyal <kovid at kovidgoyal.net>
import copy
from contextlib import contextmanager
from functools import partial
from qt.core import (
QAbstractItemView,
QAction,
QApplication,
QColor,
QDialog,
QDialogButtonBox,
QFrame,
QIcon,
QLabel,
QMenu,
QSize,
QStyledItemDelegate,
Qt,
QTableWidgetItem,
QTimer,
pyqtSignal,
sip,
)
from calibre import sanitize_file_name
from calibre.gui2 import choose_files, choose_save_file, error_dialog, gprefs, question_dialog
from calibre.gui2.actions.show_quickview import get_quickview_action_plugin
from calibre.gui2.complete2 import EditWithComplete
from calibre.gui2.dialogs.confirm_delete import confirm
from calibre.gui2.dialogs.tag_list_editor_table_widget import TleTableWidget
from calibre.gui2.dialogs.tag_list_editor_ui import Ui_TagListEditor
from calibre.gui2.widgets import EnLineEdit
from calibre.utils.config import prefs
from calibre.utils.icu import capitalize, contains, primary_contains, primary_startswith
from calibre.utils.icu import lower as icu_lower
from calibre.utils.icu import upper as icu_upper
from calibre.utils.titlecase import titlecase
QT_HIDDEN_CLEAR_ACTION = '_q_qlineeditclearaction'
class NameTableWidgetItem(QTableWidgetItem):
def __init__(self, sort_key):
QTableWidgetItem.__init__(self)
self.initial_value = ''
self.current_value = ''
self.is_deleted = False
self.is_placeholder = False
self.sort_key = sort_key
def data(self, role):
if role == Qt.ItemDataRole.DisplayRole:
if self.is_deleted:
return ''
return self.current_value
elif role == Qt.ItemDataRole.EditRole:
return self.current_value
else:
return QTableWidgetItem.data(self, role)
def set_is_deleted(self, to_what):
if to_what:
self.setIcon(QIcon.cached_icon('trash.png'))
else:
self.setIcon(QIcon.cached_icon())
self.current_value = self.initial_value
self.is_deleted = to_what
def setData(self, role, data):
if role == Qt.ItemDataRole.EditRole:
self.current_value = data
QTableWidgetItem.setData(self, role, data)
def set_initial_text(self, txt):
self.initial_value = txt
def initial_text(self):
return self.initial_value
def text_is_modified(self):
return not self.is_deleted and self.current_value != self.initial_value
def text(self):
return self.current_value
def setText(self, txt):
self.is_placeholder = False
self.current_value = txt
QTableWidgetItem.setText(self, txt)
# Before this method is called, signals should be blocked for the
# table containing this item
def set_placeholder(self, txt):
self.text_before_placeholder = self.current_value
self.setText(txt)
self.is_placeholder = True
# Before this method is called, signals should be blocked for the
# table containing this item
def reset_placeholder(self):
if self.is_placeholder:
self.setText(self.text_before_placeholder)
def __ge__(self, other):
return (self.sort_key(str(self.text())) >=
self.sort_key(str(other.text())))
def __lt__(self, other):
return (self.sort_key(str(self.text())) <
self.sort_key(str(other.text())))
class CountTableWidgetItem(QTableWidgetItem):
def __init__(self, count):
QTableWidgetItem.__init__(self, str(count))
self.setTextAlignment(Qt.AlignmentFlag.AlignRight|Qt.AlignmentFlag.AlignVCenter)
self._count = count
def __ge__(self, other):
return self._count >= other._count
def __lt__(self, other):
return self._count < other._count
class NotesTableWidgetItem(QTableWidgetItem):
# These define the sort order for notes columns
EMPTY = 0
UNCHANGED = 1
EDITED = 2
DELETED = 3
def __init__(self):
QTableWidgetItem.__init__(self, '')
self.set_sort_val(self.EMPTY)
def set_sort_val(self, val):
self._sort_val = val
def __ge__(self, other):
return self._sort_val >= other._sort_val
def __lt__(self, other):
return self._sort_val < other._sort_val
class NotesUtilities():
def __init__(self, table, category, item_id_getter):
self.table = table
self.modified_notes = {}
self.category = category
self.item_id_getter = item_id_getter
def is_note_modified(self, item_id) -> bool:
return item_id in self.modified_notes
def get_db(self):
from calibre.gui2.ui import get_gui
return get_gui().current_db.new_api
def restore_all_notes(self):
# should only be called from reject()
db = self.get_db()
for item_id, before in self.modified_notes.items():
if before:
db.import_note(self.category, item_id, before.encode('utf-8'), path_is_data=True)
else:
db.set_notes_for(self.category, item_id, '')
self.modified_notes.clear()
def set_icon(self, item, id_, has_value):
with block_signals(self.table):
if id_ not in self.modified_notes:
if not has_value:
item.setIcon(QIcon.cached_icon())
item.set_sort_val(NotesTableWidgetItem.EMPTY)
else:
item.setIcon(QIcon.cached_icon('notes.png'))
item.set_sort_val(NotesTableWidgetItem.UNCHANGED)
else:
if has_value:
item.setIcon(QIcon.cached_icon('modified.png'))
item.set_sort_val(NotesTableWidgetItem.EDITED)
elif not bool(self.modified_notes[id_]):
item.setIcon(QIcon.cached_icon())
item.set_sort_val(NotesTableWidgetItem.EMPTY)
else:
item.setIcon(QIcon.cached_icon('trash.png'))
item.set_sort_val(NotesTableWidgetItem.DELETED)
self.table.cellChanged.emit(item.row(), item.column())
self.table.itemChanged.emit(item)
def edit_note(self, item):
item_id = self.item_id_getter(item)
from calibre.gui2.dialogs.edit_category_notes import EditNoteDialog
db = self.get_db()
before = db.notes_for(self.category, item_id)
note = db.export_note(self.category, item_id) if before else ''
d = EditNoteDialog(self.category, item_id, db, parent=self.table)
if d.exec() == QDialog.DialogCode.Accepted:
after = db.notes_for(self.category, item_id)
if item_id not in self.modified_notes:
self.modified_notes[item_id] = note
self.set_icon(item, item_id, bool(after))
def undo_note_edit(self, item):
item_id = self.item_id_getter(item)
before = self.modified_notes.pop(item_id, None)
db = self.get_db()
if before is not None:
if before:
db.import_note(self.category, item_id, before.encode('utf-8'), path_is_data=True)
else:
db.set_notes_for(self.category, item_id, '')
self.set_icon(item, item_id, bool(before))
def delete_note(self, item):
item_id = self.item_id_getter(item)
db = self.get_db()
if item_id not in self.modified_notes:
self.modified_notes[item_id] = db.notes_for(self.category, item_id)
db.set_notes_for(self.category, item_id, '')
self.set_icon(item, item_id, False)
def do_export(self, item, item_name):
item_id = self.item_id_getter(item)
dest = choose_save_file(self.table, 'save-exported-note', _('Export note to a file'),
filters=[(_('HTML files'), ['html'])],
initial_filename=f'{sanitize_file_name(item_name)}.html',
all_files=False)
if dest:
html = self.get_db().export_note(self.category, item_id)
with open(dest, 'wb') as f:
f.write(html.encode('utf-8'))
def do_import(self, item):
src = choose_files(self.table, 'load-imported-note', _('Import note from a file'),
filters=[(_('HTML files'), ['html'])],
all_files=False, select_only_single_file=True)
if src:
item_id = self.item_id_getter(item)
db = self.get_db()
before = db.notes_for(self.category, item_id)
if item_id not in self.modified_notes:
self.modified_notes[item_id] = before
db.import_note(self.category, item_id, src[0])
after = db.notes_for(self.category, item_id)
self.set_icon(item, item_id, bool(after))
def context_menu(self, menu, item, item_name):
m = menu
item_id = self.item_id_getter(item)
from calibre.gui2.ui import get_gui
db = get_gui().current_db.new_api
has_note = bool(db.notes_for(self.category, item_id))
ac = m.addAction(QIcon.cached_icon('edit-undo.png'), _('Undo'))
ac.setEnabled(item_id in self.modified_notes)
ac.triggered.connect(partial(self.undo_note_edit, item))
ac = m.addAction(QIcon.cached_icon('edit_input.png'), _('Edit note') if has_note else _('Create note'))
ac.triggered.connect(partial(self.table.editItem, item))
ac = m.addAction(QIcon.cached_icon('trash.png'), _('Delete note'))
ac.setEnabled(has_note)
ac.triggered.connect(partial(self.delete_note, item))
ac = m.addAction(QIcon.cached_icon('forward.png'), _('Export note to a file'))
ac.setEnabled(has_note)
ac.triggered.connect(partial(self.do_export, item, item_name))
ac = m.addAction(QIcon.cached_icon('back.png'), _('Import note from a file'))
ac.triggered.connect(partial(self.do_import, item))
VALUE_COLUMN = 0
COUNT_COLUMN = 1
WAS_COLUMN = 2
LINK_COLUMN = 3
NOTES_COLUMN = 4
class EditColumnDelegate(QStyledItemDelegate):
editing_finished = pyqtSignal(int)
editing_started = pyqtSignal(int)
def __init__(self, table, check_for_deleted_items, category, notes_utilities, item_id_getter, parent=None):
super().__init__(table)
self.table = table
self.completion_data = None
self.check_for_deleted_items = check_for_deleted_items
self.category = category
self.notes_utilities = notes_utilities
self.item_id_getter = item_id_getter
def set_completion_data(self, data):
self.completion_data = data
def createEditor(self, parent, option, index):
if index.column() == VALUE_COLUMN:
if self.check_for_deleted_items(show_error=True):
return None
self.editing_started.emit(index.row())
self.item = self.table.itemFromIndex(index)
if self.completion_data:
editor = EditWithComplete(parent)
editor.set_separator(None)
editor.update_items_cache(self.completion_data)
else:
editor = EnLineEdit(parent)
return editor
if index.column() == NOTES_COLUMN:
self.notes_utilities.edit_note(self.table.itemFromIndex(index))
return None
self.editing_started.emit(index.row())
editor = EnLineEdit(parent)
editor.setClearButtonEnabled(True)
return editor
def destroyEditor(self, editor, index):
self.editing_finished.emit(index.row())
super().destroyEditor(editor, index)
@contextmanager
def block_signals(widget):
old = widget.blockSignals(True)
try:
yield
finally:
widget.blockSignals(old)
class TagListEditor(QDialog, Ui_TagListEditor):
def __init__(self, window, cat_name, tag_to_match, get_book_ids, sorter,
ttm_is_first_letter=False, category=None, fm=None, link_map=None):
QDialog.__init__(self, window)
Ui_TagListEditor.__init__(self)
self.table_column_widths = None
self.setupUi(self)
from calibre.gui2.ui import get_gui
self.supports_notes = bool(category and get_gui().current_db.new_api.field_supports_notes(category))
self.search_box.setMinimumContentsLength(25)
if category is not None:
item_map = get_gui().current_db.new_api.get_item_name_map(category)
self.original_links = {item_map[k]:v for k,v in link_map.items() if k in item_map}
self.current_links = copy.copy(self.original_links)
else:
self.original_links = {}
self.current_links = {}
# Put the category name into the title bar
self.category_name = cat_name
self.category = category
self.setWindowTitle(_('Manage {}').format(cat_name))
# Remove help icon on title bar
icon = self.windowIcon()
self.setWindowFlags(self.windowFlags()&(~Qt.WindowType.WindowContextHelpButtonHint))
self.setWindowIcon(icon)
# initialization
self.to_rename = {}
self.to_delete = set()
self.all_tags = {}
self.original_names = {}
self.links = {}
self.notes_utilities = NotesUtilities(None, self.category, self.get_item_id)
self.ordered_tags = []
self.sorter = sorter
self.get_book_ids = get_book_ids
self.text_before_editing = ''
self.sort_names = ('name', 'count', 'was', 'link', 'notes')
self.last_sorted_by = 'name'
self.name_order = self.count_order = self.was_order = self.link_order = self.notes_order = 0
if prefs['case_sensitive']:
self.string_contains = contains
else:
self.string_contains = self.case_insensitive_compare
self.delete_button.clicked.connect(self.delete_tags)
self.rename_button.clicked.connect(self.edit_button_clicked)
self.undo_button.clicked.connect(self.undo_edit)
self.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setText(_('&OK'))
self.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setText(_('&Cancel'))
self.buttonBox.accepted.connect(self.accepted)
self.buttonBox.rejected.connect(self.rejected)
self.search_box.initialize('tag_list_search_box_' + cat_name)
le = self.search_box.lineEdit()
ac = le.findChild(QAction, QT_HIDDEN_CLEAR_ACTION)
if ac is not None:
ac.triggered.connect(self.clear_search)
self.search_box.textChanged.connect(self.search_text_changed)
self.search_button.clicked.connect(self.do_search)
self.search_button.setDefault(True)
self.filter_box.initialize('tag_list_filter_box_' + cat_name)
le = self.filter_box.lineEdit()
ac = le.findChild(QAction, QT_HIDDEN_CLEAR_ACTION)
if ac is not None:
ac.triggered.connect(self.clear_filter)
le.returnPressed.connect(self.do_filter)
self.filter_button.clicked.connect(self.do_filter)
self.show_button_layout.setSpacing(0)
self.show_button_layout.setContentsMargins(0, 0, 0, 0)
self.apply_all_checkbox.setContentsMargins(0, 0, 0, 0)
self.apply_all_checkbox.setChecked(True)
self.apply_vl_checkbox.toggled.connect(self.vl_box_changed)
self.apply_selection_checkbox.setContentsMargins(0, 0, 0, 0)
self.apply_selection_checkbox.toggled.connect(self.apply_selection_box_changed)
self.is_enumerated = False
if fm:
if fm['datatype'] == 'enumeration':
self.is_enumerated = True
self.enum_permitted_values = fm.get('display', {}).get('enum_values', None)
# Add the data
self.search_item_row = -1
self.table = None
self.fill_in_table(None, tag_to_match, ttm_is_first_letter)
def sizeHint(self):
return super().sizeHint() + QSize(150, 100)
def link_context_menu(self, menu, item):
m = menu
is_deleted = bool(self.table.item(item.row(), VALUE_COLUMN).is_deleted)
item_id = self.get_item_id(item)
ca = m.addAction(_('Copy'))
ca.triggered.connect(partial(self.copy_to_clipboard, item))
ca.setIcon(QIcon.cached_icon('edit-copy.png'))
ca.setEnabled(not is_deleted)
ca = m.addAction(_('Paste'))
ca.setIcon(QIcon.cached_icon('edit-paste.png'))
ca.triggered.connect(partial(self.paste_from_clipboard, item))
ca.setEnabled(not is_deleted)
ca = m.addAction(_('Undo'))
ca.setIcon(QIcon.cached_icon('edit-undo.png'))
ca.triggered.connect(partial(self.undo_link_edit, item, item_id))
ca.setEnabled(not is_deleted and self.link_is_edited(item_id))
ca = m.addAction(_('Edit'))
ca.setIcon(QIcon.cached_icon('edit_input.png'))
ca.triggered.connect(partial(self.table.editItem, item))
ca.setEnabled(not is_deleted)
ca = m.addAction(_('Delete link'))
ca.setIcon(QIcon.cached_icon('trash.png'))
def delete_link_text(item):
item.setText('')
ca.triggered.connect(partial(delete_link_text, item))
ca.setEnabled(not is_deleted)
def value_context_menu(self, menu, item):
m = menu
self.table.setCurrentItem(item)
ca = m.addAction(_('Copy'))
ca.triggered.connect(partial(self.copy_to_clipboard, item))
ca.setIcon(QIcon.cached_icon('edit-copy.png'))
ca.setEnabled(not item.is_deleted)
ca = m.addAction(_('Paste'))
ca.setIcon(QIcon.cached_icon('edit-paste.png'))
ca.triggered.connect(partial(self.paste_from_clipboard, item))
ca.setEnabled(not item.is_deleted)
ca = m.addAction(_('Undo'))
ca.setIcon(QIcon.cached_icon('edit-undo.png'))
if item.is_deleted:
ca.triggered.connect(self.undo_edit)
else:
ca.triggered.connect(partial(self.undo_value_edit, item, self.get_item_id(item)))
ca.setEnabled(item.is_deleted or item.text() != self.original_names[self.get_item_id(item)])
ca = m.addAction(_('Edit'))
ca.setIcon(QIcon.cached_icon('edit_input.png'))
ca.triggered.connect(self.edit_button_clicked)
ca.setEnabled(not item.is_deleted)
ca = m.addAction(_('Delete'))
ca.setIcon(QIcon.cached_icon('trash.png'))
ca.triggered.connect(self.delete_tags)
item_name = str(item.text())
ca.setEnabled(not item.is_deleted)
ca = m.addAction(_('Search for {}').format(item_name))
ca.setIcon(QIcon.cached_icon('search.png'))
ca.triggered.connect(partial(self.set_search_text, item_name))
item_name = str(item.text())
ca.setEnabled(not item.is_deleted)
ca = m.addAction(_('Filter by {}').format(item_name))
ca.setIcon(QIcon.cached_icon('filter.png'))
ca.triggered.connect(partial(self.set_filter_text, item_name))
ca.setEnabled(not item.is_deleted)
if self.category is not None:
ca = m.addAction(_("Search the library for {0}").format(item_name))
ca.setIcon(QIcon.cached_icon('lt.png'))
ca.triggered.connect(partial(self.search_for_books, item))
ca.setEnabled(not item.is_deleted)
if self.table.state() == QAbstractItemView.State.EditingState:
m.addSeparator()
case_menu = QMenu(_('Change case'))
case_menu.setIcon(QIcon.cached_icon('font_size_larger.png'))
action_upper_case = case_menu.addAction(_('Upper case'))
action_lower_case = case_menu.addAction(_('Lower case'))
action_swap_case = case_menu.addAction(_('Swap case'))
action_title_case = case_menu.addAction(_('Title case'))
action_capitalize = case_menu.addAction(_('Capitalize'))
action_upper_case.triggered.connect(partial(self.do_case, icu_upper))
action_lower_case.triggered.connect(partial(self.do_case, icu_lower))
action_swap_case.triggered.connect(partial(self.do_case, self.swap_case))
action_title_case.triggered.connect(partial(self.do_case, titlecase))
action_capitalize.triggered.connect(partial(self.do_case, capitalize))
m.addMenu(case_menu)
def show_context_menu(self, point):
item = self.table.itemAt(point)
if item is None or item.column() in (WAS_COLUMN, COUNT_COLUMN):
return
m = QMenu()
if item.column() == NOTES_COLUMN:
self.notes_utilities.context_menu(m, item, self.table.item(item.row(), VALUE_COLUMN).text())
elif item.column() == VALUE_COLUMN:
self.value_context_menu(m, item)
elif item.column() == LINK_COLUMN:
self.link_context_menu(m, item)
m.exec(self.table.viewport().mapToGlobal(point))
def search_for_books(self, item):
from calibre.gui2.ui import get_gui
get_gui().search.set_search_string('{}:"={}"'.format(self.category,
str(item.text()).replace(r'"', r'\"')))
qv = get_quickview_action_plugin()
if qv:
view = get_gui().library_view
rows = view.selectionModel().selectedRows()
if len(rows) > 0:
current_row = rows[0].row()
current_col = view.column_map.index(self.category)
index = view.model().index(current_row, current_col)
qv.change_quickview_column(index, show=False)
def copy_to_clipboard(self, item):
cb = QApplication.clipboard()
cb.setText(str(item.text()))
def paste_from_clipboard(self, item):
cb = QApplication.clipboard()
item.setText(cb.text())
def case_insensitive_compare(self, l, r):
if prefs['use_primary_find_in_search']:
return primary_contains(l, r)
return contains(l.lower(), r.lower())
def do_case(self, func):
items = self.table.selectedItems()
# block signals to avoid the "edit one changes all" behavior
with block_signals(self.table):
for item in items:
item.setText(func(str(item.text())))
def swap_case(self, txt):
return txt.swapcase()
def vl_box_changed(self):
self.search_item_row = -1
self.fill_in_table(None, None, False)
def apply_selection_box_changed(self):
self.search_item_row = -1
self.fill_in_table(None, None, False)
def selection_to_apply(self):
if self.apply_selection_checkbox.isChecked():
return 'selection'
if self.apply_vl_checkbox.isChecked():
return 'virtual_library'
return None
def do_search(self):
self.not_found_label.setVisible(False)
find_text = str(self.search_box.currentText())
if not find_text:
return
for _ in range(0, self.table.rowCount()):
r = self.search_item_row = (self.search_item_row + 1) % self.table.rowCount()
if self.string_contains(find_text, self.table.item(r, VALUE_COLUMN).text()):
self.table.setCurrentItem(self.table.item(r, VALUE_COLUMN))
self.table.setFocus(Qt.FocusReason.OtherFocusReason)
return
# Nothing found. Pop up the little dialog for 1.5 seconds
self.not_found_label.setVisible(True)
self.not_found_label_timer.start(1500)
def search_text_changed(self):
self.search_item_row = -1
def clear_search(self):
self.search_item_row = -1
self.search_box.setText('')
def set_search_text(self, txt):
self.search_box.setText(txt)
self.do_search()
def create_table(self):
# For some reason we must recreate the table if we change the row count.
# If we don't then the old items remain even if replaced by setItem().
# I'm not sure if this is standard Qt behavior or behavior triggered by
# something in this class, but replacing the table fixes it.
self.table_column_widths = gprefs.get('tag_list_editor_table_widths', None)
if self.table is not None:
self.save_geometry()
self.central_layout.removeWidget(self.table)
sip.delete(self.table)
self.table = TleTableWidget(self)
self.central_layout.addWidget(self.table)
self.table.setAlternatingRowColors(True)
self.table.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectItems)
hh = self.table.horizontalHeader()
hh.sectionResized.connect(self.table_column_resized)
hh.setSectionsClickable(True)
self.table.setSortingEnabled(True)
hh.sectionClicked.connect(self.record_sort)
hh.setSortIndicatorShown(True)
vh = self.table.verticalHeader()
vh.setDefaultSectionSize(gprefs.get('general_category_editor_row_height', vh.defaultSectionSize()))
vh.sectionResized.connect(self.row_height_changed)
self.table.setColumnCount(5)
self.notes_utilities.table = self.table
self.edit_delegate = EditColumnDelegate(self.table, self.check_for_deleted_items,
self.category, self.notes_utilities, self.get_item_id)
self.edit_delegate.editing_finished.connect(self.stop_editing)
self.edit_delegate.editing_started.connect(self.start_editing)
self.table.setItemDelegateForColumn(VALUE_COLUMN, self.edit_delegate)
self.table.setItemDelegateForColumn(LINK_COLUMN, self.edit_delegate)
self.table.setItemDelegateForColumn(NOTES_COLUMN, self.edit_delegate)
self.table.delete_pressed.connect(self.delete_pressed)
self.table.itemDoubleClicked.connect(self.edit_item)
self.table.itemChanged.connect(self.finish_editing)
self.table.itemSelectionChanged.connect(self.selection_changed)
l = QLabel(self.table)
self.not_found_label = l
l.setFrameStyle(QFrame.Shape.StyledPanel)
l.setAutoFillBackground(True)
l.setText(_('No matches found'))
l.setAlignment(Qt.AlignmentFlag.AlignVCenter)
l.resize(l.sizeHint())
l.move(10, 0)
l.setVisible(False)
self.not_found_label_timer = QTimer()
self.not_found_label_timer.setSingleShot(True)
self.not_found_label_timer.timeout.connect(
self.not_found_label_timer_event, type=Qt.ConnectionType.QueuedConnection)
self.table.setEditTriggers(QAbstractItemView.EditTrigger.EditKeyPressed)
self.restore_geometry(gprefs, 'tag_list_editor_dialog_geometry')
if self.table_column_widths is not None:
for col,width in enumerate(self.table_column_widths):
self.table.setColumnWidth(col, width)
self.table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.table.customContextMenuRequested.connect(self.show_context_menu)
def get_item_id(self, item):
return int(self.table.item(item.row(), VALUE_COLUMN).data(Qt.ItemDataRole.UserRole))
def row_height_changed(self, row, old, new):
self.table.verticalHeader().setDefaultSectionSize(new)
def link_is_edited(self, item_id):
return self.current_links.get(item_id, None) != self.original_links.get(item_id)
def set_link_icon(self, id_, item):
with block_signals(self.table):
if self.link_is_edited(id_):
item.setIcon(QIcon.cached_icon('modified.png'))
else:
item.setIcon(QIcon.cached_icon())
def fill_in_table(self, tags, tag_to_match, ttm_is_first_letter):
self.create_table()
data = self.get_book_ids(self.selection_to_apply())
self.all_tags = {}
filter_text = icu_lower(str(self.filter_box.text()))
for k,v,count in data:
if not filter_text or self.string_contains(filter_text, icu_lower(v)):
self.all_tags[v] = {'key': k, 'count': count, 'cur_name': v,
'is_deleted': k in self.to_delete}
self.original_names[k] = v
if self.is_enumerated:
self.edit_delegate.set_completion_data(self.enum_permitted_values)
else:
self.edit_delegate.set_completion_data(self.original_names.values())
self.ordered_tags = sorted(self.all_tags.keys(), key=self.sorter)
if tags is None:
tags = self.ordered_tags
select_item = None
tooltips = ( # must be in the same order as the columns in the table
_('Name of the item'),
_('Count of books with this item'),
_('Value of the item before it was edited'),
_('The link (URL) associated with this item'),
_('Whether the item has a note. The icon changes if the note was created or edited')
)
with block_signals(self.table):
self.name_col = QTableWidgetItem(self.category_name)
self.table.setHorizontalHeaderItem(VALUE_COLUMN, self.name_col)
self.count_col = QTableWidgetItem(_('Count'))
self.table.setHorizontalHeaderItem(1, self.count_col)
self.was_col = QTableWidgetItem(_('Was'))
self.table.setHorizontalHeaderItem(2, self.was_col)
self.link_col = QTableWidgetItem(_('Link'))
self.table.setHorizontalHeaderItem(LINK_COLUMN, self.link_col)
if self.supports_notes:
self.notes_col = QTableWidgetItem(_('Notes'))
self.table.setHorizontalHeaderItem(4, self.notes_col)
for i,tt in enumerate(tooltips):
header_item = self.table.horizontalHeaderItem(i)
header_item.setToolTip(tt)
self.table.setRowCount(len(tags))
if self.supports_notes:
from calibre.gui2.ui import get_gui
all_items_that_have_notes = get_gui().current_db.new_api.get_all_items_that_have_notes(self.category)
for row,tag in enumerate(tags):
item = NameTableWidgetItem(self.sorter)
is_deleted = self.all_tags[tag]['is_deleted']
item.set_is_deleted(is_deleted)
id_ = self.all_tags[tag]['key']
item.setData(Qt.ItemDataRole.UserRole, id_)
item.set_initial_text(tag)
if id_ in self.to_rename:
item.setText(self.to_rename[id_])
else:
item.setText(tag)
if self.is_enumerated and str(item.text()) not in self.enum_permitted_values:
item.setBackground(QColor('#FF2400'))
item.setToolTip(
'<p>' +
_("This is not one of this column's permitted values ({0})"
).format(', '.join(self.enum_permitted_values)) + '</p>')
item.setFlags(item.flags() | Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEditable)
self.table.setItem(row, VALUE_COLUMN, item)
if select_item is None:
if ttm_is_first_letter:
if primary_startswith(tag, tag_to_match):
select_item = item
elif tag == tag_to_match:
select_item = item
if item.text_is_modified():
item.setIcon(QIcon.cached_icon('modified.png'))
item = CountTableWidgetItem(self.all_tags[tag]['count'])
item.setFlags(item.flags() & ~(Qt.ItemFlag.ItemIsSelectable|Qt.ItemFlag.ItemIsEditable))
self.table.setItem(row, COUNT_COLUMN, item)
item = QTableWidgetItem()
item.setFlags(item.flags() & ~(Qt.ItemFlag.ItemIsSelectable|Qt.ItemFlag.ItemIsEditable))
if id_ in self.to_rename or id_ in self.to_delete:
item.setData(Qt.ItemDataRole.DisplayRole, tag)
self.table.setItem(row, WAS_COLUMN, item)
item = QTableWidgetItem()
if self.original_links is None:
item.setFlags(item.flags() & ~(Qt.ItemFlag.ItemIsSelectable|Qt.ItemFlag.ItemIsEditable))
item.setText(_('no links available'))
else:
if is_deleted:
item.setFlags(item.flags() & ~(Qt.ItemFlag.ItemIsSelectable|Qt.ItemFlag.ItemIsEditable))
else:
item.setFlags(item.flags() | (Qt.ItemFlag.ItemIsSelectable|Qt.ItemFlag.ItemIsEditable))
self.set_link_icon(id_, item)
item.setText(self.current_links.get(id_, ''))
self.table.setItem(row, LINK_COLUMN, item)
if self.supports_notes:
item = NotesTableWidgetItem()
self.notes_utilities.set_icon(item, id_, id_ in all_items_that_have_notes)
if is_deleted:
item.setFlags(item.flags() & ~(Qt.ItemFlag.ItemIsSelectable|Qt.ItemFlag.ItemIsEditable))
else:
item.setFlags(item.flags() | (Qt.ItemFlag.ItemIsSelectable|Qt.ItemFlag.ItemIsEditable))
self.table.setItem(row, NOTES_COLUMN, item)
# re-sort the table
column = self.sort_names.index(self.last_sorted_by)
sort_order = getattr(self, self.last_sorted_by + '_order')
self.table.sortByColumn(column, Qt.SortOrder(sort_order))
if select_item is not None:
self.table.setCurrentItem(select_item)
self.table.setFocus(Qt.FocusReason.OtherFocusReason)
self.start_find_pos = select_item.row()
else:
self.table.setCurrentCell(0, 0)
self.search_box.setFocus()
self.start_find_pos = -1
self.table.setFocus(Qt.FocusReason.OtherFocusReason)
def not_found_label_timer_event(self):
self.not_found_label.setVisible(False)
def clear_filter(self):
self.filter_box.setText('')
self.do_filter()
def set_filter_text(self, txt):
self.filter_box.setText(txt)
self.do_filter()
def do_filter(self):
self.fill_in_table(None, None, False)
def table_column_resized(self, *args):
self.table_column_widths = []
for c in range(0, self.table.columnCount()):
self.table_column_widths.append(self.table.columnWidth(c))
def resizeEvent(self, *args):
QDialog.resizeEvent(self, *args)
if self.table_column_widths is not None:
for c,w in enumerate(self.table_column_widths):
self.table.setColumnWidth(c, w)
else:
# the vertical scroll bar might not be rendered, so might not yet
# have a width. Assume 25. Not a problem because user-changed column
# widths will be remembered
w = self.table.width() - 25 - self.table.verticalHeader().width()
w //= self.table.columnCount()
for c in range(0, self.table.columnCount()):
self.table.setColumnWidth(c, w)
def start_editing(self, on_row):
current_column = self.table.currentItem().column()
# We don't support editing multiple link or notes rows at the same time.
# Use the current cell.
if current_column != VALUE_COLUMN:
self.table.setCurrentItem(self.table.item(on_row, current_column))
items = self.table.selectedItems()
with block_signals(self.table):
self.table.setSortingEnabled(False)
for item in items:
if item.row() != on_row:
item.set_placeholder(_('Editing...'))
else:
self.text_before_editing = item.text()
def stop_editing(self, on_row):
# This works because the link and notes fields doesn't support editing
# on multiple lines, so the on_row check will always be false.
items = self.table.selectedItems()
with block_signals(self.table):
for item in items:
if item.row() != on_row and item.is_placeholder:
item.reset_placeholder()
self.table.setSortingEnabled(True)
def finish_editing(self, edited_item):
if edited_item.column() == LINK_COLUMN:
id_ = self.get_item_id(edited_item)
txt = edited_item.text()
if txt:
self.current_links[id_] = txt
else:
self.current_links.pop(id_, None)
self.set_link_icon(id_, edited_item)
return
if edited_item.column() == NOTES_COLUMN:
# Done elsewhere
return
# Item value column
if not edited_item.text():
error_dialog(self, _('Item is blank'), _(
'An item cannot be set to nothing. Delete it instead.'), show=True)
with block_signals(self.table):
edited_item.setText(self.text_before_editing)
return
new_text = str(edited_item.text())
if self.is_enumerated and new_text not in self.enum_permitted_values:
error_dialog(self, _('Item is not a permitted value'), '<p>' + _(
"This column has a fixed set of permitted values. The entered "
"text must be one of ({0}).").format(', '.join(self.enum_permitted_values)) +
'</p>', show=True)
with block_signals(self.table):
edited_item.setText(self.text_before_editing)
return
items = self.table.selectedItems()
with block_signals(self.table):
for item in items:
id_ = int(item.data(Qt.ItemDataRole.UserRole))
self.to_rename[id_] = new_text
orig = self.table.item(item.row(), WAS_COLUMN)
item.setText(new_text)
if item.text_is_modified():
item.setIcon(QIcon.cached_icon('modified.png'))
orig.setData(Qt.ItemDataRole.DisplayRole, item.initial_text())
else:
item.setIcon(QIcon.cached_icon())
orig.setData(Qt.ItemDataRole.DisplayRole, '')
def undo_link_edit(self, item, item_id):
if item_id in self.original_links:
link_txt = self.current_links[item_id] = self.original_links[item_id]
else:
self.current_links.pop(item_id, None)
link_txt = ''
item = self.table.item(item.row(), LINK_COLUMN)
item.setFlags(item.flags() | Qt.ItemFlag.ItemIsEditable | Qt.ItemFlag.ItemIsSelectable)
item.setText(link_txt)
item.setIcon(QIcon.cached_icon())
def undo_value_edit(self, item, item_id):
with block_signals(self.table):
item.setText(item.initial_text())
self.to_rename.pop(item_id, None)
row = item.row()
self.table.item(row, WAS_COLUMN).setData(Qt.ItemDataRole.DisplayRole, '')
item.setIcon(QIcon.cached_icon('modified.png') if item.text_is_modified() else QIcon.cached_icon())
def undo_edit(self):
col_zero_items = (self.table.item(item.row(), VALUE_COLUMN) for item in self.table.selectedItems())
if not col_zero_items:
error_dialog(self, _('No item selected'),
_('You must select one item from the list of available items.')).exec()
return
if not confirm(
_('Do you really want to undo all your changes on selected rows?'),
'tag_list_editor_undo'):
return
with block_signals(self.table):
for col_zero_item in col_zero_items:
id_ = self.get_item_id(col_zero_item)
row = col_zero_item.row()
# item value column
self.undo_value_edit(col_zero_item, id_)
col_zero_item.set_is_deleted(False)
self.to_delete.discard(id_)
# Link column
self.undo_link_edit(self.table.item(row, LINK_COLUMN), id_)
# Notes column
item = self.table.item(row, NOTES_COLUMN)
item.setFlags(item.flags() | Qt.ItemFlag.ItemIsEditable | Qt.ItemFlag.ItemIsSelectable)
if id_ in self.notes_utilities.modified_notes:
self.notes_utilities.undo_note_edit(item)
item.setIcon(QIcon.cached_icon())
def selection_changed(self):
if self.table.currentIndex().isValid():
col = self.table.currentIndex().column()
with block_signals(self.table):
if col != VALUE_COLUMN:
self.table.setCurrentIndex(self.table.currentIndex())
else:
for itm in (item for item in self.table.selectedItems() if item.column() != col):
itm.setSelected(False)
def check_for_deleted_items(self, show_error=False):
for col_zero_item in (self.table.item(item.row(), VALUE_COLUMN) for item in self.table.selectedItems()):
if col_zero_item.is_deleted:
if show_error:
error_dialog(self, _('Selection contains deleted items'),
'<p>'+_('The selection contains deleted items. You '
'must undelete them before editing.')+'<br>',
show=True)
return True
return False
def edit_button_clicked(self):
self.edit_item(self.table.currentItem())
def edit_item(self, item):
if item is None:
error_dialog(self, _('No item selected'),
_('You must select one item from the list of available items.')).exec()
return
if self.check_for_deleted_items():
if not question_dialog(self, _('Undelete items?'),
'<p>'+_('Items must be undeleted to continue. Do you want '
'to do this?')+'<br>'):
return
with block_signals(self.table):
for col_zero_item in (self.table.item(item.row(), VALUE_COLUMN)
for item in self.table.selectedItems()):
# undelete any deleted items
if col_zero_item.is_deleted:
col_zero_item.set_is_deleted(False)
self.to_delete.discard(int(col_zero_item.data(Qt.ItemDataRole.UserRole)))
orig = self.table.item(col_zero_item.row(), WAS_COLUMN)
orig.setData(Qt.ItemDataRole.DisplayRole, '')
self.table.editItem(item)
def delete_pressed(self):
if self.table.currentColumn() == VALUE_COLUMN:
self.delete_tags()
return
if not confirm(
'<p>'+_('Are you sure you want to delete the selected links? '
'There is no undo.')+'<br>',
'tag_list_editor_link_delete'):
return
for item in self.table.selectedItems():
item.setText('')
def delete_tags(self):
# This check works because we ensure that the selection is in only one column
if self.table.currentItem().column() != VALUE_COLUMN:
return
# We know the selected items are in column zero
deletes = self.table.selectedItems()
if not deletes:
error_dialog(self, _('No items selected'),
_('You must select at least one item from the list.')).exec()
return
to_del = []
for item in deletes:
if not item.is_deleted:
to_del.append(item)
if to_del:
ct = ', '.join([str(item.text()) for item in to_del])
if not confirm(
'<p>'+_('Are you sure you want to delete the following items?')+'<br>'+ct,
'tag_list_editor_delete'):
return
row = self.table.row(deletes[0])
with block_signals(self.table):
for item in deletes:
id_ = int(item.data(Qt.ItemDataRole.UserRole))
self.to_delete.add(id_)
item.set_is_deleted(True)
row = item.row()
orig = self.table.item(row, WAS_COLUMN)
orig.setData(Qt.ItemDataRole.DisplayRole, item.initial_text())
link = self.table.item(row, LINK_COLUMN)
link.setFlags(link.flags() & ~(Qt.ItemFlag.ItemIsSelectable|Qt.ItemFlag.ItemIsEditable))
note = self.table.item(row, NOTES_COLUMN)
note.setFlags(link.flags() & ~(Qt.ItemFlag.ItemIsSelectable|Qt.ItemFlag.ItemIsEditable))
if row >= self.table.rowCount():
row = self.table.rowCount() - 1
if row >= 0:
self.table.scrollToItem(self.table.item(row, VALUE_COLUMN))
def record_sort(self, section):
# Note what sort was done so we can redo it when the table is rebuilt
sort_name = self.sort_names[section]
sort_order_attr = sort_name + '_order'
setattr(self, sort_order_attr, 1 - getattr(self, sort_order_attr))
self.last_sorted_by = sort_name
def save_geometry(self):
gprefs['general_category_editor_row_height'] = self.table.verticalHeader().defaultSectionSize()
gprefs['tag_list_editor_table_widths'] = self.table_column_widths
super().save_geometry(gprefs, 'tag_list_editor_dialog_geometry')
def accepted(self):
for t in self.all_tags.values():
if t['is_deleted']:
continue
if t['key'] in self.to_rename:
name = self.to_rename[t['key']]
else:
name = t['cur_name']
self.links[name] = self.current_links.get(t['key'], '')
self.save_geometry()
def rejected(self):
self.notes_utilities.restore_all_notes()
self.save_geometry()
| 46,522 | Python | .py | 949 | 37.546891 | 117 | 0.608817 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,031 | authors_edit.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/authors_edit.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
from collections import OrderedDict
from qt.core import (
QAbstractItemView,
QApplication,
QDialog,
QDialogButtonBox,
QGridLayout,
QIcon,
QLabel,
QListWidget,
QPushButton,
QSize,
QStyledItemDelegate,
Qt,
pyqtSignal,
)
from calibre.ebooks.metadata import string_to_authors
from calibre.gui2 import gprefs
from calibre.gui2.complete2 import EditWithComplete
from calibre.utils.config_base import tweaks
from calibre.utils.icu import lower as icu_lower
class ItemDelegate(QStyledItemDelegate):
edited = pyqtSignal(object)
def __init__(self, all_authors, parent):
QStyledItemDelegate.__init__(self, parent)
self.all_authors = all_authors
def sizeHint(self, *args):
return QStyledItemDelegate.sizeHint(self, *args) + QSize(0, 15)
def setEditorData(self, editor, index):
name = str(index.data(Qt.ItemDataRole.DisplayRole) or '')
n = editor.metaObject().userProperty().name()
editor.setProperty(n, name)
def setModelData(self, editor, model, index):
authors = string_to_authors(str(editor.text()))
model.setData(index, authors[0])
self.edited.emit(index.row())
def createEditor(self, parent, option, index):
self.ed = EditWithComplete(parent)
self.ed.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
init_line_edit(self.ed, self.all_authors)
return self.ed
class List(QListWidget):
def __init__(self, all_authors, parent):
QListWidget.__init__(self, parent)
self.setDragEnabled(True)
self.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
self.setDropIndicatorShown(True)
self.setDragDropMode(QAbstractItemView.DragDropMode.InternalMove)
self.setAlternatingRowColors(True)
self.d = ItemDelegate(all_authors, self)
self.d.edited.connect(self.edited, type=Qt.ConnectionType.QueuedConnection)
self.setItemDelegate(self.d)
def delete_selected(self):
for item in self.selectedItems():
self.takeItem(self.row(item))
def keyPressEvent(self, ev):
if ev.key() == Qt.Key.Key_Delete:
self.delete_selected()
ev.accept()
return
return QListWidget.keyPressEvent(self, ev)
def addItem(self, *args):
try:
return QListWidget.addItem(self, *args)
finally:
self.mark_as_editable()
def addItems(self, *args):
try:
return QListWidget.addItems(self, *args)
finally:
self.mark_as_editable()
def mark_as_editable(self):
for i in range(self.count()):
item = self.item(i)
item.setFlags(item.flags() | Qt.ItemFlag.ItemIsEditable)
def edited(self, i):
item = self.item(i)
q = str(item.text())
remove = []
for j in range(self.count()):
if i != j and str(self.item(j).text()) == q:
remove.append(j)
for x in sorted(remove, reverse=True):
self.takeItem(x)
class Edit(EditWithComplete):
returnPressed = pyqtSignal()
def keyPressEvent(self, ev):
if ev.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter):
ev.accept()
self.returnPressed.emit()
return
return EditWithComplete.keyPressEvent(self, ev)
def init_line_edit(a, all_authors):
a.set_separator('&')
a.set_space_before_sep(True)
a.set_add_separator(tweaks['authors_completer_append_separator'])
a.update_items_cache(all_authors)
class AuthorsEdit(QDialog):
def __init__(self, all_authors, current_authors, parent=None):
QDialog.__init__(self, parent)
self.l = l = QGridLayout()
self.setLayout(l)
self.setWindowTitle(_('Edit authors'))
self.la = QLabel(_(
'Edit the authors for this book. You can drag and drop to re-arrange authors'))
self.la.setWordWrap(True)
l.addWidget(self.la, 0, 0, 1, 3)
self.al = al = List(all_authors, self)
al.addItems(current_authors)
l.addWidget(al, 1, 0, 1, 3)
self.author = a = Edit(self)
init_line_edit(a, all_authors)
a.lineEdit().setPlaceholderText(_('Enter an author to add'))
a.returnPressed.connect(self.add_author)
l.addWidget(a, 2, 0)
self.ab = b = QPushButton(_('&Add'))
b.setIcon(QIcon.ic('plus.png'))
l.addWidget(b, 2, 1)
b.clicked.connect(self.add_author)
self.db = b = QPushButton(_('&Remove selected'))
l.addWidget(b, 2, 2)
b.setIcon(QIcon.ic('minus.png'))
b.clicked.connect(self.al.delete_selected)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
bb.accepted.connect(self.accept)
bb.rejected.connect(self.reject)
l.addWidget(bb, 3, 0, 1, 3)
l.setColumnStretch(0, 10)
self.resize(self.sizeHint() + QSize(150, 100))
self.restore_geometry(gprefs, 'authors-edit-geometry')
self.author.setFocus(Qt.FocusReason.OtherFocusReason)
def accept(self):
self.save_geometry(gprefs, 'authors-edit-geometry')
return QDialog.accept(self)
def reject(self):
self.save_geometry(gprefs, 'authors-edit-geometry')
return QDialog.reject(self)
@property
def authors(self):
ans = []
for i in range(self.al.count()):
ans.append(str(self.al.item(i).text()))
return ans or [_('Unknown')]
def add_author(self):
text = self.author.text().strip()
authors = OrderedDict((icu_lower(x), (i, x)) for i, x in enumerate(self.authors))
if text:
for author in string_to_authors(text):
la = icu_lower(author)
if la in authors and authors[la][1] != author:
# Case change
i = authors[la][0]
authors[la] = (i, author)
self.al.item(i).setText(author)
else:
self.al.addItem(author)
authors[la] = author
self.author.setText('')
if __name__ == '__main__':
app = QApplication([])
d = AuthorsEdit(['kovid goyal', 'divok layog', 'other author'], ['kovid goyal', 'other author'])
d.exec()
print(d.authors)
| 6,533 | Python | .py | 166 | 30.861446 | 116 | 0.626759 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,032 | template_line_editor.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/template_line_editor.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from qt.core import QLineEdit
from calibre import prints
from calibre.gui2.dialogs.template_dialog import TemplateDialog
class TemplateLineEditor(QLineEdit):
'''
Extend the context menu of a QLineEdit to include more actions.
'''
def __init__(self, parent):
QLineEdit.__init__(self, parent)
try:
from calibre.gui2.ui import get_gui
gui = get_gui()
view = gui.library_view
db = gui.current_db
mi = []
for _id in view.get_selected_ids()[:5]:
mi.append(db.new_api.get_metadata(_id))
self.mi = mi
except Exception as e:
prints(f'TemplateLineEditor: exception fetching metadata: {str(e)}')
self.mi = None
self.setClearButtonEnabled(True)
def set_mi(self, mi):
self.mi = mi
def contextMenuEvent(self, event):
menu = self.createStandardContextMenu()
menu.addSeparator()
action_clear_field = menu.addAction(_('Remove any template from the box'))
action_clear_field.triggered.connect(self.clear_field)
action_open_editor = menu.addAction(_('Open template editor'))
action_open_editor.triggered.connect(self.open_editor)
menu.exec(event.globalPos())
def clear_field(self):
self.setText('')
def open_editor(self):
t = TemplateDialog(self, self.text(), mi=self.mi)
t.setWindowTitle(_('Edit template'))
if t.exec():
self.setText(t.rule[1])
| 1,681 | Python | .py | 43 | 30.883721 | 82 | 0.627463 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,033 | data_files_manager.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/data_files_manager.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2023, Kovid Goyal <kovid at kovidgoyal.net>
import os
import posixpath
from contextlib import contextmanager
from datetime import datetime
from functools import partial
from math import ceil
from qt.core import (
QAbstractItemView,
QAbstractListModel,
QComboBox,
QCursor,
QDialogButtonBox,
QDropEvent,
QHBoxLayout,
QIcon,
QItemSelection,
QItemSelectionModel,
QLabel,
QListView,
QMenu,
QPushButton,
QRect,
QSize,
QStyle,
QStyledItemDelegate,
Qt,
QTextDocument,
QTimer,
QVBoxLayout,
pyqtSignal,
sip,
)
from calibre import human_readable, prepare_string_for_xml
from calibre.constants import ismacos
from calibre.db.constants import DATA_DIR_NAME, DATA_FILE_PATTERN
from calibre.gui2 import choose_files, error_dialog, file_icon_provider, gprefs, open_local_file, question_dialog
from calibre.gui2.dialogs.confirm_delete import confirm
from calibre.gui2.open_with import choose_program, edit_programs, populate_menu, run_program
from calibre.gui2.widgets2 import Dialog
from calibre.utils.icu import primary_sort_key
from calibre.utils.recycle_bin import delete_file
from calibre_extensions.progress_indicator import set_no_activate_on_click
NAME_ROLE = Qt.ItemDataRole.UserRole
class Delegate(QStyledItemDelegate):
rename_requested = pyqtSignal(int, str)
doc_size = None
def setModelData(self, editor, model, index):
newname = editor.text()
oldname = index.data(NAME_ROLE) or ''
if newname != oldname:
self.rename_requested.emit(index.row(), newname)
def setEditorData(self, editor, index):
name = index.data(NAME_ROLE) or ''
# We do this because Qt calls selectAll() unconditionally on the
# editor, and we want only a part of the file name to be selected
QTimer.singleShot(0, partial(self.set_editor_data, name, editor))
def set_editor_data(self, name, editor):
if sip.isdeleted(editor):
return
editor.setText(name)
ext_pos = name.rfind('.')
slash_pos = name.rfind(os.sep)
if slash_pos == -1 and ext_pos > 0:
editor.setSelection(0, ext_pos)
elif ext_pos > -1 and slash_pos > -1 and ext_pos > slash_pos + 1:
editor.setSelection(slash_pos+1, ext_pos - slash_pos - 1)
else:
editor.selectAll()
def doc_for_index(self, index):
d = QTextDocument()
d.setDocumentMargin(0)
lines = (index.data(Qt.ItemDataRole.DisplayRole) or ' \n ').splitlines()
d.setHtml(f'<b>{prepare_string_for_xml(lines[0])}</b><br><small>{prepare_string_for_xml(lines[1])}')
return d
def sizeHint(self, option, index):
ans = super().sizeHint(option, index)
if self.doc_size is None:
d = self.doc_for_index(index)
self.doc_size = d.size()
ans.setHeight(max(int(ceil(self.doc_size.height()) + 2), ans.height()))
return ans
def paint(self, painter, option, index):
painter.save()
painter.setClipRect(option.rect)
if option.state & QStyle.StateFlag.State_Selected:
painter.fillRect(option.rect, option.palette.highlight())
dec = index.data(Qt.ItemDataRole.DecorationRole)
sz = QSize(option.rect.height(), option.rect.height())
r = option.rect
ir = QRect(r.topLeft(), sz)
dec.paint(painter, ir)
r.adjust(ir.width(), 0, 0, 0)
d = self.doc_for_index(index)
extra = int(r.height() - d.size().height()) // 2
if extra > 0:
r.adjust(0, extra, 0, 0)
painter.translate(r.topLeft())
d.drawContents(painter)
painter.restore()
class Files(QAbstractListModel):
def __init__(self, db, book_id, parent=None):
self.db = db
self.book_id = book_id
super().__init__(parent=parent)
self.fi = file_icon_provider()
self.files = []
def refresh(self, key=None, reverse=False):
self.modelAboutToBeReset.emit()
self.files = sorted(self.db.list_extra_files(self.book_id, pattern=DATA_FILE_PATTERN), key=key or self.file_sort_key, reverse=reverse)
self.modelReset.emit()
def file_sort_key(self, ef):
return primary_sort_key(ef.relpath)
def date_sort_key(self, ef):
return ef.stat_result.st_mtime
def size_sort_key(self, ef):
return ef.stat_result.st_size
def resort(self, which):
k, reverse = self.file_sort_key, False
if which == 1:
k, reverse = self.date_sort_key, True
elif which == 2:
k, reverse = self.size_sort_key, True
self.refresh(key=k, reverse=reverse)
def rowCount(self, parent=None):
return len(self.files)
def file_display_name(self, rownum):
ef = self.files[rownum]
name = ef.relpath.split('/', 1)[1]
return name.replace('/', os.sep)
def item_at(self, rownum):
return self.files[rownum]
def rownum_for_relpath(self, relpath):
for i, e in enumerate(self.files):
if e.relpath == relpath:
return i
return -1
def data(self, index, role):
row = index.row()
if row >= len(self.files):
return None
if role == Qt.ItemDataRole.DisplayRole:
name = self.file_display_name(row)
e = self.item_at(row)
date = datetime.fromtimestamp(e.stat_result.st_mtime)
l2 = human_readable(e.stat_result.st_size) + date.strftime(' [%Y/%m/%d]')
return name + '\n' + l2
if role == Qt.ItemDataRole.DecorationRole:
ef = self.files[row]
fmt = ef.relpath.rpartition('.')[-1].lower()
return self.fi.icon_from_ext(fmt)
if role == NAME_ROLE:
return self.file_display_name(row)
return None
def flags(self, index):
return Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsEditable
class ListView(QListView):
files_dropped = pyqtSignal(object)
def __init__(self, parent=None):
super().__init__(parent)
self.setAcceptDrops(True)
def is_drop_event_ok(self, ev: QDropEvent):
if ev.proposedAction() in (Qt.DropAction.CopyAction, Qt.DropAction.MoveAction, Qt.DropAction.TargetMoveAction):
md = ev.mimeData()
if md.hasUrls():
for url in md.urls():
if url.isLocalFile() and os.access(url.toLocalFile(), os.R_OK):
return True
return False
def dragEnterEvent(self, ev: QDropEvent):
if self.is_drop_event_ok(ev):
ev.accept()
def dragMoveEvent(self, ev: QDropEvent):
ev.accept()
def dropEvent(self, ev):
files = []
if self.is_drop_event_ok(ev):
md = ev.mimeData()
for url in md.urls():
if url.isLocalFile() and os.access(url.toLocalFile(), os.R_OK):
files.append(url.toLocalFile())
if files:
self.files_dropped.emit(files)
class DataFilesManager(Dialog):
def __init__(self, db, book_id, parent=None):
self.db = db.new_api
self.book_title = title = self.db.field_for('title', book_id) or _('Unknown')
self.book_id = book_id
super().__init__(_('Manage data files for {}').format(title), 'manage-data-files-xx',
parent=parent, default_buttons=QDialogButtonBox.StandardButton.Close)
def sizeHint(self):
return QSize(400, 500)
def setup_ui(self):
self.l = l = QVBoxLayout(self)
self.sbla = la = QLabel(_('&Sort by:'))
self.sort_by = sb = QComboBox(self)
sb.addItems((_('Name'), _('Recency'), _('Size')))
sb.setCurrentIndex(gprefs.get('manage_data_files_last_sort_idx', 0))
sb.currentIndexChanged.connect(self.sort_changed)
sb.setFocusPolicy(Qt.FocusPolicy.NoFocus)
la.setBuddy(sb)
h = QHBoxLayout()
l.addLayout(h)
h.addWidget(la), h.addWidget(sb)
self.delegate = d = Delegate(self)
d.rename_requested.connect(self.rename_requested, type=Qt.ConnectionType.QueuedConnection)
self.fview = v = ListView(self)
v.files_dropped.connect(self.do_add_files)
v.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
v.customContextMenuRequested.connect(self.context_menu)
set_no_activate_on_click(v)
v.activated.connect(self.activated)
v.setItemDelegate(d)
l.addWidget(v)
self.files = Files(self.db.new_api, self.book_id, parent=v)
self.files.resort(self.sort_by.currentIndex())
v.setModel(self.files)
v.setEditTriggers(QAbstractItemView.EditTrigger.AnyKeyPressed | QAbstractItemView.EditTrigger.EditKeyPressed)
v.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
if self.files.rowCount():
v.setCurrentIndex(self.files.index(0))
v.selectionModel().currentChanged.connect(self.current_changed)
self.current_label = la = QLabel(self)
la.setWordWrap(True)
la.setTextFormat(Qt.TextFormat.PlainText)
self.clah = h = QHBoxLayout()
l.addLayout(h)
h.addWidget(la, stretch=100)
h.addSpacing(4)
self.open_with_label = la = QLabel('<a style="text-decoration:none" href="open_with://current">{}</a>'.format(_('Open with')))
la.setOpenExternalLinks(False)
la.setTextFormat(Qt.TextFormat.RichText)
la.linkActivated.connect(self.open_with, type=Qt.ConnectionType.QueuedConnection)
la.setVisible(False)
h.addWidget(la)
l.addWidget(self.bb)
self.add_button = b = QPushButton(QIcon.ic('plus.png'), _('&Add files'), self)
b.clicked.connect(self.add_files)
self.bb.addButton(b, QDialogButtonBox.ButtonRole.ActionRole)
self.remove_button = b = QPushButton(QIcon.ic('minus.png'), _('&Remove files'), self)
b.clicked.connect(self.remove_files)
if ismacos:
trash = _('Trash bin')
else:
trash = _('Recycle bin')
b.setToolTip(_('Move all selected files to the system {trash}.\nThey can be restored from there if needed').format(trash=trash))
self.bb.addButton(b, QDialogButtonBox.ButtonRole.ActionRole)
self.current_changed()
self.resize(self.sizeHint())
self.fview.setFocus(Qt.FocusReason.OtherFocusReason)
def context_menu(self, pos):
m = QMenu(self)
idx = self.fview.indexAt(pos)
if not idx.isValid():
return
e = self.files.item_at(idx.row())
m.addAction(QIcon.ic('modified.png'), _('Rename this file')).triggered.connect(lambda: self.fview.edit(idx))
if e:
om = self.open_with_menu(e.file_path)
if len(om.actions()) == 1:
m.addActions(om.actions())
else:
m.addMenu(om)
m.exec(self.fview.mapToGlobal(pos))
def keyPressEvent(self, ev):
if ev.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter):
return
return super().keyPressEvent(ev)
def sort_changed(self):
idx = max(0, self.sort_by.currentIndex())
gprefs.set('manage_data_files_last_sort_idx', idx)
with self.preserve_state():
self.files.resort(idx)
def current_changed(self):
idx = self.fview.currentIndex()
txt = ''
if idx.isValid():
txt = self.files.file_display_name(idx.row())
txt = prepare_string_for_xml(txt)
if txt:
self.current_label.setText(txt)
self.open_with_label.setVisible(True)
else:
self.current_label.setText('\xa0')
self.open_with_label.setVisible(False)
def open_with_menu(self, file_path):
m = QMenu(_('Open with...'), parent=self)
fmt = file_path.rpartition('.')[-1].lower()
populate_menu(m, lambda ac, entry:ac.triggered.connect(partial(self.do_open_with, file_path, entry)), fmt)
if len(m.actions()) == 0:
m.addAction(_('Open %s file with...') % fmt.upper(), partial(self.choose_open_with, file_path, fmt))
else:
m.addSeparator()
m.addAction(_('Add other application for %s files...') % fmt.upper(), partial(self.choose_open_with, file_path, fmt))
m.addAction(_('Edit Open with applications...'), partial(edit_programs, fmt, self))
return m
def choose_open_with(self, file_path, fmt):
entry = choose_program(fmt, self)
if entry is not None:
self.do_open_with(file_path, entry)
def do_open_with(self, path, entry):
run_program(entry, path, self)
def open_with(self):
idx = self.fview.currentIndex()
if not idx.isValid():
return
e = self.files.item_at(idx.row())
m = self.open_with_menu(e.file_path)
m.exec(QCursor.pos())
@property
def current_item(self):
ci = self.fview.currentIndex()
try:
return self.files.item_at(ci.row())
except Exception:
return None
@contextmanager
def preserve_state(self):
selected = set()
vs = self.fview.verticalScrollBar()
pos = vs.value()
for idx in self.fview.selectionModel().selectedRows():
e = self.files.item_at(idx.row())
selected.add(e.relpath)
current = self.current_item
try:
yield
finally:
sm = self.fview.selectionModel()
sm.clearSelection()
current_idx = None
s = QItemSelection()
for i in range(self.files.rowCount()):
e = self.files.item_at(i)
if current is not None and e.relpath == current.relpath:
current_idx = i
if e.relpath in selected:
ii = self.files.index(i)
s.select(ii, ii)
if current_idx is not None:
flags = QItemSelectionModel.SelectionFlag.Current
if current.relpath in selected:
flags |= QItemSelectionModel.SelectionFlag.Select
sm.setCurrentIndex(self.files.index(current_idx), flags)
sm.select(s, QItemSelectionModel.SelectionFlag.SelectCurrent)
self.current_changed()
vs.setValue(pos)
def add_files(self):
files = choose_files(self, 'choose-data-files-to-add', _('Choose files to add'))
if not files:
return
self.do_add_files(files)
def do_add_files(self, files):
q = self.db.are_paths_inside_book_dir(self.book_id, files, DATA_DIR_NAME)
if q:
return error_dialog(
self, _('Cannot add'), _(
'Cannot add these data files to the book because they are already in the book\'s data files folder'
), show=True, det_msg='\n'.join(q))
m = {f'{DATA_DIR_NAME}/{os.path.basename(x)}': x for x in files}
added = self.db.add_extra_files(self.book_id, m, replace=False, auto_rename=False)
collisions = set(m) - set(added)
if collisions:
if question_dialog(self, _('Replace existing files?'), _(
'The following files already exist as data files in the book. Replace them?'
) + '\n' + '\n'.join(x.partition('/')[2] for x in collisions)):
self.db.add_extra_files(self.book_id, m, replace=True, auto_rename=False)
with self.preserve_state():
self.files.refresh()
def remove_files(self):
files = []
for idx in self.fview.selectionModel().selectedRows():
files.append(self.files.item_at(idx.row()))
if not files:
return error_dialog(self, _('Cannot delete'), _('No files selected to remove'), show=True)
if len(files) == 1:
msg = _('Send the file "{}" to the Recycle Bin?').format(files[0].relpath.replace('/', os.sep))
else:
msg = _('Send the {} selected files to the Recycle Bin?').format(len(files))
if not confirm(msg, 'manage-data-files-confirm-delete'):
return
for f in files:
delete_file(f.file_path, permanent=False)
with self.preserve_state():
self.files.refresh()
def rename_requested(self, idx, new_name):
e = self.files.item_at(idx)
newrelpath = posixpath.normpath(posixpath.join(DATA_DIR_NAME, new_name.replace(os.sep, '/')))
if not newrelpath.startswith(DATA_DIR_NAME + '/'):
return error_dialog(self, _('Invalid name'), _('"{}" is not a valid file name').format(new_name), show=True)
if e.relpath not in self.db.rename_extra_files(self.book_id, {e.relpath: newrelpath}, replace=False):
if question_dialog(self, _('Replace existing file?'), _(
'Another data file with the name "{}" already exists. Replace it?').format(new_name)):
self.db.rename_extra_files(self.book_id, {e.relpath: newrelpath}, replace=True)
with self.preserve_state():
self.files.refresh()
row = self.files.rownum_for_relpath(newrelpath)
if row > -1:
idx = self.files.index(row)
self.fview.setCurrentIndex(idx)
self.fview.selectionModel().select(idx, QItemSelectionModel.SelectionFlag.SelectCurrent)
self.fview.scrollTo(idx)
def activated(self, idx):
e = self.files.item_at(idx.row())
open_local_file(e.file_path)
if __name__ == '__main__':
from calibre.gui2 import Application
from calibre.library import db as di
app = Application([])
dfm = DataFilesManager(di(os.path.expanduser('~/test library')), 1893)
dfm.exec()
| 18,013 | Python | .py | 412 | 34.376214 | 142 | 0.616503 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,034 | opml.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/opml.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>'
from collections import defaultdict, namedtuple
from operator import itemgetter
from lxml import etree
from qt.core import QCheckBox, QDialog, QDialogButtonBox, QFormLayout, QHBoxLayout, QIcon, QLineEdit, QSpinBox, Qt, QToolButton
from calibre.gui2 import choose_files, error_dialog
from calibre.utils.icu import sort_key
from calibre.utils.xml_parse import safe_xml_fromstring
Group = namedtuple('Group', 'title feeds')
def uniq(vals, kmap=lambda x:x):
''' Remove all duplicates from vals, while preserving order. kmap must be a
callable that returns a hashable value for every item in vals '''
vals = vals or ()
lvals = (kmap(x) for x in vals)
seen = set()
seen_add = seen.add
return tuple(x for x, k in zip(vals, lvals) if k not in seen and not seen_add(k))
def import_opml(raw, preserve_groups=True):
root = safe_xml_fromstring(raw)
groups = defaultdict(list)
ax = etree.XPath('ancestor::outline[@title or @text]')
for outline in root.xpath('//outline[@type="rss" and @xmlUrl]'):
url = outline.get('xmlUrl')
parent = outline.get('title', '') or url
title = parent if ('title' in outline.attrib and parent) else None
if preserve_groups:
for ancestor in ax(outline):
if ancestor.get('type', None) != 'rss':
text = ancestor.get('title') or ancestor.get('text')
if text:
parent = text
break
groups[parent].append((title, url))
for title in sorted(groups, key=sort_key):
yield Group(title, uniq(groups[title], kmap=itemgetter(1)))
class ImportOPML(QDialog):
def __init__(self, parent=None):
QDialog.__init__(self, parent=parent)
self.l = l = QFormLayout(self)
self.setLayout(l)
self.setWindowTitle(_('Import OPML file'))
self.setWindowIcon(QIcon.ic('opml.png'))
self.h = h = QHBoxLayout()
self.path = p = QLineEdit(self)
p.setMinimumWidth(300)
p.setPlaceholderText(_('Path to OPML file'))
h.addWidget(p)
self.cfb = b = QToolButton(self)
b.setIcon(QIcon.ic('document_open.png'))
b.setToolTip(_('Browse for OPML file'))
b.clicked.connect(self.choose_file)
h.addWidget(b)
l.addRow(_('&OPML file:'), h)
l.labelForField(h).setBuddy(p)
b.setFocus(Qt.FocusReason.OtherFocusReason)
self._articles_per_feed = a = QSpinBox(self)
a.setMinimum(1), a.setMaximum(1000), a.setValue(100)
a.setToolTip(_('Maximum number of articles to download per RSS feed'))
l.addRow(_('&Maximum articles per feed:'), a)
self._oldest_article = o = QSpinBox(self)
o.setMinimum(1), o.setMaximum(3650), o.setValue(7)
o.setSuffix(_(' days'))
o.setToolTip(_('Articles in the RSS feeds older than this will be ignored'))
l.addRow(_('&Oldest article:'), o)
self.preserve_groups = g = QCheckBox(_('Preserve groups in the OPML file'))
g.setToolTip('<p>' + _(
'If enabled, every group of feeds in the OPML file will be converted into a single recipe. Otherwise every feed becomes its own recipe'))
g.setChecked(True)
l.addRow(g)
self._replace_existing = r = QCheckBox(_('Replace existing recipes'))
r.setToolTip('<p>' + _(
'If enabled, any existing recipes with the same titles as entries in the OPML file will be replaced.'
' Otherwise, new entries with modified titles will be created'))
r.setChecked(True)
l.addRow(r)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel)
bb.accepted.connect(self.accept), bb.rejected.connect(self.reject)
l.addRow(bb)
self.recipes = ()
@property
def articles_per_feed(self):
return self._articles_per_feed.value()
@property
def oldest_article(self):
return self._oldest_article.value()
@property
def replace_existing(self):
return self._replace_existing.isChecked()
def choose_file(self):
opml_files = choose_files(
self, 'opml-select-dialog', _('Select OPML file'), filters=[(_('OPML files'), ['opml'])],
all_files=False, select_only_single_file=True)
if opml_files:
self.path.setText(opml_files[0])
def accept(self):
path = str(self.path.text())
if not path:
return error_dialog(self, _('Path not specified'), _(
'You must specify the path to the OPML file to import'), show=True)
with open(path, 'rb') as f:
raw = f.read()
self.recipes = tuple(import_opml(raw, self.preserve_groups.isChecked()))
if len(self.recipes) == 0:
return error_dialog(self, _('No feeds found'), _(
'No importable RSS feeds found in the OPML file'), show=True)
QDialog.accept(self)
if __name__ == '__main__':
import sys
for group in import_opml(open(sys.argv[-1], 'rb').read()):
print(group.title)
for title, url in group.feeds:
print(f'\t{title} - {url}')
print()
| 5,357 | Python | .py | 115 | 38.095652 | 149 | 0.629196 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,035 | restore_library.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/restore_library.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2011, Kovid Goyal <kovid at kovidgoyal.net>
from qt.core import QDialog, QDialogButtonBox, QLabel, QProgressBar, QSize, Qt, QTimer, QVBoxLayout, pyqtSignal
from calibre import force_unicode
from calibre.constants import filesystem_encoding
from calibre.gui2 import error_dialog, info_dialog, question_dialog, warning_dialog
class DBRestore(QDialog):
update_signal = pyqtSignal(object, object)
def __init__(self, parent, library_path, wait_time=2):
QDialog.__init__(self, parent)
self.l = QVBoxLayout()
self.setLayout(self.l)
self.l1 = QLabel('<b>'+_('Restoring database from backups, do not'
' interrupt, this will happen in multiple stages')+'...')
self.setWindowTitle(_('Restoring database'))
self.l.addWidget(self.l1)
self.pb = QProgressBar(self)
self.l.addWidget(self.pb)
self.pb.setMaximum(0)
self.pb.setMinimum(0)
self.msg = QLabel('')
self.l.addWidget(self.msg)
self.msg.setWordWrap(True)
self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel)
self.l.addWidget(self.bb)
self.bb.rejected.connect(self.confirm_cancel)
self.resize(self.sizeHint() + QSize(100, 50))
self.error = None
self.rejected = False
self.library_path = library_path
self.update_signal.connect(self.do_update, type=Qt.ConnectionType.QueuedConnection)
from calibre.db.restore import Restore
self.restorer = Restore(library_path, self)
self.restorer.daemon = True
# Give the metadata backup thread time to stop
QTimer.singleShot(wait_time * 1000, self.start)
def start(self):
self.restorer.start()
QTimer.singleShot(10, self.update)
def reject(self):
self.rejected = True
self.restorer.progress_callback = lambda x, y: x
QDialog.reject(self)
def confirm_cancel(self):
if question_dialog(self, _('Are you sure?'), _(
'The restore has not completed, are you sure you want to cancel?'),
default_yes=False, override_icon='dialog_warning.png'):
self.reject()
def update(self):
if self.restorer.is_alive():
QTimer.singleShot(10, self.update)
else:
self.restorer.progress_callback = lambda x, y: x
self.accept()
def __call__(self, msg, step):
self.update_signal.emit(msg, step)
def do_update(self, msg, step):
if msg is None:
self.pb.setMaximum(step)
else:
self.msg.setText(msg)
self.pb.setValue(step)
def _show_success_msg(restorer, parent=None):
r = restorer
olddb = _('The old database was saved as: %s')%force_unicode(r.olddb,
filesystem_encoding)
if r.errors_occurred:
warning_dialog(parent, _('Success'),
_('Restoring the database succeeded with some warnings'
' click "Show details" to see the details. %s')%olddb,
det_msg=r.report, show=True)
else:
info_dialog(parent, _('Success'),
_('Restoring database was successful. %s')%olddb, show=True,
show_copy_button=False)
def restore_database(db, parent=None):
if not question_dialog(parent, _('Are you sure?'), '<p>'+
_('Your list of books, with all their metadata is '
'stored in a single file, called a database. '
'In addition, metadata for each individual '
'book is stored in that books\' folder, as '
'a backup.'
'<p>This operation will rebuild '
'the database from the individual book '
'metadata. This is useful if the '
'database has been corrupted and you get a '
'blank list of books.'
'<p>Do you want to restore the database?')):
return False
db.close()
d = DBRestore(parent, db.library_path)
d.exec()
r = d.restorer
d.restorer = None
if d.rejected:
return True
if r.tb is not None:
error_dialog(parent, _('Failed'),
_('Restoring database failed, click "Show details" to see details'),
det_msg=r.tb, show=True)
else:
_show_success_msg(r, parent=parent)
return True
def repair_library_at(library_path, parent=None, wait_time=2):
d = DBRestore(parent, library_path, wait_time=wait_time)
d.exec()
if d.rejected:
return False
r = d.restorer
if r.tb is not None:
error_dialog(parent, _('Failed to repair library'),
_('Restoring database failed, click "Show details" to see details'),
det_msg=r.tb, show=True)
return False
_show_success_msg(r, parent=parent)
return True
if __name__ == '__main__':
from calibre.gui2 import Application
app = Application([])
repair_library_at('/t')
del app
| 5,021 | Python | .py | 121 | 32.702479 | 111 | 0.622719 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,036 | choose_plugin_toolbars.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/choose_plugin_toolbars.py | #!/usr/bin/env python
__copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net'
__docformat__ = 'restructuredtext en'
__license__ = 'GPL v3'
from qt.core import QAbstractItemView, QDialog, QDialogButtonBox, QLabel, QListWidget, QSizePolicy, QVBoxLayout
class ChoosePluginToolbarsDialog(QDialog):
def __init__(self, parent, plugin, locations):
QDialog.__init__(self, parent)
self.locations = locations
self.setWindowTitle(
_('Add "%s" to toolbars or menus')%plugin.name)
self._layout = QVBoxLayout(self)
self.setLayout(self._layout)
self._header_label = QLabel(
_('Select the toolbars and/or menus to add <b>%s</b> to:') %
plugin.name)
self._layout.addWidget(self._header_label)
self._locations_list = QListWidget(self)
self._locations_list.setSelectionMode(QAbstractItemView.SelectionMode.MultiSelection)
sizePolicy = QSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
self._locations_list.setSizePolicy(sizePolicy)
for key, text in locations:
self._locations_list.addItem(text)
if key in {'toolbar', 'toolbar-device'}:
self._locations_list.item(self._locations_list.count()-1
).setSelected(True)
self._layout.addWidget(self._locations_list)
self._footer_label = QLabel(
_('You can also customise the plugin locations '
'using <b>Preferences -> Interface -> Toolbars</b>'))
self._layout.addWidget(self._footer_label)
button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok |
QDialogButtonBox.StandardButton.Cancel)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
self._layout.addWidget(button_box)
self.resize(self.sizeHint())
def selected_locations(self):
selected = []
for row in self._locations_list.selectionModel().selectedRows():
selected.append(self.locations[row.row()])
return selected
| 2,210 | Python | .py | 44 | 40.5 | 111 | 0.660316 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,037 | metadata_bulk.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/metadata_bulk.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2008, Kovid Goyal <kovid at kovidgoyal.net>
import numbers
from collections import defaultdict, namedtuple
from io import BytesIO
from threading import Thread
import regex
from qt.core import (
QComboBox,
QCompleter,
QDateTime,
QDialog,
QDialogButtonBox,
QFont,
QGridLayout,
QIcon,
QInputDialog,
QLabel,
QLineEdit,
QProgressBar,
QSize,
Qt,
QVBoxLayout,
pyqtSignal,
)
from calibre import human_readable, prints
from calibre.constants import DEBUG
from calibre.db import _get_next_series_num_for_list
from calibre.ebooks.metadata import authors_to_string, string_to_authors, title_sort
from calibre.ebooks.metadata.book.formatter import SafeFormat
from calibre.ebooks.metadata.opf2 import OPF
from calibre.gui2 import UNDEFINED_QDATETIME, FunctionDispatcher, error_dialog, gprefs, info_dialog, question_dialog
from calibre.gui2.custom_column_widgets import populate_metadata_page
from calibre.gui2.dialogs.metadata_bulk_ui import Ui_MetadataBulkDialog
from calibre.gui2.dialogs.tag_editor import TagEditor
from calibre.gui2.dialogs.template_line_editor import TemplateLineEditor
from calibre.gui2.widgets import LineEditECM, setup_status_actions, update_status_actions
from calibre.startup import connect_lambda
from calibre.utils.config import JSONConfig, dynamic, prefs, tweaks
from calibre.utils.date import internal_iso_format_string, qt_to_dt
from calibre.utils.icu import capitalize, sort_key
from calibre.utils.icu import lower as icu_lower
from calibre.utils.icu import upper as icu_upper
from calibre.utils.localization import ngettext
from calibre.utils.titlecase import titlecase
from polyglot.builtins import error_message, iteritems, itervalues, native_string_type
Settings = namedtuple('Settings',
'remove_all remove add au aus do_aus rating pub do_series do_autonumber '
'do_swap_ta do_remove_conv do_auto_author series do_series_restart series_start_value series_increment '
'do_title_case cover_action clear_series clear_pub pubdate adddate do_title_sort languages clear_languages '
'restore_original comments generate_cover_settings read_file_metadata casing_algorithm do_compress_cover compress_cover_quality '
'tag_map_rules author_map_rules publisher_map_rules'
)
null = object()
class Caser(LineEditECM):
def __init__(self, title):
self.title = title
def text(self):
return self.title
def setText(self, text):
self.title = text
def hasSelectedText(self):
return False
class MyBlockingBusy(QDialog): # {{{
all_done = pyqtSignal()
progress_update = pyqtSignal(int)
progress_finished_cur_step = pyqtSignal()
progress_next_step_range = pyqtSignal(int)
def __init__(self, args, ids, db, refresh_books, cc_widgets, s_r_func, do_sr, sr_calls, parent=None, window_title=_('Working')):
QDialog.__init__(self, parent)
self._layout = l = QVBoxLayout()
self.setLayout(l)
self.cover_sizes = {'old': 0, 'new': 0}
# Every Path that will be taken in do_all
options = [
args.cover_action == 'fromfmt' or args.read_file_metadata,
args.do_swap_ta, args.do_title_case and not
args.do_swap_ta, args.do_title_sort, bool(args.au),
args.do_auto_author, bool(args.aus) and args.do_aus,
args.cover_action == 'remove' or args.cover_action ==
'generate' or args.cover_action == 'trim' or
args.cover_action == 'clone', args.restore_original,
args.rating != -1, args.clear_pub, bool(args.pub),
args.clear_series, args.pubdate is not None, args.adddate
is not None, args.do_series, bool(args.series) and
args.do_autonumber, args.comments is not null,
args.do_remove_conv, args.clear_languages, args.remove_all,
bool(do_sr), args.do_compress_cover
]
self.selected_options = sum(options)
if args.tag_map_rules:
self.selected_options += 1
if args.author_map_rules:
self.selected_options += 1
if args.publisher_map_rules:
self.selected_options += 1
if DEBUG:
print("Number of steps for bulk metadata: %d" % self.selected_options)
print("Optionslist: ")
print(options)
self.msg = QLabel(_('Processing %d books, please wait...') % len(ids))
self.font = QFont()
self.font.setPointSize(self.font.pointSize() + 8)
self.msg.setFont(self.font)
self.current_step_pb = QProgressBar(self)
self.current_step_pb.setFormat(_("Current step progress: %p %"))
if self.selected_options > 1:
# More than one Option needs to be done! Add Overall ProgressBar
self.overall_pb = QProgressBar(self)
self.overall_pb.setRange(0, self.selected_options)
self.overall_pb.setValue(0)
self.overall_pb.setFormat(_("Step %v/%m"))
self._layout.addWidget(self.overall_pb)
self._layout.addSpacing(15)
self.current_option = 0
self.current_step_value = 0
self._layout.addWidget(self.current_step_pb)
self._layout.addSpacing(15)
self._layout.addWidget(self.msg, 0, Qt.AlignmentFlag.AlignHCenter)
self.setWindowTitle(window_title + '...')
self.setMinimumWidth(200)
self.resize(self.sizeHint())
self.error = None
self.all_done.connect(self.on_all_done, type=Qt.ConnectionType.QueuedConnection)
self.progress_update.connect(self.on_progress_update, type=Qt.ConnectionType.QueuedConnection)
self.progress_finished_cur_step.connect(self.on_progress_finished_cur_step, type=Qt.ConnectionType.QueuedConnection)
self.progress_next_step_range.connect(self.on_progress_next_step_range, type=Qt.ConnectionType.QueuedConnection)
self.args, self.ids = args, ids
self.db, self.cc_widgets = db, cc_widgets
self.s_r_func = FunctionDispatcher(s_r_func)
self.do_sr = do_sr
self.sr_calls = sr_calls
self.refresh_books = refresh_books
def accept(self):
pass
def reject(self):
pass
def on_progress_update(self, processed_steps):
"""
This signal should be emitted if a step can be traced with numbers.
"""
self.current_step_value += processed_steps
self.current_step_pb.setValue(self.current_step_value)
def on_progress_finished_cur_step(self):
if self.selected_options > 1:
self.current_option += 1
self.overall_pb.setValue(self.current_option)
def on_progress_next_step_range(self, steps_of_progress):
"""
If steps_of_progress equals 0 results this in a indetermined ProgressBar
Otherwise the range is from 0..steps_of_progress
"""
self.current_step_value = 0
self.current_step_pb.setRange(0, steps_of_progress)
def on_all_done(self):
if not self.error:
# The cc widgets can only be accessed in the GUI thread
try:
for w in self.cc_widgets:
w.commit(self.ids)
except Exception as err:
import traceback
self.error = (err, traceback.format_exc())
QDialog.accept(self)
def exec(self):
self.thread = Thread(target=self.do_it)
self.thread.start()
return QDialog.exec(self)
exec_ = exec
def do_it(self):
try:
self.do_all()
except Exception as err:
import traceback
try:
err = str(err)
except:
err = repr(err)
self.error = (err, traceback.format_exc())
self.all_done.emit()
def read_file_metadata(self, args):
from calibre.utils.ipc.simple_worker import offload_worker
db = self.db.new_api
worker = offload_worker()
try:
self.progress_next_step_range.emit(len(self.ids))
for book_id in self.ids:
fmts = db.formats(book_id, verify_formats=False)
paths = list(filter(None, [db.format_abspath(book_id, fmt) for fmt in fmts]))
if paths:
ret = worker(
'calibre.ebooks.metadata.worker', 'read_metadata_bulk',
args.read_file_metadata, args.cover_action == 'fromfmt', paths)
if ret['tb'] is not None:
prints(ret['tb'])
else:
ans = ret['result']
opf, cdata = ans['opf'], ans['cdata']
if opf is not None:
try:
mi = OPF(BytesIO(opf), populate_spine=False, try_to_guess_cover=False).to_book_metadata()
except Exception:
import traceback
traceback.print_exc()
else:
db.set_metadata(book_id, mi, allow_case_change=True)
if cdata is not None:
try:
db.set_cover({book_id: cdata})
except Exception:
import traceback
traceback.print_exc()
self.progress_update.emit(1)
self.progress_finished_cur_step.emit()
finally:
worker.shutdown()
def do_all(self):
cache = self.db.new_api
args = self.args
from_file = args.cover_action == 'fromfmt' or args.read_file_metadata
if args.author_map_rules:
from calibre.ebooks.metadata.author_mapper import compile_rules
args = args._replace(author_map_rules=compile_rules(args.author_map_rules))
if from_file:
old = prefs['read_file_metadata']
if not old:
prefs['read_file_metadata'] = True
try:
self.read_file_metadata(args)
finally:
if old != prefs['read_file_metadata']:
prefs['read_file_metadata'] = old
def change_title_casing(val):
caser = Caser(val)
getattr(caser, args.casing_algorithm)()
return caser.title
# Title and authors
if args.do_swap_ta:
self.progress_next_step_range.emit(3)
title_map = cache.all_field_for('title', self.ids)
authors_map = cache.all_field_for('authors', self.ids)
self.progress_update.emit(1)
def new_title(authors):
ans = authors_to_string(authors)
return change_title_casing(ans) if args.do_title_case else ans
new_title_map = {bid:new_title(authors) for bid, authors in iteritems(authors_map)}
new_authors_map = {bid:string_to_authors(title) for bid, title in iteritems(title_map)}
self.progress_update.emit(1)
cache.set_field('authors', new_authors_map)
cache.set_field('title', new_title_map)
self.progress_update.emit(1)
self.progress_finished_cur_step.emit()
if args.do_title_case and not args.do_swap_ta:
self.progress_next_step_range.emit(0)
title_map = cache.all_field_for('title', self.ids)
cache.set_field('title', {bid:change_title_casing(title) for bid, title in iteritems(title_map)})
self.progress_finished_cur_step.emit()
if args.do_title_sort:
self.progress_next_step_range.emit(2)
lang_map = cache.all_field_for('languages', self.ids)
title_map = cache.all_field_for('title', self.ids)
self.progress_update.emit(1)
def get_sort(book_id):
if args.languages:
lang = args.languages[0]
else:
try:
lang = lang_map[book_id][0]
except (KeyError, IndexError, TypeError, AttributeError):
lang = 'eng'
return title_sort(title_map[book_id], lang=lang)
cache.set_field('sort', {bid:get_sort(bid) for bid in self.ids})
self.progress_update.emit(1)
self.progress_finished_cur_step.emit()
if args.au:
self.progress_next_step_range.emit(0)
self.processed_books = 0
authors = string_to_authors(args.au)
cache.set_field('authors', {bid: authors for bid in self.ids})
self.progress_finished_cur_step.emit()
if args.do_auto_author:
self.progress_next_step_range.emit(0)
aus_map = cache.author_sort_strings_for_books(self.ids)
cache.set_field('author_sort', {book_id: ' & '.join(aus_map[book_id]) for book_id in aus_map})
self.progress_finished_cur_step.emit()
if args.aus and args.do_aus:
self.progress_next_step_range.emit(0)
cache.set_field('author_sort', {bid:args.aus for bid in self.ids})
self.progress_finished_cur_step.emit()
if args.author_map_rules:
self.progress_next_step_range.emit(0)
from calibre.ebooks.metadata.author_mapper import map_authors
authors_map = cache.all_field_for('authors', self.ids)
changed, sorts = {}, {}
for book_id, authors in authors_map.items():
new_authors = map_authors(authors, args.author_map_rules)
if tuple(new_authors) != tuple(authors):
changed[book_id] = new_authors
sorts[book_id] = cache.author_sort_from_authors(new_authors)
cache.set_field('authors', changed)
cache.set_field('author_sort', sorts)
self.progress_finished_cur_step.emit()
# Covers
if args.cover_action == 'remove':
self.progress_next_step_range.emit(0)
cache.set_cover({bid: None for bid in self.ids})
self.progress_finished_cur_step.emit()
elif args.cover_action == 'generate':
self.progress_next_step_range.emit(len(self.ids))
from calibre.ebooks.covers import generate_cover
for book_id in self.ids:
mi = self.db.get_metadata(book_id, index_is_id=True)
cdata = generate_cover(mi, prefs=args.generate_cover_settings)
cache.set_cover({book_id:cdata})
self.progress_update.emit(1)
self.progress_finished_cur_step.emit()
elif args.cover_action == 'trim':
self.progress_next_step_range.emit(len(self.ids))
from calibre.utils.img import image_from_data, image_to_data, remove_borders_from_image
for book_id in self.ids:
cdata = cache.cover(book_id)
if cdata:
img = image_from_data(cdata)
nimg = remove_borders_from_image(img)
if nimg is not img:
cdata = image_to_data(nimg)
cache.set_cover({book_id:cdata})
self.progress_update.emit(1)
self.progress_finished_cur_step.emit()
elif args.cover_action == 'clone':
self.progress_next_step_range.emit(len(self.ids))
cdata = None
for book_id in self.ids:
cdata = cache.cover(book_id)
if cdata:
break
self.progress_update.emit(1)
self.progress_finished_cur_step.emit()
if cdata:
self.progress_next_step_range.emit(0)
cache.set_cover({bid:cdata for bid in self.ids if bid != book_id})
self.progress_finished_cur_step.emit()
if args.restore_original:
self.progress_next_step_range.emit(len(self.ids))
for book_id in self.ids:
formats = cache.formats(book_id)
originals = tuple(x.upper() for x in formats if x.upper().startswith('ORIGINAL_'))
for ofmt in originals:
cache.restore_original_format(book_id, ofmt)
self.progress_update.emit(1)
self.progress_finished_cur_step.emit()
# Various fields
if args.rating != -1:
self.progress_next_step_range.emit(0)
cache.set_field('rating', {bid: args.rating for bid in self.ids})
self.progress_finished_cur_step.emit()
if args.clear_pub:
self.progress_next_step_range.emit(0)
cache.set_field('publisher', {bid: '' for bid in self.ids})
self.progress_finished_cur_step.emit()
if args.pub:
self.progress_next_step_range.emit(0)
cache.set_field('publisher', {bid: args.pub for bid in self.ids})
self.progress_finished_cur_step.emit()
if args.publisher_map_rules:
self.progress_next_step_range.emit(0)
from calibre.ebooks.metadata.tag_mapper import map_tags
publishers_map = cache.all_field_for('publisher', self.ids)
changed = {}
for book_id, publisher in publishers_map.items():
new_publishers = map_tags([publisher], args.publisher_map_rules)
new_publisher = new_publishers[0] if new_publishers else ''
if new_publisher != publisher:
changed[book_id] = new_publisher
cache.set_field('publisher', changed)
self.progress_finished_cur_step.emit()
if args.clear_series:
self.progress_next_step_range.emit(0)
cache.set_field('series', {bid: '' for bid in self.ids})
cache.set_field('series_index', {bid:1.0 for bid in self.ids})
self.progress_finished_cur_step.emit()
if args.pubdate is not None:
self.progress_next_step_range.emit(0)
cache.set_field('pubdate', {bid: args.pubdate for bid in self.ids})
self.progress_finished_cur_step.emit()
if args.adddate is not None:
self.progress_next_step_range.emit(0)
cache.set_field('timestamp', {bid: args.adddate for bid in self.ids})
self.progress_finished_cur_step.emit()
if args.do_series:
self.progress_next_step_range.emit(0)
sval = args.series_start_value if args.do_series_restart else cache.get_next_series_num_for(args.series, current_indices=True)
cache.set_field('series', {bid:args.series for bid in self.ids})
self.progress_finished_cur_step.emit()
if not args.series:
self.progress_next_step_range.emit(0)
cache.set_field('series_index', {bid:1.0 for bid in self.ids})
self.progress_finished_cur_step.emit()
else:
def next_series_num(bid, i):
if args.do_series_restart:
return sval + (i * args.series_increment)
next_num = _get_next_series_num_for_list(sorted(itervalues(sval)), unwrap=False)
sval[bid] = next_num
return next_num
smap = {bid:next_series_num(bid, i) for i, bid in enumerate(self.ids)}
if args.do_autonumber:
self.progress_next_step_range.emit(0)
cache.set_field('series_index', smap)
self.progress_finished_cur_step.emit()
elif tweaks['series_index_auto_increment'] != 'no_change':
self.progress_next_step_range.emit(0)
cache.set_field('series_index', {bid:1.0 for bid in self.ids})
self.progress_finished_cur_step.emit()
if args.comments is not null:
self.progress_next_step_range.emit(0)
cache.set_field('comments', {bid: args.comments for bid in self.ids})
self.progress_finished_cur_step.emit()
if args.do_remove_conv:
self.progress_next_step_range.emit(0)
cache.delete_conversion_options(self.ids)
self.progress_finished_cur_step.emit()
if args.clear_languages:
self.progress_next_step_range.emit(0)
cache.set_field('languages', {bid: () for bid in self.ids})
self.progress_finished_cur_step.emit()
elif args.languages:
self.progress_next_step_range.emit(0)
cache.set_field('languages', {bid: args.languages for bid in self.ids})
self.progress_finished_cur_step.emit()
if args.remove_all:
self.progress_next_step_range.emit(0)
cache.set_field('tags', {bid: () for bid in self.ids})
self.progress_finished_cur_step.emit()
if args.add or args.remove:
self.progress_next_step_range.emit(0)
self.db.bulk_modify_tags(self.ids, add=args.add, remove=args.remove)
self.progress_finished_cur_step.emit()
if args.tag_map_rules:
self.progress_next_step_range.emit(0)
from calibre.ebooks.metadata.tag_mapper import map_tags
tags_map = cache.all_field_for('tags', self.ids)
changed = {}
for book_id, tags in tags_map.items():
new_tags = map_tags(tags, args.tag_map_rules)
if new_tags != tags:
changed[book_id] = new_tags
cache.set_field('tags', changed)
self.progress_finished_cur_step.emit()
if args.do_compress_cover:
self.progress_next_step_range.emit(len(self.ids))
def pc(book_id, old_sz, new_sz):
if isinstance(new_sz, int):
self.cover_sizes['old'] += old_sz
self.cover_sizes['new'] += new_sz
self.progress_update.emit(1)
self.db.new_api.compress_covers(self.ids, args.compress_cover_quality, pc)
self.progress_finished_cur_step.emit()
if self.do_sr:
self.progress_next_step_range.emit(len(self.ids))
for book_id in self.ids:
ans = self.s_r_func(book_id)
if isinstance(ans, bool) and not ans:
break
self.progress_update.emit(1)
if self.sr_calls:
self.progress_next_step_range.emit(len(self.sr_calls))
self.progress_update.emit(0)
for field, book_id_val_map in iteritems(self.sr_calls):
self.refresh_books.update(self.db.new_api.set_field(field, book_id_val_map))
self.progress_update.emit(1)
self.progress_finished_cur_step.emit()
self.progress_finished_cur_step.emit()
# }}}
class MetadataBulkDialog(QDialog, Ui_MetadataBulkDialog):
s_r_functions = {'' : lambda x: x,
_('Lower Case') : lambda x: icu_lower(x),
_('Upper Case') : lambda x: icu_upper(x),
_('Title Case') : lambda x: titlecase(x),
_('Capitalize') : lambda x: capitalize(x),
}
s_r_match_modes = [_('Character match'),
_('Regular expression'),
]
s_r_replace_modes = [_('Replace field'),
_('Prepend to field'),
_('Append to field'),
]
def __init__(self, window, rows, model, starting_tab, refresh_books):
QDialog.__init__(self, window)
self.setupUi(self)
setup_status_actions(self.test_result)
self.series.set_sort_func(title_sort)
self.model = model
self.db = model.db
self.refresh_book_list.setChecked(gprefs['refresh_book_list_on_bulk_edit'])
self.refresh_book_list.toggled.connect(self.save_refresh_booklist)
self.ids = [self.db.id(r) for r in rows]
self.first_title = self.db.title(self.ids[0], index_is_id=True)
self.cover_clone.setToolTip(str(self.cover_clone.toolTip()) + ' (%s)' % self.first_title)
self.setWindowTitle(ngettext(
'Editing metadata for one book',
'Editing metadata for {} books', len(rows)).format(len(rows)))
self.write_series = False
self.changed = False
self.refresh_books = refresh_books
self.comments = null
self.comments_button.clicked.connect(self.set_comments)
all_tags = self.db.new_api.all_field_names('tags')
self.tags.update_items_cache(all_tags)
self.tags.set_elide_mode(Qt.TextElideMode.ElideMiddle)
self.remove_tags.update_items_cache(all_tags)
self.remove_tags.set_elide_mode(Qt.TextElideMode.ElideMiddle)
self.initialize_combos()
self.series.currentIndexChanged.connect(self.series_changed)
connect_lambda(self.rating.currentIndexChanged, self, lambda self:self.apply_rating.setChecked(True))
self.series.editTextChanged.connect(self.series_changed)
self.tag_editor_button.clicked.connect(self.tag_editor)
self.autonumber_series.stateChanged[int].connect(self.auto_number_changed)
pubdate_format = tweaks['gui_pubdate_display_format']
if pubdate_format == 'iso':
pubdate_format = internal_iso_format_string()
if pubdate_format is not None:
self.pubdate.setDisplayFormat(pubdate_format)
self.pubdate.setSpecialValueText(_('Undefined'))
self.clear_pubdate_button.clicked.connect(self.clear_pubdate)
self.pubdate.dateTimeChanged.connect(self.do_apply_pubdate)
self.adddate.setDateTime(QDateTime.currentDateTime())
adddate_format = tweaks['gui_timestamp_display_format']
if adddate_format == 'iso':
adddate_format = internal_iso_format_string()
if adddate_format is not None:
self.adddate.setDisplayFormat(adddate_format)
self.adddate.setSpecialValueText(_('Undefined'))
self.clear_adddate_button.clicked.connect(self.clear_adddate)
self.adddate.dateTimeChanged.connect(self.do_apply_adddate)
self.casing_algorithm.addItems([
_('Title case'), _('Capitalize'), _('Upper case'), _('Lower case'), _('Swap case')
])
self.casing_map = ['title_case', 'capitalize', 'upper_case', 'lower_case', 'swap_case']
prevca = gprefs.get('bulk-mde-casing-algorithm', 'title_case')
idx = max(0, self.casing_map.index(prevca))
self.casing_algorithm.setCurrentIndex(idx)
self.casing_algorithm.setEnabled(False)
connect_lambda(
self.change_title_to_title_case.toggled, self,
lambda self: self.casing_algorithm.setEnabled(self.change_title_to_title_case.isChecked()))
if len(self.db.custom_field_keys(include_composites=False)) == 0:
self.central_widget.removeTab(1)
else:
self.create_custom_column_editors()
self.prepare_search_and_replace()
self.button_box.clicked.connect(self.button_clicked)
self.button_box.button(QDialogButtonBox.StandardButton.Apply).setToolTip(_(
'Immediately make all changes without closing the dialog. '
'This operation cannot be canceled or undone'))
self.do_again = False
self.restore_geometry(gprefs, 'bulk_metadata_window_geometry')
self.languages.init_langs(self.db)
self.languages.setEditText('')
self.authors.setFocus(Qt.FocusReason.OtherFocusReason)
self.generate_cover_settings = None
self.button_config_cover_gen.clicked.connect(self.customize_cover_generation)
self.button_transform_tags.clicked.connect(self.transform_tags)
self.button_transform_authors.clicked.connect(self.transform_authors)
self.button_transform_publishers.clicked.connect(self.transform_publishers)
self.tag_map_rules = self.author_map_rules = self.publisher_map_rules = ()
tuple(map(lambda b: (b.clicked.connect(self.clear_transform_rules_for), b.setIcon(QIcon.ic('clear_left.png')), b.setToolTip(_(
'Clear the rules'))),
(self.button_clear_tags_rules, self.button_clear_authors_rules, self.button_clear_publishers_rules)
))
self.update_transform_labels()
if starting_tab < 0:
starting_tab = gprefs.get('bulk_metadata_window_tab', 0)
self.central_widget.setCurrentIndex(starting_tab)
self.exec()
def update_transform_labels(self):
def f(label, count):
if count:
label.setText(_('Number of rules: {}').format(count))
else:
label.setText(_('There are currently no rules'))
f(self.label_transform_tags, len(self.tag_map_rules))
f(self.label_transform_authors, len(self.author_map_rules))
f(self.label_transform_publishers, len(self.publisher_map_rules))
self.button_clear_tags_rules.setVisible(bool(self.tag_map_rules))
self.button_clear_authors_rules.setVisible(bool(self.author_map_rules))
self.button_clear_publishers_rules.setVisible(bool(self.publisher_map_rules))
def clear_transform_rules_for(self):
n = self.sender().objectName()
if 'tags' in n:
self.tag_map_rules = ()
elif 'authors' in n:
self.author_map_rules = ()
elif 'publisher' in n:
self.publisher_map_rules = ()
self.update_transform_labels()
def _change_transform_rules(self, RulesDialog, which):
d = RulesDialog(self)
pref = f'{which}_map_on_bulk_metadata_rules'
previously_used = gprefs.get(pref)
if previously_used:
d.rules = previously_used
if d.exec() == QDialog.DialogCode.Accepted:
setattr(self, f'{which}_map_rules', d.rules)
gprefs.set(pref, d.rules)
self.update_transform_labels()
def transform_tags(self):
from calibre.gui2.tag_mapper import RulesDialog
self._change_transform_rules(RulesDialog, 'tag')
def transform_authors(self):
from calibre.gui2.author_mapper import RulesDialog
self._change_transform_rules(RulesDialog, 'author')
def transform_publishers(self):
from calibre.gui2.publisher_mapper import RulesDialog
self._change_transform_rules(RulesDialog, 'publisher')
def sizeHint(self):
geom = self.screen().availableSize()
nh, nw = max(300, geom.height()-50), max(400, geom.width()-70)
return QSize(nw, nh)
def customize_cover_generation(self):
from calibre.gui2.covers import CoverSettingsDialog
d = CoverSettingsDialog(parent=self)
if d.exec() == QDialog.DialogCode.Accepted:
self.generate_cover_settings = d.prefs_for_rendering
def set_comments(self):
from calibre.gui2.dialogs.comments_dialog import CommentsDialog
d = CommentsDialog(self, '' if self.comments is null else (self.comments or ''), _('Comments'))
if d.exec() == QDialog.DialogCode.Accepted:
self.comments = d.textbox.html
b = self.comments_button
b.setStyleSheet('QPushButton { font-weight: bold }')
if str(b.text())[-1] != '*':
b.setText(str(b.text()) + ' *')
def save_refresh_booklist(self, *args):
gprefs['refresh_book_list_on_bulk_edit'] = bool(self.refresh_book_list.isChecked())
def save_state(self, *args):
self.save_geometry(gprefs, 'bulk_metadata_window_geometry')
gprefs['bulk_metadata_window_tab'] = self.central_widget.currentIndex()
def do_apply_pubdate(self, *args):
self.apply_pubdate.setChecked(True)
def clear_pubdate(self, *args):
self.pubdate.setDateTime(UNDEFINED_QDATETIME)
def do_apply_adddate(self, *args):
self.apply_adddate.setChecked(True)
def clear_adddate(self, *args):
self.adddate.setDateTime(UNDEFINED_QDATETIME)
def button_clicked(self, which):
if which == self.button_box.button(QDialogButtonBox.StandardButton.Apply):
self.do_again = True
self.accept()
# S&R {{{
def prepare_search_and_replace(self):
self.search_for.initialize('bulk_edit_search_for')
self.replace_with.initialize('bulk_edit_replace_with')
self.s_r_template.setLineEdit(TemplateLineEditor(self.s_r_template))
self.s_r_template.initialize('bulk_edit_template')
self.test_text.initialize('bulk_edit_test_test')
self.all_fields = ['']
self.writable_fields = ['']
fm = self.db.field_metadata
for f in fm:
if (f in ['author_sort'] or
(fm[f]['datatype'] in ['text', 'series', 'enumeration', 'comments', 'rating'] and
fm[f].get('search_terms', None) and
f not in ['formats', 'ondevice', 'series_sort', 'in_tag_browser']) or
(fm[f]['datatype'] in ['int', 'float', 'bool', 'datetime'] and
f not in ['id', 'timestamp'])):
self.all_fields.append(f)
self.writable_fields.append(f)
if fm[f]['datatype'] == 'composite':
self.all_fields.append(f)
self.all_fields.sort()
self.all_fields.insert(1, '{template}')
self.writable_fields.sort()
self.search_field.setMaxVisibleItems(25)
self.destination_field.setMaxVisibleItems(25)
self.testgrid.setColumnStretch(1, 1)
self.testgrid.setColumnStretch(2, 1)
offset = 10
self.s_r_number_of_books = min(10, len(self.ids))
for i in range(1,self.s_r_number_of_books+1):
w = QLabel(self.tabWidgetPage3)
w.setText(_('Book %d:')%i)
self.testgrid.addWidget(w, i+offset, 0, 1, 1)
w = QLineEdit(self.tabWidgetPage3)
w.setReadOnly(True)
name = 'book_%d_text'%i
setattr(self, name, w)
self.book_1_text.setObjectName(name)
self.testgrid.addWidget(w, i+offset, 1, 1, 1)
w = QLineEdit(self.tabWidgetPage3)
w.setReadOnly(True)
name = 'book_%d_result'%i
setattr(self, name, w)
self.book_1_text.setObjectName(name)
self.testgrid.addWidget(w, i+offset, 2, 1, 1)
ident_types = sorted(self.db.get_all_identifier_types(), key=sort_key)
self.s_r_dst_ident.setCompleter(QCompleter(ident_types))
try:
self.s_r_dst_ident.setPlaceholderText(_('Enter an identifier type'))
except:
pass
self.s_r_src_ident.addItems(ident_types)
self.main_heading = _(
'<b>You can destroy your library using this feature.</b> '
'Changes are permanent. There is no undo function. '
'You are strongly encouraged to back up your library '
'before proceeding.<p>'
'Search and replace in text fields using character matching '
'or regular expressions. ')
self.character_heading = _(
'In character mode, the field is searched for the entered '
'search text. The text is replaced by the specified replacement '
'text everywhere it is found in the specified field. After '
'replacement is finished, the text can be changed to '
'upper-case, lower-case, or title-case. If the Case-sensitive '
'check box is checked, the search text must match exactly. If '
'it is unchecked, the search text will match both upper- and '
'lower-case letters'
)
self.regexp_heading = _(
'In regular expression mode, the search text is an '
'arbitrary Python-compatible regular expression. The '
'replacement text can contain backreferences to parenthesized '
'expressions in the pattern. The search is not anchored, '
'and can match and replace multiple times on the same string. '
'The modification functions (lower-case etc) are applied to the '
'matched text, not to the field as a whole. '
'The destination box specifies the field where the result after '
'matching and replacement is to be assigned. You can replace '
'the text in the field, or prepend or append the matched text. '
'See <a href="https://docs.python.org/library/re.html">'
'this reference</a> for more information on Python\'s regular '
'expressions, and in particular the \'sub\' function.'
)
self.search_mode.addItems(self.s_r_match_modes)
self.search_mode.setCurrentIndex(dynamic.get('s_r_search_mode', 0))
self.replace_mode.addItems(self.s_r_replace_modes)
self.replace_mode.setCurrentIndex(0)
self.s_r_search_mode = 0
self.s_r_error = None
self.s_r_obj = None
self.replace_func.addItems(sorted(self.s_r_functions.keys()))
self.search_mode.currentIndexChanged.connect(self.s_r_search_mode_changed)
self.search_field.currentIndexChanged.connect(self.s_r_search_field_changed)
self.destination_field.currentIndexChanged.connect(self.s_r_destination_field_changed)
self.replace_mode.currentIndexChanged.connect(self.s_r_paint_results)
self.replace_func.currentIndexChanged.connect(self.s_r_paint_results)
self.search_for.editTextChanged[native_string_type].connect(self.s_r_paint_results)
self.replace_with.editTextChanged[native_string_type].connect(self.s_r_paint_results)
self.test_text.editTextChanged[native_string_type].connect(self.s_r_paint_results)
self.comma_separated.stateChanged.connect(self.s_r_paint_results)
self.case_sensitive.stateChanged.connect(self.s_r_paint_results)
self.s_r_src_ident.currentIndexChanged.connect(self.s_r_identifier_type_changed)
self.s_r_dst_ident.textChanged.connect(self.s_r_paint_results)
self.s_r_template.lost_focus.connect(self.s_r_template_changed)
self.central_widget.setCurrentIndex(0)
self.search_for.completer().setCaseSensitivity(Qt.CaseSensitivity.CaseSensitive)
self.replace_with.completer().setCaseSensitivity(Qt.CaseSensitivity.CaseSensitive)
self.s_r_template.completer().setCaseSensitivity(Qt.CaseSensitivity.CaseSensitive)
self.s_r_search_mode_changed(self.search_mode.currentIndex())
self.multiple_separator.setFixedWidth(30)
self.multiple_separator.setText(' ::: ')
self.multiple_separator.textChanged.connect(self.s_r_separator_changed)
self.results_count.valueChanged[int].connect(self.s_r_display_bounds_changed)
self.starting_from.valueChanged[int].connect(self.s_r_display_bounds_changed)
self.save_button.clicked.connect(self.s_r_save_query)
self.remove_button.clicked.connect(self.s_r_remove_query)
self.queries = JSONConfig("search_replace_queries")
self.saved_search_name = ''
self.query_field.addItem("")
self.query_field_values = sorted(self.queries, key=sort_key)
self.query_field.addItems(self.query_field_values)
self.query_field.currentIndexChanged.connect(self.s_r_query_change)
self.query_field.setCurrentIndex(0)
self.search_field.setCurrentIndex(0)
self.s_r_search_field_changed(0)
def s_r_sf_itemdata(self, idx):
if idx is None:
idx = self.search_field.currentIndex()
return str(self.search_field.itemData(idx) or '')
def s_r_df_itemdata(self, idx):
if idx is None:
idx = self.destination_field.currentIndex()
return str(self.destination_field.itemData(idx) or '')
def s_r_get_field(self, mi, field):
if field:
if field == '{template}':
v = SafeFormat().safe_format(
str(self.s_r_template.text()), mi, _('S/R TEMPLATE ERROR'), mi)
return [v]
fm = self.db.metadata_for_field(field)
if field == 'sort':
val = mi.get('title_sort', None)
elif fm['datatype'] == 'datetime':
val = mi.format_field(field)[1]
else:
val = mi.get(field, None)
if isinstance(val, (numbers.Number, bool)):
val = str(val)
elif fm['is_csp']:
# convert the csp dict into a list
id_type = str(self.s_r_src_ident.currentText())
if id_type:
val = [val.get(id_type, '')]
else:
val = ['%s:%s'%(t[0], t[1]) for t in iteritems(val)]
if val is None:
val = [] if fm['is_multiple'] else ['']
elif not fm['is_multiple']:
val = [val]
elif fm['datatype'] == 'composite':
val = [v2.strip() for v2 in val.split(fm['is_multiple']['ui_to_list'])]
elif field == 'authors':
val = [v2.replace('|', ',') for v2 in val]
else:
val = []
if not val:
val = ['']
return val
def s_r_display_bounds_changed(self, i):
self.s_r_search_field_changed(self.search_field.currentIndex())
def s_r_template_changed(self):
self.s_r_search_field_changed(self.search_field.currentIndex())
def s_r_identifier_type_changed(self, idx):
self.s_r_search_field_changed(self.search_field.currentIndex())
self.s_r_paint_results(idx)
def s_r_search_field_changed(self, idx):
self.s_r_template.setVisible(False)
self.template_label.setVisible(False)
self.s_r_src_ident_label.setVisible(False)
self.s_r_src_ident.setVisible(False)
if idx == 1: # Template
self.s_r_template.setVisible(True)
self.template_label.setVisible(True)
elif self.s_r_sf_itemdata(idx) == 'identifiers':
self.s_r_src_ident_label.setVisible(True)
self.s_r_src_ident.setVisible(True)
for i in range(0, self.s_r_number_of_books):
w = getattr(self, 'book_%d_text'%(i+1))
mi = self.db.get_metadata(self.ids[i], index_is_id=True)
src = self.s_r_sf_itemdata(idx)
t = self.s_r_get_field(mi, src)
if len(t) > 1:
t = t[self.starting_from.value()-1:
self.starting_from.value()-1 + self.results_count.value()]
w.setText(str(self.multiple_separator.text()).join(t))
if self.search_mode.currentIndex() == 0:
self.destination_field.setCurrentIndex(idx)
else:
self.s_r_destination_field_changed(self.destination_field.currentIndex())
self.s_r_paint_results(None)
def s_r_destination_field_changed(self, idx):
self.s_r_dst_ident_label.setVisible(False)
self.s_r_dst_ident.setVisible(False)
txt = self.s_r_df_itemdata(idx)
if not txt:
txt = self.s_r_sf_itemdata(None)
if txt and txt in self.writable_fields:
if txt == 'identifiers':
self.s_r_dst_ident_label.setVisible(True)
self.s_r_dst_ident.setVisible(True)
self.destination_field_fm = self.db.metadata_for_field(txt)
self.s_r_paint_results(None)
def s_r_search_mode_changed(self, val):
self.search_field.clear()
self.destination_field.clear()
if val == 0:
for f in self.writable_fields:
self.search_field.addItem(f if f != 'sort' else 'title_sort', f)
self.destination_field.addItem(f if f != 'sort' else 'title_sort', f)
self.destination_field.setCurrentIndex(0)
self.destination_field.setVisible(False)
self.destination_field_label.setVisible(False)
self.replace_mode.setCurrentIndex(0)
self.replace_mode.setVisible(False)
self.replace_mode_label.setVisible(False)
self.comma_separated.setVisible(False)
self.s_r_heading.setText('<p>'+self.main_heading + self.character_heading)
else:
self.search_field.blockSignals(True)
self.destination_field.blockSignals(True)
for f in self.all_fields:
self.search_field.addItem(f if f != 'sort' else 'title_sort', f)
for f in self.writable_fields:
self.destination_field.addItem(f if f != 'sort' else 'title_sort', f)
self.search_field.blockSignals(False)
self.destination_field.blockSignals(False)
self.destination_field.setVisible(True)
self.destination_field_label.setVisible(True)
self.replace_mode.setVisible(True)
self.replace_mode_label.setVisible(True)
self.comma_separated.setVisible(True)
self.s_r_heading.setText('<p>'+self.main_heading + self.regexp_heading)
self.s_r_paint_results(None)
def s_r_separator_changed(self, txt):
self.s_r_search_field_changed(self.search_field.currentIndex())
def s_r_set_colors(self):
tt = ''
if self.s_r_error is not None:
tt = error_message(self.s_r_error)
self.test_result.setText(tt)
update_status_actions(self.test_result, self.s_r_error is None, tt)
for i in range(0,self.s_r_number_of_books):
getattr(self, 'book_%d_result'%(i+1)).setText('')
def s_r_func(self, match):
rfunc = self.s_r_functions[str(self.replace_func.currentText())]
rtext = str(self.replace_with.text())
rtext = match.expand(rtext)
return rfunc(rtext)
def s_r_do_regexp(self, mi):
src_field = self.s_r_sf_itemdata(None)
src = self.s_r_get_field(mi, src_field)
result = []
rfunc = self.s_r_functions[str(self.replace_func.currentText())]
for s in src:
t = self.s_r_obj.sub(self.s_r_func, s)
if self.search_mode.currentIndex() == 0:
t = rfunc(t)
result.append(t)
return result
def s_r_do_destination(self, mi, val):
src = self.s_r_sf_itemdata(None)
if src == '':
return ''
dest = self.s_r_df_itemdata(None)
if dest == '':
if (src == '{template}' or
self.db.metadata_for_field(src)['datatype'] == 'composite'):
raise Exception(_('You must specify a destination when source is '
'a composite field or a template'))
dest = src
if self.destination_field_fm['datatype'] == 'rating' and val[0]:
ok = True
try:
v = int(val[0])
if v < 0 or v > 10:
ok = False
except:
ok = False
if not ok:
raise Exception(_('The replacement value for a rating column must '
'be empty or an integer between 0 and 10'))
dest_mode = self.replace_mode.currentIndex()
if self.destination_field_fm['is_csp']:
dest_ident = str(self.s_r_dst_ident.text())
if not dest_ident or (src == 'identifiers' and dest_ident == '*'):
raise Exception(_('You must specify a destination identifier type'))
if self.destination_field_fm['is_multiple']:
if self.comma_separated.isChecked():
splitter = self.destination_field_fm['is_multiple']['ui_to_list']
res = []
for v in val:
res.extend([x.strip() for x in v.split(splitter) if x.strip()])
val = res
else:
val = [v.replace(',', '') for v in val]
if dest_mode != 0:
dest_val = mi.get(dest, '')
if self.db.metadata_for_field(dest)['is_csp']:
dst_id_type = str(self.s_r_dst_ident.text())
if dst_id_type:
dest_val = [dest_val.get(dst_id_type, '')]
else:
# convert the csp dict into a list
dest_val = ['%s:%s'%(t[0], t[1]) for t in iteritems(dest_val)]
if dest_val is None:
dest_val = []
elif not isinstance(dest_val, list):
dest_val = [dest_val]
else:
dest_val = []
if dest_mode == 1:
val.extend(dest_val)
elif dest_mode == 2:
val[0:0] = dest_val
return val
def s_r_replace_mode_separator(self):
if self.comma_separated.isChecked():
return ','
return ''
def s_r_paint_results(self, txt):
self.s_r_error = None
self.s_r_set_colors()
flags = regex.FULLCASE | regex.UNICODE
if not self.case_sensitive.isChecked():
flags |= regex.IGNORECASE
try:
stext = str(self.search_for.text())
if not stext:
raise Exception(_('You must specify a search expression in the "Search for" field'))
if self.search_mode.currentIndex() == 0:
self.s_r_obj = regex.compile(regex.escape(stext), flags | regex.V1)
else:
try:
self.s_r_obj = regex.compile(stext, flags | regex.V1)
except regex.error:
self.s_r_obj = regex.compile(stext, flags)
except Exception as e:
self.s_r_obj = None
self.s_r_error = e
self.s_r_set_colors()
return
try:
test_result = self.s_r_obj.sub(self.s_r_func, self.test_text.text())
if self.search_mode.currentIndex() == 0:
rfunc = self.s_r_functions[self.replace_func.currentText()]
test_result = rfunc(test_result)
self.test_result.setText(test_result)
except Exception as e:
self.s_r_error = e
self.s_r_set_colors()
return
for i in range(0,self.s_r_number_of_books):
mi = self.db.get_metadata(self.ids[i], index_is_id=True)
wr = getattr(self, 'book_%d_result'%(i+1))
try:
result = self.s_r_do_regexp(mi)
t = self.s_r_do_destination(mi, result)
if len(t) > 1 and self.destination_field_fm['is_multiple']:
t = t[self.starting_from.value()-1:
self.starting_from.value()-1 + self.results_count.value()]
t = str(self.multiple_separator.text()).join(t)
else:
t = self.s_r_replace_mode_separator().join(t)
wr.setText(t)
except Exception as e:
self.s_r_error = e
self.s_r_set_colors()
break
def do_search_replace(self, book_id):
source = self.s_r_sf_itemdata(None)
if not source or not self.s_r_obj:
return
dest = self.s_r_df_itemdata(None)
if not dest:
dest = source
dfm = self.db.field_metadata[dest]
mi = self.db.new_api.get_proxy_metadata(book_id)
val = self.s_r_do_regexp(mi)
val = self.s_r_do_destination(mi, val)
if dfm['is_multiple']:
if dfm['is_csp']:
# convert the colon-separated pair strings back into a dict,
# which is what set_identifiers wants
dst_id_type = str(self.s_r_dst_ident.text())
if dst_id_type and dst_id_type != '*':
v = ''.join(val)
ids = mi.get(dest)
ids[dst_id_type] = v
val = ids
else:
try:
val = dict([(t.split(':', maxsplit=1)) for t in val])
except:
import traceback
ans = question_dialog(self, _('Invalid identifier string'),
_('The identifier string for book "{0}" (id {1}) is '
'invalid. It must be a comma-separated list of '
'pairs of strings separated by a colon.\n\n'
'Do you want to continue processing books?').format(mi.title, mi.id),
det_msg='\n'.join([_('Result identifier string: '),
', '.join(val), '-----', traceback.format_exc()]),
show_copy_button=True)
return ans
else:
val = self.s_r_replace_mode_separator().join(val)
if dest == 'title' and len(val) == 0:
val = _('Unknown')
if not val and dfm['datatype'] == 'datetime':
val = None
if dfm['datatype'] == 'rating':
if (not val or int(val) == 0):
val = None
if dest == 'rating' and val:
val = (int(val) // 2) * 2
self.set_field_calls[dest][book_id] = val
# }}}
def create_custom_column_editors(self):
w = self.tab
layout = QGridLayout()
self.custom_column_widgets, self.__cc_spacers = \
populate_metadata_page(layout, self.db, self.ids, parent=w,
two_column=False, bulk=True)
w.setLayout(layout)
self.__custom_col_layouts = [layout]
ans = self.custom_column_widgets
for i in range(len(ans)-1):
w.setTabOrder(ans[i].widgets[-1], ans[i+1].widgets[1])
for c in range(2, len(ans[i].widgets), 2):
w.setTabOrder(ans[i].widgets[c-1], ans[i].widgets[c+1])
def initialize_combos(self):
self.initalize_authors()
self.initialize_series()
self.initialize_publisher()
for x in ('authors', 'publisher', 'series'):
x = getattr(self, x)
x.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
x.setMinimumContentsLength(25)
def initalize_authors(self):
all_authors = self.db.all_authors()
all_authors.sort(key=lambda x : sort_key(x[1]))
self.authors.set_separator('&')
self.authors.set_space_before_sep(True)
self.authors.set_add_separator(tweaks['authors_completer_append_separator'])
self.authors.update_items_cache(self.db.new_api.all_field_names('authors'))
self.authors.show_initial_value('')
def initialize_series(self):
self.series.set_separator(None)
self.series.update_items_cache(self.db.new_api.all_field_names('series'))
self.series.show_initial_value('')
self.publisher.set_add_separator(False)
def initialize_publisher(self):
self.publisher.update_items_cache(self.db.new_api.all_field_names('publisher'))
self.publisher.set_add_separator(False)
self.publisher.show_initial_value('')
def tag_editor(self, *args):
d = TagEditor(self, self.db, None)
d.exec()
if d.result() == QDialog.DialogCode.Accepted:
tag_string = ', '.join(d.tags)
self.tags.setText(tag_string)
all_tags = self.db.new_api.all_field_names('tags')
self.tags.update_items_cache(all_tags)
self.remove_tags.update_items_cache(all_tags)
def auto_number_changed(self, state):
self.series_start_number.setEnabled(bool(state))
self.series_increment.setEnabled(bool(state))
if state:
self.series_numbering_restarts.setEnabled(True)
else:
self.series_numbering_restarts.setEnabled(False)
self.series_numbering_restarts.setChecked(False)
self.series_start_number.setValue(1.0)
self.series_increment.setValue(1.0)
def reject(self):
self.save_state()
QDialog.reject(self)
def accept(self):
self.save_state()
if len(self.ids) < 1:
return QDialog.accept(self)
try:
source = self.s_r_sf_itemdata(None)
except:
source = ''
do_sr = source and self.s_r_obj
if self.s_r_error is not None and do_sr:
error_dialog(self, _('Search/replace invalid'),
_('Search/replace is invalid: %s')%error_message(self.s_r_error),
show=True)
return False
self.changed = bool(self.ids)
# Cache values from GUI so that Qt widgets are not used in
# non GUI thread
for w in getattr(self, 'custom_column_widgets', []):
w.gui_val
remove_all = self.remove_all_tags.isChecked()
remove = []
if not remove_all:
remove = str(self.remove_tags.text()).strip().split(',')
add = str(self.tags.text()).strip().split(',')
au = str(self.authors.text())
aus = str(self.author_sort.text())
do_aus = self.author_sort.isEnabled()
rating = self.rating.rating_value
if not self.apply_rating.isChecked():
rating = -1
pub = str(self.publisher.text())
do_series = self.write_series
clear_series = self.clear_series.isChecked()
clear_pub = self.clear_pub.isChecked()
series = str(self.series.currentText()).strip()
do_autonumber = self.autonumber_series.isChecked()
do_series_restart = self.series_numbering_restarts.isChecked()
series_start_value = self.series_start_number.value()
series_increment = self.series_increment.value()
do_swap_ta = self.swap_title_and_author.isChecked()
do_remove_conv = self.remove_conversion_settings.isChecked()
do_auto_author = self.auto_author_sort.isChecked()
do_title_case = self.change_title_to_title_case.isChecked()
do_title_sort = self.update_title_sort.isChecked()
do_compress_cover = self.compress_cover_images.isChecked()
compress_cover_quality = self.compress_quality.value()
read_file_metadata = self.read_file_metadata.isChecked()
clear_languages = self.clear_languages.isChecked()
restore_original = self.restore_original.isChecked()
languages = self.languages.lang_codes
pubdate = adddate = None
if self.apply_pubdate.isChecked():
pubdate = qt_to_dt(self.pubdate.dateTime(), as_utc=False)
if self.apply_adddate.isChecked():
adddate = qt_to_dt(self.adddate.dateTime(), as_utc=False)
cover_action = None
if self.cover_remove.isChecked():
cover_action = 'remove'
elif self.cover_generate.isChecked():
cover_action = 'generate'
elif self.cover_from_fmt.isChecked():
cover_action = 'fromfmt'
elif self.cover_trim.isChecked():
cover_action = 'trim'
elif self.cover_clone.isChecked():
cover_action = 'clone'
args = Settings(
remove_all, remove, add, au, aus, do_aus, rating, pub, do_series,
do_autonumber, do_swap_ta, do_remove_conv, do_auto_author, series,
do_series_restart, series_start_value, series_increment,
do_title_case, cover_action, clear_series, clear_pub, pubdate,
adddate, do_title_sort, languages, clear_languages,
restore_original, self.comments, self.generate_cover_settings,
read_file_metadata, self.casing_map[self.casing_algorithm.currentIndex()],
do_compress_cover, compress_cover_quality, self.tag_map_rules, self.author_map_rules,
self.publisher_map_rules
)
if DEBUG:
print('Running bulk metadata operation with settings:')
print(args)
self.set_field_calls = defaultdict(dict)
bb = MyBlockingBusy(args, self.ids, self.db, self.refresh_books,
getattr(self, 'custom_column_widgets', []),
self.do_search_replace, do_sr, self.set_field_calls, parent=self)
# The metadata backup thread causes database commits
# which can slow down bulk editing of large numbers of books
self.model.stop_metadata_backup()
try:
bb.exec()
finally:
self.model.start_metadata_backup()
bb.thread = bb.db = bb.cc_widgets = None
if bb.error is not None:
return error_dialog(self, _('Failed'),
bb.error[0], det_msg=bb.error[1],
show=True)
dynamic['s_r_search_mode'] = self.search_mode.currentIndex()
gprefs.set('bulk-mde-casing-algorithm', args.casing_algorithm)
self.db.clean()
if args.do_compress_cover:
total_old, total_new = bb.cover_sizes['old'], bb.cover_sizes['new']
if total_old > 0:
percent = (total_old - total_new) / total_old
info_dialog(self, _('Covers compressed'), _(
'Covers were compressed by {percent:.1%} from a total size of'
' {old} to {new}.').format(
percent=percent, old=human_readable(total_old), new=human_readable(total_new))
).exec()
return QDialog.accept(self)
def series_changed(self, *args):
self.write_series = bool(str(self.series.currentText()).strip())
self.autonumber_series.setEnabled(True)
def s_r_remove_query(self, *args):
if self.query_field.currentIndex() == 0:
return
if not question_dialog(self, _("Delete saved search/replace"),
_("The selected saved search/replace will be deleted. "
"Are you sure?")):
return
item_id = self.query_field.currentIndex()
item_name = str(self.query_field.currentText())
self.query_field.blockSignals(True)
self.query_field.removeItem(item_id)
self.query_field.blockSignals(False)
self.query_field.setCurrentIndex(0)
if item_name in list(self.queries.keys()):
del self.queries[item_name]
self.queries.commit()
def s_r_save_query(self, *args):
names = ['']
names.extend(self.query_field_values)
try:
dex = names.index(self.saved_search_name)
except:
dex = 0
name = ''
while not name:
name, ok = QInputDialog.getItem(self, _('Save search/replace'),
_('Search/replace name:'), names, dex, True)
if not ok:
return
if not name:
error_dialog(self, _("Save search/replace"),
_("You must provide a name."), show=True)
new = True
name = str(name)
if name in list(self.queries.keys()):
if not question_dialog(self, _("Save search/replace"),
_("That saved search/replace already exists and will be overwritten. "
"Are you sure?")):
return
new = False
query = {}
query['name'] = name
query['search_field'] = str(self.search_field.currentText())
query['search_mode'] = str(self.search_mode.currentText())
query['s_r_template'] = str(self.s_r_template.text())
query['s_r_src_ident'] = str(self.s_r_src_ident.currentText())
query['search_for'] = str(self.search_for.text())
query['case_sensitive'] = self.case_sensitive.isChecked()
query['replace_with'] = str(self.replace_with.text())
query['replace_func'] = str(self.replace_func.currentText())
query['destination_field'] = str(self.destination_field.currentText())
query['s_r_dst_ident'] = str(self.s_r_dst_ident.text())
query['replace_mode'] = str(self.replace_mode.currentText())
query['comma_separated'] = self.comma_separated.isChecked()
query['results_count'] = self.results_count.value()
query['starting_from'] = self.starting_from.value()
query['multiple_separator'] = str(self.multiple_separator.text())
self.queries[name] = query
self.queries.commit()
if new:
self.query_field.blockSignals(True)
self.query_field.clear()
self.query_field.addItem('')
self.query_field_values = sorted(self.queries, key=sort_key)
self.query_field.addItems(self.query_field_values)
self.query_field.blockSignals(False)
self.query_field.setCurrentIndex(self.query_field.findText(name))
def s_r_query_change(self, idx):
item_name = self.query_field.currentText()
if not item_name:
self.s_r_reset_query_fields()
self.saved_search_name = ''
return
item = self.queries.get(str(item_name), None)
if item is None:
self.s_r_reset_query_fields()
return
self.saved_search_name = item_name
def set_text(attr, key):
try:
attr.setText(item[key])
except:
pass
def set_checked(attr, key):
try:
attr.setChecked(item[key])
except:
attr.setChecked(False)
def set_value(attr, key):
try:
attr.setValue(int(item[key]))
except:
attr.setValue(0)
def set_index(attr, key):
try:
attr.setCurrentIndex(attr.findText(item[key]))
except:
attr.setCurrentIndex(0)
set_index(self.search_mode, 'search_mode')
set_index(self.search_field, 'search_field')
set_text(self.s_r_template, 's_r_template')
self.s_r_template_changed() # simulate gain/loss of focus
set_index(self.s_r_src_ident, 's_r_src_ident')
set_text(self.s_r_dst_ident, 's_r_dst_ident')
set_text(self.search_for, 'search_for')
set_checked(self.case_sensitive, 'case_sensitive')
set_text(self.replace_with, 'replace_with')
set_index(self.replace_func, 'replace_func')
set_index(self.destination_field, 'destination_field')
set_index(self.replace_mode, 'replace_mode')
set_checked(self.comma_separated, 'comma_separated')
set_value(self.results_count, 'results_count')
set_value(self.starting_from, 'starting_from')
set_text(self.multiple_separator, 'multiple_separator')
def s_r_reset_query_fields(self):
# Don't reset the search mode. The user will probably want to use it
# as it was
self.search_field.setCurrentIndex(0)
self.s_r_src_ident.setCurrentIndex(0)
self.s_r_template.setText("")
self.search_for.setText("")
self.case_sensitive.setChecked(False)
self.replace_with.setText("")
self.replace_func.setCurrentIndex(0)
self.destination_field.setCurrentIndex(0)
self.s_r_dst_ident.setText('')
self.replace_mode.setCurrentIndex(0)
self.comma_separated.setChecked(True)
self.results_count.setValue(999)
self.starting_from.setValue(1)
self.multiple_separator.setText(" ::: ")
| 67,917 | Python | .py | 1,382 | 36.982634 | 138 | 0.593219 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,038 | quickview.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/quickview.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net'
__docformat__ = 'restructuredtext en'
import traceback
from functools import partial
from qt.core import (
QAbstractItemView,
QApplication,
QCoreApplication,
QDialog,
QEvent,
QIcon,
QListWidgetItem,
QMenu,
QObject,
QShortcut,
QStyle,
Qt,
QTableWidgetItem,
QTimer,
pyqtSignal,
)
from calibre.customize.ui import find_plugin
from calibre.gui2 import error_dialog, gprefs
from calibre.gui2.dialogs.quickview_ui import Ui_Quickview
from calibre.utils.date import timestampfromdt
from calibre.utils.icu import sort_key
from calibre.utils.iso8601 import UNDEFINED_DATE
class TableItem(QTableWidgetItem):
'''
A QTableWidgetItem that sorts on a separate string and uses ICU rules
'''
def __init__(self, getter=None):
self.val = ''
self.sort = None
self.sort_idx = 0
self.getter = getter
self.resolved = False
QTableWidgetItem.__init__(self, '')
self.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsSelectable)
def __ge__(self, other):
self.get_data()
other.get_data()
if self.sort is None:
if other.sort is None:
# None == None therefore >=
return True
# self is None, other is not None therefore self < other
return False
if other.sort is None:
# self is not None and other is None therefore self >= other
return True
if isinstance(self.sort, (bytes, str)):
l = sort_key(self.sort)
r = sort_key(other.sort)
else:
l = self.sort
r = other.sort
if l > r:
return 1
if l == r:
return self.sort_idx >= other.sort_idx
return 0
def __lt__(self, other):
self.get_data()
other.get_data()
if self.sort is None:
if other.sort is None:
# None == None therefore not <
return False
# self is None, other is not None therefore self < other
return True
if other.sort is None:
# self is not None therefore self > other
return False
if isinstance(self.sort, (bytes, str)):
l = sort_key(self.sort)
r = sort_key(other.sort)
else:
l = self.sort
r = other.sort
if l < r:
return 1
if l == r:
return self.sort_idx < other.sort_idx
return 0
def get_data(self):
if not self.resolved and self.getter:
self.resolved = True
self.val, self.sort, self.sort_idx = self.getter()
def data(self, role):
self.get_data()
if role == Qt.ItemDataRole.DisplayRole:
return self.val
return QTableWidgetItem.data(self, role)
IN_WIDGET_ITEMS = 0
IN_WIDGET_BOOKS = 1
IN_WIDGET_LOCK = 2
IN_WIDGET_DOCK = 3
IN_WIDGET_SEARCH = 4
IN_WIDGET_CLOSE = 5
class BooksTableFilter(QObject):
return_pressed_signal = pyqtSignal()
def eventFilter(self, obj, event):
if event.type() == QEvent.Type.KeyPress and event.key() == Qt.Key.Key_Return:
self.return_pressed_signal.emit()
return True
return False
class WidgetFocusFilter(QObject):
focus_entered_signal = pyqtSignal(object)
def eventFilter(self, obj, event):
if event.type() == QEvent.Type.FocusIn:
self.focus_entered_signal.emit(obj)
return False
class WidgetTabFilter(QObject):
def __init__(self, attach_to_Class, which_widget, tab_signal):
QObject.__init__(self, attach_to_Class)
self.tab_signal = tab_signal
self.which_widget = which_widget
def eventFilter(self, obj, event):
if event.type() == QEvent.Type.KeyPress:
if event.key() == Qt.Key.Key_Tab:
self.tab_signal.emit(self.which_widget, True)
return True
if event.key() == Qt.Key.Key_Backtab:
self.tab_signal.emit(self.which_widget, False)
return True
return False
class Quickview(QDialog, Ui_Quickview):
reopen_after_dock_change = pyqtSignal()
tab_pressed_signal = pyqtSignal(object, object)
quickview_closed = pyqtSignal()
def __init__(self, gui, row, toggle_shortcut, focus_booklist_shortcut=None):
self.is_pane = gprefs.get('quickview_is_pane', False)
if not self.is_pane:
QDialog.__init__(self, None, flags=Qt.WindowType.Window)
else:
QDialog.__init__(self, None, flags=Qt.WindowType.Dialog)
Ui_Quickview.__init__(self)
self.setupUi(self)
self.isClosed = False
self.current_book = None
self.closed_by_button = False
if self.is_pane:
self.main_grid_layout.setContentsMargins(0, 0, 0, 0)
else:
self.setWindowIcon(self.windowIcon())
self.books_table_column_widths = None
try:
self.books_table_column_widths = \
gprefs.get('quickview_dialog_books_table_widths', None)
if not self.is_pane:
self.restore_geometry(gprefs, 'quickview_dialog_geometry')
except:
pass
self.view = gui.library_view
self.db = self.view.model().db
self.gui = gui
self.is_closed = False
self.current_book_id = None # the db id of the book used to fill the lh pane
self.current_column = None # current logical column in books list
self.current_key = None # current lookup key in books list
self.last_search = None
self.no_valid_items = False
self.follow_library_view = True
self.apply_vls.setCheckState(Qt.CheckState.Checked if gprefs['qv_respects_vls']
else Qt.CheckState.Unchecked)
self.apply_vls.stateChanged.connect(self.vl_box_changed)
self.fm = self.db.field_metadata
self.items.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
self.items.currentTextChanged.connect(self.item_selected)
self.items.setProperty('highlight_current_item', 150)
self.items.itemDoubleClicked.connect(self.item_doubleclicked)
self.items.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.items.customContextMenuRequested.connect(self.show_item_context_menu)
focus_filter = WidgetFocusFilter(self.items)
focus_filter.focus_entered_signal.connect(self.focus_entered)
self.items.installEventFilter(focus_filter)
self.tab_pressed_signal.connect(self.tab_pressed)
return_filter = BooksTableFilter(self.books_table)
return_filter.return_pressed_signal.connect(self.return_pressed)
self.books_table.installEventFilter(return_filter)
focus_filter = WidgetFocusFilter(self.books_table)
focus_filter.focus_entered_signal.connect(self.focus_entered)
self.books_table.installEventFilter(focus_filter)
self.close_button.clicked.connect(self.close_button_clicked)
self.refresh_button.clicked.connect(self.refill)
self.tab_order_widgets = [self.items, self.books_table, self.lock_qv,
self.dock_button, self.refresh_button,
self.close_button]
for idx,widget in enumerate(self.tab_order_widgets):
widget.installEventFilter(WidgetTabFilter(widget, idx, self.tab_pressed_signal))
self.books_table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
self.books_table.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
self.books_table.setProperty('highlight_current_item', 150)
# Set up the books table columns
self.add_columns_to_widget()
self.books_table_header_height = self.books_table.height()
self.books_table.cellDoubleClicked.connect(self.book_doubleclicked)
self.books_table.currentCellChanged.connect(self.books_table_cell_changed)
self.books_table.cellClicked.connect(self.books_table_set_search_string)
self.books_table.cellActivated.connect(self.books_table_set_search_string)
self.books_table.sortByColumn(0, Qt.SortOrder.AscendingOrder)
# get the standard table row height. Do this here because calling
# resizeRowsToContents can word wrap long cell contents, creating
# double-high rows
self.books_table.setRowCount(1)
self.books_table.setItem(0, 0, TableItem())
self.books_table.resizeRowsToContents()
self.books_table_row_height = self.books_table.rowHeight(0)
self.books_table.setRowCount(0)
# Add the data
self.refresh(row)
self.slave_timers = [QTimer(self), QTimer(self), QTimer(self)]
self.view.clicked.connect(partial(self.delayed_slave, func=self.slave, dex=0))
self.view.selectionModel().currentColumnChanged.connect(
partial(self.delayed_slave, func=self.column_slave, dex=1))
QCoreApplication.instance().aboutToQuit.connect(self.save_state)
self.view.model().new_bookdisplay_data.connect(
partial(self.delayed_slave, func=self.book_was_changed, dex=2))
self.close_button.setDefault(False)
self.close_button_tooltip = _('The Quickview shortcut ({0}) shows/hides the Quickview panel')
self.refresh_button.setIcon(QIcon.ic('view-refresh.png'))
self.close_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_DialogCloseButton))
if self.is_pane:
self.dock_button.setText(_('Undock'))
self.dock_button.setToolTip(_('Show the Quickview panel in its own floating window'))
self.dock_button.setIcon(QIcon.ic('arrow-up.png'))
# Remove the ampersands from the buttons because shortcuts exist.
self.lock_qv.setText(_('Lock Quickview contents'))
self.refresh_button.setText(_('Refresh'))
self.gui.layout_container.set_widget('quick_view', self)
self.close_button.setVisible(False)
else:
self.dock_button.setToolTip(_('Embed the Quickview panel into the main calibre window'))
self.dock_button.setIcon(QIcon.ic('arrow-down.png'))
self.set_focus()
self.books_table.horizontalHeader().sectionResized.connect(self.section_resized)
self.dock_button.clicked.connect(self.show_as_pane_changed)
self.view.model().search_done.connect(self.check_for_no_items)
# Enable the refresh button only when QV is locked
self.refresh_button.setEnabled(False)
self.lock_qv.stateChanged.connect(self.lock_qv_changed)
self.view_icon = QIcon.ic('view.png')
self.view_plugin = self.gui.iactions['View']
self.show_details_plugin = self.gui.iactions['Show Book Details']
self.edit_metadata_icon = QIcon.ic('edit_input.png')
self.quickview_icon = QIcon.ic('quickview.png')
self.select_book_icon = QIcon.ic('library.png')
self.search_icon = QIcon.ic('search.png')
self.books_table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.books_table.customContextMenuRequested.connect(self.show_context_menu)
# Add the quickview toggle as a shortcut for the close button
# Don't add it if it identical to the current &X shortcut because that
# breaks &X. Also add the focus booklist shortcut
if not self.is_pane:
if toggle_shortcut and self.close_button.shortcut() != toggle_shortcut:
toggle_sc = QShortcut(toggle_shortcut, self.close_button)
toggle_sc.activated.connect(lambda: self.close_button_clicked())
toggle_sc.setEnabled(True)
self.close_button.setToolTip(_('Alternate shortcut: ') +
toggle_shortcut.toString())
if focus_booklist_shortcut is not None:
toggle_sc = QShortcut(focus_booklist_shortcut, self)
toggle_sc.activated.connect(self.focus_booklist)
toggle_sc.setEnabled(True)
def focus_booklist(self):
from calibre.gui2.ui import get_gui
gui = get_gui()
gui.activateWindow()
gui.focus_current_view()
def delayed_slave(self, current, func=None, dex=None):
self.slave_timers[dex].stop()
t = self.slave_timers[dex] = QTimer(self)
t.timeout.connect(partial(func, current))
t.setSingleShot(True)
t.setInterval(200)
t.start()
def item_doubleclicked(self, item):
tb = self.gui.tb_widget
tb.set_focus_to_find_box()
tb.item_search.lineEdit().setText(self.current_key + ':=' + item.text())
tb.do_find()
def show_item_context_menu(self, point):
item = self.items.currentItem()
self.context_menu = QMenu(self)
self.context_menu.addAction(self.search_icon, _('Find item in the Tag browser'),
partial(self.item_doubleclicked, item))
self.context_menu.addAction(self.search_icon, _('Find item in the library'),
partial(self.do_search, follow_library_view=False))
self.context_menu.popup(self.items.mapToGlobal(point))
self.context_menu = QMenu(self)
def show_context_menu(self, point):
index = self.books_table.indexAt(point)
row = index.row()
column = index.column()
item = self.books_table.item(index.row(), 0)
if item is None:
return False
book_id = int(item.data(Qt.ItemDataRole.UserRole))
book_displayed = self.book_displayed_in_library_view(book_id)
m = self.context_menu = QMenu(self)
a = m.addAction(self.select_book_icon, _('Select this book in the library'),
partial(self.select_book, book_id))
a.setEnabled(book_displayed)
m.addAction(_('Open a locked Book details window for this book'),
partial(self.show_book_details, book_id))
m.addAction(self.search_icon, _('Find item in the library'),
partial(self.do_search, follow_library_view=False))
a = m.addAction(self.edit_metadata_icon, _('Edit metadata'),
partial(self.edit_metadata, book_id, follow_library_view=False))
a.setEnabled(book_displayed)
a = m.addAction(self.quickview_icon, _('Quickview this cell'),
partial(self.quickview_item, row, column))
key = self.column_order[column]
a.setEnabled(self.is_category(key) and book_displayed and
key in self.view.visible_columns and
not self.lock_qv.isChecked())
m.addSeparator()
m.addAction(self.view_icon, _('Open book in the E-book viewer'),
partial(self.view_plugin._view_calibre_books, [book_id]))
self.context_menu.popup(self.books_table.mapToGlobal(point))
return True
def lock_qv_changed(self, state):
self.refresh_button.setEnabled(state)
def add_columns_to_widget(self):
'''
Get the list of columns from the preferences. Clear the current table
and add the current column set
'''
self.column_order = [x[0] for x in get_qv_field_list(self.fm) if x[1]]
self.books_table.clear()
self.books_table.setRowCount(0)
self.books_table.setColumnCount(len(self.column_order))
for idx,col in enumerate(self.column_order):
t = QTableWidgetItem(self.fm[col]['name'])
self.books_table.setHorizontalHeaderItem(idx, t)
def refill(self):
'''
Refill the table in case the columns displayed changes
'''
self.add_columns_to_widget()
self.refresh(self.view.currentIndex(), ignore_lock=True)
def set_search_text(self, txt):
self.last_search = txt
def focus_entered(self, obj):
if obj == self.books_table:
self.books_table_set_search_string(self.books_table.currentRow(),
self.books_table.currentColumn())
elif obj.currentItem():
self.item_selected(obj.currentItem().text())
def books_table_cell_changed(self, cur_row, cur_col, prev_row, prev_col):
self.books_table_set_search_string(cur_row, cur_col)
def books_table_set_search_string(self, current_row, current_col):
'''
Given the contents of a cell, compute a search string that will find
that book and any others with identical contents in the cell.
'''
current = self.books_table.item(current_row, current_col)
if current is None:
return
book_id = current.data(Qt.ItemDataRole.UserRole)
if current is None:
return
col = self.column_order[current.column()]
if col == 'title':
self.set_search_text('title:="' + current.text().replace('"', '\\"') + '"')
elif col == 'authors':
authors = []
for aut in [t.strip() for t in current.text().split('&')]:
authors.append('authors:="' + aut.replace('"', '\\"') + '"')
self.set_search_text(' and '.join(authors))
elif self.fm[col]['datatype'] == 'series':
mi = self.db.get_metadata(book_id, index_is_id=True, get_user_categories=False)
t = mi.get(col)
if t:
self.set_search_text(col+ ':="' + t + '"')
else:
self.set_search_text(None)
else:
if self.fm[col]['is_multiple']:
items = [(col + ':"=' + v.strip() + '"') for v in
current.text().split(self.fm[col]['is_multiple']['ui_to_list'])]
self.set_search_text(' and '.join(items))
else:
self.set_search_text(col + ':"=' + current.text() + '"')
def tab_pressed(self, in_widget, isForward):
if isForward:
in_widget += 1
if in_widget >= len(self.tab_order_widgets):
in_widget = 0
else:
in_widget -= 1
if in_widget < 0:
in_widget = len(self.tab_order_widgets) - 1
self.tab_order_widgets[in_widget].setFocus(Qt.FocusReason.TabFocusReason)
def show(self):
QDialog.show(self)
if self.is_pane:
self.gui.show_panel('quick_view')
def show_as_pane_changed(self):
gprefs['quickview_is_pane'] = not gprefs.get('quickview_is_pane', False)
self.reopen_after_dock_change.emit()
# search button
def do_search(self, follow_library_view=True):
if self.no_valid_items:
return
if self.last_search is not None:
try:
self.follow_library_view = follow_library_view
self.gui.search.set_search_string(self.last_search)
finally:
self.follow_library_view = True
def book_was_changed(self, mi):
'''
Called when book information is changed in the library view. Make that
book info current. This means that prev and next in edit metadata will move
the current book and change quickview
'''
if self.is_closed or self.current_column is None or not self.follow_library_view:
return
# There is an ordering problem when libraries are changed. The library
# view is changed, triggering a book_was_changed signal. Unfortunately
# this happens before the library_changed actions are run, meaning we
# still have the old database. To avoid the problem we just ignore the
# operation if we get an exception. The "close" will come
# eventually.
try:
self.refresh(self.view.model().index(self.db.row(mi.id), self.current_column))
except:
pass
# clicks on the items listWidget
def item_selected(self, txt):
if self.no_valid_items:
return
self.fill_in_books_box(str(txt))
self.set_search_text(self.current_key + ':"=' + txt.replace('"', '\\"') + '"')
def vl_box_changed(self):
gprefs['qv_respects_vls'] = self.apply_vls.isChecked()
self._refresh(self.current_book_id, self.current_key)
def refresh(self, idx, ignore_lock=False):
'''
Given a cell in the library view, display the information. This method
converts the index into the lookup key
'''
if (not ignore_lock and self.lock_qv.isChecked()):
return
if not idx.isValid():
from calibre.constants import DEBUG
if DEBUG:
from calibre import prints
prints('QuickView: current index is not valid')
return
try:
self.current_column = (
self.view.column_map.index('authors') if (
self.current_column is None and self.view.column_map[idx.column()] == 'title'
) else idx.column())
key = self.view.column_map[self.current_column]
book_id = self.view.model().id(idx.row())
if self.current_book_id == book_id and self.current_key == key:
return
self._refresh(book_id, key)
except:
traceback.print_exc()
self.indicate_no_items()
def is_category(self, key):
return key is not None and (
self.fm[key]['table'] is not None and
(self.fm[key]['is_category'] or
(self.fm[key]['datatype'] == 'composite' and
self.fm[key]['display'].get('make_category', False))))
def _refresh(self, book_id, key):
'''
Actually fill in the left-hand panel from the information in the
selected column of the selected book
'''
# Only show items for categories
if not self.is_category(key):
if self.current_key is None:
self.indicate_no_items()
return
key = self.current_key
label_text = _('&Item: {0} ({1})')
if self.is_pane:
label_text = label_text.replace('&', '')
self.items.blockSignals(True)
self.items.clear()
self.books_table.setRowCount(0)
mi = self.db.new_api.get_proxy_metadata(book_id)
vals = self.db.new_api.split_if_is_multiple_composite(key, mi.get(key, None))
try:
# Check if we are in the GridView and there are no values for the
# selected column. In this case switch the column to 'authors'
# because there isn't an easy way to switch columns in GridView
# when the QV box is empty.
if not vals:
is_grid_view = (self.gui.current_view().alternate_views.current_view !=
self.gui.current_view().alternate_views.main_view)
if is_grid_view:
key = 'authors'
vals = mi.get(key, None)
except:
traceback.print_exc()
self.current_book_id = book_id
self.current_key = key
self.items_label.setText(label_text.format(self.fm[key]['name'], key))
if vals:
self.no_valid_items = False
if self.fm[key]['datatype'] == 'rating':
if self.fm[key]['display'].get('allow_half_stars', False):
vals = str(vals/2.0)
else:
vals = str(vals//2)
if not isinstance(vals, list):
vals = [vals]
vals.sort(key=sort_key)
for v in vals:
a = QListWidgetItem(v)
a.setToolTip(
'<p>' + _(
'Click to show only books with this item. '
'Double click to search for this item in the Tag browser') + '</p>')
self.items.addItem(a)
self.items.setCurrentRow(0)
self.fill_in_books_box(vals[0])
else:
self.indicate_no_items()
self.items.blockSignals(False)
def check_for_no_items(self):
if not self.is_closed and self.view.model().count() == 0:
self.indicate_no_items()
def indicate_no_items(self):
self.no_valid_items = True
self.items.clear()
self.add_columns_to_widget()
self.items.addItem(QListWidgetItem(_('**No items found**')))
self.books_label.setText(_('Click in a column in the library view '
'to see the information for that book'))
def fill_in_books_box(self, selected_item):
'''
Given the selected row in the left-hand box, fill in the grid with
the books that contain that data.
'''
# Do a bit of fix-up on the items so that the search works.
if selected_item.startswith('.'):
sv = '.' + selected_item
else:
sv = selected_item
sv = self.current_key + ':"=' + sv.replace('"', r'\"') + '"'
if self.apply_vls.isChecked():
books = self.db.search(sv, return_matches=True, sort_results=False)
else:
books = self.db.new_api.search(sv)
self.books_table.setRowCount(len(books))
label_text = _('&Books with selected item "{0}": {1}')
if self.is_pane:
label_text = label_text.replace('&', '')
self.books_label.setText(label_text.format(selected_item, len(books)))
select_item = None
self.books_table.setSortingEnabled(False)
self.books_table.blockSignals(True)
tt = ('<p>' + _(
'Double click on a book to change the selection in the library view or '
'change the column shown in the left-hand panel. '
'Shift- or Ctrl- double click to edit the metadata of a book, '
'which also changes the selected book.'
) + '</p>')
for row, b in enumerate(books):
for col in self.column_order:
a = TableItem(partial(self.get_item_data, b, col))
if col == 'title':
if b == self.current_book_id:
select_item = a
# The data is supplied on demand when the item is displayed
a.setData(Qt.ItemDataRole.UserRole, b)
a.setToolTip(f"<div>{_('Value')}: {a.text()}</div>{tt}")
self.books_table.setItem(row, self.key_to_table_widget_column(col), a)
self.books_table.setRowHeight(row, self.books_table_row_height)
self.books_table.blockSignals(False)
self.books_table.setSortingEnabled(True)
if select_item is not None:
self.books_table.setCurrentItem(select_item)
self.books_table.scrollToItem(select_item, QAbstractItemView.ScrollHint.PositionAtCenter)
self.set_search_text(sv)
def get_item_data(self, book_id, col):
mi = self.db.new_api.get_proxy_metadata(book_id)
try:
if col == 'title':
return (mi.title, mi.title_sort, 0)
elif col == 'authors':
return (' & '.join(mi.authors), mi.author_sort, 0)
elif col == 'series':
series = mi.format_field('series')[1]
if series is None:
return ('', None, 0)
else:
return (series, mi.series, mi.series_index)
elif col == 'size':
v = mi.get('book_size')
if v is not None:
return (f'{v:n}', v, 0)
else:
return ('', None, 0)
elif self.fm[col]['datatype'] == 'series':
v = mi.format_field(col)[1]
return (v, mi.get(col), mi.get(col+'_index'))
elif self.fm[col]['datatype'] == 'datetime':
v = mi.format_field(col)[1]
d = mi.get(col)
if d is None:
d = UNDEFINED_DATE
return (v, timestampfromdt(d), 0)
elif self.fm[col]['datatype'] in ('float', 'int'):
v = mi.format_field(col)[1]
sort_val = mi.get(col)
return (v, sort_val, 0)
else:
v = mi.format_field(col)[1]
return (v, v, 0)
except:
traceback.print_exc()
return (_('Something went wrong while filling in the table'), '', 0)
# Deal with sizing the table columns. Done here because the numbers are not
# correct until the first paint.
def resizeEvent(self, *args):
QDialog.resizeEvent(self, *args)
if self.books_table_column_widths is not None:
for c,w in enumerate(self.books_table_column_widths):
self.books_table.setColumnWidth(c, w)
else:
# the vertical scroll bar might not be rendered, so might not yet
# have a width. Assume 25. Not a problem because user-changed column
# widths will be remembered
w = self.books_table.width() - 25 - self.books_table.verticalHeader().width()
w //= self.books_table.columnCount()
for c in range(0, self.books_table.columnCount()):
self.books_table.setColumnWidth(c, w)
self.save_state()
def key_to_table_widget_column(self, key):
return self.column_order.index(key)
def return_pressed(self):
row = self.books_table.currentRow()
if gprefs['qv_retkey_changes_column']:
self.select_book_and_qv(row, self.books_table.currentColumn())
else:
self.select_book_and_qv(row, self.key_to_table_widget_column(self.current_key))
def book_not_in_view_error(self):
error_dialog(self, _('Quickview: Book not in library view'),
_('The book you selected is not currently displayed in '
'the library view, perhaps because of a search or a '
'Virtual library, so Quickview cannot select it.'),
show=True,
show_copy_button=False)
def book_displayed_in_library_view(self, book_id):
try:
self.db.data.index(book_id)
return True
except:
return False
def quickview_item(self, row, column):
self.select_book_and_qv(row, column)
def book_doubleclicked(self, row, column):
if self.no_valid_items:
return
try:
if gprefs['qv_dclick_changes_column']:
self.quickview_item(row, column)
else:
self.quickview_item(row, self.key_to_table_widget_column(self.current_key))
except:
traceback.print_exc()
self.book_not_in_view_error()
def edit_metadata(self, book_id, follow_library_view=True):
try:
self.follow_library_view = follow_library_view
self.view.select_rows([book_id])
em = find_plugin('Edit Metadata')
if em and em.actual_plugin_:
em.actual_plugin_.edit_metadata(None)
finally:
self.follow_library_view = True
def show_book_details(self, book_id):
try:
self.show_details_plugin.show_book_info(book_id=book_id, locked=True)
finally:
pass
def select_book(self, book_id):
'''
Select a book in the library view without changing the QV lists
'''
try:
self.follow_library_view = False
self.view.select_cell(self.db.data.id_to_index(book_id),
self.current_column)
finally:
self.follow_library_view = True
def select_book_and_qv(self, row, column):
'''
row and column both refer the qv table. In particular, column is not
the logical column in the book list.
'''
item = self.books_table.item(row, column)
if item is None:
return
book_id = int(self.books_table.item(row, column).data(Qt.ItemDataRole.UserRole))
if not self.book_displayed_in_library_view(book_id):
self.book_not_in_view_error()
return
key = self.column_order[column]
if QApplication.keyboardModifiers() in (Qt.KeyboardModifier.ControlModifier, Qt.KeyboardModifier.ShiftModifier):
self.edit_metadata(book_id)
else:
if key not in self.view.visible_columns:
error_dialog(self, _("Quickview: Column cannot be selected"),
_("The column you double-clicked, '{}', is not shown in the "
"library view. The book/column cannot be selected by Quickview.").format(key),
show=True,
show_copy_button=False)
return
self.view.select_cell(self.db.data.id_to_index(book_id),
self.view.column_map.index(key))
def set_focus(self):
self.activateWindow()
self.books_table.setFocus()
def column_slave(self, current):
'''
called when the column is changed on the booklist
'''
if self.follow_library_view and gprefs['qv_follows_column']:
self.slave(current)
def slave(self, current):
'''
called when a book is clicked on the library view
'''
if self.is_closed or not self.follow_library_view:
return
self.refresh(current)
self.view.activateWindow()
def section_resized(self, logicalIndex, oldSize, newSize):
self.save_state()
def save_state(self):
if self.is_closed:
return
self.books_table_column_widths = []
for c in range(0, self.books_table.columnCount()):
self.books_table_column_widths.append(self.books_table.columnWidth(c))
gprefs['quickview_dialog_books_table_widths'] = self.books_table_column_widths
if not self.is_pane:
self.save_geometry(gprefs, 'quickview_dialog_geometry')
def _close(self):
self.save_state()
# clean up to prevent memory leaks
self.db = self.view = self.gui = None
self.is_closed = True
def close_button_clicked(self):
self.closed_by_button = True
self.quickview_closed.emit()
def reject(self):
if not self.closed_by_button:
self.close_button_clicked()
else:
self._reject()
def _reject(self):
gui = self.gui
if self.is_pane:
gui.hide_panel('quick_view')
gui.library_view.setFocus(Qt.FocusReason.ActiveWindowFocusReason)
self._close()
QDialog.reject(self)
def get_qv_field_list(fm, use_defaults=False):
from calibre.gui2.ui import get_gui
db = get_gui().current_db
if use_defaults:
src = db.prefs.defaults
else:
src = db.prefs
fieldlist = list(src['qv_display_fields'])
names = frozenset(x[0] for x in fieldlist)
for field in fm.displayable_field_keys():
if (field != 'comments' and fm[field]['datatype'] != 'comments' and field not in names):
fieldlist.append((field, False))
available = frozenset(fm.displayable_field_keys())
return [(f, d) for f, d in fieldlist if f in available]
| 35,887 | Python | .py | 785 | 34.509554 | 120 | 0.597107 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,039 | tag_categories.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/tag_categories.py | __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
from collections import defaultdict, namedtuple
from qt.core import QApplication, QDialog, QIcon, QListWidgetItem, Qt
from calibre.constants import islinux
from calibre.gui2 import error_dialog, gprefs, warning_dialog
from calibre.gui2.dialogs.confirm_delete import confirm
from calibre.gui2.dialogs.tag_categories_ui import Ui_TagCategories
from calibre.utils.icu import lower as icu_lower
from calibre.utils.icu import primary_contains, primary_sort_key, strcmp
class TagCategories(QDialog, Ui_TagCategories):
'''
The structure of user_categories stored in preferences is
{cat_name: [ [name, category, v], [], [] ]}, cat_name: [ [name, cat, v] ...]}
where name is the item name, category is where it came from (series, etc),
and v is a scratch area.
If you add a category, set v to zero. If you delete a category, ensure that
both the name and the category match.
'''
category_icons = {'authors': QIcon.ic('user_profile.png'),
'series': QIcon.ic('series.png'),
'publisher': QIcon.ic('publisher.png'),
'tags': QIcon.ic('tags.png'),
'languages': QIcon.ic('languages.png')}
ItemTuple = namedtuple('ItemTuple', 'v k')
CategoryNameTuple = namedtuple('CategoryNameTuple', 'n k')
def __init__(self, window, db, on_category=None, book_ids=None):
QDialog.__init__(self, window)
Ui_TagCategories.__init__(self)
self.setupUi(self)
# I can't figure out how to get these into the .ui file
self.gridLayout_2.setColumnMinimumWidth(0, 50)
self.gridLayout_2.setColumnStretch(0, 1)
self.gridLayout_2.setColumnMinimumWidth(2, 50)
self.gridLayout_2.setColumnStretch(2, 1)
# Remove help icon on title bar
icon = self.windowIcon()
self.setWindowFlags(self.windowFlags()&(~Qt.WindowType.WindowContextHelpButtonHint))
self.setWindowIcon(icon)
self.db = db
self.applied_items = []
self.book_ids = book_ids
self.hide_hidden_categories = False
self.filter_by_vl = False
self.category_labels = [] # The label is the lookup key
if self.book_ids is None:
self.apply_vl_checkbox.setEnabled(False)
self.cc_icon = QIcon.ic('column.png')
# Build a dict of all available items, used when checking and building user cats
self.all_items = {}
db_categories = self.db.new_api.get_categories()
for key, tag in db_categories.items():
self.all_items[key] = {'icon': self.category_icons.get(key, self.cc_icon),
'name': self.db.field_metadata[key]['name'],
'values': {t.original_name for t in tag}
}
# build the list of all user categories. Filter out keys that no longer exist
self.user_categories = {}
for cat_name, values in db.new_api.pref('user_categories', {}).items():
fv = set()
for v in values:
if v[1] in self.db.field_metadata:
fv.add(self.item_tuple(v[1], v[0]))
self.user_categories[cat_name] = fv
# get the hidden categories
hidden_cats = self.db.new_api.pref('tag_browser_hidden_categories', None)
self.hidden_categories = set()
# strip non-existent field keys from hidden categories (just in case)
for cat in hidden_cats:
if cat in self.db.field_metadata:
self.hidden_categories.add(cat)
self.copy_category_name_to_clipboard.clicked.connect(self.copy_category_name_to_clipboard_clicked)
self.apply_button.clicked.connect(self.apply_button_clicked)
self.unapply_button.clicked.connect(self.unapply_button_clicked)
self.add_category_button.clicked.connect(self.add_category)
self.rename_category_button.clicked.connect(self.rename_category)
self.category_box.currentIndexChanged.connect(self.select_category)
self.category_filter_box.currentIndexChanged.connect(
self.display_filtered_categories)
self.item_filter_box.textEdited.connect(self.apply_filter)
self.delete_category_button.clicked.connect(self.delete_category)
if islinux:
self.available_items_box.itemDoubleClicked.connect(self.apply_tags)
else:
self.available_items_box.itemActivated.connect(self.apply_tags)
self.applied_items_box.itemActivated.connect(self.unapply_tags)
self.apply_vl_checkbox.clicked.connect(self.apply_vl_clicked)
self.hide_hidden_categories_checkbox.clicked.connect(self.hide_hidden_categories_clicked)
self.current_cat_name = None
self.initialize_category_lists()
self.display_filtered_categories()
self.populate_category_list()
if on_category is not None:
self.category_box.setCurrentIndex(self.category_box.findText(on_category))
if self.current_cat_name is None:
self.category_box.setCurrentIndex(0)
self.select_category(0)
self.restore_geometry(gprefs, 'user_category_editor_dialog_geometry')
def copy_category_name_to_clipboard_clicked(self):
t = self.category_box.itemText(self.category_box.currentIndex())
QApplication.clipboard().setText(t)
def item_tuple(self, key, val):
return self.ItemTuple(val, key)
def category_name_tuple(self, key, name):
return self.CategoryNameTuple(name, key)
def item_sort_key(self, v):
# Add the key so the order of identical items is predictable.
# The tab ensures that the values sort together regardless of key
return primary_sort_key(v.v + '\t ' + (v.k[1:] if v.k.startswith('#') else v.k))
def initialize_category_lists(self):
cfb = self.category_filter_box
current_cat_filter = (self.category_labels[cfb.currentIndex()]
if self.category_labels and cfb.currentIndex() > 0
else '')
# get the values for each category taking into account the VL, then
# populate the lists taking hidden and filtered categories into account
self.available_items = {}
self.sorted_items = []
sorted_categories = []
item_filter = self.item_filter_box.text()
db_categories = self.db.new_api.get_categories(book_ids=self.book_ids if
self.filter_by_vl else None)
for key, tags in db_categories.items():
if key == 'search' or key.startswith('@'):
continue
if self.hide_hidden_categories and key in self.hidden_categories:
continue
av = set()
for t in tags:
if item_filter and not primary_contains(item_filter, t.original_name):
continue
av.add(t.original_name)
self.sorted_items.append(self.item_tuple(key, t.original_name))
self.available_items[key] = av
sorted_categories.append(self.category_name_tuple(key, self.all_items[key]['name']))
self.sorted_items.sort(key=self.item_sort_key)
sorted_categories.sort(key=lambda v: primary_sort_key(v.n))
cfb.blockSignals(True)
cfb.clear()
cfb.addItem('', '')
for i,v in enumerate(sorted_categories):
cfb.addItem(f'{v.n} ({v.k})', v.k)
if current_cat_filter == v.k:
cfb.setCurrentIndex(i+1)
cfb.blockSignals(False)
def populate_category_list(self):
self.category_box.blockSignals(True)
self.category_box.clear()
self.category_box.addItems(sorted(self.user_categories.keys(), key=primary_sort_key))
self.category_box.blockSignals(False)
def make_available_list_item(self, key, val):
w = QListWidgetItem(self.all_items[key]['icon'], val)
w.setData(Qt.ItemDataRole.UserRole, self.item_tuple(key, val))
w.setToolTip(_('Lookup name: {}').format(key))
return w
def make_applied_list_item(self, tup):
if tup.v not in self.all_items[tup.k]['values']:
t = tup.v + ' ' + _('(Not in library)')
elif tup.k not in self.available_items:
t = tup.v + ' ' + _('(Hidden in Tag browser)')
elif tup.v not in self.available_items[tup.k]:
t = tup.v + ' ' + _('(Hidden by Virtual library)')
else:
t = tup.v
w = QListWidgetItem(self.all_items[tup.k]['icon'], t)
w.setData(Qt.ItemDataRole.UserRole, tup)
w.setToolTip(_('Lookup name: {}').format(tup.k))
return w
def hide_hidden_categories_clicked(self, checked):
self.hide_hidden_categories = checked
self.initialize_category_lists()
self.display_filtered_categories()
self.fill_applied_items()
def apply_vl_clicked(self, checked):
self.filter_by_vl = checked
self.initialize_category_lists()
self.fill_applied_items()
def apply_filter(self, _):
self.initialize_category_lists()
self.display_filtered_categories()
def display_filtered_categories(self):
idx = self.category_filter_box.currentIndex()
filter_key = self.category_filter_box.itemData(idx)
self.available_items_box.clear()
applied = defaultdict(set)
for it in self.applied_items:
applied[it.k].add(it.v)
for it in self.sorted_items:
if idx != 0 and it.k != filter_key:
continue
if it.v in applied[it.k]:
continue
self.available_items_box.addItem(self.make_available_list_item(it.k, it.v))
def fill_applied_items(self):
ccn = self.current_cat_name
if ccn:
self.applied_items = [v for v in self.user_categories[ccn]]
self.applied_items.sort(key=self.item_sort_key)
else:
self.applied_items = []
self.applied_items_box.clear()
for tup in self.applied_items:
self.applied_items_box.addItem(self.make_applied_list_item(tup))
self.display_filtered_categories()
def apply_button_clicked(self):
self.apply_tags(node=None)
def apply_tags(self, node=None):
if self.current_cat_name is None:
return
nodes = self.available_items_box.selectedItems() if node is None else [node]
if len(nodes) == 0:
warning_dialog(self, _('No items selected'),
_('You must select items to apply'),
show=True, show_copy_button=False)
return
for node in nodes:
tup = node.data(Qt.ItemDataRole.UserRole)
self.user_categories[self.current_cat_name].add(tup)
self.fill_applied_items()
def unapply_button_clicked(self):
self.unapply_tags(node=None)
def unapply_tags(self, node=None):
if self.current_cat_name is None:
return
nodes = self.applied_items_box.selectedItems() if node is None else [node]
if len(nodes) == 0:
warning_dialog(self, _('No items selected'),
_('You must select items to unapply'),
show=True, show_copy_button=False)
return
for node in nodes:
tup = node.data(Qt.ItemDataRole.UserRole)
self.user_categories[self.current_cat_name].discard(tup)
self.fill_applied_items()
def add_category(self):
cat_name = str(self.input_box.text()).strip()
if cat_name == '':
return
comps = [c.strip() for c in cat_name.split('.') if c.strip()]
if len(comps) == 0 or '.'.join(comps) != cat_name:
error_dialog(self, _('Invalid name'),
_('That name contains leading or trailing periods, '
'multiple periods in a row or spaces before '
'or after periods.')).exec()
return False
for c in sorted(self.user_categories.keys(), key=primary_sort_key):
if strcmp(c, cat_name) == 0:
error_dialog(self, _('Name already used'),
_('The user category name is already used, perhaps with different case.'),
det_msg=_('Existing category: {existing}\nNew category name: {new}').format(existing=c, new=cat_name),
show=True)
return False
if icu_lower(cat_name).startswith(icu_lower(c) + '.') and not cat_name.startswith(c + '.'):
error_dialog(self, _('Name already used'),
_('The hierarchical prefix of the new category is already used, '
'perhaps with different case.'),
det_msg=_('Existing prefix: {prefix}\n'
'New category name: {new}').format(prefix=c, new=cat_name),
show=True)
return False
if cat_name not in self.user_categories:
self.user_categories[cat_name] = set()
self.category_box.clear()
self.current_cat_name = cat_name
self.populate_category_list()
self.fill_applied_items()
self.input_box.clear()
self.category_box.setCurrentIndex(self.category_box.findText(cat_name))
def rename_category(self):
cat_name = str(self.input_box.text()).strip()
if cat_name == '':
return
if not self.current_cat_name:
return
comps = [c.strip() for c in cat_name.split('.') if c.strip()]
if len(comps) == 0 or '.'.join(comps) != cat_name:
error_dialog(self, _('Invalid name'),
_('That name contains leading or trailing periods, '
'multiple periods in a row or spaces before '
'or after periods.')).exec()
return
for c in self.user_categories:
if strcmp(c, cat_name) == 0:
error_dialog(self, _('Name already used'),
_('The user category name is already used, perhaps with different case.'),
det_msg=_('Existing category: {existing}\n'
'New category: {new}').format(existing=c, new=cat_name),
show=True)
return
# The order below is important because of signals
self.user_categories[cat_name] = self.user_categories[self.current_cat_name]
del self.user_categories[self.current_cat_name]
self.current_cat_name = None
self.populate_category_list()
self.input_box.clear()
self.category_box.setCurrentIndex(self.category_box.findText(cat_name))
return
def delete_category(self):
if self.current_cat_name is not None:
if not confirm('<p>'+_('The current User category will be '
'<b>permanently deleted</b>. Are you sure?') +
'</p>', 'tag_category_delete', self):
return
del self.user_categories[self.current_cat_name]
# self.category_box.removeItem(self.category_box.currentIndex())
self.populate_category_list()
if self.category_box.count():
self.current_cat_name = self.category_box.itemText(0)
else:
self.current_cat_name = None
self.fill_applied_items()
def select_category(self, idx):
s = self.category_box.itemText(idx)
if s:
self.current_cat_name = str(s)
else:
self.current_cat_name = None
self.fill_applied_items()
def accept(self):
# Reconstruct the pref value
self.categories = {}
for cat in self.user_categories:
cat_values = []
for tup in self.user_categories[cat]:
cat_values.append([tup.v, tup.k, 0])
self.categories[cat] = cat_values
super().save_geometry(gprefs, 'user_category_editor_dialog_geometry')
QDialog.accept(self)
def reject(self):
super().save_geometry(gprefs, 'user_category_editor_dialog_geometry')
QDialog.reject(self)
| 16,581 | Python | .py | 331 | 38.202417 | 126 | 0.60063 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,040 | message_box.py | kovidgoyal_calibre/src/calibre/gui2/dialogs/message_box.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import sys
from contextlib import suppress
from qt.core import (
QAction,
QApplication,
QCheckBox,
QDialog,
QDialogButtonBox,
QGridLayout,
QIcon,
QKeySequence,
QLabel,
QPainter,
QPlainTextEdit,
QSize,
QSizePolicy,
Qt,
QTextBrowser,
QTextDocument,
QVBoxLayout,
QWidget,
pyqtSignal,
)
from calibre.constants import __version__, isfrozen
from calibre.gui2 import gprefs
from calibre.utils.localization import ngettext
class Icon(QWidget):
def __init__(self, parent=None, size=None):
QWidget.__init__(self, parent)
self.pixmap = None
self.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
self.size = size or 64
def set_icon(self, qicon):
self.pixmap = qicon.pixmap(self.size, self.size)
self.update()
def sizeHint(self):
return QSize(self.size, self.size)
def paintEvent(self, ev):
if self.pixmap is not None:
x = (self.width() - self.size) // 2
y = (self.height() - self.size) // 2
p = QPainter(self)
p.drawPixmap(x, y, self.size, self.size, self.pixmap)
class MessageBox(QDialog): # {{{
ERROR = 0
WARNING = 1
INFO = 2
QUESTION = 3
resize_needed = pyqtSignal()
def setup_ui(self):
self.setObjectName("Dialog")
self.resize(497, 235)
self.gridLayout = l = QGridLayout(self)
l.setObjectName("gridLayout")
self.icon_widget = Icon(self)
l.addWidget(self.icon_widget)
self.msg = la = QLabel(self)
la.setWordWrap(True), la.setMinimumWidth(400)
la.setOpenExternalLinks(True)
la.setObjectName("msg")
l.addWidget(la, 0, 1, 1, 1)
self.det_msg = dm = QTextBrowser(self)
dm.setReadOnly(True)
dm.setObjectName("det_msg")
l.addWidget(dm, 1, 0, 1, 2)
self.bb = bb = QDialogButtonBox(self)
bb.setStandardButtons(QDialogButtonBox.StandardButton.Ok)
bb.setObjectName("bb")
bb.accepted.connect(self.accept)
bb.rejected.connect(self.reject)
l.addWidget(bb, 3, 0, 1, 2)
self.toggle_checkbox = tc = QCheckBox(self)
tc.setObjectName("toggle_checkbox")
l.addWidget(tc, 2, 0, 1, 2)
def __init__(
self, type_, title, msg,
det_msg='',
q_icon=None,
show_copy_button=True,
parent=None, default_yes=True,
yes_text=None, no_text=None, yes_icon=None, no_icon=None,
add_abort_button=False,
only_copy_details=False
):
super().__init__(parent)
self.only_copy_details = only_copy_details
self.aborted = False
if q_icon is None:
icon = {
self.ERROR : 'error',
self.WARNING: 'warning',
self.INFO: 'information',
self.QUESTION: 'question',
}[type_]
icon = 'dialog_%s.png'%icon
self.icon = QIcon.ic(icon)
else:
self.icon = q_icon if isinstance(q_icon, QIcon) else QIcon.ic(q_icon)
self.setup_ui()
self.setWindowTitle(title)
self.setWindowIcon(self.icon)
self.icon_widget.set_icon(self.icon)
self.msg.setText(msg)
if det_msg and Qt.mightBeRichText(det_msg):
self.det_msg.setHtml(det_msg)
else:
self.det_msg.setPlainText(det_msg)
self.det_msg.setVisible(False)
self.toggle_checkbox.setVisible(False)
if show_copy_button:
self.ctc_button = self.bb.addButton(_('&Copy to clipboard'),
QDialogButtonBox.ButtonRole.ActionRole)
self.ctc_button.clicked.connect(self.copy_to_clipboard)
self.show_det_msg = _('Show &details')
self.hide_det_msg = _('Hide &details')
self.det_msg_toggle = self.bb.addButton(self.show_det_msg, QDialogButtonBox.ButtonRole.ActionRole)
self.det_msg_toggle.clicked.connect(self.toggle_det_msg)
self.det_msg_toggle.setToolTip(
_('Show detailed information about this error'))
self.copy_action = QAction(self)
self.addAction(self.copy_action)
self.copy_action.setShortcuts(QKeySequence.StandardKey.Copy)
self.copy_action.triggered.connect(self.copy_to_clipboard)
self.is_question = type_ == self.QUESTION
if self.is_question:
self.bb.setStandardButtons(QDialogButtonBox.StandardButton.Yes|QDialogButtonBox.StandardButton.No)
self.bb.button(QDialogButtonBox.StandardButton.Yes if default_yes else QDialogButtonBox.StandardButton.No
).setDefault(True)
self.default_yes = default_yes
if yes_text is not None:
self.bb.button(QDialogButtonBox.StandardButton.Yes).setText(yes_text)
if no_text is not None:
self.bb.button(QDialogButtonBox.StandardButton.No).setText(no_text)
if yes_icon is not None:
self.bb.button(QDialogButtonBox.StandardButton.Yes).setIcon(yes_icon if isinstance(yes_icon, QIcon) else QIcon.ic(yes_icon))
if no_icon is not None:
self.bb.button(QDialogButtonBox.StandardButton.No).setIcon(no_icon if isinstance(no_icon, QIcon) else QIcon.ic(no_icon))
else:
self.bb.button(QDialogButtonBox.StandardButton.Ok).setDefault(True)
if add_abort_button:
self.bb.addButton(QDialogButtonBox.StandardButton.Abort).clicked.connect(self.on_abort)
if not det_msg:
self.det_msg_toggle.setVisible(False)
self.resize_needed.connect(self.do_resize)
self.do_resize()
def on_abort(self):
self.aborted = True
def toggle_det_msg(self, *args):
vis = self.det_msg.isVisible()
self.det_msg.setVisible(not vis)
self.det_msg_toggle.setText(self.show_det_msg if vis else self.hide_det_msg)
self.resize_needed.emit()
def do_resize(self):
sz = self.sizeHint()
sz.setWidth(max(min(sz.width(), 500), self.bb.sizeHint().width() + 100))
sz.setHeight(min(sz.height(), 500))
self.setMaximumSize(sz)
self.resize(self.sizeHint())
def copy_to_clipboard(self, *args):
text = self.det_msg.toPlainText()
if not self.only_copy_details:
text = f'calibre, version {__version__}\n{self.windowTitle()}: {self.msg.text()}\n\n{text}'
QApplication.clipboard().setText(text)
if hasattr(self, 'ctc_button'):
self.ctc_button.setText(_('Copied'))
def showEvent(self, ev):
ret = QDialog.showEvent(self, ev)
if self.is_question:
with suppress(Exception):
self.bb.button(QDialogButtonBox.StandardButton.Yes if self.default_yes else QDialogButtonBox.StandardButton.No
).setFocus(Qt.FocusReason.OtherFocusReason)
else:
self.bb.button(QDialogButtonBox.StandardButton.Ok).setFocus(Qt.FocusReason.OtherFocusReason)
return ret
def set_details(self, msg):
if not msg:
msg = ''
if Qt.mightBeRichText(msg):
self.det_msg.setHtml(msg)
else:
self.det_msg.setPlainText(msg)
self.det_msg_toggle.setText(self.show_det_msg)
self.det_msg_toggle.setVisible(bool(msg))
self.det_msg.setVisible(False)
self.resize_needed.emit()
# }}}
class ViewLog(QDialog): # {{{
def __init__(self, title, html, parent=None, unique_name=None):
QDialog.__init__(self, parent)
self.l = l = QVBoxLayout()
self.setLayout(l)
self.tb = QTextBrowser(self)
self.tb.setHtml('<pre style="font-family: monospace">%s</pre>' % html)
l.addWidget(self.tb)
self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok)
self.bb.accepted.connect(self.accept)
self.bb.rejected.connect(self.reject)
self.copy_button = self.bb.addButton(_('Copy to clipboard'),
QDialogButtonBox.ButtonRole.ActionRole)
self.copy_button.setIcon(QIcon.ic('edit-copy.png'))
self.copy_button.clicked.connect(self.copy_to_clipboard)
l.addWidget(self.bb)
self.unique_name = unique_name or 'view-log-dialog'
self.finished.connect(self.dialog_closing)
self.restore_geometry(gprefs, self.unique_name)
self.setModal(False)
self.setWindowTitle(title)
self.setWindowIcon(QIcon.ic('debug.png'))
self.show()
def sizeHint(self):
return QSize(700, 500)
def copy_to_clipboard(self):
txt = self.tb.toPlainText()
QApplication.clipboard().setText(txt)
def dialog_closing(self, result):
self.save_geometry(gprefs, self.unique_name)
# }}}
_proceed_memory = []
class ProceedNotification(MessageBox): # {{{
'''
WARNING: This class is deprecated. DO not use it as some users have
reported crashes when closing the dialog box generated by this class.
Instead use: gui.proceed_question(...) The arguments are the same as for
this class.
'''
def __init__(self, callback, payload, html_log, log_viewer_title, title, msg,
det_msg='', show_copy_button=False, parent=None,
cancel_callback=None, log_is_file=False):
'''
A non modal popup that notifies the user that a background task has
been completed.
:param callback: A callable that is called with payload if the user
asks to proceed. Note that this is always called in the GUI thread.
:param cancel_callback: A callable that is called with the payload if
the users asks not to proceed.
:param payload: Arbitrary object, passed to callback
:param html_log: An HTML or plain text log
:param log_viewer_title: The title for the log viewer window
:param title: The title for this popup
:param msg: The msg to display
:param det_msg: Detailed message
:param log_is_file: If True the html_log parameter is interpreted as
the path to a file on disk containing the log encoded with utf-8
'''
MessageBox.__init__(self, MessageBox.QUESTION, title, msg,
det_msg=det_msg, show_copy_button=show_copy_button,
parent=parent)
self.payload = payload
self.html_log = html_log
self.log_is_file = log_is_file
self.log_viewer_title = log_viewer_title
self.vlb = self.bb.addButton(_('&View log'), QDialogButtonBox.ButtonRole.ActionRole)
self.vlb.setIcon(QIcon.ic('debug.png'))
self.vlb.clicked.connect(self.show_log)
self.det_msg_toggle.setVisible(bool(det_msg))
self.setModal(False)
self.callback, self.cancel_callback = callback, cancel_callback
_proceed_memory.append(self)
def show_log(self):
log = self.html_log
if self.log_is_file:
with open(log, 'rb') as f:
log = f.read().decode('utf-8')
self.log_viewer = ViewLog(self.log_viewer_title, log,
parent=self)
def do_proceed(self, result):
from calibre.gui2.ui import get_gui
func = (self.callback if result == QDialog.DialogCode.Accepted else
self.cancel_callback)
gui = get_gui()
gui.proceed_requested.emit(func, self.payload)
# Ensure this notification is garbage collected
self.vlb.clicked.disconnect()
self.callback = self.cancel_callback = self.payload = None
self.setParent(None)
_proceed_memory.remove(self)
def done(self, r):
self.do_proceed(r)
return MessageBox.done(self, r)
# }}}
class ErrorNotification(MessageBox): # {{{
def __init__(self, html_log, log_viewer_title, title, msg,
det_msg='', show_copy_button=False, parent=None):
'''
A non modal popup that notifies the user that a background task has
errored.
:param html_log: An HTML or plain text log
:param log_viewer_title: The title for the log viewer window
:param title: The title for this popup
:param msg: The msg to display
:param det_msg: Detailed message
'''
MessageBox.__init__(self, MessageBox.ERROR, title, msg,
det_msg=det_msg, show_copy_button=show_copy_button,
parent=parent)
self.html_log = html_log
self.log_viewer_title = log_viewer_title
self.finished.connect(self.do_close, type=Qt.ConnectionType.QueuedConnection)
self.vlb = self.bb.addButton(_('&View log'), QDialogButtonBox.ButtonRole.ActionRole)
self.vlb.setIcon(QIcon.ic('debug.png'))
self.vlb.clicked.connect(self.show_log)
self.det_msg_toggle.setVisible(bool(det_msg))
self.setModal(False)
_proceed_memory.append(self)
def show_log(self):
self.log_viewer = ViewLog(self.log_viewer_title, self.html_log,
parent=self)
def do_close(self, result):
# Ensure this notification is garbage collected
self.setParent(None)
self.finished.disconnect()
self.vlb.clicked.disconnect()
_proceed_memory.remove(self)
# }}}
class JobError(QDialog): # {{{
WIDTH = 600
do_pop = pyqtSignal()
def __init__(self, parent):
QDialog.__init__(self, parent)
self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False)
self.queue = []
self.do_pop.connect(self.pop, type=Qt.ConnectionType.QueuedConnection)
self._layout = l = QGridLayout()
self.setLayout(l)
self.icon = QIcon.ic('dialog_error.png')
self.setWindowIcon(self.icon)
self.icon_widget = Icon(self)
self.icon_widget.set_icon(self.icon)
self.msg_label = QLabel('<p> ')
self.msg_label.setStyleSheet('QLabel { margin-top: 1ex; }')
self.msg_label.setWordWrap(True)
self.msg_label.setTextFormat(Qt.TextFormat.RichText)
self.det_msg = QPlainTextEdit(self)
self.det_msg.setVisible(False)
self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close, parent=self)
self.bb.accepted.connect(self.accept)
self.bb.rejected.connect(self.reject)
self.ctc_button = self.bb.addButton(_('&Copy to clipboard'),
QDialogButtonBox.ButtonRole.ActionRole)
self.ctc_button.clicked.connect(self.copy_to_clipboard)
self.retry_button = self.bb.addButton(_('&Retry'), QDialogButtonBox.ButtonRole.ActionRole)
self.retry_button.clicked.connect(self.retry)
self.retry_func = None
self.show_det_msg = _('Show &details')
self.hide_det_msg = _('Hide &details')
self.det_msg_toggle = self.bb.addButton(self.show_det_msg, QDialogButtonBox.ButtonRole.ActionRole)
self.det_msg_toggle.clicked.connect(self.toggle_det_msg)
self.det_msg_toggle.setToolTip(
_('Show detailed information about this error'))
self.suppress = QCheckBox(self)
l.addWidget(self.icon_widget, 0, 0, 1, 1)
l.addWidget(self.msg_label, 0, 1, 1, 1)
l.addWidget(self.det_msg, 1, 0, 1, 2)
l.addWidget(self.suppress, 2, 0, 1, 2, Qt.AlignmentFlag.AlignLeft|Qt.AlignmentFlag.AlignBottom)
l.addWidget(self.bb, 3, 0, 1, 2, Qt.AlignmentFlag.AlignRight|Qt.AlignmentFlag.AlignBottom)
l.setColumnStretch(1, 100)
self.setModal(False)
self.suppress.setVisible(False)
self.do_resize()
def retry(self):
if self.retry_func is not None:
self.accept()
self.retry_func()
def update_suppress_state(self):
self.suppress.setText(ngettext(
'Hide the remaining error message',
'Hide the {} remaining error messages', len(self.queue)).format(len(self.queue)))
self.suppress.setVisible(len(self.queue) > 3)
self.do_resize()
def copy_to_clipboard(self, *args):
d = QTextDocument()
d.setHtml(self.msg_label.text())
QApplication.clipboard().setText(
'calibre, version %s (%s, embedded-python: %s)\n%s: %s\n\n%s' %
(__version__, sys.platform, isfrozen,
str(self.windowTitle()), str(d.toPlainText()),
str(self.det_msg.toPlainText())))
if hasattr(self, 'ctc_button'):
self.ctc_button.setText(_('Copied'))
def toggle_det_msg(self, *args):
vis = str(self.det_msg_toggle.text()) == self.hide_det_msg
self.det_msg_toggle.setText(self.show_det_msg if vis else
self.hide_det_msg)
self.det_msg.setVisible(not vis)
self.do_resize()
def do_resize(self):
h = self.sizeHint().height()
self.setMinimumHeight(0) # Needed as this gets set if det_msg is shown
# Needed otherwise re-showing the box after showing det_msg causes the box
# to not reduce in height
self.setMaximumHeight(h)
self.resize(QSize(self.WIDTH, h))
def showEvent(self, ev):
ret = QDialog.showEvent(self, ev)
self.bb.button(QDialogButtonBox.StandardButton.Close).setFocus(Qt.FocusReason.OtherFocusReason)
return ret
def show_error(self, title, msg, det_msg='', retry_func=None):
self.queue.append((title, msg, det_msg, retry_func))
self.update_suppress_state()
self.pop()
def pop(self):
if not self.queue or self.isVisible():
return
title, msg, det_msg, retry_func = self.queue.pop(0)
self.setWindowTitle(title)
self.msg_label.setText(msg)
self.det_msg.setPlainText(det_msg)
self.det_msg.setVisible(False)
self.det_msg_toggle.setText(self.show_det_msg)
self.det_msg_toggle.setVisible(True)
self.suppress.setChecked(False)
self.update_suppress_state()
if not det_msg:
self.det_msg_toggle.setVisible(False)
self.retry_button.setVisible(retry_func is not None)
self.retry_func = retry_func
self.do_resize()
self.show()
def done(self, r):
if self.suppress.isChecked():
self.queue = []
QDialog.done(self, r)
self.do_pop.emit()
# }}}
if __name__ == '__main__':
from qt.core import QMainWindow, QTimer
from calibre import prepare_string_for_xml
from calibre.gui2 import Application, question_dialog
app = Application([])
merged = {'Kovid Goyal': ['Waterloo', 'Doomed'], 'Someone Else': ['Some other book ' * 1000]}
lines = []
for author in sorted(merged):
lines.append(f'<b><i>{prepare_string_for_xml(author)}</i></b><ol style="margin-top: 0">')
for title in sorted(merged[author]):
lines.append(f'<li>{prepare_string_for_xml(title)}</li>')
lines.append('</ol>')
w = QMainWindow()
w.show()
def doit():
print(question_dialog(w, 'title', 'msg <a href="http://google.com">goog</a> ',
det_msg='\n'.join(lines),
show_copy_button=True))
w.close()
QTimer.singleShot(100, doit)
app.exec()
| 19,419 | Python | .py | 449 | 34.184855 | 140 | 0.631426 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,041 | location.py | kovidgoyal_calibre/src/calibre/gui2/toc/location.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2013, Kovid Goyal <kovid at kovidgoyal.net>
import json
import os
import sys
import weakref
from functools import lru_cache
from qt.core import (
QApplication,
QByteArray,
QFrame,
QGridLayout,
QIcon,
QLabel,
QLineEdit,
QListWidget,
QPushButton,
QSize,
QSplitter,
Qt,
QUrl,
QVBoxLayout,
QWidget,
pyqtSignal,
)
from qt.webengine import (
QWebEnginePage,
QWebEngineProfile,
QWebEngineScript,
QWebEngineUrlRequestInterceptor,
QWebEngineUrlRequestJob,
QWebEngineUrlSchemeHandler,
QWebEngineView,
)
from calibre.constants import FAKE_HOST, FAKE_PROTOCOL
from calibre.ebooks.oeb.polish.utils import guess_type
from calibre.gui2 import error_dialog, gprefs, is_dark_theme, question_dialog
from calibre.gui2.palette import dark_color, dark_link_color, dark_text_color
from calibre.utils.logging import default_log
from calibre.utils.resources import get_path as P
from calibre.utils.short_uuid import uuid4
from calibre.utils.webengine import secure_webengine, send_reply, setup_profile
from polyglot.builtins import as_bytes
class RequestInterceptor(QWebEngineUrlRequestInterceptor):
def interceptRequest(self, request_info):
method = bytes(request_info.requestMethod())
if method not in (b'GET', b'HEAD'):
default_log.warn(f'Blocking URL request with method: {method}')
request_info.block(True)
return
qurl = request_info.requestUrl()
if qurl.scheme() not in (FAKE_PROTOCOL,):
default_log.warn(f'Blocking URL request {qurl.toString()} as it is not for a resource in the book')
request_info.block(True)
return
def current_container():
return getattr(current_container, 'ans', lambda: None)()
@lru_cache(maxsize=2)
def mathjax_dir():
return P('mathjax', allow_user_override=False)
class UrlSchemeHandler(QWebEngineUrlSchemeHandler):
def __init__(self, parent=None):
QWebEngineUrlSchemeHandler.__init__(self, parent)
self.allowed_hosts = (FAKE_HOST,)
def requestStarted(self, rq):
if bytes(rq.requestMethod()) != b'GET':
return self.fail_request(rq, QWebEngineUrlRequestJob.Error.RequestDenied)
c = current_container()
if c is None:
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)
path = url.path()
if path.startswith('/book/'):
name = path[len('/book/'):]
try:
mime_type = c.mime_map.get(name) or guess_type(name)
try:
with c.open(name) as f:
q = os.path.abspath(f.name)
if not q.startswith(c.root):
raise FileNotFoundError('Attempt to leave sandbox')
data = f.read()
except FileNotFoundError:
print(f'Could not find file {name} in book', file=sys.stderr)
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)
send_reply(rq, mime_type, data)
except Exception:
import traceback
traceback.print_exc()
return self.fail_request(rq, QWebEngineUrlRequestJob.Error.RequestFailed)
elif path.startswith('/mathjax/'):
try:
ignore, ignore, base, rest = path.split('/', 3)
except ValueError:
print(f'Could not find file {path} in mathjax', file=sys.stderr)
rq.fail(QWebEngineUrlRequestJob.Error.UrlNotFound)
return
try:
mime_type = guess_type(rest)
if base == 'loader' and '/' not in rest and '\\' not in rest:
data = P(rest, allow_user_override=False, data=True)
elif base == 'data':
q = os.path.abspath(os.path.join(mathjax_dir(), rest))
if not q.startswith(mathjax_dir()):
raise FileNotFoundError('')
with open(q, 'rb') as f:
data = f.read()
else:
raise FileNotFoundError('')
send_reply(rq, mime_type, data)
except FileNotFoundError:
print(f'Could not find file {path} in mathjax', file=sys.stderr)
rq.fail(QWebEngineUrlRequestJob.Error.UrlNotFound)
return
except Exception:
import traceback
traceback.print_exc()
return self.fail_request(rq, QWebEngineUrlRequestJob.Error.RequestFailed)
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)
print(f"Blocking FAKE_PROTOCOL request: {rq.requestUrl().toString()} with code: {fail_code}", file=sys.stderr)
class Page(QWebEnginePage): # {{{
elem_clicked = pyqtSignal(object, object, object, object, object)
frag_shown = pyqtSignal(object)
def __init__(self, parent, prefs):
self.log = default_log
self.current_frag = None
self.com_id = str(uuid4())
profile = QWebEngineProfile(QApplication.instance())
setup_profile(profile)
# store these globally as they need to be destructed after the QWebEnginePage
current_container.url_handler = UrlSchemeHandler(parent=profile)
current_container.interceptor = RequestInterceptor(profile)
current_container.profile_memory = profile
profile.installUrlSchemeHandler(QByteArray(FAKE_PROTOCOL.encode('ascii')), current_container.url_handler)
s = profile.settings()
s.setDefaultTextEncoding('utf-8')
profile.setUrlRequestInterceptor(current_container.interceptor)
QWebEnginePage.__init__(self, profile, parent)
secure_webengine(self, for_viewer=True)
self.titleChanged.connect(self.title_changed)
self.loadFinished.connect(self.show_frag)
s = QWebEngineScript()
s.setName('toc.js')
s.setInjectionPoint(QWebEngineScript.InjectionPoint.DocumentCreation)
s.setRunsOnSubFrames(True)
s.setWorldId(QWebEngineScript.ScriptWorldId.ApplicationWorld)
js = P('toc.js', allow_user_override=False, data=True).decode('utf-8').replace('COM_ID', self.com_id, 1)
if 'preview_background' in prefs.defaults and 'preview_foreground' in prefs.defaults:
from calibre.gui2.tweak_book.preview import get_editor_settings
settings = get_editor_settings(prefs)
else:
if is_dark_theme():
settings = {
'is_dark_theme': True,
'bg': dark_color.name(),
'fg': dark_text_color.name(),
'link': dark_link_color.name(),
}
else:
settings = {}
js = js.replace('SETTINGS', json.dumps(settings), 1)
s.setSourceCode(js)
self.scripts().insert(s)
def javaScriptConsoleMessage(self, level, msg, lineno, msgid):
self.log('JS:', str(msg))
def javaScriptAlert(self, origin, msg):
self.log(str(msg))
def title_changed(self, title):
parts = title.split('-', 1)
if len(parts) == 2 and parts[0] == self.com_id:
self.runJavaScript(
'JSON.stringify(window.calibre_toc_data)',
QWebEngineScript.ScriptWorldId.ApplicationWorld, self.onclick)
def onclick(self, data):
try:
tag, elem_id, loc, totals, frac = json.loads(data)
except Exception:
return
elem_id = elem_id or None
self.elem_clicked.emit(tag, frac, elem_id, loc, totals)
def show_frag(self, ok):
if ok and self.current_frag:
self.runJavaScript('''
document.location = '#non-existent-anchor';
document.location = '#' + {};
'''.format(json.dumps(self.current_frag)))
self.current_frag = None
self.runJavaScript('window.pageYOffset/document.body.scrollHeight', QWebEngineScript.ScriptWorldId.ApplicationWorld, self.frag_shown.emit)
# }}}
class WebView(QWebEngineView): # {{{
elem_clicked = pyqtSignal(object, object, object, object, object)
frag_shown = pyqtSignal(object)
def __init__(self, parent, prefs):
QWebEngineView.__init__(self, parent)
self._page = Page(self, prefs)
self._page.elem_clicked.connect(self.elem_clicked)
self._page.frag_shown.connect(self.frag_shown)
self.setPage(self._page)
def load_name(self, name, frag=None):
self._page.current_frag = frag
url = QUrl(f'{FAKE_PROTOCOL}://{FAKE_HOST}/')
url.setPath(f'/book/{name}')
self.setUrl(url)
def sizeHint(self):
return QSize(300, 300)
def contextMenuEvent(self, ev):
pass
# }}}
class ItemEdit(QWidget):
def __init__(self, parent, prefs=None):
QWidget.__init__(self, parent)
self.prefs = prefs or gprefs
self.pending_search = None
self.current_frag = None
self.setLayout(QVBoxLayout())
self.la = la = QLabel('<b>'+_(
'Select a destination for the Table of Contents entry'))
self.layout().addWidget(la)
self.splitter = sp = QSplitter(self)
self.layout().addWidget(sp)
self.layout().setStretch(1, 10)
sp.setOpaqueResize(False)
sp.setChildrenCollapsible(False)
self.dest_list = dl = QListWidget(self)
dl.setMinimumWidth(250)
dl.currentItemChanged.connect(self.current_changed)
sp.addWidget(dl)
w = self.w = QWidget(self)
l = w.l = QGridLayout()
w.setLayout(l)
self.view = WebView(self, self.prefs)
self.view.elem_clicked.connect(self.elem_clicked)
self.view.frag_shown.connect(self.update_dest_label, type=Qt.ConnectionType.QueuedConnection)
self.view.loadFinished.connect(self.load_finished, type=Qt.ConnectionType.QueuedConnection)
l.addWidget(self.view, 0, 0, 1, 3)
sp.addWidget(w)
self.search_text = s = QLineEdit(self)
s.setPlaceholderText(_('Search for text...'))
s.returnPressed.connect(self.find_next)
l.addWidget(s, 1, 0)
self.ns_button = b = QPushButton(QIcon.ic('arrow-down.png'), _('Find &next'), self)
b.clicked.connect(self.find_next)
l.addWidget(b, 1, 1)
self.ps_button = b = QPushButton(QIcon.ic('arrow-up.png'), _('Find &previous'), self)
l.addWidget(b, 1, 2)
b.clicked.connect(self.find_previous)
self.f = f = QFrame()
f.setFrameShape(QFrame.Shape.StyledPanel)
f.setMinimumWidth(250)
l = f.l = QVBoxLayout()
f.setLayout(l)
sp.addWidget(f)
f.la = la = QLabel('<p>'+_(
'Here you can choose a destination for the Table of Contents\' entry'
' to point to. First choose a file from the book in the left-most panel. The'
' file will open in the central panel.<p>'
'Then choose a location inside the file. To do so, simply click on'
' the place in the central panel that you want to use as the'
' destination. As you move the mouse around the central panel, a'
' thick green line appears, indicating the precise location'
' that will be selected when you click.'))
la.setStyleSheet('QLabel { margin-bottom: 20px }')
la.setWordWrap(True)
l.addWidget(la)
f.la2 = la = QLabel('<b>'+_('Na&me of the ToC entry:'))
l.addWidget(la)
self.name = QLineEdit(self)
self.name.setPlaceholderText(_('(Untitled)'))
la.setBuddy(self.name)
l.addWidget(self.name)
self.base_msg = '<b>'+_('Currently selected destination:')+'</b>'
self.dest_label = la = QLabel(self.base_msg)
la.setWordWrap(True)
la.setStyleSheet('QLabel { margin-top: 20px }')
l.addWidget(la)
l.addStretch()
state = self.prefs.get('toc_edit_splitter_state', None)
if state is not None:
sp.restoreState(state)
def load_finished(self, ok):
if self.pending_search:
self.pending_search()
self.pending_search = None
def keyPressEvent(self, ev):
if ev.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter) and self.search_text.hasFocus():
# Prevent pressing enter in the search box from triggering the dialog's accept() method
ev.accept()
return
return super().keyPressEvent(ev)
def find(self, forwards=True):
text = str(self.search_text.text()).strip()
flags = QWebEnginePage.FindFlag(0) if forwards else QWebEnginePage.FindFlag.FindBackward
self.find_data = text, flags, forwards
self.view.findText(text, flags, self.find_callback)
def find_callback(self, found):
d = self.dest_list
text, flags, forwards = self.find_data
if not found and text:
if d.count() == 1:
return error_dialog(self, _('No match found'),
_('No match found for: %s')%text, show=True)
delta = 1 if forwards else -1
current = str(d.currentItem().data(Qt.ItemDataRole.DisplayRole) or '')
next_index = (d.currentRow() + delta)%d.count()
next = str(d.item(next_index).data(Qt.ItemDataRole.DisplayRole) or '')
msg = '<p>'+_('No matches for %(text)s found in the current file [%(current)s].'
' Do you want to search in the %(which)s file [%(next)s]?')
msg = msg%dict(text=text, current=current, next=next,
which=_('next') if forwards else _('previous'))
if question_dialog(self, _('No match found'), msg):
self.pending_search = self.find_next if forwards else self.find_previous
d.setCurrentRow(next_index)
def find_next(self):
return self.find()
def find_previous(self):
return self.find(forwards=False)
def load(self, container):
self.container = container
current_container.ans = weakref.ref(container)
spine_names = [container.abspath_to_name(p) for p in
container.spine_items]
spine_names = [n for n in spine_names if container.has_name(n)]
self.dest_list.addItems(spine_names)
def current_changed(self, item):
name = self.current_name = str(item.data(Qt.ItemDataRole.DisplayRole) or '')
# Ensure encoding map is populated
root = self.container.parsed(name)
nasty = root.xpath('//*[local-name()="head"]/*[local-name()="p"]')
if nasty:
body = root.xpath('//*[local-name()="body"]')
if not body:
return error_dialog(self, _('Bad markup'),
_('This book has severely broken markup, its ToC cannot be edited.'), show=True)
for x in reversed(nasty):
body[0].insert(0, x)
self.container.commit_item(name, keep_parsed=True)
self.view.load_name(name, self.current_frag)
self.current_frag = None
self.dest_label.setText(self.base_msg + '<br>' + _('File:') + ' ' +
name + '<br>' + _('Top of the file'))
def __call__(self, item, where):
self.current_item, self.current_where = item, where
self.current_name = None
self.current_frag = None
self.name.setText('')
dest_index, frag = 0, None
if item is not None:
if where is None:
self.name.setText(item.data(0, Qt.ItemDataRole.DisplayRole) or '')
self.name.setCursorPosition(0)
toc = item.data(0, Qt.ItemDataRole.UserRole)
if toc.dest:
for i in range(self.dest_list.count()):
litem = self.dest_list.item(i)
if str(litem.data(Qt.ItemDataRole.DisplayRole) or '') == toc.dest:
dest_index = i
frag = toc.frag
break
self.dest_list.blockSignals(True)
self.dest_list.setCurrentRow(dest_index)
self.dest_list.blockSignals(False)
item = self.dest_list.item(dest_index)
if frag:
self.current_frag = frag
self.current_changed(item)
def get_loctext(self, frac):
frac = int(round(frac * 100))
if frac == 0:
loctext = _('Top of the file')
else:
loctext = _('Approximately %d%% from the top')%frac
return loctext
def elem_clicked(self, tag, frac, elem_id, loc, totals):
self.current_frag = elem_id or (loc, totals)
base = _('Location: A <%s> tag inside the file')%tag
loctext = base + ' [%s]'%self.get_loctext(frac)
self.dest_label.setText(self.base_msg + '<br>' +
_('File:') + ' ' + self.current_name + '<br>' + loctext)
def update_dest_label(self, val):
self.dest_label.setText(self.base_msg + '<br>' +
_('File:') + ' ' + self.current_name + '<br>' +
self.get_loctext(val))
@property
def result(self):
return (self.current_item, self.current_where, self.current_name,
self.current_frag, self.name.text().strip() or _('(Untitled)'))
| 18,339 | Python | .py | 402 | 34.880597 | 150 | 0.60151 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,042 | __init__.py | kovidgoyal_calibre/src/calibre/gui2/toc/__init__.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
| 152 | Python | .py | 4 | 35.75 | 61 | 0.678322 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,043 | main.py | kovidgoyal_calibre/src/calibre/gui2/toc/main.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2013, Kovid Goyal <kovid at kovidgoyal.net>
import os
import sys
import tempfile
import textwrap
from functools import partial
from threading import Thread
from time import monotonic
from qt.core import (
QAbstractItemView,
QCheckBox,
QCursor,
QDialog,
QDialogButtonBox,
QEvent,
QFrame,
QGridLayout,
QIcon,
QInputDialog,
QItemSelectionModel,
QKeySequence,
QLabel,
QMenu,
QPushButton,
QScrollArea,
QSize,
QSizePolicy,
QStackedWidget,
Qt,
QTimer,
QToolButton,
QTreeWidget,
QTreeWidgetItem,
QVBoxLayout,
QWidget,
pyqtSignal,
)
from calibre.constants import TOC_DIALOG_APP_UID, islinux, ismacos, iswindows
from calibre.ebooks.oeb.polish.container import AZW3Container, get_container
from calibre.ebooks.oeb.polish.toc import TOC, add_id, commit_toc, from_files, from_links, from_xpaths, get_toc
from calibre.gui2 import Application, error_dialog, info_dialog, set_app_uid
from calibre.gui2.convert.xpath_wizard import XPathEdit
from calibre.gui2.progress_indicator import ProgressIndicator
from calibre.gui2.toc.location import ItemEdit
from calibre.ptempfile import reset_base_dir
from calibre.startup import connect_lambda
from calibre.utils.config import JSONConfig
from calibre.utils.filenames import atomic_rename
from calibre.utils.icu import lower as icu_lower
from calibre.utils.icu import upper as icu_upper
from calibre.utils.logging import GUILog
ICON_SIZE = 24
class XPathDialog(QDialog): # {{{
def __init__(self, parent, prefs):
QDialog.__init__(self, parent)
self.prefs = prefs
self.setWindowTitle(_('Create ToC from XPath'))
self.l = l = QVBoxLayout()
self.setLayout(l)
self.la = la = QLabel(_(
'Specify a series of XPath expressions for the different levels of'
' the Table of Contents. You can use the wizard buttons to help'
' you create XPath expressions.'))
la.setWordWrap(True)
l.addWidget(la)
self.widgets = []
for i in range(5):
la = _('Level %s ToC:')%('&%d'%(i+1))
xp = XPathEdit(self)
xp.set_msg(la)
self.widgets.append(xp)
l.addWidget(xp)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel)
bb.accepted.connect(self.accept)
bb.rejected.connect(self.reject)
self.ssb = b = bb.addButton(_('&Save settings'), QDialogButtonBox.ButtonRole.ActionRole)
b.clicked.connect(self.save_settings)
self.load_button = b = bb.addButton(_('&Load settings'), QDialogButtonBox.ButtonRole.ActionRole)
self.load_menu = QMenu(b)
b.setMenu(self.load_menu)
self.setup_load_button()
self.remove_duplicates_cb = QCheckBox(_('Do not add duplicate entries at the same level'))
self.remove_duplicates_cb.setChecked(self.prefs.get('xpath_toc_remove_duplicates', True))
l.addWidget(self.remove_duplicates_cb)
l.addStretch()
l.addWidget(bb)
self.resize(self.sizeHint() + QSize(50, 75))
def save_settings(self):
xpaths = self.xpaths
if not xpaths:
return error_dialog(self, _('No XPaths'),
_('No XPaths have been entered'), show=True)
if not self.check():
return
name, ok = QInputDialog.getText(self, _('Choose name'),
_('Choose a name for these settings'))
if ok:
name = str(name).strip()
if name:
saved = self.prefs.get('xpath_toc_settings', {})
# in JSON all keys have to be strings
saved[name] = {str(i):x for i, x in enumerate(xpaths)}
self.prefs.set('xpath_toc_settings', saved)
self.setup_load_button()
def setup_load_button(self):
saved = self.prefs.get('xpath_toc_settings', {})
m = self.load_menu
m.clear()
self.__actions = []
a = self.__actions.append
for name in sorted(saved):
a(m.addAction(name, partial(self.load_settings, name)))
m.addSeparator()
a(m.addAction(_('Remove saved settings'), self.clear_settings))
self.load_button.setEnabled(bool(saved))
def clear_settings(self):
self.prefs.set('xpath_toc_settings', {})
self.setup_load_button()
def load_settings(self, name):
saved = self.prefs.get('xpath_toc_settings', {}).get(name, {})
for i, w in enumerate(self.widgets):
txt = saved.get(str(i), '')
w.edit.setText(txt)
def check(self):
for w in self.widgets:
if not w.check():
error_dialog(self, _('Invalid XPath'),
_('The XPath expression %s is not valid.')%w.xpath,
show=True)
return False
return True
def accept(self):
if self.check():
self.prefs.set('xpath_toc_remove_duplicates', self.remove_duplicates_cb.isChecked())
super().accept()
@property
def xpaths(self):
return [w.xpath for w in self.widgets if w.xpath.strip()]
# }}}
class ItemView(QStackedWidget): # {{{
add_new_item = pyqtSignal(object, object)
delete_item = pyqtSignal()
flatten_item = pyqtSignal()
go_to_root = pyqtSignal()
create_from_xpath = pyqtSignal(object, object, object)
create_from_links = pyqtSignal()
create_from_files = pyqtSignal()
flatten_toc = pyqtSignal()
def __init__(self, parent, prefs):
QStackedWidget.__init__(self, parent)
self.prefs = prefs
self.setMinimumWidth(250)
self.root_pane = rp = QWidget(self)
self.item_pane = ip = QWidget(self)
self.current_item = None
sa = QScrollArea(self)
sa.setWidgetResizable(True)
sa.setWidget(rp)
self.addWidget(sa)
sa = QScrollArea(self)
sa.setWidgetResizable(True)
sa.setWidget(ip)
self.addWidget(sa)
self.l1 = la = QLabel('<p>'+_(
'You can edit existing entries in the Table of Contents by clicking them'
' in the panel to the left.')+'<p>'+_(
'Entries with a green tick next to them point to a location that has '
'been verified to exist. Entries with a red dot are broken and may need'
' to be fixed.'))
la.setStyleSheet('QLabel { margin-bottom: 20px }')
la.setWordWrap(True)
l = rp.l = QVBoxLayout()
rp.setLayout(l)
l.addWidget(la)
self.add_new_to_root_button = b = QPushButton(_('Create a &new entry'))
b.clicked.connect(self.add_new_to_root)
l.addWidget(b)
l.addStretch()
self.cfmhb = b = QPushButton(_('Generate ToC from &major headings'))
b.clicked.connect(self.create_from_major_headings)
b.setToolTip(textwrap.fill(_(
'Generate a Table of Contents from the major headings in the book.'
' This will work if the book identifies its headings using HTML'
' heading tags. Uses the <h1>, <h2> and <h3> tags.')))
l.addWidget(b)
self.cfmab = b = QPushButton(_('Generate ToC from &all headings'))
b.clicked.connect(self.create_from_all_headings)
b.setToolTip(textwrap.fill(_(
'Generate a Table of Contents from all the headings in the book.'
' This will work if the book identifies its headings using HTML'
' heading tags. Uses the <h1-6> tags.')))
l.addWidget(b)
self.lb = b = QPushButton(_('Generate ToC from &links'))
b.clicked.connect(self.create_from_links)
b.setToolTip(textwrap.fill(_(
'Generate a Table of Contents from all the links in the book.'
' Links that point to destinations that do not exist in the book are'
' ignored. Also multiple links with the same destination or the same'
' text are ignored.'
)))
l.addWidget(b)
self.cfb = b = QPushButton(_('Generate ToC from &files'))
b.clicked.connect(self.create_from_files)
b.setToolTip(textwrap.fill(_(
'Generate a Table of Contents from individual files in the book.'
' Each entry in the ToC will point to the start of the file, the'
' text of the entry will be the "first line" of text from the file.'
)))
l.addWidget(b)
self.xpb = b = QPushButton(_('Generate ToC from &XPath'))
b.clicked.connect(self.create_from_user_xpath)
b.setToolTip(textwrap.fill(_(
'Generate a Table of Contents from arbitrary XPath expressions.'
)))
l.addWidget(b)
self.fal = b = QPushButton(_('&Flatten the ToC'))
b.clicked.connect(self.flatten_toc)
b.setToolTip(textwrap.fill(_(
'Flatten the Table of Contents, putting all entries at the top level'
)))
l.addWidget(b)
l.addStretch()
self.w1 = la = QLabel(_('<b>WARNING:</b> calibre only supports the '
'creation of linear ToCs in AZW3 files. In a '
'linear ToC every entry must point to a '
'location after the previous entry. If you '
'create a non-linear ToC it will be '
'automatically re-arranged inside the AZW3 file.'
))
la.setWordWrap(True)
l.addWidget(la)
l = ip.l = QGridLayout()
ip.setLayout(l)
la = ip.heading = QLabel('')
l.addWidget(la, 0, 0, 1, 2)
la.setWordWrap(True)
la = ip.la = QLabel(_(
'You can move this entry around the Table of Contents by drag '
'and drop or using the up and down buttons to the left'))
la.setWordWrap(True)
l.addWidget(la, 1, 0, 1, 2)
# Item status
ip.hl1 = hl = QFrame()
hl.setFrameShape(QFrame.Shape.HLine)
l.addWidget(hl, l.rowCount(), 0, 1, 2)
self.icon_label = QLabel()
self.status_label = QLabel()
self.status_label.setWordWrap(True)
l.addWidget(self.icon_label, l.rowCount(), 0)
l.addWidget(self.status_label, l.rowCount()-1, 1)
ip.hl2 = hl = QFrame()
hl.setFrameShape(QFrame.Shape.HLine)
l.addWidget(hl, l.rowCount(), 0, 1, 2)
# Edit/remove item
rs = l.rowCount()
ip.b1 = b = QPushButton(QIcon.ic('edit_input.png'),
_('Change the &location this entry points to'), self)
b.clicked.connect(self.edit_item)
l.addWidget(b, l.rowCount()+1, 0, 1, 2)
ip.b2 = b = QPushButton(QIcon.ic('trash.png'),
_('&Remove this entry'), self)
l.addWidget(b, l.rowCount(), 0, 1, 2)
b.clicked.connect(self.delete_item)
ip.hl3 = hl = QFrame()
hl.setFrameShape(QFrame.Shape.HLine)
l.addWidget(hl, l.rowCount(), 0, 1, 2)
l.setRowMinimumHeight(rs, 20)
# Add new item
rs = l.rowCount()
ip.b3 = b = QPushButton(QIcon.ic('plus.png'), _('New entry &inside this entry'))
connect_lambda(b.clicked, self, lambda self: self.add_new('inside'))
l.addWidget(b, l.rowCount()+1, 0, 1, 2)
ip.b4 = b = QPushButton(QIcon.ic('plus.png'), _('New entry &above this entry'))
connect_lambda(b.clicked, self, lambda self: self.add_new('before'))
l.addWidget(b, l.rowCount(), 0, 1, 2)
ip.b5 = b = QPushButton(QIcon.ic('plus.png'), _('New entry &below this entry'))
connect_lambda(b.clicked, self, lambda self: self.add_new('after'))
l.addWidget(b, l.rowCount(), 0, 1, 2)
# Flatten entry
ip.b3 = b = QPushButton(QIcon.ic('heuristics.png'), _('&Flatten this entry'))
b.clicked.connect(self.flatten_item)
b.setToolTip(_('All children of this entry are brought to the same '
'level as this entry.'))
l.addWidget(b, l.rowCount()+1, 0, 1, 2)
ip.hl4 = hl = QFrame()
hl.setFrameShape(QFrame.Shape.HLine)
l.addWidget(hl, l.rowCount(), 0, 1, 2)
l.setRowMinimumHeight(rs, 20)
# Return to welcome
rs = l.rowCount()
ip.b4 = b = QPushButton(QIcon.ic('back.png'), _('&Return to welcome screen'))
b.clicked.connect(self.go_to_root)
b.setToolTip(_('Go back to the top level view'))
l.addWidget(b, l.rowCount()+1, 0, 1, 2)
l.setRowMinimumHeight(rs, 20)
l.addWidget(QLabel(), l.rowCount(), 0, 1, 2)
l.setColumnStretch(1, 10)
l.setRowStretch(l.rowCount()-1, 10)
self.w2 = la = QLabel(self.w1.text())
self.w2.setWordWrap(True)
l.addWidget(la, l.rowCount(), 0, 1, 2)
def headings_question(self, xpaths):
from calibre.gui2.widgets2 import Dialog
class D(Dialog):
def __init__(self, parent):
super().__init__(_('Configure ToC generation'), 'configure-toc-from-headings', parent=parent)
def setup_ui(s):
s.l = l = QVBoxLayout(s)
s.remove_duplicates_cb = rd = QCheckBox(_('Remove &duplicated headings at the same ToC level'))
l.addWidget(rd)
rd.setChecked(bool(self.prefs.get('toc_from_headings_remove_duplicates', True)))
s.prefer_title_cb = pt = QCheckBox(_('Use the &title attribute for ToC text'))
l.addWidget(pt)
pt.setToolTip(textwrap.fill(_(
'When a heading tag has the "title" attribute use its contents as the text for the ToC entry,'
' instead of the text inside the heading tag itself.')))
pt.setChecked(bool(self.prefs.get('toc_from_headings_prefer_title')))
l.addWidget(s.bb)
d = D(self)
if d.exec() == QDialog.DialogCode.Accepted:
self.create_from_xpath.emit(xpaths, d.remove_duplicates_cb.isChecked(), d.prefer_title_cb.isChecked())
self.prefs.set('toc_from_headings_remove_duplicates', d.remove_duplicates_cb.isChecked())
self.prefs.set('toc_from_headings_prefer_title', d.prefer_title_cb.isChecked())
def create_from_major_headings(self):
self.headings_question(['//h:h%d'%i for i in range(1, 4)])
def create_from_all_headings(self):
self.headings_question(['//h:h%d'%i for i in range(1, 7)])
def create_from_user_xpath(self):
d = XPathDialog(self, self.prefs)
if d.exec() == QDialog.DialogCode.Accepted and d.xpaths:
self.create_from_xpath.emit(d.xpaths, d.remove_duplicates_cb.isChecked(), False)
def hide_azw3_warning(self):
self.w1.setVisible(False), self.w2.setVisible(False)
def add_new_to_root(self):
self.add_new_item.emit(None, None)
def add_new(self, where):
self.add_new_item.emit(self.current_item, where)
def edit_item(self):
self.add_new_item.emit(self.current_item, None)
def __call__(self, item):
if item is None:
self.current_item = None
self.setCurrentIndex(0)
else:
self.current_item = item
self.setCurrentIndex(1)
self.populate_item_pane()
def populate_item_pane(self):
item = self.current_item
name = str(item.data(0, Qt.ItemDataRole.DisplayRole) or '')
self.item_pane.heading.setText('<h2>%s</h2>'%name)
self.icon_label.setPixmap(item.data(0, Qt.ItemDataRole.DecorationRole
).pixmap(32, 32))
tt = _('This entry points to an existing destination')
toc = item.data(0, Qt.ItemDataRole.UserRole)
if toc.dest_exists is False:
tt = _('The location this entry points to does not exist')
elif toc.dest_exists is None:
tt = ''
self.status_label.setText(tt)
def data_changed(self, item):
if item is self.current_item:
self.populate_item_pane()
# }}}
NODE_FLAGS = (Qt.ItemFlag.ItemIsDragEnabled|Qt.ItemFlag.ItemIsEditable|Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsSelectable|Qt.ItemFlag.ItemIsDropEnabled)
class TreeWidget(QTreeWidget): # {{{
edit_item = pyqtSignal()
history_state_changed = pyqtSignal()
def __init__(self, parent):
QTreeWidget.__init__(self, parent)
self.history = []
self.setHeaderLabel(_('Table of Contents'))
self.setIconSize(QSize(ICON_SIZE, ICON_SIZE))
self.setDragEnabled(True)
self.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
self.viewport().setAcceptDrops(True)
self.setDropIndicatorShown(True)
self.setDragDropMode(QAbstractItemView.DragDropMode.InternalMove)
self.setAutoScroll(True)
self.setAutoScrollMargin(ICON_SIZE*2)
self.setDefaultDropAction(Qt.DropAction.MoveAction)
self.setAutoExpandDelay(1000)
self.setAnimated(True)
self.setMouseTracking(True)
self.in_drop_event = False
self.root = self.invisibleRootItem()
self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.customContextMenuRequested.connect(self.show_context_menu)
def push_history(self):
self.history.append(self.serialize_tree())
self.history_state_changed.emit()
def pop_history(self):
if self.history:
self.unserialize_tree(self.history.pop())
self.history_state_changed.emit()
def commitData(self, editor):
self.push_history()
return QTreeWidget.commitData(self, editor)
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 update_status_tip(self, item):
c = item.data(0, Qt.ItemDataRole.UserRole)
if c is not None:
frag = c.frag or ''
if frag:
frag = '#'+frag
item.setStatusTip(0, _('<b>Title</b>: {0} <b>Dest</b>: {1}{2}').format(
c.title, c.dest, frag))
def serialize_tree(self):
def serialize_node(node):
return {
'title': node.data(0, Qt.ItemDataRole.DisplayRole),
'toc_node': node.data(0, Qt.ItemDataRole.UserRole),
'icon': node.data(0, Qt.ItemDataRole.DecorationRole),
'tooltip': node.data(0, Qt.ItemDataRole.ToolTipRole),
'is_selected': node.isSelected(),
'is_expanded': node.isExpanded(),
'children': list(map(serialize_node, (node.child(i) for i in range(node.childCount())))),
}
node = self.invisibleRootItem()
return {'children': list(map(serialize_node, (node.child(i) for i in range(node.childCount()))))}
def unserialize_tree(self, serialized):
def unserialize_node(dict_node, parent):
n = QTreeWidgetItem(parent)
n.setData(0, Qt.ItemDataRole.DisplayRole, dict_node['title'])
n.setData(0, Qt.ItemDataRole.UserRole, dict_node['toc_node'])
n.setFlags(NODE_FLAGS)
n.setData(0, Qt.ItemDataRole.DecorationRole, dict_node['icon'])
n.setData(0, Qt.ItemDataRole.ToolTipRole, dict_node['tooltip'])
self.update_status_tip(n)
n.setExpanded(dict_node['is_expanded'])
n.setSelected(dict_node['is_selected'])
for c in dict_node['children']:
unserialize_node(c, n)
i = self.invisibleRootItem()
i.takeChildren()
for child in serialized['children']:
unserialize_node(child, i)
def dropEvent(self, event):
self.in_drop_event = True
self.push_history()
try:
super().dropEvent(event)
finally:
self.in_drop_event = False
def selectedIndexes(self):
ans = super().selectedIndexes()
if self.in_drop_event:
# For order to be preserved when moving by drag and drop, we
# have to ensure that selectedIndexes returns an ordered list of
# indexes.
sort_map = {self.indexFromItem(item):i for i, item in enumerate(self.iter_items())}
ans = sorted(ans, key=lambda x:sort_map.get(x, -1))
return ans
def highlight_item(self, item):
self.setCurrentItem(item, 0, QItemSelectionModel.SelectionFlag.ClearAndSelect)
self.scrollToItem(item)
def check_multi_selection(self):
if len(self.selectedItems()) > 1:
info_dialog(self, _('Multiple items selected'), _(
'You are trying to move multiple items at once, this is not supported. Instead use'
' Drag and Drop to move multiple items'), show=True)
return False
return True
def move_left(self):
if not self.check_multi_selection():
return
self.push_history()
item = self.currentItem()
if item is not None:
parent = item.parent()
if parent is not None:
is_expanded = item.isExpanded() or item.childCount() == 0
gp = parent.parent() or self.invisibleRootItem()
idx = gp.indexOfChild(parent)
for gc in [parent.child(i) for i in range(parent.indexOfChild(item)+1, parent.childCount())]:
parent.removeChild(gc)
item.addChild(gc)
parent.removeChild(item)
gp.insertChild(idx+1, item)
if is_expanded:
self.expandItem(item)
self.highlight_item(item)
def move_right(self):
if not self.check_multi_selection():
return
self.push_history()
item = self.currentItem()
if item is not None:
parent = item.parent() or self.invisibleRootItem()
idx = parent.indexOfChild(item)
if idx > 0:
is_expanded = item.isExpanded()
np = parent.child(idx-1)
parent.removeChild(item)
np.addChild(item)
if is_expanded:
self.expandItem(item)
self.highlight_item(item)
def move_down(self):
if not self.check_multi_selection():
return
self.push_history()
item = self.currentItem()
if item is None:
if self.root.childCount() == 0:
return
item = self.root.child(0)
self.highlight_item(item)
return
parent = item.parent() or self.root
idx = parent.indexOfChild(item)
if idx == parent.childCount() - 1:
# At end of parent, need to become sibling of parent
if parent is self.root:
return
gp = parent.parent() or self.root
parent.removeChild(item)
gp.insertChild(gp.indexOfChild(parent)+1, item)
else:
sibling = parent.child(idx+1)
parent.removeChild(item)
sibling.insertChild(0, item)
self.highlight_item(item)
def move_up(self):
if not self.check_multi_selection():
return
self.push_history()
item = self.currentItem()
if item is None:
if self.root.childCount() == 0:
return
item = self.root.child(self.root.childCount()-1)
self.highlight_item(item)
return
parent = item.parent() or self.root
idx = parent.indexOfChild(item)
if idx == 0:
# At end of parent, need to become sibling of parent
if parent is self.root:
return
gp = parent.parent() or self.root
parent.removeChild(item)
gp.insertChild(gp.indexOfChild(parent), item)
else:
sibling = parent.child(idx-1)
parent.removeChild(item)
sibling.addChild(item)
self.highlight_item(item)
def del_items(self):
self.push_history()
for item in self.selectedItems():
p = item.parent() or self.root
p.removeChild(item)
def title_case(self):
self.push_history()
from calibre.utils.titlecase import titlecase
for item in self.selectedItems():
t = str(item.data(0, Qt.ItemDataRole.DisplayRole) or '')
item.setData(0, Qt.ItemDataRole.DisplayRole, titlecase(t))
def upper_case(self):
self.push_history()
for item in self.selectedItems():
t = str(item.data(0, Qt.ItemDataRole.DisplayRole) or '')
item.setData(0, Qt.ItemDataRole.DisplayRole, icu_upper(t))
def lower_case(self):
self.push_history()
for item in self.selectedItems():
t = str(item.data(0, Qt.ItemDataRole.DisplayRole) or '')
item.setData(0, Qt.ItemDataRole.DisplayRole, icu_lower(t))
def swap_case(self):
self.push_history()
from calibre.utils.icu import swapcase
for item in self.selectedItems():
t = str(item.data(0, Qt.ItemDataRole.DisplayRole) or '')
item.setData(0, Qt.ItemDataRole.DisplayRole, swapcase(t))
def capitalize(self):
self.push_history()
from calibre.utils.icu import capitalize
for item in self.selectedItems():
t = str(item.data(0, Qt.ItemDataRole.DisplayRole) or '')
item.setData(0, Qt.ItemDataRole.DisplayRole, capitalize(t))
def bulk_rename(self):
from calibre.gui2.tweak_book.file_list import get_bulk_rename_settings
sort_map = {id(item):i for i, item in enumerate(self.iter_items())}
items = sorted(self.selectedItems(), key=lambda x:sort_map.get(id(x), -1))
settings = get_bulk_rename_settings(self, len(items), prefix=_('Chapter '), msg=_(
'All selected items will be renamed to the form prefix-number'), sanitize=lambda x:x, leading_zeros=False)
fmt, num = settings['prefix'], settings['start']
if fmt is not None and num is not None:
self.push_history()
for i, item in enumerate(items):
item.setData(0, Qt.ItemDataRole.DisplayRole, fmt % (num + i))
def keyPressEvent(self, ev):
if ev.key() == Qt.Key.Key_Left and ev.modifiers() & Qt.KeyboardModifier.ControlModifier:
self.move_left()
ev.accept()
elif ev.key() == Qt.Key.Key_Right and ev.modifiers() & Qt.KeyboardModifier.ControlModifier:
self.move_right()
ev.accept()
elif ev.key() == Qt.Key.Key_Up and (ev.modifiers() & Qt.KeyboardModifier.ControlModifier or ev.modifiers() & Qt.KeyboardModifier.AltModifier):
self.move_up()
ev.accept()
elif ev.key() == Qt.Key.Key_Down and (ev.modifiers() & Qt.KeyboardModifier.ControlModifier or ev.modifiers() & Qt.KeyboardModifier.AltModifier):
self.move_down()
ev.accept()
elif ev.key() in (Qt.Key.Key_Delete, Qt.Key.Key_Backspace):
self.del_items()
ev.accept()
else:
return super().keyPressEvent(ev)
def show_context_menu(self, point):
item = self.currentItem()
def key(k):
sc = str(QKeySequence(k | Qt.KeyboardModifier.ControlModifier).toString(QKeySequence.SequenceFormat.NativeText))
return ' [%s]'%sc
if item is not None:
m = QMenu(self)
m.addAction(QIcon.ic('edit_input.png'), _('Change the location this entry points to'), self.edit_item)
m.addAction(QIcon.ic('modified.png'), _('Bulk rename all selected items'), self.bulk_rename)
m.addAction(QIcon.ic('trash.png'), _('Remove all selected items'), self.del_items)
m.addSeparator()
ci = str(item.data(0, Qt.ItemDataRole.DisplayRole) or '')
p = item.parent() or self.invisibleRootItem()
idx = p.indexOfChild(item)
if idx > 0:
m.addAction(QIcon.ic('arrow-up.png'), (_('Move "%s" up')%ci)+key(Qt.Key.Key_Up), self.move_up)
if idx + 1 < p.childCount():
m.addAction(QIcon.ic('arrow-down.png'), (_('Move "%s" down')%ci)+key(Qt.Key.Key_Down), self.move_down)
if item.parent() is not None:
m.addAction(QIcon.ic('back.png'), (_('Unindent "%s"')%ci)+key(Qt.Key.Key_Left), self.move_left)
if idx > 0:
m.addAction(QIcon.ic('forward.png'), (_('Indent "%s"')%ci)+key(Qt.Key.Key_Right), self.move_right)
m.addSeparator()
case_menu = QMenu(_('Change case'), m)
case_menu.addAction(_('Upper case'), self.upper_case)
case_menu.addAction(_('Lower case'), self.lower_case)
case_menu.addAction(_('Swap case'), self.swap_case)
case_menu.addAction(_('Title case'), self.title_case)
case_menu.addAction(_('Capitalize'), self.capitalize)
m.addMenu(case_menu)
m.exec(QCursor.pos())
# }}}
class TOCView(QWidget): # {{{
add_new_item = pyqtSignal(object, object)
def __init__(self, parent, prefs):
QWidget.__init__(self, parent)
self.toc_title = None
self.prefs = prefs
l = self.l = QGridLayout()
self.setLayout(l)
self.tocw = t = TreeWidget(self)
self.tocw.edit_item.connect(self.edit_item)
l.addWidget(t, 0, 0, 7, 3)
self.up_button = b = QToolButton(self)
b.setIcon(QIcon.ic('arrow-up.png'))
b.setIconSize(QSize(ICON_SIZE, ICON_SIZE))
l.addWidget(b, 0, 3)
b.setToolTip(_('Move current entry up [Ctrl+Up]'))
b.clicked.connect(self.move_up)
self.left_button = b = QToolButton(self)
b.setIcon(QIcon.ic('back.png'))
b.setIconSize(QSize(ICON_SIZE, ICON_SIZE))
l.addWidget(b, 2, 3)
b.setToolTip(_('Unindent the current entry [Ctrl+Left]'))
b.clicked.connect(self.tocw.move_left)
self.del_button = b = QToolButton(self)
b.setIcon(QIcon.ic('trash.png'))
b.setIconSize(QSize(ICON_SIZE, ICON_SIZE))
l.addWidget(b, 3, 3)
b.setToolTip(_('Remove all selected entries'))
b.clicked.connect(self.del_items)
self.right_button = b = QToolButton(self)
b.setIcon(QIcon.ic('forward.png'))
b.setIconSize(QSize(ICON_SIZE, ICON_SIZE))
l.addWidget(b, 4, 3)
b.setToolTip(_('Indent the current entry [Ctrl+Right]'))
b.clicked.connect(self.tocw.move_right)
self.down_button = b = QToolButton(self)
b.setIcon(QIcon.ic('arrow-down.png'))
b.setIconSize(QSize(ICON_SIZE, ICON_SIZE))
l.addWidget(b, 6, 3)
b.setToolTip(_('Move current entry down [Ctrl+Down]'))
b.clicked.connect(self.move_down)
self.expand_all_button = b = QPushButton(_('&Expand all'))
col = 7
l.addWidget(b, col, 0)
b.clicked.connect(self.tocw.expandAll)
self.collapse_all_button = b = QPushButton(_('&Collapse all'))
b.clicked.connect(self.tocw.collapseAll)
l.addWidget(b, col, 1)
self.default_msg = _('Double click on an entry to change the text')
self.hl = hl = QLabel(self.default_msg)
hl.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Ignored)
l.addWidget(hl, col, 2, 1, -1)
self.item_view = i = ItemView(self, self.prefs)
self.item_view.delete_item.connect(self.delete_current_item)
i.add_new_item.connect(self.add_new_item)
i.create_from_xpath.connect(self.create_from_xpath)
i.create_from_links.connect(self.create_from_links)
i.create_from_files.connect(self.create_from_files)
i.flatten_item.connect(self.flatten_item)
i.flatten_toc.connect(self.flatten_toc)
i.go_to_root.connect(self.go_to_root)
l.addWidget(i, 0, 4, col, 1)
l.setColumnStretch(2, 10)
def edit_item(self):
self.item_view.edit_item()
def event(self, e):
if e.type() == QEvent.Type.StatusTip:
txt = str(e.tip()) or self.default_msg
self.hl.setText(txt)
return super().event(e)
def item_title(self, item):
return str(item.data(0, Qt.ItemDataRole.DisplayRole) or '')
def del_items(self):
self.tocw.del_items()
def delete_current_item(self):
item = self.tocw.currentItem()
if item is not None:
self.tocw.push_history()
p = item.parent() or self.root
p.removeChild(item)
def iter_items(self, parent=None):
yield from self.tocw.iter_items(parent=parent)
def flatten_toc(self):
self.tocw.push_history()
found = True
while found:
found = False
for item in self.iter_items():
if item.childCount() > 0:
self._flatten_item(item)
found = True
break
def flatten_item(self):
self.tocw.push_history()
self._flatten_item(self.tocw.currentItem())
def _flatten_item(self, item):
if item is not None:
p = item.parent() or self.root
idx = p.indexOfChild(item)
children = [item.child(i) for i in range(item.childCount())]
for child in reversed(children):
item.removeChild(child)
p.insertChild(idx+1, child)
def go_to_root(self):
self.tocw.setCurrentItem(None)
def highlight_item(self, item):
self.tocw.highlight_item(item)
def move_up(self):
self.tocw.move_up()
def move_down(self):
self.tocw.move_down()
def data_changed(self, top_left, bottom_right):
for r in range(top_left.row(), bottom_right.row()+1):
idx = self.tocw.model().index(r, 0, top_left.parent())
new_title = str(idx.data(Qt.ItemDataRole.DisplayRole) or '').strip()
toc = idx.data(Qt.ItemDataRole.UserRole)
if toc is not None:
toc.title = new_title or _('(Untitled)')
item = self.tocw.itemFromIndex(idx)
self.tocw.update_status_tip(item)
self.item_view.data_changed(item)
def create_item(self, parent, child, idx=-1):
if idx == -1:
c = QTreeWidgetItem(parent)
else:
c = QTreeWidgetItem()
parent.insertChild(idx, c)
self.populate_item(c, child)
return c
def populate_item(self, c, child):
c.setData(0, Qt.ItemDataRole.DisplayRole, child.title or _('(Untitled)'))
c.setData(0, Qt.ItemDataRole.UserRole, child)
c.setFlags(NODE_FLAGS)
c.setData(0, Qt.ItemDataRole.DecorationRole, self.icon_map[child.dest_exists])
if child.dest_exists is False:
c.setData(0, Qt.ItemDataRole.ToolTipRole, _(
'The location this entry point to does not exist:\n%s')
%child.dest_error)
else:
c.setData(0, Qt.ItemDataRole.ToolTipRole, None)
self.tocw.update_status_tip(c)
def __call__(self, ebook):
self.ebook = ebook
if not isinstance(ebook, AZW3Container):
self.item_view.hide_azw3_warning()
self.toc = get_toc(self.ebook)
self.toc_lang, self.toc_uid = self.toc.lang, self.toc.uid
self.toc_title = self.toc.toc_title
self.blank = QIcon.ic('blank.png')
self.ok = QIcon.ic('ok.png')
self.err = QIcon.ic('dot_red.png')
self.icon_map = {None:self.blank, True:self.ok, False:self.err}
def process_item(toc_node, parent):
for child in toc_node:
c = self.create_item(parent, child)
process_item(child, c)
root = self.root = self.tocw.invisibleRootItem()
root.setData(0, Qt.ItemDataRole.UserRole, self.toc)
process_item(self.toc, root)
self.tocw.model().dataChanged.connect(self.data_changed)
self.tocw.currentItemChanged.connect(self.current_item_changed)
self.tocw.setCurrentItem(None)
def current_item_changed(self, current, previous):
self.item_view(current)
def update_item(self, item, where, name, frag, title):
if isinstance(frag, tuple):
frag = add_id(self.ebook, name, *frag)
child = TOC(title, name, frag)
child.dest_exists = True
self.tocw.push_history()
if item is None:
# New entry at root level
c = self.create_item(self.root, child)
self.tocw.setCurrentItem(c, 0, QItemSelectionModel.SelectionFlag.ClearAndSelect)
self.tocw.scrollToItem(c)
else:
if where is None:
# Editing existing entry
self.populate_item(item, child)
else:
if where == 'inside':
parent = item
idx = -1
else:
parent = item.parent() or self.root
idx = parent.indexOfChild(item)
if where == 'after':
idx += 1
c = self.create_item(parent, child, idx=idx)
self.tocw.setCurrentItem(c, 0, QItemSelectionModel.SelectionFlag.ClearAndSelect)
self.tocw.scrollToItem(c)
def create_toc(self):
root = TOC()
def process_node(parent, toc_parent):
for i in range(parent.childCount()):
item = parent.child(i)
title = str(item.data(0, Qt.ItemDataRole.DisplayRole) or '').strip()
toc = item.data(0, Qt.ItemDataRole.UserRole)
dest, frag = toc.dest, toc.frag
toc = toc_parent.add(title, dest, frag)
process_node(item, toc)
process_node(self.tocw.invisibleRootItem(), root)
return root
def insert_toc_fragment(self, toc):
def process_node(root, tocparent, added):
for child in tocparent:
item = self.create_item(root, child)
added.append(item)
process_node(item, child, added)
self.tocw.push_history()
nodes = []
process_node(self.root, toc, nodes)
self.highlight_item(nodes[0])
def create_from_xpath(self, xpaths, remove_duplicates=True, prefer_title=False):
toc = from_xpaths(self.ebook, xpaths, prefer_title=prefer_title)
if len(toc) == 0:
return error_dialog(self, _('No items found'),
_('No items were found that could be added to the Table of Contents.'), show=True)
if remove_duplicates:
toc.remove_duplicates()
self.insert_toc_fragment(toc)
def create_from_links(self):
toc = from_links(self.ebook)
if len(toc) == 0:
return error_dialog(self, _('No items found'),
_('No links were found that could be added to the Table of Contents.'), show=True)
self.insert_toc_fragment(toc)
def create_from_files(self):
toc = from_files(self.ebook)
if len(toc) == 0:
return error_dialog(self, _('No items found'),
_('No files were found that could be added to the Table of Contents.'), show=True)
self.insert_toc_fragment(toc)
def undo(self):
self.tocw.pop_history()
# }}}
te_prefs = JSONConfig('toc-editor')
class TOCEditor(QDialog): # {{{
explode_done = pyqtSignal(object)
writing_done = pyqtSignal(object)
def __init__(self, pathtobook, title=None, parent=None, prefs=None, write_result_to=None):
QDialog.__init__(self, parent)
self.last_reject_at = self.last_accept_at = -1000
self.write_result_to = write_result_to
self.prefs = prefs or te_prefs
self.pathtobook = pathtobook
self.working = True
t = title or os.path.basename(pathtobook)
self.book_title = t
self.setWindowTitle(_('Edit the ToC in %s')%t)
self.setWindowIcon(QIcon.ic('highlight_only_on.png'))
l = self.l = QVBoxLayout()
self.setLayout(l)
self.stacks = s = QStackedWidget(self)
l.addWidget(s)
self.loading_widget = lw = QWidget(self)
s.addWidget(lw)
ll = self.ll = QVBoxLayout(lw)
self.pi = pi = ProgressIndicator()
pi.setDisplaySize(QSize(200, 200))
pi.startAnimation()
ll.addWidget(pi, alignment=Qt.AlignmentFlag.AlignHCenter|Qt.AlignmentFlag.AlignCenter)
la = self.wait_label = QLabel(_('Loading %s, please wait...')%t)
la.setWordWrap(True)
f = la.font()
f.setPointSize(20), la.setFont(f)
ll.addWidget(la, alignment=Qt.AlignmentFlag.AlignHCenter|Qt.AlignmentFlag.AlignTop)
self.toc_view = TOCView(self, self.prefs)
self.toc_view.add_new_item.connect(self.add_new_item)
self.toc_view.tocw.history_state_changed.connect(self.update_history_buttons)
s.addWidget(self.toc_view)
self.item_edit = ItemEdit(self)
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.explode_done.connect(self.read_toc, type=Qt.ConnectionType.QueuedConnection)
self.writing_done.connect(self.really_accept, type=Qt.ConnectionType.QueuedConnection)
self.restore_geometry(self.prefs, 'toc_editor_window_geom')
self.stacks.currentChanged.connect(self.update_history_buttons)
self.update_history_buttons()
def sizeHint(self):
return QSize(900, 600)
def update_history_buttons(self):
self.undo_button.setVisible(self.stacks.currentIndex() == 1)
self.undo_button.setEnabled(bool(self.toc_view.tocw.history))
def add_new_item(self, item, where):
self.item_edit(item, where)
self.stacks.setCurrentIndex(2)
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() == 2:
self.toc_view.update_item(*self.item_edit.result)
self.prefs['toc_edit_splitter_state'] = bytearray(self.item_edit.splitter.saveState())
self.stacks.setCurrentIndex(1)
elif self.stacks.currentIndex() == 1:
self.working = False
Thread(target=self.write_toc).start()
self.pi.startAnimation()
self.wait_label.setText(_('Writing %s, please wait...')%
self.book_title)
self.stacks.setCurrentIndex(0)
self.bb.setEnabled(False)
def really_accept(self, tb):
self.save_geometry(self.prefs, '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
self.write_result(0)
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() == 2:
self.prefs['toc_edit_splitter_state'] = bytearray(self.item_edit.splitter.saveState())
self.stacks.setCurrentIndex(1)
else:
self.working = False
self.save_geometry(self.prefs, 'toc_editor_window_geom')
self.write_result(1)
super().reject()
def write_result(self, res):
if self.write_result_to:
with tempfile.NamedTemporaryFile(dir=os.path.dirname(self.write_result_to), delete=False) as f:
src = f.name
f.write(str(res).encode('utf-8'))
f.flush()
atomic_rename(src, self.write_result_to)
def start(self):
t = Thread(target=self.explode)
t.daemon = True
self.log = GUILog()
t.start()
def explode(self):
tb = None
try:
self.ebook = get_container(self.pathtobook, log=self.log)
except Exception:
import traceback
tb = traceback.format_exc()
if self.working:
self.working = False
self.explode_done.emit(tb)
def read_toc(self, tb):
if tb:
error_dialog(self, _('Failed to load book'),
_('Could not load %s. Click "Show details" for'
' more information.')%self.book_title, det_msg=tb, show=True)
self.reject()
return
self.pi.stopAnimation()
self.toc_view(self.ebook)
self.item_edit.load(self.ebook)
self.stacks.setCurrentIndex(1)
def write_toc(self):
tb = None
try:
toc = self.toc_view.create_toc()
toc.toc_title = getattr(self.toc_view, 'toc_title', None)
commit_toc(self.ebook, toc, lang=self.toc_view.toc_lang,
uid=self.toc_view.toc_uid)
self.ebook.commit()
except:
import traceback
tb = traceback.format_exc()
self.writing_done.emit(tb)
# }}}
def develop():
from calibre.utils.webengine import setup_fake_protocol
setup_fake_protocol()
from calibre.gui2 import Application
app = Application([])
d = TOCEditor(sys.argv[-1])
d.start()
d.exec()
del app
def main(shm_name=None):
import json
import struct
from calibre.utils.shm import SharedMemory
# Ensure we can continue to function if GUI is closed
os.environ.pop('CALIBRE_WORKER_TEMP_DIR', None)
reset_base_dir()
if iswindows:
# Ensure that all instances are grouped together in the task bar. This
# prevents them from being grouped with viewer/editor process when
# launched from within calibre, as both use calibre-parallel.exe
set_app_uid(TOC_DIALOG_APP_UID)
with SharedMemory(name=shm_name) as shm:
pos = struct.calcsize('>II')
state, ok = struct.unpack('>II', shm.read(pos))
data = json.loads(shm.read_data_with_size())
title = data['title']
path = data['path']
s = struct.pack('>I', 1)
shm.seek(0), shm.write(s), shm.flush()
override = 'calibre-gui' if islinux else None
app = Application([], override_program_name=override)
from calibre.utils.webengine import setup_default_profile, setup_fake_protocol
setup_fake_protocol()
setup_default_profile()
d = TOCEditor(path, title=title, write_result_to=path + '.result')
d.start()
ok = 0
if d.exec() == QDialog.DialogCode.Accepted:
ok = 1
s = struct.pack('>II', 2, ok)
shm.seek(0), shm.write(s), shm.flush()
del d
del app
raise SystemExit(0 if ok else 1)
if __name__ == '__main__':
main(path=sys.argv[-1], title='test')
os.remove(sys.argv[-1] + '.lock')
| 48,338 | Python | .py | 1,084 | 34.298893 | 156 | 0.601746 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,044 | text.py | kovidgoyal_calibre/src/calibre/gui2/lrf_renderer/text.py | __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
import collections
import copy
import numbers
import operator
import re
import sys
from qt.core import QBrush, QColor, QFont, QFontMetrics, QGraphicsItem, QGraphicsPixmapItem, QGraphicsRectItem, QPen, QPixmap, QRectF, Qt
from calibre.ebooks.hyphenate import hyphenate_word
from calibre.ebooks.lrf.fonts import LIBERATION_FONT_MAP
from polyglot.builtins import string_or_bytes
def WEIGHT_MAP(wt):
return int(wt / 10 - 1)
def NULL(a, b):
return a
def COLOR(a, b):
return QColor(*a)
def WEIGHT(a, b):
return WEIGHT_MAP(a)
class PixmapItem(QGraphicsPixmapItem):
def __init__(self, data, encoding, x0, y0, x1, y1, xsize, ysize):
p = QPixmap()
p.loadFromData(data, encoding, Qt.ImageConversionFlag.AutoColor)
w, h = p.width(), p.height()
p = p.copy(x0, y0, min(w, x1-x0), min(h, y1-y0))
if p.width() != xsize or p.height() != ysize:
p = p.scaled(int(xsize), int(ysize), Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation)
QGraphicsPixmapItem.__init__(self, p)
self.height, self.width = ysize, xsize
self.setTransformationMode(Qt.TransformationMode.SmoothTransformation)
self.setShapeMode(QGraphicsPixmapItem.ShapeMode.BoundingRectShape)
def resize(self, width, height):
p = self.pixmap()
self.setPixmap(p.scaled(int(width), int(height), Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation))
self.width, self.height = width, height
class Plot(PixmapItem):
def __init__(self, plot, dpi):
img = plot.refobj
xsize, ysize = dpi*plot.attrs['xsize']/720, dpi*plot.attrs['ysize']/720
x0, y0, x1, y1 = img.x0, img.y0, img.x1, img.y1
data, encoding = img.data, img.encoding
PixmapItem.__init__(self, data, encoding, x0, y0, x1, y1, xsize, ysize)
class FontLoader:
font_map = {
'Swis721 BT Roman' : 'Liberation Sans',
'Dutch801 Rm BT Roman' : 'Liberation Serif',
'Courier10 BT Roman' : 'Liberation Mono',
}
def __init__(self, font_map, dpi):
self.face_map = {}
self.cache = {}
self.dpi = dpi
self.face_map = font_map
def font(self, text_style):
device_font = text_style.fontfacename in LIBERATION_FONT_MAP
try:
if device_font:
face = self.font_map[text_style.fontfacename]
else:
face = self.face_map[text_style.fontfacename]
except KeyError: # Bad fontfacename field in LRF
face = self.font_map['Dutch801 Rm BT Roman']
sz = text_style.fontsize
wt = text_style.fontweight
style = text_style.fontstyle
font = (face, wt, style, sz,)
if font in self.cache:
rfont = self.cache[font]
else:
italic = font[2] == QFont.Style.StyleItalic
rfont = QFont(font[0], int(font[3]), int(font[1]), italic)
rfont.setPixelSize(int(font[3]))
rfont.setBold(wt>=69)
self.cache[font] = rfont
qfont = rfont
if text_style.emplinetype != 'none':
qfont = QFont(rfont)
qfont.setOverline(text_style.emplineposition == 'before')
qfont.setUnderline(text_style.emplineposition == 'after')
return qfont
class Style:
map = collections.defaultdict(lambda : NULL)
def __init__(self, style, dpi):
self.fdpi = dpi/720
self.update(style.as_dict())
def update(self, *args, **kwds):
if len(args) > 0:
kwds = args[0]
for attr in kwds:
setattr(self, attr, self.__class__.map[attr](kwds[attr], self.fdpi))
def copy(self):
return copy.copy(self)
class TextStyle(Style):
map = collections.defaultdict(lambda : NULL,
fontsize=operator.mul,
fontwidth=operator.mul,
fontweight=WEIGHT,
textcolor=COLOR,
textbgcolor=COLOR,
wordspace=operator.mul,
letterspace=operator.mul,
baselineskip=operator.mul,
linespace=operator.mul,
parindent=operator.mul,
parskip=operator.mul,
textlinewidth=operator.mul,
charspace=operator.mul,
linecolor=COLOR,
)
def __init__(self, style, font_loader, ruby_tags):
self.font_loader = font_loader
self.fontstyle = QFont.Style.StyleNormal
for attr in ruby_tags:
setattr(self, attr, ruby_tags[attr])
Style.__init__(self, style, font_loader.dpi)
self.emplinetype = 'none'
self.font = self.font_loader.font(self)
def update(self, *args, **kwds):
Style.update(self, *args, **kwds)
self.font = self.font_loader.font(self)
class BlockStyle(Style):
map = collections.defaultdict(lambda : NULL,
bgcolor=COLOR,
framecolor=COLOR,
)
class ParSkip:
def __init__(self, parskip):
self.height = parskip
def __str__(self):
return 'Parskip: '+str(self.height)
class TextBlock:
class HeightExceeded(Exception):
pass
has_content = property(fget=lambda self: self.peek_index < len(self.lines)-1)
XML_ENTITIES = {
"apos" : "'",
"quot" : '"',
"amp" : "&",
"lt" : "<",
"gt" : ">"
}
def __init__(self, tb, font_loader, respect_max_y, text_width, logger,
opts, ruby_tags, link_activated):
self.block_id = tb.id
self.bs, self.ts = BlockStyle(tb.style, font_loader.dpi), \
TextStyle(tb.textstyle, font_loader, ruby_tags)
self.bs.update(tb.attrs)
self.ts.update(tb.attrs)
self.lines = collections.deque()
self.line_length = min(self.bs.blockwidth, text_width)
self.line_length -= 2*self.bs.sidemargin
self.line_offset = self.bs.sidemargin
self.first_line = True
self.current_style = self.ts.copy()
self.current_line = None
self.font_loader, self.logger, self.opts = font_loader, logger, opts
self.in_link = False
self.link_activated = link_activated
self.max_y = self.bs.blockheight if (respect_max_y or self.bs.blockrule.lower() in ('vert-fixed', 'block-fixed')) else sys.maxsize
self.height = 0
self.peek_index = -1
try:
self.populate(tb.content)
self.end_line()
except TextBlock.HeightExceeded:
pass
# logger.warning('TextBlock height exceeded, skipping line:\n%s'%(err,))
def peek(self):
return self.lines[self.peek_index+1]
def commit(self):
self.peek_index += 1
def reset(self):
self.peek_index = -1
def create_link(self, refobj):
if self.current_line is None:
self.create_line()
self.current_line.start_link(refobj, self.link_activated)
self.link_activated(refobj, on_creation=True)
def end_link(self):
if self.current_line is not None:
self.current_line.end_link()
def close_valign(self):
if self.current_line is not None:
self.current_line.valign = None
def populate(self, tb):
self.create_line()
open_containers = collections.deque()
self.in_para = False
for i in tb.content:
if isinstance(i, string_or_bytes):
self.process_text(i)
elif i is None:
if len(open_containers) > 0:
for a, b in open_containers.pop():
if callable(a):
a(*b)
else:
setattr(self, a, b)
elif i.name == 'P':
open_containers.append((('in_para', False),))
self.in_para = True
elif i.name == 'CR':
if self.in_para:
self.end_line()
self.create_line()
else:
self.end_line()
delta = getattr(self.current_style, 'parskip', 0)
if isinstance(self.lines[-1], ParSkip):
delta += self.current_style.baselineskip
self.lines.append(ParSkip(delta))
self.first_line = True
elif i.name == 'Span':
open_containers.append((('current_style', self.current_style.copy()),))
self.current_style.update(i.attrs)
elif i.name == 'CharButton':
open_containers.append(((self.end_link, []),))
self.create_link(i.attrs['refobj'])
elif i.name == 'Italic':
open_containers.append((('current_style', self.current_style.copy()),))
self.current_style.update(fontstyle=QFont.Style.StyleItalic)
elif i.name == 'Plot':
plot = Plot(i, self.font_loader.dpi)
if self.current_line is None:
self.create_line()
if not self.current_line.can_add_plot(plot):
self.end_line()
self.create_line()
self.current_line.add_plot(plot)
elif i.name in ['Sup', 'Sub']:
if self.current_line is None:
self.create_line()
self.current_line.valign = i.name
open_containers.append(((self.close_valign, []),))
elif i.name == 'Space' and self.current_line is not None:
self.current_line.add_space(i.attrs['xsize'])
elif i.name == 'EmpLine':
if i.attrs:
open_containers.append((('current_style', self.current_style.copy()),))
self.current_style.update(i.attrs)
else:
self.logger.warning('Unhandled TextTag %s'%(i.name,))
if not i.self_closing:
open_containers.append([])
def end_line(self):
if self.current_line is not None:
self.height += self.current_line.finalize(self.current_style.baselineskip,
self.current_style.linespace,
self.opts.visual_debug)
if self.height > self.max_y+10:
raise TextBlock.HeightExceeded(str(self.current_line))
self.lines.append(self.current_line)
self.current_line = None
def create_line(self):
line_length = self.line_length
line_offset = self.line_offset
if self.first_line:
line_length -= self.current_style.parindent
line_offset += self.current_style.parindent
self.current_line = Line(line_length, line_offset,
self.current_style.linespace,
self.current_style.align,
self.opts.hyphenate, self.block_id)
self.first_line = False
def process_text(self, raw):
for ent, rep in TextBlock.XML_ENTITIES.items():
raw = raw.replace('&%s;'%ent, rep)
while len(raw) > 0:
if self.current_line is None:
self.create_line()
pos, line_filled = self.current_line.populate(raw, self.current_style)
raw = raw[pos:]
if line_filled:
self.end_line()
if not pos:
break
def __iter__(self):
yield from self.lines
def __str__(self):
s = ''
for line in self:
s += str(line) + '\n'
return s
class Link(QGraphicsRectItem):
inactive_brush = QBrush(QColor(0xff, 0xff, 0xff, 0xff))
active_brush = QBrush(QColor(0x00, 0x00, 0x00, 0x59))
def __init__(self, parent, start, stop, refobj, slot):
QGraphicsRectItem.__init__(self, start, 0, stop-start, parent.height, parent)
self.refobj = refobj
self.slot = slot
self.brush = self.__class__.inactive_brush
self.setPen(QPen(Qt.PenStyle.NoPen))
self.setCursor(Qt.CursorShape.PointingHandCursor)
self.setAcceptHoverEvents(True)
def hoverEnterEvent(self, event):
self.brush = self.__class__.active_brush
self.parentItem().update()
def hoverLeaveEvent(self, event):
self.brush = self.__class__.inactive_brush
self.parentItem().update()
def mousePressEvent(self, event):
self.hoverLeaveEvent(None)
self.slot(self.refobj)
class Line(QGraphicsItem):
whitespace = re.compile(r'\s+')
def __init__(self, line_length, offset, linespace, align, hyphenate, block_id):
QGraphicsItem.__init__(self)
self.line_length, self.offset, self.line_space = line_length, offset, linespace
self.align, self.hyphenate, self.block_id = align, hyphenate, block_id
self.tokens = collections.deque()
self.current_width = 0
self.length_in_space = 0
self.height, self.descent, self.width = 0, 0, 0
self.links = collections.deque()
self.current_link = None
self.valign = None
if not hasattr(self, 'children'):
self.children = self.childItems
def start_link(self, refobj, slot):
self.current_link = [self.current_width, sys.maxsize, refobj, slot]
def end_link(self):
if self.current_link is not None:
self.current_link[1] = self.current_width
self.links.append(self.current_link)
self.current_link = None
def can_add_plot(self, plot):
return self.line_length - self.current_width >= plot.width
def add_plot(self, plot):
self.tokens.append(plot)
self.current_width += plot.width
self.height = max(self.height, plot.height)
self.add_space(6)
def populate(self, phrase, ts, process_space=True):
phrase_pos = 0
processed = False
matches = self.__class__.whitespace.finditer(phrase)
font = QFont(ts.font)
if self.valign is not None:
font.setPixelSize(int(font.pixelSize()/1.5))
fm = QFontMetrics(font)
single_space_width = fm.horizontalAdvance(' ')
height, descent = fm.height(), fm.descent()
for match in matches:
processed = True
left, right = match.span()
if not process_space:
right = left
space_width = single_space_width * (right-left)
word = phrase[phrase_pos:left]
width = fm.horizontalAdvance(word)
if self.current_width + width < self.line_length:
self.commit(word, width, height, descent, ts, font)
if space_width > 0 and self.current_width + space_width < self.line_length:
self.add_space(space_width)
phrase_pos = right
continue
# Word doesn't fit on line
if self.hyphenate and len(word) > 3:
tokens = hyphenate_word(word)
for i in range(len(tokens)-2, -1, -1):
word = ''.join(tokens[0:i+1])+'-'
width = fm.horizontalAdvance(word)
if self.current_width + width < self.line_length:
self.commit(word, width, height, descent, ts, font)
return phrase_pos + len(word)-1, True
if self.current_width < 5: # Force hyphenation as word is longer than line
for i in range(len(word)-5, 0, -5):
part = word[:i] + '-'
width = fm.horizontalAdvance(part)
if self.current_width + width < self.line_length:
self.commit(part, width, height, descent, ts, font)
return phrase_pos + len(part)-1, True
# Failed to add word.
return phrase_pos, True
if not processed:
return self.populate(phrase+' ', ts, False)
return phrase_pos, False
def commit(self, word, width, height, descent, ts, font):
self.tokens.append(Word(word, width, height, ts, font, self.valign))
self.current_width += width
self.height = max(self.height, height)
self.descent = max(self.descent, descent)
def add_space(self, min_width):
self.tokens.append(min_width)
self.current_width += min_width
self.length_in_space += min_width
def justify(self):
delta = self.line_length - self.current_width
if self.length_in_space > 0:
frac = 1 + float(delta)/self.length_in_space
for i in range(len(self.tokens)):
if isinstance(self.tokens[i], numbers.Number):
self.tokens[i] *= frac
self.current_width = self.line_length
def finalize(self, baselineskip, linespace, vdebug):
if self.current_link is not None:
self.end_link()
# We justify if line is small and it doesn't have links in it
# If it has links, justification would cause the boundingrect of the link to
# be too small
if self.current_width >= 0.85 * self.line_length and len(self.links) == 0:
self.justify()
self.width = float(self.current_width)
if self.height == 0:
self.height = baselineskip
self.height = float(self.height)
self.vdebug = vdebug
for link in self.links:
Link(self, *link)
return self.height
def boundingRect(self):
return QRectF(0, 0, self.width, self.height)
def paint(self, painter, option, widget):
x, y = 0, 0+self.height-self.descent
if self.vdebug:
painter.save()
painter.setPen(QPen(Qt.GlobalColor.yellow, 1, Qt.PenStyle.DotLine))
painter.drawRect(self.boundingRect())
painter.restore()
painter.save()
painter.setPen(QPen(Qt.PenStyle.NoPen))
for c in self.children():
painter.setBrush(c.brush)
painter.drawRect(c.boundingRect())
painter.restore()
painter.save()
for tok in self.tokens:
if isinstance(tok, numbers.Number):
x += tok
elif isinstance(tok, Word):
painter.setFont(tok.font)
if tok.highlight:
painter.save()
painter.setPen(QPen(Qt.PenStyle.NoPen))
painter.setBrush(QBrush(Qt.GlobalColor.yellow))
painter.drawRect(int(x), 0, tok.width, tok.height)
painter.restore()
painter.setPen(QPen(tok.text_color))
if tok.valign is None:
painter.drawText(int(x), int(y), tok.string)
elif tok.valign == 'Sub':
painter.drawText(int(x+1), int(y+self.descent/1.5), tok.string)
elif tok.valign == 'Sup':
painter.drawText(int(x+1), int(y-2.*self.descent), tok.string)
x += tok.width
else:
painter.drawPixmap(int(x), 0, tok.pixmap())
x += tok.width
painter.restore()
def words(self):
for w in self.tokens:
if isinstance(w, Word):
yield w
def search(self, phrase):
tokens = phrase.lower().split()
if len(tokens) < 1:
return None
words = self.words()
matches = []
try:
while True:
word = next(words)
word.highlight = False
if tokens[0] in str(word.string).lower():
matches.append(word)
for c in range(1, len(tokens)):
word = next(words)
print(tokens[c], word.string)
if tokens[c] not in str(word.string):
return None
matches.append(word)
for w in matches:
w.highlight = True
return self
except StopIteration:
return None
def getx(self, textwidth):
if self.align == 'head':
return self.offset
if self.align == 'foot':
return textwidth - self.width
if self.align == 'center':
return (textwidth-self.width)/2.
def __unicode__(self):
s = ''
for tok in self.tokens:
if isinstance(tok, numbers.Number):
s += ' '
elif isinstance(tok, Word):
s += str(tok.string)
return s
def __str__(self):
return str(self).encode('utf-8')
class Word:
def __init__(self, string, width, height, ts, font, valign):
self.string, self.width, self.height = string, width, height
self.font = font
self.text_color = ts.textcolor
self.highlight = False
self.valign = valign
def main(args=sys.argv):
return 0
if __name__ == '__main__':
sys.exit(main())
| 21,311 | Python | .py | 505 | 30.580198 | 139 | 0.564917 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,045 | __init__.py | kovidgoyal_calibre/src/calibre/gui2/lrf_renderer/__init__.py | __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
| 87 | Python | .py | 2 | 42.5 | 61 | 0.647059 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,046 | bookview.py | kovidgoyal_calibre/src/calibre/gui2/lrf_renderer/bookview.py | __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
from qt.core import QGraphicsView, QSize
class BookView(QGraphicsView):
MINIMUM_SIZE = QSize(400, 500)
def __init__(self, parent=None):
QGraphicsView.__init__(self, parent)
self.preferred_size = self.MINIMUM_SIZE
def minimumSizeHint(self):
return self.MINIMUM_SIZE
def sizeHint(self):
return self.preferred_size
def resize_for(self, width, height):
self.preferred_size = QSize(width, height)
| 547 | Python | .py | 14 | 33.214286 | 61 | 0.681905 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,047 | document.py | kovidgoyal_calibre/src/calibre/gui2/lrf_renderer/document.py | __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
import collections
import glob
import itertools
from qt.core import QBrush, QByteArray, QColor, QFontDatabase, QGraphicsItem, QGraphicsLineItem, QGraphicsRectItem, QGraphicsScene, QPen, Qt, pyqtSignal
from calibre.ebooks.lrf.objects import Canvas as __Canvas
from calibre.ebooks.lrf.objects import RuledLine as _RuledLine
from calibre.gui2.lrf_renderer.text import COLOR, FontLoader, PixmapItem, TextBlock
from calibre.utils.resources import get_path as P
class Color(QColor):
def __init__(self, color):
QColor.__init__(self, color.r, color.g, color.b, 0xff-color.a)
class Pen(QPen):
def __init__(self, color, width):
QPen.__init__(self, QBrush(Color(color)), width,
(Qt.PenStyle.SolidLine if width > 0 else Qt.PenStyle.NoPen))
class ContentObject:
has_content = True
def reset(self):
self.has_content = True
class RuledLine(QGraphicsLineItem, ContentObject):
map = {'solid': Qt.PenStyle.SolidLine, 'dashed': Qt.PenStyle.DashLine, 'dotted': Qt.PenStyle.DotLine, 'double': Qt.PenStyle.DashDotLine}
def __init__(self, rl):
QGraphicsLineItem.__init__(self, 0, 0, rl.linelength, 0)
ContentObject.__init__(self)
self.setPen(QPen(COLOR(rl.linecolor, None), rl.linewidth, ))
class ImageBlock(PixmapItem, ContentObject):
def __init__(self, obj):
ContentObject.__init__(self)
x0, y0, x1, y1 = obj.attrs['x0'], obj.attrs['y0'], obj.attrs['x1'], obj.attrs['y1']
xsize, ysize, refstream = obj.attrs['xsize'], obj.attrs['ysize'], obj.refstream
data, encoding = refstream.stream, refstream.encoding
PixmapItem.__init__(self, data, encoding, x0, y0, x1, y1, xsize, ysize)
self.block_id = obj.id
def object_factory(container, obj, respect_max_y=False):
if hasattr(obj, 'name'):
if obj.name.endswith('TextBlock'):
return TextBlock(obj, container.font_loader, respect_max_y, container.text_width,
container.logger, container.opts, container.ruby_tags,
container.link_activated)
elif obj.name.endswith('ImageBlock'):
return ImageBlock(obj)
elif isinstance(obj, _RuledLine):
return RuledLine(obj)
elif isinstance(obj, __Canvas):
return Canvas(container.font_loader, obj, container.logger, container.opts,
container.ruby_tags, container.link_activated)
return None
class _Canvas(QGraphicsRectItem):
def __init__(self, font_loader, logger, opts, width=0, height=0, parent=None, x=0, y=0):
QGraphicsRectItem.__init__(self, x, y, width, height, parent)
self.font_loader, self.logger, self.opts = font_loader, logger, opts
self.current_y, self.max_y, self.max_x = 0, height, width
self.is_full = False
pen = QPen()
pen.setStyle(Qt.PenStyle.NoPen)
self.setPen(pen)
if not hasattr(self, 'children'):
self.children = self.childItems
def layout_block(self, block, x, y):
if isinstance(block, TextBlock):
self.layout_text_block(block, x, y)
elif isinstance(block, RuledLine):
self.layout_ruled_line(block, x, y)
elif isinstance(block, ImageBlock):
self.layout_image_block(block, x, y)
elif isinstance(block, Canvas):
self.layout_canvas(block, x, y)
def layout_canvas(self, canvas, x, y):
if canvas.max_y + y > self.max_y and y > 0:
self.is_full = True
return
canvas.setParentItem(self)
canvas.setPos(x, y)
canvas.has_content = False
canvas.put_objects()
self.current_y += canvas.max_y
def layout_text_block(self, block, x, y):
textwidth = block.bs.blockwidth - block.bs.sidemargin
if block.max_y == 0 or not block.lines: # Empty block skipping
self.is_full = False
return
line = block.peek()
y += block.bs.topskip
block_consumed = False
line.height = min(line.height, self.max_y-block.bs.topskip) # LRF files from TOR have Plot elements with their height set to 800
while y + line.height <= self.max_y:
block.commit()
if isinstance(line, QGraphicsItem):
line.setParentItem(self)
line.setPos(x + line.getx(textwidth), y)
y += line.height + line.line_space
else:
y += line.height
if not block.has_content:
try:
y += block.bs.footskip
except AttributeError: # makelrf generates BlockStyles without footskip
pass
block_consumed = True
break
else:
line = block.peek()
self.current_y = y
self.is_full = not block_consumed
def layout_ruled_line(self, rl, x, y):
br = rl.boundingRect()
rl.setParentItem(self)
rl.setPos(x, y+1)
self.current_y = y + br.height() + 1
self.is_full = y > self.max_y-5
rl.has_content = False
def layout_image_block(self, ib, x, y):
mw, mh = self.max_x - x, self.max_y - y
if self.current_y + ib.height > self.max_y-y and self.current_y > 5:
self.is_full = True
else:
if ib.width > mw or ib.height > mh:
ib.resize(mw, mh)
br = ib.boundingRect()
max_height = min(br.height(), self.max_y-y)
max_width = min(br.width(), self.max_x-x)
if br.height() > max_height or br.width() > max_width:
p = ib.pixmap()
ib.setPixmap(p.scaled(int(max_width), int(max_height), Qt.AspectRatioMode.IgnoreAspectRatio,
Qt.TransformationMode.SmoothTransformation))
br = ib.boundingRect()
ib.setParentItem(self)
ib.setPos(x, y)
self.current_y = y + br.height()
self.is_full = y > self.max_y-5
ib.has_content = False
if ib.block_id == 54:
print()
print(ib.block_id, ib.has_content, self.is_full)
print(self.current_y, self.max_y, y, br.height())
print()
def search(self, phrase):
matches = []
for child in self.children():
if hasattr(child, 'search'):
res = child.search(phrase)
if res:
if isinstance(res, list):
matches += res
else:
matches.append(res)
return matches
class Canvas(_Canvas, ContentObject):
def __init__(self, font_loader, canvas, logger, opts, ruby_tags, link_activated, width=0, height=0):
if hasattr(canvas, 'canvaswidth'):
width, height = canvas.canvaswidth, canvas.canvasheight
_Canvas.__init__(self, font_loader, logger, opts, width=width, height=height)
self.block_id = canvas.id
self.ruby_tags = ruby_tags
self.link_activated = link_activated
self.text_width = width
fg = canvas.framecolor
bg = canvas.bgcolor
if not opts.visual_debug and canvas.framemode != 'none':
self.setPen(Pen(fg, canvas.framewidth))
self.setBrush(QBrush(Color(bg)))
self.items = []
for po in canvas:
obj = po.object
item = object_factory(self, obj, respect_max_y=True)
if item:
self.items.append((item, po.x1, po.y1))
def put_objects(self):
for block, x, y in self.items:
self.layout_block(block, x, y)
def layout_block(self, block, x, y):
block.reset()
_Canvas.layout_block(self, block, x, y)
class Header(Canvas):
def __init__(self, font_loader, header, page_style, logger, opts, ruby_tags, link_activated):
Canvas.__init__(self, font_loader, header, logger, opts, ruby_tags, link_activated,
page_style.textwidth, page_style.headheight)
if opts.visual_debug:
self.setPen(QPen(Qt.GlobalColor.blue, 1, Qt.PenStyle.DashLine))
class Footer(Canvas):
def __init__(self, font_loader, footer, page_style, logger, opts, ruby_tags, link_activated):
Canvas.__init__(self, font_loader, footer, logger, opts, ruby_tags, link_activated,
page_style.textwidth, page_style.footheight)
if opts.visual_debug:
self.setPen(QPen(Qt.GlobalColor.blue, 1, Qt.PenStyle.DashLine))
class Screen(_Canvas):
def __init__(self, font_loader, chapter, odd, logger, opts, ruby_tags, link_activated):
self.logger, self.opts = logger, opts
page_style = chapter.style
sidemargin = page_style.oddsidemargin if odd else page_style.evensidemargin
width = 2*sidemargin + page_style.textwidth
self.content_x = 0 + sidemargin
self.text_width = page_style.textwidth
self.header_y = page_style.topmargin
self.text_y = self.header_y + page_style.headheight + page_style.headsep
self.text_height = page_style.textheight
self.footer_y = self.text_y + self.text_height + (page_style.footspace - page_style.footheight)
_Canvas.__init__(self, font_loader, logger, opts, width=width, height=self.footer_y+page_style.footheight)
if opts.visual_debug:
self.setPen(QPen(Qt.GlobalColor.red, 1, Qt.PenStyle.SolidLine))
header = footer = None
if page_style.headheight > 0:
try:
header = chapter.oddheader if odd else chapter.evenheader
except AttributeError:
pass
if page_style.footheight > 0:
try:
footer = chapter.oddfooter if odd else chapter.evenfooter
except AttributeError:
pass
if header:
header = Header(font_loader, header, page_style, logger, opts, ruby_tags, link_activated)
self.layout_canvas(header, self.content_x, self.header_y)
if footer:
footer = Footer(font_loader, footer, page_style, logger, opts, ruby_tags, link_activated)
self.layout_canvas(footer, self.content_x, self.header_y)
self.page = None
def set_page(self, page):
if self.page is not None and self.page.scene():
self.scene().removeItem(self.page)
self.page = page
self.page.setPos(self.content_x, self.text_y)
self.scene().addItem(self.page)
def remove(self):
if self.scene():
if self.page is not None and self.page.scene():
self.scene().removeItem(self.page)
self.scene().removeItem(self)
class Page(_Canvas):
def __init__(self, font_loader, logger, opts, width, height):
_Canvas.__init__(self, font_loader, logger, opts, width, height)
if opts.visual_debug:
self.setPen(QPen(Qt.GlobalColor.cyan, 1, Qt.PenStyle.DashLine))
def id(self):
for child in self.children():
if hasattr(child, 'block_id'):
return child.block_id
def add_block(self, block):
self.layout_block(block, 0, self.current_y)
class Chapter:
num_of_pages = property(fget=lambda self: len(self.pages))
def __init__(self, oddscreen, evenscreen, pages, object_to_page_map):
self.oddscreen, self.evenscreen, self.pages, self.object_to_page_map = \
oddscreen, evenscreen, pages, object_to_page_map
def page_of_object(self, id):
return self.object_to_page_map[id]
def page(self, num):
return self.pages[num-1]
def screen(self, odd):
return self.oddscreen if odd else self.evenscreen
def search(self, phrase):
pages = []
for i in range(len(self.pages)):
matches = self.pages[i].search(phrase)
if matches:
pages.append([i, matches])
return pages
class History(collections.deque):
def __init__(self):
collections.deque.__init__(self)
self.pos = 0
def back(self):
if self.pos - 1 < 0:
return None
self.pos -= 1
return self[self.pos]
def forward(self):
if self.pos + 1 >= len(self):
return None
self.pos += 1
return self[self.pos]
def add(self, item):
while len(self) > self.pos+1:
self.pop()
self.append(item)
self.pos += 1
class Document(QGraphicsScene):
num_of_pages = property(fget=lambda self: sum(self.chapter_layout or ()))
chapter_rendered = pyqtSignal(object)
page_changed = pyqtSignal(object)
def __init__(self, logger, opts):
QGraphicsScene.__init__(self)
self.logger, self.opts = logger, opts
self.pages = []
self.chapters = []
self.chapter_layout = None
self.current_screen = None
self.current_page = 0
self.link_map = {}
self.chapter_map = {}
self.history = History()
self.last_search = iter([])
if not opts.white_background:
self.setBackgroundBrush(QBrush(QColor(0xee, 0xee, 0xee)))
def page_of(self, oid):
for chapter in self.chapters:
if oid in chapter.object_to_page_map:
return chapter.object_to_page_map[oid]
def get_page_num(self, chapterid, objid):
cnum = self.chapter_map[chapterid]
page = self.chapters[cnum].object_to_page_map[objid]
return sum(self.chapter_layout[:cnum])+page
def add_to_history(self):
page = self.chapter_page(self.current_page)[1]
page_id = page.id()
if page_id is not None:
self.history.add(page_id)
def link_activated(self, objid, on_creation=None):
if on_creation is None:
cid, oid = self.link_map[objid]
if oid is not None:
self.add_to_history()
page = self.get_page_num(cid, oid)
self.show_page(page)
else:
jb = self.objects[objid]
self.link_map[objid] = (jb.refpage, jb.refobj)
def back(self):
oid = self.history.back()
if oid is not None:
page = self.page_of(oid)
self.show_page(page)
def forward(self):
oid = self.history.forward()
if oid is not None:
page = self.page_of(oid)
self.show_page(page)
def load_fonts(self, lrf, load_substitutions=True):
font_map = {}
for font in lrf.font_map:
fdata = QByteArray(lrf.font_map[font].data)
id = QFontDatabase.addApplicationFontFromData(fdata)
if id != -1:
font_map[font] = [str(i) for i in QFontDatabase.applicationFontFamilies(id)][0]
if load_substitutions:
base = P('fonts/liberation/*.ttf')
for f in glob.glob(base):
QFontDatabase.addApplicationFont(f)
self.font_loader = FontLoader(font_map, self.dpi)
def render_chapter(self, chapter, lrf):
oddscreen, evenscreen = Screen(self.font_loader, chapter, True, self.logger, self.opts, self.ruby_tags, self.link_activated), \
Screen(self.font_loader, chapter, False, self.logger, self.opts, self.ruby_tags, self.link_activated)
pages = []
width, height = oddscreen.text_width, oddscreen.text_height
current_page = Page(self.font_loader, self.logger, self.opts, width, height)
object_to_page_map = {}
for object in chapter:
self.text_width = width
block = object_factory(self, object)
if block is None:
continue
object_to_page_map[object.id] = len(pages) + 1
while block.has_content:
current_page.add_block(block)
if current_page.is_full:
pages.append(current_page)
current_page = Page(self.font_loader, self.logger, self.opts, width, height)
if current_page:
pages.append(current_page)
self.chapters.append(Chapter(oddscreen, evenscreen, pages, object_to_page_map))
self.chapter_map[chapter.id] = len(self.chapters)-1
def render(self, lrf, load_substitutions=True):
self.dpi = lrf.device_info.dpi/10.
self.ruby_tags = dict(**lrf.ruby_tags)
self.load_fonts(lrf, load_substitutions)
self.objects = lrf.objects
num_chaps = 0
for pt in lrf.page_trees:
for chapter in pt:
num_chaps += 1
self.chapter_rendered.emit(num_chaps)
for pt in lrf.page_trees:
for chapter in pt:
self.render_chapter(chapter, lrf)
self.chapter_rendered.emit(-1)
self.chapter_layout = [i.num_of_pages for i in self.chapters]
self.objects = None
def chapter_page(self, num):
for chapter in self.chapters:
if num <= chapter.num_of_pages:
break
num -= chapter.num_of_pages
return chapter, chapter.page(num)
def show_page(self, num):
num = int(num)
if num < 1 or num > self.num_of_pages or num == self.current_page:
return
odd = num%2 == 1
self.current_page = num
chapter, page = self.chapter_page(num)
screen = chapter.screen(odd)
if self.current_screen is not None and self.current_screen is not screen:
self.current_screen.remove()
self.current_screen = screen
if self.current_screen.scene() is None:
self.addItem(self.current_screen)
self.current_screen.set_page(page)
self.page_changed.emit(self.current_page)
def next(self):
self.next_by(1)
def previous(self):
self.previous_by(1)
def next_by(self, num):
self.show_page(self.current_page + num)
def previous_by(self, num):
self.show_page(self.current_page - num)
def show_page_at_percent(self, p):
num = self.num_of_pages*(p/100.)
self.show_page(num)
def search(self, phrase):
if not phrase:
return
matches = []
for i in range(len(self.chapters)):
cmatches = self.chapters[i].search(phrase)
for match in cmatches:
match[0] += sum(self.chapter_layout[:i])+1
matches += cmatches
self.last_search = itertools.cycle(matches)
self.next_match()
def next_match(self):
page_num = next(self.last_search)[0]
if self.current_page == page_num:
self.update()
else:
self.add_to_history()
self.show_page(page_num)
| 18,949 | Python | .py | 430 | 33.637209 | 152 | 0.597394 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,048 | main.py | kovidgoyal_calibre/src/calibre/gui2/lrf_renderer/main.py | __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
import logging
import os
import sys
import time
import traceback
from qt.core import QCoreApplication, QDialog, QIcon, QKeySequence, QPainter, QScrollBar, QSlider, QSpinBox, Qt, QThread
from calibre import __appname__, as_unicode, isbsd, islinux, setup_cli_handlers
from calibre.ebooks.lrf.lrfparser import LRFDocument
from calibre.gui2 import Application, choose_files, error_dialog, gprefs
from calibre.gui2.dialogs.conversion_error import ConversionErrorDialog
from calibre.gui2.lrf_renderer.config_ui import Ui_ViewerConfig
from calibre.gui2.lrf_renderer.document import Document
from calibre.gui2.lrf_renderer.main_ui import Ui_MainWindow
from calibre.gui2.main_window import MainWindow
from calibre.gui2.search_box import SearchBox2
class RenderWorker(QThread):
def __init__(self, parent, lrf_stream, logger, opts):
QThread.__init__(self, parent)
self.stream, self.logger, self.opts = lrf_stream, logger, opts
self.aborted = False
self.lrf = None
self.document = None
self.exception = None
def run(self):
try:
self.lrf = LRFDocument(self.stream)
self.lrf.parse()
self.stream.close()
self.stream = None
if self.aborted:
self.lrf = None
except Exception as err:
self.lrf, self.stream = None, None
self.exception = err
self.formatted_traceback = traceback.format_exc()
def abort(self):
if self.lrf is not None:
self.aborted = True
self.lrf.keep_parsing = False
class Config(QDialog, Ui_ViewerConfig):
def __init__(self, parent, opts):
QDialog.__init__(self, parent)
Ui_ViewerConfig.__init__(self)
self.setupUi(self)
self.white_background.setChecked(opts.white_background)
self.hyphenate.setChecked(opts.hyphenate)
class Main(MainWindow, Ui_MainWindow):
def create_document(self):
self.document = Document(self.logger, self.opts)
self.document.chapter_rendered.connect(self.chapter_rendered)
self.document.page_changed.connect(self.page_changed)
def __init__(self, logger, opts, parent=None):
MainWindow.__init__(self, opts, parent)
Ui_MainWindow.__init__(self)
self.setupUi(self)
self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
self.setWindowTitle(__appname__ + _(' - LRF viewer'))
self.logger = logger
self.opts = opts
self.create_document()
self.spin_box_action = self.spin_box = QSpinBox()
self.tool_bar.addWidget(self.spin_box)
self.tool_bar.addSeparator()
self.slider_action = self.slider = QSlider(Qt.Orientation.Horizontal)
self.tool_bar.addWidget(self.slider)
self.tool_bar.addSeparator()
self.search = SearchBox2(self)
self.search.initialize('lrf_viewer_search_history')
self.search_action = self.tool_bar.addWidget(self.search)
self.search.search.connect(self.find)
self.action_next_page.setShortcuts([QKeySequence.StandardKey.MoveToNextPage, QKeySequence(Qt.Key.Key_Space)])
self.action_previous_page.setShortcuts([QKeySequence.StandardKey.MoveToPreviousPage, QKeySequence(Qt.Key.Key_Backspace)])
self.action_next_match.setShortcuts(QKeySequence.StandardKey.FindNext)
self.addAction(self.action_next_match)
self.action_next_page.triggered[(bool)].connect(self.next)
self.action_previous_page.triggered[(bool)].connect(self.previous)
self.action_back.triggered[(bool)].connect(self.back)
self.action_forward.triggered[(bool)].connect(self.forward)
self.action_next_match.triggered[(bool)].connect(self.next_match)
self.action_open_ebook.triggered[(bool)].connect(self.open_ebook)
self.action_configure.triggered[(bool)].connect(self.configure)
self.spin_box.valueChanged[(int)].connect(self.go_to_page)
self.slider.valueChanged[(int)].connect(self.go_to_page)
self.graphics_view.setRenderHint(QPainter.RenderHint.Antialiasing, True)
self.graphics_view.setRenderHint(QPainter.RenderHint.TextAntialiasing, True)
self.graphics_view.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform, True)
self.closed = False
def configure(self, triggered):
opts = self.opts
d = Config(self, opts)
d.exec()
if d.result() == QDialog.DialogCode.Accepted:
gprefs['lrf_viewer_white_background'] = opts.white_background = bool(d.white_background.isChecked())
gprefs['lrf_viewer_hyphenate'] = opts.hyphenate = bool(d.hyphenate.isChecked())
def set_ebook(self, stream):
self.progress_bar.setMinimum(0)
self.progress_bar.setMaximum(0)
self.progress_bar.setValue(0)
self.create_document()
if stream is not None:
self.file_name = os.path.basename(stream.name) if hasattr(stream, 'name') else ''
self.progress_label.setText('Parsing '+ self.file_name)
self.renderer = RenderWorker(self, stream, self.logger, self.opts)
self.renderer.finished.connect(self.parsed, type=Qt.ConnectionType.QueuedConnection)
self.search.clear()
self.last_search = None
else:
self.stack.setCurrentIndex(0)
self.renderer = None
def open_ebook(self, triggered):
files = choose_files(self, 'open ebook dialog', 'Choose ebook',
[('Ebooks', ['lrf'])], all_files=False,
select_only_single_file=True)
if files:
file = files[0]
self.set_ebook(open(file, 'rb'))
self.render()
def page_changed(self, num):
self.slider.setValue(num)
self.spin_box.setValue(num)
def render(self):
if self.renderer is not None:
self.stack.setCurrentIndex(1)
self.renderer.start()
def find(self, search):
self.last_search = search
try:
self.document.search(search)
except StopIteration:
error_dialog(self, _('No matches found'), _('<b>No matches</b> for the search phrase <i>%s</i> were found.')%(search,)).exec()
self.search.search_done(True)
def parsed(self):
if not self.renderer.aborted and self.renderer.lrf is not None:
width, height = self.renderer.lrf.device_info.width, \
self.renderer.lrf.device_info.height
hdelta = self.tool_bar.height()+3
s = QScrollBar(self)
scrollbar_adjust = min(s.width(), s.height())
self.graphics_view.resize_for(width+scrollbar_adjust, height+scrollbar_adjust)
screen_height = self.screen().availableSize().height() - 25
height = min(screen_height, height+hdelta+scrollbar_adjust)
self.resize(width+scrollbar_adjust, height)
self.setWindowTitle(self.renderer.lrf.metadata.title + ' - ' + __appname__)
self.document_title = self.renderer.lrf.metadata.title
if self.opts.profile:
import cProfile
lrf = self.renderer.lrf
cProfile.runctx('self.document.render(lrf)', globals(), locals(), lrf.metadata.title+'.stats')
print('Stats written to', self.renderer.lrf.metadata.title+'.stats')
else:
start = time.time()
self.document.render(self.renderer.lrf)
print('Layout time:', time.time()-start, 'seconds')
self.renderer.lrf = None
self.graphics_view.setScene(self.document)
self.graphics_view.show()
self.spin_box.setRange(1, self.document.num_of_pages)
self.slider.setRange(1, self.document.num_of_pages)
self.spin_box.setSuffix(' of %d'%(self.document.num_of_pages,))
self.spin_box.updateGeometry()
self.stack.setCurrentIndex(0)
self.graphics_view.setFocus(Qt.FocusReason.OtherFocusReason)
elif self.renderer.exception is not None:
exception = self.renderer.exception
print('Error rendering document', file=sys.stderr)
print(exception, file=sys.stderr)
print(self.renderer.formatted_traceback, file=sys.stderr)
msg = '<p><b>%s</b>: '%(exception.__class__.__name__,) + as_unicode(exception) + '</p>'
msg += '<p>Failed to render document</p>'
msg += '<p>Detailed <b>traceback</b>:<pre>'
msg += self.renderer.formatted_traceback + '</pre>'
d = ConversionErrorDialog(self, 'Error while rendering file', msg)
d.exec()
def chapter_rendered(self, num):
if num > 0:
self.progress_bar.setMinimum(0)
self.progress_bar.setMaximum(num)
self.progress_bar.setValue(0)
self.progress_label.setText('Laying out '+ self.document_title)
else:
self.progress_bar.setValue(self.progress_bar.value()+1)
QCoreApplication.processEvents()
def next(self, triggered):
self.document.next()
def next_match(self, triggered):
try:
self.document.next_match()
except StopIteration:
pass
def previous(self, triggered):
self.document.previous()
def go_to_page(self, num):
self.document.show_page(num)
def forward(self, triggered):
self.document.forward()
def back(self, triggered):
self.document.back()
def wheelEvent(self, ev):
d = ev.angleDelta().y()
if d > 0:
self.document.previous()
elif d < 0:
self.document.next()
def closeEvent(self, event):
if self.renderer is not None and self.renderer.isRunning():
self.renderer.abort()
self.renderer.wait()
event.accept()
def file_renderer(stream, opts, parent=None, logger=None):
if logger is None:
level = logging.DEBUG if opts.verbose else logging.INFO
logger = logging.getLogger('lrfviewer')
setup_cli_handlers(logger, level)
if islinux or isbsd:
try: # Set lrfviewer as the default for LRF files for this user
from subprocess import call
call('xdg-mime default calibre-lrfviewer.desktop application/lrf', shell=True)
except:
pass
m = Main(logger, opts, parent=parent)
m.set_ebook(stream)
return m
def option_parser():
from calibre.gui2.main_window import option_parser
parser = option_parser(_('''\
%prog [options] book.lrf
Read the LRF e-book book.lrf
'''))
parser.add_option('--verbose', default=False, action='store_true', dest='verbose',
help=_('Print more information about the rendering process'))
parser.add_option('--visual-debug', help=_('Turn on visual aids to debugging the rendering engine'),
default=False, action='store_true', dest='visual_debug')
parser.add_option('--disable-hyphenation', dest='hyphenate', default=True, action='store_false',
help=_('Disable hyphenation. Should significantly speed up rendering.'))
parser.add_option('--white-background', dest='white_background', default=False, action='store_true',
help=_('By default the background is off white as I find this easier on the eyes. Use this option to make the background pure white.'))
parser.add_option('--profile', dest='profile', default=False, action='store_true',
help=_('Profile the LRF renderer'))
return parser
def normalize_settings(parser, opts):
saved_opts = opts
dh = gprefs.get('lrf_viewer_hyphenate', None)
if dh is not None:
opts.hyphenate = bool(dh)
wb = gprefs.get('lrf_viewer_white_background', None)
if wb is not None:
opts.white_background = bool(wb)
return saved_opts
def main(args=sys.argv, logger=None):
parser = option_parser()
opts, args = parser.parse_args(args)
if hasattr(opts, 'help'):
parser.print_help()
return 1
pid = os.fork() if (islinux or isbsd) else -1
if pid <= 0:
override = 'calibre-lrfviewer' if islinux else None
app = Application(args, override_program_name=override)
app.setWindowIcon(QIcon.ic('viewer.png'))
opts = normalize_settings(parser, opts)
stream = open(args[1], 'rb') if len(args) > 1 else None
main = file_renderer(stream, opts, logger=logger)
main.set_exception_handler()
main.show()
main.render()
main.raise_and_focus()
return app.exec()
return 0
if __name__ == '__main__':
sys.exit(main())
| 12,921 | Python | .py | 272 | 38.011029 | 157 | 0.642988 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,049 | ui.py | kovidgoyal_calibre/src/calibre/customize/ui.py | __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
import functools
import os
import shutil
import sys
import traceback
from collections import defaultdict
from itertools import chain, repeat
from calibre.constants import DEBUG, ismacos, numeric_version, system_plugins_loc
from calibre.customize import (
CatalogPlugin,
EditBookToolPlugin,
FileTypePlugin,
InvalidPlugin,
LibraryClosedPlugin,
MetadataReaderPlugin,
MetadataWriterPlugin,
PluginInstallationType,
PluginNotFound,
PreferencesPlugin,
platform,
)
from calibre.customize import InterfaceActionBase as InterfaceAction
from calibre.customize import StoreBase as Store
from calibre.customize.builtins import plugins as builtin_plugins
from calibre.customize.conversion import InputFormatPlugin, OutputFormatPlugin
from calibre.customize.profiles import InputProfile, OutputProfile
from calibre.customize.zipplugin import loader
from calibre.devices.interface import DevicePlugin
from calibre.ebooks.metadata import MetaInformation
from calibre.ebooks.metadata.sources.base import Source
from calibre.utils.config import Config, ConfigProxy, OptionParser, make_config_dir, plugin_dir
from polyglot.builtins import iteritems, itervalues
builtin_names = frozenset(p.name for p in builtin_plugins)
BLACKLISTED_PLUGINS = frozenset({'Marvin XD', 'iOS reader applications'})
def zip_value(iterable, value):
return zip(iterable, repeat(value))
class NameConflict(ValueError):
pass
def _config():
c = Config('customize')
c.add_opt('plugins', default={}, help=_('Installed plugins'))
c.add_opt('filetype_mapping', default={}, help=_('Mapping for filetype plugins'))
c.add_opt('plugin_customization', default={}, help=_('Local plugin customization'))
c.add_opt('disabled_plugins', default=set(), help=_('Disabled plugins'))
c.add_opt('enabled_plugins', default=set(), help=_('Enabled plugins'))
return ConfigProxy(c)
config = _config()
def find_plugin(name):
for plugin in _initialized_plugins:
if plugin.name == name:
return plugin
def load_plugin(path_to_zip_file): # {{{
'''
Load plugin from ZIP file or raise InvalidPlugin error
:return: A :class:`Plugin` instance.
'''
return loader.load(path_to_zip_file)
# }}}
# Enable/disable plugins {{{
def disable_plugin(plugin_or_name):
x = getattr(plugin_or_name, 'name', plugin_or_name)
plugin = find_plugin(x)
if plugin is None:
raise ValueError(f'No plugin named: {x} found')
if not plugin.can_be_disabled:
raise ValueError('Plugin %s cannot be disabled'%x)
dp = config['disabled_plugins']
dp.add(x)
config['disabled_plugins'] = dp
ep = config['enabled_plugins']
if x in ep:
ep.remove(x)
config['enabled_plugins'] = ep
def enable_plugin(plugin_or_name):
x = getattr(plugin_or_name, 'name', plugin_or_name)
dp = config['disabled_plugins']
if x in dp:
dp.remove(x)
config['disabled_plugins'] = dp
ep = config['enabled_plugins']
ep.add(x)
config['enabled_plugins'] = ep
def restore_plugin_state_to_default(plugin_or_name):
x = getattr(plugin_or_name, 'name', plugin_or_name)
dp = config['disabled_plugins']
if x in dp:
dp.remove(x)
config['disabled_plugins'] = dp
ep = config['enabled_plugins']
if x in ep:
ep.remove(x)
config['enabled_plugins'] = ep
default_disabled_plugins = {
'Overdrive', 'Douban Books', 'OZON.ru', 'Edelweiss', 'Google Images', 'Big Book Search',
}
def is_disabled(plugin):
if plugin.name in config['enabled_plugins']:
return False
return plugin.name in config['disabled_plugins'] or \
plugin.name in default_disabled_plugins
# }}}
# File type plugins {{{
_on_import = {}
_on_postimport = {}
_on_postconvert = {}
_on_postdelete = {}
_on_preprocess = {}
_on_postprocess = {}
_on_postadd = []
def reread_filetype_plugins():
global _on_import, _on_postimport, _on_postconvert, _on_postdelete, _on_preprocess, _on_postprocess, _on_postadd
_on_import = defaultdict(list)
_on_postimport = defaultdict(list)
_on_postconvert = defaultdict(list)
_on_postdelete = defaultdict(list)
_on_preprocess = defaultdict(list)
_on_postprocess = defaultdict(list)
_on_postadd = []
for plugin in _initialized_plugins:
if isinstance(plugin, FileTypePlugin):
if ismacos and plugin.name == 'DeDRM' and plugin.version < (10, 0, 3):
print(f'Blacklisting the {plugin.name} plugin as it is too old and causes crashes', file=sys.stderr)
continue
for ft in plugin.file_types:
if plugin.on_import:
_on_import[ft].append(plugin)
if plugin.on_postimport:
_on_postimport[ft].append(plugin)
_on_postadd.append(plugin)
if plugin.on_postconvert:
_on_postconvert[ft].append(plugin)
if plugin.on_postdelete:
_on_postdelete[ft].append(plugin)
if plugin.on_preprocess:
_on_preprocess[ft].append(plugin)
if plugin.on_postprocess:
_on_postprocess[ft].append(plugin)
def plugins_for_ft(ft, occasion):
op = {
'import':_on_import, 'preprocess':_on_preprocess, 'postprocess':_on_postprocess, 'postimport':_on_postimport,
'postconvert':_on_postconvert, 'postdelete':_on_postdelete,
}[occasion]
for p in chain(op.get(ft, ()), op.get('*', ())):
if not is_disabled(p):
yield p
def _run_filetype_plugins(path_to_file, ft=None, occasion='preprocess'):
customization = config['plugin_customization']
if ft is None:
ft = os.path.splitext(path_to_file)[-1].lower().replace('.', '')
nfp = path_to_file
for plugin in plugins_for_ft(ft, occasion):
plugin.site_customization = customization.get(plugin.name, '')
oo, oe = sys.stdout, sys.stderr # Some file type plugins out there override the output streams with buggy implementations
with plugin:
try:
plugin.original_path_to_file = path_to_file
except Exception:
pass
try:
nfp = plugin.run(nfp) or nfp
except:
print('Running file type plugin %s failed with traceback:'%plugin.name, file=oe)
traceback.print_exc(file=oe)
sys.stdout, sys.stderr = oo, oe
def x(j):
return os.path.normpath(os.path.normcase(j))
if occasion == 'postprocess' and x(nfp) != x(path_to_file):
shutil.copyfile(nfp, path_to_file)
nfp = path_to_file
return nfp
run_plugins_on_import = functools.partial(_run_filetype_plugins, occasion='import')
run_plugins_on_preprocess = functools.partial(_run_filetype_plugins, occasion='preprocess')
run_plugins_on_postprocess = functools.partial(_run_filetype_plugins, occasion='postprocess')
def run_plugins_on_postimport(db, book_id, fmt):
customization = config['plugin_customization']
fmt = fmt.lower()
for plugin in plugins_for_ft(fmt, 'postimport'):
plugin.site_customization = customization.get(plugin.name, '')
with plugin:
try:
plugin.postimport(book_id, fmt, db)
except Exception:
print(f'Running file type plugin {plugin.name} failed with traceback:', file=sys.stderr)
traceback.print_exc()
def run_plugins_on_postconvert(db, book_id, fmt):
customization = config['plugin_customization']
fmt = fmt.lower()
for plugin in plugins_for_ft(fmt, 'postconvert'):
plugin.site_customization = customization.get(plugin.name, '')
with plugin:
try:
plugin.postconvert(book_id, fmt, db)
except Exception:
print(f'Running file type plugin {plugin.name} failed with traceback:', file=sys.stderr)
traceback.print_exc()
def run_plugins_on_postdelete(db, book_id, fmt):
customization = config['plugin_customization']
fmt = fmt.lower()
for plugin in plugins_for_ft(fmt, 'postdelete'):
plugin.site_customization = customization.get(plugin.name, '')
with plugin:
try:
plugin.postdelete(book_id, fmt, db)
except Exception:
print(f'Running file type plugin {plugin.name} failed with traceback:', file=sys.stderr)
traceback.print_exc()
def run_plugins_on_postadd(db, book_id, fmt_map):
customization = config['plugin_customization']
for plugin in _on_postadd:
if is_disabled(plugin):
continue
plugin.site_customization = customization.get(plugin.name, '')
with plugin:
try:
plugin.postadd(book_id, fmt_map, db)
except Exception:
print(f'Running file type plugin {plugin.name} failed with traceback:', file=sys.stderr)
traceback.print_exc()
# }}}
# Plugin customization {{{
def customize_plugin(plugin, custom):
d = config['plugin_customization']
d[plugin.name] = custom.strip()
config['plugin_customization'] = d
def plugin_customization(plugin):
return config['plugin_customization'].get(plugin.name, '')
# }}}
# Input/Output profiles {{{
def input_profiles():
for plugin in _initialized_plugins:
if isinstance(plugin, InputProfile):
yield plugin
def output_profiles():
for plugin in _initialized_plugins:
if isinstance(plugin, OutputProfile):
yield plugin
# }}}
# Interface Actions # {{{
def interface_actions():
customization = config['plugin_customization']
for plugin in _initialized_plugins:
if isinstance(plugin, InterfaceAction):
if not is_disabled(plugin):
plugin.site_customization = customization.get(plugin.name, '')
yield plugin
# }}}
# Preferences Plugins # {{{
def preferences_plugins():
customization = config['plugin_customization']
for plugin in _initialized_plugins:
if isinstance(plugin, PreferencesPlugin):
if not is_disabled(plugin):
plugin.site_customization = customization.get(plugin.name, '')
yield plugin
# }}}
# Library Closed Plugins # {{{
def available_library_closed_plugins():
customization = config['plugin_customization']
for plugin in _initialized_plugins:
if isinstance(plugin, LibraryClosedPlugin):
if not is_disabled(plugin):
plugin.site_customization = customization.get(plugin.name, '')
yield plugin
def has_library_closed_plugins():
for plugin in _initialized_plugins:
if isinstance(plugin, LibraryClosedPlugin):
if not is_disabled(plugin):
return True
return False
# }}}
# Store Plugins # {{{
def store_plugins():
customization = config['plugin_customization']
for plugin in _initialized_plugins:
if isinstance(plugin, Store):
plugin.site_customization = customization.get(plugin.name, '')
yield plugin
def available_store_plugins():
for plugin in store_plugins():
if not is_disabled(plugin):
yield plugin
def stores():
stores = set()
for plugin in store_plugins():
stores.add(plugin.name)
return stores
def available_stores():
stores = set()
for plugin in available_store_plugins():
stores.add(plugin.name)
return stores
# }}}
# Metadata read/write {{{
_metadata_readers = {}
_metadata_writers = {}
def reread_metadata_plugins():
global _metadata_readers
global _metadata_writers
_metadata_readers = defaultdict(list)
_metadata_writers = defaultdict(list)
for plugin in _initialized_plugins:
if isinstance(plugin, MetadataReaderPlugin):
for ft in plugin.file_types:
_metadata_readers[ft].append(plugin)
elif isinstance(plugin, MetadataWriterPlugin):
for ft in plugin.file_types:
_metadata_writers[ft].append(plugin)
# Ensure the following metadata plugin preference is used:
# external > system > builtin
def key(plugin):
order = sys.maxsize if plugin.installation_type is None else plugin.installation_type
return order, plugin.name
for group in (_metadata_readers, _metadata_writers):
for plugins in itervalues(group):
if len(plugins) > 1:
plugins.sort(key=key)
def metadata_readers():
ans = set()
for plugins in _metadata_readers.values():
for plugin in plugins:
ans.add(plugin)
return ans
def metadata_writers():
ans = set()
for plugins in _metadata_writers.values():
for plugin in plugins:
ans.add(plugin)
return ans
class QuickMetadata:
def __init__(self):
self.quick = False
def __enter__(self):
self.quick = True
def __exit__(self, *args):
self.quick = False
quick_metadata = QuickMetadata()
class ApplyNullMetadata:
def __init__(self):
self.apply_null = False
def __enter__(self):
self.apply_null = True
def __exit__(self, *args):
self.apply_null = False
apply_null_metadata = ApplyNullMetadata()
class ForceIdentifiers:
def __init__(self):
self.force_identifiers = False
def __enter__(self):
self.force_identifiers = True
def __exit__(self, *args):
self.force_identifiers = False
force_identifiers = ForceIdentifiers()
def get_file_type_metadata(stream, ftype):
mi = MetaInformation(None, None)
ftype = ftype.lower().strip()
if ftype in _metadata_readers:
for plugin in _metadata_readers[ftype]:
if not is_disabled(plugin):
with plugin:
try:
plugin.quick = quick_metadata.quick
if hasattr(stream, 'seek'):
stream.seek(0)
mi = plugin.get_metadata(stream, ftype.lower().strip())
break
except:
traceback.print_exc()
continue
return mi
def set_file_type_metadata(stream, mi, ftype, report_error=None):
ftype = ftype.lower().strip()
if ftype in _metadata_writers:
customization = config['plugin_customization']
for plugin in _metadata_writers[ftype]:
if not is_disabled(plugin):
with plugin:
try:
plugin.apply_null = apply_null_metadata.apply_null
plugin.force_identifiers = force_identifiers.force_identifiers
plugin.site_customization = customization.get(plugin.name, '')
plugin.set_metadata(stream, mi, ftype.lower().strip())
break
except:
if report_error is None:
from calibre import prints
prints('Failed to set metadata for the', ftype.upper(), 'format of:', getattr(mi, 'title', ''), file=sys.stderr)
traceback.print_exc()
else:
report_error(mi, ftype, traceback.format_exc())
def can_set_metadata(ftype):
ftype = ftype.lower().strip()
for plugin in _metadata_writers.get(ftype, ()):
if not is_disabled(plugin):
return True
return False
# }}}
# Add/remove plugins {{{
def add_plugin(path_to_zip_file):
make_config_dir()
plugin = load_plugin(path_to_zip_file)
if plugin.name in builtin_names:
raise NameConflict(
'A builtin plugin with the name %r already exists' % plugin.name)
if plugin.name in get_system_plugins():
raise NameConflict(
'A system plugin with the name %r already exists' % plugin.name)
plugin = initialize_plugin(plugin, path_to_zip_file, PluginInstallationType.EXTERNAL)
plugins = config['plugins']
zfp = os.path.join(plugin_dir, plugin.name+'.zip')
if os.path.exists(zfp):
os.remove(zfp)
shutil.copyfile(path_to_zip_file, zfp)
plugins[plugin.name] = zfp
config['plugins'] = plugins
initialize_plugins()
return plugin
def remove_plugin(plugin_or_name):
name = getattr(plugin_or_name, 'name', plugin_or_name)
plugins = config['plugins']
removed = False
if name in plugins:
removed = True
try:
zfp = os.path.join(plugin_dir, name+'.zip')
if os.path.exists(zfp):
os.remove(zfp)
zfp = plugins[name]
if os.path.exists(zfp):
os.remove(zfp)
except:
pass
plugins.pop(name)
config['plugins'] = plugins
initialize_plugins()
return removed
# }}}
# Input/Output format plugins {{{
def input_format_plugins():
for plugin in _initialized_plugins:
if isinstance(plugin, InputFormatPlugin):
yield plugin
def plugin_for_input_format(fmt):
customization = config['plugin_customization']
for plugin in input_format_plugins():
if fmt.lower() in plugin.file_types:
plugin.site_customization = customization.get(plugin.name, None)
return plugin
def all_input_formats():
formats = set()
for plugin in input_format_plugins():
for format in plugin.file_types:
formats.add(format)
return formats
def available_input_formats():
formats = set()
for plugin in input_format_plugins():
if not is_disabled(plugin):
for format in plugin.file_types:
formats.add(format)
formats.add('zip'), formats.add('rar')
return formats
def output_format_plugins():
for plugin in _initialized_plugins:
if isinstance(plugin, OutputFormatPlugin):
yield plugin
def plugin_for_output_format(fmt):
customization = config['plugin_customization']
for plugin in output_format_plugins():
if fmt.lower() == plugin.file_type:
plugin.site_customization = customization.get(plugin.name, None)
return plugin
def available_output_formats():
formats = set()
for plugin in output_format_plugins():
if not is_disabled(plugin):
formats.add(plugin.file_type)
return formats
# }}}
# Catalog plugins {{{
def catalog_plugins():
for plugin in _initialized_plugins:
if isinstance(plugin, CatalogPlugin):
yield plugin
def available_catalog_formats():
formats = set()
for plugin in catalog_plugins():
if not is_disabled(plugin):
for format in plugin.file_types:
formats.add(format)
return formats
def plugin_for_catalog_format(fmt):
for plugin in catalog_plugins():
if fmt.lower() in plugin.file_types:
return plugin
# }}}
# Device plugins {{{
def device_plugins(include_disabled=False):
for plugin in _initialized_plugins:
if isinstance(plugin, DevicePlugin):
if include_disabled or not is_disabled(plugin):
if platform in plugin.supported_platforms:
if getattr(plugin, 'plugin_needs_delayed_initialization',
False):
plugin.do_delayed_plugin_initialization()
yield plugin
def disabled_device_plugins():
for plugin in _initialized_plugins:
if isinstance(plugin, DevicePlugin):
if is_disabled(plugin):
if platform in plugin.supported_platforms:
yield plugin
# }}}
# Metadata sources2 {{{
def metadata_plugins(capabilities):
capabilities = frozenset(capabilities)
for plugin in all_metadata_plugins():
if plugin.capabilities.intersection(capabilities) and \
not is_disabled(plugin):
yield plugin
def all_metadata_plugins():
for plugin in _initialized_plugins:
if isinstance(plugin, Source):
yield plugin
def patch_metadata_plugins(possibly_updated_plugins):
patches = {}
for i, plugin in enumerate(_initialized_plugins):
if isinstance(plugin, Source) and plugin.name in builtin_names:
pup = possibly_updated_plugins.get(plugin.name)
if pup is not None:
if pup.version > plugin.version and pup.minimum_calibre_version <= numeric_version:
patches[i] = pup(None)
# Metadata source plugins dont use initialize() but that
# might change in the future, so be safe.
patches[i].initialize()
for i, pup in iteritems(patches):
_initialized_plugins[i] = pup
# }}}
# Editor plugins {{{
def all_edit_book_tool_plugins():
for plugin in _initialized_plugins:
if isinstance(plugin, EditBookToolPlugin):
yield plugin
# }}}
# Initialize plugins {{{
_initialized_plugins = []
def initialize_plugin(plugin, path_to_zip_file, installation_type):
try:
p = plugin(path_to_zip_file)
p.installation_type = installation_type
p.initialize()
return p
except Exception:
print('Failed to initialize plugin:', plugin.name, plugin.version)
tb = traceback.format_exc()
raise InvalidPlugin((_('Initialization of plugin %s failed with traceback:')
%tb) + '\n'+tb)
def has_external_plugins():
'True if there are updateable (ZIP file based) plugins'
return bool(config['plugins'])
@functools.lru_cache(maxsize=2)
def get_system_plugins():
if not system_plugins_loc:
return {}
try:
plugin_file_names = os.listdir(system_plugins_loc)
except OSError:
return {}
ans = []
for plugin_file_name in plugin_file_names:
plugin_path = os.path.join(system_plugins_loc, plugin_file_name)
if os.path.isfile(plugin_path) and plugin_file_name.endswith('.zip'):
ans.append((os.path.splitext(plugin_file_name)[0], plugin_path))
return dict(ans)
def initialize_plugins(perf=False):
global _initialized_plugins
_initialized_plugins = []
system_plugins = get_system_plugins().copy()
conflicts = {name for name in config['plugins'] if name in
builtin_names or name in system_plugins}
for p in conflicts:
remove_plugin(p)
system_conflicts = [name for name in system_plugins if name in
builtin_names]
for p in system_conflicts:
system_plugins.pop(p, None)
external_plugins = config['plugins'].copy()
for name in BLACKLISTED_PLUGINS:
external_plugins.pop(name, None)
system_plugins.pop(name, None)
ostdout, ostderr = sys.stdout, sys.stderr
if perf:
import time
from collections import defaultdict
times = defaultdict(int)
for zfp, installation_type in chain(
zip_value(external_plugins.items(), PluginInstallationType.EXTERNAL),
zip_value(system_plugins.items(), PluginInstallationType.SYSTEM),
zip_value(builtin_plugins, PluginInstallationType.BUILTIN),
):
try:
if not isinstance(zfp, type):
# We have a plugin name
pname, path = zfp
zfp = os.path.join(plugin_dir, pname+'.zip')
if not os.path.exists(zfp):
zfp = path
try:
plugin = load_plugin(zfp) if not isinstance(zfp, type) else zfp
except PluginNotFound:
continue
if perf:
st = time.time()
plugin = initialize_plugin(
plugin,
None if isinstance(zfp, type) else zfp, installation_type,
)
if perf:
times[plugin.name] = time.time() - st
_initialized_plugins.append(plugin)
except:
print('Failed to initialize plugin:', repr(zfp), file=sys.stderr)
if DEBUG:
traceback.print_exc()
# Prevent a custom plugin from overriding stdout/stderr as this breaks
# ipython
sys.stdout, sys.stderr = ostdout, ostderr
if perf:
for x in sorted(times, key=lambda x: times[x]):
print('%50s: %.3f'%(x, times[x]))
_initialized_plugins.sort(key=lambda x: x.priority, reverse=True)
reread_filetype_plugins()
reread_metadata_plugins()
initialize_plugins()
def initialized_plugins():
yield from _initialized_plugins
# }}}
# CLI {{{
def build_plugin(path):
from calibre import prints
from calibre.ptempfile import PersistentTemporaryFile
from calibre.utils.zipfile import ZIP_STORED, ZipFile
path = str(path)
names = frozenset(os.listdir(path))
if '__init__.py' not in names:
prints(path, ' is not a valid plugin')
raise SystemExit(1)
t = PersistentTemporaryFile('.zip')
with ZipFile(t, 'w', ZIP_STORED) as zf:
zf.add_dir(path, simple_filter=lambda x:x in {'.git', '.bzr', '.svn', '.hg'})
t.close()
plugin = add_plugin(t.name)
os.remove(t.name)
prints('Plugin updated:', plugin.name, plugin.version)
def option_parser():
parser = OptionParser(usage=_('''\
%prog options
Customize calibre by loading external plugins.
'''))
parser.add_option('-a', '--add-plugin', default=None,
help=_('Add a plugin by specifying the path to the ZIP file containing it.'))
parser.add_option('-b', '--build-plugin', default=None,
help=_('For plugin developers: Path to the folder where you are'
' developing the plugin. This command will automatically zip '
'up the plugin and update it in calibre.'))
parser.add_option('-r', '--remove-plugin', default=None,
help=_('Remove a custom plugin by name. Has no effect on builtin plugins'))
parser.add_option('--customize-plugin', default=None,
help=_('Customize plugin. Specify name of plugin and customization string separated by a comma.'
' The customization string is the same as you would enter when customizing the plugin in the main calibre GUI.'))
parser.add_option('-l', '--list-plugins', default=False, action='store_true',
help=_('List all installed plugins'))
parser.add_option('--enable-plugin', default=None,
help=_('Enable the named plugin'))
parser.add_option('--disable-plugin', default=None,
help=_('Disable the named plugin'))
return parser
def main(args=sys.argv):
parser = option_parser()
if len(args) < 2:
parser.print_help()
return 1
opts, args = parser.parse_args(args)
if opts.add_plugin is not None:
plugin = add_plugin(opts.add_plugin)
print('Plugin added:', plugin.name, plugin.version)
if opts.build_plugin is not None:
build_plugin(opts.build_plugin)
if opts.remove_plugin is not None:
if remove_plugin(opts.remove_plugin):
print('Plugin removed')
else:
print('No custom plugin named', opts.remove_plugin)
if opts.customize_plugin is not None:
try:
name, custom = opts.customize_plugin.split(',')
except ValueError:
name, custom = opts.customize_plugin, ''
plugin = find_plugin(name.strip())
if plugin is None:
print('No plugin with the name %s exists'%name)
return 1
customize_plugin(plugin, custom)
if opts.enable_plugin is not None:
enable_plugin(opts.enable_plugin.strip())
if opts.disable_plugin is not None:
disable_plugin(opts.disable_plugin.strip())
if opts.list_plugins:
type_len = name_len = 0
for plugin in initialized_plugins():
type_len, name_len = max(type_len, len(plugin.type)), max(name_len, len(plugin.name))
fmt = f'%-{type_len+1}s%-{name_len+1}s%-15s%-15s%s'
print(fmt%tuple('Type|Name|Version|Disabled|Site Customization'.split('|')))
print()
for plugin in initialized_plugins():
print(fmt%(
plugin.type, plugin.name,
plugin.version, is_disabled(plugin),
plugin_customization(plugin)
))
print('\t', plugin.description)
if plugin.is_customizable():
try:
print('\t', plugin.customization_help())
except NotImplementedError:
pass
print()
return 0
if __name__ == '__main__':
sys.exit(main())
# }}}
| 29,212 | Python | .py | 732 | 31.336066 | 142 | 0.628116 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,050 | builtins.py | kovidgoyal_calibre/src/calibre/customize/builtins.py | __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
import glob
import os
from calibre.constants import numeric_version
from calibre.customize import FileTypePlugin, InterfaceActionBase, MetadataReaderPlugin, MetadataWriterPlugin, PreferencesPlugin, StoreBase
from calibre.ebooks.html.to_zip import HTML2ZIP
from calibre.ebooks.metadata.archive import ArchiveExtract, KPFExtract, get_comic_metadata
plugins = []
# To archive plugins {{{
class PML2PMLZ(FileTypePlugin):
name = 'PML to PMLZ'
author = 'John Schember'
description = _('Create a PMLZ archive containing the PML file '
'and all images in the folder pmlname_img or images. '
'This plugin is run every time you add '
'a PML file to the library.')
version = numeric_version
file_types = {'pml'}
supported_platforms = ['windows', 'osx', 'linux']
on_import = True
def run(self, pmlfile):
import zipfile
of = self.temporary_file('_plugin_pml2pmlz.pmlz')
pmlz = zipfile.ZipFile(of.name, 'w')
pmlz.write(pmlfile, os.path.basename(pmlfile), zipfile.ZIP_DEFLATED)
pml_img = os.path.splitext(pmlfile)[0] + '_img'
i_img = os.path.join(os.path.dirname(pmlfile),'images')
img_dir = pml_img if os.path.isdir(pml_img) else i_img if \
os.path.isdir(i_img) else ''
if img_dir:
for image in glob.glob(os.path.join(img_dir, '*.png')):
pmlz.write(image, os.path.join('images', (os.path.basename(image))))
pmlz.close()
return of.name
class TXT2TXTZ(FileTypePlugin):
name = 'TXT to TXTZ'
author = 'John Schember'
description = _('Create a TXTZ archive when a TXT file is imported '
'containing Markdown or Textile references to images. The referenced '
'images as well as the TXT file are added to the archive.')
version = numeric_version
file_types = {'txt', 'text', 'md', 'markdown', 'textile'}
supported_platforms = ['windows', 'osx', 'linux']
on_import = True
def run(self, path_to_ebook):
from calibre.ebooks.metadata.opf2 import metadata_to_opf
from calibre.ebooks.txt.processor import get_images_from_polyglot_text
with open(path_to_ebook, 'rb') as ebf:
txt = ebf.read().decode('utf-8', 'replace')
base_dir = os.path.dirname(path_to_ebook)
ext = path_to_ebook.rpartition('.')[-1].lower()
images = get_images_from_polyglot_text(txt, base_dir, ext)
if images:
# Create TXTZ and put file plus images inside of it.
import zipfile
of = self.temporary_file('_plugin_txt2txtz.txtz')
txtz = zipfile.ZipFile(of.name, 'w')
# Add selected TXT file to archive.
txtz.write(path_to_ebook, os.path.basename(path_to_ebook), zipfile.ZIP_DEFLATED)
# metadata.opf
if os.path.exists(os.path.join(base_dir, 'metadata.opf')):
txtz.write(os.path.join(base_dir, 'metadata.opf'), 'metadata.opf', zipfile.ZIP_DEFLATED)
else:
from calibre.ebooks.metadata.txt import get_metadata
with open(path_to_ebook, 'rb') as ebf:
mi = get_metadata(ebf)
opf = metadata_to_opf(mi)
txtz.writestr('metadata.opf', opf, zipfile.ZIP_DEFLATED)
# images
for image in images:
txtz.write(os.path.join(base_dir, image), image)
txtz.close()
return of.name
else:
# No images so just import the TXT file.
return path_to_ebook
plugins += [HTML2ZIP, PML2PMLZ, TXT2TXTZ, ArchiveExtract, KPFExtract]
# }}}
# Metadata reader plugins {{{
class ComicMetadataReader(MetadataReaderPlugin):
name = 'Read comic metadata'
file_types = {'cbr', 'cbz', 'cb7', 'cbc'}
description = _('Extract cover from comic files')
def customization_help(self, gui=False):
return 'Read series number from volume or issue number. Default is volume, set this to issue to use issue number instead.'
def get_metadata(self, stream, ftype):
if ftype == 'cbc':
from zipfile import ZipFile
zf = ZipFile(stream)
fcn = zf.open('comics.txt').read().decode('utf-8').splitlines()[0]
oname = getattr(stream, 'name', None)
stream = zf.open(fcn)
ftype = fcn.split('.')[-1].lower()
if oname:
stream.name = oname
if hasattr(stream, 'seek') and hasattr(stream, 'tell'):
pos = stream.tell()
id_ = stream.read(3)
stream.seek(pos)
if id_ == b'Rar':
ftype = 'cbr'
elif id_.startswith(b'PK'):
ftype = 'cbz'
elif id_.startswith(b'7z'):
ftype = 'cb7'
if ftype == 'cbr':
from calibre.utils.unrar import extract_cover_image
elif ftype == 'cb7':
from calibre.utils.seven_zip import extract_cover_image
else:
from calibre.libunzip import extract_cover_image
from calibre.ebooks.metadata import MetaInformation
ret = extract_cover_image(stream)
mi = MetaInformation(None, None)
stream.seek(0)
if ftype in {'cbr', 'cbz'}:
series_index = self.site_customization
if series_index not in {'volume', 'issue'}:
series_index = 'volume'
try:
mi.smart_update(get_comic_metadata(stream, ftype, series_index=series_index))
except:
pass
if ret is not None:
path, data = ret
ext = os.path.splitext(path)[1][1:]
mi.cover_data = (ext.lower(), data)
return mi
class CHMMetadataReader(MetadataReaderPlugin):
name = 'Read CHM metadata'
file_types = {'chm'}
description = _('Read metadata from %s files') % 'CHM'
def get_metadata(self, stream, ftype):
from calibre.ebooks.chm.metadata import get_metadata
return get_metadata(stream)
class EPUBMetadataReader(MetadataReaderPlugin):
name = 'Read EPUB metadata'
file_types = {'epub'}
description = _('Read metadata from %s files')%'EPUB'
def get_metadata(self, stream, ftype):
from calibre.ebooks.metadata.epub import get_metadata, get_quick_metadata
if self.quick:
return get_quick_metadata(stream)
return get_metadata(stream)
class FB2MetadataReader(MetadataReaderPlugin):
name = 'Read FB2 metadata'
file_types = {'fb2', 'fbz'}
description = _('Read metadata from %s files')%'FB2'
def get_metadata(self, stream, ftype):
from calibre.ebooks.metadata.fb2 import get_metadata
return get_metadata(stream)
class HTMLMetadataReader(MetadataReaderPlugin):
name = 'Read HTML metadata'
file_types = {'html'}
description = _('Read metadata from %s files')%'HTML'
def get_metadata(self, stream, ftype):
from calibre.ebooks.metadata.html import get_metadata
return get_metadata(stream)
class HTMLZMetadataReader(MetadataReaderPlugin):
name = 'Read HTMLZ metadata'
file_types = {'htmlz'}
description = _('Read metadata from %s files') % 'HTMLZ'
author = 'John Schember'
def get_metadata(self, stream, ftype):
from calibre.ebooks.metadata.extz import get_metadata
return get_metadata(stream)
class IMPMetadataReader(MetadataReaderPlugin):
name = 'Read IMP metadata'
file_types = {'imp'}
description = _('Read metadata from %s files')%'IMP'
author = 'Ashish Kulkarni'
def get_metadata(self, stream, ftype):
from calibre.ebooks.metadata.imp import get_metadata
return get_metadata(stream)
class LITMetadataReader(MetadataReaderPlugin):
name = 'Read LIT metadata'
file_types = {'lit'}
description = _('Read metadata from %s files')%'LIT'
def get_metadata(self, stream, ftype):
from calibre.ebooks.metadata.lit import get_metadata
return get_metadata(stream)
class LRFMetadataReader(MetadataReaderPlugin):
name = 'Read LRF metadata'
file_types = {'lrf'}
description = _('Read metadata from %s files')%'LRF'
def get_metadata(self, stream, ftype):
from calibre.ebooks.lrf.meta import get_metadata
return get_metadata(stream)
class LRXMetadataReader(MetadataReaderPlugin):
name = 'Read LRX metadata'
file_types = {'lrx'}
description = _('Read metadata from %s files')%'LRX'
def get_metadata(self, stream, ftype):
from calibre.ebooks.metadata.lrx import get_metadata
return get_metadata(stream)
class MOBIMetadataReader(MetadataReaderPlugin):
name = 'Read MOBI metadata'
file_types = {'mobi', 'prc', 'azw', 'azw3', 'azw4', 'pobi'}
description = _('Read metadata from %s files')%'MOBI'
def get_metadata(self, stream, ftype):
from calibre.ebooks.metadata.mobi import get_metadata
return get_metadata(stream)
class ODTMetadataReader(MetadataReaderPlugin):
name = 'Read ODT metadata'
file_types = {'odt'}
description = _('Read metadata from %s files')%'ODT'
def get_metadata(self, stream, ftype):
from calibre.ebooks.metadata.odt import get_metadata
return get_metadata(stream)
class DocXMetadataReader(MetadataReaderPlugin):
name = 'Read DOCX metadata'
file_types = {'docx'}
description = _('Read metadata from %s files')%'DOCX'
def get_metadata(self, stream, ftype):
from calibre.ebooks.metadata.docx import get_metadata
return get_metadata(stream)
class OPFMetadataReader(MetadataReaderPlugin):
name = 'Read OPF metadata'
file_types = {'opf'}
description = _('Read metadata from %s files')%'OPF'
def get_metadata(self, stream, ftype):
from calibre.ebooks.metadata.opf import get_metadata
return get_metadata(stream)[0]
class PDBMetadataReader(MetadataReaderPlugin):
name = 'Read PDB metadata'
file_types = {'pdb', 'updb'}
description = _('Read metadata from %s files') % 'PDB'
author = 'John Schember'
def get_metadata(self, stream, ftype):
from calibre.ebooks.metadata.pdb import get_metadata
return get_metadata(stream)
class PDFMetadataReader(MetadataReaderPlugin):
name = 'Read PDF metadata'
file_types = {'pdf'}
description = _('Read metadata from %s files')%'PDF'
def get_metadata(self, stream, ftype):
from calibre.ebooks.metadata.pdf import get_metadata, get_quick_metadata
if self.quick:
return get_quick_metadata(stream)
return get_metadata(stream)
class PMLMetadataReader(MetadataReaderPlugin):
name = 'Read PML metadata'
file_types = {'pml', 'pmlz'}
description = _('Read metadata from %s files') % 'PML'
author = 'John Schember'
def get_metadata(self, stream, ftype):
from calibre.ebooks.metadata.pml import get_metadata
return get_metadata(stream)
class RARMetadataReader(MetadataReaderPlugin):
name = 'Read RAR metadata'
file_types = {'rar'}
description = _('Read metadata from e-books in RAR archives')
def get_metadata(self, stream, ftype):
from calibre.ebooks.metadata.rar import get_metadata
return get_metadata(stream)
class RBMetadataReader(MetadataReaderPlugin):
name = 'Read RB metadata'
file_types = {'rb'}
description = _('Read metadata from %s files')%'RB'
author = 'Ashish Kulkarni'
def get_metadata(self, stream, ftype):
from calibre.ebooks.metadata.rb import get_metadata
return get_metadata(stream)
class RTFMetadataReader(MetadataReaderPlugin):
name = 'Read RTF metadata'
file_types = {'rtf'}
description = _('Read metadata from %s files')%'RTF'
def get_metadata(self, stream, ftype):
from calibre.ebooks.metadata.rtf import get_metadata
return get_metadata(stream)
class SNBMetadataReader(MetadataReaderPlugin):
name = 'Read SNB metadata'
file_types = {'snb'}
description = _('Read metadata from %s files') % 'SNB'
author = 'Li Fanxi'
def get_metadata(self, stream, ftype):
from calibre.ebooks.metadata.snb import get_metadata
return get_metadata(stream)
class TOPAZMetadataReader(MetadataReaderPlugin):
name = 'Read Topaz metadata'
file_types = {'tpz', 'azw1'}
description = _('Read metadata from %s files')%'MOBI'
def get_metadata(self, stream, ftype):
from calibre.ebooks.metadata.topaz import get_metadata
return get_metadata(stream)
class TXTMetadataReader(MetadataReaderPlugin):
name = 'Read TXT metadata'
file_types = {'txt'}
description = _('Read metadata from %s files') % 'TXT'
author = 'John Schember'
def get_metadata(self, stream, ftype):
from calibre.ebooks.metadata.txt import get_metadata
return get_metadata(stream)
class TXTZMetadataReader(MetadataReaderPlugin):
name = 'Read TXTZ metadata'
file_types = {'txtz'}
description = _('Read metadata from %s files') % 'TXTZ'
author = 'John Schember'
def get_metadata(self, stream, ftype):
from calibre.ebooks.metadata.extz import get_metadata
return get_metadata(stream)
class ZipMetadataReader(MetadataReaderPlugin):
name = 'Read ZIP metadata'
file_types = {'zip', 'oebzip'}
description = _('Read metadata from e-books in ZIP archives')
def get_metadata(self, stream, ftype):
from calibre.ebooks.metadata.zip import get_metadata
return get_metadata(stream)
plugins += [x for x in list(locals().values()) if isinstance(x, type) and
x.__name__.endswith('MetadataReader')]
# }}}
# Metadata writer plugins {{{
class EPUBMetadataWriter(MetadataWriterPlugin):
name = 'Set EPUB metadata'
file_types = {'epub'}
description = _('Set metadata in %s files')%'EPUB'
def set_metadata(self, stream, mi, type):
from calibre.ebooks.metadata.epub import set_metadata
q = self.site_customization or ''
set_metadata(stream, mi, apply_null=self.apply_null, force_identifiers=self.force_identifiers, add_missing_cover='disable-add-missing-cover' != q)
def customization_help(self, gui=False):
h = 'disable-add-missing-cover'
if gui:
h = '<i>' + h + '</i>'
return _('Enter {0} below to have the EPUB metadata writer plugin not'
' add cover images to EPUB files that have no existing cover image.').format(h)
class FB2MetadataWriter(MetadataWriterPlugin):
name = 'Set FB2 metadata'
file_types = {'fb2', 'fbz'}
description = _('Set metadata in %s files')%'FB2'
def set_metadata(self, stream, mi, type):
from calibre.ebooks.metadata.fb2 import set_metadata
set_metadata(stream, mi, apply_null=self.apply_null)
class HTMLZMetadataWriter(MetadataWriterPlugin):
name = 'Set HTMLZ metadata'
file_types = {'htmlz'}
description = _('Set metadata from %s files') % 'HTMLZ'
author = 'John Schember'
def set_metadata(self, stream, mi, type):
from calibre.ebooks.metadata.extz import set_metadata
set_metadata(stream, mi)
class LRFMetadataWriter(MetadataWriterPlugin):
name = 'Set LRF metadata'
file_types = {'lrf'}
description = _('Set metadata in %s files')%'LRF'
def set_metadata(self, stream, mi, type):
from calibre.ebooks.lrf.meta import set_metadata
set_metadata(stream, mi)
class MOBIMetadataWriter(MetadataWriterPlugin):
name = 'Set MOBI metadata'
file_types = {'mobi', 'prc', 'azw', 'azw3', 'azw4'}
description = _('Set metadata in %s files')%'MOBI'
author = 'Marshall T. Vandegrift'
def set_metadata(self, stream, mi, type):
from calibre.ebooks.metadata.mobi import set_metadata
set_metadata(stream, mi)
class PDBMetadataWriter(MetadataWriterPlugin):
name = 'Set PDB metadata'
file_types = {'pdb'}
description = _('Set metadata from %s files') % 'PDB'
author = 'John Schember'
def set_metadata(self, stream, mi, type):
from calibre.ebooks.metadata.pdb import set_metadata
set_metadata(stream, mi)
class PDFMetadataWriter(MetadataWriterPlugin):
name = 'Set PDF metadata'
file_types = {'pdf'}
description = _('Set metadata in %s files') % 'PDF'
author = 'Kovid Goyal'
def set_metadata(self, stream, mi, type):
from calibre.ebooks.metadata.pdf import set_metadata
set_metadata(stream, mi)
class RTFMetadataWriter(MetadataWriterPlugin):
name = 'Set RTF metadata'
file_types = {'rtf'}
description = _('Set metadata in %s files')%'RTF'
def set_metadata(self, stream, mi, type):
from calibre.ebooks.metadata.rtf import set_metadata
set_metadata(stream, mi)
class TOPAZMetadataWriter(MetadataWriterPlugin):
name = 'Set TOPAZ metadata'
file_types = {'tpz', 'azw1'}
description = _('Set metadata in %s files')%'TOPAZ'
author = 'Greg Riker'
def set_metadata(self, stream, mi, type):
from calibre.ebooks.metadata.topaz import set_metadata
set_metadata(stream, mi)
class TXTZMetadataWriter(MetadataWriterPlugin):
name = 'Set TXTZ metadata'
file_types = {'txtz'}
description = _('Set metadata from %s files') % 'TXTZ'
author = 'John Schember'
def set_metadata(self, stream, mi, type):
from calibre.ebooks.metadata.extz import set_metadata
set_metadata(stream, mi)
class ODTMetadataWriter(MetadataWriterPlugin):
name = 'Set ODT metadata'
file_types = {'odt'}
description = _('Set metadata from %s files')%'ODT'
def set_metadata(self, stream, mi, type):
from calibre.ebooks.metadata.odt import set_metadata
return set_metadata(stream, mi)
class DocXMetadataWriter(MetadataWriterPlugin):
name = 'Set DOCX metadata'
file_types = {'docx'}
description = _('Set metadata from %s files')%'DOCX'
def set_metadata(self, stream, mi, type):
from calibre.ebooks.metadata.docx import set_metadata
return set_metadata(stream, mi)
plugins += [x for x in list(locals().values()) if isinstance(x, type) and
x.__name__.endswith('MetadataWriter')]
# }}}
# Conversion plugins {{{
from calibre.ebooks.conversion.plugins.azw4_input import AZW4Input
from calibre.ebooks.conversion.plugins.chm_input import CHMInput
from calibre.ebooks.conversion.plugins.comic_input import ComicInput
from calibre.ebooks.conversion.plugins.djvu_input import DJVUInput
from calibre.ebooks.conversion.plugins.docx_input import DOCXInput
from calibre.ebooks.conversion.plugins.docx_output import DOCXOutput
from calibre.ebooks.conversion.plugins.epub_input import EPUBInput
from calibre.ebooks.conversion.plugins.epub_output import EPUBOutput
from calibre.ebooks.conversion.plugins.fb2_input import FB2Input
from calibre.ebooks.conversion.plugins.fb2_output import FB2Output
from calibre.ebooks.conversion.plugins.html_input import HTMLInput
from calibre.ebooks.conversion.plugins.html_output import HTMLOutput
from calibre.ebooks.conversion.plugins.htmlz_input import HTMLZInput
from calibre.ebooks.conversion.plugins.htmlz_output import HTMLZOutput
from calibre.ebooks.conversion.plugins.lit_input import LITInput
from calibre.ebooks.conversion.plugins.lit_output import LITOutput
from calibre.ebooks.conversion.plugins.lrf_input import LRFInput
from calibre.ebooks.conversion.plugins.lrf_output import LRFOutput
from calibre.ebooks.conversion.plugins.mobi_input import MOBIInput
from calibre.ebooks.conversion.plugins.mobi_output import AZW3Output, MOBIOutput
from calibre.ebooks.conversion.plugins.odt_input import ODTInput
from calibre.ebooks.conversion.plugins.oeb_output import OEBOutput
from calibre.ebooks.conversion.plugins.pdb_input import PDBInput
from calibre.ebooks.conversion.plugins.pdb_output import PDBOutput
from calibre.ebooks.conversion.plugins.pdf_input import PDFInput
from calibre.ebooks.conversion.plugins.pdf_output import PDFOutput
from calibre.ebooks.conversion.plugins.pml_input import PMLInput
from calibre.ebooks.conversion.plugins.pml_output import PMLOutput
from calibre.ebooks.conversion.plugins.rb_input import RBInput
from calibre.ebooks.conversion.plugins.rb_output import RBOutput
from calibre.ebooks.conversion.plugins.recipe_input import RecipeInput
from calibre.ebooks.conversion.plugins.rtf_input import RTFInput
from calibre.ebooks.conversion.plugins.rtf_output import RTFOutput
from calibre.ebooks.conversion.plugins.snb_input import SNBInput
from calibre.ebooks.conversion.plugins.snb_output import SNBOutput
from calibre.ebooks.conversion.plugins.tcr_input import TCRInput
from calibre.ebooks.conversion.plugins.tcr_output import TCROutput
from calibre.ebooks.conversion.plugins.txt_input import TXTInput
from calibre.ebooks.conversion.plugins.txt_output import TXTOutput, TXTZOutput
plugins += [
ComicInput,
DJVUInput,
EPUBInput,
FB2Input,
HTMLInput,
HTMLZInput,
LITInput,
MOBIInput,
ODTInput,
PDBInput,
AZW4Input,
PDFInput,
PMLInput,
RBInput,
RecipeInput,
RTFInput,
TCRInput,
TXTInput,
LRFInput,
CHMInput,
SNBInput,
DOCXInput,
]
plugins += [
EPUBOutput,
DOCXOutput,
FB2Output,
LITOutput,
LRFOutput,
MOBIOutput, AZW3Output,
OEBOutput,
PDBOutput,
PDFOutput,
PMLOutput,
RBOutput,
RTFOutput,
TCROutput,
TXTOutput,
TXTZOutput,
HTMLOutput,
HTMLZOutput,
SNBOutput,
]
# }}}
# Catalog plugins {{{
from calibre.library.catalogs.bibtex import BIBTEX
from calibre.library.catalogs.csv_xml import CSV_XML
from calibre.library.catalogs.epub_mobi import EPUB_MOBI
plugins += [CSV_XML, BIBTEX, EPUB_MOBI]
# }}}
# Profiles {{{
from calibre.customize.profiles import input_profiles, output_profiles
plugins += input_profiles + output_profiles
# }}}
# Device driver plugins {{{
from calibre.devices.android.driver import ANDROID, S60, WEBOS
from calibre.devices.binatone.driver import README
from calibre.devices.blackberry.driver import BLACKBERRY, PLAYBOOK
from calibre.devices.boeye.driver import BOEYE_BDX, BOEYE_BEX
from calibre.devices.cybook.driver import CYBOOK, DIVA, MUSE, ORIZON
from calibre.devices.eb600.driver import (
BOOQ,
COOL_ER,
DBOOK,
EB600,
ECLICTO,
ELONEX,
GER2,
INVESBOOK,
ITALICA,
MENTOR,
PI2,
POCKETBOOK301,
POCKETBOOK360,
POCKETBOOK360P,
POCKETBOOK602,
POCKETBOOK622,
POCKETBOOK701,
POCKETBOOK740,
POCKETBOOKHD,
SHINEBOOK,
TOLINO,
)
from calibre.devices.edge.driver import EDGE
from calibre.devices.eslick.driver import EBK52, ESLICK
from calibre.devices.folder_device.driver import FOLDER_DEVICE_FOR_CONFIG
from calibre.devices.hanlin.driver import BOOX, HANLINV3, HANLINV5, SPECTRA
from calibre.devices.hanvon.driver import ALEX, AZBOOKA, EB511, KIBANO, LIBREAIR, N516, ODYSSEY, THEBOOK
from calibre.devices.iliad.driver import ILIAD
from calibre.devices.irexdr.driver import IREXDR800, IREXDR1000
from calibre.devices.iriver.driver import IRIVER_STORY
from calibre.devices.jetbook.driver import JETBOOK, JETBOOK_COLOR, JETBOOK_MINI, MIBUK
from calibre.devices.kindle.driver import KINDLE, KINDLE2, KINDLE_DX, KINDLE_FIRE
from calibre.devices.kobo.driver import KOBO, KOBOTOUCH
from calibre.devices.misc import (
ADAM,
ALURATEK_COLOR,
AVANT,
CERVANTES,
COBY,
EEEREADER,
EX124G,
GEMEI,
LUMIREAD,
MOOVYBOOK,
NEXTBOOK,
PALMPRE,
PDNOVEL,
PDNOVEL_KOBO,
POCKETBOOK626,
SONYDPTS1,
SWEEX,
TREKSTOR,
VELOCITYMICRO,
WAYTEQ,
WOXTER,
)
from calibre.devices.mtp.driver import MTP_DEVICE
from calibre.devices.nokia.driver import E52, E71X, N770, N810
from calibre.devices.nook.driver import NOOK, NOOK_COLOR
from calibre.devices.nuut2.driver import NUUT2
from calibre.devices.prs505.driver import PRS505
from calibre.devices.prst1.driver import PRST1
from calibre.devices.smart_device_app.driver import SMART_DEVICE_APP
from calibre.devices.sne.driver import SNE
from calibre.devices.teclast.driver import ARCHOS7O, IPAPYRUS, NEWSMY, PICO, SOVOS, STASH, SUNSTECH_EB700, TECLAST_K3, WEXLER
from calibre.devices.user_defined.driver import USER_DEFINED
# Order here matters. The first matched device is the one used.
plugins += [
HANLINV3,
HANLINV5,
BLACKBERRY, PLAYBOOK,
CYBOOK, ORIZON, MUSE, DIVA,
ILIAD,
IREXDR1000,
IREXDR800,
JETBOOK, JETBOOK_MINI, MIBUK, JETBOOK_COLOR,
SHINEBOOK,
POCKETBOOK360, POCKETBOOK301, POCKETBOOK602, POCKETBOOK701, POCKETBOOK360P,
POCKETBOOK622, PI2, POCKETBOOKHD, POCKETBOOK740,
KINDLE, KINDLE2, KINDLE_DX, KINDLE_FIRE,
NOOK, NOOK_COLOR,
PRS505, PRST1,
ANDROID, S60, WEBOS,
N770,
E71X,
E52,
N810,
COOL_ER,
ESLICK,
EBK52,
NUUT2,
IRIVER_STORY,
GER2,
ITALICA,
ECLICTO,
DBOOK,
INVESBOOK,
BOOX,
BOOQ,
EB600, TOLINO,
README,
N516, KIBANO,
THEBOOK, LIBREAIR,
EB511,
ELONEX,
TECLAST_K3,
NEWSMY,
PICO, SUNSTECH_EB700, ARCHOS7O, SOVOS, STASH, WEXLER,
IPAPYRUS,
EDGE,
SNE,
ALEX, ODYSSEY,
PALMPRE,
KOBO, KOBOTOUCH,
AZBOOKA,
FOLDER_DEVICE_FOR_CONFIG,
AVANT, CERVANTES,
MENTOR,
SWEEX,
PDNOVEL,
SPECTRA,
GEMEI,
VELOCITYMICRO,
PDNOVEL_KOBO,
LUMIREAD,
ALURATEK_COLOR,
TREKSTOR,
EEEREADER,
NEXTBOOK,
ADAM,
MOOVYBOOK, COBY, EX124G, WAYTEQ, WOXTER, POCKETBOOK626, SONYDPTS1,
BOEYE_BEX,
BOEYE_BDX,
MTP_DEVICE,
SMART_DEVICE_APP,
USER_DEFINED,
]
# }}}
# New metadata download plugins {{{
from calibre.ebooks.metadata.sources.amazon import Amazon
from calibre.ebooks.metadata.sources.big_book_search import BigBookSearch
from calibre.ebooks.metadata.sources.edelweiss import Edelweiss
from calibre.ebooks.metadata.sources.google import GoogleBooks
from calibre.ebooks.metadata.sources.google_images import GoogleImages
from calibre.ebooks.metadata.sources.openlibrary import OpenLibrary
plugins += [GoogleBooks, GoogleImages, Amazon, Edelweiss, OpenLibrary, BigBookSearch]
# }}}
# Interface Actions {{{
class ActionAdd(InterfaceActionBase):
name = 'Add Books'
actual_plugin = 'calibre.gui2.actions.add:AddAction'
description = _('Add books to calibre or the connected device')
class ActionFetchAnnotations(InterfaceActionBase):
name = 'Fetch Annotations'
actual_plugin = 'calibre.gui2.actions.annotate:FetchAnnotationsAction'
description = _('Fetch annotations from a connected Kindle (experimental)')
class ActionGenerateCatalog(InterfaceActionBase):
name = 'Generate Catalog'
actual_plugin = 'calibre.gui2.actions.catalog:GenerateCatalogAction'
description = _('Generate a catalog of the books in your calibre library')
class ActionConvert(InterfaceActionBase):
name = 'Convert Books'
actual_plugin = 'calibre.gui2.actions.convert:ConvertAction'
description = _('Convert books to various e-book formats')
class ActionPolish(InterfaceActionBase):
name = 'Polish Books'
actual_plugin = 'calibre.gui2.actions.polish:PolishAction'
description = _('Fine tune your e-books')
class ActionBrowseAnnotations(InterfaceActionBase):
name = 'Browse Annotations'
actual_plugin = 'calibre.gui2.actions.browse_annots:BrowseAnnotationsAction'
description = _('Browse highlights and bookmarks from all books in the library')
class ActionBrowseNotes(InterfaceActionBase):
name = 'Browse Notes'
actual_plugin = 'calibre.gui2.actions.browse_notes:BrowseNotesAction'
description = _('Browse notes for authors, tags, etc. in the library')
class ActionFullTextSearch(InterfaceActionBase):
name = 'Full Text Search'
actual_plugin = 'calibre.gui2.actions.fts:FullTextSearchAction'
description = _('Search the full text of all books in the calibre library')
class ActionEditToC(InterfaceActionBase):
name = 'Edit ToC'
actual_plugin = 'calibre.gui2.actions.toc_edit:ToCEditAction'
description = _('Edit the Table of Contents in your books')
class ActionDelete(InterfaceActionBase):
name = 'Remove Books'
actual_plugin = 'calibre.gui2.actions.delete:DeleteAction'
description = _('Delete books from your calibre library or connected device')
class ActionEmbed(InterfaceActionBase):
name = 'Embed Metadata'
actual_plugin = 'calibre.gui2.actions.embed:EmbedAction'
description = _('Embed updated metadata into the actual book files in your calibre library')
class ActionEditMetadata(InterfaceActionBase):
name = 'Edit Metadata'
actual_plugin = 'calibre.gui2.actions.edit_metadata:EditMetadataAction'
description = _('Edit the metadata of books in your calibre library')
class ActionView(InterfaceActionBase):
name = 'View'
actual_plugin = 'calibre.gui2.actions.view:ViewAction'
description = _('Read books in your calibre library')
class ActionFetchNews(InterfaceActionBase):
name = 'Fetch News'
actual_plugin = 'calibre.gui2.actions.fetch_news:FetchNewsAction'
description = _('Download news from the internet in e-book form')
class ActionQuickview(InterfaceActionBase):
name = 'Quickview'
actual_plugin = 'calibre.gui2.actions.show_quickview:ShowQuickviewAction'
description = _('Show a list of related books quickly')
class ActionTagMapper(InterfaceActionBase):
name = 'Tag Mapper'
actual_plugin = 'calibre.gui2.actions.tag_mapper:TagMapAction'
description = _('Filter/transform the tags for books in the library')
class ActionAuthorMapper(InterfaceActionBase):
name = 'Author Mapper'
actual_plugin = 'calibre.gui2.actions.author_mapper:AuthorMapAction'
description = _('Transform the authors for books in the library')
class ActionTemplateTester(InterfaceActionBase):
name = 'Template Tester'
actual_plugin = 'calibre.gui2.actions.show_template_tester:ShowTemplateTesterAction'
description = _('Show an editor for testing templates')
class ActionTemplateFunctions(InterfaceActionBase):
name = 'Template Functions'
actual_plugin = 'calibre.gui2.actions.show_stored_templates:ShowTemplateFunctionsAction'
description = _('Show a dialog for creating and managing template functions and stored templates')
class ActionSaveToDisk(InterfaceActionBase):
name = 'Save To Disk'
actual_plugin = 'calibre.gui2.actions.save_to_disk:SaveToDiskAction'
description = _('Export books from your calibre library to the hard disk')
class ActionShowBookDetails(InterfaceActionBase):
name = 'Show Book Details'
actual_plugin = 'calibre.gui2.actions.show_book_details:ShowBookDetailsAction'
description = _('Show Book details in a separate popup')
class ActionRestart(InterfaceActionBase):
name = 'Restart'
actual_plugin = 'calibre.gui2.actions.restart:RestartAction'
description = _('Restart calibre')
class ActionOpenFolder(InterfaceActionBase):
name = 'Open Folder'
actual_plugin = 'calibre.gui2.actions.open:OpenFolderAction'
description = _('Open the folder that contains the book files in your'
' calibre library')
class ActionAutoscrollBooks(InterfaceActionBase):
name = 'Autoscroll Books'
actual_plugin = 'calibre.gui2.actions.auto_scroll:AutoscrollBooksAction'
description = _('Auto scroll through the list of books')
class ActionSendToDevice(InterfaceActionBase):
name = 'Send To Device'
actual_plugin = 'calibre.gui2.actions.device:SendToDeviceAction'
description = _('Send books to the connected device')
class ActionConnectShare(InterfaceActionBase):
name = 'Connect Share'
actual_plugin = 'calibre.gui2.actions.device:ConnectShareAction'
description = _('Send books via email or the web. Also connect to'
' folders on your computer as if they are devices')
class ActionHelp(InterfaceActionBase):
name = 'Help'
actual_plugin = 'calibre.gui2.actions.help:HelpAction'
description = _('Browse the calibre User Manual')
class ActionPreferences(InterfaceActionBase):
name = 'Preferences'
actual_plugin = 'calibre.gui2.actions.preferences:PreferencesAction'
description = _('Customize calibre')
class ActionSimilarBooks(InterfaceActionBase):
name = 'Similar Books'
actual_plugin = 'calibre.gui2.actions.similar_books:SimilarBooksAction'
description = _('Easily find books similar to the currently selected one')
class ActionChooseLibrary(InterfaceActionBase):
name = 'Choose Library'
actual_plugin = 'calibre.gui2.actions.choose_library:ChooseLibraryAction'
description = _('Switch between different calibre libraries and perform'
' maintenance on them')
class ActionAddToLibrary(InterfaceActionBase):
name = 'Add To Library'
actual_plugin = 'calibre.gui2.actions.add_to_library:AddToLibraryAction'
description = _('Copy books from the device to your calibre library')
class ActionEditCollections(InterfaceActionBase):
name = 'Edit Collections'
actual_plugin = 'calibre.gui2.actions.edit_collections:EditCollectionsAction'
description = _('Edit the collections in which books are placed on your device')
class ActionMatchBooks(InterfaceActionBase):
name = 'Match Books'
actual_plugin = 'calibre.gui2.actions.match_books:MatchBookAction'
description = _('Match book on the devices to books in the library')
class ActionShowMatchedBooks(InterfaceActionBase):
name = 'Show Matched Book In Library'
actual_plugin = 'calibre.gui2.actions.match_books:ShowMatchedBookAction'
description = _('Show the book in the calibre library that matches this book')
class ActionCopyToLibrary(InterfaceActionBase):
name = 'Copy To Library'
actual_plugin = 'calibre.gui2.actions.copy_to_library:CopyToLibraryAction'
description = _('Copy a book from one calibre library to another')
class ActionTweakEpub(InterfaceActionBase):
name = 'Tweak ePub'
actual_plugin = 'calibre.gui2.actions.tweak_epub:TweakEpubAction'
description = _('Edit e-books in the EPUB or AZW3 formats')
class ActionUnpackBook(InterfaceActionBase):
name = 'Unpack Book'
actual_plugin = 'calibre.gui2.actions.unpack_book:UnpackBookAction'
description = _('Make small changes to EPUB or HTMLZ files in your calibre library')
class ActionNextMatch(InterfaceActionBase):
name = 'Next Match'
actual_plugin = 'calibre.gui2.actions.next_match:NextMatchAction'
description = _('Find the next or previous match when searching in '
'your calibre library in highlight mode')
class ActionPickRandom(InterfaceActionBase):
name = 'Pick Random Book'
actual_plugin = 'calibre.gui2.actions.random:PickRandomAction'
description = _('Choose a random book from your calibre library')
class ActionSortBy(InterfaceActionBase):
name = 'Sort By'
actual_plugin = 'calibre.gui2.actions.sort:SortByAction'
description = _('Sort the list of books')
class ActionMarkBooks(InterfaceActionBase):
name = 'Mark Books'
actual_plugin = 'calibre.gui2.actions.mark_books:MarkBooksAction'
description = _('Temporarily mark books')
class ActionManageCategories(InterfaceActionBase):
name = 'Manage categories'
author = 'Charles Haley'
actual_plugin = 'calibre.gui2.actions.manage_categories:ManageCategoriesAction'
description = _('Manage tag browser categories')
class ActionSavedSearches(InterfaceActionBase):
name = 'Saved searches'
author = 'Charles Haley'
actual_plugin = 'calibre.gui2.actions.saved_searches:SavedSearchesAction'
description = _('Show a menu of saved searches')
class ActionLayoutActions(InterfaceActionBase):
name = 'Layout Actions'
author = 'Charles Haley'
actual_plugin = 'calibre.gui2.actions.layout_actions:LayoutActions'
description = _("Show a menu of actions to change calibre's layout")
class ActionBooklistContextMenu(InterfaceActionBase):
name = 'Booklist context menu'
author = 'Charles Haley'
actual_plugin = 'calibre.gui2.actions.booklist_context_menu:BooklistContextMenuAction'
description = _('Open the context menu for the column')
class ActionAllActions(InterfaceActionBase):
name = 'All GUI actions'
author = 'Charles Haley'
actual_plugin = 'calibre.gui2.actions.all_actions:AllGUIActions'
description = _('Open a menu showing all installed GUI actions')
class ActionVirtualLibrary(InterfaceActionBase):
name = 'Virtual Library'
actual_plugin = 'calibre.gui2.actions.virtual_library:VirtualLibraryAction'
description = _('Change the current Virtual library')
class ActionStore(InterfaceActionBase):
name = 'Store'
author = 'John Schember'
actual_plugin = 'calibre.gui2.actions.store:StoreAction'
description = _('Search for books from different book sellers')
def customization_help(self, gui=False):
return 'Customize the behavior of the store search.'
def config_widget(self):
from calibre.gui2.store.config.store import config_widget as get_cw
return get_cw()
def save_settings(self, config_widget):
from calibre.gui2.store.config.store import save_settings as save
save(config_widget)
class ActionPluginUpdater(InterfaceActionBase):
name = 'Plugin Updater'
author = 'Grant Drake'
description = _('Get new calibre plugins or update your existing ones')
actual_plugin = 'calibre.gui2.actions.plugin_updates:PluginUpdaterAction'
plugins += [ActionAdd, ActionAllActions, ActionFetchAnnotations, ActionGenerateCatalog,
ActionConvert, ActionDelete, ActionEditMetadata, ActionView,
ActionFetchNews, ActionSaveToDisk, ActionQuickview, ActionPolish,
ActionShowBookDetails,ActionRestart, ActionOpenFolder, ActionConnectShare,
ActionSendToDevice, ActionHelp, ActionPreferences, ActionSimilarBooks,
ActionAddToLibrary, ActionEditCollections, ActionMatchBooks, ActionShowMatchedBooks, ActionChooseLibrary,
ActionCopyToLibrary, ActionTweakEpub, ActionUnpackBook, ActionNextMatch, ActionStore,
ActionPluginUpdater, ActionPickRandom, ActionEditToC, ActionSortBy,
ActionMarkBooks, ActionEmbed, ActionTemplateTester, ActionTagMapper, ActionAuthorMapper,
ActionVirtualLibrary, ActionBrowseAnnotations, ActionTemplateFunctions, ActionAutoscrollBooks,
ActionFullTextSearch, ActionManageCategories, ActionBooklistContextMenu, ActionSavedSearches,
ActionLayoutActions, ActionBrowseNotes,]
# }}}
# Preferences Plugins {{{
class LookAndFeel(PreferencesPlugin):
name = 'Look & Feel'
icon = 'lookfeel.png'
gui_name = _('Look & feel')
category = 'Interface'
gui_category = _('Interface')
category_order = 1
name_order = 1
config_widget = 'calibre.gui2.preferences.look_feel'
description = _('Adjust the look and feel of the calibre interface'
' to suit your tastes')
class Behavior(PreferencesPlugin):
name = 'Behavior'
icon = 'config.png'
gui_name = _('Behavior')
category = 'Interface'
gui_category = _('Interface')
category_order = 1
name_order = 2
config_widget = 'calibre.gui2.preferences.behavior'
description = _('Change the way calibre behaves')
class Columns(PreferencesPlugin):
name = 'Custom Columns'
icon = 'column.png'
gui_name = _('Add your own columns')
category = 'Interface'
gui_category = _('Interface')
category_order = 1
name_order = 3
config_widget = 'calibre.gui2.preferences.columns'
description = _('Add/remove your own columns to the calibre book list')
class Toolbar(PreferencesPlugin):
name = 'Toolbar'
icon = 'wizard.png'
gui_name = _('Toolbars & menus')
category = 'Interface'
gui_category = _('Interface')
category_order = 1
name_order = 4
config_widget = 'calibre.gui2.preferences.toolbar'
description = _('Customize the toolbars and context menus, changing which'
' actions are available in each')
class Search(PreferencesPlugin):
name = 'Search'
icon = 'search.png'
gui_name = _('Searching')
category = 'Interface'
gui_category = _('Interface')
category_order = 1
name_order = 5
config_widget = 'calibre.gui2.preferences.search'
description = _('Customize the way searching for books works in calibre')
class InputOptions(PreferencesPlugin):
name = 'Input Options'
icon = 'arrow-down.png'
gui_name = _('Input options')
category = 'Conversion'
gui_category = _('Conversion')
category_order = 2
name_order = 1
config_widget = 'calibre.gui2.preferences.conversion:InputOptions'
description = _('Set conversion options specific to each input format')
def create_widget(self, *args, **kwargs):
# The DOC Input plugin tries to override this
self.config_widget = 'calibre.gui2.preferences.conversion:InputOptions'
return PreferencesPlugin.create_widget(self, *args, **kwargs)
class CommonOptions(PreferencesPlugin):
name = 'Common Options'
icon = 'convert.png'
gui_name = _('Common options')
category = 'Conversion'
gui_category = _('Conversion')
category_order = 2
name_order = 2
config_widget = 'calibre.gui2.preferences.conversion:CommonOptions'
description = _('Set conversion options common to all formats')
class OutputOptions(PreferencesPlugin):
name = 'Output Options'
icon = 'arrow-up.png'
gui_name = _('Output options')
category = 'Conversion'
gui_category = _('Conversion')
category_order = 2
name_order = 3
config_widget = 'calibre.gui2.preferences.conversion:OutputOptions'
description = _('Set conversion options specific to each output format')
class Adding(PreferencesPlugin):
name = 'Adding'
icon = 'add_book.png'
gui_name = _('Adding books')
category = 'Import/Export'
gui_category = _('Import/export')
category_order = 3
name_order = 1
config_widget = 'calibre.gui2.preferences.adding'
description = _('Control how calibre reads metadata from files when '
'adding books')
class Saving(PreferencesPlugin):
name = 'Saving'
icon = 'save.png'
gui_name = _('Saving books to disk')
category = 'Import/Export'
gui_category = _('Import/export')
category_order = 3
name_order = 2
config_widget = 'calibre.gui2.preferences.saving'
description = _('Control how calibre exports files from its database '
'to disk when using Save to disk')
class Sending(PreferencesPlugin):
name = 'Sending'
icon = 'sync.png'
gui_name = _('Sending books to devices')
category = 'Import/Export'
gui_category = _('Import/export')
category_order = 3
name_order = 3
config_widget = 'calibre.gui2.preferences.sending'
description = _('Control how calibre transfers files to your '
'e-book reader')
class Plugboard(PreferencesPlugin):
name = 'Plugboard'
icon = 'plugboard.png'
gui_name = _('Metadata plugboards')
category = 'Import/Export'
gui_category = _('Import/export')
category_order = 3
name_order = 4
config_widget = 'calibre.gui2.preferences.plugboard'
description = _('Change metadata fields before saving/sending')
class TemplateFunctions(PreferencesPlugin):
name = 'TemplateFunctions'
icon = 'template_funcs.png'
gui_name = _('Template functions')
category = 'Advanced'
gui_category = _('Advanced')
category_order = 5
name_order = 5
config_widget = 'calibre.gui2.preferences.template_functions'
description = _('Create your own template functions')
class Email(PreferencesPlugin):
name = 'Email'
icon = 'mail.png'
gui_name = _('Sharing books by email')
category = 'Sharing'
gui_category = _('Sharing')
category_order = 4
name_order = 1
config_widget = 'calibre.gui2.preferences.emailp'
description = _('Setup sharing of books via email. Can be used '
'for automatic sending of downloaded news to your devices')
class Server(PreferencesPlugin):
name = 'Server'
icon = 'network-server.png'
gui_name = _('Sharing over the net')
category = 'Sharing'
gui_category = _('Sharing')
category_order = 4
name_order = 2
config_widget = 'calibre.gui2.preferences.server'
description = _('Setup the calibre Content server which will '
'give you access to your calibre library from anywhere, '
'on any device, over the internet')
class MetadataSources(PreferencesPlugin):
name = 'Metadata download'
icon = 'download-metadata.png'
gui_name = _('Metadata download')
category = 'Sharing'
gui_category = _('Sharing')
category_order = 4
name_order = 3
config_widget = 'calibre.gui2.preferences.metadata_sources'
description = _('Control how calibre downloads e-book metadata from the net')
class IgnoredDevices(PreferencesPlugin):
name = 'Ignored Devices'
icon = 'reader.png'
gui_name = _('Ignored devices')
category = 'Sharing'
gui_category = _('Sharing')
category_order = 4
name_order = 4
config_widget = 'calibre.gui2.preferences.ignored_devices'
description = _('Control which devices calibre will ignore when they are connected '
'to the computer.')
class Plugins(PreferencesPlugin):
name = 'Plugins'
icon = 'plugins.png'
gui_name = _('Plugins')
category = 'Advanced'
gui_category = _('Advanced')
category_order = 5
name_order = 1
config_widget = 'calibre.gui2.preferences.plugins'
description = _('Add/remove/customize various bits of calibre '
'functionality')
class Tweaks(PreferencesPlugin):
name = 'Tweaks'
icon = 'tweaks.png'
gui_name = _('Tweaks')
category = 'Advanced'
gui_category = _('Advanced')
category_order = 5
name_order = 2
config_widget = 'calibre.gui2.preferences.tweaks'
description = _('Fine tune how calibre behaves in various contexts')
class Keyboard(PreferencesPlugin):
name = 'Keyboard'
icon = 'keyboard-prefs.png'
gui_name = _('Shortcuts')
category = 'Advanced'
gui_category = _('Advanced')
category_order = 5
name_order = 4
config_widget = 'calibre.gui2.preferences.keyboard'
description = _('Customize the keyboard shortcuts used by calibre')
class Misc(PreferencesPlugin):
name = 'Misc'
icon = 'exec.png'
gui_name = _('Miscellaneous')
category = 'Advanced'
gui_category = _('Advanced')
category_order = 5
name_order = 3
config_widget = 'calibre.gui2.preferences.misc'
description = _('Miscellaneous advanced configuration')
plugins += [LookAndFeel, Behavior, Columns, Toolbar, Search, InputOptions,
CommonOptions, OutputOptions, Adding, Saving, Sending, Plugboard,
Email, Server, Plugins, Tweaks, Misc, TemplateFunctions,
MetadataSources, Keyboard, IgnoredDevices]
# }}}
# Store plugins {{{
class StoreAmazonKindleStore(StoreBase):
name = 'Amazon Kindle'
description = 'Kindle books from Amazon.'
actual_plugin = 'calibre.gui2.store.stores.amazon_plugin:AmazonKindleStore'
headquarters = 'US'
formats = ['KINDLE']
affiliate = False
class StoreAmazonAUKindleStore(StoreBase):
name = 'Amazon AU Kindle'
author = 'Kovid Goyal'
description = 'Kindle books from Amazon.'
actual_plugin = 'calibre.gui2.store.stores.amazon_au_plugin:AmazonKindleStore'
headquarters = 'AU'
formats = ['KINDLE']
class StoreAmazonCAKindleStore(StoreBase):
name = 'Amazon CA Kindle'
author = 'Kovid Goyal'
description = 'Kindle books from Amazon.'
actual_plugin = 'calibre.gui2.store.stores.amazon_ca_plugin:AmazonKindleStore'
headquarters = 'CA'
formats = ['KINDLE']
class StoreAmazonINKindleStore(StoreBase):
name = 'Amazon IN Kindle'
author = 'Kovid Goyal'
description = 'Kindle books from Amazon.'
actual_plugin = 'calibre.gui2.store.stores.amazon_in_plugin:AmazonKindleStore'
headquarters = 'IN'
formats = ['KINDLE']
class StoreAmazonDEKindleStore(StoreBase):
name = 'Amazon DE Kindle'
author = 'Kovid Goyal'
description = 'Kindle Bücher von Amazon.'
actual_plugin = 'calibre.gui2.store.stores.amazon_de_plugin:AmazonKindleStore'
headquarters = 'DE'
formats = ['KINDLE']
class StoreAmazonFRKindleStore(StoreBase):
name = 'Amazon FR Kindle'
author = 'Kovid Goyal'
description = 'Tous les e-books Kindle'
actual_plugin = 'calibre.gui2.store.stores.amazon_fr_plugin:AmazonKindleStore'
headquarters = 'FR'
formats = ['KINDLE']
class StoreAmazonITKindleStore(StoreBase):
name = 'Amazon IT Kindle'
author = 'Kovid Goyal'
description = 'e-book Kindle a prezzi incredibili'
actual_plugin = 'calibre.gui2.store.stores.amazon_it_plugin:AmazonKindleStore'
headquarters = 'IT'
formats = ['KINDLE']
class StoreAmazonESKindleStore(StoreBase):
name = 'Amazon ES Kindle'
author = 'Kovid Goyal'
description = 'e-book Kindle en España'
actual_plugin = 'calibre.gui2.store.stores.amazon_es_plugin:AmazonKindleStore'
headquarters = 'ES'
formats = ['KINDLE']
class StoreAmazonUKKindleStore(StoreBase):
name = 'Amazon UK Kindle'
author = 'Kovid Goyal'
description = 'Kindle books from Amazon\'s UK web site. Also, includes French language e-books.'
actual_plugin = 'calibre.gui2.store.stores.amazon_uk_plugin:AmazonKindleStore'
headquarters = 'UK'
formats = ['KINDLE']
class StoreArchiveOrgStore(StoreBase):
name = 'Archive.org'
description = 'An Internet library offering permanent access for researchers, historians, scholars, people with disabilities, and the general public to historical collections that exist in digital format.' # noqa
actual_plugin = 'calibre.gui2.store.stores.archive_org_plugin:ArchiveOrgStore'
drm_free_only = True
headquarters = 'US'
formats = ['DAISY', 'DJVU', 'EPUB', 'MOBI', 'PDF', 'TXT']
class StoreBubokPublishingStore(StoreBase):
name = 'Bubok Spain'
description = 'Bubok Publishing is a publisher, library and store of books of authors from all around the world. They have a big amount of books of a lot of topics' # noqa
actual_plugin = 'calibre.gui2.store.stores.bubok_publishing_plugin:BubokPublishingStore'
drm_free_only = True
headquarters = 'ES'
formats = ['EPUB', 'PDF']
class StoreBubokPortugalStore(StoreBase):
name = 'Bubok Portugal'
description = 'Bubok Publishing Portugal is a publisher, library and store of books of authors from Portugal. They have a big amount of books of a lot of topics' # noqa
actual_plugin = 'calibre.gui2.store.stores.bubok_portugal_plugin:BubokPortugalStore'
drm_free_only = True
headquarters = 'PT'
formats = ['EPUB', 'PDF']
class StoreBaenWebScriptionStore(StoreBase):
name = 'Baen Ebooks'
description = 'Sci-Fi & Fantasy brought to you by Jim Baen.'
actual_plugin = 'calibre.gui2.store.stores.baen_webscription_plugin:BaenWebScriptionStore'
drm_free_only = True
headquarters = 'US'
formats = ['EPUB', 'LIT', 'LRF', 'MOBI', 'RB', 'RTF', 'ZIP']
class StoreBNStore(StoreBase):
name = 'Barnes and Noble'
description = 'The world\'s largest book seller. As the ultimate destination for book lovers, Barnes & Noble.com offers an incredible array of content.'
actual_plugin = 'calibre.gui2.store.stores.bn_plugin:BNStore'
headquarters = 'US'
formats = ['NOOK']
class StoreBeamEBooksDEStore(StoreBase):
name = 'Beam EBooks DE'
author = 'Charles Haley'
description = 'Bei uns finden Sie: Tausende deutschsprachige e-books; Alle e-books ohne hartes DRM; PDF, ePub und Mobipocket Format; Sofortige Verfügbarkeit - 24 Stunden am Tag; Günstige Preise; e-books für viele Lesegeräte, PC,Mac und Smartphones; Viele Gratis e-books' # noqa
actual_plugin = 'calibre.gui2.store.stores.beam_ebooks_de_plugin:BeamEBooksDEStore'
drm_free_only = True
headquarters = 'DE'
formats = ['EPUB', 'MOBI', 'PDF']
class StoreBiblioStore(StoreBase):
name = 'Библио.бг'
author = 'Alex Stanev'
description = 'Електронна книжарница за книги и списания във формати ePUB и PDF. Част от заглавията са с активна DRM защита.'
actual_plugin = 'calibre.gui2.store.stores.biblio_plugin:BiblioStore'
headquarters = 'BG'
formats = ['EPUB, PDF']
class StoreChitankaStore(StoreBase):
name = 'Моята библиотека'
author = 'Alex Stanev'
description = 'Независим сайт за DRM свободна литература на български език'
actual_plugin = 'calibre.gui2.store.stores.chitanka_plugin:ChitankaStore'
drm_free_only = True
headquarters = 'BG'
formats = ['FB2', 'EPUB', 'TXT', 'SFB']
class StoreEbookNLStore(StoreBase):
name = 'eBook.nl'
description = 'De eBookwinkel van Nederland'
actual_plugin = 'calibre.gui2.store.stores.ebook_nl_plugin:EBookNLStore'
headquarters = 'NL'
formats = ['EPUB', 'PDF']
affiliate = False
class StoreEbookpointStore(StoreBase):
name = 'Ebookpoint'
author = 'Tomasz Długosz'
description = 'E-booki wolne od DRM, 3 formaty w pakiecie, wysyłanie na Kindle'
actual_plugin = 'calibre.gui2.store.stores.ebookpoint_plugin:EbookpointStore'
drm_free_only = True
headquarters = 'PL'
formats = ['EPUB', 'MOBI', 'PDF']
affiliate = True
class StoreEbookscomStore(StoreBase):
name = 'eBooks.com'
description = 'Sells books in multiple electronic formats in all categories. Technical infrastructure is cutting edge, robust and scalable, with servers in the US and Europe.' # noqa
actual_plugin = 'calibre.gui2.store.stores.ebooks_com_plugin:EbookscomStore'
headquarters = 'US'
formats = ['EPUB', 'LIT', 'MOBI', 'PDF']
affiliate = True
class StoreEbooksGratuitsStore(StoreBase):
name = 'EbooksGratuits.com'
description = 'Ebooks Libres et Gratuits'
actual_plugin = 'calibre.gui2.store.stores.ebooksgratuits_plugin:EbooksGratuitsStore'
headquarters = 'FR'
formats = ['EPUB', 'MOBI', 'PDF', 'PDB']
drm_free_only = True
# class StoreEBookShoppeUKStore(StoreBase):
# name = 'ebookShoppe UK'
# author = 'Charles Haley'
# description = 'We made this website in an attempt to offer the widest range of UK eBooks possible across and as many formats as we could manage.'
# actual_plugin = 'calibre.gui2.store.stores.ebookshoppe_uk_plugin:EBookShoppeUKStore'
#
# headquarters = 'UK'
# formats = ['EPUB', 'PDF']
# affiliate = True
class StoreEmpikStore(StoreBase):
name = 'Empik'
author = 'Tomasz Długosz'
description = 'Empik to marka o unikalnym dziedzictwie i legendarne miejsce, dawne “okno na świat”. Jest obecna w polskim krajobrazie kulturalnym od 60 lat (wcześniej jako Kluby Międzynarodowej Prasy i Książki).' # noqa
actual_plugin = 'calibre.gui2.store.stores.empik_plugin:EmpikStore'
headquarters = 'PL'
formats = ['EPUB', 'MOBI', 'PDF']
affiliate = True
class StoreFeedbooksStore(StoreBase):
name = 'Feedbooks'
description = 'Feedbooks is a cloud publishing and distribution service, connected to a large ecosystem of reading systems and social networks. Provides a variety of genres from independent and classic books.' # noqa
actual_plugin = 'calibre.gui2.store.stores.feedbooks_plugin:FeedbooksStore'
headquarters = 'FR'
formats = ['EPUB', 'MOBI', 'PDF']
class StoreGoogleBooksStore(StoreBase):
name = 'Google Books'
description = 'Google Books'
actual_plugin = 'calibre.gui2.store.stores.google_books_plugin:GoogleBooksStore'
headquarters = 'US'
formats = ['EPUB', 'PDF', 'TXT']
class StoreGutenbergStore(StoreBase):
name = 'Project Gutenberg'
description = 'The first producer of free e-books. Free in the United States because their copyright has expired. They may not be free of copyright in other countries. Readers outside of the United States must check the copyright laws of their countries before downloading or redistributing our e-books.' # noqa
actual_plugin = 'calibre.gui2.store.stores.gutenberg_plugin:GutenbergStore'
drm_free_only = True
headquarters = 'US'
formats = ['EPUB', 'HTML', 'MOBI', 'PDB', 'TXT']
class StoreKoboStore(StoreBase):
name = 'Kobo'
description = 'With over 2.3 million e-books to browse we have engaged readers in over 200 countries in Kobo eReading. Our e-book listings include New York Times Bestsellers, award winners, classics and more!' # noqa
actual_plugin = 'calibre.gui2.store.stores.kobo_plugin:KoboStore'
headquarters = 'CA'
formats = ['EPUB']
affiliate = False
class StoreLegimiStore(StoreBase):
name = 'Legimi'
author = 'Tomasz Długosz'
description = 'E-booki w formacie EPUB, MOBI i PDF'
actual_plugin = 'calibre.gui2.store.stores.legimi_plugin:LegimiStore'
headquarters = 'PL'
formats = ['EPUB', 'PDF', 'MOBI']
affiliate = True
class StoreLibreDEStore(StoreBase):
name = 'ebook.de'
author = 'Charles Haley'
description = 'All Ihre Bücher immer dabei. Suchen, finden, kaufen: so einfach wie nie. ebook.de war libre.de'
actual_plugin = 'calibre.gui2.store.stores.libri_de_plugin:LibreDEStore'
headquarters = 'DE'
formats = ['EPUB', 'PDF']
affiliate = True
class StoreLitResStore(StoreBase):
name = 'LitRes'
description = 'e-books from LitRes.ru'
actual_plugin = 'calibre.gui2.store.stores.litres_plugin:LitResStore'
author = 'Roman Mukhin'
drm_free_only = False
headquarters = 'RU'
formats = ['EPUB', 'TXT', 'RTF', 'HTML', 'FB2', 'LRF', 'PDF', 'MOBI', 'LIT', 'ISILO3', 'JAR', 'RB', 'PRC']
affiliate = True
class StoreManyBooksStore(StoreBase):
name = 'ManyBooks'
description = 'Public domain and creative commons works from many sources.'
actual_plugin = 'calibre.gui2.store.stores.manybooks_plugin:ManyBooksStore'
drm_free_only = True
headquarters = 'US'
formats = ['EPUB', 'FB2', 'JAR', 'LIT', 'LRF', 'MOBI', 'PDB', 'PDF', 'RB', 'RTF', 'TCR', 'TXT', 'ZIP']
class StoreMillsBoonUKStore(StoreBase):
name = 'Mills and Boon UK'
author = 'Charles Haley'
description = '"Bring Romance to Life" "[A] hallmark for romantic fiction, recognised around the world."'
actual_plugin = 'calibre.gui2.store.stores.mills_boon_uk_plugin:MillsBoonUKStore'
headquarters = 'UK'
formats = ['EPUB']
affiliate = False
class StoreMobileReadStore(StoreBase):
name = 'MobileRead'
description = 'E-books handcrafted with the utmost care.'
actual_plugin = 'calibre.gui2.store.stores.mobileread.mobileread_plugin:MobileReadStore'
drm_free_only = True
headquarters = 'CH'
formats = ['EPUB', 'IMP', 'LRF', 'LIT', 'MOBI', 'PDF']
class StoreNextoStore(StoreBase):
name = 'Nexto'
author = 'Tomasz Długosz'
description = 'Największy w Polsce sklep internetowy z audiobookami mp3, ebookami pdf oraz prasą do pobrania on-line.'
actual_plugin = 'calibre.gui2.store.stores.nexto_plugin:NextoStore'
headquarters = 'PL'
formats = ['EPUB', 'MOBI', 'PDF']
affiliate = True
class StoreOzonRUStore(StoreBase):
name = 'OZON.ru'
description = 'e-books from OZON.ru'
actual_plugin = 'calibre.gui2.store.stores.ozon_ru_plugin:OzonRUStore'
author = 'Roman Mukhin'
drm_free_only = True
headquarters = 'RU'
formats = ['TXT', 'PDF', 'DJVU', 'RTF', 'DOC', 'JAR', 'FB2']
affiliate = True
class StorePragmaticBookshelfStore(StoreBase):
name = 'Pragmatic Bookshelf'
description = 'The Pragmatic Bookshelf\'s collection of programming and tech books available as e-books.'
actual_plugin = 'calibre.gui2.store.stores.pragmatic_bookshelf_plugin:PragmaticBookshelfStore'
drm_free_only = True
headquarters = 'US'
formats = ['EPUB', 'MOBI', 'PDF']
class StorePublioStore(StoreBase):
name = 'Publio'
description = 'Publio.pl to księgarnia internetowa, w której mogą Państwo nabyć e-booki i audiobooki.'
actual_plugin = 'calibre.gui2.store.stores.publio_plugin:PublioStore'
author = 'Tomasz Długosz'
headquarters = 'PL'
formats = ['EPUB', 'MOBI', 'PDF']
affiliate = True
class StoreRW2010Store(StoreBase):
name = 'RW2010'
description = 'Polski serwis self-publishingowy. Pliki PDF, EPUB i MOBI.'
actual_plugin = 'calibre.gui2.store.stores.rw2010_plugin:RW2010Store'
author = 'Tomasz Długosz'
drm_free_only = True
headquarters = 'PL'
formats = ['EPUB', 'MOBI', 'PDF']
class StoreSmashwordsStore(StoreBase):
name = 'Smashwords'
description = 'An e-book publishing and distribution platform for e-book authors, publishers and readers. Covers many genres and formats.'
actual_plugin = 'calibre.gui2.store.stores.smashwords_plugin:SmashwordsStore'
drm_free_only = True
headquarters = 'US'
formats = ['EPUB', 'HTML', 'LRF', 'MOBI', 'PDB', 'RTF', 'TXT']
affiliate = True
class StoreSwiatEbookowStore(StoreBase):
name = 'Świat Ebooków'
author = 'Tomasz Długosz'
description = 'Ebooki maje tę zaletę, że są zawsze i wszędzie tam, gdzie tylko nas dopadnie ochota na czytanie.'
actual_plugin = 'calibre.gui2.store.stores.swiatebookow_plugin:SwiatEbookowStore'
drm_free_only = True
headquarters = 'PL'
formats = ['EPUB', 'MOBI', 'PDF']
affiliate = True
class StoreVirtualoStore(StoreBase):
name = 'Virtualo'
author = 'Tomasz Długosz'
description = 'Księgarnia internetowa, która oferuje bezpieczny i szeroki dostęp do książek w formie cyfrowej.'
actual_plugin = 'calibre.gui2.store.stores.virtualo_plugin:VirtualoStore'
headquarters = 'PL'
formats = ['EPUB', 'MOBI', 'PDF']
affiliate = True
class StoreWeightlessBooksStore(StoreBase):
name = 'Weightless Books'
description = 'An independent DRM-free e-book site devoted to e-books of all sorts.'
actual_plugin = 'calibre.gui2.store.stores.weightless_books_plugin:WeightlessBooksStore'
drm_free_only = True
headquarters = 'US'
formats = ['EPUB', 'HTML', 'LIT', 'MOBI', 'PDF']
class StoreWolneLekturyStore(StoreBase):
name = 'Wolne Lektury'
author = 'Tomasz Długosz'
description = 'Wolne Lektury to biblioteka internetowa czynna 24 godziny na dobę, 365 dni w roku, której zasoby dostępne są całkowicie za darmo. Wszystkie dzieła są odpowiednio opracowane - opatrzone przypisami, motywami i udostępnione w kilku formatach - HTML, TXT, PDF, EPUB, MOBI, FB2.' # noqa
actual_plugin = 'calibre.gui2.store.stores.wolnelektury_plugin:WolneLekturyStore'
headquarters = 'PL'
formats = ['EPUB', 'MOBI', 'PDF', 'TXT', 'FB2']
class StoreWoblinkStore(StoreBase):
name = 'Woblink'
author = 'Tomasz Długosz'
description = 'Czytanie zdarza się wszędzie!'
actual_plugin = 'calibre.gui2.store.stores.woblink_plugin:WoblinkStore'
headquarters = 'PL'
formats = ['EPUB', 'MOBI', 'PDF', 'WOBLINK']
affiliate = True
plugins += [
StoreArchiveOrgStore,
StoreBubokPublishingStore,
StoreBubokPortugalStore,
StoreAmazonKindleStore,
StoreAmazonAUKindleStore,
StoreAmazonCAKindleStore,
StoreAmazonINKindleStore,
StoreAmazonDEKindleStore,
StoreAmazonESKindleStore,
StoreAmazonFRKindleStore,
StoreAmazonITKindleStore,
StoreAmazonUKKindleStore,
StoreBaenWebScriptionStore,
StoreBNStore,
StoreBeamEBooksDEStore,
StoreBiblioStore,
StoreChitankaStore,
StoreEbookNLStore,
StoreEbookpointStore,
StoreEbookscomStore,
StoreEbooksGratuitsStore,
StoreEmpikStore,
StoreFeedbooksStore,
StoreGoogleBooksStore,
StoreGutenbergStore,
StoreKoboStore,
StoreLegimiStore,
StoreLibreDEStore,
StoreLitResStore,
StoreManyBooksStore,
StoreMillsBoonUKStore,
StoreMobileReadStore,
StoreNextoStore,
StoreOzonRUStore,
StorePragmaticBookshelfStore,
StorePublioStore,
StoreRW2010Store,
StoreSmashwordsStore,
StoreSwiatEbookowStore,
StoreVirtualoStore,
StoreWeightlessBooksStore,
StoreWolneLekturyStore,
StoreWoblinkStore,
]
# }}}
if __name__ == '__main__':
# Test load speed
import subprocess
import textwrap
try:
subprocess.check_call(['python', '-c', textwrap.dedent(
'''
import init_calibre # noqa
def doit():
import calibre.customize.builtins as b # noqa
def show_stats():
from pstats import Stats
s = Stats('/tmp/calibre_stats')
s.sort_stats('cumulative')
s.print_stats(30)
import cProfile
cProfile.run('doit()', '/tmp/calibre_stats')
show_stats()
'''
)])
except subprocess.CalledProcessError:
raise SystemExit(1)
try:
subprocess.check_call(['python', '-c', textwrap.dedent(
'''
import time, sys, init_calibre
st = time.time()
import calibre.customize.builtins
t = time.time() - st
ret = 0
for x in ('lxml', 'calibre.ebooks.BeautifulSoup', 'uuid',
'calibre.utils.terminal', 'calibre.utils.img', 'PIL', 'Image',
'sqlite3', 'mechanize', 'httplib', 'xml', 'inspect', 'urllib',
'calibre.utils.date', 'calibre.utils.config', 'platform',
'calibre.utils.zipfile', 'calibre.utils.formatter',
):
if x in sys.modules:
ret = 1
print(x, 'has been loaded by a plugin')
if ret:
print('\\nA good way to track down what is loading something is to run'
' python -c "import init_calibre; import calibre.customize.builtins"')
print()
print('Time taken to import all plugins: %.2f'%t)
sys.exit(ret)
''')])
except subprocess.CalledProcessError:
raise SystemExit(1)
| 66,801 | Python | .py | 1,543 | 37.621517 | 316 | 0.709173 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,051 | zipplugin.py | kovidgoyal_calibre/src/calibre/customize/zipplugin.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import importlib
import os
import posixpath
import re
import sys
import threading
import zipfile
from collections import OrderedDict
from functools import partial
from importlib.machinery import ModuleSpec
from importlib.util import decode_source
from calibre import as_unicode
from calibre.customize import InvalidPlugin, Plugin, PluginNotFound, numeric_version, platform
from polyglot.builtins import itervalues, reload, string_or_bytes
def get_resources(zfp, name_or_list_of_names, print_tracebacks_for_missing_resources=True):
'''
Load resources from the plugin zip file
:param name_or_list_of_names: List of paths to resources in the zip file using / as
separator, or a single path
:param print_tracebacks_for_missing_resources: When True missing resources are reported to STDERR
:return: A dictionary of the form ``{name : file_contents}``. Any names
that were not found in the zip file will not be present in the
dictionary. If a single path is passed in the return value will
be just the bytes of the resource or None if it wasn't found.
'''
names = name_or_list_of_names
if isinstance(names, string_or_bytes):
names = [names]
ans = {}
with zipfile.ZipFile(zfp) as zf:
for name in names:
try:
ans[name] = zf.read(name)
except:
if print_tracebacks_for_missing_resources:
print('Failed to load resource:', repr(name), 'from the plugin zip file:', zfp, file=sys.stderr)
import traceback
traceback.print_exc()
if len(names) == 1:
ans = ans.pop(names[0], None)
return ans
def get_icons(zfp, name_or_list_of_names, plugin_name='', print_tracebacks_for_missing_resources=True):
'''
Load icons from the plugin zip file
:param name_or_list_of_names: List of paths to resources in the zip file using / as
separator, or a single path
:param plugin_name: The human friendly name of the plugin, used to load icons from
the current theme, if present.
:param print_tracebacks_for_missing_resources: When True missing resources are reported to STDERR
:return: A dictionary of the form ``{name : QIcon}``. Any names
that were not found in the zip file will be null QIcons.
If a single path is passed in the return value will
be A QIcon.
'''
from qt.core import QIcon, QPixmap
ans = {}
namelist = [name_or_list_of_names] if isinstance(name_or_list_of_names, string_or_bytes) else name_or_list_of_names
failed = set()
if plugin_name:
for name in namelist:
q = QIcon.ic(f'{plugin_name}/{name}')
if q.is_ok():
ans[name] = q
else:
failed.add(name)
else:
failed = set(namelist)
if failed:
from_zfp = get_resources(zfp, list(failed), print_tracebacks_for_missing_resources=print_tracebacks_for_missing_resources)
if from_zfp is None:
from_zfp = {}
elif isinstance(from_zfp, string_or_bytes):
from_zfp = {namelist[0]: from_zfp}
for name in failed:
p = QPixmap()
raw = from_zfp.get(name)
if raw:
p.loadFromData(raw)
ans[name] = QIcon(p)
if len(namelist) == 1 and ans:
ans = ans.pop(namelist[0])
return ans
_translations_cache = {}
def load_translations(namespace, zfp):
null = object()
trans = _translations_cache.get(zfp, null)
if trans is None:
return
if trans is null:
from calibre.utils.localization import get_lang
lang = get_lang()
if not lang or lang == 'en': # performance optimization
_translations_cache[zfp] = None
return
with zipfile.ZipFile(zfp) as zf:
mo_path = zipfile.Path(zf, f"translations/{lang}.mo")
if not mo_path.exists() and "_" in lang:
mo_path = zipfile.Path(zf, f"translations/{lang.split('_')[0]}.mo")
if mo_path.exists():
mo = mo_path.read_bytes()
else:
_translations_cache[zfp] = None
return
from gettext import GNUTranslations
from io import BytesIO
trans = _translations_cache[zfp] = GNUTranslations(BytesIO(mo))
namespace['_'] = trans.gettext
namespace['ngettext'] = trans.ngettext
class CalibrePluginLoader:
__slots__ = (
'plugin_name', 'fullname_in_plugin', 'zip_file_path', '_is_package', 'names',
'filename', 'all_names'
)
def __init__(self, plugin_name, fullname_in_plugin, zip_file_path, names, filename, is_package, all_names):
self.plugin_name = plugin_name
self.fullname_in_plugin = fullname_in_plugin
self.zip_file_path = zip_file_path
self.names = names
self.filename = filename
self._is_package = is_package
self.all_names = all_names
def __eq__(self, other):
return (
self.__class__ == other.__class__ and
self.plugin_name == other.plugin_name and
self.fullname_in_plugin == other.fullname_in_plugin
)
def get_resource_reader(self, fullname=None):
return self
def __hash__(self):
return hash(self.name) ^ hash(self.plugin_name) ^ hash(self.fullname_in_plugin)
def create_module(self, spec):
pass
def is_package(self, fullname):
return self._is_package
def get_source_as_bytes(self, fullname=None):
src = b''
if self.plugin_name and self.fullname_in_plugin and self.zip_file_path:
zinfo = self.names.get(self.fullname_in_plugin)
if zinfo is not None:
with zipfile.ZipFile(self.zip_file_path) as zf:
try:
src = zf.read(zinfo)
except Exception:
# Maybe the zip file changed from under us
src = zf.read(zinfo.filename)
return src
def get_source(self, fullname=None):
raw = self.get_source_as_bytes(fullname)
return decode_source(raw)
def get_filename(self, fullname):
return self.filename
def get_code(self, fullname=None):
return compile(self.get_source_as_bytes(fullname), f'calibre_plugins.{self.plugin_name}.{self.fullname_in_plugin}',
'exec', dont_inherit=True)
def exec_module(self, module):
compiled = self.get_code()
module.__file__ = self.filename
if self.zip_file_path:
zfp = self.zip_file_path
module.__dict__['get_resources'] = partial(get_resources, zfp)
module.__dict__['get_icons'] = partial(get_icons, zfp)
module.__dict__['load_translations'] = partial(load_translations, module.__dict__, zfp)
exec(compiled, module.__dict__)
def resource_path(self, name):
raise FileNotFoundError(
f'{name} is not available as a filesystem path in calibre plugins')
def contents(self):
if not self._is_package:
return ()
zinfo = self.names.get(self.fullname_in_plugin)
if zinfo is None:
return ()
base = posixpath.dirname(zinfo.filename)
if base:
base += '/'
def is_ok(x):
if not base or x.startswith(base):
rest = x[len(base):]
return '/' not in rest
return False
return tuple(filter(is_ok, self.all_names))
def is_resource(self, name):
zinfo = self.names.get(self.fullname_in_plugin)
if zinfo is None:
return False
base = posixpath.dirname(zinfo.filename)
q = posixpath.join(base, name)
return q in self.all_names
def open_resource(self, name):
zinfo = self.names.get(self.fullname_in_plugin)
if zinfo is None:
raise FileNotFoundError(f'{self.fullname_in_plugin} not in plugin zip file')
base = posixpath.dirname(zinfo.filename)
q = posixpath.join(base, name)
with zipfile.ZipFile(self.zip_file_path) as zf:
return zf.open(q)
class CalibrePluginFinder:
def __init__(self):
self.loaded_plugins = {}
self._lock = threading.RLock()
self._identifier_pat = re.compile(r'[a-zA-Z][_0-9a-zA-Z]*')
def find_spec(self, fullname, path, target=None):
if not fullname.startswith('calibre_plugins'):
return
parts = fullname.split('.')
if parts[0] != 'calibre_plugins':
return
plugin_name = fullname_in_plugin = zip_file_path = filename = None
all_names = frozenset()
names = OrderedDict()
if len(parts) > 1:
plugin_name = parts[1]
with self._lock:
zip_file_path, names, all_names = self.loaded_plugins.get(plugin_name, (None, None, None))
if zip_file_path is None:
return
fullname_in_plugin = '.'.join(parts[2:])
if not fullname_in_plugin:
fullname_in_plugin = '__init__'
if fullname_in_plugin not in names:
if fullname_in_plugin + '.__init__' in names:
fullname_in_plugin += '.__init__'
else:
return
is_package = bool(
fullname.count('.') < 2 or
fullname_in_plugin == '__init__' or
(fullname_in_plugin and fullname_in_plugin.endswith('.__init__'))
)
if zip_file_path:
filename = posixpath.join(zip_file_path, *fullname_in_plugin.split('.')) + '.py'
return ModuleSpec(
fullname,
CalibrePluginLoader(plugin_name, fullname_in_plugin, zip_file_path, names, filename, is_package, all_names),
is_package=is_package, origin=filename
)
def load(self, path_to_zip_file):
if not os.access(path_to_zip_file, os.R_OK):
raise PluginNotFound('Cannot access %r'%path_to_zip_file)
with zipfile.ZipFile(path_to_zip_file) as zf:
plugin_name = self._locate_code(zf, path_to_zip_file)
try:
ans = None
plugin_module = 'calibre_plugins.%s'%plugin_name
m = sys.modules.get(plugin_module, None)
if m is not None:
reload(m)
else:
m = importlib.import_module(plugin_module)
plugin_classes = []
for obj in itervalues(m.__dict__):
if isinstance(obj, type) and issubclass(obj, Plugin) and \
obj.name != 'Trivial Plugin':
plugin_classes.append(obj)
if not plugin_classes:
raise InvalidPlugin('No plugin class found in %s:%s'%(
as_unicode(path_to_zip_file), plugin_name))
if len(plugin_classes) > 1:
plugin_classes.sort(key=lambda c:(getattr(c, '__module__', None) or '').count('.'))
ans = plugin_classes[0]
if ans.minimum_calibre_version > numeric_version:
raise InvalidPlugin(
'The plugin at %s needs a version of calibre >= %s' %
(as_unicode(path_to_zip_file), '.'.join(map(str,
ans.minimum_calibre_version))))
if platform not in ans.supported_platforms:
raise InvalidPlugin(
'The plugin at %s cannot be used on %s' %
(as_unicode(path_to_zip_file), platform))
return ans
except:
with self._lock:
del self.loaded_plugins[plugin_name]
raise
def _locate_code(self, zf, path_to_zip_file):
all_names = frozenset(zf.namelist())
names = [x[1:] if x[0] == '/' else x for x in all_names]
plugin_name = None
for name in names:
name, ext = posixpath.splitext(name)
if name.startswith('plugin-import-name-') and ext == '.txt':
plugin_name = name.rpartition('-')[-1]
if plugin_name is None:
c = 0
while True:
c += 1
plugin_name = 'dummy%d'%c
if plugin_name not in self.loaded_plugins:
break
else:
if self._identifier_pat.match(plugin_name) is None:
raise InvalidPlugin(
'The plugin at %r uses an invalid import name: %r' %
(path_to_zip_file, plugin_name))
pynames = [x for x in names if x.endswith('.py')]
candidates = [posixpath.dirname(x) for x in pynames if
x.endswith('/__init__.py')]
candidates.sort(key=lambda x: x.count('/'))
valid_packages = set()
for candidate in candidates:
parts = candidate.split('/')
parent = '.'.join(parts[:-1])
if parent and parent not in valid_packages:
continue
valid_packages.add('.'.join(parts))
names = OrderedDict()
for candidate in pynames:
parts = posixpath.splitext(candidate)[0].split('/')
package = '.'.join(parts[:-1])
if package and package not in valid_packages:
continue
name = '.'.join(parts)
names[name] = zf.getinfo(candidate)
# Legacy plugins
if '__init__' not in names:
for name in tuple(names):
if '.' not in name and name.endswith('plugin'):
names['__init__'] = names[name]
break
if '__init__' not in names:
raise InvalidPlugin(('The plugin in %r is invalid. It does not '
'contain a top-level __init__.py file')
% path_to_zip_file)
with self._lock:
self.loaded_plugins[plugin_name] = path_to_zip_file, names, tuple(all_names)
return plugin_name
loader = CalibrePluginFinder()
sys.meta_path.append(loader)
if __name__ == '__main__':
from tempfile import NamedTemporaryFile
from calibre import CurrentDir
from calibre.customize.ui import add_plugin
path = sys.argv[-1]
with NamedTemporaryFile(suffix='.zip') as f:
with zipfile.ZipFile(f, 'w') as zf:
with CurrentDir(path):
for x in os.listdir('.'):
if x[0] != '.':
print('Adding', x)
zf.write(x)
if os.path.isdir(x):
for y in os.listdir(x):
zf.write(os.path.join(x, y))
add_plugin(f.name)
print('Added plugin from', sys.argv[-1])
| 15,072 | Python | .py | 350 | 32.002857 | 130 | 0.575193 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,052 | __init__.py | kovidgoyal_calibre/src/calibre/customize/__init__.py | __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
import enum
import importlib
import os
import sys
import zipfile
from calibre.constants import ismacos, iswindows, numeric_version
from calibre.ptempfile import PersistentTemporaryFile
if iswindows:
platform = 'windows'
elif ismacos:
platform = 'osx'
else:
platform = 'linux'
class PluginNotFound(ValueError):
pass
class InvalidPlugin(ValueError):
pass
class PluginInstallationType(enum.IntEnum):
EXTERNAL = 1
SYSTEM = 2
BUILTIN = 3
class Plugin: # {{{
'''
A calibre plugin. Useful members include:
* ``self.installation_type``: Stores how the plugin was installed.
* ``self.plugin_path``: Stores path to the ZIP file that contains
this plugin or None if it is a builtin
plugin
* ``self.site_customization``: Stores a customization string entered
by the user.
Methods that should be overridden in sub classes:
* :meth:`initialize`
* :meth:`customization_help`
Useful methods:
* :meth:`temporary_file`
* :meth:`__enter__`
* :meth:`load_resources`
'''
#: List of platforms this plugin works on.
#: For example: ``['windows', 'osx', 'linux']``
supported_platforms = []
#: The name of this plugin. You must set it something other
#: than Trivial Plugin for it to work.
name = 'Trivial Plugin'
#: The version of this plugin as a 3-tuple (major, minor, revision)
version = (1, 0, 0)
#: A short string describing what this plugin does
description = _('Does absolutely nothing')
#: The author of this plugin
author = _('Unknown')
#: When more than one plugin exists for a filetype,
#: the plugins are run in order of decreasing priority.
#: Plugins with higher priority will be run first.
#: The highest possible priority is ``sys.maxsize``.
#: Default priority is 1.
priority = 1
#: The earliest version of calibre this plugin requires
minimum_calibre_version = (0, 4, 118)
#: The way this plugin is installed
installation_type = None
#: If False, the user will not be able to disable this plugin. Use with
#: care.
can_be_disabled = True
#: The type of this plugin. Used for categorizing plugins in the
#: GUI
type = _('Base')
def __init__(self, plugin_path):
self.plugin_path = plugin_path
self.site_customization = None
def initialize(self):
'''
Called once when calibre plugins are initialized. Plugins are
re-initialized every time a new plugin is added. Also note that if the
plugin is run in a worker process, such as for adding books, then the
plugin will be initialized for every new worker process.
Perform any plugin specific initialization here, such as extracting
resources from the plugin ZIP file. The path to the ZIP file is
available as ``self.plugin_path``.
Note that ``self.site_customization`` is **not** available at this point.
'''
pass
def config_widget(self):
'''
Implement this method and :meth:`save_settings` in your plugin to
use a custom configuration dialog, rather then relying on the simple
string based default customization.
This method, if implemented, must return a QWidget. The widget can have
an optional method validate() that takes no arguments and is called
immediately after the user clicks OK. Changes are applied if and only
if the method returns True.
If for some reason you cannot perform the configuration at this time,
return a tuple of two strings (message, details), these will be
displayed as a warning dialog to the user and the process will be
aborted.
'''
raise NotImplementedError()
def save_settings(self, config_widget):
'''
Save the settings specified by the user with config_widget.
:param config_widget: The widget returned by :meth:`config_widget`.
'''
raise NotImplementedError()
def do_user_config(self, parent=None):
'''
This method shows a configuration dialog for this plugin. It returns
True if the user clicks OK, False otherwise. The changes are
automatically applied.
'''
from qt.core import QApplication, QDialog, QDialogButtonBox, QLabel, QLineEdit, QScrollArea, QSize, Qt, QVBoxLayout
from calibre.gui2 import gprefs
prefname = 'plugin config dialog:'+self.type + ':' + self.name
config_dialog = QDialog(parent)
button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
v = QVBoxLayout(config_dialog)
button_box.accepted.connect(config_dialog.accept)
button_box.rejected.connect(config_dialog.reject)
config_dialog.setWindowTitle(_('Customize') + ' ' + self.name)
try:
config_widget = self.config_widget()
except NotImplementedError:
config_widget = None
if isinstance(config_widget, tuple):
from calibre.gui2 import warning_dialog
warning_dialog(parent, _('Cannot configure'), config_widget[0],
det_msg=config_widget[1], show=True)
return False
if config_widget is not None:
class SA(QScrollArea):
def sizeHint(self):
sz = self.widget().sizeHint()
fw = 2 * self.frameWidth()
return QSize(sz.width() + self.verticalScrollBar().sizeHint().width() + fw, sz.height() + fw)
sa = SA(config_dialog)
sa.setWidget(config_widget)
sa.setWidgetResizable(True)
v.addWidget(sa)
v.addWidget(button_box)
if not config_dialog.restore_geometry(gprefs, prefname):
QApplication.instance().ensure_window_on_screen(config_dialog)
config_dialog.exec()
if config_dialog.result() == QDialog.DialogCode.Accepted:
if hasattr(config_widget, 'validate'):
if config_widget.validate():
self.save_settings(config_widget)
else:
self.save_settings(config_widget)
else:
from calibre.customize.ui import customize_plugin, plugin_customization
help_text = self.customization_help(gui=True)
help_text = QLabel(help_text, config_dialog)
help_text.setWordWrap(True)
help_text.setTextInteractionFlags(Qt.TextInteractionFlag.LinksAccessibleByMouse | Qt.TextInteractionFlag.LinksAccessibleByKeyboard)
help_text.setOpenExternalLinks(True)
v.addWidget(help_text)
sc = plugin_customization(self)
if not sc:
sc = ''
sc = sc.strip()
sc = QLineEdit(sc, config_dialog)
v.addWidget(sc)
v.addWidget(button_box)
config_dialog.restore_geometry(gprefs, prefname)
config_dialog.exec()
if config_dialog.result() == QDialog.DialogCode.Accepted:
sc = str(sc.text()).strip()
customize_plugin(self, sc)
config_dialog.save_geometry(gprefs, prefname)
return config_dialog.result()
def load_resources(self, names):
'''
If this plugin comes in a ZIP file (user added plugin), this method
will allow you to load resources from the ZIP file.
For example to load an image::
pixmap = QPixmap()
pixmap.loadFromData(self.load_resources(['images/icon.png'])['images/icon.png'])
icon = QIcon(pixmap)
:param names: List of paths to resources in the ZIP file using / as separator
:return: A dictionary of the form ``{name: file_contents}``. Any names
that were not found in the ZIP file will not be present in the
dictionary.
'''
if self.plugin_path is None:
raise ValueError('This plugin was not loaded from a ZIP file')
ans = {}
with zipfile.ZipFile(self.plugin_path, 'r') as zf:
for candidate in zf.namelist():
if candidate in names:
ans[candidate] = zf.read(candidate)
return ans
def customization_help(self, gui=False):
'''
Return a string giving help on how to customize this plugin.
By default raise a :class:`NotImplementedError`, which indicates that
the plugin does not require customization.
If you re-implement this method in your subclass, the user will
be asked to enter a string as customization for this plugin.
The customization string will be available as
``self.site_customization``.
Site customization could be anything, for example, the path to
a needed binary on the user's computer.
:param gui: If True return HTML help, otherwise return plain text help.
'''
raise NotImplementedError()
def temporary_file(self, suffix):
'''
Return a file-like object that is a temporary file on the file system.
This file will remain available even after being closed and will only
be removed on interpreter shutdown. Use the ``name`` member of the
returned object to access the full path to the created temporary file.
:param suffix: The suffix that the temporary file will have.
'''
return PersistentTemporaryFile(suffix)
def is_customizable(self):
try:
self.customization_help()
return True
except NotImplementedError:
return False
def __enter__(self, *args):
'''
Add this plugin to the python path so that it's contents become directly importable.
Useful when bundling large python libraries into the plugin. Use it like this::
with plugin:
import something
'''
if self.plugin_path is not None:
from importlib.machinery import EXTENSION_SUFFIXES
from calibre.utils.zipfile import ZipFile
with ZipFile(self.plugin_path) as zf:
extensions = {x.lower() for x in EXTENSION_SUFFIXES}
zip_safe = True
for name in zf.namelist():
for q in extensions:
if name.endswith(q):
zip_safe = False
break
if not zip_safe:
break
if zip_safe:
sys.path.append(self.plugin_path)
self.sys_insertion_path = self.plugin_path
else:
from calibre.ptempfile import TemporaryDirectory
self._sys_insertion_tdir = TemporaryDirectory('plugin_unzip')
self.sys_insertion_path = self._sys_insertion_tdir.__enter__(*args)
zf.extractall(self.sys_insertion_path)
sys.path.append(self.sys_insertion_path)
def __exit__(self, *args):
ip, it = getattr(self, 'sys_insertion_path', None), getattr(self,
'_sys_insertion_tdir', None)
if ip in sys.path:
sys.path.remove(ip)
if hasattr(it, '__exit__'):
it.__exit__(*args)
def cli_main(self, args):
'''
This method is the main entry point for your plugins command line
interface. It is called when the user does: calibre-debug -r "Plugin
Name". Any arguments passed are present in the args variable.
'''
raise NotImplementedError('The %s plugin has no command line interface'
%self.name)
# }}}
class FileTypePlugin(Plugin): # {{{
'''
A plugin that is associated with a particular set of file types.
'''
#: Set of file types for which this plugin should be run.
#: Use '*' for all file types.
#: For example: ``{'lit', 'mobi', 'prc'}``
file_types = set()
#: If True, this plugin is run when books are added
#: to the database
on_import = False
#: If True, this plugin is run after books are added
#: to the database. In this case the postimport and postadd
#: methods of the plugin are called.
on_postimport = False
#: If True, this plugin is run after a book is converted.
#: In this case the postconvert method of the plugin is called.
on_postconvert = False
#: If True, this plugin is run after a book file is deleted
#: from the database. In this case the postdelete method of
#: the plugin is called.
on_postdelete = False
#: If True, this plugin is run just before a conversion
on_preprocess = False
#: If True, this plugin is run after conversion
#: on the final file produced by the conversion output plugin.
on_postprocess = False
type = _('File type')
def run(self, path_to_ebook):
'''
Run the plugin. Must be implemented in subclasses.
It should perform whatever modifications are required
on the e-book and return the absolute path to the
modified e-book. If no modifications are needed, it should
return the path to the original e-book. If an error is encountered
it should raise an Exception. The default implementation
simply return the path to the original e-book. Note that the path to
the original file (before any file type plugins are run, is available as
self.original_path_to_file).
The modified e-book file should be created with the
:meth:`temporary_file` method.
:param path_to_ebook: Absolute path to the e-book.
:return: Absolute path to the modified e-book.
'''
# Default implementation does nothing
return path_to_ebook
def postimport(self, book_id, book_format, db):
'''
Called post import, i.e., after the book file has been added to the database. Note that
this is different from :meth:`postadd` which is called when the book record is created for
the first time. This method is called whenever a new file is added to a book record. It is
useful for modifying the book record based on the contents of the newly added file.
:param book_id: Database id of the added book.
:param book_format: The file type of the book that was added.
:param db: Library database.
'''
pass # Default implementation does nothing
def postconvert(self, book_id, book_format, db):
'''
Called post conversion, i.e., after the conversion output book file has been added to the database.
Note that it is run after a conversion only, not after a book is added. It is useful for modifying
the book record based on the contents of the newly added file.
:param book_id: Database id of the added book.
:param book_format: The file type of the book that was added.
:param db: Library database.
'''
pass # Default implementation does nothing
def postdelete(self, book_id, book_format, db):
'''
Called post deletion, i.e., after the book file has been deleted from the database. Note
that it is not run when a book record is deleted, only when one or more formats from the
book are deleted. It is useful for modifying the book record based on the format of the
deleted file.
:param book_id: Database id of the added book.
:param book_format: The file type of the book that was added.
:param db: Library database.
'''
pass # Default implementation does nothing
def postadd(self, book_id, fmt_map, db):
'''
Called post add, i.e. after a book has been added to the db. Note that
this is different from :meth:`postimport`, which is called after a single book file
has been added to a book. postadd() is called only when an entire book record
with possibly more than one book file has been created for the first time.
This is useful if you wish to modify the book record in the database when the
book is first added to calibre.
:param book_id: Database id of the added book.
:param fmt_map: Map of file format to path from which the file format
was added. Note that this might or might not point to an actual
existing file, as sometimes files are added as streams. In which case
it might be a dummy value or a non-existent path.
:param db: Library database
'''
pass # Default implementation does nothing
# }}}
class MetadataReaderPlugin(Plugin): # {{{
'''
A plugin that implements reading metadata from a set of file types.
'''
#: Set of file types for which this plugin should be run.
#: For example: ``set(['lit', 'mobi', 'prc'])``
file_types = set()
supported_platforms = ['windows', 'osx', 'linux']
version = numeric_version
author = 'Kovid Goyal'
type = _('Metadata reader')
def __init__(self, *args, **kwargs):
Plugin.__init__(self, *args, **kwargs)
self.quick = False
def get_metadata(self, stream, type):
'''
Return metadata for the file represented by stream (a file like object
that supports reading). Raise an exception when there is an error
with the input data.
:param type: The type of file. Guaranteed to be one of the entries
in :attr:`file_types`.
:return: A :class:`calibre.ebooks.metadata.book.Metadata` object
'''
return None
# }}}
class MetadataWriterPlugin(Plugin): # {{{
'''
A plugin that implements reading metadata from a set of file types.
'''
#: Set of file types for which this plugin should be run.
#: For example: ``set(['lit', 'mobi', 'prc'])``
file_types = set()
supported_platforms = ['windows', 'osx', 'linux']
version = numeric_version
author = 'Kovid Goyal'
type = _('Metadata writer')
def __init__(self, *args, **kwargs):
Plugin.__init__(self, *args, **kwargs)
self.apply_null = False
def set_metadata(self, stream, mi, type):
'''
Set metadata for the file represented by stream (a file like object
that supports reading). Raise an exception when there is an error
with the input data.
:param type: The type of file. Guaranteed to be one of the entries
in :attr:`file_types`.
:param mi: A :class:`calibre.ebooks.metadata.book.Metadata` object
'''
pass
# }}}
class CatalogPlugin(Plugin): # {{{
'''
A plugin that implements a catalog generator.
'''
resources_path = None
#: Output file type for which this plugin should be run.
#: For example: 'epub' or 'xml'
file_types = set()
type = _('Catalog generator')
#: CLI parser options specific to this plugin, declared as `namedtuple` `Option`:
#:
#: from collections import namedtuple
#: Option = namedtuple('Option', 'option, default, dest, help')
#: cli_options = [Option('--catalog-title', default = 'My Catalog',
#: dest = 'catalog_title', help = (_('Title of generated catalog. \nDefault:') + " '" + '%default' + "'"))]
#: cli_options parsed in calibre.db.cli.cmd_catalog:option_parser()
#:
cli_options = []
def _field_sorter(self, key):
'''
Custom fields sort after standard fields
'''
if key.startswith('#'):
return '~%s' % key[1:]
else:
return key
def search_sort_db(self, db, opts):
db.search(opts.search_text)
if getattr(opts, 'sort_by', None):
# 2nd arg = ascending
db.sort(opts.sort_by, True)
return db.get_data_as_dict(ids=opts.ids)
def get_output_fields(self, db, opts):
# Return a list of requested fields
all_std_fields = {'author_sort','authors','comments','cover','formats',
'id','isbn','library_name','ondevice','pubdate','publisher',
'rating','series_index','series','size','tags','timestamp',
'title_sort','title','uuid','languages','identifiers'}
all_custom_fields = set(db.custom_field_keys())
for field in list(all_custom_fields):
fm = db.field_metadata[field]
if fm['datatype'] == 'series':
all_custom_fields.add(field+'_index')
all_fields = all_std_fields.union(all_custom_fields)
if getattr(opts, 'fields', 'all') != 'all':
# Make a list from opts.fields
of = [x.strip() for x in opts.fields.split(',')]
requested_fields = set(of)
# Validate requested_fields
if requested_fields - all_fields:
from calibre.library import current_library_name
invalid_fields = sorted(list(requested_fields - all_fields))
print("invalid --fields specified: %s" % ', '.join(invalid_fields))
print("available fields in '%s': %s" %
(current_library_name(), ', '.join(sorted(list(all_fields)))))
raise ValueError("unable to generate catalog with specified fields")
fields = [x for x in of if x in all_fields]
else:
fields = sorted(all_fields, key=self._field_sorter)
if not opts.connected_device['is_device_connected'] and 'ondevice' in fields:
fields.pop(int(fields.index('ondevice')))
return fields
def initialize(self):
'''
If plugin is not a built-in, copy the plugin's .ui and .py files from
the ZIP file to $TMPDIR.
Tab will be dynamically generated and added to the Catalog Options dialog in
calibre.gui2.dialogs.catalog.py:Catalog
'''
from calibre.customize.builtins import plugins as builtin_plugins
from calibre.customize.ui import config
from calibre.ptempfile import PersistentTemporaryDirectory
if type(self) not in builtin_plugins and self.name not in config['disabled_plugins']:
files_to_copy = [f"{self.name.lower()}.{ext}" for ext in ["ui","py"]]
resources = zipfile.ZipFile(self.plugin_path,'r')
if self.resources_path is None:
self.resources_path = PersistentTemporaryDirectory('_plugin_resources', prefix='')
for file in files_to_copy:
try:
resources.extract(file, self.resources_path)
except:
print(f" customize:__init__.initialize(): {file} not found in {os.path.basename(self.plugin_path)}")
continue
resources.close()
def run(self, path_to_output, opts, db, ids, notification=None):
'''
Run the plugin. Must be implemented in subclasses.
It should generate the catalog in the format specified
in file_types, returning the absolute path to the
generated catalog file. If an error is encountered
it should raise an Exception.
The generated catalog file should be created with the
:meth:`temporary_file` method.
:param path_to_output: Absolute path to the generated catalog file.
:param opts: A dictionary of keyword arguments
:param db: A LibraryDatabase2 object
'''
# Default implementation does nothing
raise NotImplementedError('CatalogPlugin.generate_catalog() default '
'method, should be overridden in subclass')
# }}}
class InterfaceActionBase(Plugin): # {{{
supported_platforms = ['windows', 'osx', 'linux']
author = 'Kovid Goyal'
type = _('User interface action')
can_be_disabled = False
actual_plugin = None
def __init__(self, *args, **kwargs):
Plugin.__init__(self, *args, **kwargs)
self.actual_plugin_ = None
def load_actual_plugin(self, gui):
'''
This method must return the actual interface action plugin object.
'''
ac = self.actual_plugin_
if ac is None:
mod, cls = self.actual_plugin.split(':')
ac = getattr(importlib.import_module(mod), cls)(gui,
self.site_customization)
self.actual_plugin_ = ac
return ac
# }}}
class PreferencesPlugin(Plugin): # {{{
'''
A plugin representing a widget displayed in the Preferences dialog.
This plugin has only one important method :meth:`create_widget`. The
various fields of the plugin control how it is categorized in the UI.
'''
supported_platforms = ['windows', 'osx', 'linux']
author = 'Kovid Goyal'
type = _('Preferences')
can_be_disabled = False
#: Import path to module that contains a class named ConfigWidget
#: which implements the ConfigWidgetInterface. Used by
#: :meth:`create_widget`.
config_widget = None
#: Where in the list of categories the :attr:`category` of this plugin should be.
category_order = 100
#: Where in the list of names in a category, the :attr:`gui_name` of this
#: plugin should be
name_order = 100
#: The category this plugin should be in
category = None
#: The category name displayed to the user for this plugin
gui_category = None
#: The name displayed to the user for this plugin
gui_name = None
#: The icon for this plugin, should be an absolute path
icon = None
#: The description used for tooltips and the like
description = None
def create_widget(self, parent=None):
'''
Create and return the actual Qt widget used for setting this group of
preferences. The widget must implement the
:class:`calibre.gui2.preferences.ConfigWidgetInterface`.
The default implementation uses :attr:`config_widget` to instantiate
the widget.
'''
base, _, wc = self.config_widget.partition(':')
if not wc:
wc = 'ConfigWidget'
base = importlib.import_module(base)
widget = getattr(base, wc)
return widget(parent)
# }}}
class StoreBase(Plugin): # {{{
supported_platforms = ['windows', 'osx', 'linux']
author = 'John Schember'
type = _('Store')
# Information about the store. Should be in the primary language
# of the store. This should not be translatable when set by
# a subclass.
description = _('An e-book store.')
minimum_calibre_version = (0, 8, 0)
version = (1, 0, 1)
actual_plugin = None
# Does the store only distribute e-books without DRM.
drm_free_only = False
# This is the 2 letter country code for the corporate
# headquarters of the store.
headquarters = ''
# All formats the store distributes e-books in.
formats = []
# Is this store on an affiliate program?
affiliate = False
def load_actual_plugin(self, gui):
'''
This method must return the actual interface action plugin object.
'''
mod, cls = self.actual_plugin.split(':')
self.actual_plugin_object = getattr(importlib.import_module(mod), cls)(gui, self.name)
return self.actual_plugin_object
def customization_help(self, gui=False):
if getattr(self, 'actual_plugin_object', None) is not None:
return self.actual_plugin_object.customization_help(gui)
raise NotImplementedError()
def config_widget(self):
if getattr(self, 'actual_plugin_object', None) is not None:
return self.actual_plugin_object.config_widget()
raise NotImplementedError()
def save_settings(self, config_widget):
if getattr(self, 'actual_plugin_object', None) is not None:
return self.actual_plugin_object.save_settings(config_widget)
raise NotImplementedError()
# }}}
class EditBookToolPlugin(Plugin): # {{{
type = _('Edit book tool')
minimum_calibre_version = (1, 46, 0)
# }}}
class LibraryClosedPlugin(Plugin): # {{{
'''
LibraryClosedPlugins are run when a library is closed, either at shutdown,
when the library is changed, or when a library is used in some other way.
At the moment these plugins won't be called by the CLI functions.
'''
type = _('Library closed')
# minimum version 2.54 because that is when support was added
minimum_calibre_version = (2, 54, 0)
def run(self, db):
'''
The db will be a reference to the new_api (db.cache.py).
The plugin must run to completion. It must not use the GUI, threads, or
any signals.
'''
raise NotImplementedError('LibraryClosedPlugin '
'run method must be overridden in subclass')
# }}}
| 29,323 | Python | .py | 638 | 36.796238 | 143 | 0.629918 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,053 | profiles.py | kovidgoyal_calibre/src/calibre/customize/profiles.py | __license__ = 'GPL 3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from calibre.customize import Plugin as _Plugin
FONT_SIZES = [('xx-small', 1),
('x-small', None),
('small', 2),
('medium', 3),
('large', 4),
('x-large', 5),
('xx-large', 6),
(None, 7)]
class Plugin(_Plugin):
fbase = 12
fsizes = [5, 7, 9, 12, 13.5, 17, 20, 22, 24]
screen_size = (1600, 1200)
dpi = 100
def __init__(self, *args, **kwargs):
_Plugin.__init__(self, *args, **kwargs)
self.width, self.height = self.screen_size
fsizes = list(self.fsizes)
self.fkey = list(self.fsizes)
self.fsizes = []
for (name, num), size in zip(FONT_SIZES, fsizes):
self.fsizes.append((name, num, float(size)))
self.fnames = {name: sz for name, _, sz in self.fsizes if name}
self.fnums = {num: sz for _, num, sz in self.fsizes if num}
self.width_pts = self.width * 72./self.dpi
self.height_pts = self.height * 72./self.dpi
# Input profiles {{{
class InputProfile(Plugin):
author = 'Kovid Goyal'
supported_platforms = {'windows', 'osx', 'linux'}
can_be_disabled = False
type = _('Input profile')
name = 'Default Input Profile'
short_name = 'default' # Used in the CLI so dont use spaces etc. in it
description = _('This profile tries to provide sane defaults and is useful '
'if you know nothing about the input document.')
class SonyReaderInput(InputProfile):
name = 'Sony Reader'
short_name = 'sony'
description = _('This profile is intended for the SONY PRS line. '
'The 500/505/600/700 etc.')
screen_size = (584, 754)
dpi = 168.451
fbase = 12
fsizes = [7.5, 9, 10, 12, 15.5, 20, 22, 24]
class SonyReader300Input(SonyReaderInput):
name = 'Sony Reader 300'
short_name = 'sony300'
description = _('This profile is intended for the SONY PRS 300.')
dpi = 200
class SonyReader900Input(SonyReaderInput):
author = 'John Schember'
name = 'Sony Reader 900'
short_name = 'sony900'
description = _('This profile is intended for the SONY PRS-900.')
screen_size = (584, 978)
class MSReaderInput(InputProfile):
name = 'Microsoft Reader'
short_name = 'msreader'
description = _('This profile is intended for the Microsoft Reader.')
screen_size = (480, 652)
dpi = 96
fbase = 13
fsizes = [10, 11, 13, 16, 18, 20, 22, 26]
class MobipocketInput(InputProfile):
name = 'Mobipocket Books'
short_name = 'mobipocket'
description = _('This profile is intended for the Mobipocket books.')
# Unfortunately MOBI books are not narrowly targeted, so this information is
# quite likely to be spurious
screen_size = (600, 800)
dpi = 96
fbase = 18
fsizes = [14, 14, 16, 18, 20, 22, 24, 26]
class HanlinV3Input(InputProfile):
name = 'Hanlin V3'
short_name = 'hanlinv3'
description = _('This profile is intended for the Hanlin V3 and its clones.')
# Screen size is a best guess
screen_size = (584, 754)
dpi = 168.451
fbase = 16
fsizes = [12, 12, 14, 16, 18, 20, 22, 24]
class HanlinV5Input(HanlinV3Input):
name = 'Hanlin V5'
short_name = 'hanlinv5'
description = _('This profile is intended for the Hanlin V5 and its clones.')
# Screen size is a best guess
screen_size = (584, 754)
dpi = 200
class CybookG3Input(InputProfile):
name = 'Cybook G3'
short_name = 'cybookg3'
description = _('This profile is intended for the Cybook G3.')
# Screen size is a best guess
screen_size = (600, 800)
dpi = 168.451
fbase = 16
fsizes = [12, 12, 14, 16, 18, 20, 22, 24]
class CybookOpusInput(InputProfile):
author = 'John Schember'
name = 'Cybook Opus'
short_name = 'cybook_opus'
description = _('This profile is intended for the Cybook Opus.')
# Screen size is a best guess
screen_size = (600, 800)
dpi = 200
fbase = 16
fsizes = [12, 12, 14, 16, 18, 20, 22, 24]
class KindleInput(InputProfile):
name = 'Kindle'
short_name = 'kindle'
description = _('This profile is intended for the Amazon Kindle.')
# Screen size is a best guess
screen_size = (525, 640)
dpi = 168.451
fbase = 16
fsizes = [12, 12, 14, 16, 18, 20, 22, 24]
class IlliadInput(InputProfile):
name = 'Illiad'
short_name = 'illiad'
description = _('This profile is intended for the Irex Illiad.')
screen_size = (760, 925)
dpi = 160.0
fbase = 12
fsizes = [7.5, 9, 10, 12, 15.5, 20, 22, 24]
class IRexDR1000Input(InputProfile):
author = 'John Schember'
name = 'IRex Digital Reader 1000'
short_name = 'irexdr1000'
description = _('This profile is intended for the IRex Digital Reader 1000.')
# Screen size is a best guess
screen_size = (1024, 1280)
dpi = 160
fbase = 16
fsizes = [12, 14, 16, 18, 20, 22, 24]
class IRexDR800Input(InputProfile):
author = 'Eric Cronin'
name = 'IRex Digital Reader 800'
short_name = 'irexdr800'
description = _('This profile is intended for the IRex Digital Reader 800.')
screen_size = (768, 1024)
dpi = 160
fbase = 16
fsizes = [12, 14, 16, 18, 20, 22, 24]
class NookInput(InputProfile):
author = 'John Schember'
name = 'Nook'
short_name = 'nook'
description = _('This profile is intended for the B&N Nook.')
# Screen size is a best guess
screen_size = (600, 800)
dpi = 167
fbase = 16
fsizes = [12, 12, 14, 16, 18, 20, 22, 24]
input_profiles = [InputProfile, SonyReaderInput, SonyReader300Input,
SonyReader900Input, MSReaderInput, MobipocketInput, HanlinV3Input,
HanlinV5Input, CybookG3Input, CybookOpusInput, KindleInput, IlliadInput,
IRexDR1000Input, IRexDR800Input, NookInput]
input_profiles.sort(key=lambda x: x.name.lower())
# }}}
class OutputProfile(Plugin):
author = 'Kovid Goyal'
supported_platforms = {'windows', 'osx', 'linux'}
can_be_disabled = False
type = _('Output profile')
name = 'Default Output Profile'
short_name = 'default' # Used in the CLI so dont use spaces etc. in it
description = _('This profile tries to provide sane defaults and is useful '
'if you want to produce a document intended to be read at a '
'computer or on a range of devices.')
#: The image size for comics
comic_screen_size = (584, 754)
#: If True the MOBI renderer on the device supports MOBI indexing
supports_mobi_indexing = False
#: If True output should be optimized for a touchscreen interface
touchscreen = False
touchscreen_news_css = ''
#: A list of extra (beyond CSS 2.1) modules supported by the device
#: Format is a css_parser profile dictionary (see iPad for example)
extra_css_modules = []
#: If True, the date is appended to the title of downloaded news
periodical_date_in_title = True
#: Characters used in jackets and catalogs
ratings_char = '*'
empty_ratings_char = ' '
#: Unsupported unicode characters to be replaced during preprocessing
unsupported_unicode_chars = []
#: Number of ems that the left margin of a blockquote is rendered as
mobi_ems_per_blockquote = 1.0
#: Special periodical formatting needed in EPUB
epub_periodical_format = None
class iPadOutput(OutputProfile):
name = 'iPad'
short_name = 'ipad'
description = _('Intended for the iPad and similar devices with a '
'resolution of 768x1024')
screen_size = (768, 1024)
comic_screen_size = (768, 1024)
dpi = 132.0
extra_css_modules = [
{
'name':'webkit',
'props': {'-webkit-border-bottom-left-radius':'{length}',
'-webkit-border-bottom-right-radius':'{length}',
'-webkit-border-top-left-radius':'{length}',
'-webkit-border-top-right-radius':'{length}',
'-webkit-border-radius': r'{border-width}(\s+{border-width}){0,3}|inherit',
},
'macros': {'border-width': '{length}|medium|thick|thin'}
}
]
ratings_char = '\u2605' # filled star
empty_ratings_char = '\u2606' # hollow star
touchscreen = True
# touchscreen_news_css {{{
touchscreen_news_css = '''
/* hr used in articles */
.article_articles_list {
width:18%;
}
.article_link {
color: #593f29;
font-style: italic;
}
.article_next {
-webkit-border-top-right-radius:4px;
-webkit-border-bottom-right-radius:4px;
font-style: italic;
width:32%;
}
.article_prev {
-webkit-border-top-left-radius:4px;
-webkit-border-bottom-left-radius:4px;
font-style: italic;
width:32%;
}
.article_sections_list {
width:18%;
}
.articles_link {
font-weight: bold;
}
.sections_link {
font-weight: bold;
}
.caption_divider {
border:#ccc 1px solid;
}
.touchscreen_navbar {
background:#c3bab2;
border:#ccc 0px solid;
border-collapse:separate;
border-spacing:1px;
margin-left: 5%;
margin-right: 5%;
page-break-inside:avoid;
width: 90%;
-webkit-border-radius:4px;
}
.touchscreen_navbar td {
background:#fff;
font-family:Helvetica;
font-size:80%;
/* UI touchboxes use 8px padding */
padding: 6px;
text-align:center;
}
.touchscreen_navbar td a:link {
color: #593f29;
text-decoration: none;
}
/* Index formatting */
.publish_date {
text-align:center;
}
.divider {
border-bottom:1em solid white;
border-top:1px solid gray;
}
hr.caption_divider {
border-color:black;
border-style:solid;
border-width:1px;
}
/* Feed summary formatting */
.article_summary {
display:inline-block;
padding-bottom:0.5em;
}
.feed {
font-family:sans-serif;
font-weight:bold;
font-size:larger;
}
.feed_link {
font-style: italic;
}
.feed_next {
-webkit-border-top-right-radius:4px;
-webkit-border-bottom-right-radius:4px;
font-style: italic;
width:40%;
}
.feed_prev {
-webkit-border-top-left-radius:4px;
-webkit-border-bottom-left-radius:4px;
font-style: italic;
width:40%;
}
.feed_title {
text-align: center;
font-size: 160%;
}
.feed_up {
font-weight: bold;
width:20%;
}
.summary_headline {
font-weight:bold;
text-align:left;
}
.summary_byline {
text-align:left;
font-family:monospace;
}
.summary_text {
text-align:left;
}
'''
# }}}
class iPad3Output(iPadOutput):
screen_size = comic_screen_size = (2048, 1536)
dpi = 264.0
name = 'iPad 3'
short_name = 'ipad3'
description = _('Intended for the iPad 3 and similar devices with a '
'resolution of 1536x2048')
class TabletOutput(iPadOutput):
name = _('Tablet')
short_name = 'tablet'
description = _('Intended for generic tablet devices, does no resizing of images')
screen_size = (10000, 10000)
comic_screen_size = screen_size
class SamsungGalaxy(TabletOutput):
name = 'Samsung Galaxy'
short_name = 'galaxy'
description = _('Intended for the Samsung Galaxy and similar tablet devices with '
'a resolution of 600x1280')
screen_size = comic_screen_size = (600, 1280)
class NookHD(TabletOutput):
name = 'Nook HD+'
short_name = 'nook_hd_plus'
description = _('Intended for the Nook HD+ and similar tablet devices with '
'a resolution of 1280x1920')
screen_size = comic_screen_size = (1280, 1920)
class SonyReaderOutput(OutputProfile):
name = 'Sony Reader'
short_name = 'sony'
description = _('This profile is intended for the SONY PRS line. '
'The 500/505/600/700 etc.')
screen_size = (590, 775)
dpi = 168.451
fbase = 12
fsizes = [7.5, 9, 10, 12, 15.5, 20, 22, 24]
unsupported_unicode_chars = ['\u201f', '\u201b']
epub_periodical_format = 'sony'
# periodical_date_in_title = False
class KoboReaderOutput(OutputProfile):
name = 'Kobo Reader'
short_name = 'kobo'
description = _('This profile is intended for the Kobo Reader.')
screen_size = (536, 710)
comic_screen_size = (536, 710)
dpi = 168.451
fbase = 12
fsizes = [7.5, 9, 10, 12, 15.5, 20, 22, 24]
class SonyReader300Output(SonyReaderOutput):
author = 'John Schember'
name = 'Sony Reader 300'
short_name = 'sony300'
description = _('This profile is intended for the SONY PRS-300.')
dpi = 200
class SonyReader900Output(SonyReaderOutput):
author = 'John Schember'
name = 'Sony Reader 900'
short_name = 'sony900'
description = _('This profile is intended for the SONY PRS-900.')
screen_size = (600, 999)
comic_screen_size = screen_size
class SonyReaderT3Output(SonyReaderOutput):
author = 'Kovid Goyal'
name = 'Sony Reader T3'
short_name = 'sonyt3'
description = _('This profile is intended for the SONY PRS-T3.')
screen_size = (758, 934)
comic_screen_size = screen_size
class GenericEink(SonyReaderOutput):
name = _('Generic e-ink')
short_name = 'generic_eink'
description = _('Suitable for use with any e-ink device')
epub_periodical_format = None
class GenericEinkLarge(GenericEink):
name = _('Generic e-ink large')
short_name = 'generic_eink_large'
description = _('Suitable for use with any large screen e-ink device')
screen_size = (600, 999)
comic_screen_size = screen_size
class GenericEinkHD(GenericEink):
name = _('Generic e-ink HD')
short_name = 'generic_eink_hd'
description = _('Suitable for use with any modern high resolution e-ink device')
screen_size = (10000, 10000)
comic_screen_size = screen_size
class JetBook5Output(OutputProfile):
name = 'JetBook 5-inch'
short_name = 'jetbook5'
description = _('This profile is intended for the 5-inch JetBook.')
screen_size = (480, 640)
dpi = 168.451
class SonyReaderLandscapeOutput(SonyReaderOutput):
name = 'Sony Reader Landscape'
short_name = 'sony-landscape'
description = _('This profile is intended for the SONY PRS line. '
'The 500/505/700 etc, in landscape mode. Mainly useful '
'for comics.')
screen_size = (784, 1012)
comic_screen_size = (784, 1012)
class MSReaderOutput(OutputProfile):
name = 'Microsoft Reader'
short_name = 'msreader'
description = _('This profile is intended for the Microsoft Reader.')
screen_size = (480, 652)
dpi = 96
fbase = 13
fsizes = [10, 11, 13, 16, 18, 20, 22, 26]
class MobipocketOutput(OutputProfile):
name = 'Mobipocket Books'
short_name = 'mobipocket'
description = _('This profile is intended for the Mobipocket books.')
# Unfortunately MOBI books are not narrowly targeted, so this information is
# quite likely to be spurious
screen_size = (600, 800)
dpi = 96
fbase = 18
fsizes = [14, 14, 16, 18, 20, 22, 24, 26]
class HanlinV3Output(OutputProfile):
name = 'Hanlin V3'
short_name = 'hanlinv3'
description = _('This profile is intended for the Hanlin V3 and its clones.')
# Screen size is a best guess
screen_size = (584, 754)
dpi = 168.451
fbase = 16
fsizes = [12, 12, 14, 16, 18, 20, 22, 24]
class HanlinV5Output(HanlinV3Output):
name = 'Hanlin V5'
short_name = 'hanlinv5'
description = _('This profile is intended for the Hanlin V5 and its clones.')
dpi = 200
class CybookG3Output(OutputProfile):
name = 'Cybook G3'
short_name = 'cybookg3'
description = _('This profile is intended for the Cybook G3.')
# Screen size is a best guess
screen_size = (600, 800)
comic_screen_size = (600, 757)
dpi = 168.451
fbase = 16
fsizes = [12, 12, 14, 16, 18, 20, 22, 24]
class CybookOpusOutput(SonyReaderOutput):
author = 'John Schember'
name = 'Cybook Opus'
short_name = 'cybook_opus'
description = _('This profile is intended for the Cybook Opus.')
# Screen size is a best guess
dpi = 200
fbase = 16
fsizes = [12, 12, 14, 16, 18, 20, 22, 24]
epub_periodical_format = None
class KindleOutput(OutputProfile):
name = 'Kindle'
short_name = 'kindle'
description = _('This profile is intended for the Amazon Kindle.')
# Screen size is a best guess
screen_size = (525, 640)
dpi = 168.451
fbase = 16
fsizes = [12, 12, 14, 16, 18, 20, 22, 24]
supports_mobi_indexing = True
periodical_date_in_title = False
empty_ratings_char = '\u2606'
ratings_char = '\u2605'
mobi_ems_per_blockquote = 2.0
class KindleDXOutput(OutputProfile):
name = 'Kindle DX'
short_name = 'kindle_dx'
description = _('This profile is intended for the Amazon Kindle DX.')
# Screen size is a best guess
screen_size = (744, 1022)
dpi = 150.0
comic_screen_size = (771, 1116)
# comic_screen_size = (741, 1022)
supports_mobi_indexing = True
periodical_date_in_title = False
empty_ratings_char = '\u2606'
ratings_char = '\u2605'
mobi_ems_per_blockquote = 2.0
class KindlePaperWhiteOutput(KindleOutput):
name = 'Kindle PaperWhite'
short_name = 'kindle_pw'
description = _('This profile is intended for the Amazon Kindle Paperwhite 1 and 2')
# Screen size is a best guess
screen_size = (658, 940)
dpi = 212.0
comic_screen_size = screen_size
class KindleVoyageOutput(KindleOutput):
name = 'Kindle Voyage'
short_name = 'kindle_voyage'
description = _('This profile is intended for the Amazon Kindle Voyage')
# Screen size is currently just the spec size, actual renderable area will
# depend on someone with the device doing tests.
screen_size = (1080, 1430)
dpi = 300.0
comic_screen_size = screen_size
class KindlePaperWhite3Output(KindleVoyageOutput):
name = 'Kindle PaperWhite 3'
short_name = 'kindle_pw3'
description = _('This profile is intended for the Amazon Kindle Paperwhite 3 and above')
# Screen size is currently just the spec size, actual renderable area will
# depend on someone with the device doing tests.
screen_size = (1072, 1430)
dpi = 300.0
comic_screen_size = screen_size
class KindleOasisOutput(KindlePaperWhite3Output):
name = 'Kindle Oasis'
short_name = 'kindle_oasis'
description = _('This profile is intended for the Amazon Kindle Oasis 2017, Paperwhite 2021 and above')
# Screen size is currently just the spec size, actual renderable area will
# depend on someone with the device doing tests.
screen_size = (1264, 1680)
dpi = 300.0
comic_screen_size = screen_size
class KindleScribeOutput(KindlePaperWhite3Output):
name = 'Kindle Scribe'
short_name = 'kindle_scribe'
description = _('This profile is intended for the Amazon Kindle Scribe 2022 and above')
# Screen size is currently just the spec size, actual renderable area will
# depend on someone with the device doing tests.
screen_size = (1860, 2480)
dpi = 300.0
comic_screen_size = screen_size
class KindleFireOutput(KindleDXOutput):
name = 'Kindle Fire'
short_name = 'kindle_fire'
description = _('This profile is intended for the Amazon Kindle Fire.')
screen_size = (570, 1016)
dpi = 169.0
comic_screen_size = (570, 1016)
class IlliadOutput(OutputProfile):
name = 'Illiad'
short_name = 'illiad'
description = _('This profile is intended for the Irex Illiad.')
screen_size = (760, 925)
comic_screen_size = (760, 925)
dpi = 160.0
fbase = 12
fsizes = [7.5, 9, 10, 12, 15.5, 20, 22, 24]
class IRexDR1000Output(OutputProfile):
author = 'John Schember'
name = 'IRex Digital Reader 1000'
short_name = 'irexdr1000'
description = _('This profile is intended for the IRex Digital Reader 1000.')
# Screen size is a best guess
screen_size = (1024, 1280)
comic_screen_size = (996, 1241)
dpi = 160
fbase = 16
fsizes = [12, 14, 16, 18, 20, 22, 24]
class IRexDR800Output(OutputProfile):
author = 'Eric Cronin'
name = 'IRex Digital Reader 800'
short_name = 'irexdr800'
description = _('This profile is intended for the IRex Digital Reader 800.')
# Screen size is a best guess
screen_size = (768, 1024)
comic_screen_size = (768, 1024)
dpi = 160
fbase = 16
fsizes = [12, 14, 16, 18, 20, 22, 24]
class NookOutput(OutputProfile):
author = 'John Schember'
name = 'Nook'
short_name = 'nook'
description = _('This profile is intended for the B&N Nook.')
# Screen size is a best guess
screen_size = (600, 730)
comic_screen_size = (584, 730)
dpi = 167
fbase = 16
fsizes = [12, 12, 14, 16, 18, 20, 22, 24]
class NookColorOutput(NookOutput):
name = 'Nook Color'
short_name = 'nook_color'
description = _('This profile is intended for the B&N Nook Color.')
screen_size = (600, 900)
comic_screen_size = (594, 900)
dpi = 169
class PocketBook900Output(OutputProfile):
author = 'Chris Lockfort'
name = 'PocketBook Pro 900'
short_name = 'pocketbook_900'
description = _('This profile is intended for the PocketBook Pro 900 series of devices.')
screen_size = (810, 1180)
dpi = 150.0
comic_screen_size = screen_size
class PocketBookPro912Output(OutputProfile):
author = 'Daniele Pizzolli'
name = 'PocketBook Pro 912'
short_name = 'pocketbook_pro_912'
description = _('This profile is intended for the PocketBook Pro 912 series of devices.')
# According to http://download.pocketbook-int.com/user-guides/E_Ink/912/User_Guide_PocketBook_912(EN).pdf
screen_size = (825, 1200)
dpi = 155.0
comic_screen_size = screen_size
class PocketBookLuxOutput(OutputProfile):
author = 'William Ouwehand'
name = 'PocketBook Lux (1-5) and Basic 4'
short_name = 'pocketbook_lux'
description = _('This profile is intended for the PocketBook Lux (1-5) and Basic 4 series of devices.')
screen_size = (758, 1024)
dpi = 212.0
comic_screen_size = screen_size
class PocketBookHDOutput(OutputProfile):
author = 'William Ouwehand'
name = 'PocketBook PocketBook HD Touch (1-3)'
short_name = 'pocketbook_hd'
description = _('This profile is intended for the PocketBook HD Touch (1-3) series of devices.')
screen_size = (1072, 1448)
dpi = 300.0
comic_screen_size = screen_size
class PocketBookInkpad3Output(OutputProfile):
author = 'William Ouwehand'
name = 'PocketBook Inkpad 3 (Pro) and X'
short_name = 'pocketbook_inkpad3'
description = _('This profile is intended for the PocketBook Inkpad 3 and X series of devices.')
screen_size = (1404, 1872)
dpi = 227.0
comic_screen_size = screen_size
output_profiles = [
OutputProfile, SonyReaderOutput, SonyReader300Output, SonyReader900Output,
SonyReaderT3Output, MSReaderOutput, MobipocketOutput, HanlinV3Output,
HanlinV5Output, CybookG3Output, CybookOpusOutput, KindleOutput, iPadOutput,
iPad3Output, KoboReaderOutput, TabletOutput, SamsungGalaxy,
SonyReaderLandscapeOutput, KindleDXOutput, IlliadOutput, NookHD,
IRexDR1000Output, IRexDR800Output, JetBook5Output, NookOutput,
NookColorOutput, PocketBook900Output,
PocketBookPro912Output, PocketBookLuxOutput, PocketBookHDOutput,
PocketBookInkpad3Output, GenericEink, GenericEinkLarge, GenericEinkHD,
KindleFireOutput, KindlePaperWhiteOutput, KindleVoyageOutput,
KindlePaperWhite3Output, KindleOasisOutput, KindleScribeOutput,
]
output_profiles.sort(key=lambda x: x.name.lower())
| 28,144 | Python | .py | 666 | 34.881381 | 109 | 0.562424 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,054 | conversion.py | kovidgoyal_calibre/src/calibre/customize/conversion.py | '''
Defines the plugin system for conversions.
'''
import numbers
import os
import re
import shutil
from calibre import CurrentDir
from calibre.customize import Plugin
class ConversionOption:
'''
Class representing conversion options
'''
def __init__(self, name=None, help=None, long_switch=None,
short_switch=None, choices=None):
self.name = name
self.help = help
self.long_switch = long_switch
self.short_switch = short_switch
self.choices = choices
if self.long_switch is None:
self.long_switch = self.name.replace('_', '-')
self.validate_parameters()
def validate_parameters(self):
'''
Validate the parameters passed to :meth:`__init__`.
'''
if re.match(r'[a-zA-Z_]([a-zA-Z0-9_])*', self.name) is None:
raise ValueError(self.name + ' is not a valid Python identifier')
if not self.help:
raise ValueError('You must set the help text')
def __hash__(self):
return hash(self.name)
def __eq__(self, other):
return self.name == getattr(other, 'name', other)
def clone(self):
return ConversionOption(name=self.name, help=self.help,
long_switch=self.long_switch, short_switch=self.short_switch,
choices=self.choices)
class OptionRecommendation:
LOW = 1
MED = 2
HIGH = 3
def __init__(self, recommended_value=None, level=LOW, **kwargs):
'''
An option recommendation. That is, an option as well as its recommended
value and the level of the recommendation.
'''
self.level = level
self.recommended_value = recommended_value
self.option = kwargs.pop('option', None)
if self.option is None:
self.option = ConversionOption(**kwargs)
self.validate_parameters()
@property
def help(self):
return self.option.help
def clone(self):
return OptionRecommendation(recommended_value=self.recommended_value,
level=self.level, option=self.option.clone())
def validate_parameters(self):
if self.option.choices and self.recommended_value not in \
self.option.choices:
raise ValueError('OpRec: %s: Recommended value not in choices'%
self.option.name)
if not (isinstance(self.recommended_value, (numbers.Number, bytes, str)) or self.recommended_value is None):
raise ValueError('OpRec: %s:'%self.option.name + repr(
self.recommended_value) + ' is not a string or a number')
class DummyReporter:
def __init__(self):
self.cancel_requested = False
def __call__(self, percent, msg=''):
pass
def gui_configuration_widget(name, parent, get_option_by_name,
get_option_help, db, book_id, for_output=True):
import importlib
def widget_factory(cls):
return cls(parent, get_option_by_name,
get_option_help, db, book_id)
if for_output:
try:
output_widget = importlib.import_module(
'calibre.gui2.convert.'+name)
pw = output_widget.PluginWidget
pw.ICON = 'back.png'
pw.HELP = _('Options specific to the output format.')
return widget_factory(pw)
except ImportError:
pass
else:
try:
input_widget = importlib.import_module(
'calibre.gui2.convert.'+name)
pw = input_widget.PluginWidget
pw.ICON = 'forward.png'
pw.HELP = _('Options specific to the input format.')
return widget_factory(pw)
except ImportError:
pass
return None
class InputFormatPlugin(Plugin):
'''
InputFormatPlugins are responsible for converting a document into
HTML+OPF+CSS+etc.
The results of the conversion *must* be encoded in UTF-8.
The main action happens in :meth:`convert`.
'''
type = _('Conversion input')
can_be_disabled = False
supported_platforms = ['windows', 'osx', 'linux']
commit_name = None # unique name under which options for this plugin are saved
ui_data = None
#: Set of file types for which this plugin should be run
#: For example: ``set(['azw', 'mobi', 'prc'])``
file_types = set()
#: If True, this input plugin generates a collection of images,
#: one per HTML file. This can be set dynamically, in the convert method
#: if the input files can be both image collections and non-image collections.
#: If you set this to True, you must implement the get_images() method that returns
#: a list of images.
is_image_collection = False
#: Number of CPU cores used by this plugin.
#: A value of -1 means that it uses all available cores
core_usage = 1
#: If set to True, the input plugin will perform special processing
#: to make its output suitable for viewing
for_viewer = False
#: The encoding that this input plugin creates files in. A value of
#: None means that the encoding is undefined and must be
#: detected individually
output_encoding = 'utf-8'
#: Options shared by all Input format plugins. Do not override
#: in sub-classes. Use :attr:`options` instead. Every option must be an
#: instance of :class:`OptionRecommendation`.
common_options = {
OptionRecommendation(name='input_encoding',
recommended_value=None, level=OptionRecommendation.LOW,
help=_('Specify the character encoding of the input document. If '
'set this option will override any encoding declared by the '
'document itself. Particularly useful for documents that '
'do not declare an encoding or that have erroneous '
'encoding declarations.')
)}
#: Options to customize the behavior of this plugin. Every option must be an
#: instance of :class:`OptionRecommendation`.
options = set()
#: A set of 3-tuples of the form
#: (option_name, recommended_value, recommendation_level)
recommendations = set()
def __init__(self, *args):
Plugin.__init__(self, *args)
self.report_progress = DummyReporter()
def get_images(self):
'''
Return a list of absolute paths to the images, if this input plugin
represents an image collection. The list of images is in the same order
as the spine and the TOC.
'''
raise NotImplementedError()
def convert(self, stream, options, file_ext, log, accelerators):
'''
This method must be implemented in sub-classes. It must return
the path to the created OPF file or an :class:`OEBBook` instance.
All output should be contained in the current folder.
If this plugin creates files outside the current
folder they must be deleted/marked for deletion before this method
returns.
:param stream: A file like object that contains the input file.
:param options: Options to customize the conversion process.
Guaranteed to have attributes corresponding
to all the options declared by this plugin. In
addition, it will have a verbose attribute that
takes integral values from zero upwards. Higher numbers
mean be more verbose. Another useful attribute is
``input_profile`` that is an instance of
:class:`calibre.customize.profiles.InputProfile`.
:param file_ext: The extension (without the .) of the input file. It
is guaranteed to be one of the `file_types` supported
by this plugin.
:param log: A :class:`calibre.utils.logging.Log` object. All output
should use this object.
:param accelerators: A dictionary of various information that the input
plugin can get easily that would speed up the
subsequent stages of the conversion.
'''
raise NotImplementedError()
def __call__(self, stream, options, file_ext, log,
accelerators, output_dir):
try:
log('InputFormatPlugin: %s running'%self.name)
if hasattr(stream, 'name'):
log('on', stream.name)
except:
# In case stdout is broken
pass
with CurrentDir(output_dir):
for x in os.listdir('.'):
shutil.rmtree(x) if os.path.isdir(x) else os.remove(x)
ret = self.convert(stream, options, file_ext,
log, accelerators)
return ret
def postprocess_book(self, oeb, opts, log):
'''
Called to allow the input plugin to perform postprocessing after
the book has been parsed.
'''
pass
def specialize(self, oeb, opts, log, output_fmt):
'''
Called to allow the input plugin to specialize the parsed book
for a particular output format. Called after postprocess_book
and before any transforms are performed on the parsed book.
'''
pass
def gui_configuration_widget(self, parent, get_option_by_name,
get_option_help, db, book_id=None):
'''
Called to create the widget used for configuring this plugin in the
calibre GUI. The widget must be an instance of the PluginWidget class.
See the builtin input plugins for examples.
'''
name = self.name.lower().replace(' ', '_')
return gui_configuration_widget(name, parent, get_option_by_name,
get_option_help, db, book_id, for_output=False)
class OutputFormatPlugin(Plugin):
'''
OutputFormatPlugins are responsible for converting an OEB document
(OPF+HTML) into an output e-book.
The OEB document can be assumed to be encoded in UTF-8.
The main action happens in :meth:`convert`.
'''
type = _('Conversion output')
can_be_disabled = False
supported_platforms = ['windows', 'osx', 'linux']
commit_name = None # unique name under which options for this plugin are saved
ui_data = None
#: The file type (extension without leading period) that this
#: plugin outputs
file_type = None
#: Options shared by all Input format plugins. Do not override
#: in sub-classes. Use :attr:`options` instead. Every option must be an
#: instance of :class:`OptionRecommendation`.
common_options = {
OptionRecommendation(name='pretty_print',
recommended_value=False, level=OptionRecommendation.LOW,
help=_('If specified, the output plugin will try to create output '
'that is as human readable as possible. May not have any effect '
'for some output plugins.')
)}
#: Options to customize the behavior of this plugin. Every option must be an
#: instance of :class:`OptionRecommendation`.
options = set()
#: A set of 3-tuples of the form
#: (option_name, recommended_value, recommendation_level)
recommendations = set()
@property
def description(self):
return _('Convert e-books to the %s format')%self.file_type.upper()
def __init__(self, *args):
Plugin.__init__(self, *args)
self.report_progress = DummyReporter()
def convert(self, oeb_book, output, input_plugin, opts, log):
'''
Render the contents of `oeb_book` (which is an instance of
:class:`calibre.ebooks.oeb.OEBBook`) to the file specified by output.
:param output: Either a file like object or a string. If it is a string
it is the path to a folder that may or may not exist. The output
plugin should write its output into that folder. If it is a file like
object, the output plugin should write its output into the file.
:param input_plugin: The input plugin that was used at the beginning of
the conversion pipeline.
:param opts: Conversion options. Guaranteed to have attributes
corresponding to the OptionRecommendations of this plugin.
:param log: The logger. Print debug/info messages etc. using this.
'''
raise NotImplementedError()
@property
def is_periodical(self):
return self.oeb.metadata.publication_type and \
str(self.oeb.metadata.publication_type[0]).startswith('periodical:')
def specialize_options(self, log, opts, input_fmt):
'''
Can be used to change the values of conversion options, as used by the
conversion pipeline.
'''
pass
def specialize_css_for_output(self, log, opts, item, stylizer):
'''
Can be used to make changes to the CSS during the CSS flattening
process.
:param item: The item (HTML file) being processed
:param stylizer: A Stylizer object containing the flattened styles for
item. You can get the style for any element by
stylizer.style(element).
'''
pass
def gui_configuration_widget(self, parent, get_option_by_name,
get_option_help, db, book_id=None):
'''
Called to create the widget used for configuring this plugin in the
calibre GUI. The widget must be an instance of the PluginWidget class.
See the builtin output plugins for examples.
'''
name = self.name.lower().replace(' ', '_')
return gui_configuration_widget(name, parent, get_option_by_name,
get_option_help, db, book_id, for_output=True)
| 13,982 | Python | .py | 306 | 35.934641 | 116 | 0.628326 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,055 | schema_upgrades.py | kovidgoyal_calibre/src/calibre/db/schema_upgrades.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os
from calibre import prints
from calibre.utils.date import DEFAULT_DATE, isoformat
from polyglot.builtins import itervalues
class SchemaUpgrade:
def __init__(self, db, library_path, field_metadata):
db.execute('BEGIN EXCLUSIVE TRANSACTION')
self.db = db
self.library_path = library_path
self.field_metadata = field_metadata
# Upgrade database
try:
while True:
uv = next(self.db.execute('pragma user_version'))[0]
meth = getattr(self, 'upgrade_version_%d'%uv, None)
if meth is None:
break
else:
prints('Upgrading database to version %d...'%(uv+1))
meth()
self.db.execute('pragma user_version=%d'%(uv+1))
except:
self.db.execute('ROLLBACK')
raise
else:
self.db.execute('COMMIT')
finally:
self.db = self.field_metadata = None
def upgrade_version_1(self):
'''
Normalize indices.
'''
self.db.execute('''\
DROP INDEX IF EXISTS authors_idx;
CREATE INDEX authors_idx ON books (author_sort COLLATE NOCASE, sort COLLATE NOCASE);
DROP INDEX IF EXISTS series_idx;
CREATE INDEX series_idx ON series (name COLLATE NOCASE);
DROP INDEX IF EXISTS series_sort_idx;
CREATE INDEX series_sort_idx ON books (series_index, id);
''')
def upgrade_version_2(self):
''' Fix Foreign key constraints for deleting from link tables. '''
script = '''\
DROP TRIGGER IF EXISTS fkc_delete_books_%(ltable)s_link;
CREATE TRIGGER fkc_delete_on_%(table)s
BEFORE DELETE ON %(table)s
BEGIN
SELECT CASE
WHEN (SELECT COUNT(id) FROM books_%(ltable)s_link WHERE %(ltable_col)s=OLD.id) > 0
THEN RAISE(ABORT, 'Foreign key violation: %(table)s is still referenced')
END;
END;
DELETE FROM %(table)s WHERE (SELECT COUNT(id) FROM books_%(ltable)s_link WHERE %(ltable_col)s=%(table)s.id) < 1;
'''
self.db.execute(script%dict(ltable='authors', table='authors', ltable_col='author'))
self.db.execute(script%dict(ltable='publishers', table='publishers', ltable_col='publisher'))
self.db.execute(script%dict(ltable='tags', table='tags', ltable_col='tag'))
self.db.execute(script%dict(ltable='series', table='series', ltable_col='series'))
def upgrade_version_3(self):
' Add path to result cache '
self.db.execute('''
DROP VIEW IF EXISTS meta;
CREATE VIEW meta AS
SELECT id, title,
(SELECT concat(name) FROM authors WHERE authors.id IN (SELECT author from books_authors_link WHERE book=books.id)) authors,
(SELECT name FROM publishers WHERE publishers.id IN (SELECT publisher from books_publishers_link WHERE book=books.id)) publisher,
(SELECT rating FROM ratings WHERE ratings.id IN (SELECT rating from books_ratings_link WHERE book=books.id)) rating,
timestamp,
(SELECT MAX(uncompressed_size) FROM data WHERE book=books.id) size,
(SELECT concat(name) FROM tags WHERE tags.id IN (SELECT tag from books_tags_link WHERE book=books.id)) tags,
(SELECT text FROM comments WHERE book=books.id) comments,
(SELECT name FROM series WHERE series.id IN (SELECT series FROM books_series_link WHERE book=books.id)) series,
series_index,
sort,
author_sort,
(SELECT concat(format) FROM data WHERE data.book=books.id) formats,
isbn,
path
FROM books;
''')
def upgrade_version_4(self):
'Rationalize books table'
self.db.execute('''
CREATE TEMPORARY TABLE
books_backup(id,title,sort,timestamp,series_index,author_sort,isbn,path);
INSERT INTO books_backup SELECT id,title,sort,timestamp,series_index,author_sort,isbn,path FROM books;
DROP TABLE books;
CREATE TABLE books ( id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL DEFAULT 'Unknown' COLLATE NOCASE,
sort TEXT COLLATE NOCASE,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
pubdate TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
series_index REAL NOT NULL DEFAULT 1.0,
author_sort TEXT COLLATE NOCASE,
isbn TEXT DEFAULT "" COLLATE NOCASE,
lccn TEXT DEFAULT "" COLLATE NOCASE,
path TEXT NOT NULL DEFAULT "",
flags INTEGER NOT NULL DEFAULT 1
);
INSERT INTO
books (id,title,sort,timestamp,pubdate,series_index,author_sort,isbn,path)
SELECT id,title,sort,timestamp,timestamp,series_index,author_sort,isbn,path FROM books_backup;
DROP TABLE books_backup;
DROP VIEW IF EXISTS meta;
CREATE VIEW meta AS
SELECT id, title,
(SELECT concat(name) FROM authors WHERE authors.id IN (SELECT author from books_authors_link WHERE book=books.id)) authors,
(SELECT name FROM publishers WHERE publishers.id IN (SELECT publisher from books_publishers_link WHERE book=books.id)) publisher,
(SELECT rating FROM ratings WHERE ratings.id IN (SELECT rating from books_ratings_link WHERE book=books.id)) rating,
timestamp,
(SELECT MAX(uncompressed_size) FROM data WHERE book=books.id) size,
(SELECT concat(name) FROM tags WHERE tags.id IN (SELECT tag from books_tags_link WHERE book=books.id)) tags,
(SELECT text FROM comments WHERE book=books.id) comments,
(SELECT name FROM series WHERE series.id IN (SELECT series FROM books_series_link WHERE book=books.id)) series,
series_index,
sort,
author_sort,
(SELECT concat(format) FROM data WHERE data.book=books.id) formats,
isbn,
path,
lccn,
pubdate,
flags
FROM books;
''')
def upgrade_version_5(self):
'Update indexes/triggers for new books table'
self.db.execute('''
CREATE INDEX authors_idx ON books (author_sort COLLATE NOCASE);
CREATE INDEX books_idx ON books (sort COLLATE NOCASE);
CREATE TRIGGER books_delete_trg
AFTER DELETE ON books
BEGIN
DELETE FROM books_authors_link WHERE book=OLD.id;
DELETE FROM books_publishers_link WHERE book=OLD.id;
DELETE FROM books_ratings_link WHERE book=OLD.id;
DELETE FROM books_series_link WHERE book=OLD.id;
DELETE FROM books_tags_link WHERE book=OLD.id;
DELETE FROM data WHERE book=OLD.id;
DELETE FROM comments WHERE book=OLD.id;
DELETE FROM conversion_options WHERE book=OLD.id;
END;
CREATE TRIGGER books_insert_trg
AFTER INSERT ON books
BEGIN
UPDATE books SET sort=title_sort(NEW.title) WHERE id=NEW.id;
END;
CREATE TRIGGER books_update_trg
AFTER UPDATE ON books
BEGIN
UPDATE books SET sort=title_sort(NEW.title) WHERE id=NEW.id;
END;
UPDATE books SET sort=title_sort(title) WHERE sort IS NULL;
'''
)
def upgrade_version_6(self):
'Show authors in order'
self.db.execute('''
DROP VIEW IF EXISTS meta;
CREATE VIEW meta AS
SELECT id, title,
(SELECT sortconcat(bal.id, name) FROM books_authors_link AS bal JOIN authors ON(author = authors.id) WHERE book = books.id) authors,
(SELECT name FROM publishers WHERE publishers.id IN (SELECT publisher from books_publishers_link WHERE book=books.id)) publisher,
(SELECT rating FROM ratings WHERE ratings.id IN (SELECT rating from books_ratings_link WHERE book=books.id)) rating,
timestamp,
(SELECT MAX(uncompressed_size) FROM data WHERE book=books.id) size,
(SELECT concat(name) FROM tags WHERE tags.id IN (SELECT tag from books_tags_link WHERE book=books.id)) tags,
(SELECT text FROM comments WHERE book=books.id) comments,
(SELECT name FROM series WHERE series.id IN (SELECT series FROM books_series_link WHERE book=books.id)) series,
series_index,
sort,
author_sort,
(SELECT concat(format) FROM data WHERE data.book=books.id) formats,
isbn,
path,
lccn,
pubdate,
flags
FROM books;
''')
def upgrade_version_7(self):
'Add uuid column'
self.db.execute('''
ALTER TABLE books ADD COLUMN uuid TEXT;
DROP TRIGGER IF EXISTS books_insert_trg;
DROP TRIGGER IF EXISTS books_update_trg;
UPDATE books SET uuid=uuid4();
CREATE TRIGGER books_insert_trg AFTER INSERT ON books
BEGIN
UPDATE books SET sort=title_sort(NEW.title),uuid=uuid4() WHERE id=NEW.id;
END;
CREATE TRIGGER books_update_trg AFTER UPDATE ON books
BEGIN
UPDATE books SET sort=title_sort(NEW.title) WHERE id=NEW.id;
END;
DROP VIEW IF EXISTS meta;
CREATE VIEW meta AS
SELECT id, title,
(SELECT sortconcat(bal.id, name) FROM books_authors_link AS bal JOIN authors ON(author = authors.id) WHERE book = books.id) authors,
(SELECT name FROM publishers WHERE publishers.id IN (SELECT publisher from books_publishers_link WHERE book=books.id)) publisher,
(SELECT rating FROM ratings WHERE ratings.id IN (SELECT rating from books_ratings_link WHERE book=books.id)) rating,
timestamp,
(SELECT MAX(uncompressed_size) FROM data WHERE book=books.id) size,
(SELECT concat(name) FROM tags WHERE tags.id IN (SELECT tag from books_tags_link WHERE book=books.id)) tags,
(SELECT text FROM comments WHERE book=books.id) comments,
(SELECT name FROM series WHERE series.id IN (SELECT series FROM books_series_link WHERE book=books.id)) series,
series_index,
sort,
author_sort,
(SELECT concat(format) FROM data WHERE data.book=books.id) formats,
isbn,
path,
lccn,
pubdate,
flags,
uuid
FROM books;
''')
def upgrade_version_8(self):
'Add Tag Browser views'
def create_tag_browser_view(table_name, column_name):
self.db.execute('''
DROP VIEW IF EXISTS tag_browser_{tn};
CREATE VIEW tag_browser_{tn} AS SELECT
id,
name,
(SELECT COUNT(id) FROM books_{tn}_link WHERE {cn}={tn}.id) count
FROM {tn};
'''.format(tn=table_name, cn=column_name))
for tn in ('authors', 'tags', 'publishers', 'series'):
cn = tn[:-1]
if tn == 'series':
cn = tn
create_tag_browser_view(tn, cn)
def upgrade_version_9(self):
'Add custom columns'
self.db.execute('''
CREATE TABLE custom_columns (
id INTEGER PRIMARY KEY AUTOINCREMENT,
label TEXT NOT NULL,
name TEXT NOT NULL,
datatype TEXT NOT NULL,
mark_for_delete BOOL DEFAULT 0 NOT NULL,
editable BOOL DEFAULT 1 NOT NULL,
display TEXT DEFAULT "{}" NOT NULL,
is_multiple BOOL DEFAULT 0 NOT NULL,
normalized BOOL NOT NULL,
UNIQUE(label)
);
CREATE INDEX IF NOT EXISTS custom_columns_idx ON custom_columns (label);
CREATE INDEX IF NOT EXISTS formats_idx ON data (format);
''')
def upgrade_version_10(self):
'Add restricted Tag Browser views'
def create_tag_browser_view(table_name, column_name, view_column_name):
script = ('''
DROP VIEW IF EXISTS tag_browser_{tn};
CREATE VIEW tag_browser_{tn} AS SELECT
id,
{vcn},
(SELECT COUNT(id) FROM books_{tn}_link WHERE {cn}={tn}.id) count
FROM {tn};
DROP VIEW IF EXISTS tag_browser_filtered_{tn};
CREATE VIEW tag_browser_filtered_{tn} AS SELECT
id,
{vcn},
(SELECT COUNT(books_{tn}_link.id) FROM books_{tn}_link WHERE
{cn}={tn}.id AND books_list_filter(book)) count
FROM {tn};
'''.format(tn=table_name, cn=column_name, vcn=view_column_name))
self.db.execute(script)
for field in itervalues(self.field_metadata):
if field['is_category'] and not field['is_custom'] and 'link_column' in field:
table = self.db.get(
'SELECT name FROM sqlite_master WHERE type=\'table\' AND name=?',
('books_%s_link'%field['table'],), all=False)
if table is not None:
create_tag_browser_view(field['table'], field['link_column'], field['column'])
def upgrade_version_11(self):
'Add average rating to tag browser views'
def create_std_tag_browser_view(table_name, column_name,
view_column_name, sort_column_name):
script = ('''
DROP VIEW IF EXISTS tag_browser_{tn};
CREATE VIEW tag_browser_{tn} AS SELECT
id,
{vcn},
(SELECT COUNT(id) FROM books_{tn}_link WHERE {cn}={tn}.id) count,
(SELECT AVG(ratings.rating)
FROM books_{tn}_link AS tl, books_ratings_link AS bl, ratings
WHERE tl.{cn}={tn}.id AND bl.book=tl.book AND
ratings.id = bl.rating AND ratings.rating <> 0) avg_rating,
{scn} AS sort
FROM {tn};
DROP VIEW IF EXISTS tag_browser_filtered_{tn};
CREATE VIEW tag_browser_filtered_{tn} AS SELECT
id,
{vcn},
(SELECT COUNT(books_{tn}_link.id) FROM books_{tn}_link WHERE
{cn}={tn}.id AND books_list_filter(book)) count,
(SELECT AVG(ratings.rating)
FROM books_{tn}_link AS tl, books_ratings_link AS bl, ratings
WHERE tl.{cn}={tn}.id AND bl.book=tl.book AND
ratings.id = bl.rating AND ratings.rating <> 0 AND
books_list_filter(bl.book)) avg_rating,
{scn} AS sort
FROM {tn};
'''.format(tn=table_name, cn=column_name,
vcn=view_column_name, scn=sort_column_name))
self.db.execute(script)
def create_cust_tag_browser_view(table_name, link_table_name):
script = '''
DROP VIEW IF EXISTS tag_browser_{table};
CREATE VIEW tag_browser_{table} AS SELECT
id,
value,
(SELECT COUNT(id) FROM {lt} WHERE value={table}.id) count,
(SELECT AVG(r.rating)
FROM {lt},
books_ratings_link AS bl,
ratings AS r
WHERE {lt}.value={table}.id AND bl.book={lt}.book AND
r.id = bl.rating AND r.rating <> 0) avg_rating,
value AS sort
FROM {table};
DROP VIEW IF EXISTS tag_browser_filtered_{table};
CREATE VIEW tag_browser_filtered_{table} AS SELECT
id,
value,
(SELECT COUNT({lt}.id) FROM {lt} WHERE value={table}.id AND
books_list_filter(book)) count,
(SELECT AVG(r.rating)
FROM {lt},
books_ratings_link AS bl,
ratings AS r
WHERE {lt}.value={table}.id AND bl.book={lt}.book AND
r.id = bl.rating AND r.rating <> 0 AND
books_list_filter(bl.book)) avg_rating,
value AS sort
FROM {table};
'''.format(lt=link_table_name, table=table_name)
self.db.execute(script)
for field in itervalues(self.field_metadata):
if field['is_category'] and not field['is_custom'] and 'link_column' in field:
table = self.db.get(
'SELECT name FROM sqlite_master WHERE type=\'table\' AND name=?',
('books_%s_link'%field['table'],), all=False)
if table is not None:
create_std_tag_browser_view(field['table'], field['link_column'],
field['column'], field['category_sort'])
db_tables = self.db.get('''SELECT name FROM sqlite_master
WHERE type='table'
ORDER BY name''')
tables = []
for (table,) in db_tables:
tables.append(table)
for table in tables:
link_table = 'books_%s_link'%table
if table.startswith('custom_column_') and link_table in tables:
create_cust_tag_browser_view(table, link_table)
self.db.execute('UPDATE authors SET sort=author_to_author_sort(name)')
def upgrade_version_12(self):
'DB based preference store'
script = '''
DROP TABLE IF EXISTS preferences;
CREATE TABLE preferences(id INTEGER PRIMARY KEY,
key TEXT NOT NULL,
val TEXT NOT NULL,
UNIQUE(key));
'''
self.db.execute(script)
def upgrade_version_13(self):
'Dirtied table for OPF metadata backups'
script = '''
DROP TABLE IF EXISTS metadata_dirtied;
CREATE TABLE metadata_dirtied(id INTEGER PRIMARY KEY,
book INTEGER NOT NULL,
UNIQUE(book));
INSERT INTO metadata_dirtied (book) SELECT id FROM books;
'''
self.db.execute(script)
def upgrade_version_14(self):
'Cache has_cover'
self.db.execute('ALTER TABLE books ADD COLUMN has_cover BOOL DEFAULT 0')
data = self.db.get('SELECT id,path FROM books', all=True)
def has_cover(path):
if path:
path = os.path.join(self.library_path, path.replace('/', os.sep),
'cover.jpg')
return os.path.exists(path)
return False
ids = [(x[0],) for x in data if has_cover(x[1])]
self.db.executemany('UPDATE books SET has_cover=1 WHERE id=?', ids)
def upgrade_version_15(self):
'Remove commas from tags'
self.db.execute("UPDATE OR IGNORE tags SET name=REPLACE(name, ',', ';')")
self.db.execute("UPDATE OR IGNORE tags SET name=REPLACE(name, ',', ';;')")
self.db.execute("UPDATE OR IGNORE tags SET name=REPLACE(name, ',', '')")
def upgrade_version_16(self):
self.db.execute('''
DROP TRIGGER IF EXISTS books_update_trg;
CREATE TRIGGER books_update_trg
AFTER UPDATE ON books
BEGIN
UPDATE books SET sort=title_sort(NEW.title)
WHERE id=NEW.id AND OLD.title <> NEW.title;
END;
''')
def upgrade_version_17(self):
'custom book data table (for plugins)'
script = '''
DROP TABLE IF EXISTS books_plugin_data;
CREATE TABLE books_plugin_data(id INTEGER PRIMARY KEY,
book INTEGER NOT NULL,
name TEXT NOT NULL,
val TEXT NOT NULL,
UNIQUE(book,name));
DROP TRIGGER IF EXISTS books_delete_trg;
CREATE TRIGGER books_delete_trg
AFTER DELETE ON books
BEGIN
DELETE FROM books_authors_link WHERE book=OLD.id;
DELETE FROM books_publishers_link WHERE book=OLD.id;
DELETE FROM books_ratings_link WHERE book=OLD.id;
DELETE FROM books_series_link WHERE book=OLD.id;
DELETE FROM books_tags_link WHERE book=OLD.id;
DELETE FROM data WHERE book=OLD.id;
DELETE FROM comments WHERE book=OLD.id;
DELETE FROM conversion_options WHERE book=OLD.id;
DELETE FROM books_plugin_data WHERE book=OLD.id;
END;
'''
self.db.execute(script)
def upgrade_version_18(self):
'''
Add a library UUID.
Add an identifiers table.
Add a languages table.
Add a last_modified column.
NOTE: You cannot downgrade after this update, if you do
any changes you make to book isbns will be lost.
'''
script = '''
DROP TABLE IF EXISTS library_id;
CREATE TABLE library_id ( id INTEGER PRIMARY KEY,
uuid TEXT NOT NULL,
UNIQUE(uuid)
);
DROP TABLE IF EXISTS identifiers;
CREATE TABLE identifiers ( id INTEGER PRIMARY KEY,
book INTEGER NOT NULL,
type TEXT NOT NULL DEFAULT "isbn" COLLATE NOCASE,
val TEXT NOT NULL COLLATE NOCASE,
UNIQUE(book, type)
);
DROP TABLE IF EXISTS languages;
CREATE TABLE languages ( id INTEGER PRIMARY KEY,
lang_code TEXT NOT NULL COLLATE NOCASE,
UNIQUE(lang_code)
);
DROP TABLE IF EXISTS books_languages_link;
CREATE TABLE books_languages_link ( id INTEGER PRIMARY KEY,
book INTEGER NOT NULL,
lang_code INTEGER NOT NULL,
item_order INTEGER NOT NULL DEFAULT 0,
UNIQUE(book, lang_code)
);
DROP TRIGGER IF EXISTS fkc_delete_on_languages;
CREATE TRIGGER fkc_delete_on_languages
BEFORE DELETE ON languages
BEGIN
SELECT CASE
WHEN (SELECT COUNT(id) FROM books_languages_link WHERE lang_code=OLD.id) > 0
THEN RAISE(ABORT, 'Foreign key violation: language is still referenced')
END;
END;
DROP TRIGGER IF EXISTS fkc_delete_on_languages_link;
CREATE TRIGGER fkc_delete_on_languages_link
BEFORE INSERT ON books_languages_link
BEGIN
SELECT CASE
WHEN (SELECT id from books WHERE id=NEW.book) IS NULL
THEN RAISE(ABORT, 'Foreign key violation: book not in books')
WHEN (SELECT id from languages WHERE id=NEW.lang_code) IS NULL
THEN RAISE(ABORT, 'Foreign key violation: lang_code not in languages')
END;
END;
DROP TRIGGER IF EXISTS fkc_update_books_languages_link_a;
CREATE TRIGGER fkc_update_books_languages_link_a
BEFORE UPDATE OF book ON books_languages_link
BEGIN
SELECT CASE
WHEN (SELECT id from books WHERE id=NEW.book) IS NULL
THEN RAISE(ABORT, 'Foreign key violation: book not in books')
END;
END;
DROP TRIGGER IF EXISTS fkc_update_books_languages_link_b;
CREATE TRIGGER fkc_update_books_languages_link_b
BEFORE UPDATE OF lang_code ON books_languages_link
BEGIN
SELECT CASE
WHEN (SELECT id from languages WHERE id=NEW.lang_code) IS NULL
THEN RAISE(ABORT, 'Foreign key violation: lang_code not in languages')
END;
END;
DROP INDEX IF EXISTS books_languages_link_aidx;
CREATE INDEX books_languages_link_aidx ON books_languages_link (lang_code);
DROP INDEX IF EXISTS books_languages_link_bidx;
CREATE INDEX books_languages_link_bidx ON books_languages_link (book);
DROP INDEX IF EXISTS languages_idx;
CREATE INDEX languages_idx ON languages (lang_code COLLATE NOCASE);
DROP TRIGGER IF EXISTS books_delete_trg;
CREATE TRIGGER books_delete_trg
AFTER DELETE ON books
BEGIN
DELETE FROM books_authors_link WHERE book=OLD.id;
DELETE FROM books_publishers_link WHERE book=OLD.id;
DELETE FROM books_ratings_link WHERE book=OLD.id;
DELETE FROM books_series_link WHERE book=OLD.id;
DELETE FROM books_tags_link WHERE book=OLD.id;
DELETE FROM books_languages_link WHERE book=OLD.id;
DELETE FROM data WHERE book=OLD.id;
DELETE FROM comments WHERE book=OLD.id;
DELETE FROM conversion_options WHERE book=OLD.id;
DELETE FROM books_plugin_data WHERE book=OLD.id;
DELETE FROM identifiers WHERE book=OLD.id;
END;
INSERT INTO identifiers (book, val) SELECT id,isbn FROM books WHERE isbn;
ALTER TABLE books ADD COLUMN last_modified TIMESTAMP NOT NULL DEFAULT "%s";
'''%isoformat(DEFAULT_DATE, sep=' ')
# Sqlite does not support non constant default values in alter
# statements
self.db.execute(script)
def upgrade_version_19(self):
recipes = self.db.get('SELECT id,title,script FROM feeds')
if recipes:
from calibre.web.feeds.recipes import custom_recipe_filename, custom_recipes
bdir = os.path.dirname(custom_recipes.file_path)
for id_, title, script in recipes:
existing = frozenset(map(int, custom_recipes))
if id_ in existing:
id_ = max(existing) + 1000
id_ = str(id_)
fname = custom_recipe_filename(id_, title)
custom_recipes[id_] = (title, fname)
if isinstance(script, str):
script = script.encode('utf-8')
with open(os.path.join(bdir, fname), 'wb') as f:
f.write(script)
def upgrade_version_20(self):
'''
Add a link column to the authors table.
'''
script = '''
ALTER TABLE authors ADD COLUMN link TEXT NOT NULL DEFAULT "";
'''
self.db.execute(script)
def upgrade_version_21(self):
'''
Write the series sort into the existing sort column in the series table
'''
script = '''
DROP TRIGGER IF EXISTS series_insert_trg;
DROP TRIGGER IF EXISTS series_update_trg;
UPDATE series SET sort=title_sort(name);
CREATE TRIGGER series_insert_trg
AFTER INSERT ON series
BEGIN
UPDATE series SET sort=title_sort(NEW.name) WHERE id=NEW.id;
END;
CREATE TRIGGER series_update_trg
AFTER UPDATE ON series
BEGIN
UPDATE series SET sort=title_sort(NEW.name) WHERE id=NEW.id;
END;
'''
self.db.execute(script)
def upgrade_version_22(self):
''' Create the last_read_positions table '''
self.db.execute('''
DROP TABLE IF EXISTS last_read_positions;
CREATE TABLE last_read_positions ( id INTEGER PRIMARY KEY,
book INTEGER NOT NULL,
format TEXT NOT NULL COLLATE NOCASE,
user TEXT NOT NULL,
device TEXT NOT NULL,
cfi TEXT NOT NULL,
epoch REAL NOT NULL,
pos_frac REAL NOT NULL DEFAULT 0,
UNIQUE(user, device, book, format)
);
DROP INDEX IF EXISTS lrp_idx;
CREATE INDEX lrp_idx ON last_read_positions (book);
DROP TRIGGER IF EXISTS books_delete_trg;
CREATE TRIGGER books_delete_trg
AFTER DELETE ON books
BEGIN
DELETE FROM books_authors_link WHERE book=OLD.id;
DELETE FROM books_publishers_link WHERE book=OLD.id;
DELETE FROM books_ratings_link WHERE book=OLD.id;
DELETE FROM books_series_link WHERE book=OLD.id;
DELETE FROM books_tags_link WHERE book=OLD.id;
DELETE FROM books_languages_link WHERE book=OLD.id;
DELETE FROM data WHERE book=OLD.id;
DELETE FROM last_read_positions WHERE book=OLD.id;
DELETE FROM comments WHERE book=OLD.id;
DELETE FROM conversion_options WHERE book=OLD.id;
DELETE FROM books_plugin_data WHERE book=OLD.id;
DELETE FROM identifiers WHERE book=OLD.id;
END;
DROP TRIGGER IF EXISTS fkc_lrp_insert;
DROP TRIGGER IF EXISTS fkc_lrp_update;
CREATE TRIGGER fkc_lrp_insert
BEFORE INSERT ON last_read_positions
BEGIN
SELECT CASE
WHEN (SELECT id from books WHERE id=NEW.book) IS NULL
THEN RAISE(ABORT, 'Foreign key violation: book not in books')
END;
END;
CREATE TRIGGER fkc_lrp_update
BEFORE UPDATE OF book ON last_read_positions
BEGIN
SELECT CASE
WHEN (SELECT id from books WHERE id=NEW.book) IS NULL
THEN RAISE(ABORT, 'Foreign key violation: book not in books')
END;
END;
''')
def upgrade_version_23(self):
''' Create the annotations table '''
self.db.execute('''
DROP TABLE IF EXISTS annotations_dirtied;
CREATE TABLE annotations_dirtied(id INTEGER PRIMARY KEY,
book INTEGER NOT NULL,
UNIQUE(book));
DROP TABLE IF EXISTS annotations;
CREATE TABLE annotations ( id INTEGER PRIMARY KEY,
book INTEGER NOT NULL,
format TEXT NOT NULL COLLATE NOCASE,
user_type TEXT NOT NULL,
user TEXT NOT NULL,
timestamp REAL NOT NULL,
annot_id TEXT NOT NULL,
annot_type TEXT NOT NULL,
annot_data TEXT NOT NULL,
searchable_text TEXT NOT NULL DEFAULT "",
UNIQUE(book, user_type, user, format, annot_type, annot_id)
);
DROP INDEX IF EXISTS annot_idx;
CREATE INDEX annot_idx ON annotations (book);
DROP TABLE IF EXISTS annotations_fts;
DROP TABLE IF EXISTS annotations_fts_stemmed;
CREATE VIRTUAL TABLE annotations_fts USING fts5(searchable_text,
content = 'annotations', content_rowid = 'id', tokenize = 'unicode61 remove_diacritics 2');
CREATE VIRTUAL TABLE annotations_fts_stemmed USING fts5(searchable_text,
content = 'annotations', content_rowid = 'id', tokenize = 'porter unicode61 remove_diacritics 2');
DROP TRIGGER IF EXISTS annotations_fts_insert_trg;
CREATE TRIGGER annotations_fts_insert_trg AFTER INSERT ON annotations
BEGIN
INSERT INTO annotations_fts(rowid, searchable_text) VALUES (NEW.id, NEW.searchable_text);
INSERT INTO annotations_fts_stemmed(rowid, searchable_text) VALUES (NEW.id, NEW.searchable_text);
END;
DROP TRIGGER IF EXISTS annotations_fts_delete_trg;
CREATE TRIGGER annotations_fts_delete_trg AFTER DELETE ON annotations
BEGIN
INSERT INTO annotations_fts(annotations_fts, rowid, searchable_text) VALUES('delete', OLD.id, OLD.searchable_text);
INSERT INTO annotations_fts_stemmed(annotations_fts_stemmed, rowid, searchable_text) VALUES('delete', OLD.id, OLD.searchable_text);
END;
DROP TRIGGER IF EXISTS annotations_fts_update_trg;
CREATE TRIGGER annotations_fts_update_trg AFTER UPDATE ON annotations
BEGIN
INSERT INTO annotations_fts(annotations_fts, rowid, searchable_text) VALUES('delete', OLD.id, OLD.searchable_text);
INSERT INTO annotations_fts(rowid, searchable_text) VALUES (NEW.id, NEW.searchable_text);
INSERT INTO annotations_fts_stemmed(annotations_fts_stemmed, rowid, searchable_text) VALUES('delete', OLD.id, OLD.searchable_text);
INSERT INTO annotations_fts_stemmed(rowid, searchable_text) VALUES (NEW.id, NEW.searchable_text);
END;
DROP TRIGGER IF EXISTS books_delete_trg;
CREATE TRIGGER books_delete_trg
AFTER DELETE ON books
BEGIN
DELETE FROM books_authors_link WHERE book=OLD.id;
DELETE FROM books_publishers_link WHERE book=OLD.id;
DELETE FROM books_ratings_link WHERE book=OLD.id;
DELETE FROM books_series_link WHERE book=OLD.id;
DELETE FROM books_tags_link WHERE book=OLD.id;
DELETE FROM books_languages_link WHERE book=OLD.id;
DELETE FROM data WHERE book=OLD.id;
DELETE FROM last_read_positions WHERE book=OLD.id;
DELETE FROM annotations WHERE book=OLD.id;
DELETE FROM comments WHERE book=OLD.id;
DELETE FROM conversion_options WHERE book=OLD.id;
DELETE FROM books_plugin_data WHERE book=OLD.id;
DELETE FROM identifiers WHERE book=OLD.id;
END;
DROP TRIGGER IF EXISTS fkc_annot_insert;
DROP TRIGGER IF EXISTS fkc_annot_update;
CREATE TRIGGER fkc_annot_insert
BEFORE INSERT ON annotations
BEGIN
SELECT CASE
WHEN (SELECT id from books WHERE id=NEW.book) IS NULL
THEN RAISE(ABORT, 'Foreign key violation: book not in books')
END;
END;
CREATE TRIGGER fkc_annot_update
BEFORE UPDATE OF book ON annotations
BEGIN
SELECT CASE
WHEN (SELECT id from books WHERE id=NEW.book) IS NULL
THEN RAISE(ABORT, 'Foreign key violation: book not in books')
END;
END;
''')
def upgrade_version_24(self):
self.db.reindex_annotations()
def upgrade_version_25(self):
alters = []
for record in self.db.execute(
'SELECT label,name,datatype,editable,display,normalized,id,is_multiple FROM custom_columns'):
data = {
'label':record[0],
'name':record[1],
'datatype':record[2],
'editable':bool(record[3]),
'display':record[4],
'normalized':bool(record[5]),
'num':record[6],
'is_multiple':bool(record[7]),
}
if data['normalized']:
tn = 'custom_column_{}'.format(data['num'])
alters.append(f"ALTER TABLE {tn} ADD COLUMN link TEXT NOT NULL DEFAULT '';")
alters.append("ALTER TABLE publishers ADD COLUMN link TEXT NOT NULL DEFAULT '';")
alters.append("ALTER TABLE series ADD COLUMN link TEXT NOT NULL DEFAULT '';")
alters.append("ALTER TABLE tags ADD COLUMN link TEXT NOT NULL DEFAULT '';")
# These aren't necessary in that there is no UI to set links, but having them
# makes the code uniform
alters.append("ALTER TABLE languages ADD COLUMN link TEXT NOT NULL DEFAULT '';")
alters.append("ALTER TABLE ratings ADD COLUMN link TEXT NOT NULL DEFAULT '';")
self.db.execute('\n'.join(alters))
| 35,911 | Python | .py | 745 | 35.088591 | 147 | 0.583101 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,056 | locking.py | kovidgoyal_calibre/src/calibre/db/locking.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os
import sys
import traceback
from contextlib import contextmanager
from threading import Condition, Lock, current_thread
@contextmanager
def try_lock(lock):
got_lock = lock.acquire(blocking=False)
try:
yield got_lock
finally:
if got_lock:
lock.release()
class LockingError(RuntimeError):
is_locking_error = True
def __init__(self, msg, extra=None):
RuntimeError.__init__(self, msg)
self.locking_debug_msg = extra
class DowngradeLockError(LockingError):
pass
def create_locks():
'''
Return a pair of locks: (read_lock, write_lock)
The read_lock can be acquired by multiple threads simultaneously, it can
also be acquired multiple times by the same thread.
Only one thread can hold write_lock at a time, and only if there are no
current read_locks. While the write_lock is held no
other threads can acquire read locks. The write_lock can also be acquired
multiple times by the same thread.
Both read_lock and write_lock are meant to be used in with statements (they
operate on a single underlying lock.
WARNING: Be very careful to not try to acquire a read lock while the same
thread holds a write lock and vice versa. That is, a given thread should
always release *all* locks of type A before trying to acquire a lock of type
B. Bad things will happen if you violate this rule, the most benign of
which is the raising of a LockingError (I haven't been able to eliminate
the possibility of deadlocking in this scenario).
'''
l = SHLock()
wrapper = DebugRWLockWrapper if os.environ.get('CALIBRE_DEBUG_DB_LOCKING') == '1' else RWLockWrapper
return wrapper(l), wrapper(l, is_shared=False)
class SHLock: # {{{
'''
Shareable lock class. Used to implement the Multiple readers-single writer
paradigm. As best as I can tell, neither writer nor reader starvation
should be possible.
Based on code from: https://github.com/rfk/threading2
'''
def __init__(self):
self._lock = Lock()
# When a shared lock is held, is_shared will give the cumulative
# number of locks and _shared_owners maps each owning thread to
# the number of locks is holds.
self.is_shared = 0
self._shared_owners = {}
# When an exclusive lock is held, is_exclusive will give the number
# of locks held and _exclusive_owner will give the owning thread
self.is_exclusive = 0
self._exclusive_owner = None
# When someone is forced to wait for a lock, they add themselves
# to one of these queues along with a "waiter" condition that
# is used to wake them up.
self._shared_queue = []
self._exclusive_queue = []
# This is for recycling waiter objects.
self._free_waiters = []
def acquire(self, blocking=True, shared=False):
'''
Acquire the lock in shared or exclusive mode.
If blocking is False this method will return False if acquiring the
lock failed.
'''
with self._lock:
if shared:
return self._acquire_shared(blocking)
else:
return self._acquire_exclusive(blocking)
assert not (self.is_shared and self.is_exclusive)
def owns_lock(self):
me = current_thread()
with self._lock:
return self._exclusive_owner is me or me in self._shared_owners
def release(self):
''' Release the lock. '''
# This decrements the appropriate lock counters, and if the lock
# becomes free, it looks for a queued thread to hand it off to.
# By doing the handoff here we ensure fairness.
me = current_thread()
with self._lock:
if self.is_exclusive:
if self._exclusive_owner is not me:
raise LockingError("release() called on unheld lock")
self.is_exclusive -= 1
if not self.is_exclusive:
self._exclusive_owner = None
# If there are waiting shared locks, issue them
# all and them wake everyone up.
if self._shared_queue:
for (thread, waiter) in self._shared_queue:
self.is_shared += 1
self._shared_owners[thread] = 1
waiter.notify()
del self._shared_queue[:]
# Otherwise, if there are waiting exclusive locks,
# they get first dibbs on the lock.
elif self._exclusive_queue:
(thread, waiter) = self._exclusive_queue.pop(0)
self._exclusive_owner = thread
self.is_exclusive += 1
waiter.notify()
elif self.is_shared:
try:
self._shared_owners[me] -= 1
if self._shared_owners[me] == 0:
del self._shared_owners[me]
except KeyError:
raise LockingError("release() called on unheld lock")
self.is_shared -= 1
if not self.is_shared:
# If there are waiting exclusive locks,
# they get first dibbs on the lock.
if self._exclusive_queue:
(thread, waiter) = self._exclusive_queue.pop(0)
self._exclusive_owner = thread
self.is_exclusive += 1
waiter.notify()
else:
assert not self._shared_queue
else:
raise LockingError("release() called on unheld lock")
def _acquire_shared(self, blocking=True):
me = current_thread()
# Each case: acquiring a lock we already hold.
if self.is_shared and me in self._shared_owners:
self.is_shared += 1
self._shared_owners[me] += 1
return True
# If the lock is already spoken for by an exclusive, add us
# to the shared queue and it will give us the lock eventually.
if self.is_exclusive or self._exclusive_queue:
if self._exclusive_owner is me:
raise DowngradeLockError("can't downgrade SHLock object")
if not blocking:
return False
waiter = self._take_waiter()
try:
self._shared_queue.append((me, waiter))
waiter.wait()
assert not self.is_exclusive
finally:
self._return_waiter(waiter)
else:
self.is_shared += 1
self._shared_owners[me] = 1
return True
def _acquire_exclusive(self, blocking=True):
me = current_thread()
# Each case: acquiring a lock we already hold.
if self._exclusive_owner is me:
assert self.is_exclusive
self.is_exclusive += 1
return True
# Do not allow upgrade of lock
if self.is_shared and me in self._shared_owners:
raise LockingError("can't upgrade SHLock object")
# If the lock is already spoken for, add us to the exclusive queue.
# This will eventually give us the lock when it's our turn.
if self.is_shared or self.is_exclusive:
if not blocking:
return False
waiter = self._take_waiter()
try:
self._exclusive_queue.append((me, waiter))
waiter.wait()
finally:
self._return_waiter(waiter)
else:
self._exclusive_owner = me
self.is_exclusive += 1
return True
def _take_waiter(self):
try:
return self._free_waiters.pop()
except IndexError:
return Condition(self._lock)
def _return_waiter(self, waiter):
self._free_waiters.append(waiter)
# }}}
class RWLockWrapper:
def __init__(self, shlock, is_shared=True):
self._shlock = shlock
self._is_shared = is_shared
def acquire(self):
self._shlock.acquire(shared=self._is_shared)
def release(self, *args):
self._shlock.release()
__enter__ = acquire
__exit__ = release
def owns_lock(self):
return self._shlock.owns_lock()
class DebugRWLockWrapper(RWLockWrapper):
def __init__(self, *args, **kwargs):
RWLockWrapper.__init__(self, *args, **kwargs)
self.print_lock = Lock()
def acquire(self):
with self.print_lock:
print('#' * 120, file=sys.stderr)
print('acquire called: thread id:', current_thread(), 'shared:', self._is_shared, file=sys.stderr)
traceback.print_stack()
RWLockWrapper.acquire(self)
with self.print_lock:
print('acquire done: thread id:', current_thread(), file=sys.stderr)
print('_' * 120, file=sys.stderr)
def release(self, *args):
with self.print_lock:
print('*' * 120, file=sys.stderr)
print('release called: thread id:', current_thread(), 'shared:', self._is_shared, file=sys.stderr)
traceback.print_stack()
RWLockWrapper.release(self)
with self.print_lock:
print('release done: thread id:', current_thread(), 'is_shared:', self._shlock.is_shared, 'is_exclusive:', self._shlock.is_exclusive,
file=sys.stderr)
print('_' * 120, file=sys.stderr)
__enter__ = acquire
__exit__ = release
class SafeReadLock:
def __init__(self, read_lock):
self.read_lock = read_lock
self.acquired = False
def acquire(self):
try:
self.read_lock.acquire()
except DowngradeLockError:
pass
else:
self.acquired = True
return self
def release(self, *args):
if self.acquired:
self.read_lock.release()
self.acquired = False
__enter__ = acquire
__exit__ = release
| 10,370 | Python | .py | 247 | 31.157895 | 145 | 0.585765 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,057 | errors.py | kovidgoyal_calibre/src/calibre/db/errors.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
class NoSuchFormat(ValueError):
pass
class NoSuchBook(KeyError):
def __init__(self, book_id):
KeyError.__init__(self, f'No book with id: {book_id} in database')
self.book_id = book_id
| 359 | Python | .py | 10 | 31.8 | 74 | 0.663743 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,058 | restore.py | kovidgoyal_calibre/src/calibre/db/restore.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os
import re
import shutil
import sys
import time
import traceback
from contextlib import suppress
from operator import itemgetter
from threading import Thread
from calibre import force_unicode, isbytestring
from calibre.constants import filesystem_encoding, iswindows
from calibre.db.backend import DB, DBPrefs
from calibre.db.cache import Cache
from calibre.db.constants import METADATA_FILE_NAME, NOTES_DB_NAME, NOTES_DIR_NAME, TRASH_DIR_NAME
from calibre.ebooks.metadata.opf2 import OPF
from calibre.ptempfile import TemporaryDirectory
from calibre.utils.date import utcfromtimestamp
NON_EBOOK_EXTENSIONS = frozenset((
'jpg', 'jpeg', 'gif', 'png', 'bmp',
'opf', 'swp', 'swo'
))
def read_opf(dirpath, read_annotations=True):
opf = os.path.join(dirpath, METADATA_FILE_NAME)
parsed_opf = OPF(opf, basedir=dirpath)
mi = parsed_opf.to_book_metadata()
annotations = tuple(parsed_opf.read_annotations()) if read_annotations else ()
timestamp = os.path.getmtime(opf)
return mi, timestamp, annotations
def is_ebook_file(filename):
ext = os.path.splitext(filename)[1]
if not ext:
return False
ext = ext[1:].lower()
bad_ext_pat = re.compile(r'[^a-z0-9_]+')
if ext in NON_EBOOK_EXTENSIONS or bad_ext_pat.search(ext) is not None:
return False
return True
class Restorer(Cache):
def __init__(self, library_path, default_prefs=None, restore_all_prefs=False, progress_callback=lambda x, y:True):
backend = DB(
library_path, default_prefs=default_prefs, restore_all_prefs=restore_all_prefs, progress_callback=progress_callback
)
Cache.__init__(self, backend)
for x in ('update_path', 'mark_as_dirty'):
setattr(self, x, self.no_op)
setattr(self, '_' + x, self.no_op)
self.init()
def no_op(self, *args, **kwargs):
pass
class Restore(Thread):
def __init__(self, library_path, progress_callback=None):
super().__init__()
if isbytestring(library_path):
library_path = library_path.decode(filesystem_encoding)
self.src_library_path = os.path.abspath(library_path)
self.progress_callback = progress_callback
self.db_id_regexp = re.compile(r'^.* \((\d+)\)$')
if not callable(self.progress_callback):
self.progress_callback = lambda x, y: x
self.dirs = []
self.failed_dirs = []
self.books = []
self.conflicting_custom_cols = {}
self.failed_restores = []
self.mismatched_dirs = []
self.notes_errors = []
self.successes = 0
self.tb = None
self.link_maps = {}
@property
def errors_occurred(self):
return (self.failed_dirs or self.mismatched_dirs or
self.conflicting_custom_cols or self.failed_restores or self.notes_errors)
@property
def report(self):
ans = ''
failures = list(self.failed_dirs) + [(x['dirpath'], tb) for x, tb in
self.failed_restores]
if failures:
ans += 'Failed to restore the books in the following folders:\n'
for dirpath, tb in failures:
ans += '\t' + force_unicode(dirpath, filesystem_encoding) + ' with error:\n'
ans += '\n'.join('\t\t'+force_unicode(x, filesystem_encoding) for x in tb.splitlines())
ans += '\n\n'
if self.conflicting_custom_cols:
ans += '\n\n'
ans += 'The following custom columns have conflicting definitions ' \
'and were not fully restored:\n'
for x in self.conflicting_custom_cols:
ans += '\t#'+x+'\n'
ans += '\tused:\t%s, %s, %s, %s\n'%(self.custom_columns[x][1],
self.custom_columns[x][2],
self.custom_columns[x][3],
self.custom_columns[x][5])
for coldef in self.conflicting_custom_cols[x]:
ans += '\tother:\t%s, %s, %s, %s\n'%(coldef[1], coldef[2],
coldef[3], coldef[5])
if self.mismatched_dirs:
ans += '\n\n'
ans += 'The following folders were ignored:\n'
for x in self.mismatched_dirs:
ans += '\t' + force_unicode(x, filesystem_encoding) + '\n'
if self.notes_errors:
ans += '\n\n'
ans += 'Failed to restore notes for the following items:\n'
for x in self.notes_errors:
ans += '\t' + x
return ans
def run(self):
try:
basedir = os.path.dirname(self.src_library_path)
try:
tdir = TemporaryDirectory('_rlib', dir=basedir)
tdir.__enter__()
except OSError:
# In case we dont have permissions to create directories in the
# parent folder of the src library
tdir = TemporaryDirectory('_rlib')
with tdir as tdir:
self.library_path = tdir
self.scan_library()
if not self.load_preferences():
# Something went wrong with preferences restore. Start over
# with a new database and attempt to rebuild the structure
# from the metadata in the opf
dbpath = os.path.join(self.library_path, 'metadata.db')
if os.path.exists(dbpath):
os.remove(dbpath)
self.create_cc_metadata()
self.restore_books()
if self.successes == 0 and len(self.dirs) > 0:
raise Exception('Something bad happened')
self.replace_db()
except:
self.tb = traceback.format_exc()
if self.failed_dirs:
for x in self.failed_dirs:
for (dirpath, tb) in self.failed_dirs:
self.tb += f'\n\n-------------\nFailed to restore: {dirpath}\n{tb}'
if self.failed_restores:
for (book, tb) in self.failed_restores:
self.tb += f'\n\n-------------\nFailed to restore: {book["path"]}\n{tb}'
def load_preferences(self):
self.progress_callback(None, 1)
self.progress_callback(_('Starting restoring preferences and column metadata'), 0)
prefs_path = os.path.join(self.src_library_path, 'metadata_db_prefs_backup.json')
if not os.path.exists(prefs_path):
self.progress_callback(_('Cannot restore preferences. Backup file not found.'), 1)
return False
try:
prefs = DBPrefs.read_serialized(self.src_library_path, recreate_prefs=False)
db = Restorer(self.library_path, default_prefs=prefs,
restore_all_prefs=True,
progress_callback=self.progress_callback)
db.close()
self.progress_callback(None, 1)
if 'field_metadata' in prefs:
self.progress_callback(_('Finished restoring preferences and column metadata'), 1)
return True
self.progress_callback(_('Finished restoring preferences'), 1)
return False
except:
traceback.print_exc()
self.progress_callback(None, 1)
self.progress_callback(_('Restoring preferences and column metadata failed'), 0)
return False
def scan_library(self):
for dirpath, dirnames, filenames in os.walk(self.src_library_path):
with suppress(ValueError):
dirnames.remove(TRASH_DIR_NAME)
leaf = os.path.basename(dirpath)
m = self.db_id_regexp.search(leaf)
if m is None or METADATA_FILE_NAME not in filenames:
continue
self.dirs.append((dirpath, list(dirnames), filenames, m.group(1)))
del dirnames[:]
self.progress_callback(None, len(self.dirs))
for i, (dirpath, dirnames, filenames, book_id) in enumerate(self.dirs):
try:
self.process_dir(dirpath, dirnames, filenames, book_id)
except Exception:
self.failed_dirs.append((dirpath, traceback.format_exc()))
traceback.print_exc()
self.progress_callback(_('Processed') + ' ' + dirpath, i+1)
def process_dir(self, dirpath, dirnames, filenames, book_id):
book_id = int(book_id)
def safe_mtime(path):
with suppress(OSError):
return os.path.getmtime(path)
return sys.maxsize
filenames.sort(key=lambda f: safe_mtime(os.path.join(dirpath, f)))
fmt_map = {}
fmts, formats, sizes, names = [], [], [], []
for x in filenames:
if is_ebook_file(x):
fmt = os.path.splitext(x)[1][1:].upper()
if fmt and fmt_map.setdefault(fmt, x) is x:
formats.append(x)
sizes.append(os.path.getsize(os.path.join(dirpath, x)))
names.append(os.path.splitext(x)[0])
fmts.append(fmt)
mi, timestamp, annotations = read_opf(dirpath)
path = os.path.relpath(dirpath, self.src_library_path).replace(os.sep, '/')
if int(mi.application_id) == book_id:
self.books.append({
'mi': mi,
'timestamp': timestamp,
'formats': list(zip(fmts, sizes, names)),
'id': book_id,
'dirpath': dirpath,
'path': path,
'annotations': annotations
})
else:
self.mismatched_dirs.append(dirpath)
alm = mi.get('link_maps', {})
for field, lmap in alm.items():
dest = self.link_maps.setdefault(field, {})
for item, link in lmap.items():
existing_link, timestamp = dest.get(item, (None, None))
if existing_link is None or existing_link != link and timestamp < mi.timestamp:
dest[item] = link, mi.timestamp
def create_cc_metadata(self):
self.books.sort(key=itemgetter('timestamp'))
self.custom_columns = {}
fields = ('label', 'name', 'datatype', 'is_multiple', 'is_editable',
'display')
for b in self.books:
for key in b['mi'].custom_field_keys():
cfm = b['mi'].metadata_for_field(key)
args = []
for x in fields:
if x in cfm:
if x == 'is_multiple':
args.append(bool(cfm[x]))
else:
args.append(cfm[x])
if len(args) == len(fields):
# TODO: Do series type columns need special handling?
label = cfm['label']
if label in self.custom_columns and args != self.custom_columns[label]:
if label not in self.conflicting_custom_cols:
self.conflicting_custom_cols[label] = []
if self.custom_columns[label] not in self.conflicting_custom_cols[label]:
self.conflicting_custom_cols[label].append(self.custom_columns[label])
self.custom_columns[label] = args
db = Restorer(self.library_path)
self.progress_callback(None, len(self.custom_columns))
if len(self.custom_columns):
for i, args in enumerate(self.custom_columns.values()):
db.create_custom_column(*args)
self.progress_callback(_('Creating custom column ')+args[0], i+1)
db.close()
def restore_books(self):
self.progress_callback(None, len(self.books))
self.books.sort(key=itemgetter('id'))
notes_dest = os.path.join(self.library_path, NOTES_DIR_NAME)
if os.path.exists(notes_dest): # created by load_preferences()
shutil.rmtree(notes_dest)
shutil.copytree(os.path.join(self.src_library_path, NOTES_DIR_NAME), notes_dest)
with suppress(FileNotFoundError):
os.remove(os.path.join(notes_dest, NOTES_DB_NAME))
db = Restorer(self.library_path)
for i, book in enumerate(self.books):
try:
db.restore_book(book['id'], book['mi'], utcfromtimestamp(book['timestamp']), book['path'], book['formats'], book['annotations'])
self.successes += 1
except:
self.failed_restores.append((book, traceback.format_exc()))
traceback.print_exc()
self.progress_callback(book['mi'].title, i+1)
for field, lmap in self.link_maps.items():
with suppress(Exception):
db.set_link_map(field, {k:v[0] for k, v in lmap.items()})
self.notes_errors = db.backend.restore_notes(self.progress_callback)
db.close()
def replace_db(self):
dbpath = os.path.join(self.src_library_path, 'metadata.db')
ndbpath = os.path.join(self.library_path, 'metadata.db')
sleep_time = 30 if iswindows else 0
save_path = self.olddb = os.path.splitext(dbpath)[0]+'_pre_restore.db'
if os.path.exists(save_path):
os.remove(save_path)
if os.path.exists(dbpath):
try:
os.replace(dbpath, save_path)
except OSError:
if iswindows:
time.sleep(sleep_time) # Wait a little for dropbox or the antivirus or whatever to release the file
shutil.copyfile(dbpath, save_path)
os.remove(dbpath)
shutil.copyfile(ndbpath, dbpath)
old_notes_path = os.path.join(self.src_library_path, NOTES_DIR_NAME)
new_notes_path = os.path.join(self.library_path, NOTES_DIR_NAME)
temp = old_notes_path + '-staging'
with suppress(OSError):
shutil.rmtree(temp)
try:
shutil.move(new_notes_path, temp)
except OSError:
if not iswindows:
raise
time.sleep(sleep_time) # Wait a little for dropbox or the antivirus or whatever to release the file
shutil.move(new_notes_path, temp)
try:
shutil.rmtree(old_notes_path)
except OSError:
if not iswindows:
raise
time.sleep(sleep_time) # Wait a little for dropbox or the antivirus or whatever to release the file
shutil.rmtree(old_notes_path)
try:
shutil.move(temp, old_notes_path)
except OSError:
if not iswindows:
raise
time.sleep(sleep_time) # Wait a little for dropbox or the antivirus or whatever to release the file
shutil.move(temp, old_notes_path)
| 15,188 | Python | .py | 322 | 34.506211 | 144 | 0.566775 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,059 | tables.py | kovidgoyal_calibre/src/calibre/db/tables.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import numbers
from collections import defaultdict
from datetime import datetime, timedelta
from typing import Iterable
from calibre.ebooks.metadata import author_to_author_sort
from calibre.utils.date import UNDEFINED_DATE, parse_date, utc_tz
from calibre.utils.icu import lower as icu_lower
from calibre_extensions.speedup import parse_date as _c_speedup
from polyglot.builtins import iteritems, itervalues
def identity(x):
return x
def c_parse(val):
try:
year, month, day, hour, minutes, seconds, tzsecs = _c_speedup(val)
except (AttributeError, TypeError):
# If a value like 2001 is stored in the column, apsw will return it as
# an int
if isinstance(val, numbers.Number):
return datetime(int(val), 1, 3, tzinfo=utc_tz)
if val is None:
return UNDEFINED_DATE
except:
pass
else:
try:
ans = datetime(year, month, day, hour, minutes, seconds, tzinfo=utc_tz)
if tzsecs != 0:
ans -= timedelta(seconds=tzsecs)
except OverflowError:
ans = UNDEFINED_DATE
return ans
try:
return parse_date(val, as_utc=True, assume_utc=True)
except (ValueError, TypeError):
return UNDEFINED_DATE
ONE_ONE, MANY_ONE, MANY_MANY = range(3)
null = object()
class Table:
supports_notes = False
def __init__(self, name, metadata, link_table=None):
self.name, self.metadata = name, metadata
self.sort_alpha = metadata.get('is_multiple', False) and metadata.get('display', {}).get('sort_alpha', False)
dt = metadata['datatype']
# self.unserialize() maps values from the db to python objects
self.unserialize = {
'datetime': c_parse,
'bool': bool
}.get(dt)
self.serialize = None
if name == 'authors':
# Legacy
self.unserialize = lambda x: x.replace('|', ',') if x else ''
self.serialize = lambda x: x.replace(',', '|')
self.link_table = (link_table if link_table else
'books_%s_link'%self.metadata['table'])
if self.supports_notes and dt == 'rating': # custom ratings table
self.supports_notes = False
def remove_books(self, book_ids, db):
return set()
def fix_link_table(self, db):
pass
def fix_case_duplicates(self, db):
''' If this table contains entries that differ only by case, then merge
those entries. This can happen in databases created with old versions
of calibre and non-ascii values, since sqlite's NOCASE only works with
ascii text. '''
pass
class VirtualTable(Table):
'''
A dummy table used for fields that only exist in memory like ondevice
'''
def __init__(self, name, table_type=ONE_ONE, datatype='text'):
metadata = {'datatype':datatype, 'table':name}
self.table_type = table_type
Table.__init__(self, name, metadata)
class OneToOneTable(Table):
'''
Represents data that is unique per book (it may not actually be unique) but
each item is assigned to a book in a one-to-one mapping. For example: uuid,
timestamp, size, etc.
'''
table_type = ONE_ONE
def read(self, db):
idcol = 'id' if self.metadata['table'] == 'books' else 'book'
query = db.execute('SELECT {}, {} FROM {}'.format(idcol,
self.metadata['column'], self.metadata['table']))
if self.unserialize is None:
try:
self.book_col_map = dict(query)
except UnicodeDecodeError:
# The db is damaged, try to work around it by ignoring
# failures to decode utf-8
query = db.execute('SELECT {}, cast({} as blob) FROM {}'.format(idcol,
self.metadata['column'], self.metadata['table']))
self.book_col_map = {k:bytes(val).decode('utf-8', 'replace') for k, val in query}
else:
us = self.unserialize
self.book_col_map = {book_id:us(val) for book_id, val in query}
def remove_books(self, book_ids, db):
clean = set()
for book_id in book_ids:
val = self.book_col_map.pop(book_id, null)
if val is not null:
clean.add(val)
return clean
class PathTable(OneToOneTable):
def set_path(self, book_id, path, db):
self.book_col_map[book_id] = path
db.execute('UPDATE books SET path=? WHERE id=?',
(path, book_id))
class SizeTable(OneToOneTable):
def read(self, db):
query = db.execute(
'SELECT books.id, (SELECT MAX(uncompressed_size) FROM data '
'WHERE data.book=books.id) FROM books')
self.book_col_map = dict(query)
def update_sizes(self, size_map):
self.book_col_map.update(size_map)
class UUIDTable(OneToOneTable):
def read(self, db):
OneToOneTable.read(self, db)
self.uuid_to_id_map = {v:k for k, v in iteritems(self.book_col_map)}
def update_uuid_cache(self, book_id_val_map):
for book_id, uuid in iteritems(book_id_val_map):
self.uuid_to_id_map.pop(self.book_col_map.get(book_id, None), None) # discard old uuid
self.uuid_to_id_map[uuid] = book_id
def remove_books(self, book_ids, db):
clean = set()
for book_id in book_ids:
val = self.book_col_map.pop(book_id, null)
if val is not null:
self.uuid_to_id_map.pop(val, None)
clean.add(val)
return clean
def lookup_by_uuid(self, uuid):
return self.uuid_to_id_map.get(uuid, None)
class CompositeTable(OneToOneTable):
def read(self, db):
self.book_col_map = {}
d = self.metadata['display']
self.composite_template = ['composite_template']
self.contains_html = d.get('contains_html', False)
self.make_category = d.get('make_category', False)
self.composite_sort = d.get('composite_sort', False)
self.use_decorations = d.get('use_decorations', False)
def remove_books(self, book_ids, db):
return set()
class ManyToOneTable(Table):
'''
Represents data where one data item can map to many books, for example:
series or publisher.
Each book however has only one value for data of this type.
'''
table_type = MANY_ONE
supports_notes = True
def read(self, db):
self.id_map = {}
self.link_map = {}
self.col_book_map = defaultdict(set)
self.book_col_map = {}
self.read_id_maps(db)
self.read_maps(db)
def read_id_maps(self, db):
query = db.execute('SELECT id, {}, link FROM {}'.format(
self.metadata['column'], self.metadata['table']))
us = identity if self.unserialize is None else self.unserialize
for id_, val, link in query:
self.id_map[id_] = us(val)
self.link_map[id_] = link
def read_maps(self, db):
cbm = self.col_book_map
bcm = self.book_col_map
for book, item_id in db.execute(
'SELECT book, {} FROM {}'.format(
self.metadata['link_column'], self.link_table)):
cbm[item_id].add(book)
bcm[book] = item_id
def fix_link_table(self, db):
linked_item_ids = {item_id for item_id in itervalues(self.book_col_map)}
extra_item_ids = linked_item_ids - set(self.id_map)
if extra_item_ids:
for item_id in extra_item_ids:
book_ids = self.col_book_map.pop(item_id, ())
for book_id in book_ids:
self.book_col_map.pop(book_id, None)
db.executemany('DELETE FROM {} WHERE {}=?'.format(
self.link_table, self.metadata['link_column']), tuple((x,) for x in extra_item_ids))
def fix_case_duplicates(self, db):
case_map = defaultdict(set)
for item_id, val in iteritems(self.id_map):
case_map[icu_lower(val)].add(item_id)
for v in itervalues(case_map):
if len(v) > 1:
main_id = min(v)
v.discard(main_id)
item_map = {}
for item_id in v:
val = self.id_map.pop(item_id, null)
if val is not null:
item_map[item_id] = val
books = self.col_book_map.pop(item_id, set())
for book_id in books:
self.book_col_map[book_id] = main_id
db.executemany('UPDATE {0} SET {1}=? WHERE {1}=?'.format(
self.link_table, self.metadata['link_column']),
tuple((main_id, x) for x in v))
db.delete_category_items(self.name, self.metadata['table'], item_map)
def item_ids_for_names(self, db, item_names: Iterable[str], case_sensitive: bool = False) -> dict[str, int]:
item_names = tuple(item_names)
if case_sensitive:
colname = self.metadata['column']
serialized_names = tuple(map(self.serialize, item_names)) if self.serialize else item_names
if len(item_names) == 1:
iid = db.get(f'SELECT id FROM {self.metadata["table"]} WHERE {colname} = ?', ((serialized_names[0],)), all=False)
return {item_names[0]: iid}
inq = ('?,' * len(item_names))[:-1]
ans = dict.fromkeys(item_names)
res = db.get(f'SELECT {colname}, id FROM {self.metadata["table"]} WHERE {colname} IN ({inq})', serialized_names)
if self.unserialize:
res = ((self.unserialize(name), iid) for name, iid in res)
ans.update(res)
return ans
if len(item_names) == 1:
q = icu_lower(item_names[0])
for iid, name in self.id_map.items():
if icu_lower(name) == q:
return {item_names[0]: iid}
return {item_names[0]: None}
rmap = {icu_lower(v) if isinstance(v, str) else v:k for k, v in self.id_map.items()}
return {name: rmap.get(icu_lower(name) if isinstance(name, str) else name, None) for name in item_names}
def remove_books(self, book_ids, db):
clean = set()
for book_id in book_ids:
item_id = self.book_col_map.pop(book_id, None)
if item_id is not None:
try:
self.col_book_map[item_id].discard(book_id)
except KeyError:
if self.id_map.pop(item_id, null) is not null:
clean.add(item_id)
else:
if not self.col_book_map[item_id]:
del self.col_book_map[item_id]
if self.id_map.pop(item_id, null) is not null:
clean.add(item_id)
if clean:
db.executemany(
'DELETE FROM {} WHERE id=?'.format(self.metadata['table']),
[(x,) for x in clean])
return clean
def remove_items(self, item_ids, db, restrict_to_book_ids=None):
affected_books = set()
if restrict_to_book_ids is not None:
items_to_process_normally = set()
# Check if all the books with the item are in the restriction. If
# so, process them normally
for item_id in item_ids:
books_to_process = self.col_book_map.get(item_id, set())
books_not_to_delete = books_to_process - restrict_to_book_ids
if books_not_to_delete:
# Some books not in restriction. Must do special processing
books_to_delete = books_to_process & restrict_to_book_ids
# remove the books from the old id maps
self.col_book_map[item_id] = books_not_to_delete
for book_id in books_to_delete:
self.book_col_map.pop(book_id, None)
if books_to_delete:
# Delete links to the affected books from the link table. As
# this is a many-to-one mapping we know that we can delete
# links without checking the item ID
db.executemany(
f'DELETE FROM {self.link_table} WHERE book=?', tuple((x,) for x in books_to_delete))
affected_books |= books_to_delete
else:
# Process normally any items where the VL was not significant
items_to_process_normally.add(item_id)
if items_to_process_normally:
affected_books |= self.remove_items(items_to_process_normally, db)
return affected_books
item_map = {}
for item_id in item_ids:
val = self.id_map.pop(item_id, null)
if val is null:
continue
item_map[item_id] = val
book_ids = self.col_book_map.pop(item_id, set())
for book_id in book_ids:
self.book_col_map.pop(book_id, None)
affected_books.update(book_ids)
db.delete_category_items(self.name, self.metadata['table'], item_map, self.link_table, self.metadata['link_column'])
return affected_books
def rename_item(self, item_id, new_name, db):
existing_item = None
q = icu_lower(new_name)
for q_id, q_val in self.id_map.items():
if icu_lower(q_val) == q:
existing_item = q_id
break
table, col, lcol = self.metadata['table'], self.metadata['column'], self.metadata['link_column']
affected_books = self.col_book_map.get(item_id, set())
new_id = item_id
if existing_item is None or existing_item == item_id:
# A simple rename will do the trick
self.id_map[item_id] = new_name
db.execute(f'UPDATE {table} SET {col}=? WHERE id=?', (new_name, item_id))
else:
# We have to replace
new_id = existing_item
self.id_map.pop(item_id, None)
self.link_map.pop(item_id, None)
books = self.col_book_map.pop(item_id, set())
for book_id in books:
self.book_col_map[book_id] = existing_item
self.col_book_map[existing_item].update(books)
db.rename_category_item(self.name, table, self.link_table, lcol, item_id, existing_item, self.id_map[new_id])
return affected_books, new_id
def set_links(self, link_map, db):
link_map = {id_:(l or '').strip() for id_, l in link_map.items()}
link_map = {id_:l for id_, l in link_map.items() if l != self.link_map.get(id_)}
if link_map:
self.link_map.update(link_map)
db.executemany(f'UPDATE {self.metadata["table"]} SET link=? WHERE id=?',
tuple((v, k) for k, v in link_map.items()))
return link_map
class RatingTable(ManyToOneTable):
supports_notes = False
def read_id_maps(self, db):
ManyToOneTable.read_id_maps(self, db)
# Ensure there are no records with rating=0 in the table. These should
# be represented as rating:None instead.
bad_ids = {item_id for item_id, rating in iteritems(self.id_map) if rating == 0}
if bad_ids:
self.id_map = {item_id:rating for item_id, rating in iteritems(self.id_map) if rating != 0}
db.executemany('DELETE FROM {} WHERE {}=?'.format(self.link_table, self.metadata['link_column']),
tuple((x,) for x in bad_ids))
db.execute('DELETE FROM {} WHERE {}=0'.format(
self.metadata['table'], self.metadata['column']))
class ManyToManyTable(ManyToOneTable):
'''
Represents data that has a many-to-many mapping with books. i.e. each book
can have more than one value and each value can be mapped to more than one
book. For example: tags or authors.
'''
table_type = MANY_MANY
selectq = 'SELECT book, {0} FROM {1} ORDER BY id'
do_clean_on_remove = True
def read_maps(self, db):
bcm = defaultdict(list)
cbm = self.col_book_map
for book, item_id in db.execute(
self.selectq.format(self.metadata['link_column'], self.link_table)):
cbm[item_id].add(book)
bcm[book].append(item_id)
self.book_col_map = {k:tuple(v) for k, v in iteritems(bcm)}
def fix_link_table(self, db):
linked_item_ids = {item_id for item_ids in itervalues(self.book_col_map) for item_id in item_ids}
extra_item_ids = linked_item_ids - set(self.id_map)
if extra_item_ids:
for item_id in extra_item_ids:
book_ids = self.col_book_map.pop(item_id, ())
for book_id in book_ids:
self.book_col_map[book_id] = tuple(iid for iid in self.book_col_map.pop(book_id, ()) if iid not in extra_item_ids)
db.executemany('DELETE FROM {} WHERE {}=?'.format(
self.link_table, self.metadata['link_column']), tuple((x,) for x in extra_item_ids))
def remove_books(self, book_ids, db):
clean = {}
for book_id in book_ids:
item_ids = self.book_col_map.pop(book_id, ())
for item_id in item_ids:
try:
self.col_book_map[item_id].discard(book_id)
except KeyError:
if self.id_map.pop(item_id, null) is not null:
clean.add(item_id)
else:
if not self.col_book_map[item_id]:
del self.col_book_map[item_id]
val = self.id_map.pop(item_id, null)
if val is not null:
clean[item_id] = val
if clean and self.do_clean_on_remove:
db.delete_category_items(self.name, self.metadata['table'], clean)
return set(clean)
def remove_items(self, item_ids, db, restrict_to_book_ids=None):
affected_books = set()
if restrict_to_book_ids is not None:
items_to_process_normally = set()
# Check if all the books with the item are in the restriction. If
# so, process them normally
for item_id in item_ids:
books_to_process = self.col_book_map.get(item_id, set())
books_not_to_delete = books_to_process - restrict_to_book_ids
if books_not_to_delete:
# Some books not in restriction. Must do special processing
books_to_delete = books_to_process & restrict_to_book_ids
# remove the books from the old id maps
self.col_book_map[item_id] = books_not_to_delete
for book_id in books_to_delete:
self.book_col_map[book_id] = tuple(
x for x in self.book_col_map.get(book_id, ()) if x != item_id)
affected_books |= books_to_delete
else:
items_to_process_normally.add(item_id)
# Delete book/item pairs from the link table. We don't need to do
# anything with the main table because books with the old ID are
# still in the library.
db.executemany('DELETE FROM {} WHERE {}=? and {}=?'.format(
self.link_table, 'book', self.metadata['link_column']),
[(b, i) for b in affected_books for i in item_ids])
# Take care of any items where the VL was not significant
if items_to_process_normally:
affected_books |= self.remove_items(items_to_process_normally, db)
return affected_books
item_map = {}
for item_id in item_ids:
val = self.id_map.pop(item_id, null)
if val is null:
continue
item_map[item_id] = val
book_ids = self.col_book_map.pop(item_id, set())
for book_id in book_ids:
self.book_col_map[book_id] = tuple(x for x in self.book_col_map.get(book_id, ()) if x != item_id)
affected_books.update(book_ids)
db.delete_category_items(self.name, self.metadata['table'], item_map, self.link_table, self.metadata['link_column'])
return affected_books
def rename_item(self, item_id, new_name, db):
existing_item = None
q = icu_lower(new_name)
for q_id, q_val in self.id_map.items():
if icu_lower(q_val) == q:
existing_item = q_id
break
table, col, lcol = self.metadata['table'], self.metadata['column'], self.metadata['link_column']
affected_books = self.col_book_map.get(item_id, set())
new_id = item_id
if existing_item is None or existing_item == item_id:
# A simple rename will do the trick
self.id_map[item_id] = new_name
db.execute(f'UPDATE {table} SET {col}=? WHERE id=?', (new_name, item_id))
else:
# We have to replace
new_id = existing_item
self.id_map.pop(item_id, None)
self.link_map.pop(item_id, None)
books = self.col_book_map.pop(item_id, set())
# Replacing item_id with existing_item could cause the same id to
# appear twice in the book list. Handle that by removing existing
# item from the book list before replacing.
for book_id in books:
self.book_col_map[book_id] = tuple((existing_item if x == item_id else x) for x in self.book_col_map.get(book_id, ()) if x != existing_item)
self.col_book_map[existing_item].update(books)
db.executemany(f'DELETE FROM {self.link_table} WHERE book=? AND {lcol}=?', [
(book_id, existing_item) for book_id in books])
db.rename_category_item(self.name, table, self.link_table, lcol, item_id, existing_item, self.id_map[new_id])
return affected_books, new_id
def fix_case_duplicates(self, db):
from calibre.db.write import uniq
case_map = defaultdict(set)
for item_id, val in iteritems(self.id_map):
case_map[icu_lower(val)].add(item_id)
for v in itervalues(case_map):
if len(v) > 1:
done_books = set()
main_id = min(v)
v.discard(main_id)
item_map = {}
for item_id in v:
val = self.id_map.pop(item_id, null)
if val is not null:
item_map[item_id] = val
books = self.col_book_map.pop(item_id, set())
for book_id in books:
if book_id in done_books:
continue
done_books.add(book_id)
orig = self.book_col_map.get(book_id, ())
if not orig:
continue
vals = uniq(tuple(main_id if x in v else x for x in orig))
self.book_col_map[book_id] = vals
if len(orig) == len(vals):
# We have a simple replacement
db.executemany(
'UPDATE {0} SET {1}=? WHERE {1}=? AND book=?'.format(
self.link_table, self.metadata['link_column']),
tuple((main_id, x, book_id) for x in v))
else:
# duplicates
db.execute(f'DELETE FROM {self.link_table} WHERE book=?', (book_id,))
db.executemany(
'INSERT INTO {} (book,{}) VALUES (?,?)'.format(self.link_table, self.metadata['link_column']),
tuple((book_id, x) for x in vals))
db.delete_category_items(self.name, self.metadata['table'], item_map)
class AuthorsTable(ManyToManyTable):
def read_id_maps(self, db):
self.link_map = lm = {}
self.asort_map = sm = {}
self.id_map = im = {}
us = self.unserialize
for aid, name, sort, link in db.execute(
'SELECT id, name, sort, link FROM authors'):
name = us(name)
im[aid] = name
sm[aid] = (sort or author_to_author_sort(name))
lm[aid] = link
def set_sort_names(self, aus_map, db):
aus_map = {aid:(a or '').strip() for aid, a in iteritems(aus_map)}
aus_map = {aid:a for aid, a in iteritems(aus_map) if a != self.asort_map.get(aid, None)}
self.asort_map.update(aus_map)
db.executemany('UPDATE authors SET sort=? WHERE id=?',
[(v, k) for k, v in iteritems(aus_map)])
return aus_map
def set_links(self, link_map, db):
link_map = {aid:(l or '').strip() for aid, l in iteritems(link_map)}
link_map = {aid:l for aid, l in iteritems(link_map) if l != self.link_map.get(aid, None)}
self.link_map.update(link_map)
db.executemany('UPDATE authors SET link=? WHERE id=?',
[(v, k) for k, v in iteritems(link_map)])
return link_map
def remove_books(self, book_ids, db):
clean = ManyToManyTable.remove_books(self, book_ids, db)
for item_id in clean:
self.link_map.pop(item_id, None)
self.asort_map.pop(item_id, None)
return clean
def rename_item(self, item_id, new_name, db):
ret = ManyToManyTable.rename_item(self, item_id, new_name, db)
if item_id not in self.id_map:
self.asort_map.pop(item_id, None)
else:
# Was a simple rename, update the author sort value
self.set_sort_names({item_id:author_to_author_sort(new_name)}, db)
return ret
def remove_items(self, item_ids, db, restrict_to_book_ids=None):
raise NotImplementedError('Direct removal of authors is not allowed')
class FormatsTable(ManyToManyTable):
do_clean_on_remove = False
supports_notes = False
def read_id_maps(self, db):
pass
def fix_case_duplicates(self, db):
pass
def read_maps(self, db):
self.fname_map = fnm = defaultdict(dict)
self.size_map = sm = defaultdict(dict)
self.col_book_map = cbm = defaultdict(set)
bcm = defaultdict(list)
for book, fmt, name, sz in db.execute('SELECT book, format, name, uncompressed_size FROM data'):
if fmt is not None:
fmt = fmt.upper()
cbm[fmt].add(book)
bcm[book].append(fmt)
fnm[book][fmt] = name
sm[book][fmt] = sz
self.book_col_map = {k:tuple(sorted(v)) for k, v in iteritems(bcm)}
def remove_books(self, book_ids, db):
clean = ManyToManyTable.remove_books(self, book_ids, db)
for book_id in book_ids:
self.fname_map.pop(book_id, None)
self.size_map.pop(book_id, None)
return clean
def set_fname(self, book_id, fmt, fname, db):
self.fname_map[book_id][fmt] = fname
db.execute('UPDATE data SET name=? WHERE book=? AND format=?',
(fname, book_id, fmt))
def remove_formats(self, formats_map, db):
for book_id, fmts in iteritems(formats_map):
self.book_col_map[book_id] = [fmt for fmt in self.book_col_map.get(book_id, []) if fmt not in fmts]
for m in (self.fname_map, self.size_map):
m[book_id] = {k:v for k, v in iteritems(m[book_id]) if k not in fmts}
for fmt in fmts:
try:
self.col_book_map[fmt].discard(book_id)
except KeyError:
pass
db.executemany('DELETE FROM data WHERE book=? AND format=?',
[(book_id, fmt) for book_id, fmts in iteritems(formats_map) for fmt in fmts])
def zero_max(book_id):
try:
return max(itervalues(self.size_map[book_id]))
except ValueError:
return 0
return {book_id:zero_max(book_id) for book_id in formats_map}
def remove_items(self, item_ids, db):
raise NotImplementedError('Cannot delete a format directly')
def rename_item(self, item_id, new_name, db):
raise NotImplementedError('Cannot rename formats')
def update_fmt(self, book_id, fmt, fname, size, db):
fmts = list(self.book_col_map.get(book_id, []))
try:
fmts.remove(fmt)
except ValueError:
pass
fmts.append(fmt)
self.book_col_map[book_id] = tuple(fmts)
try:
self.col_book_map[fmt].add(book_id)
except KeyError:
self.col_book_map[fmt] = {book_id}
self.fname_map[book_id][fmt] = fname
self.size_map[book_id][fmt] = size
db.execute('INSERT OR REPLACE INTO data (book,format,uncompressed_size,name) VALUES (?,?,?,?)',
(book_id, fmt, size, fname))
return max(itervalues(self.size_map[book_id]))
class IdentifiersTable(ManyToManyTable):
supports_notes = False
def read_id_maps(self, db):
pass
def fix_case_duplicates(self, db):
pass
def read_maps(self, db):
self.book_col_map = defaultdict(dict)
self.col_book_map = defaultdict(set)
for book, typ, val in db.execute('SELECT book, type, val FROM identifiers'):
if typ is not None and val is not None:
self.col_book_map[typ].add(book)
self.book_col_map[book][typ] = val
def remove_books(self, book_ids, db):
clean = set()
for book_id in book_ids:
item_map = self.book_col_map.pop(book_id, {})
for item_id in item_map:
try:
self.col_book_map[item_id].discard(book_id)
except KeyError:
clean.add(item_id)
else:
if not self.col_book_map[item_id]:
del self.col_book_map[item_id]
clean.add(item_id)
return clean
def remove_items(self, item_ids, db):
raise NotImplementedError('Direct deletion of identifiers is not implemented')
def rename_item(self, item_id, new_name, db):
raise NotImplementedError('Cannot rename identifiers')
def all_identifier_types(self):
return frozenset(k for k, v in iteritems(self.col_book_map) if v)
| 30,941 | Python | .py | 641 | 35.976599 | 156 | 0.563728 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,060 | backup.py | kovidgoyal_calibre/src/calibre/db/backup.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import sys
import traceback
import weakref
from threading import Event, Thread
from calibre.ebooks.metadata.opf2 import metadata_to_opf
def prints(*a, **kw):
kw['file'] = sys.stderr
return print(*a, **kw)
class Abort(Exception):
pass
class MetadataBackup(Thread):
'''
Continuously backup changed metadata into OPF files
in the book directory. This class runs in its own
thread.
'''
def __init__(self, db, interval=2, scheduling_interval=0.1):
Thread.__init__(self)
self.daemon = True
self._db = weakref.ref(getattr(db, 'new_api', db))
self.stop_running = Event()
self.interval = interval
self.scheduling_interval = scheduling_interval
self.check_dirtied_annotations = 0
@property
def db(self):
ans = self._db()
if ans is None:
raise Abort()
return ans
def stop(self):
self.stop_running.set()
def wait(self, interval):
if self.stop_running.wait(interval):
raise Abort()
def run(self):
while not self.stop_running.is_set():
try:
self.wait(self.interval)
self.do_one()
except Abort:
break
def do_one(self):
self.check_dirtied_annotations += 1
if self.check_dirtied_annotations > 2:
self.check_dirtied_annotations = 0
try:
self.db.check_dirtied_annotations()
except Exception:
if self.stop_running.is_set() or self.db.is_closed:
return
traceback.print_exc()
try:
book_id = self.db.get_a_dirtied_book()
if book_id is None:
return
except Abort:
raise
except:
# Happens during interpreter shutdown
return
self.wait(0)
try:
mi, sequence = self.db.get_metadata_for_dump(book_id)
except:
prints('Failed to get backup metadata for id:', book_id, 'once')
traceback.print_exc()
self.wait(self.interval)
try:
mi, sequence = self.db.get_metadata_for_dump(book_id)
except:
prints('Failed to get backup metadata for id:', book_id, 'again, giving up')
traceback.print_exc()
return
if mi is None:
self.db.clear_dirtied(book_id, sequence)
return
# Give the GUI thread a chance to do something. Python threads don't
# have priorities, so this thread would naturally keep the processor
# until some scheduling event happens. The wait makes such an event
self.wait(self.scheduling_interval)
try:
raw = metadata_to_opf(mi)
except:
prints('Failed to convert to opf for id:', book_id)
traceback.print_exc()
self.db.clear_dirtied(book_id, sequence)
return
self.wait(self.scheduling_interval)
try:
self.db.write_backup(book_id, raw)
except:
prints('Failed to write backup metadata for id:', book_id, 'once')
traceback.print_exc()
self.wait(self.interval)
try:
self.db.write_backup(book_id, raw)
except:
prints('Failed to write backup metadata for id:', book_id, 'again, giving up')
traceback.print_exc()
return
self.db.clear_dirtied(book_id, sequence)
def break_cycles(self):
# Legacy compatibility
pass
| 3,817 | Python | .py | 109 | 24.899083 | 94 | 0.573873 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,061 | lazy.py | kovidgoyal_calibre/src/calibre/db/lazy.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import weakref
from collections.abc import MutableMapping, MutableSequence
from copy import deepcopy
from functools import wraps
from calibre.ebooks.metadata.book import STANDARD_METADATA_FIELDS
from calibre.ebooks.metadata.book.base import ALL_METADATA_FIELDS, NULL_VALUES, SIMPLE_GET, TOP_LEVEL_IDENTIFIERS, Metadata
from calibre.ebooks.metadata.book.formatter import SafeFormat
from calibre.utils.date import utcnow
from polyglot.builtins import native_string_type
# Lazy format metadata retrieval {{{
'''
Avoid doing stats on all files in a book when getting metadata for that book.
Speeds up calibre startup with large libraries/libraries on a network share,
with a composite custom column.
'''
def resolved(f):
@wraps(f)
def wrapper(self, *args, **kwargs):
if getattr(self, '_must_resolve', True):
self._resolve()
self._must_resolve = False
return f(self, *args, **kwargs)
return wrapper
class MutableBase:
@resolved
def __str__(self):
return native_string_type(self._values)
@resolved
def __repr__(self):
return repr(self._values)
@resolved
def __unicode__(self):
return str(self._values)
@resolved
def __len__(self):
return len(self._values)
@resolved
def __iter__(self):
return iter(self._values)
@resolved
def __contains__(self, key):
return key in self._values
@resolved
def __getitem__(self, fmt):
return self._values[fmt]
@resolved
def __setitem__(self, key, val):
self._values[key] = val
@resolved
def __delitem__(self, key):
del self._values[key]
class FormatMetadata(MutableBase, MutableMapping):
def __init__(self, db, id_, formats):
self._dbwref = weakref.ref(db)
self._id = id_
self._formats = formats
def _resolve(self):
db = self._dbwref()
self._values = {}
for f in self._formats:
try:
self._values[f] = db.format_metadata(self._id, f)
except:
pass
class FormatsList(MutableBase, MutableSequence):
def __init__(self, formats, format_metadata):
self._formats = formats
self._format_metadata = format_metadata
def _resolve(self):
self._values = [f for f in self._formats if f in self._format_metadata]
@resolved
def insert(self, idx, val):
self._values.insert(idx, val)
# }}}
# Lazy metadata getters {{{
ga = object.__getattribute__
sa = object.__setattr__
def simple_getter(field, default_value=None):
def func(dbref, book_id, cache):
try:
return cache[field]
except KeyError:
db = dbref()
cache[field] = ret = db.field_for(field, book_id, default_value=default_value)
return ret
return func
def pp_getter(field, postprocess, default_value=None):
def func(dbref, book_id, cache):
try:
return cache[field]
except KeyError:
db = dbref()
cache[field] = ret = postprocess(db.field_for(field, book_id, default_value=default_value))
return ret
return func
def adata_getter(field):
def func(dbref, book_id, cache):
try:
author_ids, adata = cache['adata']
except KeyError:
db = dbref()
with db.safe_read_lock:
author_ids = db._field_ids_for('authors', book_id)
adata = db._author_data(author_ids)
cache['adata'] = (author_ids, adata)
k = 'sort' if field == 'author_sort_map' else 'link'
return {adata[i]['name']:adata[i][k] for i in author_ids}
return func
def link_maps_getter(dbref, book_id, cache):
try:
ans = cache['link_maps']
except KeyError:
db = dbref()
ans = cache['link_maps'] = db.get_all_link_maps_for_book(book_id)
return ans
def dt_getter(field):
def func(dbref, book_id, cache):
try:
return cache[field]
except KeyError:
db = dbref()
cache[field] = ret = db.field_for(field, book_id, default_value=utcnow())
return ret
return func
def item_getter(field, default_value=None, key=0):
def func(dbref, book_id, cache):
try:
return cache[field]
except KeyError:
db = dbref()
ret = cache[field] = db.field_for(field, book_id, default_value=default_value)
try:
return ret[key]
except (IndexError, KeyError):
return default_value
return func
def fmt_getter(field):
def func(dbref, book_id, cache):
try:
format_metadata = cache['format_metadata']
except KeyError:
db = dbref()
format_metadata = {}
for fmt in db.formats(book_id, verify_formats=False):
m = db.format_metadata(book_id, fmt)
if m:
format_metadata[fmt] = m
if field == 'formats':
return sorted(format_metadata) or None
return format_metadata
return func
def approx_fmts_getter(dbref, book_id, cache):
try:
return cache['formats']
except KeyError:
db = dbref()
cache['formats'] = ret = list(db.field_for('formats', book_id))
return ret
def series_index_getter(field='series'):
def func(dbref, book_id, cache):
try:
series = getters[field](dbref, book_id, cache)
except KeyError:
series = custom_getter(field, dbref, book_id, cache)
if series:
try:
return cache[field + '_index']
except KeyError:
db = dbref()
cache[field + '_index'] = ret = db.field_for(field + '_index', book_id, default_value=1.0)
return ret
return func
def has_cover_getter(dbref, book_id, cache):
try:
return cache['has_cover']
except KeyError:
db = dbref()
cache['has_cover'] = ret = _('Yes') if db.field_for('cover', book_id, default_value=False) else ''
return ret
def fmt_custom(x):
return (list(x) if isinstance(x, tuple) else x)
def custom_getter(field, dbref, book_id, cache):
try:
return cache[field]
except KeyError:
db = dbref()
cache[field] = ret = fmt_custom(db.field_for(field, book_id))
return ret
def composite_getter(mi, field, dbref, book_id, cache, formatter, template_cache):
try:
return cache[field]
except KeyError:
cache[field] = 'RECURSIVE_COMPOSITE FIELD (Metadata) ' + field
try:
db = dbref()
with db.safe_read_lock:
try:
fo = db.fields[field]
except KeyError:
ret = cache[field] = _('Invalid field: %s') % field
else:
ret = cache[field] = fo._render_composite_with_cache(book_id, mi, formatter, template_cache)
except Exception:
import traceback
traceback.print_exc()
return 'ERROR WHILE EVALUATING: %s' % field
return ret
def virtual_libraries_getter(dbref, book_id, cache):
'''
This method is deprecated because it doesn't (and can't) return virtual
library names when the VL search references marked books. It is replaced
by db.view.get_virtual_libraries_for_books()
'''
try:
return cache['virtual_libraries']
except KeyError:
db = dbref()
vls = db.virtual_libraries_for_books((book_id,))[book_id]
ret = cache['virtual_libraries'] = ', '.join(vls)
return ret
def user_categories_getter(proxy_metadata):
cache = ga(proxy_metadata, '_cache')
try:
return cache['user_categories']
except KeyError:
db = ga(proxy_metadata, '_db')()
book_id = ga(proxy_metadata, '_book_id')
ret = cache['user_categories'] = db.user_categories_for_books((book_id,), {book_id:proxy_metadata})[book_id]
return ret
getters = {
'title':simple_getter('title', _('Unknown')),
'title_sort':simple_getter('sort', _('Unknown')),
'authors':pp_getter('authors', list, (_('Unknown'),)),
'author_sort':simple_getter('author_sort', _('Unknown')),
'uuid':simple_getter('uuid', 'dummy'),
'book_size':simple_getter('size', 0),
'ondevice_col':simple_getter('ondevice', ''),
'languages':pp_getter('languages', list),
'language':item_getter('languages', default_value=NULL_VALUES['language']),
'db_approx_formats': approx_fmts_getter,
'has_cover': has_cover_getter,
'tags':pp_getter('tags', list, (_('Unknown'),)),
'series_index':series_index_getter(),
'application_id':lambda x, book_id, y: book_id,
'id':lambda x, book_id, y: book_id,
'virtual_libraries':virtual_libraries_getter,
'link_maps': link_maps_getter,
}
for field in ('comments', 'publisher', 'identifiers', 'series', 'rating'):
getters[field] = simple_getter(field)
for field in ('author_sort_map',):
getters[field] = adata_getter(field)
for field in ('timestamp', 'pubdate', 'last_modified'):
getters[field] = dt_getter(field)
for field in TOP_LEVEL_IDENTIFIERS:
getters[field] = item_getter('identifiers', key=field)
for field in ('formats', 'format_metadata'):
getters[field] = fmt_getter(field)
# }}}
class ProxyMetadata(Metadata):
def __init__(self, db, book_id, formatter=None):
sa(self, 'template_cache', db.formatter_template_cache)
sa(self, 'formatter', SafeFormat() if formatter is None else formatter)
sa(self, '_db', weakref.ref(db))
sa(self, '_book_id', book_id)
sa(self, '_cache', {'cover_data':(None,None), 'device_collections':[]})
sa(self, '_user_metadata', db.field_metadata)
def __getattribute__(self, field):
getter = getters.get(field, None)
if getter is not None:
return getter(ga(self, '_db'), ga(self, '_book_id'), ga(self, '_cache'))
if field in SIMPLE_GET:
if field == 'user_categories':
return user_categories_getter(self)
return ga(self, '_cache').get(field, None)
try:
return ga(self, field)
except AttributeError:
pass
um = ga(self, '_user_metadata')
d = um.get(field, None)
if d is not None:
dt = d['datatype']
if dt != 'composite':
if field.endswith('_index') and dt == 'float':
return series_index_getter(field[:-6])(ga(self, '_db'), ga(self, '_book_id'), ga(self, '_cache'))
return custom_getter(field, ga(self, '_db'), ga(self, '_book_id'), ga(self, '_cache'))
return composite_getter(self, field, ga(self, '_db'), ga(self, '_book_id'), ga(self, '_cache'), ga(self, 'formatter'), ga(self, 'template_cache'))
try:
return ga(self, '_cache')[field]
except KeyError:
raise AttributeError('Metadata object has no attribute named: %r' % field)
def __setattr__(self, field, val, extra=None):
cache = ga(self, '_cache')
cache[field] = val
if extra is not None:
cache[field + '_index'] = val
# Replacements (overrides) for methods in the Metadata base class.
# ProxyMetadata cannot set attributes.
def _unimplemented_exception(self, method, add_txt):
raise NotImplementedError(f"{method}() cannot be used in this context. "
f"{'ProxyMetadata is read only' if add_txt else ''}")
# Metadata returns a seemingly arbitrary set of items. Rather than attempt
# compatibility, flag __iter__ as unimplemented. This won't break anything
# because the Metadata version raises AttributeError
def __iter__(self):
raise NotImplementedError("__iter__() cannot be used in this context. "
"Use the explicit methods such as all_field_keys()")
def has_key(self, key):
return key in STANDARD_METADATA_FIELDS or key in ga(self, '_user_metadata')
def deepcopy(self, **kwargs):
self._unimplemented_exception('deepcopy', add_txt=False)
def deepcopy_metadata(self):
return deepcopy(ga('_user_metadata'))
# def get(self, field, default=None)
def get_extra(self, field, default=None):
um = ga(self, '_user_metadata')
if field + '_index' in um:
try:
return getattr(self, field + '_index')
except AttributeError:
return default
raise AttributeError(
'Metadata object has no attribute named: '+ repr(field))
def set(self, *args, **kwargs):
self._unimplemented_exception('set', add_txt=True)
def get_identifiers(self):
res = self.get('identifiers')
return {} if res is None else res
def set_identifiers(self, *args):
self._unimplemented_exception('set_identifiers', add_txt=True)
def set_identifier(self, *args):
self._unimplemented_exception('set_identifier', add_txt=True)
def has_identifier(self, typ):
return typ in self.get('identifiers', {})
# def standard_field_keys(self)
def custom_field_keys(self):
um = ga(self, '_user_metadata')
return iter(um.custom_field_keys())
def all_field_keys(self):
um = ga(self, '_user_metadata')
return ALL_METADATA_FIELDS.union(frozenset(um.all_field_keys()))
def all_non_none_fields(self):
self._unimplemented_exception('all_non_none_fields', add_txt=False)
# This version can return custom column metadata while the Metadata version
# won't.
def get_standard_metadata(self, field, make_copy=False):
field_metadata = ga(self, '_user_metadata')
if field in field_metadata and field_metadata[field]['kind'] == 'field':
if make_copy:
return deepcopy(field_metadata[field])
return field_metadata[field]
return None
# def get_all_standard_metadata(self, make_copy)
def get_all_user_metadata(self, make_copy):
um = ga(self, '_user_metadata')
if make_copy:
res = {k: deepcopy(um[k]) for k in um.custom_field_keys()}
else:
res = {k: um[k] for k in um.custom_field_keys()}
return res
# The Metadata version of this method works only with custom field keys. It
# isn't clear how this method differs from get_standard_metadata other than
# it will return non-'field' metadata. Leave it in case someone depends on
# that.
def get_user_metadata(self, field, make_copy=False):
um = ga(self, '_user_metadata')
try:
ans = um[field]
except KeyError:
pass
else:
if make_copy:
ans = deepcopy(ans)
return ans
def set_all_user_metadata(self, *args):
self._unimplemented_exception('set_all_user_metadata', add_txt=True)
def set_user_metadata(self, *args):
self._unimplemented_exception('set_user_metadata', add_txt=True)
def remove_stale_user_metadata(self, *args):
self._unimplemented_exception('remove_stale_user_metadata', add_txt=True)
def template_to_attribute(self, *args):
self._unimplemented_exception('template_to_attribute', add_txt=True)
def smart_update(self, *args, **kwargs):
self._unimplemented_exception('smart_update', add_txt=True)
# The rest of the methods in Metadata can be used as is.
@property
def _proxy_metadata(self):
return self
| 15,882 | Python | .py | 393 | 32.117048 | 158 | 0.612035 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,062 | annotations.py | kovidgoyal_calibre/src/calibre/db/annotations.py | #!/usr/bin/env python
# License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from collections import defaultdict
from itertools import chain
from calibre.ebooks.epub.cfi.parse import cfi_sort_key
from polyglot.builtins import itervalues
no_cfi_sort_key = cfi_sort_key('/99999999')
def unicode_normalize(text):
if text:
from unicodedata import normalize
text = normalize('NFKC', text)
return text
def bookmark_sort_key(b):
if b.get('pos_type') == 'epubcfi':
return cfi_sort_key(b['pos'], only_path=False)
return no_cfi_sort_key
def highlight_sort_key(hl):
cfi = hl.get('start_cfi')
if cfi:
return cfi_sort_key(cfi, only_path=False)
return no_cfi_sort_key
def sort_annot_list_by_position_in_book(annots, annot_type):
annots.sort(key={'bookmark': bookmark_sort_key, 'highlight': highlight_sort_key}[annot_type])
def merge_annots_with_identical_field(a, b, field='title'):
title_groups = defaultdict(list)
for x in chain(a, b):
title_groups[x[field]].append(x)
for tg in itervalues(title_groups):
tg.sort(key=safe_timestamp_sort_key, reverse=True)
seen = set()
changed = False
ans = []
for x in chain(a, b):
title = x[field]
if title not in seen:
seen.add(title)
grp = title_groups[title]
if len(grp) > 1 and grp[0]['timestamp'] != grp[1]['timestamp']:
changed = True
ans.append(grp[0])
if len(ans) != len(a) or len(ans) != len(b):
changed = True
return changed, ans
merge_field_map = {'bookmark': 'title', 'highlight': 'uuid'}
def merge_annot_lists(a, b, annot_type):
if not a:
return list(b)
if not b:
return list(a)
if annot_type == 'last-read':
ans = a + b
ans.sort(key=safe_timestamp_sort_key, reverse=True)
return ans
merge_field = merge_field_map.get(annot_type)
if merge_field is None:
return a + b
changed, c = merge_annots_with_identical_field(a, b, merge_field)
if changed:
sort_annot_list_by_position_in_book(c, annot_type)
return c
def safe_timestamp_sort_key(x):
# ensure we return a string, so python 3 does not barf
# also if the timestamp is a datetime instance convert it to
# a string, since we expect it to always be a string
ans = x.get('timestamp')
if hasattr(ans, 'isoformat'):
ans = x['timestamp'] = ans.isoformat()
if not isinstance(ans, str):
try:
ans = str(ans)
except Exception:
ans = 'zzzz'
return ans
def merge_annotations(annots, annots_map, merge_last_read=True):
# If you make changes to this algorithm also update the
# implementation in read_book.annotations
if isinstance(annots, dict):
amap = annots
else:
amap = defaultdict(list)
for annot in annots:
amap[annot['type']].append(annot)
if merge_last_read:
lr = amap.get('last-read')
if lr:
existing = annots_map.get('last-read')
if existing:
lr = existing + lr
if lr:
lr.sort(key=safe_timestamp_sort_key, reverse=True)
annots_map['last-read'] = [lr[0]]
for annot_type, field in merge_field_map.items():
a = annots_map.get(annot_type)
b = amap.get(annot_type)
if not b:
continue
changed, annots_map[annot_type] = merge_annots_with_identical_field(a or [], b, field=field)
def annot_db_data(annot):
aid = text = None
atype = annot['type'].lower()
if atype == 'bookmark':
aid = text = annot['title']
elif atype == 'highlight':
aid = annot['uuid']
text = annot.get('highlighted_text') or ''
notes = annot.get('notes') or ''
if notes:
text += '\n\x1f\n' + notes
return aid, unicode_normalize(text)
| 3,963 | Python | .py | 109 | 29.220183 | 100 | 0.618699 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,063 | constants.py | kovidgoyal_calibre/src/calibre/db/constants.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2023, Kovid Goyal <kovid at kovidgoyal.net>
from dataclasses import dataclass
from typing import Sequence
COVER_FILE_NAME = 'cover.jpg'
METADATA_FILE_NAME = 'metadata.opf'
DEFAULT_TRASH_EXPIRY_TIME_SECONDS = 14 * 86400
TRASH_DIR_NAME = '.caltrash'
NOTES_DIR_NAME = '.calnotes'
NOTES_DB_NAME = 'notes.db'
DATA_DIR_NAME = 'data'
DATA_FILE_PATTERN = f'{DATA_DIR_NAME}/**/*'
BOOK_ID_PATH_TEMPLATE = ' ({})'
RESOURCE_URL_SCHEME = 'calres'
@dataclass
class TrashEntry:
book_id: int
title: str
author: str
cover_path: str
mtime: float
formats: Sequence[str] = ()
| 635 | Python | .py | 22 | 26.590909 | 71 | 0.720854 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,064 | covers.py | kovidgoyal_calibre/src/calibre/db/covers.py | #!/usr/bin/env python
# License: GPL v3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import os
from queue import Queue
from threading import Thread
from calibre import detect_ncpus
from calibre.utils.img import encode_jpeg, optimize_jpeg
def compress_worker(input_queue, output_queue, jpeg_quality):
while True:
task = input_queue.get()
if task is None:
break
book_id, path = task
try:
if jpeg_quality >= 100:
stderr = optimize_jpeg(path)
else:
stderr = encode_jpeg(path, jpeg_quality)
except Exception:
import traceback
stderr = traceback.format_exc()
if stderr:
output_queue.put((book_id, stderr))
else:
try:
sz = os.path.getsize(path)
except OSError as err:
sz = str(err)
output_queue.put((book_id, sz))
def compress_covers(path_map, jpeg_quality, progress_callback):
input_queue = Queue()
output_queue = Queue()
num_workers = detect_ncpus()
sz_map = {}
for book_id, (path, sz) in path_map.items():
input_queue.put((book_id, path))
sz_map[book_id] = sz
workers = [
Thread(target=compress_worker, args=(input_queue, output_queue, jpeg_quality), daemon=True, name=f'CCover-{i}')
for i in range(num_workers)
]
[w.start() for w in workers]
pending = set(path_map)
while pending:
book_id, new_sz = output_queue.get()
pending.remove(book_id)
progress_callback(book_id, sz_map[book_id], new_sz)
for w in workers:
input_queue.put(None)
for w in workers:
w.join()
| 1,726 | Python | .py | 51 | 25.823529 | 119 | 0.602157 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,065 | search.py | kovidgoyal_calibre/src/calibre/db/search.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import operator
import weakref
from collections import OrderedDict, deque
from datetime import timedelta
from functools import partial
import regex
from calibre.constants import DEBUG, preferred_encoding
from calibre.db.utils import force_to_bool
from calibre.utils.config_base import prefs
from calibre.utils.date import UNDEFINED_DATE, dt_as_local, now, parse_date
from calibre.utils.icu import lower as icu_lower
from calibre.utils.icu import primary_contains, primary_no_punc_contains, sort_key
from calibre.utils.localization import canonicalize_lang, lang_map
from calibre.utils.search_query_parser import ParseException, SearchQueryParser
from polyglot.builtins import iteritems, string_or_bytes
CONTAINS_MATCH = 0
EQUALS_MATCH = 1
REGEXP_MATCH = 2
ACCENT_MATCH = 3
# Utils {{{
def _matchkind(query, case_sensitive=False):
matchkind = CONTAINS_MATCH
if (len(query) > 1):
if query.startswith('\\'):
query = query[1:]
elif query.startswith('='):
matchkind = EQUALS_MATCH
query = query[1:]
elif query.startswith('~'):
matchkind = REGEXP_MATCH
query = query[1:]
elif query.startswith('^'):
matchkind = ACCENT_MATCH
query = query[1:]
if not case_sensitive and matchkind != REGEXP_MATCH:
# leave case in regexps because it can be significant e.g. \S \W \D
query = icu_lower(query)
return matchkind, query
def _match(query, value, matchkind, use_primary_find_in_search=True, case_sensitive=False):
if query.startswith('..'):
query = query[1:]
sq = query[1:]
internal_match_ok = True
else:
internal_match_ok = False
for t in value:
if not case_sensitive:
t = icu_lower(t)
if matchkind == EQUALS_MATCH:
if internal_match_ok:
if query == t:
return True
return sq in (c.strip() for c in t.split('.') if c.strip())
elif query[0] == '.':
if t.startswith(query[1:]):
ql = len(query) - 1
if len(t) == ql or t[ql:ql+1] == '.':
return True
elif query == t:
return True
elif matchkind == REGEXP_MATCH:
flags = regex.UNICODE | regex.VERSION1 | regex.FULLCASE | (0 if case_sensitive else regex.IGNORECASE)
try:
if regex.search(query, t, flags) is not None:
return True
except regex.error as e:
raise ParseException(_('Invalid regular expression: {!r} with error: {}').format(query, str(e)))
elif matchkind == ACCENT_MATCH:
if primary_contains(query, t):
return True
elif matchkind == CONTAINS_MATCH:
if not case_sensitive and use_primary_find_in_search:
if primary_no_punc_contains(query, t):
return True
elif query in t:
return True
return False
# }}}
class DateSearch: # {{{
def __init__(self):
self.operators = OrderedDict((
('!=', self.ne),
('>=', self.ge),
('<=', self.le),
('=', self.eq),
('>', self.gt),
('<', self.lt),
))
self.local_today = {'_today', 'today', icu_lower(_('today'))}
self.local_yesterday = {'_yesterday', 'yesterday', icu_lower(_('yesterday'))}
self.local_thismonth = {'_thismonth', 'thismonth', icu_lower(_('thismonth'))}
self.daysago_pat = regex.compile(r'(%s|daysago|_daysago)$'%_('daysago'), flags=regex.UNICODE | regex.VERSION1)
def eq(self, dbdate, query, field_count):
if dbdate.year == query.year:
if field_count == 1:
return True
if dbdate.month == query.month:
if field_count == 2:
return True
return dbdate.day == query.day
return False
def ne(self, *args):
return not self.eq(*args)
def gt(self, dbdate, query, field_count):
if dbdate.year > query.year:
return True
if field_count > 1 and dbdate.year == query.year:
if dbdate.month > query.month:
return True
return (field_count == 3 and dbdate.month == query.month and
dbdate.day > query.day)
return False
def le(self, *args):
return not self.gt(*args)
def lt(self, dbdate, query, field_count):
if dbdate.year < query.year:
return True
if field_count > 1 and dbdate.year == query.year:
if dbdate.month < query.month:
return True
return (field_count == 3 and dbdate.month == query.month and
dbdate.day < query.day)
return False
def ge(self, *args):
return not self.lt(*args)
def __call__(self, query, field_iter):
matches = set()
if len(query) < 2:
return matches
if query == 'false':
for v, book_ids in field_iter():
if isinstance(v, (bytes, str)):
if isinstance(v, bytes):
v = v.decode(preferred_encoding, 'replace')
v = parse_date(v)
if v is None or v <= UNDEFINED_DATE:
matches |= book_ids
return matches
if query == 'true':
for v, book_ids in field_iter():
if isinstance(v, (bytes, str)):
if isinstance(v, bytes):
v = v.decode(preferred_encoding, 'replace')
v = parse_date(v)
if v is not None and v > UNDEFINED_DATE:
matches |= book_ids
return matches
for k, relop in iteritems(self.operators):
if query.startswith(k):
query = query[len(k):]
break
else:
relop = self.operators['=']
if query in self.local_today:
qd = now()
field_count = 3
elif query in self.local_yesterday:
qd = now() - timedelta(1)
field_count = 3
elif query in self.local_thismonth:
qd = now()
field_count = 2
else:
m = self.daysago_pat.search(query)
if m is not None:
num = query[:-len(m.group(1))]
try:
qd = now() - timedelta(int(num))
except:
raise ParseException(_('Number conversion error: {0}').format(num))
field_count = 3
else:
try:
qd = parse_date(query, as_utc=False)
except:
raise ParseException(_('Date conversion error: {0}').format(query))
if '-' in query:
field_count = query.count('-') + 1
else:
field_count = query.count('/') + 1
for v, book_ids in field_iter():
if isinstance(v, string_or_bytes):
v = parse_date(v)
if v is not None and relop(dt_as_local(v), qd, field_count):
matches |= book_ids
return matches
# }}}
class NumericSearch: # {{{
def __init__(self):
self.operators = OrderedDict((
('!=', operator.ne),
('>=', operator.ge),
('<=', operator.le),
('=', operator.eq),
('>', operator.gt),
('<', operator.lt),
))
def __call__(self, query, field_iter, location, datatype, candidates, is_many=False):
matches = set()
if not query:
return matches
q = ''
cast = adjust = lambda x: x
dt = datatype
if is_many and query in {'true', 'false'}:
if datatype == 'rating':
def valcheck(x):
return (x is not None and x > 0)
else:
def valcheck(x):
return True
found = set()
for val, book_ids in field_iter():
if valcheck(val):
found |= book_ids
return found if query == 'true' else candidates - found
if query == 'false':
if location == 'cover':
def relop(x, y):
return (not bool(x))
else:
def relop(x, y):
return (x is None)
elif query == 'true':
if location == 'cover':
def relop(x, y):
return bool(x)
else:
def relop(x, y):
return (x is not None)
else:
for k, relop in iteritems(self.operators):
if query.startswith(k):
query = query[len(k):]
break
else:
relop = self.operators['=']
if dt == 'rating':
def cast(x):
return (0 if x is None else int(x))
def adjust(x):
return (x // 2)
else:
# Datatype is empty if the source is a template. Assume float
cast = float if dt in ('float', 'composite', 'half-rating', '') else int
mult = 1.0
if len(query) > 1:
mult = query[-1].lower()
mult = {'k': 1024.,'m': 1024.**2, 'g': 1024.**3}.get(mult, 1.0)
if mult != 1.0:
query = query[:-1]
else:
mult = 1.0
try:
q = cast(query) * mult
except Exception:
raise ParseException(
_('Non-numeric value in query: {0}').format(query))
if dt == 'half-rating':
q = int(round(q * 2))
cast = int
qfalse = query == 'false'
for val, book_ids in field_iter():
if val is None:
if qfalse:
matches |= book_ids
continue
try:
v = cast(val)
except Exception:
raise ParseException(
_('Non-numeric value in column {0}: {1}').format(location, val))
if v:
v = adjust(v)
if relop(v, q):
matches |= book_ids
return matches
# }}}
class BooleanSearch: # {{{
def __init__(self):
self.local_no = icu_lower(_('no'))
self.local_yes = icu_lower(_('yes'))
self.local_unchecked = icu_lower(_('unchecked'))
self.local_checked = icu_lower(_('checked'))
self.local_empty = icu_lower(_('empty'))
self.local_blank = icu_lower(_('blank'))
self.local_bool_values = {
self.local_no, self.local_unchecked, '_no', 'false', 'no', 'unchecked', '_unchecked',
self.local_yes, self.local_checked, 'checked', '_checked', '_yes', 'true', 'yes',
self.local_empty, self.local_blank, 'blank', '_blank', '_empty', 'empty'}
def __call__(self, query, field_iter, bools_are_tristate):
matches = set()
if query not in self.local_bool_values:
raise ParseException(_('Invalid boolean query "{0}"').format(query))
for val, book_ids in field_iter():
val = force_to_bool(val)
if not bools_are_tristate:
if val is None or not val: # item is None or set to false
if query in {self.local_no, self.local_unchecked, 'unchecked', '_unchecked', 'no', '_no', 'false'}:
matches |= book_ids
else: # item is explicitly set to true
if query in {self.local_yes, self.local_checked, 'checked', '_checked', 'yes', '_yes', 'true'}:
matches |= book_ids
else:
if val is None:
if query in {self.local_empty, self.local_blank, 'blank', '_blank', 'empty', '_empty', 'false'}:
matches |= book_ids
elif not val: # is not None and false
if query in {self.local_no, self.local_unchecked, 'unchecked', '_unchecked', 'no', '_no', 'true'}:
matches |= book_ids
else: # item is not None and true
if query in {self.local_yes, self.local_checked, 'checked', '_checked', 'yes', '_yes', 'true'}:
matches |= book_ids
return matches
# }}}
class KeyPairSearch: # {{{
def __call__(self, query, field_iter, candidates, use_primary_find):
matches = set()
if ':' in query:
q = [q.strip() for q in query.partition(':')[0::2]]
keyq, valq = q
keyq_mkind, keyq = _matchkind(keyq)
valq_mkind, valq = _matchkind(valq)
else:
keyq = keyq_mkind = ''
valq_mkind, valq = _matchkind(query)
if valq in {'true', 'false'}:
found = set()
if keyq:
for val, book_ids in field_iter():
if val and val.get(keyq, False):
found |= book_ids
else:
for val, book_ids in field_iter():
if val:
found |= book_ids
return found if valq == 'true' else candidates - found
for m, book_ids in field_iter():
for key, val in iteritems(m):
if (keyq and not _match(keyq, (key,), keyq_mkind,
use_primary_find_in_search=use_primary_find)):
continue
if (valq and not _match(valq, (val,), valq_mkind,
use_primary_find_in_search=use_primary_find)):
continue
matches |= book_ids
break
return matches
# }}}
class SavedSearchQueries: # {{{
queries = {}
opt_name = ''
def __init__(self, db, _opt_name):
self.opt_name = _opt_name
try:
self._db = weakref.ref(db)
except TypeError:
# db could be None
self._db = lambda : None
self.load_from_db()
def load_from_db(self):
db = self.db
if db is not None:
self.queries = db._pref(self.opt_name, default={})
else:
self.queries = {}
@property
def db(self):
return self._db()
def force_unicode(self, x):
if not isinstance(x, str):
x = x.decode(preferred_encoding, 'replace')
return x
def add(self, name, value):
db = self.db
if db is not None:
self.queries[self.force_unicode(name)] = self.force_unicode(value).strip()
db._set_pref(self.opt_name, self.queries)
def lookup(self, name):
sn = self.force_unicode(name).lower()
for n, q in self.queries.items():
if sn == n.lower():
return q
return None
def delete(self, name):
db = self.db
if db is not None:
self.queries.pop(self.force_unicode(name), False)
db._set_pref(self.opt_name, self.queries)
def rename(self, old_name, new_name):
db = self.db
if db is not None:
self.queries[self.force_unicode(new_name)] = self.queries.get(self.force_unicode(old_name), None)
self.queries.pop(self.force_unicode(old_name), False)
db._set_pref(self.opt_name, self.queries)
def set_all(self, smap):
db = self.db
if db is not None:
self.queries = smap
db._set_pref(self.opt_name, smap)
def names(self):
return sorted(self.queries, key=sort_key)
# }}}
class Parser(SearchQueryParser): # {{{
def __init__(self, dbcache, all_book_ids, gst, date_search, num_search,
bool_search, keypair_search, limit_search_columns, limit_search_columns_to,
locations, virtual_fields, lookup_saved_search, parse_cache):
self.dbcache, self.all_book_ids = dbcache, all_book_ids
self.all_search_locations = frozenset(locations)
self.grouped_search_terms = gst
self.date_search, self.num_search = date_search, num_search
self.bool_search, self.keypair_search = bool_search, keypair_search
self.limit_search_columns, self.limit_search_columns_to = (
limit_search_columns, limit_search_columns_to)
self.virtual_fields = virtual_fields or {}
if 'marked' not in self.virtual_fields:
self.virtual_fields['marked'] = self
if 'in_tag_browser' not in self.virtual_fields:
self.virtual_fields['in_tag_browser'] = self
SearchQueryParser.__init__(self, locations, optimize=True, lookup_saved_search=lookup_saved_search, parse_cache=parse_cache)
@property
def field_metadata(self):
return self.dbcache.field_metadata
def universal_set(self):
return self.all_book_ids
def field_iter(self, name, candidates):
get_metadata = self.dbcache._get_proxy_metadata
try:
field = self.dbcache.fields[name]
except KeyError:
field = self.virtual_fields[name]
self.virtual_field_used = True
return field.iter_searchable_values(get_metadata, candidates)
def iter_searchable_values(self, *args, **kwargs):
for x in ():
yield x, set()
def parse(self, *args, **kwargs):
self.virtual_field_used = False
return SearchQueryParser.parse(self, *args, **kwargs)
def get_matches(self, location, query, candidates=None,
allow_recursion=True):
# If candidates is not None, it must not be modified. Changing its
# value will break query optimization in the search parser
matches = set()
if candidates is None:
candidates = self.all_book_ids
if not candidates or not query or not query.strip():
return matches
if location not in self.all_search_locations:
return matches
if location == 'vl':
vl = self.dbcache._pref('virtual_libraries', {}).get(query) if query else None
if not vl:
raise ParseException(_('No such Virtual library: {}').format(query))
try:
return candidates & self.dbcache.books_in_virtual_library(
query, virtual_fields=self.virtual_fields)
except RuntimeError:
raise ParseException(_('Virtual library search is recursive: {}').format(query))
if (len(location) > 2 and location.startswith('@') and
location[1:] in self.grouped_search_terms):
location = location[1:]
# get metadata key associated with the search term. Eliminates
# dealing with plurals and other aliases
original_location = location
location = self.field_metadata.search_term_to_field_key(
icu_lower(location.strip()))
# grouped search terms
if isinstance(location, list):
if allow_recursion:
if query.lower() == 'false':
invert = True
query = 'true'
else:
invert = False
for loc in location:
c = candidates.copy()
m = self.get_matches(loc, query,
candidates=c, allow_recursion=False)
matches |= m
c -= m
if len(c) == 0:
break
if invert:
matches = self.all_book_ids - matches
return matches
raise ParseException(
_('Recursive query group detected: {0}').format(query))
# If the user has asked to restrict searching over all field, apply
# that restriction
if (location == 'all' and self.limit_search_columns and
self.limit_search_columns_to):
terms = set()
for l in self.limit_search_columns_to:
l = icu_lower(l.strip())
if l and l != 'all' and l in self.all_search_locations:
terms.add(l)
if terms:
c = candidates.copy()
for l in terms:
try:
m = self.get_matches(l, query,
candidates=c, allow_recursion=allow_recursion)
matches |= m
c -= m
if len(c) == 0:
break
except:
pass
return matches
upf = prefs['use_primary_find_in_search']
if location in self.field_metadata:
fm = self.field_metadata[location]
dt = fm['datatype']
# take care of dates special case
if (dt == 'datetime' or (
dt == 'composite' and
fm['display'].get('composite_sort', '') == 'date')):
if location == 'date':
location = 'timestamp'
return self.date_search(
icu_lower(query), partial(self.field_iter, location, candidates))
# take care of numbers special case
if (dt in ('rating', 'int', 'float') or
(dt == 'composite' and
fm['display'].get('composite_sort', '') == 'number')):
if location == 'id':
is_many = False
def fi(default_value=None):
for qid in candidates:
yield qid, {qid}
else:
field = self.dbcache.fields[location]
fi, is_many = partial(self.field_iter, location, candidates), field.is_many
if dt == 'rating' and fm['display'].get('allow_half_stars'):
dt = 'half-rating'
return self.num_search(
icu_lower(query), fi, location, dt, candidates, is_many=is_many)
# take care of the 'count' operator for is_multiples
if (fm['is_multiple'] and
len(query) > 1 and query[0] == '#' and query[1] in '=<>!'):
return self.num_search(icu_lower(query[1:]), partial(
self.dbcache.fields[location].iter_counts, candidates,
get_metadata=self.dbcache._get_proxy_metadata),
location, dt, candidates)
# take care of boolean special case
if dt == 'bool':
return self.bool_search(icu_lower(query),
partial(self.field_iter, location, candidates),
self.dbcache._pref('bools_are_tristate'))
# special case: colon-separated fields such as identifiers. isbn
# is a special case within the case
if fm.get('is_csp', False):
field_iter = partial(self.field_iter, location, candidates)
if location == 'identifiers' and original_location == 'isbn':
return self.keypair_search('=isbn:'+query, field_iter,
candidates, upf)
return self.keypair_search(query, field_iter, candidates, upf)
# check for user categories
if len(location) >= 2 and location.startswith('@'):
return self.get_user_category_matches(location[1:], icu_lower(query), candidates)
# Everything else (and 'all' matches)
case_sensitive = prefs['case_sensitive']
if location == 'template':
try:
template, sep, query = regex.split('#@#:([tdnb]):', query, flags=regex.IGNORECASE)
if sep:
sep = sep.lower()
else:
sep = 't'
except:
if DEBUG:
import traceback
traceback.print_exc()
raise ParseException(_('search template: missing or invalid separator. Valid separators are: {}').format('#@#:[tdnb]:'))
matchkind, query = _matchkind(query, case_sensitive=case_sensitive)
matches = set()
error_string = '*@*TEMPLATE_ERROR*@*'
template_cache = {}
global_vars = {'_candidates': candidates}
for book_id in candidates:
mi = self.dbcache.get_proxy_metadata(book_id)
val = mi.formatter.safe_format(template, {}, error_string, mi,
column_name='search template',
template_cache=template_cache,
global_vars=global_vars)
if val.startswith(error_string):
raise ParseException(val[len(error_string):])
if sep == 't':
if _match(query, [val,], matchkind, use_primary_find_in_search=upf,
case_sensitive=case_sensitive):
matches.add(book_id)
elif sep == 'n' and val:
matches.update(self.num_search(
icu_lower(query), {val:{book_id,}}.items, '', '',
{book_id,}, is_many=False))
elif sep == 'd' and val:
matches.update(self.date_search(
icu_lower(query), {val:{book_id,}}.items))
elif sep == 'b':
matches.update(self.bool_search(icu_lower(query),
{'True' if val else 'False':{book_id,}}.items, False))
return matches
matchkind, query = _matchkind(query, case_sensitive=case_sensitive)
all_locs = set()
text_fields = set()
field_metadata = {}
for x, fm in self.field_metadata.iter_items():
if x.startswith('@'):
continue
if fm['search_terms'] and x not in {'series_sort', 'id'}:
if x not in self.virtual_fields and x != 'uuid':
# We dont search virtual fields because if we do, search
# caching will not be used
all_locs.add(x)
field_metadata[x] = fm
if fm['datatype'] in {'composite', 'text', 'comments', 'series', 'enumeration'}:
text_fields.add(x)
locations = all_locs if location == 'all' else {location}
current_candidates = set(candidates)
try:
rating_query = int(float(query)) * 2
except:
rating_query = None
try:
int_query = int(float(query))
except:
int_query = None
try:
float_query = float(query)
except:
float_query = None
for location in locations:
current_candidates -= matches
q = query
if location == 'languages':
q = canonicalize_lang(query)
if q is None:
lm = lang_map()
rm = {v.lower():k for k,v in iteritems(lm)}
q = rm.get(query, query)
if matchkind == CONTAINS_MATCH and q.lower() in {'true', 'false'}:
found = set()
for val, book_ids in self.field_iter(location, current_candidates):
if val and (not hasattr(val, 'strip') or val.strip()):
found |= book_ids
matches |= (found if q.lower() == 'true' else (current_candidates-found))
continue
dt = field_metadata.get(location, {}).get('datatype', None)
if dt == 'rating':
if rating_query is not None:
for val, book_ids in self.field_iter(location, current_candidates):
if val == rating_query:
matches |= book_ids
continue
if dt == 'float':
if float_query is not None:
for val, book_ids in self.field_iter(location, current_candidates):
if val == float_query:
matches |= book_ids
continue
if dt == 'int':
if int_query is not None:
for val, book_ids in self.field_iter(location, current_candidates):
if val == int_query:
matches |= book_ids
continue
if location in text_fields:
for val, book_ids in self.field_iter(location, current_candidates):
if val is not None:
if isinstance(val, string_or_bytes):
val = (val,)
if _match(q, val, matchkind, use_primary_find_in_search=upf, case_sensitive=case_sensitive):
matches |= book_ids
if location == 'series_sort':
book_lang_map = self.dbcache.fields['languages'].book_value_map
for val, book_ids in self.dbcache.fields['series'].iter_searchable_values_for_sort(current_candidates, book_lang_map):
if val is not None:
if _match(q, (val,), matchkind, use_primary_find_in_search=upf, case_sensitive=case_sensitive):
matches |= book_ids
return matches
def get_user_category_matches(self, location, query, candidates):
matches = set()
if len(query) < 2:
return matches
user_cats = self.dbcache._pref('user_categories')
c = set(candidates)
if query.startswith('.'):
check_subcats = True
query = query[1:]
else:
check_subcats = False
for key in user_cats:
if key == location or (check_subcats and key.startswith(location + '.')):
for (item, category, ign) in user_cats[key]:
s = self.get_matches(category, '=' + item, candidates=c)
c -= s
matches |= s
if query == 'false':
return candidates - matches
return matches
# }}}
class LRUCache: # {{{
'A simple Least-Recently-Used cache'
def __init__(self, limit=50):
self.item_map = {}
self.age_map = deque()
self.limit = limit
def _move_up(self, key):
if key != self.age_map[-1]:
self.age_map.remove(key)
self.age_map.append(key)
def add(self, key, val):
if key in self.item_map:
self._move_up(key)
return
if len(self.age_map) >= self.limit:
self.item_map.pop(self.age_map.popleft())
self.item_map[key] = val
self.age_map.append(key)
__setitem__ = add
def get(self, key, default=None):
ans = self.item_map.get(key, default)
if ans is not default:
self._move_up(key)
return ans
def clear(self):
self.item_map.clear()
self.age_map.clear()
def pop(self, key, default=None):
self.item_map.pop(key, default)
try:
self.age_map.remove(key)
except ValueError:
pass
def __contains__(self, key):
return key in self.item_map
def __len__(self):
return len(self.age_map)
def __getitem__(self, key):
return self.get(key)
def __iter__(self):
return iteritems(self.item_map)
# }}}
class Search:
MAX_CACHE_UPDATE = 50
def __init__(self, db, opt_name, all_search_locations=()):
self.all_search_locations = all_search_locations
self.date_search = DateSearch()
self.num_search = NumericSearch()
self.bool_search = BooleanSearch()
self.keypair_search = KeyPairSearch()
self.saved_searches = SavedSearchQueries(db, opt_name)
self.cache = LRUCache()
self.parse_cache = LRUCache(limit=100)
def get_saved_searches(self):
return self.saved_searches
def change_locations(self, newlocs):
if frozenset(newlocs) != frozenset(self.all_search_locations):
self.clear_caches()
self.parse_cache.clear()
self.all_search_locations = newlocs
def update_or_clear(self, dbcache, book_ids=None):
if book_ids and (len(book_ids) * len(self.cache)) <= self.MAX_CACHE_UPDATE:
self.update_caches(dbcache, book_ids)
else:
self.clear_caches()
def clear_caches(self):
self.cache.clear()
def update_caches(self, dbcache, book_ids):
sqp = self.create_parser(dbcache)
try:
return self._update_caches(sqp, book_ids)
finally:
sqp.dbcache = sqp.lookup_saved_search = None
def discard_books(self, book_ids):
book_ids = set(book_ids)
for query, result in self.cache:
result.difference_update(book_ids)
def _update_caches(self, sqp, book_ids):
book_ids = sqp.all_book_ids = set(book_ids)
remove = set()
for query, result in tuple(self.cache):
try:
matches = sqp.parse(query)
except ParseException:
remove.add(query)
else:
# remove books that no longer match
result.difference_update(book_ids - matches)
# add books that now match but did not before
result.update(matches)
for query in remove:
self.cache.pop(query)
def create_parser(self, dbcache, virtual_fields=None):
return Parser(
dbcache, set(), dbcache._pref('grouped_search_terms'),
self.date_search, self.num_search, self.bool_search,
self.keypair_search,
prefs['limit_search_columns'],
prefs['limit_search_columns_to'], self.all_search_locations,
virtual_fields, self.saved_searches.lookup, self.parse_cache)
def __call__(self, dbcache, query, search_restriction, virtual_fields=None, book_ids=None):
'''
Return the set of ids of all records that match the specified
query and restriction
'''
# We construct a new parser instance per search as the parse is not
# thread safe.
sqp = self.create_parser(dbcache, virtual_fields)
try:
return self._do_search(sqp, query, search_restriction, dbcache, book_ids=book_ids)
finally:
sqp.dbcache = sqp.lookup_saved_search = None
def query_is_cacheable(self, sqp, dbcache, query):
if query:
for name, value in sqp.get_queried_fields(query):
if name == 'template':
return False
elif name in dbcache.field_metadata.all_field_keys():
fm = dbcache.field_metadata[name]
if fm['datatype'] == 'datetime':
return False
if fm['datatype'] == 'composite':
if fm.get('display', {}).get('composite_sort', '') == 'date':
return False
return True
def _do_search(self, sqp, query, search_restriction, dbcache, book_ids=None):
''' Do the search, caching the results. Results are cached only if the
search is on the full library and no virtual field is searched on '''
if isinstance(search_restriction, bytes):
search_restriction = search_restriction.decode('utf-8')
if isinstance(query, bytes):
query = query.decode('utf-8')
query = query.strip()
use_cache = self.query_is_cacheable(sqp, dbcache, query)
if use_cache and book_ids is None and query and not search_restriction:
cached = self.cache.get(query)
if cached is not None:
return cached
restricted_ids = all_book_ids = dbcache._all_book_ids(type=set)
if search_restriction and search_restriction.strip():
sr = search_restriction.strip()
sqp.all_book_ids = all_book_ids if book_ids is None else book_ids
if self.query_is_cacheable(sqp, dbcache, sr):
cached = self.cache.get(sr)
if cached is None:
restricted_ids = sqp.parse(sr)
if not sqp.virtual_field_used and sqp.all_book_ids is all_book_ids:
self.cache.add(sr, restricted_ids)
else:
restricted_ids = cached
if book_ids is not None:
restricted_ids = book_ids.intersection(restricted_ids)
else:
restricted_ids = sqp.parse(sr)
elif book_ids is not None:
restricted_ids = book_ids
if not query:
return restricted_ids
if use_cache and restricted_ids is all_book_ids:
cached = self.cache.get(query)
if cached is not None:
return cached
sqp.all_book_ids = restricted_ids
result = sqp.parse(query)
if not sqp.virtual_field_used and sqp.all_book_ids is all_book_ids:
self.cache.add(query, result)
return result
| 37,983 | Python | .py | 873 | 30.004582 | 136 | 0.522104 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,066 | backend.py | kovidgoyal_calibre/src/calibre/db/backend.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
# Imports {{{
import errno
import hashlib
import json
import os
import shutil
import stat
import sys
import time
import uuid
from contextlib import closing, suppress
from functools import partial
from typing import Optional
import apsw
from calibre import as_unicode, force_unicode, isbytestring, prints
from calibre.constants import filesystem_encoding, iswindows, plugins, preferred_encoding
from calibre.db import SPOOL_SIZE, FTSQueryError
from calibre.db.annotations import annot_db_data, unicode_normalize
from calibre.db.constants import (
BOOK_ID_PATH_TEMPLATE,
COVER_FILE_NAME,
DEFAULT_TRASH_EXPIRY_TIME_SECONDS,
METADATA_FILE_NAME,
NOTES_DIR_NAME,
TRASH_DIR_NAME,
TrashEntry,
)
from calibre.db.errors import NoSuchFormat
from calibre.db.schema_upgrades import SchemaUpgrade
from calibre.db.tables import (
AuthorsTable,
CompositeTable,
FormatsTable,
IdentifiersTable,
ManyToManyTable,
ManyToOneTable,
OneToOneTable,
PathTable,
RatingTable,
SizeTable,
UUIDTable,
)
from calibre.ebooks.metadata import author_to_author_sort, title_sort
from calibre.library.field_metadata import FieldMetadata
from calibre.ptempfile import PersistentTemporaryFile, TemporaryFile
from calibre.utils import pickle_binary_string, unpickle_binary_string
from calibre.utils.config import from_json, prefs, to_json, tweaks
from calibre.utils.copy_files import copy_files, copy_tree, rename_files, windows_check_if_files_in_use
from calibre.utils.date import EPOCH, parse_date, utcfromtimestamp, utcnow
from calibre.utils.filenames import (
ascii_filename,
atomic_rename,
copyfile_using_links,
copytree_using_links,
get_long_path_name,
hardlink_file,
is_case_sensitive,
is_fat_filesystem,
make_long_path_useable,
remove_dir_if_empty,
samefile,
)
from calibre.utils.formatter_functions import compile_user_template_functions, formatter_functions, load_user_template_functions, unload_user_template_functions
from calibre.utils.icu import lower as icu_lower
from calibre.utils.icu import sort_key
from calibre.utils.resources import get_path as P
from polyglot.builtins import cmp, iteritems, itervalues, native_string_type, reraise, string_or_bytes
# }}}
CUSTOM_DATA_TYPES = frozenset(('rating', 'text', 'comments', 'datetime',
'int', 'float', 'bool', 'series', 'composite', 'enumeration'))
WINDOWS_RESERVED_NAMES = frozenset('CON PRN AUX NUL COM1 COM2 COM3 COM4 COM5 COM6 COM7 COM8 COM9 LPT1 LPT2 LPT3 LPT4 LPT5 LPT6 LPT7 LPT8 LPT9'.split())
class DynamicFilter: # {{{
'No longer used, present for legacy compatibility'
def __init__(self, name):
self.name = name
self.ids = frozenset()
def __call__(self, id_):
return int(id_ in self.ids)
def change(self, ids):
self.ids = frozenset(ids)
# }}}
class DBPrefs(dict): # {{{
'Store preferences as key:value pairs in the db'
def __init__(self, db):
dict.__init__(self)
self.db = db
self.defaults = {}
self.disable_setting = False
self.load_from_db()
def load_from_db(self):
self.clear()
for key, val in self.db.conn.get('SELECT key,val FROM preferences'):
try:
val = self.raw_to_object(val)
except:
prints('Failed to read value for:', key, 'from db')
continue
dict.__setitem__(self, key, val)
def raw_to_object(self, raw):
if not isinstance(raw, str):
raw = raw.decode(preferred_encoding)
return json.loads(raw, object_hook=from_json)
def to_raw(self, val):
# sort_keys=True is required so that the serialization of dictionaries is
# not random, which is needed for the changed check in __setitem__
return json.dumps(val, indent=2, default=to_json, sort_keys=True)
def has_setting(self, key):
return key in self
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
return self.defaults[key]
def __delitem__(self, key):
dict.__delitem__(self, key)
self.db.execute('DELETE FROM preferences WHERE key=?', (key,))
def __setitem__(self, key, val):
if not self.disable_setting:
raw = self.to_raw(val)
do_set = False
with self.db.conn:
try:
dbraw = next(self.db.execute('SELECT id,val FROM preferences WHERE key=?', (key,)))
except StopIteration:
dbraw = None
if dbraw is None or dbraw[1] != raw:
if dbraw is None:
self.db.execute('INSERT INTO preferences (key,val) VALUES (?,?)', (key, raw))
else:
self.db.execute('UPDATE preferences SET val=? WHERE id=?', (raw, dbraw[0]))
do_set = True
if do_set:
dict.__setitem__(self, key, val)
def set(self, key, val):
self.__setitem__(key, val)
def get_namespaced(self, namespace, key, default=None):
key = 'namespaced:%s:%s'%(namespace, key)
try:
return dict.__getitem__(self, key)
except KeyError:
return default
def set_namespaced(self, namespace, key, val):
if ':' in key:
raise KeyError('Colons are not allowed in keys')
if ':' in namespace:
raise KeyError('Colons are not allowed in the namespace')
key = 'namespaced:%s:%s'%(namespace, key)
self[key] = val
def write_serialized(self, library_path):
try:
to_filename = os.path.join(library_path, 'metadata_db_prefs_backup.json')
data = json.dumps(self, indent=2, default=to_json)
if not isinstance(data, bytes):
data = data.encode('utf-8')
with open(to_filename, 'wb') as f:
f.write(data)
except:
import traceback
traceback.print_exc()
@classmethod
def read_serialized(cls, library_path, recreate_prefs=False):
from_filename = os.path.join(library_path,
'metadata_db_prefs_backup.json')
with open(from_filename, 'rb') as f:
return json.load(f, object_hook=from_json)
# }}}
# Extra collators {{{
def pynocase(one, two, encoding='utf-8'):
if isbytestring(one):
try:
one = one.decode(encoding, 'replace')
except:
pass
if isbytestring(two):
try:
two = two.decode(encoding, 'replace')
except:
pass
return cmp(one.lower(), two.lower())
def _author_to_author_sort(x):
if not x:
return ''
return author_to_author_sort(x.replace('|', ','))
def icu_collator(s1, s2):
return cmp(sort_key(force_unicode(s1, 'utf-8')),
sort_key(force_unicode(s2, 'utf-8')))
# }}}
# Unused aggregators {{{
def Concatenate(sep=','):
'''String concatenation aggregator for sqlite'''
def step(ctxt, value):
if value is not None:
ctxt.append(value)
def finalize(ctxt):
try:
if not ctxt:
return None
return sep.join(ctxt)
except Exception:
import traceback
traceback.print_exc()
raise
return ([], step, finalize)
def SortedConcatenate(sep=','):
'''String concatenation aggregator for sqlite, sorted by supplied index'''
def step(ctxt, ndx, value):
if value is not None:
ctxt[ndx] = value
def finalize(ctxt):
try:
if len(ctxt) == 0:
return None
return sep.join(map(ctxt.get, sorted(ctxt)))
except Exception:
import traceback
traceback.print_exc()
raise
return ({}, step, finalize)
def IdentifiersConcat():
'''String concatenation aggregator for the identifiers map'''
def step(ctxt, key, val):
ctxt.append('%s:%s'%(key, val))
def finalize(ctxt):
try:
return ','.join(ctxt)
except Exception:
import traceback
traceback.print_exc()
raise
return ([], step, finalize)
def AumSortedConcatenate():
'''String concatenation aggregator for the author sort map'''
def step(ctxt, ndx, author, sort, link):
if author is not None:
ctxt[ndx] = ':::'.join((author, sort, link))
def finalize(ctxt):
try:
keys = list(ctxt)
l = len(keys)
if l == 0:
return None
if l == 1:
return ctxt[keys[0]]
return ':#:'.join([ctxt[v] for v in sorted(keys)])
except Exception:
import traceback
traceback.print_exc()
raise
return ({}, step, finalize)
# }}}
# Annotations {{{
def annotations_for_book(cursor, book_id, fmt, user_type='local', user='viewer'):
for (data,) in cursor.execute(
'SELECT annot_data FROM annotations WHERE book=? AND format=? AND user_type=? AND user=?',
(book_id, fmt.upper(), user_type, user)
):
try:
yield json.loads(data)
except Exception:
pass
def save_annotations_for_book(cursor, book_id, fmt, annots_list, user_type='local', user='viewer'):
data = []
fmt = fmt.upper()
for annot, timestamp_in_secs in annots_list:
atype = annot['type'].lower()
aid, text = annot_db_data(annot)
if aid is None:
continue
data.append((book_id, fmt, user_type, user, timestamp_in_secs, aid, atype, json.dumps(annot), text))
cursor.execute('INSERT OR IGNORE INTO annotations_dirtied (book) VALUES (?)', (book_id,))
cursor.execute('DELETE FROM annotations WHERE book=? AND format=? AND user_type=? AND user=?', (book_id, fmt, user_type, user))
cursor.executemany(
'INSERT OR REPLACE INTO annotations (book, format, user_type, user, timestamp, annot_id, annot_type, annot_data, searchable_text)'
' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', data)
# }}}
class Connection(apsw.Connection): # {{{
BUSY_TIMEOUT = 10000 # milliseconds
def __init__(self, path):
from calibre.utils.localization import get_lang
from calibre_extensions.sqlite_extension import set_ui_language
set_ui_language(get_lang())
super().__init__(path)
plugins.load_apsw_extension(self, 'sqlite_extension')
self.fts_dbpath = self.notes_dbpath = None
self.setbusytimeout(self.BUSY_TIMEOUT)
self.execute('PRAGMA cache_size=-5000; PRAGMA temp_store=2; PRAGMA foreign_keys=ON;')
encoding = next(self.execute('PRAGMA encoding'))[0]
self.createcollation('PYNOCASE', partial(pynocase,
encoding=encoding))
self.createscalarfunction('title_sort', title_sort, 1)
self.createscalarfunction('author_to_author_sort',
_author_to_author_sort, 1)
self.createscalarfunction('uuid4', lambda: str(uuid.uuid4()),
0)
# Dummy functions for dynamically created filters
self.createscalarfunction('books_list_filter', lambda x: 1, 1)
self.createcollation('icucollate', icu_collator)
# Legacy aggregators (never used) but present for backwards compat
self.createaggregatefunction('sortconcat', SortedConcatenate, 2)
self.createaggregatefunction('sortconcat_bar',
partial(SortedConcatenate, sep='|'), 2)
self.createaggregatefunction('sortconcat_amper',
partial(SortedConcatenate, sep='&'), 2)
self.createaggregatefunction('identifiers_concat',
IdentifiersConcat, 2)
self.createaggregatefunction('concat', Concatenate, 1)
self.createaggregatefunction('aum_sortconcat',
AumSortedConcatenate, 4)
def create_dynamic_filter(self, name):
f = DynamicFilter(name)
self.createscalarfunction(name, f, 1)
def get(self, *args, **kw):
ans = self.cursor().execute(*args)
if kw.get('all', True):
return ans.fetchall()
with suppress(StopIteration, IndexError):
return next(ans)[0]
def get_dict(self, *args, all=True):
ans = self.cursor().execute(*args)
desc = ans.getdescription()
field_names = tuple(x[0] for x in desc)
def as_dict(row):
return dict(zip(field_names, row))
if all:
return tuple(map(as_dict, ans))
ans = ans.fetchone()
if ans is not None:
ans = as_dict(ans)
return ans
def execute(self, sql, bindings=None):
cursor = self.cursor()
return cursor.execute(sql, bindings)
def executemany(self, sql, sequence_of_bindings):
with self: # Disable autocommit mode, for performance
return self.cursor().executemany(sql, sequence_of_bindings)
# }}}
def set_global_state(backend):
load_user_template_functions(
backend.library_id, (), precompiled_user_functions=backend.get_user_template_functions())
def rmtree_with_retry(path, sleep_time=1):
try:
shutil.rmtree(path)
except OSError as e:
if e.errno == errno.ENOENT and not os.path.exists(path):
return
if iswindows:
time.sleep(sleep_time) # In case something has temporarily locked a file
shutil.rmtree(path)
class DB:
PATH_LIMIT = 40 if iswindows else 100
WINDOWS_LIBRARY_PATH_LIMIT = 75
# Initialize database {{{
def __init__(self, library_path, default_prefs=None, read_only=False,
restore_all_prefs=False, progress_callback=lambda x, y:True,
load_user_formatter_functions=True):
self.is_closed = False
if isbytestring(library_path):
library_path = library_path.decode(filesystem_encoding)
self.field_metadata = FieldMetadata()
self.library_path = os.path.abspath(library_path)
self.dbpath = os.path.join(library_path, 'metadata.db')
self.dbpath = os.environ.get('CALIBRE_OVERRIDE_DATABASE_PATH',
self.dbpath)
if iswindows and len(self.library_path) + 4*self.PATH_LIMIT + 10 > 259:
raise ValueError(_(
'Path to library ({0}) too long. It must be less than'
' {1} characters.').format(self.library_path, 259-4*self.PATH_LIMIT-10))
exists = self._exists = os.path.exists(self.dbpath)
if not exists:
# Be more strict when creating new libraries as the old calculation
# allowed for max path lengths of 265 chars.
if (iswindows and len(self.library_path) > self.WINDOWS_LIBRARY_PATH_LIMIT):
raise ValueError(_(
'Path to library too long. It must be less than'
' %d characters.')%self.WINDOWS_LIBRARY_PATH_LIMIT)
if read_only and os.path.exists(self.dbpath):
# Work on only a copy of metadata.db to ensure that
# metadata.db is not changed
pt = PersistentTemporaryFile('_metadata_ro.db')
pt.close()
shutil.copyfile(self.dbpath, pt.name)
self.dbpath = pt.name
if not os.path.exists(os.path.dirname(self.dbpath)):
os.makedirs(os.path.dirname(self.dbpath))
self._conn = None
if self.user_version == 0:
self.initialize_database()
if not os.path.exists(self.library_path):
os.makedirs(self.library_path)
self.is_case_sensitive = is_case_sensitive(self.library_path)
self.is_fat_filesystem = is_fat_filesystem(self.library_path)
SchemaUpgrade(self, self.library_path, self.field_metadata)
# Guarantee that the library_id is set
self.library_id
# Fix legacy triggers and columns
self.execute('''
DROP TRIGGER IF EXISTS author_insert_trg;
CREATE TEMP TRIGGER author_insert_trg
AFTER INSERT ON authors
BEGIN
UPDATE authors SET sort=author_to_author_sort(NEW.name) WHERE id=NEW.id;
END;
DROP TRIGGER IF EXISTS author_update_trg;
CREATE TEMP TRIGGER author_update_trg
BEFORE UPDATE ON authors
BEGIN
UPDATE authors SET sort=author_to_author_sort(NEW.name)
WHERE id=NEW.id AND name <> NEW.name;
END;
UPDATE authors SET sort=author_to_author_sort(name) WHERE sort IS NULL;
''')
# Initialize_prefs must be called before initialize_custom_columns because
# icc can set a pref.
self.initialize_prefs(default_prefs, restore_all_prefs, progress_callback)
self.initialize_custom_columns()
self.initialize_tables()
self.set_user_template_functions(compile_user_template_functions(
self.prefs.get('user_template_functions', [])))
if self.prefs['last_expired_trash_at'] > 0:
self.ensure_trash_dir(during_init=True)
if load_user_formatter_functions:
set_global_state(self)
self.initialize_notes()
@property
def last_expired_trash_at(self) -> float:
return float(self.prefs['last_expired_trash_at'])
@last_expired_trash_at.setter
def last_expired_trash_at(self, val: float) -> None:
self.prefs['last_expired_trash_at'] = float(val)
def get_template_functions(self):
return self._template_functions
def get_user_template_functions(self):
return self._user_template_functions
def set_user_template_functions(self, user_formatter_functions):
self._user_template_functions = user_formatter_functions
self._template_functions = formatter_functions().get_builtins_and_aliases().copy()
self._template_functions.update(user_formatter_functions)
def initialize_prefs(self, default_prefs, restore_all_prefs, progress_callback): # {{{
self.prefs = DBPrefs(self)
if default_prefs is not None and not self._exists:
progress_callback(None, len(default_prefs))
# Only apply default prefs to a new database
for i, key in enumerate(default_prefs):
# be sure that prefs not to be copied are listed below
if restore_all_prefs or key not in frozenset(['news_to_be_synced']):
self.prefs[key] = default_prefs[key]
progress_callback(_('restored preference ') + key, i+1)
if 'field_metadata' in default_prefs:
fmvals = [f for f in default_prefs['field_metadata'].values()
if f['is_custom']]
progress_callback(None, len(fmvals))
for i, f in enumerate(fmvals):
progress_callback(_('creating custom column ') + f['label'], i)
self.create_custom_column(f['label'], f['name'],
f['datatype'],
(f['is_multiple'] is not None and len(f['is_multiple']) > 0),
f['is_editable'], f['display'])
defs = self.prefs.defaults
defs['gui_restriction'] = defs['cs_restriction'] = ''
defs['categories_using_hierarchy'] = []
defs['column_color_rules'] = []
defs['column_icon_rules'] = []
defs['cover_grid_icon_rules'] = []
defs['grouped_search_make_user_categories'] = []
defs['similar_authors_search_key'] = 'authors'
defs['similar_authors_match_kind'] = 'match_any'
defs['similar_publisher_search_key'] = 'publisher'
defs['similar_publisher_match_kind'] = 'match_any'
defs['similar_tags_search_key'] = 'tags'
defs['similar_tags_match_kind'] = 'match_all'
defs['similar_series_search_key'] = 'series'
defs['similar_series_match_kind'] = 'match_any'
defs['last_expired_trash_at'] = 0.0
defs['expire_old_trash_after'] = DEFAULT_TRASH_EXPIRY_TIME_SECONDS
defs['book_display_fields'] = [
('title', False), ('authors', True), ('series', True),
('identifiers', True), ('tags', True), ('formats', True),
('path', True), ('publisher', False), ('rating', False),
('author_sort', False), ('sort', False), ('timestamp', False),
('uuid', False), ('comments', True), ('id', False), ('pubdate', False),
('last_modified', False), ('size', False), ('languages', False),
]
defs['popup_book_display_fields'] = [('title', True)] + [(f[0], True) for f in defs['book_display_fields'] if f[0] != 'title']
defs['qv_display_fields'] = [('title', True), ('authors', True), ('series', True)]
defs['virtual_libraries'] = {}
defs['virtual_lib_on_startup'] = defs['cs_virtual_lib_on_startup'] = ''
defs['virt_libs_hidden'] = defs['virt_libs_order'] = ()
defs['update_all_last_mod_dates_on_start'] = False
defs['field_under_covers_in_grid'] = 'title'
defs['cover_browser_title_template'] = '{title}'
defs['cover_browser_subtitle_field'] = 'rating'
defs['styled_columns'] = {}
defs['edit_metadata_ignore_display_order'] = False
defs['fts_enabled'] = False
# Migrate the bool tristate tweak
defs['bools_are_tristate'] = \
tweaks.get('bool_custom_columns_are_tristate', 'yes') == 'yes'
if self.prefs.get('bools_are_tristate') is None:
self.prefs.set('bools_are_tristate', defs['bools_are_tristate'])
# Migrate column coloring rules
if self.prefs.get('column_color_name_1', None) is not None:
from calibre.library.coloring import migrate_old_rule
old_rules = []
for i in range(1, 6):
col = self.prefs.get('column_color_name_%d' % i, None)
templ = self.prefs.get('column_color_template_%d' % i, None)
if col and templ:
try:
del self.prefs['column_color_name_%d' % i]
rules = migrate_old_rule(self.field_metadata, templ)
for templ in rules:
old_rules.append((col, templ))
except:
pass
if old_rules:
self.prefs['column_color_rules'] += old_rules
# Migrate saved search and user categories to db preference scheme
def migrate_preference(key, default):
oldval = prefs[key]
if oldval != default:
self.prefs[key] = oldval
prefs[key] = default
if key not in self.prefs:
self.prefs[key] = default
migrate_preference('user_categories', {})
migrate_preference('saved_searches', {})
# migrate grouped_search_terms
if self.prefs.get('grouped_search_terms', None) is None:
try:
ogst = tweaks.get('grouped_search_terms', {})
ngst = {}
for t in ogst:
ngst[icu_lower(t)] = ogst[t]
self.prefs.set('grouped_search_terms', ngst)
except:
pass
# migrate the gui_restriction preference to a virtual library
gr_pref = self.prefs.get('gui_restriction', None)
if gr_pref:
virt_libs = self.prefs.get('virtual_libraries', {})
virt_libs[gr_pref] = 'search:"' + gr_pref + '"'
self.prefs['virtual_libraries'] = virt_libs
self.prefs['gui_restriction'] = ''
self.prefs['virtual_lib_on_startup'] = gr_pref
# migrate the cs_restriction preference to a virtual library
gr_pref = self.prefs.get('cs_restriction', None)
if gr_pref:
virt_libs = self.prefs.get('virtual_libraries', {})
virt_libs[gr_pref] = 'search:"' + gr_pref + '"'
self.prefs['virtual_libraries'] = virt_libs
self.prefs['cs_restriction'] = ''
self.prefs['cs_virtual_lib_on_startup'] = gr_pref
# Rename any user categories with names that differ only in case
user_cats = self.prefs.get('user_categories', [])
catmap = {}
for uc in user_cats:
ucl = icu_lower(uc)
if ucl not in catmap:
catmap[ucl] = []
catmap[ucl].append(uc)
cats_changed = False
for uc in catmap:
if len(catmap[uc]) > 1:
prints('found user category case overlap', catmap[uc])
cat = catmap[uc][0]
suffix = 1
while icu_lower(cat + str(suffix)) in catmap:
suffix += 1
prints('Renaming user category %s to %s'%(cat, cat+str(suffix)))
user_cats[cat + str(suffix)] = user_cats[cat]
del user_cats[cat]
cats_changed = True
if cats_changed:
self.prefs.set('user_categories', user_cats)
# }}}
def initialize_custom_columns(self): # {{{
self.custom_columns_deleted = False
self.deleted_fields = []
with self.conn:
# Delete previously marked custom columns
for (num, label) in self.conn.get(
'SELECT id,label FROM custom_columns WHERE mark_for_delete=1'):
table, lt = self.custom_table_names(num)
self.execute('''\
DROP INDEX IF EXISTS {table}_idx;
DROP INDEX IF EXISTS {lt}_aidx;
DROP INDEX IF EXISTS {lt}_bidx;
DROP TRIGGER IF EXISTS fkc_update_{lt}_a;
DROP TRIGGER IF EXISTS fkc_update_{lt}_b;
DROP TRIGGER IF EXISTS fkc_insert_{lt};
DROP TRIGGER IF EXISTS fkc_delete_{lt};
DROP TRIGGER IF EXISTS fkc_insert_{table};
DROP TRIGGER IF EXISTS fkc_delete_{table};
DROP VIEW IF EXISTS tag_browser_{table};
DROP VIEW IF EXISTS tag_browser_filtered_{table};
DROP TABLE IF EXISTS {table};
DROP TABLE IF EXISTS {lt};
'''.format(table=table, lt=lt)
)
self.prefs.set('update_all_last_mod_dates_on_start', True)
self.deleted_fields.append('#'+label)
self.execute('DELETE FROM custom_columns WHERE mark_for_delete=1')
# Load metadata for custom columns
self.custom_column_label_map, self.custom_column_num_map = {}, {}
self.custom_column_num_to_label_map = {}
triggers = []
remove = []
custom_tables = self.custom_tables
for record in self.conn.get(
'SELECT label,name,datatype,editable,display,normalized,id,is_multiple FROM custom_columns'):
data = {
'label':record[0],
'name':record[1],
'datatype':record[2],
'editable':bool(record[3]),
'display':json.loads(record[4]),
'normalized':bool(record[5]),
'num':record[6],
'is_multiple':bool(record[7]),
}
if data['display'] is None:
data['display'] = {}
# set up the is_multiple separator dict
if data['is_multiple']:
if data['display'].get('is_names', False):
seps = {'cache_to_list': '|', 'ui_to_list': '&', 'list_to_ui': ' & '}
elif data['datatype'] == 'composite':
seps = {'cache_to_list': ',', 'ui_to_list': ',', 'list_to_ui': ', '}
else:
seps = {'cache_to_list': '|', 'ui_to_list': ',', 'list_to_ui': ', '}
else:
seps = {}
data['multiple_seps'] = seps
table, lt = self.custom_table_names(data['num'])
if table not in custom_tables or (data['normalized'] and lt not in
custom_tables):
remove.append(data)
continue
self.custom_column_num_map[data['num']] = \
self.custom_column_label_map[data['label']] = data
self.custom_column_num_to_label_map[data['num']] = data['label']
# Create Foreign Key triggers
if data['normalized']:
trigger = 'DELETE FROM %s WHERE book=OLD.id;'%lt
else:
trigger = 'DELETE FROM %s WHERE book=OLD.id;'%table
triggers.append(trigger)
if remove:
with self.conn:
for data in remove:
prints('WARNING: Custom column %r not found, removing.' %
data['label'])
self.execute('DELETE FROM custom_columns WHERE id=?',
(data['num'],))
if triggers:
with self.conn:
self.execute('''\
CREATE TEMP TRIGGER custom_books_delete_trg
AFTER DELETE ON books
BEGIN
%s
END;
'''%(' \n'.join(triggers)))
# Setup data adapters
def adapt_text(x, d):
if d['is_multiple']:
if x is None:
return []
if isinstance(x, (str, bytes)):
x = x.split(d['multiple_seps']['ui_to_list'])
x = [y.strip() for y in x if y.strip()]
x = [y.decode(preferred_encoding, 'replace') if not isinstance(y,
str) else y for y in x]
return [' '.join(y.split()) for y in x]
else:
return x if x is None or isinstance(x, str) else \
x.decode(preferred_encoding, 'replace')
def adapt_datetime(x, d):
if isinstance(x, (str, bytes)):
if isinstance(x, bytes):
x = x.decode(preferred_encoding, 'replace')
x = parse_date(x, assume_utc=False, as_utc=False)
return x
def adapt_bool(x, d):
if isinstance(x, (str, bytes)):
if isinstance(x, bytes):
x = x.decode(preferred_encoding, 'replace')
x = x.lower()
if x == 'true':
x = True
elif x == 'false':
x = False
elif x == 'none':
x = None
else:
x = bool(int(x))
return x
def adapt_enum(x, d):
v = adapt_text(x, d)
if not v:
v = None
return v
def adapt_number(x, d):
if x is None:
return None
if isinstance(x, (str, bytes)):
if isinstance(x, bytes):
x = x.decode(preferred_encoding, 'replace')
if x.lower() == 'none':
return None
if d['datatype'] == 'int':
return int(x)
return float(x)
self.custom_data_adapters = {
'float': adapt_number,
'int': adapt_number,
'rating':lambda x,d: x if x is None else min(10., max(0., float(x))),
'bool': adapt_bool,
'comments': lambda x,d: adapt_text(x, {'is_multiple':False}),
'datetime': adapt_datetime,
'text':adapt_text,
'series':adapt_text,
'enumeration': adapt_enum
}
# Create Tag Browser categories for custom columns
for k in sorted(self.custom_column_label_map):
v = self.custom_column_label_map[k]
if v['normalized']:
is_category = True
else:
is_category = False
is_m = v['multiple_seps']
tn = 'custom_column_{}'.format(v['num'])
self.field_metadata.add_custom_field(label=v['label'],
table=tn, column='value', datatype=v['datatype'],
colnum=v['num'], name=v['name'], display=v['display'],
is_multiple=is_m, is_category=is_category,
is_editable=v['editable'], is_csp=False)
# }}}
def initialize_tables(self): # {{{
tables = self.tables = {}
for col in ('title', 'sort', 'author_sort', 'series_index', 'comments',
'timestamp', 'pubdate', 'uuid', 'path', 'cover',
'last_modified'):
metadata = self.field_metadata[col].copy()
if col == 'comments':
metadata['table'], metadata['column'] = 'comments', 'text'
if not metadata['table']:
metadata['table'], metadata['column'] = 'books', ('has_cover'
if col == 'cover' else col)
if not metadata['column']:
metadata['column'] = col
tables[col] = (PathTable if col == 'path' else UUIDTable if col == 'uuid' else OneToOneTable)(col, metadata)
for col in ('series', 'publisher'):
tables[col] = ManyToOneTable(col, self.field_metadata[col].copy())
for col in ('authors', 'tags', 'formats', 'identifiers', 'languages', 'rating'):
cls = {
'authors':AuthorsTable,
'formats':FormatsTable,
'identifiers':IdentifiersTable,
'rating':RatingTable,
}.get(col, ManyToManyTable)
tables[col] = cls(col, self.field_metadata[col].copy())
tables['size'] = SizeTable('size', self.field_metadata['size'].copy())
self.FIELD_MAP = {
'id':0, 'title':1, 'authors':2, 'timestamp':3, 'size':4,
'rating':5, 'tags':6, 'comments':7, 'series':8, 'publisher':9,
'series_index':10, 'sort':11, 'author_sort':12, 'formats':13,
'path':14, 'pubdate':15, 'uuid':16, 'cover':17, 'au_map':18,
'last_modified':19, 'identifiers':20, 'languages':21,
}
for k,v in iteritems(self.FIELD_MAP):
self.field_metadata.set_field_record_index(k, v, prefer_custom=False)
base = max(itervalues(self.FIELD_MAP))
for label_ in sorted(self.custom_column_label_map):
data = self.custom_column_label_map[label_]
label = self.field_metadata.custom_field_prefix + label_
metadata = self.field_metadata[label].copy()
link_table = self.custom_table_names(data['num'])[1]
self.FIELD_MAP[data['num']] = base = base+1
self.field_metadata.set_field_record_index(label_, base,
prefer_custom=True)
if data['datatype'] == 'series':
# account for the series index column. Field_metadata knows that
# the series index is one larger than the series. If you change
# it here, be sure to change it there as well.
self.FIELD_MAP[str(data['num'])+'_index'] = base = base+1
self.field_metadata.set_field_record_index(label_+'_index', base,
prefer_custom=True)
if data['normalized']:
if metadata['is_multiple']:
tables[label] = ManyToManyTable(label, metadata,
link_table=link_table)
else:
tables[label] = ManyToOneTable(label, metadata,
link_table=link_table)
if metadata['datatype'] == 'series':
# Create series index table
label += '_index'
metadata = self.field_metadata[label].copy()
metadata['column'] = 'extra'
metadata['table'] = link_table
tables[label] = OneToOneTable(label, metadata)
else:
if data['datatype'] == 'composite':
tables[label] = CompositeTable(label, metadata)
else:
tables[label] = OneToOneTable(label, metadata)
self.FIELD_MAP['ondevice'] = base = base+1
self.field_metadata.set_field_record_index('ondevice', base, prefer_custom=False)
self.FIELD_MAP['marked'] = base = base+1
self.field_metadata.set_field_record_index('marked', base, prefer_custom=False)
self.FIELD_MAP['series_sort'] = base = base+1
self.field_metadata.set_field_record_index('series_sort', base, prefer_custom=False)
self.FIELD_MAP['in_tag_browser'] = base = base+1
self.field_metadata.set_field_record_index('in_tag_browser', base, prefer_custom=False)
# }}}
def initialize_notes(self):
from .notes.connect import Notes
self.notes = Notes(self)
def clear_notes_for_category_items(self, field_name, item_map):
for item_id, item_val in item_map.items():
self.notes.set_note(self.conn, field_name, item_id, item_val or '')
def delete_category_items(self, field_name, table_name, item_map, link_table_name='', link_col_name=''):
self.clear_notes_for_category_items(field_name, item_map)
bindings = tuple((x,) for x in item_map)
if link_table_name and link_col_name:
self.executemany(f'DELETE FROM {link_table_name} WHERE {link_col_name}=?', bindings)
self.executemany(f'DELETE FROM {table_name} WHERE id=?', bindings)
def rename_category_item(self, field_name, table_name, link_table_name, link_col_name, old_item_id, new_item_id, new_item_value):
self.notes.rename_note(self.conn, field_name, old_item_id, new_item_id, new_item_value or '')
# For custom series this means that the series index can
# potentially have duplicates/be incorrect, but there is no way to
# handle that in this context.
self.execute(f'UPDATE {link_table_name} SET {link_col_name}=? WHERE {link_col_name}=?; DELETE FROM {table_name} WHERE id=?',
(new_item_id, old_item_id, old_item_id))
def notes_for(self, field_name, item_id):
return self.notes.get_note(self.conn, field_name, item_id) or ''
def notes_data_for(self, field_name, item_id):
return self.notes.get_note_data(self.conn, field_name, item_id)
def get_all_items_that_have_notes(self, field_name):
return self.notes.get_all_items_that_have_notes(self.conn, field_name)
def set_notes_for(self, field, item_id, doc: str, searchable_text: str, resource_hashes, remove_unused_resources) -> int:
id_val = self.tables[field].id_map[item_id]
note_id = self.notes.set_note(self.conn, field, item_id, id_val, doc, resource_hashes, searchable_text)
if remove_unused_resources:
self.notes.remove_unreferenced_resources(self.conn)
return note_id
def unretire_note_for(self, field, item_id) -> int:
id_val = self.tables[field].id_map[item_id]
return self.notes.unretire(self.conn, field, item_id, id_val)
def add_notes_resource(self, path_or_stream, name, mtime=None) -> int:
return self.notes.add_resource(self.conn, path_or_stream, name, mtime=mtime)
def get_notes_resource(self, resource_hash) -> Optional[dict]:
return self.notes.get_resource_data(self.conn, resource_hash)
def notes_resources_used_by(self, field, item_id):
conn = self.conn
note_id = self.notes.note_id_for(conn, field, item_id)
if note_id is not None:
yield from self.notes.resources_used_by(conn, note_id)
def unretire_note(self, field, item_id, item_val):
return self.notes.unretire(self.conn, field, item_id, item_val)
def search_notes(self,
fts_engine_query, use_stemming, highlight_start, highlight_end, snippet_size, restrict_to_fields, return_text, process_each_result, limit
):
yield from self.notes.search(
self.conn, fts_engine_query, use_stemming, highlight_start, highlight_end, snippet_size, restrict_to_fields, return_text,
process_each_result, limit)
def export_notes_data(self, outfile):
import zipfile
with zipfile.ZipFile(outfile, mode='w') as zf:
pt = PersistentTemporaryFile()
try:
pt.close()
self.backup_notes_database(pt.name)
with open(pt.name, 'rb') as dbf:
zf.writestr('notes.db', dbf.read())
finally:
try:
os.remove(pt.name)
except OSError:
if not iswindows:
raise
time.sleep(1)
os.remove(pt.name)
self.notes.export_non_db_data(zf)
def restore_notes(self, report_progress):
self.notes.restore(self.conn, self.tables, report_progress)
def import_note(self, field, item_id, html, basedir, ctime, mtime):
id_val = self.tables[field].id_map[item_id]
return self.notes.import_note(self.conn, field, item_id, id_val, html, basedir, ctime, mtime)
def export_note(self, field, item_id):
return self.notes.export_note(self.conn, field, item_id)
def initialize_fts(self, dbref):
self.fts = None
if not self.prefs['fts_enabled']:
return
from .fts.connect import FTS
self.fts = FTS(dbref)
return self.fts
def enable_fts(self, dbref=None):
enabled = dbref is not None
self.prefs['fts_enabled'] = enabled
self.initialize_fts(dbref)
if self.fts is not None:
self.fts.dirty_existing()
return self.fts
@property
def fts_enabled(self):
return getattr(self, 'fts', None) is not None
@property
def fts_has_idle_workers(self):
return self.fts_enabled and self.fts.pool.num_of_idle_workers > 0
@property
def fts_num_of_workers(self):
return self.fts.pool.num_of_workers if self.fts_enabled else 0
@fts_num_of_workers.setter
def fts_num_of_workers(self, num):
if self.fts_enabled:
self.fts.pool.num_of_workers = num
def get_next_fts_job(self):
return self.fts.get_next_fts_job()
def reindex_fts(self):
if self.conn.fts_dbpath:
self.conn.execute('DETACH fts_db')
os.remove(self.conn.fts_dbpath)
self.conn.fts_dbpath = None
def remove_dirty_fts(self, book_id, fmt):
return self.fts.remove_dirty(book_id, fmt)
def queue_fts_job(self, book_id, fmt, path, fmt_size, fmt_hash, start_time):
return self.fts.queue_job(book_id, fmt, path, fmt_size, fmt_hash, start_time)
def commit_fts_result(self, book_id, fmt, fmt_size, fmt_hash, text, err_msg):
if self.fts is not None:
return self.fts.commit_result(book_id, fmt, fmt_size, fmt_hash, text, err_msg)
def fts_unindex(self, book_id, fmt=None):
self.fts.unindex(book_id, fmt=fmt)
def reindex_fts_book(self, book_id, *fmts):
return self.fts.dirty_book(book_id, *fmts)
def fts_search(self,
fts_engine_query, use_stemming, highlight_start, highlight_end, snippet_size, restrict_to_book_ids, return_text, process_each_result
):
yield from self.fts.search(
fts_engine_query, use_stemming, highlight_start, highlight_end, snippet_size, restrict_to_book_ids, return_text, process_each_result)
def shutdown_fts(self):
if self.fts_enabled:
self.fts.shutdown()
def join_fts(self):
if self.fts:
self.fts.pool.join()
self.fts = None
def get_connection(self):
return self.conn
@property
def conn(self):
if self._conn is None:
self._conn = Connection(self.dbpath)
self.is_closed = False
if self._exists and self.user_version == 0:
self._conn.close()
os.remove(self.dbpath)
self._conn = Connection(self.dbpath)
return self._conn
def execute(self, sql, bindings=None):
try:
return self.conn.cursor().execute(sql, bindings)
except apsw.IOError:
# This can happen if the computer was suspended see for example:
# https://bugs.launchpad.net/bugs/1286522. Try to reopen the db
if not self.conn.getautocommit():
raise # We are in a transaction, re-opening the db will fail anyway
self.reopen(force=True)
return self.conn.cursor().execute(sql, bindings)
def executemany(self, sql, sequence_of_bindings):
try:
with self.conn: # Disable autocommit mode, for performance
return self.conn.cursor().executemany(sql, sequence_of_bindings)
except apsw.IOError:
# This can happen if the computer was suspended see for example:
# https://bugs.launchpad.net/bugs/1286522. Try to reopen the db
if not self.conn.getautocommit():
raise # We are in a transaction, re-opening the db will fail anyway
self.reopen(force=True)
with self.conn: # Disable autocommit mode, for performance
return self.conn.cursor().executemany(sql, sequence_of_bindings)
def get(self, *args, **kw):
ans = self.execute(*args)
if kw.get('all', True):
return ans.fetchall()
try:
return next(ans)[0]
except (StopIteration, IndexError):
return None
def last_insert_rowid(self):
return self.conn.last_insert_rowid()
def custom_field_name(self, label=None, num=None):
if label is not None:
return self.field_metadata.custom_field_prefix + label
return self.field_metadata.custom_field_prefix + self.custom_column_num_to_label_map[num]
def custom_field_metadata(self, label=None, num=None):
if label is not None:
return self.custom_column_label_map[label]
return self.custom_column_num_map[num]
def set_custom_column_metadata(self, num, name=None, label=None, is_editable=None, display=None):
changed = False
if name is not None:
self.execute('UPDATE custom_columns SET name=? WHERE id=?', (name, num))
changed = True
if label is not None:
self.execute('UPDATE custom_columns SET label=? WHERE id=?', (label, num))
changed = True
if is_editable is not None:
self.execute('UPDATE custom_columns SET editable=? WHERE id=?', (bool(is_editable), num))
self.custom_column_num_map[num]['is_editable'] = bool(is_editable)
changed = True
if display is not None:
self.execute('UPDATE custom_columns SET display=? WHERE id=?', (json.dumps(display), num))
changed = True
# Note: the caller is responsible for scheduling a metadata backup if necessary
return changed
def create_custom_column(self, label, name, datatype, is_multiple, editable=True, display={}): # {{{
import re
if not label:
raise ValueError(_('No label was provided'))
if re.match(r'^\w*$', label) is None or not label[0].isalpha() or label.lower() != label:
raise ValueError(_('The label must contain only lower case letters, digits and underscores, and start with a letter'))
if datatype not in CUSTOM_DATA_TYPES:
raise ValueError('%r is not a supported data type'%datatype)
normalized = datatype not in ('datetime', 'comments', 'int', 'bool',
'float', 'composite')
is_multiple = is_multiple and datatype in ('text', 'composite')
self.execute(
('INSERT INTO '
'custom_columns(label,name,datatype,is_multiple,editable,display,normalized)'
'VALUES (?,?,?,?,?,?,?)'),
(label, name, datatype, is_multiple, editable, json.dumps(display), normalized))
num = self.conn.last_insert_rowid()
if datatype in ('rating', 'int'):
dt = 'INT'
elif datatype in ('text', 'comments', 'series', 'composite', 'enumeration'):
dt = 'TEXT'
elif datatype in ('float',):
dt = 'REAL'
elif datatype == 'datetime':
dt = 'timestamp'
elif datatype == 'bool':
dt = 'BOOL'
collate = 'COLLATE NOCASE' if dt == 'TEXT' else ''
table, lt = self.custom_table_names(num)
if normalized:
if datatype == 'series':
s_index = 'extra REAL,'
else:
s_index = ''
lines = [
'''\
CREATE TABLE %s(
id INTEGER PRIMARY KEY AUTOINCREMENT,
value %s NOT NULL %s,
link TEXT NOT NULL DEFAULT "",
UNIQUE(value));
'''%(table, dt, collate),
'CREATE INDEX %s_idx ON %s (value %s);'%(table, table, collate),
'''\
CREATE TABLE %s(
id INTEGER PRIMARY KEY AUTOINCREMENT,
book INTEGER NOT NULL,
value INTEGER NOT NULL,
%s
UNIQUE(book, value)
);'''%(lt, s_index),
'CREATE INDEX %s_aidx ON %s (value);'%(lt,lt),
'CREATE INDEX %s_bidx ON %s (book);'%(lt,lt),
'''\
CREATE TRIGGER fkc_update_{lt}_a
BEFORE UPDATE OF book ON {lt}
BEGIN
SELECT CASE
WHEN (SELECT id from books WHERE id=NEW.book) IS NULL
THEN RAISE(ABORT, 'Foreign key violation: book not in books')
END;
END;
CREATE TRIGGER fkc_update_{lt}_b
BEFORE UPDATE OF author ON {lt}
BEGIN
SELECT CASE
WHEN (SELECT id from {table} WHERE id=NEW.value) IS NULL
THEN RAISE(ABORT, 'Foreign key violation: value not in {table}')
END;
END;
CREATE TRIGGER fkc_insert_{lt}
BEFORE INSERT ON {lt}
BEGIN
SELECT CASE
WHEN (SELECT id from books WHERE id=NEW.book) IS NULL
THEN RAISE(ABORT, 'Foreign key violation: book not in books')
WHEN (SELECT id from {table} WHERE id=NEW.value) IS NULL
THEN RAISE(ABORT, 'Foreign key violation: value not in {table}')
END;
END;
CREATE TRIGGER fkc_delete_{lt}
AFTER DELETE ON {table}
BEGIN
DELETE FROM {lt} WHERE value=OLD.id;
END;
CREATE VIEW tag_browser_{table} AS SELECT
id,
value,
(SELECT COUNT(id) FROM {lt} WHERE value={table}.id) count,
(SELECT AVG(r.rating)
FROM {lt},
books_ratings_link as bl,
ratings as r
WHERE {lt}.value={table}.id and bl.book={lt}.book and
r.id = bl.rating and r.rating <> 0) avg_rating,
value AS sort
FROM {table};
CREATE VIEW tag_browser_filtered_{table} AS SELECT
id,
value,
(SELECT COUNT({lt}.id) FROM {lt} WHERE value={table}.id AND
books_list_filter(book)) count,
(SELECT AVG(r.rating)
FROM {lt},
books_ratings_link as bl,
ratings as r
WHERE {lt}.value={table}.id AND bl.book={lt}.book AND
r.id = bl.rating AND r.rating <> 0 AND
books_list_filter(bl.book)) avg_rating,
value AS sort
FROM {table};
'''.format(lt=lt, table=table),
]
else:
lines = [
'''\
CREATE TABLE %s(
id INTEGER PRIMARY KEY AUTOINCREMENT,
book INTEGER,
value %s NOT NULL %s,
UNIQUE(book));
'''%(table, dt, collate),
'CREATE INDEX %s_idx ON %s (book);'%(table, table),
'''\
CREATE TRIGGER fkc_insert_{table}
BEFORE INSERT ON {table}
BEGIN
SELECT CASE
WHEN (SELECT id from books WHERE id=NEW.book) IS NULL
THEN RAISE(ABORT, 'Foreign key violation: book not in books')
END;
END;
CREATE TRIGGER fkc_update_{table}
BEFORE UPDATE OF book ON {table}
BEGIN
SELECT CASE
WHEN (SELECT id from books WHERE id=NEW.book) IS NULL
THEN RAISE(ABORT, 'Foreign key violation: book not in books')
END;
END;
'''.format(table=table),
]
script = ' \n'.join(lines)
self.execute(script)
self.prefs.set('update_all_last_mod_dates_on_start', True)
return num
# }}}
def delete_custom_column(self, label=None, num=None):
data = self.custom_field_metadata(label, num)
self.execute('UPDATE custom_columns SET mark_for_delete=1 WHERE id=?', (data['num'],))
def close(self, force=True, unload_formatter_functions=True):
if getattr(self, '_conn', None) is not None:
if self.prefs['expire_old_trash_after'] == 0:
self.expire_old_trash(0)
if unload_formatter_functions:
try:
unload_user_template_functions(self.library_id)
except Exception:
pass
self._conn.close(force)
del self._conn
self.is_closed = True
def reopen(self, force=True):
self.close(force=force, unload_formatter_functions=False)
self._conn = None
self.conn
self.notes.reopen(self)
def dump_and_restore(self, callback=None, sql=None):
import codecs
from apsw import Shell
if callback is None:
def callback(x):
return x
uv = int(self.user_version)
with TemporaryFile(suffix='.sql') as fname:
if sql is None:
callback(_('Dumping database to SQL') + '...')
with codecs.open(fname, 'wb', encoding='utf-8') as buf:
shell = Shell(db=self.conn, stdout=buf)
shell.process_command('.dump')
else:
with open(fname, 'wb') as buf:
buf.write(sql if isinstance(sql, bytes) else sql.encode('utf-8'))
with TemporaryFile(suffix='_tmpdb.db', dir=os.path.dirname(self.dbpath)) as tmpdb:
callback(_('Restoring database from SQL') + '...')
with closing(Connection(tmpdb)) as conn:
shell = Shell(db=conn, encoding='utf-8')
shell.process_command('.read ' + fname.replace(os.sep, '/'))
conn.execute('PRAGMA user_version=%d;'%uv)
self.close(unload_formatter_functions=False)
try:
atomic_rename(tmpdb, self.dbpath)
finally:
self.reopen()
def vacuum(self, include_fts_db, include_notes_db):
self.execute('VACUUM')
if self.fts_enabled and include_fts_db:
self.fts.vacuum()
if include_notes_db:
self.notes.vacuum(self.conn)
@property
def user_version(self):
'''The user version of this database'''
return self.conn.get('PRAGMA user_version;', all=False)
@user_version.setter
def user_version(self, val):
self.execute('PRAGMA user_version=%d'%int(val))
def initialize_database(self):
metadata_sqlite = P('metadata_sqlite.sql', data=True,
allow_user_override=False).decode('utf-8')
cur = self.conn.cursor()
cur.execute('BEGIN EXCLUSIVE TRANSACTION')
try:
cur.execute(metadata_sqlite)
except:
cur.execute('ROLLBACK')
raise
else:
cur.execute('COMMIT')
if self.user_version == 0:
self.user_version = 1
# }}}
def normpath(self, path):
path = os.path.abspath(os.path.realpath(path))
if not self.is_case_sensitive:
path = os.path.normcase(path).lower()
return path
def is_deletable(self, path):
return path and not self.normpath(self.library_path).startswith(self.normpath(path))
def rmtree(self, path):
if self.is_deletable(path):
rmtree_with_retry(path)
def construct_path_name(self, book_id, title, author):
'''
Construct the directory name for this book based on its metadata.
'''
book_id = BOOK_ID_PATH_TEMPLATE.format(book_id)
l = self.PATH_LIMIT - (len(book_id) // 2) - 2
author = ascii_filename(author)[:l]
title = ascii_filename(title.lstrip())[:l].rstrip()
if not title:
title = 'Unknown'[:l]
try:
while author[-1] in (' ', '.'):
author = author[:-1]
except IndexError:
author = ''
if not author:
author = ascii_filename(_('Unknown'))
if author.upper() in WINDOWS_RESERVED_NAMES:
author += 'w'
return f'{author}/{title}{book_id}'
def construct_file_name(self, book_id, title, author, extlen):
'''
Construct the file name for this book based on its metadata.
'''
extlen = max(extlen, 14) # 14 accounts for ORIGINAL_EPUB
# The PATH_LIMIT on windows already takes into account the doubling
# (it is used to enforce the total path length limit, individual path
# components can be much longer than the total path length would allow on
# windows).
l = (self.PATH_LIMIT - (extlen // 2) - 2) if iswindows else ((self.PATH_LIMIT - extlen - 2) // 2)
if l < 5:
raise ValueError('Extension length too long: %d' % extlen)
author = ascii_filename(author)[:l]
title = ascii_filename(title.lstrip())[:l].rstrip()
if not title:
title = 'Unknown'[:l]
name = title + ' - ' + author
while name.endswith('.'):
name = name[:-1]
if not name:
name = ascii_filename(_('Unknown'))
return name
# Database layer API {{{
def custom_table_names(self, num):
return 'custom_column_%d'%num, 'books_custom_column_%d_link'%num
@property
def custom_tables(self):
return {x[0] for x in self.conn.get(
'SELECT name FROM sqlite_master WHERE type=\'table\' AND '
'(name GLOB \'custom_column_*\' OR name GLOB \'books_custom_column_*\')')}
@classmethod
def exists_at(cls, path):
return path and os.path.exists(os.path.join(path, 'metadata.db'))
@property
def library_id(self):
'''The UUID for this library. As long as the user only operates on libraries with calibre, it will be unique'''
if getattr(self, '_library_id_', None) is None:
ans = self.conn.get('SELECT uuid FROM library_id', all=False)
if ans is None:
ans = str(uuid.uuid4())
self.library_id = ans
else:
self._library_id_ = ans
return self._library_id_
@library_id.setter
def library_id(self, val):
self._library_id_ = str(val)
self.execute('''
DELETE FROM library_id;
INSERT INTO library_id (uuid) VALUES (?);
''', (self._library_id_,))
def last_modified(self):
''' Return last modified time as a UTC datetime object '''
return utcfromtimestamp(os.stat(self.dbpath).st_mtime)
def read_tables(self):
'''
Read all data from the db into the python in-memory tables
'''
with self.conn: # Use a single transaction, to ensure nothing modifies the db while we are reading
for table in itervalues(self.tables):
try:
table.read(self)
except:
prints('Failed to read table:', table.name)
import pprint
pprint.pprint(table.metadata)
raise
def find_path_for_book(self, book_id):
q = BOOK_ID_PATH_TEMPLATE.format(book_id)
for author_dir in os.scandir(self.library_path):
if not author_dir.is_dir():
continue
try:
book_dir_iter = os.scandir(author_dir.path)
except OSError:
pass
else:
for book_dir in book_dir_iter:
if book_dir.name.endswith(q) and book_dir.is_dir():
return book_dir.path
def format_abspath(self, book_id, fmt, fname, book_path, do_file_rename=True):
path = os.path.join(self.library_path, book_path)
fmt = ('.' + fmt.lower()) if fmt else ''
fmt_path = os.path.join(path, fname+fmt)
if os.path.exists(fmt_path):
return fmt_path
if not fmt:
return
q = fmt.lower()
try:
candidates = os.scandir(path)
except OSError:
return
with candidates:
for x in candidates:
if x.name.endswith(q) and x.is_file():
if not do_file_rename:
return x.path
x = x.path
with suppress(OSError):
atomic_rename(x, fmt_path)
return fmt_path
try:
shutil.move(x, fmt_path)
except (shutil.SameFileError, OSError):
# some other process synced in the file since the last
# os.path.exists()
return x
return fmt_path
def cover_abspath(self, book_id, path):
path = os.path.join(self.library_path, path)
fmt_path = os.path.join(path, COVER_FILE_NAME)
if os.path.exists(fmt_path):
return fmt_path
def is_path_inside_book_dir(self, path, book_relpath, sub_path):
book_path = os.path.abspath(os.path.join(self.library_path, book_relpath, sub_path))
book_path = os.path.normcase(get_long_path_name(book_path)).rstrip(os.sep)
path = os.path.normcase(get_long_path_name(os.path.abspath(path))).rstrip(os.sep)
return path.startswith(book_path + os.sep)
def apply_to_format(self, book_id, path, fname, fmt, func, missing_value=None):
path = self.format_abspath(book_id, fmt, fname, path)
if path is None:
return missing_value
with open(path, 'r+b') as f:
return func(f)
def format_hash(self, book_id, fmt, fname, path):
path = self.format_abspath(book_id, fmt, fname, path)
if path is None:
raise NoSuchFormat('Record %d has no fmt: %s'%(book_id, fmt))
sha = hashlib.sha256()
with open(path, 'rb') as f:
while True:
raw = f.read(SPOOL_SIZE)
sha.update(raw)
if len(raw) < SPOOL_SIZE:
break
return sha.hexdigest()
def format_metadata(self, book_id, fmt, fname, path):
path = self.format_abspath(book_id, fmt, fname, path)
ans = {}
if path is not None:
stat = os.stat(path)
ans['path'] = path
ans['size'] = stat.st_size
ans['mtime'] = utcfromtimestamp(stat.st_mtime)
return ans
def has_format(self, book_id, fmt, fname, path):
return self.format_abspath(book_id, fmt, fname, path) is not None
def is_format_accessible(self, book_id, fmt, fname, path):
fpath = self.format_abspath(book_id, fmt, fname, path)
return fpath and os.access(fpath, os.R_OK | os.W_OK)
def rename_format_file(self, book_id, src_fname, src_fmt, dest_fname, dest_fmt, path):
src_path = self.format_abspath(book_id, src_fmt, src_fname, path)
dest_path = self.format_abspath(book_id, dest_fmt, dest_fname, path)
atomic_rename(src_path, dest_path)
return os.path.getsize(dest_path)
def remove_formats(self, remove_map, metadata_map):
self.ensure_trash_dir()
removed_map = {}
for book_id, removals in iteritems(remove_map):
paths = set()
removed_map[book_id] = set()
for fmt, fname, path in removals:
path = self.format_abspath(book_id, fmt, fname, path)
if path:
paths.add(path)
removed_map[book_id].add(fmt.upper())
if paths:
self.move_book_files_to_trash(book_id, paths, metadata_map[book_id])
return removed_map
def cover_last_modified(self, path):
path = os.path.abspath(os.path.join(self.library_path, path, COVER_FILE_NAME))
try:
return utcfromtimestamp(os.stat(path).st_mtime)
except OSError:
pass # Cover doesn't exist
def copy_cover_to(self, path, dest, windows_atomic_move=None, use_hardlink=False, report_file_size=None):
path = os.path.abspath(os.path.join(self.library_path, path, COVER_FILE_NAME))
if windows_atomic_move is not None:
if not isinstance(dest, string_or_bytes):
raise Exception('Error, you must pass the dest as a path when'
' using windows_atomic_move')
if os.access(path, os.R_OK) and dest and not samefile(dest, path):
windows_atomic_move.copy_path_to(path, dest)
return True
else:
if os.access(path, os.R_OK):
try:
f = open(path, 'rb')
except OSError:
if iswindows:
time.sleep(0.2)
f = open(path, 'rb')
with f:
if hasattr(dest, 'write'):
if report_file_size is not None:
f.seek(0, os.SEEK_END)
report_file_size(f.tell())
f.seek(0)
shutil.copyfileobj(f, dest)
if hasattr(dest, 'flush'):
dest.flush()
return True
elif dest and not samefile(dest, path):
if use_hardlink:
try:
hardlink_file(path, dest)
return True
except:
pass
with open(dest, 'wb') as d:
shutil.copyfileobj(f, d)
return True
return False
def cover_or_cache(self, path, timestamp, as_what='bytes'):
path = os.path.abspath(os.path.join(self.library_path, path, COVER_FILE_NAME))
try:
stat = os.stat(path)
except OSError:
return False, None, None
if abs(timestamp - stat.st_mtime) < 0.1:
return True, None, None
try:
f = open(path, 'rb')
except OSError:
if iswindows:
time.sleep(0.2)
f = open(path, 'rb')
with f:
if as_what == 'pil_image':
from PIL import Image
data = Image.open(f)
data.load()
else:
data = f.read()
return True, data, stat.st_mtime
def compress_covers(self, path_map, jpeg_quality, progress_callback):
cpath_map = {}
if not progress_callback:
def progress_callback(book_id, old_sz, new_sz):
return None
for book_id, path in path_map.items():
path = os.path.abspath(os.path.join(self.library_path, path, COVER_FILE_NAME))
try:
sz = os.path.getsize(path)
except OSError:
progress_callback(book_id, 0, 'ENOENT')
else:
cpath_map[book_id] = (path, sz)
from calibre.db.covers import compress_covers
compress_covers(cpath_map, jpeg_quality, progress_callback)
def set_cover(self, book_id, path, data, no_processing=False):
path = os.path.abspath(os.path.join(self.library_path, path))
if not os.path.exists(path):
os.makedirs(path)
path = os.path.join(path, COVER_FILE_NAME)
if callable(getattr(data, 'save', None)):
from calibre.gui2 import pixmap_to_data
data = pixmap_to_data(data)
elif callable(getattr(data, 'read', None)):
data = data.read()
if data is None:
if os.path.exists(path):
try:
os.remove(path)
except OSError:
if iswindows:
time.sleep(0.2)
os.remove(path)
else:
if no_processing:
with open(path, 'wb') as f:
f.write(data)
else:
from calibre.utils.img import save_cover_data_to
try:
save_cover_data_to(data, path)
except OSError:
if iswindows:
time.sleep(0.2)
save_cover_data_to(data, path)
def copy_format_to(self, book_id, fmt, fname, path, dest,
windows_atomic_move=None, use_hardlink=False, report_file_size=None):
path = self.format_abspath(book_id, fmt, fname, path)
if path is None:
return False
if windows_atomic_move is not None:
if not isinstance(dest, string_or_bytes):
raise Exception('Error, you must pass the dest as a path when'
' using windows_atomic_move')
if dest:
if samefile(dest, path):
# Ensure that the file has the same case as dest
try:
if path != dest:
os.rename(path, dest)
except:
pass # Nothing too catastrophic happened, the cases mismatch, that's all
else:
windows_atomic_move.copy_path_to(path, dest)
else:
if hasattr(dest, 'write'):
with open(path, 'rb') as f:
if report_file_size is not None:
f.seek(0, os.SEEK_END)
report_file_size(f.tell())
f.seek(0)
shutil.copyfileobj(f, dest)
if hasattr(dest, 'flush'):
dest.flush()
elif dest:
if samefile(dest, path):
if not self.is_case_sensitive and path != dest:
# Ensure that the file has the same case as dest
try:
os.rename(path, dest)
except OSError:
pass # Nothing too catastrophic happened, the cases mismatch, that's all
else:
if use_hardlink:
try:
hardlink_file(path, dest)
return True
except:
pass
with open(path, 'rb') as f, open(make_long_path_useable(dest), 'wb') as d:
shutil.copyfileobj(f, d)
return True
def windows_check_if_files_in_use(self, paths):
'''
Raises an EACCES IOError if any of the files in the specified folders
are opened in another program on windows.
'''
if iswindows:
for path in paths:
spath = os.path.join(self.library_path, *path.split('/'))
if os.path.exists(spath):
windows_check_if_files_in_use(spath)
def add_format(self, book_id, fmt, stream, title, author, path, current_name, mtime=None):
fmt = ('.' + fmt.lower()) if fmt else ''
fname = self.construct_file_name(book_id, title, author, len(fmt))
path = os.path.join(self.library_path, path)
dest = os.path.join(path, fname + fmt)
if not os.path.exists(path):
os.makedirs(path)
size = 0
if current_name is not None:
old_path = os.path.join(path, current_name + fmt)
if old_path != dest:
# Ensure that the old format file is not orphaned, this can
# happen if the algorithm in construct_file_name is changed.
try:
# rename rather than remove, so that if something goes
# wrong in the rest of this function, at least the file is
# not deleted
os.replace(old_path, dest)
except OSError as e:
if getattr(e, 'errno', None) != errno.ENOENT:
# Failing to rename the old format will at worst leave a
# harmless orphan, so log and ignore the error
import traceback
traceback.print_exc()
if isinstance(stream, str) and stream:
try:
os.replace(stream, dest)
except OSError:
if iswindows:
time.sleep(1)
os.replace(stream, dest)
else:
raise
size = os.path.getsize(dest)
elif (not getattr(stream, 'name', False) or not samefile(dest, stream.name)):
with open(dest, 'wb') as f:
shutil.copyfileobj(stream, f)
size = f.tell()
if mtime is not None:
os.utime(dest, (mtime, mtime))
elif os.path.exists(dest):
size = os.path.getsize(dest)
if mtime is not None:
os.utime(dest, (mtime, mtime))
return size, fname
def update_path(self, book_id, title, author, path_field, formats_field):
current_path = path_field.for_book(book_id, default_value='')
path = self.construct_path_name(book_id, title, author)
formats = formats_field.for_book(book_id, default_value=())
try:
extlen = max(len(fmt) for fmt in formats) + 1
except ValueError:
extlen = 10
fname = self.construct_file_name(book_id, title, author, extlen)
def rename_format_files():
changed = False
for fmt in formats:
name = formats_field.format_fname(book_id, fmt)
if name and name != fname:
changed = True
break
if changed:
rename_map = {}
for fmt in formats:
current_fname = formats_field.format_fname(book_id, fmt)
current_fmt_path = self.format_abspath(book_id, fmt, current_fname, current_path, do_file_rename=False)
if current_fmt_path:
new_fmt_path = os.path.abspath(os.path.join(os.path.dirname(current_fmt_path), fname + '.' + fmt.lower()))
if current_fmt_path != new_fmt_path:
rename_map[current_fmt_path] = new_fmt_path
if rename_map:
rename_files(rename_map)
return changed
def update_paths_in_db():
with self.conn:
for fmt in formats:
formats_field.table.set_fname(book_id, fmt, fname, self)
path_field.table.set_path(book_id, path, self)
if not current_path:
update_paths_in_db()
return
if path == current_path:
# Only format paths have possibly changed
if rename_format_files():
update_paths_in_db()
return
spath = os.path.join(self.library_path, *current_path.split('/'))
tpath = os.path.join(self.library_path, *path.split('/'))
if samefile(spath, tpath):
# format paths changed and case of path to book folder changed
rename_format_files()
update_paths_in_db()
curpath = self.library_path
c1, c2 = current_path.split('/'), path.split('/')
if not self.is_case_sensitive and len(c1) == len(c2):
# On case-insensitive systems, title and author renames that only
# change case don't cause any changes to the directories in the file
# system. This can lead to having the directory names not match the
# title/author, which leads to trouble when libraries are copied to
# a case-sensitive system. The following code attempts to fix this
# by checking each segment. If they are different because of case,
# then rename the segment. Note that the code above correctly
# handles files in the directories, so no need to do them here.
for oldseg, newseg in zip(c1, c2):
if oldseg.lower() == newseg.lower() and oldseg != newseg:
try:
os.replace(os.path.join(curpath, oldseg), os.path.join(curpath, newseg))
except OSError:
break # Fail silently since nothing catastrophic has happened
curpath = os.path.join(curpath, newseg)
return
with suppress(FileNotFoundError):
self.rmtree(tpath)
lfmts = tuple(fmt.lower() for fmt in formats)
existing_format_filenames = {}
for fmt in lfmts:
current_fname = formats_field.format_fname(book_id, fmt)
current_fmt_path = self.format_abspath(book_id, fmt, current_fname, current_path, do_file_rename=False)
if current_fmt_path:
existing_format_filenames[os.path.basename(current_fmt_path)] = fmt
def transform_format_filenames(src_path, dest_path):
src_dir, src_filename = os.path.split(os.path.abspath(src_path))
if src_dir != spath:
return dest_path
fmt = existing_format_filenames.get(src_filename)
if not fmt:
return dest_path
return os.path.join(os.path.dirname(dest_path), fname + '.' + fmt)
if os.path.exists(spath):
copy_tree(os.path.abspath(spath), tpath, delete_source=True, transform_destination_filename=transform_format_filenames)
parent = os.path.dirname(spath)
with suppress(OSError):
os.rmdir(parent) # remove empty parent directory
else:
os.makedirs(tpath)
update_paths_in_db()
def copy_extra_file_to(self, book_id, book_path, relpath, stream_or_path):
full_book_path = os.path.abspath(os.path.join(self.library_path, book_path))
extra_file_path = os.path.abspath(os.path.join(full_book_path, relpath))
if not extra_file_path.startswith(full_book_path):
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), relpath)
src_path = make_long_path_useable(extra_file_path)
if isinstance(stream_or_path, str):
shutil.copy2(src_path, make_long_path_useable(stream_or_path))
else:
with open(src_path, 'rb') as src:
shutil.copyfileobj(src, stream_or_path)
def iter_extra_files(self, book_id, book_path, formats_field, yield_paths=False, pattern=''):
known_files = {COVER_FILE_NAME, METADATA_FILE_NAME}
if '/' not in pattern:
for fmt in formats_field.for_book(book_id, default_value=()):
fname = formats_field.format_fname(book_id, fmt)
fpath = self.format_abspath(book_id, fmt, fname, book_path, do_file_rename=False)
if fpath:
known_files.add(os.path.basename(fpath))
full_book_path = os.path.abspath(os.path.join(self.library_path, book_path))
if pattern:
from pathlib import Path
def iterator():
p = Path(full_book_path)
for x in p.glob(pattern):
yield str(x)
else:
def iterator():
for dirpath, dirnames, filenames in os.walk(full_book_path):
for fname in filenames:
path = os.path.join(dirpath, fname)
yield path
for path in iterator():
if os.access(path, os.R_OK):
relpath = os.path.relpath(path, full_book_path)
relpath = relpath.replace(os.sep, '/')
if relpath not in known_files:
try:
stat_result = os.stat(path)
except OSError:
continue
if stat.S_ISDIR(stat_result.st_mode):
continue
if yield_paths:
yield relpath, path, stat_result
else:
try:
src = open(path, 'rb')
except OSError:
if iswindows:
time.sleep(1)
src = open(path, 'rb')
with src:
yield relpath, src, stat_result
def rename_extra_file(self, relpath, newrelpath, book_path, replace=True):
bookdir = os.path.join(self.library_path, book_path)
src = os.path.abspath(os.path.join(bookdir, relpath))
dest = os.path.abspath(os.path.join(bookdir, newrelpath))
src, dest = make_long_path_useable(src), make_long_path_useable(dest)
if src == dest or not os.path.exists(src):
return False
if not replace and os.path.exists(dest) and not os.path.samefile(src, dest):
return False
try:
os.replace(src, dest)
except FileNotFoundError:
os.makedirs(os.path.dirname(dest), exist_ok=True)
os.replace(src, dest)
return True
def add_extra_file(self, relpath, stream, book_path, replace=True, auto_rename=False):
bookdir = os.path.join(self.library_path, book_path)
dest = os.path.abspath(os.path.join(bookdir, relpath))
if not replace and os.path.exists(make_long_path_useable(dest)):
if not auto_rename:
return None
dirname, basename = os.path.split(dest)
num = 0
while True:
mdir = 'merge conflict'
if num:
mdir += f' {num}'
candidate = os.path.join(dirname, mdir, basename)
if not os.path.exists(make_long_path_useable(candidate)):
dest = candidate
break
num += 1
if isinstance(stream, str):
try:
shutil.copy2(make_long_path_useable(stream), make_long_path_useable(dest))
except FileNotFoundError:
os.makedirs(make_long_path_useable(os.path.dirname(dest)), exist_ok=True)
shutil.copy2(make_long_path_useable(stream), make_long_path_useable(dest))
else:
try:
d = open(make_long_path_useable(dest), 'wb')
except FileNotFoundError:
os.makedirs(make_long_path_useable(os.path.dirname(dest)), exist_ok=True)
d = open(make_long_path_useable(dest), 'wb')
with d:
shutil.copyfileobj(stream, d)
return os.path.relpath(dest, bookdir).replace(os.sep, '/')
def write_backup(self, path, raw):
path = os.path.abspath(os.path.join(self.library_path, path, METADATA_FILE_NAME))
try:
with open(path, 'wb') as f:
f.write(raw)
except OSError:
exc_info = sys.exc_info()
try:
os.makedirs(os.path.dirname(path))
except OSError as err:
if err.errno == errno.EEXIST:
# Parent directory already exists, re-raise original exception
reraise(*exc_info)
raise
finally:
del exc_info
with open(path, 'wb') as f:
f.write(raw)
def read_backup(self, path):
path = os.path.abspath(os.path.join(self.library_path, path, METADATA_FILE_NAME))
with open(path, 'rb') as f:
return f.read()
@property
def trash_dir(self):
return os.path.abspath(os.path.join(self.library_path, TRASH_DIR_NAME))
def clear_trash_dir(self):
tdir = self.trash_dir
if os.path.exists(tdir):
self.rmtree(tdir)
self.ensure_trash_dir()
def ensure_trash_dir(self, during_init=False):
tdir = self.trash_dir
os.makedirs(os.path.join(tdir, 'b'), exist_ok=True)
os.makedirs(os.path.join(tdir, 'f'), exist_ok=True)
if iswindows:
import calibre_extensions.winutil as winutil
winutil.set_file_attributes(tdir, winutil.FILE_ATTRIBUTE_HIDDEN | winutil.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED)
if time.time() - self.last_expired_trash_at >= 3600:
self.expire_old_trash(during_init=during_init)
def delete_trash_entry(self, book_id, category):
self.ensure_trash_dir()
path = os.path.join(self.trash_dir, category, str(book_id))
if os.path.exists(path):
self.rmtree(path)
def expire_old_trash(self, expire_age_in_seconds=-1, during_init=False):
if expire_age_in_seconds < 0:
expire_age_in_seconds = max(1 * 24 * 3600, float(self.prefs['expire_old_trash_after']))
self.last_expired_trash_at = now = time.time()
removals = []
for base in ('b', 'f'):
base = os.path.join(self.trash_dir, base)
for x in os.scandir(base):
if x.is_dir(follow_symlinks=False):
try:
st = x.stat(follow_symlinks=False)
mtime = st.st_mtime
except OSError:
mtime = 0
if mtime + expire_age_in_seconds <= now or expire_age_in_seconds <= 0:
removals.append(x.path)
for x in removals:
try:
rmtree_with_retry(x)
except OSError:
if not during_init:
raise
import traceback
traceback.print_exc()
def move_book_to_trash(self, book_id, book_dir_abspath):
dest = os.path.join(self.trash_dir, 'b', str(book_id))
if os.path.exists(dest):
rmtree_with_retry(dest)
copy_tree(book_dir_abspath, dest, delete_source=True)
def move_book_files_to_trash(self, book_id, format_abspaths, metadata):
dest = os.path.join(self.trash_dir, 'f', str(book_id))
if not os.path.exists(dest):
os.makedirs(dest)
fmap = {}
for path in format_abspaths:
ext = path.rpartition('.')[-1].lower()
fmap[path] = os.path.join(dest, ext)
with open(os.path.join(dest, 'metadata.json'), 'wb') as f:
f.write(json.dumps(metadata).encode('utf-8'))
copy_files(fmap, delete_source=True)
def get_metadata_for_trash_book(self, book_id, read_annotations=True):
from .restore import read_opf
bdir = os.path.join(self.trash_dir, 'b', str(book_id))
if not os.path.isdir(bdir):
raise ValueError(f'The book {book_id} not present in the trash folder')
mi, _, annotations = read_opf(bdir, read_annotations=read_annotations)
formats = []
for x in os.scandir(bdir):
if x.is_file() and x.name not in (COVER_FILE_NAME, METADATA_FILE_NAME) and '.' in x.name:
try:
size = x.stat(follow_symlinks=False).st_size
except OSError:
continue
fname, ext = os.path.splitext(x.name)
formats.append((ext[1:].upper(), size, fname))
return mi, annotations, formats
def move_book_from_trash(self, book_id, path):
bdir = os.path.join(self.trash_dir, 'b', str(book_id))
if not os.path.isdir(bdir):
raise ValueError(f'The book {book_id} not present in the trash folder')
dest = os.path.abspath(os.path.join(self.library_path, path))
copy_tree(bdir, dest, delete_source=True)
def copy_book_from_trash(self, book_id, dest):
bdir = os.path.join(self.trash_dir, 'b', str(book_id))
if not os.path.isdir(bdir):
raise ValueError(f'The book {book_id} not present in the trash folder')
copy_tree(bdir, dest, delete_source=False)
def path_for_trash_format(self, book_id, fmt):
bdir = os.path.join(self.trash_dir, 'f', str(book_id))
if not os.path.isdir(bdir):
return ''
path = os.path.join(bdir, fmt.lower())
if not os.path.exists(path):
path = ''
return path
def remove_trash_formats_dir_if_empty(self, book_id):
bdir = os.path.join(self.trash_dir, 'f', str(book_id))
if os.path.isdir(bdir) and len(os.listdir(bdir)) <= 1: # dont count metadata.json
self.rmtree(bdir)
def list_trash_entries(self):
from calibre.ebooks.metadata.opf2 import OPF
self.ensure_trash_dir()
books, files = [], []
base = os.path.join(self.trash_dir, 'b')
unknown = _('Unknown')
au = (unknown,)
for x in os.scandir(base):
if x.is_dir(follow_symlinks=False):
try:
book_id = int(x.name)
mtime = x.stat(follow_symlinks=False).st_mtime
with open(make_long_path_useable(os.path.join(x.path, METADATA_FILE_NAME)), 'rb') as opf_stream:
opf = OPF(opf_stream, basedir=x.path)
except Exception:
import traceback
traceback.print_exc()
continue
books.append(TrashEntry(book_id, opf.title or unknown, (opf.authors or au)[0], os.path.join(x.path, COVER_FILE_NAME), mtime))
base = os.path.join(self.trash_dir, 'f')
um = {'title': unknown, 'authors': au}
for x in os.scandir(base):
if x.is_dir(follow_symlinks=False):
try:
book_id = int(x.name)
mtime = x.stat(follow_symlinks=False).st_mtime
except Exception:
continue
formats = set()
metadata = um
for f in os.scandir(x.path):
if f.is_file(follow_symlinks=False):
if f.name == 'metadata.json':
try:
with open(f.path, 'rb') as mf:
metadata = json.loads(mf.read())
except Exception:
import traceback
traceback.print_exc()
continue
else:
formats.add(f.name.upper())
if formats:
files.append(TrashEntry(book_id, metadata.get('title') or unknown, (metadata.get('authors') or au)[0], '', mtime, tuple(formats)))
return books, files
def remove_books(self, path_map, permanent=False):
self.ensure_trash_dir()
self.executemany(
'DELETE FROM books WHERE id=?', [(x,) for x in path_map])
parent_paths = set()
for book_id, path in path_map.items():
if path:
path = os.path.abspath(os.path.join(self.library_path, path))
if os.path.exists(path) and self.is_deletable(path):
self.rmtree(path) if permanent else self.move_book_to_trash(book_id, path)
parent_paths.add(os.path.dirname(path))
for path in parent_paths:
remove_dir_if_empty(path, ignore_metadata_caches=True)
def add_custom_data(self, name, val_map, delete_first):
if delete_first:
self.execute('DELETE FROM books_plugin_data WHERE name=?', (name, ))
self.executemany(
'INSERT OR REPLACE INTO books_plugin_data (book, name, val) VALUES (?, ?, ?)',
[(book_id, name, json.dumps(val, default=to_json))
for book_id, val in iteritems(val_map)])
def get_custom_book_data(self, name, book_ids, default=None):
book_ids = frozenset(book_ids)
def safe_load(val):
try:
return json.loads(val, object_hook=from_json)
except:
return default
if len(book_ids) == 1:
bid = next(iter(book_ids))
ans = {book_id:safe_load(val) for book_id, val in
self.execute('SELECT book, val FROM books_plugin_data WHERE book=? AND name=?', (bid, name))}
return ans or {bid:default}
ans = {}
for book_id, val in self.execute(
'SELECT book, val FROM books_plugin_data WHERE name=?', (name,)):
if not book_ids or book_id in book_ids:
val = safe_load(val)
ans[book_id] = val
return ans
def delete_custom_book_data(self, name, book_ids):
if book_ids:
self.executemany('DELETE FROM books_plugin_data WHERE book=? AND name=?',
[(book_id, name) for book_id in book_ids])
else:
self.execute('DELETE FROM books_plugin_data WHERE name=?', (name,))
def dirtied_books(self):
for (book_id,) in self.execute('SELECT book FROM metadata_dirtied'):
yield book_id
def dirty_books(self, book_ids):
self.executemany('INSERT OR IGNORE INTO metadata_dirtied (book) VALUES (?)', ((x,) for x in book_ids))
def mark_book_as_clean(self, book_id):
self.execute('DELETE FROM metadata_dirtied WHERE book=?', (book_id,))
def get_ids_for_custom_book_data(self, name):
return frozenset(r[0] for r in self.execute('SELECT book FROM books_plugin_data WHERE name=?', (name,)))
def annotations_for_book(self, book_id, fmt, user_type, user):
yield from annotations_for_book(self.conn, book_id, fmt, user_type, user)
def search_annotations(self,
fts_engine_query, use_stemming, highlight_start, highlight_end, snippet_size, annotation_type,
restrict_to_book_ids, restrict_to_user, ignore_removed=False
):
fts_engine_query = unicode_normalize(fts_engine_query)
fts_table = 'annotations_fts_stemmed' if use_stemming else 'annotations_fts'
text = 'annotations.searchable_text'
data = []
if highlight_start is not None and highlight_end is not None:
if snippet_size is not None:
text = "snippet({fts_table}, 0, ?, ?, '…', {snippet_size})".format(
fts_table=fts_table, snippet_size=max(1, min(snippet_size, 64)))
else:
text = f"highlight({fts_table}, 0, ?, ?)"
data.append(highlight_start)
data.append(highlight_end)
query = 'SELECT {0}.id, {0}.book, {0}.format, {0}.user_type, {0}.user, {0}.annot_data, {1} FROM {0} '
query = query.format('annotations', text)
query += ' JOIN {fts_table} ON annotations.id = {fts_table}.rowid'.format(fts_table=fts_table)
query += f' WHERE {fts_table} MATCH ?'
data.append(fts_engine_query)
if restrict_to_user:
query += ' AND annotations.user_type = ? AND annotations.user = ?'
data += list(restrict_to_user)
if annotation_type:
query += ' AND annotations.annot_type = ? '
data.append(annotation_type)
query += f' ORDER BY {fts_table}.rank '
ls = json.loads
try:
for (rowid, book_id, fmt, user_type, user, annot_data, text) in self.execute(query, tuple(data)):
if restrict_to_book_ids is not None and book_id not in restrict_to_book_ids:
continue
try:
parsed_annot = ls(annot_data)
except Exception:
continue
if ignore_removed and parsed_annot.get('removed'):
continue
yield {
'id': rowid,
'book_id': book_id,
'format': fmt,
'user_type': user_type,
'user': user,
'text': text,
'annotation': parsed_annot,
}
except apsw.SQLError as e:
raise FTSQueryError(fts_engine_query, query, e)
def all_annotations_for_book(self, book_id, ignore_removed=False):
for (fmt, user_type, user, data) in self.execute(
'SELECT format, user_type, user, annot_data FROM annotations WHERE book=?', (book_id,)
):
try:
annot = json.loads(data)
except Exception:
pass
if not ignore_removed or not annot.get('removed'):
yield {'format': fmt, 'user_type': user_type, 'user': user, 'annotation': annot}
def delete_annotations(self, annot_ids):
replacements = []
removals = []
now = utcnow()
ts = now.isoformat()
timestamp = (now - EPOCH).total_seconds()
for annot_id in annot_ids:
for (raw_annot_data, annot_type) in self.execute(
'SELECT annot_data, annot_type FROM annotations WHERE id=?', (annot_id,)
):
try:
annot_data = json.loads(raw_annot_data)
except Exception:
removals.append((annot_id,))
continue
now = utcnow()
new_annot = {'removed': True, 'timestamp': ts, 'type': annot_type}
uuid = annot_data.get('uuid')
if uuid is not None:
new_annot['uuid'] = uuid
else:
new_annot['title'] = annot_data['title']
replacements.append((json.dumps(new_annot), timestamp, annot_id))
if replacements:
self.executemany("UPDATE annotations SET annot_data=?, timestamp=?, searchable_text='' WHERE id=?", replacements)
if removals:
self.executemany('DELETE FROM annotations WHERE id=?', removals)
def update_annotations(self, annot_id_map):
now = utcnow()
ts = now.isoformat()
timestamp = (now - EPOCH).total_seconds()
with self.conn:
for annot_id, annot in annot_id_map.items():
atype = annot['type']
aid, text = annot_db_data(annot)
if aid is not None:
annot['timestamp'] = ts
self.execute('UPDATE annotations SET annot_data=?, timestamp=?, annot_type=?, searchable_text=?, annot_id=? WHERE id=?',
(json.dumps(annot), timestamp, atype, text, aid, annot_id))
def all_annotations(self, restrict_to_user=None, limit=None, annotation_type=None, ignore_removed=False, restrict_to_book_ids=None):
ls = json.loads
q = 'SELECT id, book, format, user_type, user, annot_data FROM annotations'
data = []
restrict_clauses = []
if restrict_to_user is not None:
data.extend(restrict_to_user)
restrict_clauses.append(' user_type = ? AND user = ?')
if annotation_type:
data.append(annotation_type)
restrict_clauses.append(' annot_type = ? ')
if restrict_clauses:
q += ' WHERE ' + ' AND '.join(restrict_clauses)
q += ' ORDER BY timestamp DESC '
count = 0
for (rowid, book_id, fmt, user_type, user, annot_data) in self.execute(q, tuple(data)):
if restrict_to_book_ids is not None and book_id not in restrict_to_book_ids:
continue
try:
annot = ls(annot_data)
atype = annot['type']
except Exception:
continue
if ignore_removed and annot.get('removed'):
continue
text = ''
if atype == 'bookmark':
text = annot['title']
elif atype == 'highlight':
text = annot.get('highlighted_text') or ''
yield {
'id': rowid,
'book_id': book_id,
'format': fmt,
'user_type': user_type,
'user': user,
'text': text,
'annotation': annot,
}
count += 1
if limit is not None and count >= limit:
break
def all_annotation_users(self):
return self.execute('SELECT DISTINCT user_type, user FROM annotations')
def all_annotation_types(self):
for x in self.execute('SELECT DISTINCT annot_type FROM annotations'):
yield x[0]
def set_annotations_for_book(self, book_id, fmt, annots_list, user_type='local', user='viewer'):
try:
with self.conn: # Disable autocommit mode, for performance
save_annotations_for_book(self.conn.cursor(), book_id, fmt, annots_list, user_type, user)
except apsw.IOError:
# This can happen if the computer was suspended see for example:
# https://bugs.launchpad.net/bugs/1286522. Try to reopen the db
if not self.conn.getautocommit():
raise # We are in a transaction, re-opening the db will fail anyway
self.reopen(force=True)
with self.conn: # Disable autocommit mode, for performance
save_annotations_for_book(self.conn.cursor(), book_id, fmt, annots_list, user_type, user)
def dirty_books_with_dirtied_annotations(self):
with self.conn:
self.execute('INSERT or IGNORE INTO metadata_dirtied(book) SELECT book FROM annotations_dirtied;')
changed = self.conn.changes() > 0
if changed:
self.execute('DELETE FROM annotations_dirtied')
return changed
def annotation_count_for_book(self, book_id):
for (count,) in self.execute('''
SELECT count(id) FROM annotations
WHERE book=? AND json_extract(annot_data, '$.removed') IS NULL
''', (book_id,)):
return count
return 0
def reindex_annotations(self):
self.execute('''
INSERT INTO {0}({0}) VALUES('rebuild');
INSERT INTO {1}({1}) VALUES('rebuild');
'''.format('annotations_fts', 'annotations_fts_stemmed'))
def conversion_options(self, book_id, fmt):
for (data,) in self.conn.get('SELECT data FROM conversion_options WHERE book=? AND format=?', (book_id, fmt.upper())):
if data:
try:
return unpickle_binary_string(bytes(data))
except Exception:
pass
def has_conversion_options(self, ids, fmt='PIPE'):
ids = frozenset(ids)
with self.conn:
self.execute('DROP TABLE IF EXISTS conversion_options_temp; CREATE TEMP TABLE conversion_options_temp (id INTEGER PRIMARY KEY);')
self.executemany('INSERT INTO conversion_options_temp VALUES (?)', [(x,) for x in ids])
for (book_id,) in self.conn.get(
'SELECT book FROM conversion_options WHERE format=? AND book IN (SELECT id FROM conversion_options_temp)', (fmt.upper(),)):
return True
return False
def delete_conversion_options(self, book_ids, fmt):
self.executemany('DELETE FROM conversion_options WHERE book=? AND format=?',
[(book_id, fmt.upper()) for book_id in book_ids])
def set_conversion_options(self, options, fmt):
def map_data(x):
if not isinstance(x, string_or_bytes):
x = native_string_type(x)
x = x.encode('utf-8') if isinstance(x, str) else x
x = pickle_binary_string(x)
return x
options = [(book_id, fmt.upper(), map_data(data)) for book_id, data in iteritems(options)]
self.executemany('INSERT OR REPLACE INTO conversion_options(book,format,data) VALUES (?,?,?)', options)
def get_top_level_move_items(self, all_paths):
items = set(os.listdir(self.library_path))
paths = set(all_paths)
paths.update({'metadata.db', 'full-text-search.db', 'metadata_db_prefs_backup.json', NOTES_DIR_NAME})
path_map = {x:x for x in paths}
if not self.is_case_sensitive:
for x in items:
path_map[x.lower()] = x
items = {x.lower() for x in items}
paths = {x.lower() for x in paths}
items = items.intersection(paths)
return items, path_map
def move_library_to(self, all_paths, newloc, progress=(lambda item_name, item_count, total: None), abort=None):
if not os.path.exists(newloc):
os.makedirs(newloc)
old_dirs, old_files = set(), set()
items, path_map = self.get_top_level_move_items(all_paths)
total = len(items) + 1
for i, x in enumerate(items):
if abort is not None and abort.is_set():
return
src = os.path.join(self.library_path, x)
dest = os.path.join(newloc, path_map[x])
if os.path.isdir(src):
if os.path.exists(dest):
shutil.rmtree(dest)
copytree_using_links(src, dest, dest_is_parent=False)
old_dirs.add(src)
else:
if os.path.exists(dest):
os.remove(dest)
copyfile_using_links(src, dest, dest_is_dir=False)
old_files.add(src)
x = path_map[x]
if not isinstance(x, str):
x = x.decode(filesystem_encoding, 'replace')
progress(x, i+1, total)
dbpath = os.path.join(newloc, os.path.basename(self.dbpath))
odir = self.library_path
self.conn.close()
self.library_path, self.dbpath = newloc, dbpath
if self._conn is not None:
self._conn.close()
self._conn = None
for loc in old_dirs:
try:
rmtree_with_retry(loc)
except OSError as e:
if os.path.exists(loc):
prints('Failed to delete:', loc, 'with error:', as_unicode(e))
for loc in old_files:
try:
os.remove(loc)
except OSError as e:
if e.errno != errno.ENOENT:
prints('Failed to delete:', loc, 'with error:', as_unicode(e))
try:
os.rmdir(odir)
except OSError:
pass
self.conn # Connect to the moved metadata.db
progress(_('Completed'), total, total)
def _backup_database(self, path, name, extra_sql=''):
with closing(apsw.Connection(path)) as dest_db:
with dest_db.backup('main', self.conn, name) as b:
while not b.done:
with suppress(apsw.BusyError):
b.step(128)
if extra_sql:
dest_db.cursor().execute(extra_sql)
def backup_database(self, path):
self._backup_database(path, 'main', 'DELETE FROM metadata_dirtied; VACUUM;')
def backup_fts_database(self, path):
self._backup_database(path, 'fts_db')
def backup_notes_database(self, path):
self._backup_database(path, 'notes_db')
def size_stats(self):
main_size = notes_size = fts_size = 0
with suppress(OSError):
main_size = os.path.getsize(self.dbpath)
if self.conn.notes_dbpath:
with suppress(OSError):
notes_size = os.path.getsize(self.conn.notes_dbpath)
if self.conn.fts_dbpath:
with suppress(OSError):
fts_size = os.path.getsize(self.conn.fts_dbpath)
return {'main': main_size, 'fts': fts_size, 'notes': notes_size}
# }}}
| 110,639 | Python | .py | 2,367 | 33.623574 | 160 | 0.552888 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,067 | write.py | kovidgoyal_calibre/src/calibre/db/write.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import re
from datetime import datetime
from functools import partial
from calibre.constants import preferred_encoding
from calibre.ebooks.metadata import author_to_author_sort, title_sort
from calibre.utils.date import UNDEFINED_DATE, is_date_undefined, isoformat, parse_date, parse_only_date
from calibre.utils.icu import lower as icu_lower
from calibre.utils.icu import strcmp
from calibre.utils.localization import canonicalize_lang
from polyglot.builtins import iteritems, itervalues
missing = object()
# Convert data into values suitable for the db {{{
def sqlite_datetime(x):
return isoformat(x, sep=' ') if isinstance(x, datetime) else x
def single_text(x):
if x is None:
return x
if not isinstance(x, str):
x = x.decode(preferred_encoding, 'replace')
x = x.strip()
return x if x else None
series_index_pat = re.compile(r'(.*)\s+\[([.0-9]+)\]$')
def get_series_values(val):
if not val:
return (val, None)
match = series_index_pat.match(val.strip())
if match is not None:
idx = match.group(2)
try:
idx = float(idx)
return (match.group(1).strip(), idx)
except:
pass
return (val, None)
def multiple_text(sep, ui_sep, x):
if not x:
return ()
if isinstance(x, bytes):
x = x.decode(preferred_encoding, 'replace')
if isinstance(x, str):
x = x.split(sep)
else:
x = (y.decode(preferred_encoding, 'replace') if isinstance(y, bytes)
else y for y in x)
ui_sep = ui_sep.strip()
repsep = ',' if ui_sep == ';' else ';'
x = (y.strip().replace(ui_sep, repsep) for y in x if y.strip())
return tuple(' '.join(y.split()) for y in x if y)
def adapt_datetime(x):
if isinstance(x, (str, bytes)):
x = parse_date(x, assume_utc=False, as_utc=False)
if x and is_date_undefined(x):
x = UNDEFINED_DATE
return x
def adapt_date(x):
if isinstance(x, (str, bytes)):
x = parse_only_date(x)
if x is None or is_date_undefined(x):
x = UNDEFINED_DATE
return x
def adapt_number(typ, x):
if x is None:
return None
if isinstance(x, (str, bytes)):
if isinstance(x, bytes):
x = x.decode(preferred_encoding, 'replace')
if not x or x.lower() == 'none':
return None
return typ(x)
def adapt_bool(x):
if isinstance(x, (str, bytes)):
if isinstance(x, bytes):
x = x.decode(preferred_encoding, 'replace')
x = x.lower()
if x == 'true':
x = True
elif x == 'false':
x = False
elif x == 'none' or x == '':
x = None
else:
x = bool(int(x))
return x if x is None else bool(x)
def adapt_languages(to_tuple, x):
ans = []
for lang in to_tuple(x):
lc = canonicalize_lang(lang)
if not lc or lc in ans or lc in ('und', 'zxx', 'mis', 'mul'):
continue
ans.append(lc)
return tuple(ans)
def clean_identifier(typ, val):
typ = icu_lower(typ or '').strip().replace(':', '').replace(',', '')
val = (val or '').strip().replace(',', '|')
return typ, val
def adapt_identifiers(to_tuple, x):
if not isinstance(x, dict):
x = {k:v for k, v in (y.partition(':')[0::2] for y in to_tuple(x))}
ans = {}
for k, v in iteritems(x):
k, v = clean_identifier(k, v)
if k and v:
ans[k] = v
return ans
def adapt_series_index(x):
ret = adapt_number(float, x)
return 1.0 if ret is None else ret
def get_adapter(name, metadata):
dt = metadata['datatype']
if dt == 'text':
if metadata['is_multiple']:
m = metadata['is_multiple']
ans = partial(multiple_text, m['ui_to_list'], m['list_to_ui'])
else:
ans = single_text
elif dt == 'series':
ans = single_text
elif dt == 'datetime':
ans = adapt_date if name == 'pubdate' else adapt_datetime
elif dt == 'int':
ans = partial(adapt_number, int)
elif dt == 'float':
ans = partial(adapt_number, float)
elif dt == 'bool':
ans = adapt_bool
elif dt == 'comments':
ans = single_text
elif dt == 'rating':
def ans(x):
return (None if x in {None, 0} else min(10, max(0, adapt_number(int, x))))
elif dt == 'enumeration':
ans = single_text
elif dt == 'composite':
def ans(x):
return x
if name == 'title':
return lambda x: ans(x) or _('Unknown')
if name == 'author_sort':
return lambda x: ans(x) or ''
if name == 'authors':
return lambda x: tuple(y.replace('|', ',') for y in ans(x)) or (_('Unknown'),)
if name in {'timestamp', 'last_modified'}:
return lambda x: ans(x) or UNDEFINED_DATE
if name == 'series_index':
return adapt_series_index
if name == 'languages':
return partial(adapt_languages, ans)
if name == 'identifiers':
return partial(adapt_identifiers, ans)
return ans
# }}}
# One-One fields {{{
def one_one_in_books(book_id_val_map, db, field, *args):
'Set a one-one field in the books table'
# Ignore those items whose value is the same as the current value
# We can't do this for the cover because the file might change without
# the presence-of-cover flag changing
if field.name != 'cover':
g = field.table.book_col_map.get
book_id_val_map = {k:v for k, v in book_id_val_map.items() if v != g(k, missing)}
if book_id_val_map:
sequence = ((sqlite_datetime(v), k) for k, v in book_id_val_map.items())
db.executemany(
'UPDATE books SET %s=? WHERE id=?'%field.metadata['column'], sequence)
field.table.book_col_map.update(book_id_val_map)
return set(book_id_val_map)
def set_uuid(book_id_val_map, db, field, *args):
field.table.update_uuid_cache(book_id_val_map)
return one_one_in_books(book_id_val_map, db, field, *args)
def set_title(book_id_val_map, db, field, *args):
ans = one_one_in_books(book_id_val_map, db, field, *args)
# Set the title sort field if the title changed
field.title_sort_field.writer.set_books(
{k:title_sort(v) for k, v in book_id_val_map.items() if k in ans}, db)
return ans
def one_one_in_other(book_id_val_map, db, field, *args):
'Set a one-one field in the non-books table, like comments'
# Ignore those items whose value is the same as the current value
g = field.table.book_col_map.get
book_id_val_map = {k:v for k, v in iteritems(book_id_val_map) if v != g(k, missing)}
deleted = tuple((k,) for k, v in iteritems(book_id_val_map) if v is None)
if deleted:
db.executemany('DELETE FROM %s WHERE book=?'%field.metadata['table'],
deleted)
for book_id in deleted:
field.table.book_col_map.pop(book_id[0], None)
updated = {k:v for k, v in iteritems(book_id_val_map) if v is not None}
if updated:
db.executemany('INSERT OR REPLACE INTO %s(book,%s) VALUES (?,?)'%(
field.metadata['table'], field.metadata['column']),
((k, sqlite_datetime(v)) for k, v in iteritems(updated)))
field.table.book_col_map.update(updated)
return set(book_id_val_map)
def custom_series_index(book_id_val_map, db, field, *args):
series_field = field.series_field
sequence = []
for book_id, sidx in book_id_val_map.items():
ids = series_field.ids_for_book(book_id)
if sidx is None:
sidx = 1.0
if ids:
if field.table.book_col_map.get(book_id, missing) != sidx:
sequence.append((sidx, book_id, ids[0]))
field.table.book_col_map[book_id] = sidx
else:
# the series has been deleted from the book, which means no row for
# it exists in the series table. The series_index value should be
# removed from the in-memory table as well, to ensure this book
# sorts the same as other books with no series.
field.table.remove_books((book_id,), db)
if sequence:
db.executemany('UPDATE %s SET %s=? WHERE book=? AND value=?'%(
field.metadata['table'], field.metadata['column']), sequence)
return {s[1] for s in sequence}
# }}}
# Many-One fields {{{
def safe_lower(x):
try:
return icu_lower(x)
except (TypeError, ValueError, KeyError, AttributeError):
return x
def get_db_id(val, db, m, table, kmap, rid_map, allow_case_change,
case_changes, val_map, is_authors=False):
''' Get the db id for the value val. If val does not exist in the db it is
inserted into the db. '''
kval = kmap(val)
item_id = rid_map.get(kval, None)
if item_id is None:
if is_authors:
aus = author_to_author_sort(val)
db.execute('INSERT INTO authors(name,sort) VALUES (?,?)',
(val.replace(',', '|'), aus))
else:
db.execute('INSERT INTO %s(%s) VALUES (?)'%(
m['table'], m['column']), (val,))
item_id = rid_map[kval] = db.last_insert_rowid()
table.id_map[item_id] = val
table.col_book_map[item_id] = set()
if is_authors:
table.asort_map[item_id] = aus
if hasattr(table, 'link_map'):
table.link_map[item_id] = ''
if table.supports_notes:
db.unretire_note(table.name, item_id, val)
elif allow_case_change and val != table.id_map[item_id]:
case_changes[item_id] = val
val_map[val] = item_id
def change_case(case_changes, dirtied, db, table, m, is_authors=False):
if is_authors:
vals = ((val.replace(',', '|'), item_id) for item_id, val in
iteritems(case_changes))
else:
vals = ((val, item_id) for item_id, val in iteritems(case_changes))
db.executemany(
'UPDATE %s SET %s=? WHERE id=?'%(m['table'], m['column']), vals)
for item_id, val in iteritems(case_changes):
table.id_map[item_id] = val
dirtied.update(table.col_book_map[item_id])
if is_authors:
table.asort_map[item_id] = author_to_author_sort(val)
def many_one(book_id_val_map, db, field, allow_case_change, *args):
dirtied = set()
m = field.metadata
table = field.table
dt = m['datatype']
is_custom_series = dt == 'series' and table.name.startswith('#')
# Map values to db ids, including any new values
kmap = safe_lower if dt in {'text', 'series'} else lambda x:x
rid_map = {kmap(item):item_id for item_id, item in iteritems(table.id_map)}
if len(rid_map) != len(table.id_map):
# table has some entries that differ only in case, fix it
table.fix_case_duplicates(db)
rid_map = {kmap(item):item_id for item_id, item in iteritems(table.id_map)}
val_map = {None:None}
case_changes = {}
for val in itervalues(book_id_val_map):
if val is not None:
get_db_id(val, db, m, table, kmap, rid_map, allow_case_change,
case_changes, val_map)
if case_changes:
change_case(case_changes, dirtied, db, table, m)
book_id_item_id_map = {k:val_map[v] for k, v in iteritems(book_id_val_map)}
# Ignore those items whose value is the same as the current value
book_id_item_id_map = {k:v for k, v in iteritems(book_id_item_id_map)
if v != table.book_col_map.get(k, None)}
dirtied |= set(book_id_item_id_map)
# Update the book->col and col->book maps
deleted = set()
updated = {}
for book_id, item_id in iteritems(book_id_item_id_map):
old_item_id = table.book_col_map.get(book_id, None)
if old_item_id is not None:
table.col_book_map[old_item_id].discard(book_id)
if item_id is None:
table.book_col_map.pop(book_id, None)
deleted.add(book_id)
else:
table.book_col_map[book_id] = item_id
table.col_book_map[item_id].add(book_id)
updated[book_id] = item_id
# Update the db link table
if deleted:
db.executemany('DELETE FROM %s WHERE book=?'%table.link_table,
((k,) for k in deleted))
if updated:
sql = (
'DELETE FROM {0} WHERE book=?; INSERT INTO {0}(book,{1},extra) VALUES(?, ?, 1.0)'
if is_custom_series else
'DELETE FROM {0} WHERE book=?; INSERT INTO {0}(book,{1}) VALUES(?, ?)'
)
db.executemany(sql.format(table.link_table, m['link_column']),
((book_id, book_id, item_id) for book_id, item_id in
iteritems(updated)))
# Remove no longer used items
remove = {item_id:item_val for item_id, item_val in table.id_map.items() if not table.col_book_map.get(item_id, False)}
if remove:
if table.supports_notes:
db.clear_notes_for_category_items(table.name, remove)
db.executemany('DELETE FROM %s WHERE id=?'%m['table'],
((item_id,) for item_id in remove))
for item_id in remove:
del table.id_map[item_id]
table.col_book_map.pop(item_id, None)
return dirtied
# }}}
# Many-Many fields {{{
def uniq(vals, kmap=lambda x:x):
''' Remove all duplicates from vals, while preserving order. kmap must be a
callable that returns a hashable value for every item in vals '''
vals = vals or ()
lvals = (kmap(x) for x in vals)
seen = set()
seen_add = seen.add
return tuple(x for x, k in zip(vals, lvals) if k not in seen and not seen_add(k))
def many_many(book_id_val_map, db, field, allow_case_change, *args):
dirtied = set()
m = field.metadata
table = field.table
dt = m['datatype']
is_authors = field.name == 'authors'
# Map values to db ids, including any new values
kmap = safe_lower if dt == 'text' else lambda x:x
rid_map = {kmap(item):item_id for item_id, item in iteritems(table.id_map)}
if len(rid_map) != len(table.id_map):
# table has some entries that differ only in case, fix it
table.fix_case_duplicates(db)
rid_map = {kmap(item):item_id for item_id, item in iteritems(table.id_map)}
val_map = {}
case_changes = {}
book_id_val_map = {k:uniq(vals, kmap) for k, vals in iteritems(book_id_val_map)}
for vals in itervalues(book_id_val_map):
for val in vals:
get_db_id(val, db, m, table, kmap, rid_map, allow_case_change,
case_changes, val_map, is_authors=is_authors)
if case_changes:
change_case(case_changes, dirtied, db, table, m, is_authors=is_authors)
if is_authors:
for item_id, val in iteritems(case_changes):
for book_id in table.col_book_map[item_id]:
current_sort = field.db_author_sort_for_book(book_id)
new_sort = field.author_sort_for_book(book_id)
if strcmp(current_sort, new_sort) == 0:
# The sort strings differ only by case, update the db
# sort
field.author_sort_field.writer.set_books({book_id:new_sort}, db)
book_id_item_id_map = {k:tuple(val_map[v] for v in vals)
for k, vals in book_id_val_map.items()}
# Ignore those items whose value is the same as the current value
g = table.book_col_map.get
not_set = ()
book_id_item_id_map = {k:v for k, v in book_id_item_id_map.items() if v != g(k, not_set)}
dirtied |= set(book_id_item_id_map)
# Update the book->col and col->book maps
deleted = set()
updated = {}
for book_id, item_ids in iteritems(book_id_item_id_map):
old_item_ids = table.book_col_map.get(book_id, None)
if old_item_ids:
for old_item_id in old_item_ids:
table.col_book_map[old_item_id].discard(book_id)
if item_ids:
table.book_col_map[book_id] = item_ids
for item_id in item_ids:
table.col_book_map[item_id].add(book_id)
updated[book_id] = item_ids
else:
table.book_col_map.pop(book_id, None)
deleted.add(book_id)
# Update the db link table
if deleted:
db.executemany('DELETE FROM %s WHERE book=?'%table.link_table,
((k,) for k in deleted))
if updated:
vals = (
(book_id, val) for book_id, vals in iteritems(updated)
for val in vals
)
db.executemany('DELETE FROM %s WHERE book=?'%table.link_table,
((k,) for k in updated))
db.executemany('INSERT INTO {}(book,{}) VALUES(?, ?)'.format(
table.link_table, m['link_column']), vals)
if is_authors:
aus_map = {book_id:field.author_sort_for_book(book_id) for book_id
in updated}
field.author_sort_field.writer.set_books(aus_map, db)
# Remove no longer used items
remove = {item_id:item_val for item_id, item_val in table.id_map.items() if not table.col_book_map.get(item_id, False)}
if remove:
if table.supports_notes:
db.clear_notes_for_category_items(table.name, remove)
db.executemany('DELETE FROM %s WHERE id=?'%m['table'],
((item_id,) for item_id in remove))
for item_id in remove:
del table.id_map[item_id]
table.col_book_map.pop(item_id, None)
if is_authors:
table.asort_map.pop(item_id, None)
if hasattr(table, 'link_map'):
table.link_map.pop(item_id, None)
return dirtied
# }}}
def identifiers(book_id_val_map, db, field, *args): # {{{
# Ignore those items whose value is the same as the current value
g = field.table.book_col_map.get
book_id_val_map = {k:v for k, v in book_id_val_map.items() if v != g(k, missing)}
table = field.table
updates = set()
for book_id, identifiers in iteritems(book_id_val_map):
if book_id not in table.book_col_map:
table.book_col_map[book_id] = {}
current_ids = table.book_col_map[book_id]
remove_keys = set(current_ids) - set(identifiers)
for key in remove_keys:
table.col_book_map.get(key, set()).discard(book_id)
current_ids.pop(key, None)
current_ids.update(identifiers)
for key, val in iteritems(identifiers):
if key not in table.col_book_map:
table.col_book_map[key] = set()
table.col_book_map[key].add(book_id)
updates.add((book_id, key, val))
db.executemany('DELETE FROM identifiers WHERE book=?',
((x,) for x in book_id_val_map))
if updates:
db.executemany('INSERT OR REPLACE INTO identifiers (book, type, val) VALUES (?, ?, ?)',
tuple(updates))
return set(book_id_val_map)
# }}}
def dummy(book_id_val_map, *args):
return set()
class Writer:
def __init__(self, field):
self.adapter = get_adapter(field.name, field.metadata)
self.name = field.name
self.field = field
dt = field.metadata['datatype']
self.accept_vals = lambda x: True
if dt == 'composite' or field.name in {
'id', 'size', 'path', 'formats', 'news'}:
self.set_books_func = dummy
elif self.name[0] == '#' and self.name.endswith('_index'):
self.set_books_func = custom_series_index
elif self.name == 'identifiers':
self.set_books_func = identifiers
elif self.name == 'uuid':
self.set_books_func = set_uuid
elif self.name == 'title':
self.set_books_func = set_title
elif field.is_many_many:
self.set_books_func = many_many
elif field.is_many:
self.set_books_func = (self.set_books_for_enum if dt == 'enumeration' else many_one)
else:
self.set_books_func = (one_one_in_books if field.metadata['table'] == 'books' else one_one_in_other)
if self.name in {'timestamp', 'uuid', 'sort'}:
self.accept_vals = bool
def set_books(self, book_id_val_map, db, allow_case_change=True):
book_id_val_map = {k:self.adapter(v) for k, v in
iteritems(book_id_val_map) if self.accept_vals(v)}
if not book_id_val_map:
return set()
dirtied = self.set_books_func(book_id_val_map, db, self.field,
allow_case_change)
return dirtied
def set_books_for_enum(self, book_id_val_map, db, field,
allow_case_change):
allowed = set(field.metadata['display']['enum_values'])
book_id_val_map = {k:v for k, v in iteritems(book_id_val_map) if v is
None or v in allowed}
if not book_id_val_map:
return set()
return many_one(book_id_val_map, db, field, False)
| 21,234 | Python | .py | 496 | 34.235887 | 123 | 0.591836 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,068 | legacy.py | kovidgoyal_calibre/src/calibre/db/legacy.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import os
import traceback
import weakref
from collections.abc import MutableMapping
from calibre import force_unicode, isbytestring
from calibre.constants import preferred_encoding
from calibre.db import _get_next_series_num_for_list, _get_series_values, get_data_as_dict
from calibre.db.adding import add_catalog, add_news, find_books_in_directory, import_book_directory, import_book_directory_multiple, recursive_import
from calibre.db.backend import DB
from calibre.db.backend import set_global_state as backend_set_global_state
from calibre.db.cache import Cache
from calibre.db.categories import CATEGORY_SORTS
from calibre.db.errors import NoSuchFormat
from calibre.db.view import View
from calibre.db.write import clean_identifier, get_series_values
from calibre.utils.date import utcnow
from calibre.utils.icu import lower as icu_lower
from calibre.utils.search_query_parser import set_saved_searches
from polyglot.builtins import iteritems
def cleanup_tags(tags):
tags = [x.strip().replace(',', ';') for x in tags if x.strip()]
tags = [x.decode(preferred_encoding, 'replace')
if isbytestring(x) else x for x in tags]
tags = [' '.join(x.split()) for x in tags]
ans, seen = [], set()
for tag in tags:
if tag.lower() not in seen:
seen.add(tag.lower())
ans.append(tag)
return ans
def create_backend(
library_path, default_prefs=None, read_only=False,
progress_callback=lambda x, y:True, restore_all_prefs=False,
load_user_formatter_functions=True):
return DB(library_path, default_prefs=default_prefs,
read_only=read_only, restore_all_prefs=restore_all_prefs,
progress_callback=progress_callback,
load_user_formatter_functions=load_user_formatter_functions)
def set_global_state(db):
backend_set_global_state(db.backend)
set_saved_searches(db, 'saved_searches')
class ThreadSafePrefs(MutableMapping):
def __init__(self, db):
self.db = weakref.ref(db)
def has_setting(self, key):
prefs = self.db().backend.prefs
return prefs.has_setting(key)
def __getitem__(self, key):
prefs = self.db().backend.prefs
return prefs.__getitem__(key)
def __delitem__(self, key):
db = self.db()
with db.write_lock:
prefs = db.backend.prefs
prefs.__delitem__(key)
def __setitem__(self, key, val):
db = self.db()
with db.write_lock:
prefs = db.backend.prefs
prefs.__setitem__(key, val)
def __contains__(self, key):
prefs = self.db().backend.prefs
return prefs.__contains__(key)
def __iter__(self):
prefs = self.db().backend.prefs
return prefs.__iter__()
def __len__(self):
prefs = self.db().backend.prefs
return prefs.__len__()
def __bool__(self):
prefs = self.db().backend.prefs
return prefs.__bool__()
def copy(self):
prefs = self.db().backend.prefs
return prefs.copy()
def items(self):
prefs = self.db().backend.prefs
return prefs.items()
iteritems = items
def keys(self):
prefs = self.db().backend.prefs
return prefs.keys()
iterkeys = keys
def values(self):
prefs = self.db().backend.prefs
return prefs.values()
itervalues = values
@property
def defaults(self):
prefs = self.db().backend.prefs
return prefs.defaults
@property
def disable_setting(self):
prefs = self.db().backend.prefs
return prefs.disable_setting
@disable_setting.setter
def disable_setting(self, val):
prefs = self.db().backend.prefs
prefs.disable_setting = val
def get(self, key, default=None):
prefs = self.db().backend.prefs
return prefs.get(key, default)
def set(self, key, val):
self.__setitem__(key, val)
def get_namespaced(self, namespace, key, default=None):
prefs = self.db().backend.prefs
return prefs.get_namespaced(namespace, key, default)
def set_namespaced(self, namespace, key, val):
db = self.db()
with db.write_lock:
prefs = db.backend.prefs
return prefs.set_namespaced(namespace, key, val)
def write_serialized(self, library_path):
prefs = self.db().backend.prefs
prefs.write_serialized(library_path)
def to_raw(self, val):
prefs = self.db().backend.prefs
return prefs.to_raw(val)
def raw_to_object(self, raw):
if isinstance(raw, bytes):
raw = raw.decode(preferred_encoding)
import json
from calibre.utils.config import from_json
return json.loads(raw, object_hook=from_json)
class LibraryDatabase:
''' Emulate the old LibraryDatabase2 interface '''
PATH_LIMIT = DB.PATH_LIMIT
WINDOWS_LIBRARY_PATH_LIMIT = DB.WINDOWS_LIBRARY_PATH_LIMIT
CATEGORY_SORTS = CATEGORY_SORTS
MATCH_TYPE = ('any', 'all')
CUSTOM_DATA_TYPES = frozenset(['rating', 'text', 'comments', 'datetime',
'int', 'float', 'bool', 'series', 'composite', 'enumeration'])
@classmethod
def exists_at(cls, path):
return path and os.path.exists(os.path.join(path, 'metadata.db'))
def __init__(self, library_path,
default_prefs=None, read_only=False, is_second_db=False,
progress_callback=None, restore_all_prefs=False, row_factory=False):
self.is_second_db = is_second_db
if progress_callback is None:
def progress_callback(x, y):
return True
self.listeners = set()
backend = self.backend = create_backend(library_path, default_prefs=default_prefs,
read_only=read_only, restore_all_prefs=restore_all_prefs,
progress_callback=progress_callback,
load_user_formatter_functions=not is_second_db)
cache = self.new_api = Cache(backend, library_database_instance=self)
cache.init()
self.data = View(cache)
self.id = self.data.index_to_id
self.row = self.data.id_to_index
for x in ('get_property', 'count', 'refresh_ids', 'set_marked_ids',
'multisort', 'search', 'search_getting_ids'):
setattr(self, x, getattr(self.data, x))
self.is_case_sensitive = getattr(backend, 'is_case_sensitive', False)
self.custom_field_name = backend.custom_field_name
self.last_update_check = self.last_modified()
if not self.is_second_db:
set_saved_searches(self, 'saved_searches')
def close(self):
if hasattr(self, 'new_api'):
self.new_api.close()
def break_cycles(self):
if hasattr(self, 'backend'):
delattr(self.backend, 'field_metadata')
self.data.cache.backend = None
self.data.cache = None
for x in ('data', 'backend', 'new_api', 'listeners',):
delattr(self, x)
# Library wide properties {{{
@property
def prefs(self):
return ThreadSafePrefs(self.new_api)
@property
def field_metadata(self):
return self.backend.field_metadata
@property
def user_version(self):
return self.backend.user_version
@property
def library_id(self):
return self.backend.library_id
@property
def library_path(self):
return self.backend.library_path
@property
def dbpath(self):
return self.backend.dbpath
def last_modified(self):
return self.new_api.last_modified()
def check_if_modified(self):
if self.last_modified() > self.last_update_check:
self.backend.reopen()
self.new_api.reload_from_db()
self.data.refresh(clear_caches=False) # caches are already cleared by reload_from_db()
self.last_update_check = utcnow()
@property
def custom_column_num_map(self):
return self.backend.custom_column_num_map
@property
def custom_column_label_map(self):
return self.backend.custom_column_label_map
@property
def FIELD_MAP(self):
return self.backend.FIELD_MAP
@property
def formatter_template_cache(self):
return self.data.cache.formatter_template_cache
def initialize_template_cache(self):
self.data.cache.initialize_template_cache()
def all_ids(self):
'All book ids in the db. This can no longer be a generator because of db locking.'
return tuple(self.new_api.all_book_ids())
def is_empty(self):
with self.new_api.safe_read_lock:
return not bool(self.new_api.fields['title'].table.book_col_map)
def get_usage_count_by_id(self, field):
return [[k, v] for k, v in iteritems(self.new_api.get_usage_count_by_id(field))]
def field_id_map(self, field):
return [(k, v) for k, v in iteritems(self.new_api.get_id_map(field))]
def get_custom_items_with_ids(self, label=None, num=None):
try:
return [[k, v] for k, v in iteritems(self.new_api.get_id_map(self.custom_field_name(label, num)))]
except ValueError:
return []
def refresh(self, field=None, ascending=True):
self.data.refresh(field=field, ascending=ascending)
def get_id_from_uuid(self, uuid):
if uuid:
return self.new_api.lookup_by_uuid(uuid)
def add_listener(self, listener):
'''
Add a listener. Will be called on change events with two arguments.
Event name and list of affected ids.
'''
self.listeners.add(listener)
def notify(self, event, ids=[]):
'Notify all listeners'
for listener in self.listeners:
try:
listener(event, ids)
except:
traceback.print_exc()
continue
# }}}
def path(self, index, index_is_id=False):
'Return the relative path to the directory containing this books files as a unicode string.'
book_id = index if index_is_id else self.id(index)
return self.new_api.field_for('path', book_id).replace('/', os.sep)
def abspath(self, index, index_is_id=False, create_dirs=True):
'Return the absolute path to the directory containing this books files as a unicode string.'
path = os.path.join(self.library_path, self.path(index, index_is_id=index_is_id))
if create_dirs and not os.path.exists(path):
os.makedirs(path)
return path
# Adding books {{{
def create_book_entry(self, mi, cover=None, add_duplicates=True, force_id=None):
ret = self.new_api.create_book_entry(mi, cover=cover, add_duplicates=add_duplicates, force_id=force_id)
if ret is not None:
self.data.books_added((ret,))
return ret
def add_books(self, paths, formats, metadata, add_duplicates=True, return_ids=False):
books = [(mi, {fmt:path}) for mi, path, fmt in zip(metadata, paths, formats)]
book_ids, duplicates = self.new_api.add_books(books, add_duplicates=add_duplicates, dbapi=self)
if duplicates:
paths, formats, metadata = [], [], []
for mi, format_map in duplicates:
metadata.append(mi)
for fmt, path in iteritems(format_map):
formats.append(fmt)
paths.append(path)
duplicates = (paths, formats, metadata)
ids = book_ids if return_ids else len(book_ids)
if book_ids:
self.data.books_added(book_ids)
return duplicates or None, ids
def import_book(self, mi, formats, notify=True, import_hooks=True, apply_import_tags=True, preserve_uuid=False):
format_map = {}
for path in formats:
ext = os.path.splitext(path)[1][1:].upper()
if ext == 'OPF':
continue
format_map[ext] = path
book_ids, duplicates = self.new_api.add_books(
[(mi, format_map)], add_duplicates=True, apply_import_tags=apply_import_tags, preserve_uuid=preserve_uuid, dbapi=self, run_hooks=import_hooks)
if book_ids:
self.data.books_added(book_ids)
if notify:
self.notify('add', book_ids)
return book_ids[0]
def find_books_in_directory(self, dirpath, single_book_per_directory, compiled_rules=()):
return find_books_in_directory(dirpath, single_book_per_directory, compiled_rules=compiled_rules)
def import_book_directory_multiple(self, dirpath, callback=None, added_ids=None, compiled_rules=()):
return import_book_directory_multiple(self, dirpath, callback=callback, added_ids=added_ids, compiled_rules=compiled_rules)
def import_book_directory(self, dirpath, callback=None, added_ids=None, compiled_rules=()):
return import_book_directory(self, dirpath, callback=callback, added_ids=added_ids, compiled_rules=compiled_rules)
def recursive_import(self, root, single_book_per_directory=True, callback=None, added_ids=None, compiled_rules=()):
return recursive_import(
self, root, single_book_per_directory=single_book_per_directory, callback=callback, added_ids=added_ids, compiled_rules=compiled_rules)
def add_catalog(self, path, title):
book_id, new_book_added = add_catalog(self.new_api, path, title, dbapi=self)
if book_id is not None and new_book_added:
self.data.books_added((book_id,))
return book_id
def add_news(self, path, arg):
book_id = add_news(self.new_api, path, arg, dbapi=self)
if book_id is not None:
self.data.books_added((book_id,))
return book_id
def add_format(self, index, fmt, stream, index_is_id=False, path=None, notify=True, replace=True, copy_function=None):
''' path and copy_function are ignored by the new API '''
book_id = index if index_is_id else self.id(index)
ret = self.new_api.add_format(book_id, fmt, stream, replace=replace, run_hooks=False, dbapi=self)
self.notify('metadata', [book_id])
return ret
def add_format_with_hooks(self, index, fmt, fpath, index_is_id=False, path=None, notify=True, replace=True):
''' path is ignored by the new API '''
book_id = index if index_is_id else self.id(index)
ret = self.new_api.add_format(book_id, fmt, fpath, replace=replace, run_hooks=True, dbapi=self)
self.notify('metadata', [book_id])
return ret
# }}}
# Custom data {{{
def add_custom_book_data(self, book_id, name, val):
self.new_api.add_custom_book_data(name, {book_id:val})
def add_multiple_custom_book_data(self, name, val_map, delete_first=False):
self.new_api.add_custom_book_data(name, val_map, delete_first=delete_first)
def get_custom_book_data(self, book_id, name, default=None):
return self.new_api.get_custom_book_data(name, book_ids={book_id}, default=default).get(book_id, default)
def get_all_custom_book_data(self, name, default=None):
return self.new_api.get_custom_book_data(name, default=default)
def delete_custom_book_data(self, book_id, name):
self.new_api.delete_custom_book_data(name, book_ids=(book_id,))
def delete_all_custom_book_data(self, name):
self.new_api.delete_custom_book_data(name)
def get_ids_for_custom_book_data(self, name):
return list(self.new_api.get_ids_for_custom_book_data(name))
# }}}
def sort(self, field, ascending, subsort=False):
self.multisort([(field, ascending)])
def get_field(self, index, key, default=None, index_is_id=False):
book_id = index if index_is_id else self.id(index)
mi = self.new_api.get_metadata(book_id, get_cover=key == 'cover')
return mi.get(key, default)
def cover_last_modified(self, index, index_is_id=False):
book_id = index if index_is_id else self.id(index)
return self.new_api.cover_last_modified(book_id) or self.last_modified()
def cover(self, index, index_is_id=False, as_file=False, as_image=False, as_path=False):
book_id = index if index_is_id else self.id(index)
return self.new_api.cover(book_id, as_file=as_file, as_image=as_image, as_path=as_path)
def copy_cover_to(self, index, dest, index_is_id=False, windows_atomic_move=None, use_hardlink=False):
book_id = index if index_is_id else self.id(index)
return self.new_api.copy_cover_to(book_id, dest, use_hardlink=use_hardlink)
def copy_format_to(self, index, fmt, dest, index_is_id=False, windows_atomic_move=None, use_hardlink=False):
book_id = index if index_is_id else self.id(index)
return self.new_api.copy_format_to(book_id, fmt, dest, use_hardlink=use_hardlink)
def delete_book(self, book_id, notify=True, commit=True, permanent=False, do_clean=True):
self.new_api.remove_books((book_id,), permanent=permanent)
self.data.books_deleted((book_id,))
if notify:
self.notify('delete', [book_id])
def dirtied(self, book_ids, commit=True):
self.new_api.mark_as_dirty(frozenset(book_ids) if book_ids is not None else book_ids)
def dirty_queue_length(self):
return self.new_api.dirty_queue_length()
def dump_metadata(self, book_ids=None, remove_from_dirtied=True, commit=True, callback=None):
self.new_api.dump_metadata(book_ids=book_ids, remove_from_dirtied=remove_from_dirtied, callback=callback)
def authors_sort_strings(self, index, index_is_id=False):
book_id = index if index_is_id else self.id(index)
return list(self.new_api.author_sort_strings_for_books((book_id,))[book_id])
def author_sort_from_book(self, index, index_is_id=False):
return ' & '.join(self.authors_sort_strings(index, index_is_id=index_is_id))
def authors_with_sort_strings(self, index, index_is_id=False):
book_id = index if index_is_id else self.id(index)
with self.new_api.safe_read_lock:
authors = self.new_api._field_ids_for('authors', book_id)
adata = self.new_api._author_data(authors)
return [(aid, adata[aid]['name'], adata[aid]['sort'], adata[aid]['link']) for aid in authors]
def set_sort_field_for_author(self, old_id, new_sort, commit=True, notify=False):
changed_books = self.new_api.set_sort_for_authors({old_id:new_sort})
if notify:
self.notify('metadata', list(changed_books))
def set_link_field_for_author(self, aid, link, commit=True, notify=False):
changed_books = self.new_api.set_link_for_authors({aid:link})
if notify:
self.notify('metadata', list(changed_books))
def book_on_device(self, book_id):
with self.new_api.safe_read_lock:
return self.new_api.fields['ondevice'].book_on_device(book_id)
def book_on_device_string(self, book_id):
return self.new_api.field_for('ondevice', book_id)
def set_book_on_device_func(self, func):
self.new_api.fields['ondevice'].set_book_on_device_func(func)
@property
def book_on_device_func(self):
return self.new_api.fields['ondevice'].book_on_device_func
def books_in_series(self, series_id):
with self.new_api.safe_read_lock:
book_ids = self.new_api._books_for_field('series', series_id)
ff = self.new_api._field_for
return sorted(book_ids, key=lambda x:ff('series_index', x))
def books_in_series_of(self, index, index_is_id=False):
book_id = index if index_is_id else self.id(index)
series_ids = self.new_api.field_ids_for('series', book_id)
if not series_ids:
return []
return self.books_in_series(series_ids[0])
def books_with_same_title(self, mi, all_matches=True):
title = mi.title
ans = set()
if title:
title = icu_lower(force_unicode(title))
for book_id, x in iteritems(self.new_api.get_id_map('title')):
if icu_lower(x) == title:
ans.add(book_id)
if not all_matches:
break
return ans
def set_conversion_options(self, book_id, fmt, options):
self.new_api.set_conversion_options({book_id:options}, fmt=fmt)
def conversion_options(self, book_id, fmt):
return self.new_api.conversion_options(book_id, fmt=fmt)
def has_conversion_options(self, ids, format='PIPE'):
return self.new_api.has_conversion_options(ids, fmt=format)
def delete_conversion_options(self, book_id, fmt, commit=True):
self.new_api.delete_conversion_options((book_id,), fmt=fmt)
def set(self, index, field, val, allow_case_change=False):
book_id = self.id(index)
try:
return self.new_api.set_field(field, {book_id:val}, allow_case_change=allow_case_change)
finally:
self.notify('metadata', [book_id])
def set_identifier(self, book_id, typ, val, notify=True, commit=True):
with self.new_api.write_lock:
identifiers = self.new_api._field_for('identifiers', book_id)
typ, val = clean_identifier(typ, val)
if typ:
identifiers[typ] = val
self.new_api._set_field('identifiers', {book_id:identifiers})
self.notify('metadata', [book_id])
def set_isbn(self, book_id, isbn, notify=True, commit=True):
self.set_identifier(book_id, 'isbn', isbn, notify=notify, commit=commit)
def set_tags(self, book_id, tags, append=False, notify=True, commit=True, allow_case_change=False):
tags = tags or []
with self.new_api.write_lock:
if append:
otags = self.new_api._field_for('tags', book_id)
existing = {icu_lower(x) for x in otags}
tags = list(otags) + [x for x in tags if icu_lower(x) not in existing]
ret = self.new_api._set_field('tags', {book_id:tags}, allow_case_change=allow_case_change)
if notify:
self.notify('metadata', [book_id])
return ret
def set_metadata(self, book_id, mi, ignore_errors=False, set_title=True,
set_authors=True, commit=True, force_changes=False, notify=True):
self.new_api.set_metadata(book_id, mi, ignore_errors=ignore_errors, set_title=set_title, set_authors=set_authors, force_changes=force_changes)
if notify:
self.notify('metadata', [book_id])
def remove_all_tags(self, ids, notify=False, commit=True):
self.new_api.set_field('tags', {book_id:() for book_id in ids})
if notify:
self.notify('metadata', ids)
def _do_bulk_modify(self, field, ids, add, remove, notify):
add = cleanup_tags(add)
remove = cleanup_tags(remove)
remove = set(remove) - set(add)
if not ids or (not add and not remove):
return
remove = {icu_lower(x) for x in remove}
with self.new_api.write_lock:
val_map = {}
for book_id in ids:
tags = list(self.new_api._field_for(field, book_id))
existing = {icu_lower(x) for x in tags}
tags.extend(t for t in add if icu_lower(t) not in existing)
tags = tuple(t for t in tags if icu_lower(t) not in remove)
val_map[book_id] = tags
self.new_api._set_field(field, val_map, allow_case_change=False)
if notify:
self.notify('metadata', ids)
def bulk_modify_tags(self, ids, add=[], remove=[], notify=False):
self._do_bulk_modify('tags', ids, add, remove, notify)
def set_custom_bulk_multiple(self, ids, add=[], remove=[], label=None, num=None, notify=False):
data = self.backend.custom_field_metadata(label, num)
if not data['editable']:
raise ValueError('Column %r is not editable'%data['label'])
if data['datatype'] != 'text' or not data['is_multiple']:
raise ValueError('Column %r is not text/multiple'%data['label'])
field = self.custom_field_name(label, num)
self._do_bulk_modify(field, ids, add, remove, notify)
def unapply_tags(self, book_id, tags, notify=True):
self.bulk_modify_tags((book_id,), remove=tags, notify=notify)
def is_tag_used(self, tag):
return icu_lower(tag) in {icu_lower(x) for x in self.new_api.all_field_names('tags')}
def delete_tag(self, tag):
self.delete_tags((tag,))
def delete_tags(self, tags):
with self.new_api.write_lock:
tag_map = {icu_lower(v):k for k, v in iteritems(self.new_api._get_id_map('tags'))}
tag_ids = (tag_map.get(icu_lower(tag), None) for tag in tags)
tag_ids = tuple(tid for tid in tag_ids if tid is not None)
if tag_ids:
self.new_api._remove_items('tags', tag_ids)
def has_id(self, book_id):
return self.new_api.has_id(book_id)
def format(self, index, fmt, index_is_id=False, as_file=False, mode='r+b', as_path=False, preserve_filename=False):
book_id = index if index_is_id else self.id(index)
return self.new_api.format(book_id, fmt, as_file=as_file, as_path=as_path, preserve_filename=preserve_filename)
def format_abspath(self, index, fmt, index_is_id=False):
book_id = index if index_is_id else self.id(index)
return self.new_api.format_abspath(book_id, fmt)
def format_path(self, index, fmt, index_is_id=False):
book_id = index if index_is_id else self.id(index)
ans = self.new_api.format_abspath(book_id, fmt)
if ans is None:
raise NoSuchFormat('Record %d has no format: %s'%(book_id, fmt))
return ans
def format_files(self, index, index_is_id=False):
book_id = index if index_is_id else self.id(index)
return [(v, k) for k, v in iteritems(self.new_api.format_files(book_id))]
def format_metadata(self, book_id, fmt, allow_cache=True, update_db=False, commit=False):
return self.new_api.format_metadata(book_id, fmt, allow_cache=allow_cache, update_db=update_db)
def format_last_modified(self, book_id, fmt):
m = self.format_metadata(book_id, fmt)
if m:
return m['mtime']
def formats(self, index, index_is_id=False, verify_formats=True):
book_id = index if index_is_id else self.id(index)
ans = self.new_api.formats(book_id, verify_formats=verify_formats)
if ans:
return ','.join(ans)
def has_format(self, index, fmt, index_is_id=False):
book_id = index if index_is_id else self.id(index)
return self.new_api.has_format(book_id, fmt)
def refresh_format_cache(self):
self.new_api.refresh_format_cache()
def refresh_ondevice(self):
self.new_api.refresh_ondevice()
def tags_older_than(self, tag, delta, must_have_tag=None, must_have_authors=None):
yield from sorted(self.new_api.tags_older_than(tag, delta=delta, must_have_tag=must_have_tag, must_have_authors=must_have_authors))
def sizeof_format(self, index, fmt, index_is_id=False):
book_id = index if index_is_id else self.id(index)
return self.new_api.format_metadata(book_id, fmt).get('size', None)
def get_metadata(self, index, index_is_id=False, get_cover=False, get_user_categories=True, cover_as_data=False):
book_id = index if index_is_id else self.id(index)
return self.new_api.get_metadata(book_id, get_cover=get_cover, get_user_categories=get_user_categories, cover_as_data=cover_as_data)
def rename_series(self, old_id, new_name, change_index=True):
self.new_api.rename_items('series', {old_id:new_name}, change_index=change_index)
def get_custom(self, index, label=None, num=None, index_is_id=False):
book_id = index if index_is_id else self.id(index)
ans = self.new_api.field_for(self.custom_field_name(label, num), book_id)
if isinstance(ans, tuple):
ans = list(ans)
return ans
def get_custom_extra(self, index, label=None, num=None, index_is_id=False):
data = self.backend.custom_field_metadata(label, num)
# add future datatypes with an extra column here
if data['datatype'] != 'series':
return None
book_id = index if index_is_id else self.id(index)
return self.new_api.field_for(self.custom_field_name(label, num) + '_index', book_id)
def get_custom_and_extra(self, index, label=None, num=None, index_is_id=False):
book_id = index if index_is_id else self.id(index)
data = self.backend.custom_field_metadata(label, num)
ans = self.new_api.field_for(self.custom_field_name(label, num), book_id)
if isinstance(ans, tuple):
ans = list(ans)
if data['datatype'] != 'series':
return (ans, None)
return (ans, self.new_api.field_for(self.custom_field_name(label, num) + '_index', book_id))
def get_next_cc_series_num_for(self, series, label=None, num=None):
data = self.backend.custom_field_metadata(label, num)
if data['datatype'] != 'series':
return None
return self.new_api.get_next_series_num_for(series, field=self.custom_field_name(label, num))
def is_item_used_in_multiple(self, item, label=None, num=None):
existing_tags = self.all_custom(label=label, num=num)
return icu_lower(item) in {icu_lower(t) for t in existing_tags}
def delete_custom_item_using_id(self, item_id, label=None, num=None):
self.new_api.remove_items(self.custom_field_name(label, num), (item_id,))
def rename_custom_item(self, old_id, new_name, label=None, num=None):
self.new_api.rename_items(self.custom_field_name(label, num), {old_id:new_name}, change_index=False)
def delete_item_from_multiple(self, item, label=None, num=None):
field = self.custom_field_name(label, num)
existing = self.new_api.get_id_map(field)
rmap = {icu_lower(v):k for k, v in iteritems(existing)}
item_id = rmap.get(icu_lower(item), None)
if item_id is None:
return []
return list(self.new_api.remove_items(field, (item_id,)))
def set_custom(self, book_id, val, label=None, num=None, append=False,
notify=True, extra=None, commit=True, allow_case_change=False):
field = self.custom_field_name(label, num)
data = self.backend.custom_field_metadata(label, num)
if data['datatype'] == 'composite':
return set()
if not data['editable']:
raise ValueError('Column %r is not editable'%data['label'])
if data['datatype'] == 'enumeration' and (
val and val not in data['display']['enum_values']):
return set()
with self.new_api.write_lock:
if append and data['is_multiple']:
current = self.new_api._field_for(field, book_id)
existing = {icu_lower(x) for x in current}
val = current + tuple(x for x in self.new_api.fields[field].writer.adapter(val) if icu_lower(x) not in existing)
affected_books = self.new_api._set_field(field, {book_id:val}, allow_case_change=allow_case_change)
else:
affected_books = self.new_api._set_field(field, {book_id:val}, allow_case_change=allow_case_change)
if data['datatype'] == 'series':
s, sidx = get_series_values(val)
if sidx is None:
extra = 1.0 if extra is None else extra
self.new_api._set_field(field + '_index', {book_id:extra})
if notify and affected_books:
self.notify('metadata', list(affected_books))
return affected_books
def set_custom_bulk(self, ids, val, label=None, num=None,
append=False, notify=True, extras=None):
if extras is not None and len(extras) != len(ids):
raise ValueError('Length of ids and extras is not the same')
field = self.custom_field_name(label, num)
data = self.backend.custom_field_metadata(label, num)
if data['datatype'] == 'composite':
return set()
if data['datatype'] == 'enumeration' and (
val and val not in data['display']['enum_values']):
return
if not data['editable']:
raise ValueError('Column %r is not editable'%data['label'])
if append:
for book_id in ids:
self.set_custom(book_id, val, label=label, num=num, append=True, notify=False)
else:
with self.new_api.write_lock:
self.new_api._set_field(field, {book_id:val for book_id in ids}, allow_case_change=False)
if extras is not None:
self.new_api._set_field(field + '_index', {book_id:val for book_id, val in zip(ids, extras)})
if notify:
self.notify('metadata', list(ids))
def delete_custom_column(self, label=None, num=None):
self.new_api.delete_custom_column(label, num)
def create_custom_column(self, label, name, datatype, is_multiple, editable=True, display={}):
return self.new_api.create_custom_column(label, name, datatype, is_multiple, editable=editable, display=display)
def set_custom_column_metadata(self, num, name=None, label=None, is_editable=None, display=None,
notify=True, update_last_modified=False):
changed = self.new_api.set_custom_column_metadata(num, name=name, label=label, is_editable=is_editable,
display=display, update_last_modified=update_last_modified)
if changed and notify:
self.notify('metadata', [])
def remove_cover(self, book_id, notify=True, commit=True):
self.new_api.set_cover({book_id:None})
if notify:
self.notify('cover', [book_id])
def set_cover(self, book_id, data, notify=True, commit=True):
self.new_api.set_cover({book_id:data})
if notify:
self.notify('cover', [book_id])
def original_fmt(self, book_id, fmt):
nfmt = ('ORIGINAL_%s'%fmt).upper()
return nfmt if self.new_api.has_format(book_id, nfmt) else fmt
def save_original_format(self, book_id, fmt, notify=True):
ret = self.new_api.save_original_format(book_id, fmt)
if ret and notify:
self.notify('metadata', [book_id])
return ret
def restore_original_format(self, book_id, original_fmt, notify=True):
ret = self.new_api.restore_original_format(book_id, original_fmt)
if ret and notify:
self.notify('metadata', [book_id])
return ret
def remove_format(self, index, fmt, index_is_id=False, notify=True, commit=True, db_only=False):
book_id = index if index_is_id else self.id(index)
self.new_api.remove_formats({book_id:(fmt,)}, db_only=db_only)
if notify:
self.notify('metadata', [book_id])
# Private interface {{{
def __iter__(self):
yield from self.data.iterall()
def _get_next_series_num_for_list(self, series_indices):
return _get_next_series_num_for_list(series_indices)
def _get_series_values(self, val):
return _get_series_values(val)
# }}}
# Legacy getter API {{{
for prop in ('author_sort', 'authors', 'comment', 'comments', 'publisher', 'max_size',
'rating', 'series', 'series_index', 'tags', 'title', 'title_sort',
'timestamp', 'uuid', 'pubdate', 'ondevice', 'metadata_last_modified', 'languages',):
def getter(prop):
fm = {'comment':'comments', 'metadata_last_modified':
'last_modified', 'title_sort':'sort', 'max_size':'size'}.get(prop, prop)
def func(self, index, index_is_id=False):
return self.get_property(index, index_is_id=index_is_id, loc=self.FIELD_MAP[fm])
return func
setattr(LibraryDatabase, prop, getter(prop))
for prop in ('series', 'publisher'):
def getter(field):
def func(self, index, index_is_id=False):
book_id = index if index_is_id else self.id(index)
ans = self.new_api.field_ids_for(field, book_id)
try:
return ans[0]
except IndexError:
pass
return func
setattr(LibraryDatabase, prop + '_id', getter(prop))
LibraryDatabase.format_hash = lambda self, book_id, fmt:self.new_api.format_hash(book_id, fmt)
LibraryDatabase.index = lambda self, book_id, cache=False:self.data.id_to_index(book_id)
LibraryDatabase.has_cover = lambda self, book_id:self.new_api.field_for('cover', book_id)
LibraryDatabase.get_tags = lambda self, book_id:set(self.new_api.field_for('tags', book_id))
LibraryDatabase.get_categories = lambda self, sort='name', ids=None:self.new_api.get_categories(sort=sort, book_ids=ids)
LibraryDatabase.get_identifiers = lambda self, index, index_is_id=False: self.new_api.field_for('identifiers', index if index_is_id else self.id(index))
LibraryDatabase.isbn = lambda self, index, index_is_id=False: self.get_identifiers(index, index_is_id=index_is_id).get('isbn', None)
LibraryDatabase.get_books_for_category = lambda self, category, id_:self.new_api.get_books_for_category(category, id_)
LibraryDatabase.get_data_as_dict = get_data_as_dict
LibraryDatabase.find_identical_books = lambda self, mi:self.new_api.find_identical_books(mi)
LibraryDatabase.get_top_level_move_items = lambda self:self.new_api.get_top_level_move_items()
# }}}
# Legacy setter API {{{
for field in (
'!authors', 'author_sort', 'comment', 'has_cover', 'identifiers', 'languages',
'pubdate', '!publisher', 'rating', '!series', 'series_index', 'timestamp', 'uuid',
'title', 'title_sort',
):
def setter(field):
has_case_change = field.startswith('!')
field = {'comment':'comments', 'title_sort':'sort'}.get(field, field)
if has_case_change:
field = field[1:]
acc = field == 'series'
def func(self, book_id, val, notify=True, commit=True, allow_case_change=acc):
ret = self.new_api.set_field(field, {book_id:val}, allow_case_change=allow_case_change)
if notify:
self.notify([book_id])
return ret
elif field == 'has_cover':
def func(self, book_id, val):
self.new_api.set_field('cover', {book_id:bool(val)})
else:
null_field = field in {'title', 'sort', 'uuid'}
retval = (True if field == 'sort' else None)
def func(self, book_id, val, notify=True, commit=True):
if not val and null_field:
return (False if field == 'sort' else None)
ret = self.new_api.set_field(field, {book_id:val})
if notify:
self.notify([book_id])
return ret if field == 'languages' else retval
return func
setattr(LibraryDatabase, 'set_%s' % field.replace('!', ''), setter(field))
for field in ('authors', 'tags', 'publisher'):
def renamer(field):
def func(self, old_id, new_name):
id_map = self.new_api.rename_items(field, {old_id:new_name})[1]
if field == 'authors':
return id_map[old_id]
return func
fname = field[:-1] if field in {'tags', 'authors'} else field
setattr(LibraryDatabase, 'rename_%s' % fname, renamer(field))
LibraryDatabase.update_last_modified = lambda self, book_ids, commit=False, now=None: self.new_api.update_last_modified(book_ids, now=now)
# }}}
# Legacy API to get information about many-(one, many) fields {{{
for field in ('authors', 'tags', 'publisher', 'series'):
def getter(field):
def func(self):
return self.new_api.all_field_names(field)
return func
name = field[:-1] if field in {'authors', 'tags'} else field
setattr(LibraryDatabase, 'all_%s_names' % name, getter(field))
LibraryDatabase.all_formats = lambda self:self.new_api.all_field_names('formats')
LibraryDatabase.all_custom = lambda self, label=None, num=None:self.new_api.all_field_names(self.custom_field_name(label, num))
for func, field in iteritems({'all_authors':'authors', 'all_titles':'title', 'all_tags2':'tags', 'all_series':'series', 'all_publishers':'publisher'}):
def getter(field):
def func(self):
return self.field_id_map(field)
return func
setattr(LibraryDatabase, func, getter(field))
LibraryDatabase.all_tags = lambda self: list(self.all_tag_names())
LibraryDatabase.get_all_identifier_types = lambda self: list(self.new_api.fields['identifiers'].table.all_identifier_types())
LibraryDatabase.get_authors_with_ids = lambda self: [[aid, adata['name'], adata['sort'], adata['link']] for aid, adata in iteritems(self.new_api.author_data())]
LibraryDatabase.get_author_id = lambda self, author: {icu_lower(v):k for k, v in iteritems(self.new_api.get_id_map('authors'))}.get(icu_lower(author), None)
for field in ('tags', 'series', 'publishers', 'ratings', 'languages'):
def getter(field):
fname = field[:-1] if field in {'publishers', 'ratings'} else field
def func(self):
return [[tid, tag] for tid, tag in iteritems(self.new_api.get_id_map(fname))]
return func
setattr(LibraryDatabase, 'get_%s_with_ids' % field, getter(field))
for field in ('author', 'tag', 'series'):
def getter(field):
field = field if field == 'series' else (field+'s')
def func(self, item_id):
return self.new_api.get_item_name(field, item_id)
return func
setattr(LibraryDatabase, '%s_name' % field, getter(field))
for field in ('publisher', 'series', 'tag'):
def getter(field):
fname = 'tags' if field == 'tag' else field
def func(self, item_id):
self.new_api.remove_items(fname, (item_id,))
return func
setattr(LibraryDatabase, 'delete_%s_using_id' % field, getter(field))
# }}}
# Legacy field API {{{
for func in (
'standard_field_keys', '!custom_field_keys', 'all_field_keys',
'searchable_fields', 'sortable_field_keys',
'search_term_to_field_key', '!custom_field_metadata',
'all_metadata'):
def getter(func):
if func.startswith('!'):
func = func[1:]
def meth(self, include_composites=True):
return getattr(self.field_metadata, func)(include_composites=include_composites)
elif func == 'search_term_to_field_key':
def meth(self, term):
return self.field_metadata.search_term_to_field_key(term)
else:
def meth(self):
return getattr(self.field_metadata, func)()
return meth
setattr(LibraryDatabase, func.replace('!', ''), getter(func))
LibraryDatabase.metadata_for_field = lambda self, field:self.field_metadata.get(field)
# }}}
# Miscellaneous API {{{
for meth in ('get_next_series_num_for', 'has_book',):
def getter(meth):
def func(self, x):
return getattr(self.new_api, meth)(x)
return func
setattr(LibraryDatabase, meth, getter(meth))
LibraryDatabase.saved_search_names = lambda self:self.new_api.saved_search_names()
LibraryDatabase.saved_search_lookup = lambda self, x:self.new_api.saved_search_lookup(x)
LibraryDatabase.saved_search_set_all = lambda self, smap:self.new_api.saved_search_set_all(smap)
LibraryDatabase.saved_search_delete = lambda self, x:self.new_api.saved_search_delete(x)
LibraryDatabase.saved_search_add = lambda self, x, y:self.new_api.saved_search_add(x, y)
LibraryDatabase.saved_search_rename = lambda self, x, y:self.new_api.saved_search_rename(x, y)
LibraryDatabase.commit_dirty_cache = lambda self: self.new_api.commit_dirty_cache()
LibraryDatabase.author_sort_from_authors = lambda self, x: self.new_api.author_sort_from_authors(x)
# Cleaning is not required anymore
LibraryDatabase.clean = LibraryDatabase.clean_custom = lambda self:None
LibraryDatabase.clean_standard_field = lambda self, field, commit=False:None
# apsw operates in autocommit mode
LibraryDatabase.commit = lambda self:None
# }}}
| 44,508 | Python | .py | 849 | 43.519435 | 160 | 0.641633 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,069 | cache.py | kovidgoyal_calibre/src/calibre/db/cache.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import hashlib
import operator
import os
import random
import shutil
import sys
import traceback
import weakref
from collections import defaultdict
from collections.abc import MutableSet, Set
from functools import partial, wraps
from io import DEFAULT_BUFFER_SIZE, BytesIO
from queue import Queue
from threading import Lock
from time import mktime, monotonic, sleep, time
from typing import NamedTuple, Optional, Tuple
from calibre import as_unicode, detect_ncpus, isbytestring
from calibre.constants import iswindows, preferred_encoding
from calibre.customize.ui import run_plugins_on_import, run_plugins_on_postadd, run_plugins_on_postdelete, run_plugins_on_postimport
from calibre.db import SPOOL_SIZE, _get_next_series_num_for_list
from calibre.db.annotations import merge_annotations
from calibre.db.categories import get_categories
from calibre.db.constants import COVER_FILE_NAME, DATA_DIR_NAME, NOTES_DIR_NAME
from calibre.db.errors import NoSuchBook, NoSuchFormat
from calibre.db.fields import IDENTITY, InvalidLinkTable, create_field
from calibre.db.lazy import FormatMetadata, FormatsList, ProxyMetadata
from calibre.db.listeners import EventDispatcher, EventType
from calibre.db.locking import DowngradeLockError, LockingError, SafeReadLock, create_locks, try_lock
from calibre.db.notes.connect import copy_marked_up_text
from calibre.db.search import Search
from calibre.db.tables import VirtualTable
from calibre.db.utils import type_safe_sort_key_function
from calibre.db.write import get_series_values, uniq
from calibre.ebooks import check_ebook_format
from calibre.ebooks.metadata import author_to_author_sort, string_to_authors, title_sort
from calibre.ebooks.metadata.book.base import Metadata
from calibre.ebooks.metadata.opf2 import metadata_to_opf
from calibre.ptempfile import PersistentTemporaryFile, SpooledTemporaryFile, base_dir
from calibre.utils.config import prefs, tweaks
from calibre.utils.date import UNDEFINED_DATE, is_date_undefined, timestampfromdt, utcnow
from calibre.utils.date import now as nowf
from calibre.utils.filenames import make_long_path_useable
from calibre.utils.icu import lower as icu_lower
from calibre.utils.icu import sort_key
from calibre.utils.localization import canonicalize_lang
from polyglot.builtins import cmp, iteritems, itervalues, string_or_bytes
class ExtraFile(NamedTuple):
relpath: str
file_path: str
stat_result: os.stat_result
def api(f):
f.is_cache_api = True
return f
def read_api(f):
f = api(f)
f.is_read_api = True
return f
def write_api(f):
f = api(f)
f.is_read_api = False
return f
def wrap_simple(lock, func):
@wraps(func)
def call_func_with_lock(*args, **kwargs):
try:
with lock:
return func(*args, **kwargs)
except DowngradeLockError:
# We already have an exclusive lock, no need to acquire a shared
# lock. See the safe_read_lock properties' documentation for why
# this is necessary.
return func(*args, **kwargs)
return call_func_with_lock
def run_import_plugins(path_or_stream, fmt):
fmt = fmt.lower()
if hasattr(path_or_stream, 'seek'):
path_or_stream.seek(0)
pt = PersistentTemporaryFile('_import_plugin.'+fmt)
shutil.copyfileobj(path_or_stream, pt, 1024**2)
pt.close()
path = pt.name
else:
path = path_or_stream
return run_plugins_on_import(path, fmt)
def _add_newbook_tag(mi):
tags = prefs['new_book_tags']
if tags:
for tag in [t.strip() for t in tags]:
if tag:
if not mi.tags:
mi.tags = [tag]
elif tag not in mi.tags:
mi.tags.append(tag)
def _add_default_custom_column_values(mi, fm):
cols = fm.custom_field_metadata(include_composites=False)
for cc,col in iteritems(cols):
dv = col['display'].get('default_value', None)
try:
if dv is not None:
if not mi.get_user_metadata(cc, make_copy=False):
mi.set_user_metadata(cc, col)
dt = col['datatype']
if dt == 'datetime' and icu_lower(dv) == 'now':
dv = nowf()
mi.set(cc, dv)
except:
traceback.print_exc()
dynamic_category_preferences = frozenset({'grouped_search_make_user_categories', 'grouped_search_terms', 'user_categories'})
class Cache:
'''
An in-memory cache of the metadata.db file from a calibre library.
This class also serves as a threadsafe API for accessing the database.
The in-memory cache is maintained in normal form for maximum performance.
SQLITE is simply used as a way to read and write from metadata.db robustly.
All table reading/sorting/searching/caching logic is re-implemented. This
was necessary for maximum performance and flexibility.
'''
EventType = EventType
fts_indexing_sleep_time = 4 # seconds
def __init__(self, backend, library_database_instance=None):
self.shutting_down = False
self.is_doing_rebuild_or_vacuum = False
self.backend = backend
self.library_database_instance = (None if library_database_instance is None else
weakref.ref(library_database_instance))
self.event_dispatcher = EventDispatcher()
self.fields = {}
self.composites = {}
self.read_lock, self.write_lock = create_locks()
self.format_metadata_cache = defaultdict(dict)
self.formatter_template_cache = {}
self.dirtied_cache = {}
self.link_maps_cache = {}
self.extra_files_cache = {}
self.vls_for_books_cache = None
self.vls_for_books_lib_in_process = None
self.vls_cache_lock = Lock()
self.dirtied_sequence = 0
self.cover_caches = set()
self.clear_search_cache_count = 0
# Implement locking for all simple read/write API methods
# An unlocked version of the method is stored with the name starting
# with a leading underscore. Use the unlocked versions when the lock
# has already been acquired.
for name in dir(self):
func = getattr(self, name)
ira = getattr(func, 'is_read_api', None)
if ira is not None:
# Save original function
setattr(self, '_'+name, func)
# Wrap it in a lock
lock = self.read_lock if ira else self.write_lock
setattr(self, name, wrap_simple(lock, func))
self._search_api = Search(self, 'saved_searches', self.field_metadata.get_search_terms())
self.initialize_dynamic()
self.initialize_fts()
@property
def new_api(self):
return self
@property
def library_id(self):
return self.backend.library_id
@property
def dbpath(self):
return self.backend.dbpath
@property
def is_fat_filesystem(self):
return self.backend.is_fat_filesystem
@property
def safe_read_lock(self):
''' A safe read lock is a lock that does nothing if the thread already
has a write lock, otherwise it acquires a read lock. This is necessary
to prevent DowngradeLockErrors, which can happen when updating the
search cache in the presence of composite columns. Updating the search
cache holds an exclusive lock, but searching a composite column
involves reading field values via ProxyMetadata which tries to get a
shared lock. There may be other scenarios that trigger this as well.
This property returns a new lock object on every access. This lock
object is not recursive (for performance) and must only be used in a
with statement as ``with cache.safe_read_lock:`` otherwise bad things
will happen.'''
return SafeReadLock(self.read_lock)
@write_api
def ensure_has_search_category(self, fail_on_existing=True):
if len(self._search_api.saved_searches.names()) > 0:
self.field_metadata.add_search_category(label='search', name=_('Saved searches'), fail_on_existing=fail_on_existing)
def _initialize_dynamic_categories(self):
# Reconstruct the user categories, putting them into field_metadata
fm = self.field_metadata
fm.remove_dynamic_categories()
for user_cat in sorted(self._pref('user_categories', {}), key=sort_key):
cat_name = '@' + user_cat # add the '@' to avoid name collision
while cat_name:
try:
fm.add_user_category(label=cat_name, name=user_cat)
except ValueError:
break # Can happen since we are removing dots and adding parent categories ourselves
cat_name = cat_name.rpartition('.')[0]
# add grouped search term user categories
muc = frozenset(self._pref('grouped_search_make_user_categories', []))
for cat in sorted(self._pref('grouped_search_terms', {}), key=sort_key):
if cat in muc:
# There is a chance that these can be duplicates of an existing
# user category. Print the exception and continue.
try:
self.field_metadata.add_user_category(label='@' + cat, name=cat)
except ValueError:
traceback.print_exc()
self._ensure_has_search_category()
self.field_metadata.add_grouped_search_terms(
self._pref('grouped_search_terms', {}))
self._refresh_search_locations()
@write_api
def initialize_dynamic(self):
self.backend.dirty_books_with_dirtied_annotations()
self.dirtied_cache = {x:i for i, x in enumerate(self.backend.dirtied_books())}
if self.dirtied_cache:
self.dirtied_sequence = max(itervalues(self.dirtied_cache))+1
self._initialize_dynamic_categories()
@write_api
def initialize_template_cache(self):
self.formatter_template_cache = {}
@write_api
def set_user_template_functions(self, user_template_functions):
self.backend.set_user_template_functions(user_template_functions)
@write_api
def clear_composite_caches(self, book_ids=None):
for field in itervalues(self.composites):
field.clear_caches(book_ids=book_ids)
@write_api
def clear_search_caches(self, book_ids=None):
self.clear_search_cache_count += 1
self._search_api.update_or_clear(self, book_ids)
self.vls_for_books_cache = None
self.vls_for_books_lib_in_process = None
@write_api
def clear_extra_files_cache(self, book_id=None):
if book_id is None:
self.extra_files_cache = {}
else:
self.extra_files_cache.pop(book_id, None)
@read_api
def last_modified(self):
return self.backend.last_modified()
@write_api
def clear_caches(self, book_ids=None, template_cache=True, search_cache=True):
if template_cache:
self._initialize_template_cache() # Clear the formatter template cache
for field in itervalues(self.fields):
if hasattr(field, 'clear_caches'):
field.clear_caches(book_ids=book_ids) # Clear the composite cache and ondevice caches
if book_ids:
for book_id in book_ids:
self.format_metadata_cache.pop(book_id, None)
else:
self.format_metadata_cache.clear()
if search_cache:
self._clear_search_caches(book_ids)
self._clear_link_map_cache(book_ids)
@write_api
def clear_link_map_cache(self, book_ids=None):
if book_ids is None:
self.link_maps_cache = {}
else:
for book in book_ids:
self.link_maps_cache.pop(book, None)
@write_api
def reload_from_db(self, clear_caches=True):
if clear_caches:
self._clear_caches()
with self.backend.conn: # Prevent other processes, such as calibredb from interrupting the reload by locking the db
self.backend.prefs.load_from_db()
self._search_api.saved_searches.load_from_db()
for field in itervalues(self.fields):
if hasattr(field, 'table'):
field.table.read(self.backend) # Reread data from metadata.db
@property
def field_metadata(self):
return self.backend.field_metadata
def _get_metadata(self, book_id, get_user_categories=True): # {{{
mi = Metadata(None, template_cache=self.formatter_template_cache)
mi._proxy_metadata = ProxyMetadata(self, book_id, formatter=mi.formatter)
author_ids = self._field_ids_for('authors', book_id)
adata = self._author_data(author_ids)
aut_list = [adata[i] for i in author_ids]
aum = []
aus = {}
for rec in aut_list:
aut = rec['name']
aum.append(aut)
aus[aut] = rec['sort']
mi.title = self._field_for('title', book_id,
default_value=_('Unknown'))
mi.authors = aum
mi.author_sort = self._field_for('author_sort', book_id,
default_value=_('Unknown'))
mi.author_sort_map = aus
mi.comments = self._field_for('comments', book_id)
mi.publisher = self._field_for('publisher', book_id)
n = utcnow()
mi.timestamp = self._field_for('timestamp', book_id, default_value=n)
mi.pubdate = self._field_for('pubdate', book_id, default_value=n)
mi.uuid = self._field_for('uuid', book_id,
default_value='dummy')
mi.title_sort = self._field_for('sort', book_id,
default_value=_('Unknown'))
mi.last_modified = self._field_for('last_modified', book_id,
default_value=n)
formats = self._field_for('formats', book_id)
mi.format_metadata = {}
mi.languages = list(self._field_for('languages', book_id))
if not formats:
good_formats = None
else:
mi.format_metadata = FormatMetadata(self, book_id, formats)
good_formats = FormatsList(sorted(formats), mi.format_metadata)
# These three attributes are returned by the db2 get_metadata(),
# however, we dont actually use them anywhere other than templates, so
# they have been removed, to avoid unnecessary overhead. The templates
# all use _proxy_metadata.
# mi.book_size = self._field_for('size', book_id, default_value=0)
# mi.ondevice_col = self._field_for('ondevice', book_id, default_value='')
# mi.db_approx_formats = formats
mi.formats = good_formats
mi.has_cover = _('Yes') if self._field_for('cover', book_id,
default_value=False) else ''
mi.tags = list(self._field_for('tags', book_id, default_value=()))
mi.series = self._field_for('series', book_id)
if mi.series:
mi.series_index = self._field_for('series_index', book_id,
default_value=1.0)
mi.rating = self._field_for('rating', book_id)
mi.set_identifiers(self._field_for('identifiers', book_id,
default_value={}))
mi.application_id = book_id
mi.id = book_id
for key, meta in self.field_metadata.custom_iteritems():
mi.set_user_metadata(key, meta)
if meta['datatype'] != 'composite':
# composites are evaluated on demand in metadata.book.base
# because their value is None
val = self._field_for(key, book_id)
if isinstance(val, tuple):
val = list(val)
extra = self._field_for(key+'_index', book_id)
mi.set(key, val=val, extra=extra)
mi.link_maps = self._get_all_link_maps_for_book(book_id)
user_cat_vals = {}
if get_user_categories:
user_cats = self._pref('user_categories', {})
for ucat in user_cats:
res = []
for name,cat,ign in user_cats[ucat]:
v = mi.get(cat, None)
if isinstance(v, list):
if name in v:
res.append([name,cat])
elif name == v:
res.append([name,cat])
user_cat_vals[ucat] = res
mi.user_categories = user_cat_vals
return mi
# }}}
@api
def init(self):
'''
Initialize this cache with data from the backend.
'''
with self.write_lock:
self.backend.read_tables()
bools_are_tristate = self.backend.prefs['bools_are_tristate']
for field, table in iteritems(self.backend.tables):
self.fields[field] = create_field(field, table, bools_are_tristate,
self.backend.get_template_functions)
if table.metadata['datatype'] == 'composite':
self.composites[field] = self.fields[field]
self.fields['ondevice'] = create_field('ondevice',
VirtualTable('ondevice'), bools_are_tristate,
self.backend.get_template_functions)
for name, field in iteritems(self.fields):
if name[0] == '#' and name.endswith('_index'):
field.series_field = self.fields[name[:-len('_index')]]
self.fields[name[:-len('_index')]].index_field = field
elif name == 'series_index':
field.series_field = self.fields['series']
self.fields['series'].index_field = field
elif name == 'authors':
field.author_sort_field = self.fields['author_sort']
elif name == 'title':
field.title_sort_field = self.fields['sort']
if self.backend.prefs['update_all_last_mod_dates_on_start']:
self.update_last_modified(self.all_book_ids())
self.backend.prefs.set('update_all_last_mod_dates_on_start', False)
# FTS API {{{
def initialize_fts(self):
self.fts_queue_thread = None
self.fts_measuring_rate = None
self.fts_num_done_since_start = 0
self.fts_job_queue = Queue()
self.fts_indexing_left = self.fts_indexing_total = 0
fts = self.backend.initialize_fts(weakref.ref(self))
if self.is_fts_enabled():
self.start_fts_pool()
return fts
def start_fts_pool(self):
from threading import Event, Thread
self.fts_dispatch_stop_event = Event()
self.fts_queue_thread = Thread(name='FTSQueue', target=Cache.dispatch_fts_jobs, args=(
self.fts_job_queue, self.fts_dispatch_stop_event, weakref.ref(self)), daemon=True)
self.fts_queue_thread.start()
self.backend.fts.pool.initialize()
self.backend.fts.pool.initialized.wait()
self.queue_next_fts_job()
@read_api
def is_fts_enabled(self):
return self.backend.fts_enabled
@write_api
def fts_start_measuring_rate(self, measure=True):
self.fts_measuring_rate = monotonic() if measure else None
self.fts_num_done_since_start = 0
def _update_fts_indexing_numbers(self, job_time=None):
# this is called when new formats are added and when a format is
# indexed, but NOT when books or formats are deleted, so total may not
# be up to date.
nl = self.backend.fts.number_dirtied()
nt = self.backend.get('SELECT COUNT(*) FROM main.data')[0][0] or 0
if not nl:
self._fts_start_measuring_rate(measure=False)
if job_time is not None and self.fts_measuring_rate is not None:
self.fts_num_done_since_start += 1
if (self.fts_indexing_left, self.fts_indexing_total) != (nl, nt) or job_time is not None:
self.fts_indexing_left = nl
self.fts_indexing_total = nt
self.event_dispatcher(EventType.indexing_progress_changed, *self._fts_indexing_progress())
@read_api
def fts_indexing_progress(self):
rate = None
if self.fts_measuring_rate is not None and self.fts_num_done_since_start > 4:
rate = self.fts_num_done_since_start / (monotonic() - self.fts_measuring_rate)
return self.fts_indexing_left, self.fts_indexing_total, rate
@write_api
def enable_fts(self, enabled=True, start_pool=True):
fts = self.backend.enable_fts(weakref.ref(self) if enabled else None)
if fts and start_pool: # used in the tests
self.start_fts_pool()
if not fts and self.fts_queue_thread:
self.fts_job_queue.put(None)
self.fts_queue_thread = None
self.fts_job_queue = Queue()
if fts:
self._update_fts_indexing_numbers()
return fts
@write_api
def fts_unindex(self, book_id, fmt=None):
self.backend.fts_unindex(book_id, fmt=fmt)
@staticmethod
def dispatch_fts_jobs(queue, stop_dispatch, dbref):
from .fts.text import is_fmt_ok
def do_one():
self = dbref()
if self is None:
return False
start_time = monotonic()
with self.read_lock:
if not self.backend.fts_enabled:
return False
book_id, fmt = self.backend.get_next_fts_job()
if book_id is None:
return False
path = self._format_abspath(book_id, fmt)
if not path or not is_fmt_ok(fmt):
with self.write_lock:
self.backend.remove_dirty_fts(book_id, fmt)
self._update_fts_indexing_numbers()
return True
with self.read_lock, open(path, 'rb') as src, PersistentTemporaryFile(suffix=f'.{fmt.lower()}') as pt:
sz = 0
h = hashlib.sha1()
while True:
chunk = src.read(DEFAULT_BUFFER_SIZE)
if not chunk:
break
sz += len(chunk)
h.update(chunk)
pt.write(chunk)
with self.write_lock:
queued = self.backend.queue_fts_job(book_id, fmt, pt.name, sz, h.hexdigest(), start_time)
if not queued: # means a dirtied book was removed from the dirty list because the text has not changed
self._update_fts_indexing_numbers(monotonic() - start_time)
return self.backend.fts_has_idle_workers
def loop_while_more_available():
self = dbref()
if not self or not self.backend.fts_enabled:
return
has_more = True
while has_more and not self.shutting_down and self.backend.fts_enabled and not stop_dispatch.is_set():
try:
has_more = do_one()
except Exception:
if self.backend.fts_enabled:
traceback.print_exc()
sleep(self.fts_indexing_sleep_time)
while not getattr(dbref(), 'shutting_down', True):
x = queue.get()
if x is None:
break
loop_while_more_available()
@write_api
def queue_next_fts_job(self):
if not self.backend.fts_enabled:
return
self.fts_job_queue.put(True)
self._update_fts_indexing_numbers()
@write_api
def commit_fts_result(self, book_id, fmt, fmt_size, fmt_hash, text, err_msg, start_time):
ans = self.backend.commit_fts_result(book_id, fmt, fmt_size, fmt_hash, text, err_msg)
self._update_fts_indexing_numbers(monotonic() - start_time)
return ans
@write_api
def reindex_fts_book(self, book_id, *fmts):
if not self.is_fts_enabled():
return
if not fmts:
fmts = self._formats(book_id)
self.backend.reindex_fts_book(book_id, *fmts)
self._queue_next_fts_job()
@api
def reindex_fts(self):
if not self.is_fts_enabled():
return
with self.write_lock:
self._shutdown_fts()
self._shutdown_fts(stage=2)
with self.write_lock:
self.backend.reindex_fts()
fts = self.initialize_fts()
fts.initialize(self.backend.conn) # ensure fts is pre-initialized needed for the tests
self._queue_next_fts_job()
return fts
@write_api
def set_fts_num_of_workers(self, num):
existing = self.backend.fts_num_of_workers
if num != existing:
self.backend.fts_num_of_workers = num
if num > existing:
self._queue_next_fts_job()
return True
return False
@write_api
def set_fts_speed(self, slow=True):
orig = self.fts_indexing_sleep_time
if slow:
self.fts_indexing_sleep_time = Cache.fts_indexing_sleep_time
changed = self._set_fts_num_of_workers(1)
else:
self.fts_indexing_sleep_time = 0.1
changed = self._set_fts_num_of_workers(max(1, detect_ncpus()))
changed = changed or orig != self.fts_indexing_sleep_time
if changed and self.fts_measuring_rate is not None:
self._fts_start_measuring_rate()
return changed
@write_api # we need to use write locking as SQLITE gives a locked table error if multiple FTS queries are made at the same time
def fts_search(
self,
fts_engine_query,
use_stemming=True,
highlight_start=None,
highlight_end=None,
snippet_size=None,
restrict_to_book_ids=None,
return_text=True,
result_type=tuple,
process_each_result=None,
):
return result_type(self.backend.fts_search(
fts_engine_query,
use_stemming=use_stemming,
highlight_start=highlight_start,
highlight_end=highlight_end,
snippet_size=snippet_size,
return_text=return_text,
restrict_to_book_ids=restrict_to_book_ids,
process_each_result=process_each_result,
))
# }}}
# Notes API {{{
@read_api
def notes_for(self, field, item_id) -> str:
' Return the notes document or an empty string if not found '
return self.backend.notes_for(field, item_id)
@read_api
def notes_data_for(self, field, item_id) -> str:
' Return all notes data as a dict or None if note does not exist '
return self.backend.notes_data_for(field, item_id)
@read_api
def get_all_items_that_have_notes(self, field_name=None) -> set[int] | dict[str, set[int]]:
' Return all item_ids for items that have notes in the specified field or all fields if field_name is None '
return self.backend.get_all_items_that_have_notes(field_name)
@read_api
def field_supports_notes(self, field=None) -> bool:
' Return True iff the specified field supports notes. If field is None return frozenset of all fields that support notes. '
if field is None:
return self.backend.notes.allowed_fields
return field in self.backend.notes.allowed_fields
@read_api
def items_with_notes_in_book(self, book_id: int) -> dict[str, dict[int, str]]:
' Return a dict of field to items that have associated notes for that field for the specified book '
ans = {}
for k in self.backend.notes.allowed_fields:
try:
field = self.fields[k]
except KeyError:
continue
v = {}
for item_id in field.ids_for_book(book_id):
if self.backend.notes_for(k, item_id):
v[item_id] = field.table.id_map[item_id]
if v:
ans[k] = v
return ans
@write_api
def set_notes_for(self, field, item_id, doc: str, searchable_text: str = copy_marked_up_text, resource_hashes=(), remove_unused_resources=False) -> int:
'''
Set the notes document. If the searchable text is different from the document, specify it as searchable_text. If the document
references resources their hashes must be present in resource_hashes. Set remove_unused_resources to True to cleanup unused
resources, note that updating a note automatically cleans up resources pertaining to that note anyway.
'''
return self.backend.set_notes_for(field, item_id, doc, searchable_text, resource_hashes, remove_unused_resources)
@write_api
def add_notes_resource(self, path_or_stream_or_data, name: str, mtime: float = None) -> int:
' Add the specified resource so it can be referenced by notes and return its content hash '
return self.backend.add_notes_resource(path_or_stream_or_data, name, mtime)
@read_api
def get_notes_resource(self, resource_hash) -> Optional[dict]:
' Return a dict containing the resource data and name or None if no resource with the specified hash is found '
return self.backend.get_notes_resource(resource_hash)
@read_api
def notes_resources_used_by(self, field, item_id):
' Return the set of resource hashes of all resources used by the note for the specified item '
return frozenset(self.backend.notes_resources_used_by(field, item_id))
@write_api
def unretire_note_for(self, field, item_id) -> int:
' Unretire a previously retired note for the specified item. Notes are retired when an item is removed from the database '
return self.backend.unretire_note_for(field, item_id)
@read_api
def export_note(self, field, item_id) -> str:
' Export the note as a single HTML document with embedded images as data: URLs '
return self.backend.export_note(field, item_id)
@write_api
def import_note(self, field, item_id, path_to_html_file, path_is_data=False):
' Import a previously exported note or an arbitrary HTML file as the note for the specified item '
if path_is_data:
html = path_to_html_file
ctime = mtime = time()
basedir = base_dir()
else:
with open(path_to_html_file, 'rb') as f:
html = f.read()
st = os.stat(f.fileno())
ctime, mtime = st.st_ctime, st.st_mtime
basedir = os.path.dirname(os.path.abspath(path_to_html_file))
return self.backend.import_note(field, item_id, html, basedir, ctime, mtime)
@write_api # we need to use write locking as SQLITE gives a locked table error if multiple FTS queries are made at the same time
def search_notes(
self,
fts_engine_query='',
use_stemming=True,
highlight_start=None,
highlight_end=None,
snippet_size=None,
restrict_to_fields=(),
return_text=True,
result_type=tuple,
process_each_result=None,
limit=None,
):
' Search the text of notes using an FTS index. If the query is empty return all notes. '
return result_type(self.backend.search_notes(
fts_engine_query,
use_stemming=use_stemming,
highlight_start=highlight_start,
highlight_end=highlight_end,
snippet_size=snippet_size,
return_text=return_text,
restrict_to_fields=restrict_to_fields,
process_each_result=process_each_result,
limit=limit,
))
# }}}
# Cache Layer API {{{
@write_api
def add_listener(self, event_callback_function, check_already_added=False):
'''
Register a callback function that will be called after certain actions are
taken on this database. The function must take three arguments:
(:class:`EventType`, library_id, event_type_specific_data)
'''
self.event_dispatcher.library_id = getattr(self, 'server_library_id', self.library_id)
if check_already_added and event_callback_function in self.event_dispatcher:
return False
self.event_dispatcher.add_listener(event_callback_function)
return True
@write_api
def remove_listener(self, event_callback_function):
self.event_dispatcher.remove_listener(event_callback_function)
@read_api
def field_for(self, name, book_id, default_value=None):
'''
Return the value of the field ``name`` for the book identified
by ``book_id``. If no such book exists or it has no defined
value for the field ``name`` or no such field exists, then
``default_value`` is returned.
``default_value`` is not used for title, title_sort, authors, author_sort
and series_index. This is because these always have values in the db.
``default_value`` is used for all custom columns.
The returned value for is_multiple fields are always tuples, even when
no values are found (in other words, default_value is ignored). The
exception is identifiers for which the returned value is always a dictionary.
The returned tuples are always in link order, that is, the order in
which they were created.
'''
if self.composites and name in self.composites:
return self.composite_for(name, book_id,
default_value=default_value)
try:
field = self.fields[name]
except KeyError:
return default_value
if field.is_multiple:
default_value = field.default_value
try:
return field.for_book(book_id, default_value=default_value)
except (KeyError, IndexError):
return default_value
@read_api
def fast_field_for(self, field_obj, book_id, default_value=None):
' Same as field_for, except that it avoids the extra lookup to get the field object '
if field_obj.is_composite:
return field_obj.get_value_with_cache(book_id, self._get_proxy_metadata)
if field_obj.is_multiple:
default_value = field_obj.default_value
try:
return field_obj.for_book(book_id, default_value=default_value)
except (KeyError, IndexError):
return default_value
@read_api
def all_field_for(self, field, book_ids, default_value=None):
' Same as field_for, except that it operates on multiple books at once '
field_obj = self.fields[field]
return {book_id:self._fast_field_for(field_obj, book_id, default_value=default_value) for book_id in book_ids}
@read_api
def composite_for(self, name, book_id, mi=None, default_value=''):
try:
f = self.fields[name]
except KeyError:
return default_value
if mi is None:
return f.get_value_with_cache(book_id, self._get_proxy_metadata)
else:
return f._render_composite_with_cache(book_id, mi, mi.formatter, mi.template_cache)
@read_api
def field_ids_for(self, name, book_id):
'''
Return the ids (as a tuple) for the values that the field ``name`` has on the book
identified by ``book_id``. If there are no values, or no such book, or
no such field, an empty tuple is returned.
'''
try:
return self.fields[name].ids_for_book(book_id)
except (KeyError, IndexError):
return ()
@read_api
def books_for_field(self, name, item_id):
'''
Return all the books associated with the item identified by
``item_id``, where the item belongs to the field ``name``.
Returned value is a set of book ids, or the empty set if the item
or the field does not exist.
'''
try:
return self.fields[name].books_for(item_id)
except (KeyError, IndexError):
return set()
@read_api
def all_book_ids(self, type=frozenset):
'''
Frozen set of all known book ids.
'''
return type(self.fields['uuid'].table.book_col_map)
@read_api
def all_field_ids(self, name):
'''
Frozen set of ids for all values in the field ``name``.
'''
return frozenset(iter(self.fields[name]))
@read_api
def all_field_names(self, field):
''' Frozen set of all fields names (should only be used for many-one and many-many fields) '''
if field == 'formats':
return frozenset(self.fields[field].table.col_book_map)
try:
return frozenset(self.fields[field].table.id_map.values())
except AttributeError:
raise ValueError('%s is not a many-one or many-many field' % field)
@read_api
def get_usage_count_by_id(self, field):
''' Return a mapping of id to usage count for all values of the specified
field, which must be a many-one or many-many field. '''
try:
return {k:len(v) for k, v in iteritems(self.fields[field].table.col_book_map)}
except AttributeError:
raise ValueError('%s is not a many-one or many-many field' % field)
@read_api
def get_id_map(self, field):
''' Return a mapping of id numbers to values for the specified field.
The field must be a many-one or many-many field, otherwise a ValueError
is raised. '''
try:
return self.fields[field].table.id_map.copy()
except AttributeError:
if field == 'title':
return self.fields[field].table.book_col_map.copy()
raise ValueError('%s is not a many-one or many-many field' % field)
@read_api
def get_item_name(self, field, item_id):
''' Return the item name for the item specified by item_id in the
specified field. See also :meth:`get_id_map`.'''
return self.fields[field].table.id_map[item_id]
@read_api
def get_item_id(self, field, item_name, case_sensitive=False):
''' Return the item id for item_name or None if not found.
This function is very slow if doing lookups for multiple names use either get_item_ids() or get_item_name_map().
Similarly, case sensitive lookups are faster than case insensitive ones. '''
field = self.fields[field]
if hasattr(field, 'item_ids_for_names'):
d = field.item_ids_for_names(self.backend, (item_name,), case_sensitive)
for v in d.values():
return v
@read_api
def get_item_ids(self, field, item_names, case_sensitive=False):
' Return a dict mapping item_name to the item id or None '
field = self.fields[field]
if hasattr(field, 'item_ids_for_names'):
return field.item_ids_for_names(self.backend, item_names, case_sensitive)
return dict.fromkeys(item_names)
@read_api
def get_item_name_map(self, field, normalize_func=None):
' Return mapping of item values to ids '
if normalize_func is None:
return {v:k for k, v in self.fields[field].table.id_map.items()}
return {normalize_func(v):k for k, v in self.fields[field].table.id_map.items()}
@read_api
def author_data(self, author_ids=None):
'''
Return author data as a dictionary with keys: name, sort, link
If no authors with the specified ids are found an empty dictionary is
returned. If author_ids is None, data for all authors is returned.
'''
af = self.fields['authors']
if author_ids is None:
return {aid:af.author_data(aid) for aid in af.table.id_map}
return {aid:af.author_data(aid) for aid in author_ids if aid in af.table.id_map}
@read_api
def format_hash(self, book_id, fmt):
''' Return the hash of the specified format for the specified book. The
kind of hash is backend dependent, but is usually SHA-256. '''
try:
name = self.fields['formats'].format_fname(book_id, fmt)
path = self._field_for('path', book_id).replace('/', os.sep)
except:
raise NoSuchFormat('Record %d has no fmt: %s'%(book_id, fmt))
return self.backend.format_hash(book_id, fmt, name, path)
@api
def format_metadata(self, book_id, fmt, allow_cache=True, update_db=False):
'''
Return the path, size and mtime for the specified format for the specified book.
You should not use path unless you absolutely have to,
since accessing it directly breaks the threadsafe guarantees of this API. Instead use
the :meth:`copy_format_to` method.
:param allow_cache: If ``True`` cached values are used, otherwise a
slow filesystem access is done. The cache values could be out of date
if access was performed to the filesystem outside of this API.
:param update_db: If ``True`` The max_size field of the database is updated for this book.
'''
if not fmt:
return {}
fmt = fmt.upper()
# allow_cache and update_db are mutually exclusive. Give priority to update_db
if allow_cache and not update_db:
x = self.format_metadata_cache[book_id].get(fmt, None)
if x is not None:
return x
with self.safe_read_lock:
try:
name = self.fields['formats'].format_fname(book_id, fmt)
path = self._field_for('path', book_id).replace('/', os.sep)
except:
return {}
ans = {}
if path and name:
ans = self.backend.format_metadata(book_id, fmt, name, path)
self.format_metadata_cache[book_id][fmt] = ans
if update_db and 'size' in ans:
with self.write_lock:
max_size = self.fields['formats'].table.update_fmt(book_id, fmt, name, ans['size'], self.backend)
self.fields['size'].table.update_sizes({book_id: max_size})
return ans
@read_api
def format_files(self, book_id):
field = self.fields['formats']
fmts = field.table.book_col_map.get(book_id, ())
return {fmt:field.format_fname(book_id, fmt) for fmt in fmts}
@read_api
def format_db_size(self, book_id, fmt):
field = self.fields['formats']
return field.format_size(book_id, fmt)
@read_api
def pref(self, name, default=None, namespace=None):
' Return the value for the specified preference or the value specified as ``default`` if the preference is not set. '
if namespace is not None:
return self.backend.prefs.get_namespaced(namespace, name, default)
return self.backend.prefs.get(name, default)
@write_api
def set_pref(self, name, val, namespace=None):
' Set the specified preference to the specified value. See also :meth:`pref`. '
if namespace is not None:
self.backend.prefs.set_namespaced(namespace, name, val)
return
self.backend.prefs.set(name, val)
if name in ('grouped_search_terms', 'virtual_libraries'):
self._clear_search_caches()
if name in dynamic_category_preferences:
self._initialize_dynamic_categories()
@api
def get_metadata(self, book_id,
get_cover=False, get_user_categories=True, cover_as_data=False):
'''
Return metadata for the book identified by book_id as a :class:`calibre.ebooks.metadata.book.base.Metadata` object.
Note that the list of formats is not verified. If get_cover is True,
the cover is returned, either a path to temp file as mi.cover or if
cover_as_data is True then as mi.cover_data.
'''
# Check if virtual_libraries_for_books rebuilt its cache. If it did then
# we must clear the composite caches so the new data can be taken into
# account. Clearing the caches requires getting a write lock, so it must
# be done outside of the closure of _get_metadata().
composite_cache_needs_to_be_cleared = False
with self.safe_read_lock:
vl_cache_was_none = self.vls_for_books_cache is None
mi = self._get_metadata(book_id, get_user_categories=get_user_categories)
if vl_cache_was_none and self.vls_for_books_cache is not None:
composite_cache_needs_to_be_cleared = True
if composite_cache_needs_to_be_cleared:
try:
self.clear_composite_caches()
except LockingError:
# We can't clear the composite caches because a read lock is set.
# As a consequence the value of a composite column that calls
# virtual_libraries() might be wrong. Oh well. Log and keep running.
print('Couldn\'t get write lock after vls_for_books_cache was loaded', file=sys.stderr)
traceback.print_exc()
if get_cover:
if cover_as_data:
cdata = self.cover(book_id)
if cdata:
mi.cover_data = ('jpeg', cdata)
else:
mi.cover = self.cover(book_id, as_path=True)
return mi
@read_api
def get_proxy_metadata(self, book_id):
''' Like :meth:`get_metadata` except that it returns a ProxyMetadata
object that only reads values from the database on demand. This is much
faster than get_metadata when only a small number of fields need to be
accessed from the returned metadata object. '''
return ProxyMetadata(self, book_id)
@api
def cover(self, book_id,
as_file=False, as_image=False, as_path=False, as_pixmap=False):
'''
Return the cover image or None. By default, returns the cover as a
bytestring.
WARNING: Using as_path will copy the cover to a temp file and return
the path to the temp file. You should delete the temp file when you are
done with it.
:param as_file: If True return the image as an open file object (a SpooledTemporaryFile)
:param as_image: If True return the image as a QImage object
:param as_pixmap: If True return the image as a QPixmap object
:param as_path: If True return the image as a path pointing to a
temporary file
'''
if as_file:
ret = SpooledTemporaryFile(SPOOL_SIZE)
if not self.copy_cover_to(book_id, ret):
ret.close()
return
ret.seek(0)
elif as_path:
pt = PersistentTemporaryFile('_dbcover.jpg')
with pt:
if not self.copy_cover_to(book_id, pt):
return
ret = pt.name
elif as_pixmap or as_image:
from qt.core import QImage, QPixmap
ret = QImage() if as_image else QPixmap()
with self.safe_read_lock:
path = self._format_abspath(book_id, '__COVER_INTERNAL__')
if path:
ret.load(path)
else:
buf = BytesIO()
if not self.copy_cover_to(book_id, buf):
return
ret = buf.getvalue()
return ret
@read_api
def cover_or_cache(self, book_id, timestamp, as_what='bytes'):
try:
path = self._field_for('path', book_id).replace('/', os.sep)
except AttributeError:
return False, None, None
return self.backend.cover_or_cache(path, timestamp, as_what)
@read_api
def cover_last_modified(self, book_id):
try:
path = self._field_for('path', book_id).replace('/', os.sep)
except AttributeError:
return
return self.backend.cover_last_modified(path)
@read_api
def copy_cover_to(self, book_id, dest, use_hardlink=False, report_file_size=None):
'''
Copy the cover to the file like object ``dest``. Returns False
if no cover exists or dest is the same file as the current cover.
dest can also be a path in which case the cover is
copied to it if and only if the path is different from the current path (taking
case sensitivity into account).
'''
try:
path = self._field_for('path', book_id).replace('/', os.sep)
except AttributeError:
return False
return self.backend.copy_cover_to(path, dest, use_hardlink=use_hardlink,
report_file_size=report_file_size)
@write_api
def compress_covers(self, book_ids, jpeg_quality=100, progress_callback=None):
'''
Compress the cover images for the specified books. A compression quality of 100
will perform lossless compression, otherwise lossy compression.
The progress callback will be called with the book_id and the old and new sizes
for each book that has been processed. If an error occurs, the new size will
be a string with the error details.
'''
jpeg_quality = max(10, min(jpeg_quality, 100))
path_map = {}
for book_id in book_ids:
try:
path_map[book_id] = self._field_for('path', book_id).replace('/', os.sep)
except AttributeError:
continue
self.backend.compress_covers(path_map, jpeg_quality, progress_callback)
@read_api
def copy_format_to(self, book_id, fmt, dest, use_hardlink=False, report_file_size=None):
'''
Copy the format ``fmt`` to the file like object ``dest``. If the
specified format does not exist, raises :class:`NoSuchFormat` error.
dest can also be a path (to a file), in which case the format is copied to it, iff
the path is different from the current path (taking case sensitivity
into account).
'''
fmt = (fmt or '').upper()
try:
name = self.fields['formats'].format_fname(book_id, fmt)
path = self._field_for('path', book_id).replace('/', os.sep)
except (KeyError, AttributeError):
raise NoSuchFormat('Record %d has no %s file'%(book_id, fmt))
return self.backend.copy_format_to(book_id, fmt, name, path, dest,
use_hardlink=use_hardlink, report_file_size=report_file_size)
@read_api
def format_abspath(self, book_id, fmt):
'''
Return absolute path to the e-book file of format `format`. You should
almost never use this, as it breaks the threadsafe promise of this API.
Instead use, :meth:`copy_format_to`.
Currently used only in calibredb list, the viewer, edit book,
compare_format to original format, open with, bulk metadata edit and
the catalogs (via get_data_as_dict()).
Apart from the viewer, open with and edit book, I don't believe any of
the others do any file write I/O with the results of this call.
'''
fmt = (fmt or '').upper()
try:
path = self._field_for('path', book_id).replace('/', os.sep)
except:
return None
if path:
if fmt == '__COVER_INTERNAL__':
return self.backend.cover_abspath(book_id, path)
else:
try:
name = self.fields['formats'].format_fname(book_id, fmt)
except:
return None
if name:
return self.backend.format_abspath(book_id, fmt, name, path)
@read_api
def has_format(self, book_id, fmt):
'Return True iff the format exists on disk'
fmt = (fmt or '').upper()
try:
name = self.fields['formats'].format_fname(book_id, fmt)
path = self._field_for('path', book_id).replace('/', os.sep)
except:
return False
return self.backend.has_format(book_id, fmt, name, path)
@api
def save_original_format(self, book_id, fmt):
' Save a copy of the specified format as ORIGINAL_FORMAT, overwriting any existing ORIGINAL_FORMAT. '
fmt = fmt.upper()
if 'ORIGINAL' in fmt:
raise ValueError('Cannot save original of an original fmt')
fmtfile = self.format(book_id, fmt, as_file=True)
if fmtfile is None:
return False
with fmtfile:
nfmt = 'ORIGINAL_'+fmt
return self.add_format(book_id, nfmt, fmtfile, run_hooks=False)
@write_api
def restore_original_format(self, book_id, original_fmt):
''' Restore the specified format from the previously saved
ORIGINAL_FORMAT, if any. Return True on success. The ORIGINAL_FORMAT is
deleted after a successful restore. '''
original_fmt = original_fmt.upper()
fmt = original_fmt.partition('_')[2]
try:
ofmt_name = self.fields['formats'].format_fname(book_id, original_fmt)
path = self._field_for('path', book_id).replace('/', os.sep)
except Exception:
return False
if self.backend.is_format_accessible(book_id, original_fmt, ofmt_name, path):
self.add_format(book_id, fmt, BytesIO(), run_hooks=False)
fmt_name = self.fields['formats'].format_fname(book_id, fmt)
file_size = self.backend.rename_format_file(book_id, ofmt_name, original_fmt, fmt_name, fmt, path)
self.fields['formats'].table.update_fmt(book_id, fmt, fmt_name, file_size, self.backend)
self._remove_formats({book_id:(original_fmt,)})
return True
return False
@read_api
def formats(self, book_id, verify_formats=True):
'''
Return tuple of all formats for the specified book. If verify_formats
is True, verifies that the files exist on disk.
'''
ans = self.field_for('formats', book_id)
if verify_formats and ans:
try:
path = self._field_for('path', book_id).replace('/', os.sep)
except:
return ()
def verify(fmt):
try:
name = self.fields['formats'].format_fname(book_id, fmt)
except:
return False
return self.backend.has_format(book_id, fmt, name, path)
ans = tuple(x for x in ans if verify(x))
return ans
@api
def format(self, book_id, fmt, as_file=False, as_path=False, preserve_filename=False):
'''
Return the e-book format as a bytestring or `None` if the format doesn't exist,
or we don't have permission to write to the e-book file.
:param as_file: If True the e-book format is returned as a file object. Note
that the file object is a SpooledTemporaryFile, so if what you want to
do is copy the format to another file, use :meth:`copy_format_to`
instead for performance.
:param as_path: Copies the format file to a temp file and returns the
path to the temp file
:param preserve_filename: If True and returning a path the filename is
the same as that used in the library. Note that using
this means that repeated calls yield the same
temp file (which is re-created each time)
'''
fmt = (fmt or '').upper()
ext = ('.'+fmt.lower()) if fmt else ''
if as_path:
if preserve_filename:
with self.safe_read_lock:
try:
fname = self.fields['formats'].format_fname(book_id, fmt)
except:
return None
fname += ext
bd = base_dir()
d = os.path.join(bd, 'format_abspath')
try:
os.makedirs(d)
except:
pass
ret = os.path.join(d, fname)
try:
self.copy_format_to(book_id, fmt, ret)
except NoSuchFormat:
return None
else:
with PersistentTemporaryFile(ext) as pt:
try:
self.copy_format_to(book_id, fmt, pt)
except NoSuchFormat:
return None
ret = pt.name
elif as_file:
with self.safe_read_lock:
try:
fname = self.fields['formats'].format_fname(book_id, fmt)
except:
return None
fname += ext
ret = SpooledTemporaryFile(SPOOL_SIZE)
try:
self.copy_format_to(book_id, fmt, ret)
except NoSuchFormat:
ret.close()
return None
ret.seek(0)
# Various bits of code try to use the name as the default
# title when reading metadata, so set it
ret.name = fname
else:
buf = BytesIO()
try:
self.copy_format_to(book_id, fmt, buf)
except NoSuchFormat:
return None
ret = buf.getvalue()
return ret
@read_api
def newly_added_book_ids(self, count=5, book_ids=None) -> list[int]:
ids_to_sort = self._all_book_ids(list) if book_ids is None else list(book_ids)
ids_to_sort.sort(reverse=True)
return ids_to_sort[:count]
@read_api
def size_stats(self) -> dict[str, int]:
return self.backend.size_stats()
@read_api
def multisort(self, fields, ids_to_sort=None, virtual_fields=None):
'''
Return a list of sorted book ids. If ids_to_sort is None, all book ids
are returned.
fields must be a list of 2-tuples of the form (field_name,
ascending=True or False). The most significant field is the first
2-tuple.
'''
ids_to_sort = self._all_book_ids() if ids_to_sort is None else ids_to_sort
get_metadata = self._get_proxy_metadata
lang_map = self.fields['languages'].book_value_map
virtual_fields = virtual_fields or {}
fm = {'title':'sort', 'authors':'author_sort'}
def sort_key_func(field):
'Handle series type fields, virtual fields and the id field'
idx = field + '_index'
is_series = idx in self.fields
try:
func = self.fields[fm.get(field, field)].sort_keys_for_books(get_metadata, lang_map)
except KeyError:
if field == 'id':
return IDENTITY
else:
return virtual_fields[fm.get(field, field)].sort_keys_for_books(get_metadata, lang_map)
if is_series:
idx_func = self.fields[idx].sort_keys_for_books(get_metadata, lang_map)
def skf(book_id):
return (func(book_id), idx_func(book_id))
return skf
return func
# Sort only once on any given field
fields = uniq(fields, operator.itemgetter(0))
if len(fields) == 1:
keyfunc = sort_key_func(fields[0][0])
reverse = not fields[0][1]
try:
return sorted(ids_to_sort, key=keyfunc, reverse=reverse)
except Exception as err:
print('Failed to sort database on field:', fields[0][0], 'with error:', err, file=sys.stderr)
try:
return sorted(ids_to_sort, key=type_safe_sort_key_function(keyfunc), reverse=reverse)
except Exception as err:
print('Failed to type-safe sort database on field:', fields[0][0], 'with error:', err, file=sys.stderr)
return sorted(ids_to_sort, reverse=reverse)
sort_key_funcs = tuple(sort_key_func(field) for field, order in fields)
orders = tuple(1 if order else -1 for _, order in fields)
Lazy = object() # Lazy load the sort keys for sub-sort fields
class SortKey:
__slots__ = 'book_id', 'sort_key'
def __init__(self, book_id):
self.book_id = book_id
# Calculate only the first sub-sort key since that will always be used
self.sort_key = [key(book_id) if i == 0 else Lazy for i, key in enumerate(sort_key_funcs)]
def compare_to_other(self, other):
for i, (order, self_key, other_key) in enumerate(zip(orders, self.sort_key, other.sort_key)):
if self_key is Lazy:
self_key = self.sort_key[i] = sort_key_funcs[i](self.book_id)
if other_key is Lazy:
other_key = other.sort_key[i] = sort_key_funcs[i](other.book_id)
ans = cmp(self_key, other_key)
if ans != 0:
return ans * order
return 0
def __eq__(self, other):
return self.compare_to_other(other) == 0
def __ne__(self, other):
return self.compare_to_other(other) != 0
def __lt__(self, other):
return self.compare_to_other(other) < 0
def __le__(self, other):
return self.compare_to_other(other) <= 0
def __gt__(self, other):
return self.compare_to_other(other) > 0
def __ge__(self, other):
return self.compare_to_other(other) >= 0
return sorted(ids_to_sort, key=SortKey)
@read_api
def search(self, query, restriction='', virtual_fields=None, book_ids=None):
'''
Search the database for the specified query, returning a set of matched book ids.
:param restriction: A restriction that is ANDed to the specified query. Note that
restrictions are cached, therefore the search for a AND b will be slower than a with restriction b.
:param virtual_fields: Used internally (virtual fields such as on_device to search over).
:param book_ids: If not None, a set of book ids for which books will
be searched instead of searching all books.
'''
return self._search_api(self, query, restriction, virtual_fields=virtual_fields, book_ids=book_ids)
@read_api
def books_in_virtual_library(self, vl, search_restriction=None, virtual_fields=None):
' Return the set of books in the specified virtual library '
vl = self._pref('virtual_libraries', {}).get(vl) if vl else None
if not vl and not search_restriction:
return self.all_book_ids()
# We utilize the search restriction cache to speed this up
srch = partial(self._search, virtual_fields=virtual_fields)
if vl:
if search_restriction:
return frozenset(srch('', vl) & srch('', search_restriction))
return frozenset(srch('', vl))
return frozenset(srch('', search_restriction))
@read_api
def number_of_books_in_virtual_library(self, vl=None, search_restriction=None):
if not vl and not search_restriction:
return len(self.fields['uuid'].table.book_col_map)
return len(self.books_in_virtual_library(vl, search_restriction))
@api
def get_categories(self, sort='name', book_ids=None, already_fixed=None,
first_letter_sort=False):
' Used internally to implement the Tag Browser '
try:
with self.safe_read_lock:
return get_categories(self, sort=sort, book_ids=book_ids,
first_letter_sort=first_letter_sort)
except InvalidLinkTable as err:
bad_field = err.field_name
if bad_field == already_fixed:
raise
with self.write_lock:
self.fields[bad_field].table.fix_link_table(self.backend)
return self.get_categories(sort=sort, book_ids=book_ids, already_fixed=bad_field)
@write_api
def update_last_modified(self, book_ids, now=None):
if book_ids:
if now is None:
now = nowf()
f = self.fields['last_modified']
f.writer.set_books({book_id:now for book_id in book_ids}, self.backend)
if self.composites:
self._clear_composite_caches(book_ids)
self._clear_search_caches(book_ids)
@write_api
def mark_as_dirty(self, book_ids):
self._update_last_modified(book_ids)
already_dirtied = set(self.dirtied_cache).intersection(book_ids)
new_dirtied = book_ids - already_dirtied
already_dirtied = {book_id:self.dirtied_sequence+i for i, book_id in enumerate(already_dirtied)}
if already_dirtied:
self.dirtied_sequence = max(itervalues(already_dirtied)) + 1
self.dirtied_cache.update(already_dirtied)
if new_dirtied:
self.backend.dirty_books(new_dirtied)
new_dirtied = {book_id:self.dirtied_sequence+i for i, book_id in enumerate(new_dirtied)}
self.dirtied_sequence = max(itervalues(new_dirtied)) + 1
self.dirtied_cache.update(new_dirtied)
@write_api
def commit_dirty_cache(self):
if self.dirtied_cache:
self.backend.dirty_books(self.dirtied_cache)
@write_api
def check_dirtied_annotations(self):
if not self.backend.dirty_books_with_dirtied_annotations():
return
book_ids = set(self.backend.dirtied_books())
new_dirtied = book_ids - set(self.dirtied_cache)
if new_dirtied:
new_dirtied = {book_id:self.dirtied_sequence+i for i, book_id in enumerate(new_dirtied)}
self.dirtied_sequence = max(itervalues(new_dirtied)) + 1
self.dirtied_cache.update(new_dirtied)
@write_api
def set_field(self, name, book_id_to_val_map, allow_case_change=True, do_path_update=True):
'''
Set the values of the field specified by ``name``. Returns the set of all book ids that were affected by the change.
:param book_id_to_val_map: Mapping of book_ids to values that should be applied.
:param allow_case_change: If True, the case of many-one or many-many fields will be changed.
For example, if a book has the tag ``tag1`` and you set the tag for another book to ``Tag1``
then the both books will have the tag ``Tag1`` if allow_case_change is True, otherwise they will
both have the tag ``tag1``.
:param do_path_update: Used internally, you should never change it.
'''
f = self.fields[name]
is_series = f.metadata['datatype'] == 'series'
update_path = name in {'title', 'authors'}
if update_path and iswindows:
paths = (x for x in (self._field_for('path', book_id) for book_id in book_id_to_val_map) if x)
self.backend.windows_check_if_files_in_use(paths)
if is_series:
bimap, simap = {}, {}
sfield = self.fields[name + '_index']
for k, v in iteritems(book_id_to_val_map):
if isinstance(v, string_or_bytes):
v, sid = get_series_values(v)
else:
v = sid = None
if sid is None and name.startswith('#'):
sid = self._fast_field_for(sfield, k)
sid = 1.0 if sid is None else sid # The value to be set the db link table
bimap[k] = v
if sid is not None:
simap[k] = sid
book_id_to_val_map = bimap
dirtied = f.writer.set_books(
book_id_to_val_map, self.backend, allow_case_change=allow_case_change)
if is_series and simap:
sf = self.fields[f.name+'_index']
dirtied |= sf.writer.set_books(simap, self.backend, allow_case_change=False)
if dirtied:
if update_path and do_path_update:
self._update_path(dirtied, mark_as_dirtied=False)
self._mark_as_dirty(dirtied)
self._clear_link_map_cache(dirtied)
self.event_dispatcher(EventType.metadata_changed, name, dirtied)
return dirtied
@write_api
def update_path(self, book_ids, mark_as_dirtied=True):
for book_id in book_ids:
title = self._field_for('title', book_id, default_value=_('Unknown'))
try:
author = self._field_for('authors', book_id, default_value=(_('Unknown'),))[0]
except IndexError:
author = _('Unknown')
self.backend.update_path(book_id, title, author, self.fields['path'], self.fields['formats'])
self.format_metadata_cache.pop(book_id, None)
if mark_as_dirtied:
self._mark_as_dirty(book_ids)
self._clear_link_map_cache(book_ids)
@read_api
def get_a_dirtied_book(self):
if self.dirtied_cache:
return random.choice(tuple(self.dirtied_cache))
return None
def _metadata_as_object_for_dump(self, book_id):
mi = self._get_metadata(book_id)
# Always set cover to cover.jpg. Even if cover doesn't exist,
# no harm done. This way no need to call dirtied when
# cover is set/removed
mi.cover = 'cover.jpg'
mi.all_annotations = self._all_annotations_for_book(book_id)
return mi
@read_api
def get_metadata_for_dump(self, book_id):
mi = None
# get the current sequence number for this book to pass back to the
# backup thread. This will avoid double calls in the case where the
# thread has not done the work between the put and the get_metadata
sequence = self.dirtied_cache.get(book_id, None)
if sequence is not None:
try:
# While a book is being created, the path is empty. Don't bother to
# try to write the opf, because it will go to the wrong folder.
if self._field_for('path', book_id):
mi = self._metadata_as_object_for_dump(book_id)
except:
# This almost certainly means that the book has been deleted while
# the backup operation sat in the queue.
traceback.print_exc()
return mi, sequence
@write_api
def clear_dirtied(self, book_id, sequence):
# Clear the dirtied indicator for the books. This is used when fetching
# metadata, creating an OPF, and writing a file are separated into steps.
# The last step is clearing the indicator
dc_sequence = self.dirtied_cache.get(book_id, None)
if dc_sequence is None or sequence is None or dc_sequence == sequence:
self.backend.mark_book_as_clean(book_id)
self.dirtied_cache.pop(book_id, None)
@write_api
def write_backup(self, book_id, raw):
try:
path = self._field_for('path', book_id).replace('/', os.sep)
except:
return
self.backend.write_backup(path, raw)
@read_api
def dirty_queue_length(self):
return len(self.dirtied_cache)
@read_api
def read_backup(self, book_id):
''' Return the OPF metadata backup for the book as a bytestring or None
if no such backup exists. '''
try:
path = self._field_for('path', book_id).replace('/', os.sep)
except:
return
try:
return self.backend.read_backup(path)
except OSError:
return None
@write_api
def dump_metadata(self, book_ids=None, remove_from_dirtied=True,
callback=None):
# Write metadata for each record to an individual OPF file. If callback
# is not None, it is called once at the start with the number of book_ids
# being processed. And once for every book_id, with arguments (book_id,
# mi, ok).
if book_ids is None:
book_ids = set(self.dirtied_cache)
if callback is not None:
callback(len(book_ids), True, False)
for book_id in book_ids:
if self._field_for('path', book_id) is None:
if callback is not None:
callback(book_id, None, False)
continue
mi, sequence = self._get_metadata_for_dump(book_id)
if mi is None:
if callback is not None:
callback(book_id, mi, False)
continue
try:
raw = metadata_to_opf(mi)
self._write_backup(book_id, raw)
if remove_from_dirtied:
self._clear_dirtied(book_id, sequence)
except:
pass
if callback is not None:
callback(book_id, mi, True)
@write_api
def set_cover(self, book_id_data_map):
''' Set the cover for this book. The data can be either a QImage,
QPixmap, file object or bytestring. It can also be None, in which
case any existing cover is removed. '''
for book_id, data in iteritems(book_id_data_map):
try:
path = self._field_for('path', book_id).replace('/', os.sep)
except AttributeError:
self._update_path((book_id,))
path = self._field_for('path', book_id).replace('/', os.sep)
self.backend.set_cover(book_id, path, data)
for cc in self.cover_caches:
cc.invalidate(book_id_data_map)
return self._set_field('cover', {
book_id:(0 if data is None else 1) for book_id, data in iteritems(book_id_data_map)})
@write_api
def add_cover_cache(self, cover_cache):
if not callable(cover_cache.invalidate):
raise ValueError('Cover caches must have an invalidate method')
self.cover_caches.add(cover_cache)
@write_api
def remove_cover_cache(self, cover_cache):
self.cover_caches.discard(cover_cache)
@write_api
def set_metadata(self, book_id, mi, ignore_errors=False, force_changes=False,
set_title=True, set_authors=True, allow_case_change=False):
'''
Set metadata for the book `id` from the `Metadata` object `mi`
Setting force_changes=True will force set_metadata to update fields even
if mi contains empty values. In this case, 'None' is distinguished from
'empty'. If mi.XXX is None, the XXX is not replaced, otherwise it is.
The tags, identifiers, and cover attributes are special cases. Tags and
identifiers cannot be set to None so they will always be replaced if
force_changes is true. You must ensure that mi contains the values you
want the book to have. Covers are always changed if a new cover is
provided, but are never deleted. Also note that force_changes has no
effect on setting title or authors.
'''
dirtied = set()
try:
# Handle code passing in an OPF object instead of a Metadata object
mi = mi.to_book_metadata()
except (AttributeError, TypeError):
pass
def set_field(name, val):
dirtied.update(self._set_field(name, {book_id:val}, do_path_update=False, allow_case_change=allow_case_change))
path_changed = False
if set_title and mi.title:
path_changed = True
set_field('title', mi.title)
authors_changed = False
if set_authors:
path_changed = True
if not mi.authors:
mi.authors = [_('Unknown')]
authors = []
for a in mi.authors:
authors += string_to_authors(a)
set_field('authors', authors)
authors_changed = True
if path_changed:
self._update_path({book_id})
def protected_set_field(name, val):
try:
set_field(name, val)
except:
if ignore_errors:
traceback.print_exc()
else:
raise
# force_changes has no effect on cover manipulation
try:
cdata = mi.cover_data[1]
if cdata is None and isinstance(mi.cover, string_or_bytes) and mi.cover and os.access(mi.cover, os.R_OK):
with open(mi.cover, 'rb') as f:
cdata = f.read() or None
if cdata is not None:
self._set_cover({book_id: cdata})
except:
if ignore_errors:
traceback.print_exc()
else:
raise
try:
with self.backend.conn: # Speed up set_metadata by not operating in autocommit mode
for field in ('rating', 'series_index', 'timestamp'):
val = getattr(mi, field)
if val is not None:
protected_set_field(field, val)
val = mi.get('author_sort', None)
if authors_changed and (not val or mi.is_null('author_sort')):
val = self._author_sort_from_authors(mi.authors)
if authors_changed or (force_changes and val is not None) or not mi.is_null('author_sort'):
protected_set_field('author_sort', val)
for field in ('publisher', 'series', 'tags', 'comments',
'languages', 'pubdate'):
val = mi.get(field, None)
if (force_changes and val is not None) or not mi.is_null(field):
protected_set_field(field, val)
val = mi.get('title_sort', None)
if (force_changes and val is not None) or not mi.is_null('title_sort'):
protected_set_field('sort', val)
# identifiers will always be replaced if force_changes is True
mi_idents = mi.get_identifiers()
if force_changes:
protected_set_field('identifiers', mi_idents)
elif mi_idents:
identifiers = self._field_for('identifiers', book_id, default_value={})
for key, val in iteritems(mi_idents):
if val and val.strip(): # Don't delete an existing identifier
identifiers[icu_lower(key)] = val
protected_set_field('identifiers', identifiers)
user_mi = mi.get_all_user_metadata(make_copy=False)
fm = self.field_metadata
for key in user_mi:
if (key in fm and user_mi[key]['datatype'] == fm[key]['datatype'] and (
user_mi[key]['datatype'] != 'text' or (
user_mi[key]['is_multiple'] == fm[key]['is_multiple']))):
val = mi.get(key, None)
if force_changes or val is not None:
protected_set_field(key, val)
idx = key + '_index'
if idx in self.fields:
extra = mi.get_extra(key)
if extra is not None or force_changes:
protected_set_field(idx, extra)
except:
# sqlite will rollback the entire transaction, thanks to the with
# statement, so we have to re-read everything form the db to ensure
# the db and Cache are in sync
self._reload_from_db()
raise
return dirtied
def _do_add_format(self, book_id, fmt, stream, name=None, mtime=None):
path = self._field_for('path', book_id)
if path is None:
# Theoretically, this should never happen, but apparently it
# does: https://www.mobileread.com/forums/showthread.php?t=233353
self._update_path({book_id}, mark_as_dirtied=False)
path = self._field_for('path', book_id)
path = path.replace('/', os.sep)
title = self._field_for('title', book_id, default_value=_('Unknown'))
try:
author = self._field_for('authors', book_id, default_value=(_('Unknown'),))[0]
except IndexError:
author = _('Unknown')
size, fname = self.backend.add_format(book_id, fmt, stream, title, author, path, name, mtime=mtime)
return size, fname
@api
def add_format(self, book_id, fmt, stream_or_path, replace=True, run_hooks=True, dbapi=None):
'''
Add a format to the specified book. Return True if the format was added successfully.
:param replace: If True replace existing format, otherwise if the format already exists, return False.
:param run_hooks: If True, file type plugins are run on the format before and after being added.
:param dbapi: Internal use only.
'''
needs_close = False
if run_hooks:
# Run import plugins, the write lock is not held to cater for
# broken plugins that might spin the event loop by popping up a
# message in the GUI during the processing.
npath = run_import_plugins(stream_or_path, fmt)
fmt = os.path.splitext(npath)[-1].lower().replace('.', '').upper()
stream_or_path = open(make_long_path_useable(npath), 'rb')
needs_close = True
fmt = check_ebook_format(stream_or_path, fmt)
with self.write_lock:
if not self._has_id(book_id):
raise NoSuchBook(book_id)
fmt = (fmt or '').upper()
self.format_metadata_cache[book_id].pop(fmt, None)
try:
name = self.fields['formats'].format_fname(book_id, fmt)
except Exception:
name = None
if name and not replace:
if needs_close:
stream_or_path.close()
return False
if hasattr(stream_or_path, 'read'):
stream = stream_or_path
else:
stream = open(make_long_path_useable(stream_or_path), 'rb')
needs_close = True
try:
size, fname = self._do_add_format(book_id, fmt, stream, name)
finally:
if needs_close:
stream.close()
del stream
max_size = self.fields['formats'].table.update_fmt(book_id, fmt, fname, size, self.backend)
self.fields['size'].table.update_sizes({book_id: max_size})
self._update_last_modified((book_id,))
self.event_dispatcher(EventType.format_added, book_id, fmt)
if run_hooks:
# Run post import plugins, the write lock is released so the plugin
# can call api without a locking violation.
run_plugins_on_postimport(dbapi or self, book_id, fmt)
stream_or_path.close()
self.queue_next_fts_job()
return True
@write_api
def remove_formats(self, formats_map, db_only=False):
'''
Remove the specified formats from the specified books.
:param formats_map: A mapping of book_id to a list of formats to be removed from the book.
:param db_only: If True, only remove the record for the format from the db, do not delete the actual format file from the filesystem.
:return: A map of book id to set of formats actually deleted from the filesystem for that book
'''
table = self.fields['formats'].table
formats_map = {book_id:frozenset((f or '').upper() for f in fmts) for book_id, fmts in iteritems(formats_map)}
removed_map = {}
for book_id, fmts in iteritems(formats_map):
for fmt in fmts:
self.format_metadata_cache[book_id].pop(fmt, None)
if not db_only:
removes = defaultdict(set)
metadata_map = {}
for book_id, fmts in iteritems(formats_map):
try:
path = self._field_for('path', book_id).replace('/', os.sep)
except:
continue
for fmt in fmts:
try:
name = self.fields['formats'].format_fname(book_id, fmt)
except:
continue
if name and path:
removes[book_id].add((fmt, name, path))
if removes[book_id]:
metadata_map[book_id] = {'title': self._field_for('title', book_id), 'authors': self._field_for('authors', book_id)}
if removes:
removed_map = self.backend.remove_formats(removes, metadata_map)
size_map = table.remove_formats(formats_map, self.backend)
self.fields['size'].table.update_sizes(size_map)
for book_id, fmts in iteritems(formats_map):
for fmt in fmts:
run_plugins_on_postdelete(self, book_id, fmt)
self._update_last_modified(tuple(formats_map))
self.event_dispatcher(EventType.formats_removed, formats_map)
return removed_map
@read_api
def get_next_series_num_for(self, series, field='series', current_indices=False):
'''
Return the next series index for the specified series, taking into account the various preferences that
control next series number generation.
:param field: The series-like field (defaults to the builtin series column)
:param current_indices: If True, returns a mapping of book_id to current series_index value instead.
'''
books = ()
sf = self.fields[field]
if series:
q = icu_lower(series)
for val, book_ids in sf.iter_searchable_values(self._get_proxy_metadata, frozenset(self._all_book_ids())):
if q == icu_lower(val):
books = book_ids
break
idf = sf.index_field
index_map = {book_id:self._fast_field_for(idf, book_id, default_value=1.0) for book_id in books}
if current_indices:
return index_map
series_indices = sorted(index_map.values(), key=lambda s: s or 0)
return _get_next_series_num_for_list(tuple(series_indices), unwrap=False)
@read_api
def author_sort_from_authors(self, authors, key_func=icu_lower):
'''Given a list of authors, return the author_sort string for the authors,
preferring the author sort associated with the author over the computed
string. '''
table = self.fields['authors'].table
result = []
rmap = {key_func(v):k for k, v in iteritems(table.id_map)}
for aut in authors:
aid = rmap.get(key_func(aut), None)
result.append(author_to_author_sort(aut) if aid is None else table.asort_map[aid])
return ' & '.join(_f for _f in result if _f)
@read_api
def data_for_has_book(self):
''' Return data suitable for use in :meth:`has_book`. This can be used for an
implementation of :meth:`has_book` in a worker process without access to the
db. '''
try:
return {icu_lower(title) for title in itervalues(self.fields['title'].table.book_col_map)}
except TypeError:
# Some non-unicode titles in the db
return {icu_lower(as_unicode(title)) for title in itervalues(self.fields['title'].table.book_col_map)}
@read_api
def has_book(self, mi):
''' Return True iff the database contains an entry with the same title
as the passed in Metadata object. The comparison is case-insensitive.
See also :meth:`data_for_has_book`. '''
title = mi.title
if title:
if isbytestring(title):
title = title.decode(preferred_encoding, 'replace')
q = icu_lower(title).strip()
for title in itervalues(self.fields['title'].table.book_col_map):
if q == icu_lower(title):
return True
return False
@read_api
def has_id(self, book_id):
' Return True iff the specified book_id exists in the db '''
return book_id in self.fields['title'].table.book_col_map
@write_api
def create_book_entry(self, mi, cover=None, add_duplicates=True, force_id=None, apply_import_tags=True, preserve_uuid=False):
if mi.tags:
mi.tags = list(mi.tags)
if apply_import_tags:
_add_newbook_tag(mi)
_add_default_custom_column_values(mi, self.field_metadata)
if not add_duplicates and self._has_book(mi):
return
series_index = (self._get_next_series_num_for(mi.series) if mi.series_index is None else mi.series_index)
try:
series_index = float(series_index)
except Exception:
try:
series_index = float(self._get_next_series_num_for(mi.series))
except Exception:
series_index = 1.0
if not mi.authors:
mi.authors = (_('Unknown'),)
aus = mi.author_sort if not mi.is_null('author_sort') else self._author_sort_from_authors(mi.authors)
mi.title = mi.title or _('Unknown')
if mi.is_null('title_sort'):
mi.title_sort = title_sort(mi.title, lang=mi.languages[0] if mi.languages else None)
if isbytestring(aus):
aus = aus.decode(preferred_encoding, 'replace')
if isbytestring(mi.title):
mi.title = mi.title.decode(preferred_encoding, 'replace')
if force_id is None:
self.backend.execute('INSERT INTO books(title, series_index, author_sort) VALUES (?, ?, ?)',
(mi.title, series_index, aus))
else:
self.backend.execute('INSERT INTO books(id, title, series_index, author_sort) VALUES (?, ?, ?, ?)',
(force_id, mi.title, series_index, aus))
book_id = self.backend.last_insert_rowid()
self.event_dispatcher(EventType.book_created, book_id)
mi.timestamp = utcnow() if (mi.timestamp is None or is_date_undefined(mi.timestamp)) else mi.timestamp
mi.pubdate = UNDEFINED_DATE if mi.pubdate is None else mi.pubdate
if cover is not None:
mi.cover, mi.cover_data = None, (None, cover)
self._set_metadata(book_id, mi, ignore_errors=True)
lm = getattr(mi, 'link_maps', None)
if lm:
for field, link_map in lm.items():
if self._has_link_map(field):
self._set_link_map(field, link_map, only_set_if_no_existing_link=True)
if preserve_uuid and mi.uuid:
self._set_field('uuid', {book_id:mi.uuid})
# Update the caches for fields from the books table
self.fields['size'].table.book_col_map[book_id] = 0
row = next(self.backend.execute('SELECT sort, series_index, author_sort, uuid, has_cover FROM books WHERE id=?', (book_id,)))
for field, val in zip(('sort', 'series_index', 'author_sort', 'uuid', 'cover'), row):
if field == 'cover':
val = bool(val)
elif field == 'uuid':
self.fields[field].table.uuid_to_id_map[val] = book_id
self.fields[field].table.book_col_map[book_id] = val
return book_id
@api
def add_books(self, books, add_duplicates=True, apply_import_tags=True, preserve_uuid=False, run_hooks=True, dbapi=None):
'''
Add the specified books to the library. Books should be an iterable of
2-tuples, each 2-tuple of the form :code:`(mi, format_map)` where mi is a
Metadata object and format_map is a dictionary of the form :code:`{fmt: path_or_stream}`,
for example: :code:`{'EPUB': '/path/to/file.epub'}`.
Returns a pair of lists: :code:`ids, duplicates`. ``ids`` contains the book ids for all newly created books in the
database. ``duplicates`` contains the :code:`(mi, format_map)` for all books that already exist in the database
as per the simple duplicate detection heuristic used by :meth:`has_book`.
'''
duplicates, ids = [], []
for mi, format_map in books:
book_id = self.create_book_entry(mi, add_duplicates=add_duplicates, apply_import_tags=apply_import_tags, preserve_uuid=preserve_uuid)
if book_id is None:
duplicates.append((mi, format_map))
else:
fmt_map = {}
ids.append(book_id)
for fmt, stream_or_path in format_map.items():
if self.add_format(book_id, fmt, stream_or_path, dbapi=dbapi, run_hooks=run_hooks):
fmt_map[fmt.lower()] = getattr(stream_or_path, 'name', stream_or_path) or '<stream>'
run_plugins_on_postadd(dbapi or self, book_id, fmt_map)
return ids, duplicates
@write_api
def remove_books(self, book_ids, permanent=False):
''' Remove the books specified by the book_ids from the database and delete
their format files. If ``permanent`` is False, then the format files
are placed in the per-library trash directory. '''
path_map = {}
for book_id in book_ids:
try:
path = self._field_for('path', book_id).replace('/', os.sep)
except Exception:
path = None
path_map[book_id] = path
if not permanent and path:
# ensure metadata.opf is written and up-to-date so we can restore the book
try:
mi = self._metadata_as_object_for_dump(book_id)
raw = metadata_to_opf(mi)
self.backend.write_backup(path, raw)
except Exception:
traceback.print_exc()
self.backend.remove_books(path_map, permanent=permanent)
for field in itervalues(self.fields):
try:
table = field.table
except AttributeError:
continue # Some fields like ondevice do not have tables
else:
table.remove_books(book_ids, self.backend)
self._search_api.discard_books(book_ids)
self._clear_caches(book_ids=book_ids, template_cache=False, search_cache=False)
for cc in self.cover_caches:
cc.invalidate(book_ids)
self.event_dispatcher(EventType.books_removed, book_ids)
@read_api
def author_sort_strings_for_books(self, book_ids):
val_map = {}
for book_id in book_ids:
authors = self._field_ids_for('authors', book_id)
adata = self._author_data(authors)
val_map[book_id] = tuple(adata[aid]['sort'] for aid in authors)
return val_map
@write_api
def rename_items(self, field, item_id_to_new_name_map, change_index=True, restrict_to_book_ids=None):
'''
Rename items from a many-one or many-many field such as tags or series.
:param change_index: When renaming in a series-like field also change the series_index values.
:param restrict_to_book_ids: An optional set of book ids for which the rename is to be performed, defaults to all books.
'''
f = self.fields[field]
affected_books = set()
try:
sv = f.metadata['is_multiple']['ui_to_list']
except (TypeError, KeyError, AttributeError):
sv = None
if restrict_to_book_ids is not None:
# We have a VL. Only change the item name for those books
if not isinstance(restrict_to_book_ids, (Set, MutableSet)):
restrict_to_book_ids = frozenset(restrict_to_book_ids)
id_map = {}
default_process_map = {}
for old_id, new_name in iteritems(item_id_to_new_name_map):
new_names = tuple(x.strip() for x in new_name.split(sv)) if sv else (new_name,)
# Get a list of books in the VL with the item
books_with_id = f.books_for(old_id)
books_to_process = books_with_id & restrict_to_book_ids
if len(books_with_id) == len(books_to_process):
# All the books with the ID are in the VL, so we can use
# the normal processing
default_process_map[old_id] = new_name
elif books_to_process:
affected_books.update(books_to_process)
newvals = {}
for book_id in books_to_process:
# Get the current values, remove the one being renamed, then add
# the new value(s) back.
vals = self._field_for(field, book_id)
# Check for is_multiple
if isinstance(vals, tuple):
# We must preserve order.
vals = list(vals)
# Don't need to worry about case here because we
# are fetching its one-true spelling. But lets be
# careful anyway
try:
dex = vals.index(self._get_item_name(field, old_id))
# This can put the name back with a different case
vals[dex] = new_names[0]
# now add any other items if they aren't already there
if len(new_names) > 1:
set_vals = {icu_lower(x) for x in vals}
for v in new_names[1:]:
lv = icu_lower(v)
if lv not in set_vals:
vals.append(v)
set_vals.add(lv)
newvals[book_id] = vals
except Exception:
traceback.print_exc()
else:
newvals[book_id] = new_names[0]
# Allow case changes
self._set_field(field, newvals)
id_map[old_id] = self._get_item_id(field, new_names[0])
if default_process_map:
ab, idm = self._rename_items(field, default_process_map, change_index=change_index)
affected_books.update(ab)
id_map.update(idm)
self.event_dispatcher(EventType.items_renamed, field, affected_books, id_map)
return affected_books, id_map
try:
func = f.table.rename_item
except AttributeError:
raise ValueError('Cannot rename items for one-one fields: %s' % field)
moved_books = set()
id_map = {}
for item_id, new_name in iteritems(item_id_to_new_name_map):
new_names = tuple(x.strip() for x in new_name.split(sv)) if sv else (new_name,)
books, new_id = func(item_id, new_names[0], self.backend)
affected_books.update(books)
id_map[item_id] = new_id
if new_id != item_id:
moved_books.update(books)
if len(new_names) > 1:
# Add the extra items to the books
extra = new_names[1:]
self._set_field(field, {book_id:self._fast_field_for(f, book_id) + extra for book_id in books})
if affected_books:
if field == 'authors':
self._set_field('author_sort',
{k:' & '.join(v) for k, v in iteritems(self._author_sort_strings_for_books(affected_books))})
self._update_path(affected_books, mark_as_dirtied=False)
elif change_index and hasattr(f, 'index_field') and tweaks['series_index_auto_increment'] != 'no_change':
for book_id in moved_books:
self._set_field(f.index_field.name, {book_id:self._get_next_series_num_for(self._fast_field_for(f, book_id), field=field)})
self._mark_as_dirty(affected_books)
self._clear_link_map_cache(affected_books)
self.event_dispatcher(EventType.items_renamed, field, affected_books, id_map)
return affected_books, id_map
@write_api
def remove_items(self, field, item_ids, restrict_to_book_ids=None):
''' Delete all items in the specified field with the specified ids.
Returns the set of affected book ids. ``restrict_to_book_ids`` is an
optional set of books ids. If specified the items will only be removed
from those books. '''
field = self.fields[field]
if restrict_to_book_ids is not None and not isinstance(restrict_to_book_ids, (MutableSet, Set)):
restrict_to_book_ids = frozenset(restrict_to_book_ids)
affected_books = field.table.remove_items(item_ids, self.backend,
restrict_to_book_ids=restrict_to_book_ids)
if affected_books:
if hasattr(field, 'index_field'):
self._set_field(field.index_field.name, {bid:1.0 for bid in affected_books})
else:
self._mark_as_dirty(affected_books)
self._clear_link_map_cache(affected_books)
self.event_dispatcher(EventType.items_removed, field, affected_books, item_ids)
return affected_books
@write_api
def add_custom_book_data(self, name, val_map, delete_first=False):
''' Add data for name where val_map is a map of book_ids to values. If
delete_first is True, all previously stored data for name will be
removed. '''
missing = frozenset(val_map) - self._all_book_ids()
if missing:
raise ValueError('add_custom_book_data: no such book_ids: %d'%missing)
self.backend.add_custom_data(name, val_map, delete_first)
@read_api
def get_custom_book_data(self, name, book_ids=(), default=None):
''' Get data for name. By default returns data for all book_ids, pass
in a list of book ids if you only want some data. Returns a map of
book_id to values. If a particular value could not be decoded, uses
default for it. '''
return self.backend.get_custom_book_data(name, book_ids, default)
@write_api
def delete_custom_book_data(self, name, book_ids=()):
''' Delete data for name. By default deletes all data, if you only want
to delete data for some book ids, pass in a list of book ids. '''
self.backend.delete_custom_book_data(name, book_ids)
@read_api
def get_ids_for_custom_book_data(self, name):
''' Return the set of book ids for which name has data. '''
return self.backend.get_ids_for_custom_book_data(name)
@read_api
def conversion_options(self, book_id, fmt='PIPE'):
return self.backend.conversion_options(book_id, fmt)
@read_api
def has_conversion_options(self, ids, fmt='PIPE'):
return self.backend.has_conversion_options(ids, fmt)
@write_api
def delete_conversion_options(self, book_ids, fmt='PIPE'):
return self.backend.delete_conversion_options(book_ids, fmt)
@write_api
def set_conversion_options(self, options, fmt='PIPE'):
''' options must be a map of the form {book_id:conversion_options} '''
return self.backend.set_conversion_options(options, fmt)
@write_api
def refresh_format_cache(self):
self.fields['formats'].table.read(self.backend)
self.format_metadata_cache.clear()
@write_api
def refresh_ondevice(self):
self.fields['ondevice'].clear_caches()
self.clear_search_caches()
self.clear_composite_caches()
@read_api
def books_matching_device_book(self, lpath):
ans = set()
for book_id, (_, _, _, _, lpaths) in self.fields['ondevice'].cache.items():
if lpath in lpaths:
ans.add(book_id)
return ans
@read_api
def tags_older_than(self, tag, delta=None, must_have_tag=None, must_have_authors=None):
'''
Return the ids of all books having the tag ``tag`` that are older than
the specified time. tag comparison is case insensitive.
:param delta: A timedelta object or None. If None, then all ids with
the tag are returned.
:param must_have_tag: If not None the list of matches will be
restricted to books that have this tag
:param must_have_authors: A list of authors. If not None the list of
matches will be restricted to books that have these authors (case
insensitive).
'''
tag_map = {icu_lower(v):k for k, v in iteritems(self._get_id_map('tags'))}
tag = icu_lower(tag.strip())
mht = icu_lower(must_have_tag.strip()) if must_have_tag else None
tag_id, mht_id = tag_map.get(tag, None), tag_map.get(mht, None)
ans = set()
if mht_id is None and mht:
return ans
if tag_id is not None:
tagged_books = self._books_for_field('tags', tag_id)
if mht_id is not None and tagged_books:
tagged_books = tagged_books.intersection(self._books_for_field('tags', mht_id))
if tagged_books:
if must_have_authors is not None:
amap = {icu_lower(v):k for k, v in iteritems(self._get_id_map('authors'))}
books = None
for author in must_have_authors:
abooks = self._books_for_field('authors', amap.get(icu_lower(author), None))
books = abooks if books is None else books.intersection(abooks)
if not books:
break
tagged_books = tagged_books.intersection(books or set())
if delta is None:
ans = tagged_books
else:
now = nowf()
for book_id in tagged_books:
ts = self._field_for('timestamp', book_id)
if (now - ts) > delta:
ans.add(book_id)
return ans
@write_api
def set_sort_for_authors(self, author_id_to_sort_map, update_books=True):
sort_map = self.fields['authors'].table.set_sort_names(author_id_to_sort_map, self.backend)
changed_books = set()
if update_books:
val_map = {}
for author_id in sort_map:
books = self._books_for_field('authors', author_id)
changed_books |= books
for book_id in books:
authors = self._field_ids_for('authors', book_id)
adata = self._author_data(authors)
sorts = [adata[x]['sort'] for x in authors]
val_map[book_id] = ' & '.join(sorts)
if val_map:
self._set_field('author_sort', val_map)
if changed_books:
self._mark_as_dirty(changed_books)
self._clear_link_map_cache(changed_books)
return changed_books
@write_api
def set_link_for_authors(self, author_id_to_link_map):
link_map = self.fields['authors'].table.set_links(author_id_to_link_map, self.backend)
changed_books = set()
for author_id in link_map:
changed_books |= self._books_for_field('authors', author_id)
if changed_books:
self._mark_as_dirty(changed_books)
self._clear_link_map_cache(changed_books)
return changed_books
@read_api
def has_link_map(self, field):
return hasattr(getattr(self.fields.get(field), 'table', None), 'link_map')
@read_api
def get_link_map(self, for_field):
'''
Return a dictionary of links for the supplied field.
:param for_field: the lookup name of the field for which the link map is desired
:return: {field_value:link_value, ...} for non-empty links
'''
if for_field not in self.fields:
raise ValueError(f'Lookup name {for_field} is not a valid name')
table = self.fields[for_field].table
lm = getattr(table, 'link_map', None)
if lm is None:
raise ValueError(f"Lookup name {for_field} doesn't have a link map")
lm = table.link_map
vm = table.id_map
ans = {vm.get(fid):v for fid,v in lm.items() if v}
ans.pop(None, None)
return ans
@read_api
def link_for(self, field, item_id):
'''
Return the link, if any, for the specified item or None if no link is found
'''
f = self.fields.get(field)
if f is not None:
table = f.table
lm = getattr(table, 'link_map', None)
if lm is not None:
return lm.get(item_id)
@read_api
def get_all_link_maps_for_book(self, book_id):
'''
Returns all links for all fields referenced by book identified by book_id.
If book_id doesn't exist then the method returns {}.
Example: Assume author A has link X, author B has link Y, tag S has link
F, and tag T has link G. If book 1 has author A and tag T,
this method returns {'authors':{'A':'X'}, 'tags':{'T', 'G'}}.
If book 2's author is neither A nor B and has no tags, this method returns {}.
:param book_id: the book id in question.
:return: {field: {field_value, link_value}, ... for all fields with a field_value having a non-empty link value for that book
'''
if not self._has_id(book_id):
# Works for book_id is None.
return {}
cached = self.link_maps_cache.get(book_id)
if cached is not None:
return cached
links = {}
def add_links_for_field(f):
field_ids = self._field_ids_for(f, book_id)
if field_ids:
table = self.fields[f].table
lm = table.link_map
id_link_map = {fid:lm.get(fid) for fid in field_ids}
vm = table.id_map
d = {vm.get(fid):v for fid, v in id_link_map.items() if v}
d.pop(None, None)
if d:
links[f] = d
for field in ('authors', 'publisher', 'series', 'tags'):
add_links_for_field(field)
for field in self.field_metadata.custom_field_keys(include_composites=False):
if self._has_link_map(field):
add_links_for_field(field)
self.link_maps_cache[book_id] = links
return links
@write_api
def set_link_map(self, field, value_to_link_map, only_set_if_no_existing_link=False):
'''
Sets links for item values in field.
Note: this method doesn't change values not in the value_to_link_map
:param field: the lookup name
:param value_to_link_map: dict(field_value:link, ...). Note that these are values, not field ids.
:return: books changed by setting the link
'''
if field not in self.fields:
raise ValueError(f'Lookup name {field} is not a valid name')
table = getattr(self.fields[field], 'table', None)
if table is None:
raise ValueError(f"Lookup name {field} doesn't have a link map")
# Clear the links for book cache as we don't know what will be affected
self.link_maps_cache = {}
fids = self._get_item_ids(field, value_to_link_map)
if only_set_if_no_existing_link:
lm = table.link_map
id_to_link_map = {fid:value_to_link_map[k] for k, fid in fids.items() if fid is not None and not lm.get(fid)}
else:
id_to_link_map = {fid:value_to_link_map[k] for k, fid in fids.items() if fid is not None}
result_map = table.set_links(id_to_link_map, self.backend)
changed_books = set()
for id_ in result_map:
changed_books |= self._books_for_field(field, id_)
if changed_books:
self._mark_as_dirty(changed_books)
self._clear_link_map_cache(changed_books)
return changed_books
@read_api
def lookup_by_uuid(self, uuid):
return self.fields['uuid'].table.lookup_by_uuid(uuid)
@write_api
def delete_custom_column(self, label=None, num=None):
self.backend.delete_custom_column(label, num)
@write_api
def create_custom_column(self, label, name, datatype, is_multiple, editable=True, display={}):
return self.backend.create_custom_column(label, name, datatype, is_multiple, editable=editable, display=display)
@write_api
def set_custom_column_metadata(self, num, name=None, label=None, is_editable=None,
display=None, update_last_modified=False):
changed = self.backend.set_custom_column_metadata(num, name=name, label=label, is_editable=is_editable, display=display)
if changed:
if update_last_modified:
self._update_last_modified(self._all_book_ids())
else:
self.backend.prefs.set('update_all_last_mod_dates_on_start', True)
return changed
@read_api
def get_books_for_category(self, category, item_id_or_composite_value):
f = self.fields[category]
if hasattr(f, 'get_books_for_val'):
# Composite field
return f.get_books_for_val(item_id_or_composite_value, self._get_proxy_metadata, self._all_book_ids())
return self._books_for_field(f.name, int(item_id_or_composite_value))
@read_api
def split_if_is_multiple_composite(self, f, val):
'''
If f is a composite column lookup key and the column is is_multiple then
split v into unique non-empty values. The comparison is case sensitive.
Order is not preserved. Return a list() for compatibility with proxy
metadata field getters, for example tags.
'''
fm = self.field_metadata.get(f, None)
if fm and fm['datatype'] == 'composite' and fm['is_multiple']:
sep = fm['is_multiple'].get('cache_to_list', ',')
return list({v.strip() for v in val.split(sep) if v.strip()})
return val
@read_api
def data_for_find_identical_books(self):
''' Return data that can be used to implement
:meth:`find_identical_books` in a worker process without access to the
db. See db.utils for an implementation. '''
at = self.fields['authors'].table
author_map = defaultdict(set)
for aid, author in iteritems(at.id_map):
author_map[icu_lower(author)].add(aid)
return (author_map, at.col_book_map.copy(), self.fields['title'].table.book_col_map.copy(), self.fields['languages'].book_value_map.copy())
@read_api
def update_data_for_find_identical_books(self, book_id, data):
author_map, author_book_map, title_map, lang_map = data
title_map[book_id] = self._field_for('title', book_id)
lang_map[book_id] = self._field_for('languages', book_id)
at = self.fields['authors'].table
for aid in at.book_col_map.get(book_id, ()):
author_map[icu_lower(at.id_map[aid])].add(aid)
try:
author_book_map[aid].add(book_id)
except KeyError:
author_book_map[aid] = {book_id}
@read_api
def find_identical_books(self, mi, search_restriction='', book_ids=None):
''' Finds books that have a superset of the authors in mi and the same
title (title is fuzzy matched). See also :meth:`data_for_find_identical_books`. '''
from calibre.db.utils import fuzzy_title
identical_book_ids = set()
langq = tuple(x for x in map(canonicalize_lang, mi.languages or ()) if x and x != 'und')
if mi.authors:
try:
quathors = mi.authors[:20] # Too many authors causes parsing of the search expression to fail
query = ' and '.join('authors:"=%s"'%(a.replace('"', '')) for a in quathors)
qauthors = mi.authors[20:]
except ValueError:
return identical_book_ids
try:
book_ids = self._search(query, restriction=search_restriction, book_ids=book_ids)
except:
traceback.print_exc()
return identical_book_ids
if qauthors and book_ids:
matches = set()
qauthors = {icu_lower(x) for x in qauthors}
for book_id in book_ids:
aut = self._field_for('authors', book_id)
if aut:
aut = {icu_lower(x) for x in aut}
if aut.issuperset(qauthors):
matches.add(book_id)
book_ids = matches
for book_id in book_ids:
fbook_title = self._field_for('title', book_id)
fbook_title = fuzzy_title(fbook_title)
mbook_title = fuzzy_title(mi.title)
if fbook_title == mbook_title:
bl = self._field_for('languages', book_id)
if not langq or not bl or bl == langq:
identical_book_ids.add(book_id)
return identical_book_ids
@read_api
def get_top_level_move_items(self):
all_paths = {self._field_for('path', book_id).partition('/')[0] for book_id in self._all_book_ids()}
return self.backend.get_top_level_move_items(all_paths)
@write_api
def move_library_to(self, newloc, progress=None, abort=None):
def progress_callback(item_name, item_count, total):
try:
if progress is not None:
progress(item_name, item_count, total)
except Exception:
traceback.print_exc()
all_paths = {self._field_for('path', book_id).partition('/')[0] for book_id in self._all_book_ids()}
self.backend.move_library_to(all_paths, newloc, progress=progress_callback, abort=abort)
@read_api
def saved_search_names(self):
return self._search_api.saved_searches.names()
@read_api
def saved_search_lookup(self, name):
return self._search_api.saved_searches.lookup(name)
@write_api
def saved_search_set_all(self, smap):
self._search_api.saved_searches.set_all(smap)
self._clear_search_caches()
@write_api
def saved_search_delete(self, name):
self._search_api.saved_searches.delete(name)
self._clear_search_caches()
@write_api
def saved_search_add(self, name, val):
self._search_api.saved_searches.add(name, val)
@write_api
def saved_search_rename(self, old_name, new_name):
self._search_api.saved_searches.rename(old_name, new_name)
self._clear_search_caches()
@write_api
def change_search_locations(self, newlocs):
self._search_api.change_locations(newlocs)
@write_api
def refresh_search_locations(self):
self._search_api.change_locations(self.field_metadata.get_search_terms())
@write_api
def dump_and_restore(self, callback=None, sql=None):
return self.backend.dump_and_restore(callback=callback, sql=sql)
@write_api
def vacuum(self, include_fts_db=False, include_notes_db=True):
self.is_doing_rebuild_or_vacuum = True
try:
self.backend.vacuum(include_fts_db, include_notes_db)
finally:
self.is_doing_rebuild_or_vacuum = False
def __del__(self):
self.close()
def _shutdown_fts(self, stage=1):
if stage == 1:
self.backend.shutdown_fts()
if self.fts_queue_thread is not None:
self.fts_job_queue.put(None)
if hasattr(self, 'fts_dispatch_stop_event'):
self.fts_dispatch_stop_event.set()
return
# the fts supervisor thread could be in the middle of committing a
# result to the db, so holding a lock here will cause a deadlock
if self.fts_queue_thread is not None:
self.fts_queue_thread.join()
self.fts_queue_thread = None
self.backend.join_fts()
@api
def close(self):
with self.write_lock:
if hasattr(self, 'close_called'):
return
self.close_called = True
self.shutting_down = True
self.event_dispatcher.close()
self._shutdown_fts()
try:
from calibre.customize.ui import available_library_closed_plugins
except ImportError:
pass # happens during interpreter shutdown
else:
for plugin in available_library_closed_plugins():
try:
plugin.run(self)
except Exception:
traceback.print_exc()
self._shutdown_fts(stage=2)
with self.write_lock:
self.backend.close()
@property
def is_closed(self):
return self.backend.is_closed
@write_api
def clear_trash_bin(self):
self.backend.clear_trash_dir()
@read_api
def list_trash_entries(self):
books, formats = self.backend.list_trash_entries()
ff = []
for e in formats:
if self._has_id(e.book_id):
ff.append(e)
e.cover_path = self.format_abspath(e.book_id, '__COVER_INTERNAL__')
return books, formats
@read_api
def copy_format_from_trash(self, book_id, fmt, dest):
fmt = fmt.upper()
fpath = self.backend.path_for_trash_format(book_id, fmt)
if not fpath:
raise ValueError(f'No format {fmt} found in book {book_id}')
shutil.copyfile(fpath, dest)
@write_api
def move_format_from_trash(self, book_id, fmt):
''' Undelete a format from the trash directory '''
if not self._has_id(book_id):
raise ValueError(f'A book with the id {book_id} does not exist')
fmt = fmt.upper()
try:
name = self.fields['formats'].format_fname(book_id, fmt)
except Exception:
name = None
fpath = self.backend.path_for_trash_format(book_id, fmt)
if not fpath:
raise ValueError(f'No format {fmt} found in book {book_id}')
size, fname = self._do_add_format(book_id, fmt, fpath, name)
self.format_metadata_cache.pop(book_id, None)
max_size = self.fields['formats'].table.update_fmt(book_id, fmt, fname, size, self.backend)
self.fields['size'].table.update_sizes({book_id: max_size})
self.event_dispatcher(EventType.format_added, book_id, fmt)
self.backend.remove_trash_formats_dir_if_empty(book_id)
@read_api
def copy_book_from_trash(self, book_id, dest: str):
self.backend.copy_book_from_trash(book_id, dest)
@write_api
def move_book_from_trash(self, book_id):
''' Undelete a book from the trash directory '''
if self._has_id(book_id):
raise ValueError(f'A book with the id {book_id} already exists')
mi, annotations, formats = self.backend.get_metadata_for_trash_book(book_id)
mi.cover = None
self._create_book_entry(mi, add_duplicates=True,
force_id=book_id, apply_import_tags=False, preserve_uuid=True)
path = self._field_for('path', book_id).replace('/', os.sep)
self.backend.move_book_from_trash(book_id, path)
self.format_metadata_cache.pop(book_id, None)
f = self.fields['formats'].table
max_size = 0
for (fmt, size, fname) in formats:
max_size = max(max_size, f.update_fmt(book_id, fmt, fname, size, self.backend))
self.fields['size'].table.update_sizes({book_id: max_size})
cover = self.backend.cover_abspath(book_id, path)
if cover and os.path.exists(cover):
self._set_field('cover', {book_id:1})
if annotations:
self._restore_annotations(book_id, annotations)
@write_api
def delete_trash_entry(self, book_id, category):
" Delete an entry from the trash. Here category is 'b' for books and 'f' for formats. "
self.backend.delete_trash_entry(book_id, category)
@write_api
def expire_old_trash(self):
' Expire entries from the trash that are too old '
self.backend.expire_old_trash()
@write_api
def restore_book(self, book_id, mi, last_modified, path, formats, annotations=()):
''' Restore the book entry in the database for a book that already exists on the filesystem '''
cover, mi.cover = mi.cover, None
self._create_book_entry(mi, add_duplicates=True,
force_id=book_id, apply_import_tags=False, preserve_uuid=True)
self._update_last_modified((book_id,), last_modified)
if cover and os.path.exists(cover):
self._set_field('cover', {book_id:1})
f = self.fields['formats'].table
for (fmt, size, fname) in formats:
f.update_fmt(book_id, fmt, fname, size, self.backend)
self.fields['path'].table.set_path(book_id, path, self.backend)
if annotations:
self._restore_annotations(book_id, annotations)
@read_api
def virtual_libraries_for_books(self, book_ids, virtual_fields=None):
# use a primitive lock to ensure that only one thread is updating
# the cache and that recursive calls don't do the update. This
# method can recurse via self._search()
with try_lock(self.vls_cache_lock) as got_lock:
# Using a list is slightly faster than a set.
c = defaultdict(list)
if not got_lock:
# We get here if resolving the books in a VL triggers another VL
# cache calculation. This can be 'real' recursion, for example a
# VL expression using a template that calls virtual_libraries(),
# or a search using a location of 'all' that causes evaluation
# of a composite that uses virtual_libraries(). The first case
# is an error and the exception message should appear somewhere.
# However, the error can seem nondeterministic. It might not be
# raised if the use is via a composite and that composite is
# evaluated before it is used in the search. The second case is
# also an error but if the composite isn't used in a VL then the
# eventual answer will be correct because get_metadata() will
# clear the caches.
raise ValueError(_('Recursion detected while processing Virtual library "%s"')
% self.vls_for_books_lib_in_process)
if self.vls_for_books_cache is None:
libraries = self._pref('virtual_libraries', {})
for lib, expr in libraries.items():
book = None
self.vls_for_books_lib_in_process = lib
try:
for book in self._search(expr, virtual_fields=virtual_fields):
c[book].append(lib)
except Exception as e:
if book:
c[book].append(_('[Error in Virtual library {0}: {1}]').format(lib, str(e)))
self.vls_for_books_cache = {b:tuple(sorted(libs, key=sort_key)) for b, libs in c.items()}
if not book_ids:
book_ids = self._all_book_ids()
# book_ids is usually 1 long. The loop will be faster than a comprehension
r = {}
default = ()
for b in book_ids:
r[b] = self.vls_for_books_cache.get(b, default)
return r
@read_api
def user_categories_for_books(self, book_ids, proxy_metadata_map=None):
''' Return the user categories for the specified books.
proxy_metadata_map is optional and is useful for a performance boost,
in contexts where a ProxyMetadata object for the books already exists.
It should be a mapping of book_ids to their corresponding ProxyMetadata
objects.
'''
user_cats = self._pref('user_categories', {})
pmm = proxy_metadata_map or {}
ans = {}
for book_id in book_ids:
proxy_metadata = pmm.get(book_id) or self._get_proxy_metadata(book_id)
user_cat_vals = ans[book_id] = {}
for ucat, categories in iteritems(user_cats):
user_cat_vals[ucat] = res = []
for name, cat, ign in categories:
try:
field_obj = self.fields[cat]
except KeyError:
continue
if field_obj.is_composite:
v = field_obj.get_value_with_cache(book_id, lambda x:proxy_metadata)
else:
v = self._fast_field_for(field_obj, book_id)
if isinstance(v, (list, tuple)):
if name in v:
res.append([name, cat])
elif name == v:
res.append([name, cat])
return ans
@write_api
def embed_metadata(self, book_ids, only_fmts=None, report_error=None, report_progress=None):
''' Update metadata in all formats of the specified book_ids to current metadata in the database. '''
field = self.fields['formats']
from calibre.customize.ui import apply_null_metadata
from calibre.ebooks.metadata.meta import set_metadata
from calibre.ebooks.metadata.opf2 import pretty_print
if only_fmts:
only_fmts = {f.lower() for f in only_fmts}
def doit(fmt, mi, stream):
with apply_null_metadata, pretty_print:
set_metadata(stream, mi, stream_type=fmt, report_error=report_error)
stream.seek(0, os.SEEK_END)
return stream.tell()
for i, book_id in enumerate(book_ids):
fmts = field.table.book_col_map.get(book_id, ())
if not fmts:
continue
mi = self._get_metadata(book_id)
buf = BytesIO()
if not self._copy_cover_to(book_id, buf):
return
cdata = buf.getvalue()
if cdata:
mi.cover_data = ('jpeg', cdata)
try:
path = self._field_for('path', book_id).replace('/', os.sep)
except:
continue
for fmt in fmts:
if only_fmts is not None and fmt.lower() not in only_fmts:
continue
try:
name = self.fields['formats'].format_fname(book_id, fmt)
except:
continue
if name and path:
try:
new_size = self.backend.apply_to_format(book_id, path, name, fmt, partial(doit, fmt, mi))
except Exception as e:
if report_error is not None:
tb = traceback.format_exc()
if iswindows and isinstance(e, PermissionError) and e.filename and isinstance(e.filename, str):
from calibre_extensions import winutil
try:
p = winutil.get_processes_using_files(e.filename)
except OSError:
pass
else:
path_map = {x['path']: x for x in p}
tb = _('Could not open the file: "{}". It is already opened in the following programs:').format(e.filename)
for path, x in path_map.items():
tb += '\n' + f'{x["app_name"]}: {path}'
report_error(mi, fmt, tb)
new_size = None
else:
raise
if new_size is not None:
self.format_metadata_cache[book_id].get(fmt, {})['size'] = new_size
max_size = self.fields['formats'].table.update_fmt(book_id, fmt, name, new_size, self.backend)
self.fields['size'].table.update_sizes({book_id: max_size})
if report_progress is not None:
report_progress(i+1, len(book_ids), mi)
@read_api
def get_last_read_positions(self, book_id, fmt, user):
fmt = fmt.upper()
ans = []
for device, cfi, epoch, pos_frac in self.backend.execute(
'SELECT device,cfi,epoch,pos_frac FROM last_read_positions WHERE book=? AND format=? AND user=?',
(book_id, fmt, user)):
ans.append({'device':device, 'cfi': cfi, 'epoch':epoch, 'pos_frac':pos_frac})
return ans
@write_api
def set_last_read_position(self, book_id, fmt, user='_', device='_', cfi=None, epoch=None, pos_frac=0):
fmt = fmt.upper()
device = device or '_'
user = user or '_'
if not cfi:
self.backend.execute(
'DELETE FROM last_read_positions WHERE book=? AND format=? AND user=? AND device=?',
(book_id, fmt, user, device))
else:
self.backend.execute(
'INSERT OR REPLACE INTO last_read_positions(book,format,user,device,cfi,epoch,pos_frac) VALUES (?,?,?,?,?,?,?)',
(book_id, fmt, user, device, cfi, epoch or time(), pos_frac))
@read_api
def export_library(self, library_key, exporter, progress=None, abort=None):
from polyglot.binary import as_hex_unicode
key_prefix = as_hex_unicode(library_key)
book_ids = self._all_book_ids()
total = len(book_ids) + 2
has_fts = self.is_fts_enabled()
if has_fts:
total += 1
poff = 0
def report_progress(fname):
nonlocal poff
if progress is not None:
progress(fname, poff, total)
poff += 1
report_progress('metadata.db')
pt = PersistentTemporaryFile('-export.db')
pt.close()
self.backend.backup_database(pt.name)
dbkey = key_prefix + ':::' + 'metadata.db'
with open(pt.name, 'rb') as f:
exporter.add_file(f, dbkey)
os.remove(pt.name)
if has_fts:
report_progress('full-text-search.db')
pt = PersistentTemporaryFile('-export.db')
pt.close()
self.backend.backup_fts_database(pt.name)
ftsdbkey = key_prefix + ':::full-text-search.db'
with open(pt.name, 'rb') as f:
exporter.add_file(f, ftsdbkey)
os.remove(pt.name)
notesdbkey = key_prefix + ':::notes.db'
with PersistentTemporaryFile('-export.db') as pt:
self.backend.export_notes_data(pt)
pt.flush()
pt.seek(0)
report_progress('notes.db')
exporter.add_file(pt, notesdbkey)
format_metadata = {}
extra_files = {}
metadata = {'format_data':format_metadata, 'metadata.db':dbkey, 'notes.db': notesdbkey, 'total':total, 'extra_files': extra_files}
if has_fts:
metadata['full-text-search.db'] = ftsdbkey
for i, book_id in enumerate(book_ids):
if abort is not None and abort.is_set():
return
if progress is not None:
report_progress(self._field_for('title', book_id))
format_metadata[book_id] = fm = {}
for fmt in self._formats(book_id):
mdata = self.format_metadata(book_id, fmt)
key = f'{key_prefix}:{book_id}:{fmt}'
fm[fmt] = key
mtime = mdata.get('mtime')
if mtime is not None:
mtime = timestampfromdt(mtime)
with exporter.start_file(key, mtime=mtime) as dest:
self._copy_format_to(book_id, fmt, dest)
cover_key = '{}:{}:{}'.format(key_prefix, book_id, '.cover')
with exporter.start_file(cover_key) as dest:
if not self.copy_cover_to(book_id, dest):
dest.discard()
else:
fm['.cover'] = cover_key
bp = self.field_for('path', book_id)
extra_files[book_id] = ef = {}
if bp:
for (relpath, fobj, stat_result) in self.backend.iter_extra_files(book_id, bp, self.fields['formats']):
key = f'{key_prefix}:{book_id}:.|{relpath}'
with exporter.start_file(key, mtime=stat_result.st_mtime) as dest:
shutil.copyfileobj(fobj, dest)
ef[relpath] = key
exporter.set_metadata(library_key, metadata)
if progress is not None:
progress(_('Completed'), total, total)
@read_api
def annotations_map_for_book(self, book_id, fmt, user_type='local', user='viewer'):
'''
Return a map of annotation type -> annotation data for the specified book_id, format, user and user_type.
'''
ans = {}
for annot in self.backend.annotations_for_book(book_id, fmt, user_type, user):
ans.setdefault(annot['type'], []).append(annot)
return ans
@read_api
def all_annotations_for_book(self, book_id):
'''
Return a tuple containing all annotations for the specified book_id as a dict with keys:
`format`, `user_type`, `user`, `annotation`. Here, annotation is the annotation data.
'''
return tuple(self.backend.all_annotations_for_book(book_id))
@read_api
def annotation_count_for_book(self, book_id):
'''
Return the number of annotations for the specified book available in the database.
'''
return self.backend.annotation_count_for_book(book_id)
@read_api
def all_annotation_users(self):
'''
Return a tuple of all (user_type, user name) that have annotations.
'''
return tuple(self.backend.all_annotation_users())
@read_api
def all_annotation_types(self):
'''
Return a tuple of all annotation types in the database.
'''
return tuple(self.backend.all_annotation_types())
@read_api
def all_annotations(self, restrict_to_user=None, limit=None, annotation_type=None, ignore_removed=False, restrict_to_book_ids=None):
'''
Return a tuple of all annotations matching the specified criteria.
`ignore_removed` controls whether removed (deleted) annotations are also returned. Removed annotations are just a skeleton
used for merging of annotations.
'''
return tuple(self.backend.all_annotations(restrict_to_user, limit, annotation_type, ignore_removed, restrict_to_book_ids))
@read_api
def search_annotations(
self,
fts_engine_query,
use_stemming=True,
highlight_start=None,
highlight_end=None,
snippet_size=None,
annotation_type=None,
restrict_to_book_ids=None,
restrict_to_user=None,
ignore_removed=False
):
'''
Return of a tuple of annotations matching the specified Full-text query.
'''
return tuple(self.backend.search_annotations(
fts_engine_query, use_stemming, highlight_start, highlight_end,
snippet_size, annotation_type, restrict_to_book_ids, restrict_to_user,
ignore_removed
))
@write_api
def delete_annotations(self, annot_ids):
'''
Delete annotations with the specified ids.
'''
self.backend.delete_annotations(annot_ids)
@write_api
def update_annotations(self, annot_id_map):
'''
Update annotations.
'''
self.backend.update_annotations(annot_id_map)
@write_api
def restore_annotations(self, book_id, annotations):
from calibre.utils.date import EPOCH
from calibre.utils.iso8601 import parse_iso8601
umap = defaultdict(list)
for adata in annotations:
key = adata['user_type'], adata['user'], adata['format']
a = adata['annotation']
ts = (parse_iso8601(a['timestamp']) - EPOCH).total_seconds()
umap[key].append((a, ts))
for (user_type, user, fmt), annots_list in iteritems(umap):
self._set_annotations_for_book(book_id, fmt, annots_list, user_type=user_type, user=user)
@write_api
def set_annotations_for_book(self, book_id, fmt, annots_list, user_type='local', user='viewer'):
'''
Set all annotations for the specified book_id, fmt, user_type and user.
'''
self.backend.set_annotations_for_book(book_id, fmt, annots_list, user_type, user)
@write_api
def merge_annotations_for_book(self, book_id, fmt, annots_list, user_type='local', user='viewer'):
'''
Merge the specified annotations into the existing annotations for book_id, fm, user_type, and user.
'''
from calibre.utils.date import EPOCH
from calibre.utils.iso8601 import parse_iso8601
amap = self._annotations_map_for_book(book_id, fmt, user_type=user_type, user=user)
merge_annotations(annots_list, amap)
alist = []
for val in itervalues(amap):
for annot in val:
ts = (parse_iso8601(annot['timestamp']) - EPOCH).total_seconds()
alist.append((annot, ts))
self._set_annotations_for_book(book_id, fmt, alist, user_type=user_type, user=user)
@write_api
def reindex_annotations(self):
self.backend.reindex_annotations()
@read_api
def are_paths_inside_book_dir(self, book_id, paths, sub_path=''):
try:
path = self._field_for('path', book_id).replace('/', os.sep)
except:
return set()
return {x for x in paths if self.backend.is_path_inside_book_dir(x, path, sub_path)}
@write_api
def add_extra_files(self, book_id, map_of_relpath_to_stream_or_path, replace=True, auto_rename=False):
' Add extra data files '
path = self._field_for('path', book_id).replace('/', os.sep)
added = {}
for relpath, stream_or_path in map_of_relpath_to_stream_or_path.items():
added[relpath] = bool(self.backend.add_extra_file(relpath, stream_or_path, path, replace, auto_rename))
self._clear_extra_files_cache(book_id)
return added
@write_api
def rename_extra_files(self, book_id, map_of_relpath_to_new_relpath, replace=False):
' Rename extra data files '
path = self._field_for('path', book_id).replace('/', os.sep)
renamed = set()
for relpath, newrelpath in map_of_relpath_to_new_relpath.items():
if self.backend.rename_extra_file(relpath, newrelpath, path, replace):
renamed.add(relpath)
self._clear_extra_files_cache(book_id)
return renamed
@write_api
def merge_extra_files(self, dest_id, src_ids, replace=False):
' Merge the extra files from src_ids into dest_id. Conflicting files are auto-renamed unless replace=True in which case they are replaced. '
added = set()
path = self._field_for('path', dest_id)
if path:
path = path.replace('/', os.sep)
for src_id in src_ids:
book_path = self._field_for('path', src_id)
if book_path:
book_path = book_path.replace('/', os.sep)
for (relpath, file_path, stat_result) in self.backend.iter_extra_files(
src_id, book_path, self.fields['formats'], yield_paths=True):
added.add(self.backend.add_extra_file(relpath, file_path, path, replace=replace, auto_rename=True))
self._clear_extra_files_cache(dest_id)
return added
@read_api
def list_extra_files(self, book_id, use_cache=False, pattern='') -> Tuple[ExtraFile, ...]:
'''
Get information about extra files in the book's directory.
:param book_id: the database book id for the book
:param pattern: the pattern of filenames to search for. Empty pattern matches all extra files. Patterns must use / as separator.
Use the DATA_FILE_PATTERN constant to match files inside the data directory.
:return: A tuple of all extra files matching the specified pattern. Each element of the tuple is
ExtraFile(relpath, file_path, stat_result). Where relpath is the relative path of the file
to the book directory using / as a separator.
stat_result is the result of calling os.stat() on the file.
'''
ans = self.extra_files_cache.setdefault(book_id, {}).get(pattern)
if ans is None or not use_cache:
ans = []
path = self._field_for('path', book_id)
if path:
for (relpath, file_path, stat_result) in self.backend.iter_extra_files(
book_id, path, self.fields['formats'], yield_paths=True, pattern=pattern
):
ans.append(ExtraFile(relpath, file_path, stat_result))
self.extra_files_cache[book_id][pattern] = ans = tuple(ans)
return ans
@read_api
def copy_extra_file_to(self, book_id, relpath, stream_or_path):
path = self._field_for('path', book_id).replace('/', os.sep)
self.backend.copy_extra_file_to(book_id, path, relpath, stream_or_path)
@write_api
def merge_book_metadata(self, dest_id, src_ids, replace_cover=False, save_alternate_cover=False):
dest_mi = self.get_metadata(dest_id)
merged_identifiers = self._field_for('identifiers', dest_id) or {}
orig_dest_comments = dest_mi.comments
dest_cover = orig_dest_cover = self.cover(dest_id)
had_orig_cover = bool(dest_cover)
alternate_covers = []
from calibre.utils.date import is_date_undefined
def is_null_date(x):
return x is None or is_date_undefined(x)
for src_id in src_ids:
src_mi = self.get_metadata(src_id)
if src_mi.comments and orig_dest_comments != src_mi.comments:
if not dest_mi.comments:
dest_mi.comments = src_mi.comments
else:
dest_mi.comments = str(dest_mi.comments) + '\n\n' + str(src_mi.comments)
if src_mi.title and dest_mi.is_null('title'):
dest_mi.title = src_mi.title
dest_mi.title_sort = src_mi.title_sort
if (src_mi.authors and src_mi.authors[0] != _('Unknown')) and (not dest_mi.authors or dest_mi.authors[0] == _('Unknown')):
dest_mi.authors = src_mi.authors
dest_mi.author_sort = src_mi.author_sort
if src_mi.tags:
if not dest_mi.tags:
dest_mi.tags = src_mi.tags
else:
dest_mi.tags.extend(src_mi.tags)
if not dest_cover or replace_cover:
src_cover = self.cover(src_id)
if src_cover:
if save_alternate_cover and dest_cover:
alternate_covers.append(dest_cover)
dest_cover = src_cover
replace_cover = False
elif save_alternate_cover:
src_cover = self.cover(src_id)
if src_cover:
alternate_covers.append(src_cover)
if not dest_mi.publisher:
dest_mi.publisher = src_mi.publisher
if not dest_mi.rating:
dest_mi.rating = src_mi.rating
if not dest_mi.series:
dest_mi.series = src_mi.series
dest_mi.series_index = src_mi.series_index
if is_null_date(dest_mi.pubdate) and not is_null_date(src_mi.pubdate):
dest_mi.pubdate = src_mi.pubdate
src_identifiers = (src_mi.get_identifiers() or {}).copy()
src_identifiers.update(merged_identifiers)
merged_identifiers = src_identifiers.copy()
if merged_identifiers:
dest_mi.set_identifiers(merged_identifiers)
self._set_metadata(dest_id, dest_mi, ignore_errors=False)
if dest_cover and (not had_orig_cover or dest_cover is not orig_dest_cover):
self._set_cover({dest_id: dest_cover})
if alternate_covers:
existing = {x[0] for x in self._list_extra_files(dest_id)}
h, ext = os.path.splitext(COVER_FILE_NAME)
template = f'{DATA_DIR_NAME}/{h}-{{:03d}}{ext}'
for cdata in alternate_covers:
for i in range(1, 1000):
q = template.format(i)
if q not in existing:
existing.add(q)
self._add_extra_files(dest_id, {q: BytesIO(cdata)}, replace=False, auto_rename=True)
break
for key in self.field_metadata: # loop thru all defined fields
fm = self.field_metadata[key]
if not fm['is_custom']:
continue
dt = fm['datatype']
label = fm['label']
try:
field = self.field_metadata.label_to_key(label)
except ValueError:
continue
# Get orig_dest_comments before it gets changed
if dt == 'comments':
orig_dest_value = self._field_for(field, dest_id)
for src_id in src_ids:
dest_value = self._field_for(field, dest_id)
src_value = self._field_for(field, src_id)
if (dt == 'comments' and src_value and src_value != orig_dest_value):
if not dest_value:
self._set_field(field, {dest_id: src_value})
else:
dest_value = str(dest_value) + '\n\n' + str(src_value)
self._set_field(field, {dest_id: dest_value})
if (dt in {'bool', 'int', 'float', 'rating', 'datetime'} and dest_value is None):
self._set_field(field, {dest_id: src_value})
if (dt == 'series' and not dest_value and src_value):
src_index = self._field_for(field + '_index', src_id)
self._set_field(field, {dest_id:src_value})
self._set_field(field + '_index', {dest_id:src_index})
if ((dt == 'enumeration' or (dt == 'text' and not fm['is_multiple'])) and not dest_value):
self._set_field(field, {dest_id:src_value})
if (dt == 'text' and fm['is_multiple'] and src_value):
if not dest_value:
dest_value = src_value
else:
dest_value = list(dest_value)
dest_value.extend(src_value)
self._set_field(field, {dest_id: dest_value})
def import_library(library_key, importer, library_path, progress=None, abort=None):
from calibre.db.backend import DB
metadata = importer.metadata[library_key]
total = metadata['total']
poff = 0
def report_progress(fname):
nonlocal poff
if progress is not None:
progress(fname, poff, total)
poff += 1
report_progress('metadata.db')
if abort is not None and abort.is_set():
return
importer.save_file(metadata['metadata.db'], 'metadata.db for ' + library_path, os.path.join(library_path, 'metadata.db'))
if 'full-text-search.db' in metadata:
if progress is not None:
progress('full-text-search.db', 1, total)
if abort is not None and abort.is_set():
return
poff += 1
importer.save_file(metadata['full-text-search.db'], 'full-text-search.db for ' + library_path,
os.path.join(library_path, 'full-text-search.db'))
if abort is not None and abort.is_set():
return
if 'notes.db' in metadata:
import zipfile
notes_dir = os.path.join(library_path, NOTES_DIR_NAME)
os.makedirs(notes_dir, exist_ok=True)
with importer.start_file(metadata['notes.db'], 'notes.db for ' + library_path) as stream:
stream.check_hash = False
with zipfile.ZipFile(stream) as zf:
for zi in zf.infolist():
tpath = zf._extract_member(zi, notes_dir, None)
date_time = mktime(zi.date_time + (0, 0, -1))
os.utime(tpath, (date_time, date_time))
if abort is not None and abort.is_set():
return
if importer.corrupted_files:
raise ValueError('Corrupted files:\n' + '\n'.join(importer.corrupted_files))
cache = Cache(DB(library_path, load_user_formatter_functions=False))
cache.init()
format_data = {int(book_id):data for book_id, data in iteritems(metadata['format_data'])}
extra_files = {int(book_id):data for book_id, data in metadata.get('extra_files', {}).items()}
for i, (book_id, fmt_key_map) in enumerate(iteritems(format_data)):
if abort is not None and abort.is_set():
return
title = cache._field_for('title', book_id)
if progress is not None:
progress(title, i + poff, total)
cache._update_path((book_id,), mark_as_dirtied=False)
for fmt, fmtkey in fmt_key_map.items():
if fmt == '.cover':
with importer.start_file(fmtkey, _('Cover for %s') % title) as stream:
path = cache._field_for('path', book_id).replace('/', os.sep)
cache.backend.set_cover(book_id, path, stream, no_processing=True)
else:
with importer.start_file(fmtkey, _('{0} format for {1}').format(fmt.upper(), title)) as stream:
size, fname = cache._do_add_format(book_id, fmt, stream, mtime=stream.mtime)
cache.fields['formats'].table.update_fmt(book_id, fmt, fname, size, cache.backend)
for relpath, efkey in extra_files.get(book_id, {}).items():
with importer.start_file(efkey, _('Extra file {0} for book {1}').format(relpath, title)) as stream:
path = cache._field_for('path', book_id).replace('/', os.sep)
cache.backend.add_extra_file(relpath, stream, path)
cache.dump_metadata({book_id})
if importer.corrupted_files:
raise ValueError('Corrupted files:\n' + '\n'.join(importer.corrupted_files))
if progress is not None:
progress(_('Completed'), total, total)
return cache
# }}}
| 156,111 | Python | .py | 3,193 | 37.062324 | 156 | 0.589989 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,070 | __init__.py | kovidgoyal_calibre/src/calibre/db/__init__.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
SPOOL_SIZE = 30*1024*1024
import numbers
from polyglot.builtins import iteritems
class FTSQueryError(ValueError):
def __init__(self, query, sql_statement, apsw_error):
ValueError.__init__(self, f'Failed to parse search query: {query} with error: {apsw_error}')
self.query = query
self.sql_statement = sql_statement
def _get_next_series_num_for_list(series_indices, unwrap=True):
from math import ceil, floor
from calibre.utils.config_base import tweaks
if not series_indices:
if isinstance(tweaks['series_index_auto_increment'], numbers.Number):
return float(tweaks['series_index_auto_increment'])
return 1.0
if unwrap:
series_indices = [x[0] for x in series_indices]
if tweaks['series_index_auto_increment'] == 'next':
return floor(series_indices[-1]) + 1
if tweaks['series_index_auto_increment'] == 'first_free':
for i in range(1, 10000):
if i not in series_indices:
return i
# really shouldn't get here.
if tweaks['series_index_auto_increment'] == 'next_free':
for i in range(int(ceil(series_indices[0])), 10000):
if i not in series_indices:
return i
# really shouldn't get here.
if tweaks['series_index_auto_increment'] == 'last_free':
for i in range(int(ceil(series_indices[-1])), 0, -1):
if i not in series_indices:
return i
return series_indices[-1] + 1
if isinstance(tweaks['series_index_auto_increment'], numbers.Number):
return float(tweaks['series_index_auto_increment'])
return 1.0
def _get_series_values(val):
import re
series_index_pat = re.compile(r'(.*)\s+\[([.0-9]+)\]$')
if not val:
return (val, None)
match = series_index_pat.match(val.strip())
if match is not None:
idx = match.group(2)
try:
idx = float(idx)
return (match.group(1).strip(), idx)
except:
pass
return (val, None)
def get_data_as_dict(self, prefix=None, authors_as_string=False, ids=None, convert_to_local_tz=True):
'''
Return all metadata stored in the database as a dict. Includes paths to
the cover and each format.
:param prefix: The prefix for all paths. By default, the prefix is the absolute path
to the library folder.
:param ids: Set of ids to return the data for. If None return data for
all entries in database.
'''
import os
from calibre.ebooks.metadata import authors_to_string
from calibre.utils.date import as_local_time
backend = getattr(self, 'backend', self) # Works with both old and legacy interfaces
if prefix is None:
prefix = backend.library_path
fdata = backend.custom_column_num_map
FIELDS = {'title', 'sort', 'authors', 'author_sort', 'publisher',
'rating', 'timestamp', 'size', 'tags', 'comments', 'series',
'series_index', 'uuid', 'pubdate', 'last_modified', 'identifiers',
'languages'}.union(set(fdata))
for x, data in iteritems(fdata):
if data['datatype'] == 'series':
FIELDS.add('%d_index'%x)
data = []
for record in self.data:
if record is None:
continue
db_id = record[self.FIELD_MAP['id']]
if ids is not None and db_id not in ids:
continue
x = {}
for field in FIELDS:
x[field] = record[self.FIELD_MAP[field]]
if convert_to_local_tz:
for tf in ('timestamp', 'pubdate', 'last_modified'):
x[tf] = as_local_time(x[tf])
data.append(x)
x['id'] = db_id
x['formats'] = []
isbn = self.isbn(db_id, index_is_id=True)
x['isbn'] = isbn if isbn else ''
if not x['authors']:
x['authors'] = _('Unknown')
x['authors'] = [i.replace('|', ',') for i in x['authors'].split(',')]
if authors_as_string:
x['authors'] = authors_to_string(x['authors'])
x['tags'] = [i.replace('|', ',').strip() for i in x['tags'].split(',')] if x['tags'] else []
path = os.path.join(prefix, self.path(record[self.FIELD_MAP['id']], index_is_id=True))
x['cover'] = os.path.join(path, 'cover.jpg')
if not record[self.FIELD_MAP['cover']]:
x['cover'] = None
formats = self.formats(record[self.FIELD_MAP['id']], index_is_id=True)
if formats:
for fmt in formats.split(','):
path = self.format_abspath(x['id'], fmt, index_is_id=True)
if path is None:
continue
if prefix != self.library_path:
path = os.path.relpath(path, self.library_path)
path = os.path.join(prefix, path)
x['formats'].append(path)
x['fmt_'+fmt.lower()] = path
x['available_formats'] = [i.upper() for i in formats.split(',')]
return data
| 5,134 | Python | .py | 119 | 34.445378 | 101 | 0.592593 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,071 | copy_to_library.py | kovidgoyal_calibre/src/calibre/db/copy_to_library.py | #!/usr/bin/env python
# License: GPL v3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net>
from calibre.db.utils import find_identical_books
from calibre.utils.config import tweaks
from calibre.utils.date import now
from polyglot.builtins import iteritems
def automerge_book(automerge_action, book_id, mi, identical_book_list, newdb, format_map, extra_file_map):
seen_fmts = set()
replace = automerge_action == 'overwrite'
for identical_book in identical_book_list:
ib_fmts = newdb.formats(identical_book)
if ib_fmts:
seen_fmts |= {fmt.upper() for fmt in ib_fmts}
at_least_one_format_added = False
for fmt, path in iteritems(format_map):
if newdb.add_format(identical_book, fmt, path, replace=replace, run_hooks=False):
at_least_one_format_added = True
if at_least_one_format_added and extra_file_map:
newdb.add_extra_files(identical_book, extra_file_map, replace=False, auto_rename=True)
if automerge_action == 'new record':
incoming_fmts = {fmt.upper() for fmt in format_map}
if incoming_fmts.intersection(seen_fmts):
# There was at least one duplicate format
# so create a new record and put the
# incoming formats into it
# We should arguably put only the duplicate
# formats, but no real harm is done by having
# all formats
new_book_id = newdb.add_books(
[(mi, format_map)], add_duplicates=True, apply_import_tags=tweaks['add_new_book_tags_when_importing_books'],
preserve_uuid=False, run_hooks=False)[0][0]
if extra_file_map:
newdb.add_extra_files(new_book_id, extra_file_map)
return new_book_id
def postprocess_copy(book_id, new_book_id, new_authors, db, newdb, identical_books_data, duplicate_action):
if not new_book_id:
return
if new_authors:
author_id_map = db.get_item_ids('authors', new_authors)
sort_map = {}
for author, aid in iteritems(author_id_map):
if aid is not None:
adata = db.author_data((aid,)).get(aid)
if adata is not None:
aid = newdb.get_item_id('authors', author)
if aid is not None:
asv = adata.get('sort')
if asv:
sort_map[aid] = asv
if sort_map:
newdb.set_sort_for_authors(sort_map, update_books=False)
co = db.conversion_options(book_id)
if co is not None:
newdb.set_conversion_options({new_book_id:co})
annots = db.all_annotations_for_book(book_id)
if annots:
newdb.restore_annotations(new_book_id, annots)
if identical_books_data is not None and duplicate_action != 'add':
newdb.update_data_for_find_identical_books(new_book_id, identical_books_data)
def copy_one_book(
book_id, src_db, dest_db, duplicate_action='add', automerge_action='overwrite',
preserve_date=True, identical_books_data=None, preserve_uuid=False):
db = src_db.new_api
newdb = dest_db.new_api
with db.safe_read_lock, newdb.write_lock:
mi = db.get_metadata(book_id, get_cover=True, cover_as_data=True)
if not preserve_date:
mi.timestamp = now()
format_map = {}
fmts = list(db.formats(book_id, verify_formats=False))
extra_file_map = {}
for ef in db.list_extra_files(book_id):
extra_file_map[ef.relpath] = ef.file_path
for fmt in fmts:
path = db.format_abspath(book_id, fmt)
if path:
format_map[fmt.upper()] = path
identical_book_list = set()
new_authors = {k for k, v in iteritems(newdb.get_item_ids('authors', mi.authors)) if v is None}
new_book_id = None
return_data = {
'book_id': book_id, 'title': mi.title, 'authors': mi.authors, 'author': mi.format_field('authors')[1],
'action': 'add', 'new_book_id': None
}
if duplicate_action != 'add':
# Scanning for dupes can be slow on a large library so
# only do it if the option is set
if identical_books_data is None:
identical_books_data = identical_books_data = newdb.data_for_find_identical_books()
identical_book_list = find_identical_books(mi, identical_books_data)
if identical_book_list: # books with same author and nearly same title exist in newdb
if duplicate_action == 'add_formats_to_existing':
new_book_id = automerge_book(automerge_action, book_id, mi, identical_book_list, newdb, format_map, extra_file_map)
return_data['action'] = 'automerge'
return_data['new_book_id'] = new_book_id
postprocess_copy(book_id, new_book_id, new_authors, db, newdb, identical_books_data, duplicate_action)
else:
return_data['action'] = 'duplicate'
return return_data
new_book_id = newdb.add_books(
[(mi, format_map)], add_duplicates=True, apply_import_tags=tweaks['add_new_book_tags_when_importing_books'],
preserve_uuid=preserve_uuid, run_hooks=False)[0][0]
bp = db.field_for('path', book_id)
if bp:
for (relpath, src_path, stat_result) in db.backend.iter_extra_files(book_id, bp, db.fields['formats'], yield_paths=True):
nbp = newdb.field_for('path', new_book_id)
if nbp:
newdb.backend.add_extra_file(relpath, src_path, nbp)
postprocess_copy(book_id, new_book_id, new_authors, db, newdb, identical_books_data, duplicate_action)
return_data['new_book_id'] = new_book_id
return return_data
| 5,890 | Python | .py | 111 | 41.756757 | 135 | 0.610196 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,072 | adding.py | kovidgoyal_calibre/src/calibre/db/adding.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import os
import re
import time
from collections import defaultdict
from contextlib import contextmanager
from functools import partial
from calibre import prints
from calibre.constants import filesystem_encoding, ismacos, iswindows
from calibre.ebooks import BOOK_EXTENSIONS
from calibre.utils.filenames import make_long_path_useable
from calibre.utils.icu import lower as icu_lower
from polyglot.builtins import itervalues
def splitext(path):
key, ext = os.path.splitext(path)
return key, ext[1:].lower()
def formats_ok(formats):
return len(formats) > 0
def path_ok(path):
return not os.path.isdir(path) and os.access(path, os.R_OK)
def compile_glob(pat):
import fnmatch
return re.compile(fnmatch.translate(pat), flags=re.I)
def compile_rule(rule):
mt = rule['match_type']
if 'with' in mt:
q = icu_lower(rule['query'])
if 'startswith' in mt:
def func(filename):
return icu_lower(filename).startswith(q)
else:
def func(filename):
return icu_lower(filename).endswith(q)
elif 'glob' in mt:
q = compile_glob(rule['query'])
def func(filename):
return (q.match(filename) is not None)
else:
q = re.compile(rule['query'])
def func(filename):
return (q.match(filename) is not None)
ans = func
if mt.startswith('not_'):
def ans(filename):
return (not func(filename))
return ans, rule['action'] == 'add'
def filter_filename(compiled_rules, filename):
for q, action in compiled_rules:
if q(filename):
return action
_metadata_extensions = None
def metadata_extensions():
# Set of all known book extensions + OPF (the OPF is used to read metadata,
# but not actually added)
global _metadata_extensions
if _metadata_extensions is None:
_metadata_extensions = frozenset(BOOK_EXTENSIONS) | {'opf'}
return _metadata_extensions
if iswindows or ismacos:
unicode_listdir = os.listdir
else:
def unicode_listdir(root):
root = root.encode(filesystem_encoding)
for x in os.listdir(root):
try:
yield x.decode(filesystem_encoding)
except UnicodeDecodeError:
prints('Ignoring un-decodable file:', x)
def listdir(root, sort_by_mtime=False):
items = (make_long_path_useable(os.path.join(root, x)) for x in unicode_listdir(root))
if sort_by_mtime:
def safe_mtime(x):
try:
return os.path.getmtime(x)
except OSError:
return time.time()
items = sorted(items, key=safe_mtime)
for path in items:
if path_ok(path):
yield path
def allow_path(path, ext, compiled_rules):
ans = filter_filename(compiled_rules, os.path.basename(path))
if ans is None:
ans = ext in metadata_extensions()
return ans
import_ctx = None
@contextmanager
def run_import_plugins_before_metadata(tdir, group_id=0):
global import_ctx
import_ctx = {'tdir': tdir, 'group_id': group_id, 'format_map': {}}
yield import_ctx
import_ctx = None
def run_import_plugins(formats):
from calibre.ebooks.metadata.worker import run_import_plugins
import_ctx['group_id'] += 1
ans = run_import_plugins(formats, import_ctx['group_id'], import_ctx['tdir'])
fm = import_ctx['format_map']
for old_path, new_path in zip(formats, ans):
new_path = make_long_path_useable(new_path)
fm[new_path] = old_path
return ans
def find_books_in_directory(dirpath, single_book_per_directory, compiled_rules=(), listdir_impl=listdir):
dirpath = make_long_path_useable(os.path.abspath(dirpath))
if single_book_per_directory:
formats = {}
for path in listdir_impl(dirpath):
key, ext = splitext(path)
if allow_path(path, ext, compiled_rules):
formats[ext] = path
if formats_ok(formats):
yield list(itervalues(formats))
else:
books = defaultdict(dict)
for path in listdir_impl(dirpath, sort_by_mtime=True):
key, ext = splitext(path)
if allow_path(path, ext, compiled_rules):
books[icu_lower(key) if isinstance(key, str) else key.lower()][ext] = path
for formats in itervalues(books):
if formats_ok(formats):
yield list(itervalues(formats))
def create_format_map(formats):
format_map = {}
for path in formats:
ext = os.path.splitext(path)[1][1:].upper()
if ext == 'OPF':
continue
format_map[ext] = path
return format_map
def import_book_directory_multiple(db, dirpath, callback=None,
added_ids=None, compiled_rules=(), add_duplicates=False):
from calibre.ebooks.metadata.meta import metadata_from_formats
duplicates = []
for formats in find_books_in_directory(dirpath, False, compiled_rules=compiled_rules):
mi = metadata_from_formats(formats)
if mi.title is None:
continue
ids, dups = db.new_api.add_books([(mi, create_format_map(formats))], add_duplicates=add_duplicates)
if dups:
duplicates.append((mi, formats))
continue
book_id = next(iter(ids))
if added_ids is not None:
added_ids.add(book_id)
if callable(callback):
if callback(mi.title):
break
return duplicates
def import_book_directory(db, dirpath, callback=None, added_ids=None, compiled_rules=(), add_duplicates=False):
from calibre.ebooks.metadata.meta import metadata_from_formats
dirpath = os.path.abspath(dirpath)
formats = None
for formats in find_books_in_directory(dirpath, True, compiled_rules=compiled_rules):
break
if not formats:
return
mi = metadata_from_formats(formats)
if mi.title is None:
return
ids, dups = db.new_api.add_books([(mi, create_format_map(formats))], add_duplicates=add_duplicates)
if dups:
return [(mi, formats)]
book_id = next(iter(ids))
if added_ids is not None:
added_ids.add(book_id)
if callable(callback):
callback(mi.title)
def recursive_import(db, root, single_book_per_directory=True,
callback=None, added_ids=None, compiled_rules=(), add_duplicates=False):
root = os.path.abspath(root)
duplicates = []
for dirpath in os.walk(root):
func = import_book_directory if single_book_per_directory else import_book_directory_multiple
res = func(db, dirpath[0], callback=callback,
added_ids=added_ids, compiled_rules=compiled_rules, add_duplicates=add_duplicates)
if res is not None:
duplicates.extend(res)
if callable(callback):
if callback(''):
break
return duplicates
def cdb_find_in_dir(dirpath, single_book_per_directory, compiled_rules):
return find_books_in_directory(dirpath, single_book_per_directory=single_book_per_directory,
compiled_rules=compiled_rules, listdir_impl=partial(listdir, sort_by_mtime=True))
def cdb_recursive_find(root, single_book_per_directory=True, compiled_rules=()):
root = os.path.abspath(root)
for dirpath in os.walk(root):
yield from cdb_find_in_dir(dirpath[0], single_book_per_directory, compiled_rules)
def add_catalog(cache, path, title, dbapi=None):
from calibre.ebooks.metadata.book.base import Metadata
from calibre.ebooks.metadata.meta import get_metadata
from calibre.utils.date import utcnow
fmt = os.path.splitext(path)[1][1:].lower()
new_book_added = False
with open(path, 'rb') as stream:
with cache.write_lock:
matches = cache._search('title:="{}" and tags:="{}"'.format(title.replace('"', '\\"'), _('Catalog')), None)
db_id = None
if matches:
db_id = list(matches)[0]
try:
mi = get_metadata(stream, fmt)
mi.authors = ['calibre']
except Exception:
mi = Metadata(title, ['calibre'])
mi.title, mi.authors = title, ['calibre']
mi.author_sort = 'calibre' # The MOBI/AZW3 format sets author sort to date
mi.pubdate = mi.timestamp = utcnow()
if fmt == 'mobi':
mi.cover, mi.cover_data = None, (None, None)
if db_id is None:
mi.tags = [_('Catalog')]
db_id = cache._create_book_entry(mi, apply_import_tags=False)
new_book_added = True
else:
tags = list(cache._field_for('tags', db_id) or ())
if _('Catalog') not in tags:
tags.append(_('Catalog'))
mi.tags = tags
cache._set_metadata(db_id, mi)
cache.add_format(db_id, fmt, stream, dbapi=dbapi) # Can't keep write lock since post-import hooks might run
return db_id, new_book_added
def add_news(cache, path, arg, dbapi=None):
from calibre.ebooks.metadata.meta import get_metadata
from calibre.utils.date import utcnow
fmt = os.path.splitext(getattr(path, 'name', path))[1][1:].lower()
stream = path if hasattr(path, 'read') else open(path, 'rb')
stream.seek(0)
mi = get_metadata(stream, fmt, use_libprs_metadata=False,
force_read_metadata=True)
# Force the author to calibre as the auto delete of old news checks for
# both the author==calibre and the tag News
mi.authors = ['calibre']
stream.seek(0)
with cache.write_lock:
if mi.series_index is None:
mi.series_index = cache._get_next_series_num_for(mi.series)
mi.tags = [_('News')]
if arg.get('add_title_tag'):
mi.tags += [arg['title']]
if arg.get('custom_tags'):
mi.tags += arg['custom_tags']
if mi.pubdate is None:
mi.pubdate = utcnow()
if mi.timestamp is None:
mi.timestamp = utcnow()
db_id = cache._create_book_entry(mi, apply_import_tags=False)
cache.add_format(db_id, fmt, stream, dbapi=dbapi) # Can't keep write lock since post-import hooks might run
if not hasattr(path, 'read'):
stream.close()
return db_id
| 10,433 | Python | .py | 252 | 33.337302 | 119 | 0.636992 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,073 | listeners.py | kovidgoyal_calibre/src/calibre/db/listeners.py | #!/usr/bin/env python
# License: GPL v3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import weakref
from contextlib import suppress
from enum import Enum, auto
from queue import Queue
from threading import Thread
class EventType(Enum):
#: When some metadata is changed for some books, with
#: arguments: (name of changed field, set of affected book ids)
metadata_changed = auto()
#: When a format is added to a book, with arguments:
#: (book_id, format)
format_added = auto()
#: When formats are removed from a book, with arguments:
#: (mapping of book id to set of formats removed from the book)
formats_removed = auto()
#: When a new book record is created in the database, with the
#: book id as the only argument
book_created = auto()
#: When books are removed from the database with the list of book
#: ids as the only argument
books_removed = auto()
#: When items such as tags or authors are renamed in some or all books.
#: Arguments: (field_name, affected book ids, map of old item id to new item id)
items_renamed = auto()
#: When items such as tags or authors are removed from some books.
#: Arguments: (field_name, affected book ids, ids of removed items)
items_removed = auto()
#: When a book format is edited, with arguments: (book_id, fmt)
book_edited = auto()
#: When the indexing progress changes
indexing_progress_changed = auto()
class EventDispatcher(Thread):
def __init__(self):
Thread.__init__(self, name='DBListener', daemon=True)
self.refs = []
self.queue = Queue()
self.activated = False
self.library_id = ''
def add_listener(self, callback):
# note that we intentionally leak dead weakrefs. To not do so would
# require using a lock to serialize access to self.refs. Given that
# currently the use case for listeners is register one and leave it
# forever, this is a worthwhile tradeoff
self.remove_listener(callback)
ref = weakref.ref(callback)
self.refs.append(ref)
if not self.activated:
self.activated = True
self.start()
def remove_listener(self, callback):
ref = weakref.ref(callback)
with suppress(ValueError):
self.refs.remove(ref)
def __contains__(self, callback):
ref = weakref.ref(callback)
return ref in self.refs
def __call__(self, event_name, *args):
if self.activated:
self.queue.put((event_name, self.library_id, args))
def close(self):
if self.activated:
self.queue.put(None)
self.join()
self.refs = []
def run(self):
while True:
val = self.queue.get()
if val is None:
break
for ref in self.refs:
listener = ref()
if listener is not None:
listener(*val)
| 3,002 | Python | .py | 75 | 32.413333 | 84 | 0.639147 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,074 | view.py | kovidgoyal_calibre/src/calibre/db/view.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import numbers
import operator
import sys
import weakref
from functools import partial
from calibre.db.write import uniq
from calibre.ebooks.metadata import title_sort
from calibre.utils.config_base import prefs, tweaks
from polyglot.builtins import iteritems, itervalues
def sanitize_sort_field_name(field_metadata, field):
field = field_metadata.search_term_to_field_key(field.lower().strip())
# translate some fields to their hidden equivalent
field = {'title': 'sort', 'authors':'author_sort'}.get(field, field)
return field
class MarkedVirtualField:
def __init__(self, marked_ids):
self.marked_ids = marked_ids
def iter_searchable_values(self, get_metadata, candidates, default_value=None):
for book_id in candidates:
yield self.marked_ids.get(book_id, default_value), {book_id}
def sort_keys_for_books(self, get_metadata, lang_map):
g = self.marked_ids.get
return lambda book_id:g(book_id, '')
class InTagBrowserVirtualField:
def __init__(self, _ids):
self._ids = _ids
def iter_searchable_values(self, get_metadata, candidates, default_value=None):
# The returned value can be any string. For example it could be book_id
# as a string, but there is little point in spending the cpu cycles for
# that as no one will do a search like in_tag_browser:1544 (a book id)
for book_id in candidates:
yield 'A' if self._ids is None or book_id in self._ids else default_value, {book_id}
def sort_keys_for_books(self, get_metadata, lang_map):
null = sys.maxsize
if self._ids is None:
def key(_id):
return null
else:
def key(_id):
return _id if _id in self._ids else null
return key
class TableRow:
def __init__(self, book_id, view):
self.book_id = book_id
self.view = weakref.ref(view)
self.column_count = view.column_count
def __getitem__(self, obj):
view = self.view()
if isinstance(obj, slice):
return [view._field_getters[c](self.book_id)
for c in range(*obj.indices(len(view._field_getters)))]
else:
return view._field_getters[obj](self.book_id)
def __len__(self):
return self.column_count
def __iter__(self):
for i in range(self.column_count):
yield self[i]
def format_is_multiple(x, sep=',', repl=None):
if not x:
return None
if repl is not None:
x = (y.replace(sep, repl) for y in x)
return sep.join(x)
def format_identifiers(x):
if not x:
return None
return ','.join('%s:%s'%(k, v) for k, v in iteritems(x))
class View:
''' A table view of the database, with rows and columns. Also supports
filtering and sorting. '''
def __init__(self, cache):
self.cache = cache
self.marked_ids = {}
self.tag_browser_ids = None
self.marked_listeners = {}
self.search_restriction_book_count = 0
self.search_restriction = self.base_restriction = ''
self.search_restriction_name = self.base_restriction_name = ''
self._field_getters = {}
self.column_count = len(cache.backend.FIELD_MAP)
for col, idx in iteritems(cache.backend.FIELD_MAP):
label, fmt = col, lambda x:x
func = {
'id': self._get_id,
'au_map': self.get_author_data,
'ondevice': self.get_ondevice,
'marked': self.get_marked,
'all_marked_labels': self.all_marked_labels,
'series_sort':self.get_series_sort,
}.get(col, self._get)
if isinstance(col, numbers.Integral):
label = self.cache.backend.custom_column_num_map[col]['label']
label = (self.cache.backend.field_metadata.custom_field_prefix + label)
if label.endswith('_index'):
try:
num = int(label.partition('_')[0])
except ValueError:
pass # series_index
else:
label = self.cache.backend.custom_column_num_map[num]['label']
label = (self.cache.backend.field_metadata.custom_field_prefix + label + '_index')
fm = self.field_metadata[label]
fm
if label == 'authors':
fmt = partial(format_is_multiple, repl='|')
elif label in {'tags', 'languages', 'formats'}:
fmt = format_is_multiple
elif label == 'cover':
fmt = bool
elif label == 'identifiers':
fmt = format_identifiers
elif fm['datatype'] == 'text' and fm['is_multiple']:
sep = fm['is_multiple']['cache_to_list']
if sep not in {'&','|'}:
sep = '|'
fmt = partial(format_is_multiple, sep=sep)
self._field_getters[idx] = partial(func, label, fmt=fmt) if func == self._get else func
self._real_map_filtered = ()
self._real_map_filtered_id_to_row = {}
self._map = tuple(sorted(self.cache.all_book_ids()))
self._map_filtered = tuple(self._map)
self.full_map_is_sorted = True
self.sort_history = [('id', True)]
def add_marked_listener(self, func):
self.marked_listeners[id(func)] = weakref.ref(func)
def add_to_sort_history(self, items):
self.sort_history = uniq((list(items) + list(self.sort_history)),
operator.itemgetter(0))[:tweaks['maximum_resort_levels']]
def count(self):
return len(self._map)
def get_property(self, id_or_index, index_is_id=False, loc=-1):
book_id = id_or_index if index_is_id else self._map_filtered[id_or_index]
return self._field_getters[loc](book_id)
def sanitize_sort_field_name(self, field):
return sanitize_sort_field_name(self.field_metadata, field)
@property
def _map_filtered(self):
return self._real_map_filtered
@_map_filtered.setter
def _map_filtered(self, v):
self._real_map_filtered = v
self._real_map_filtered_id_to_row = {id_:row for row, id_ in enumerate(self._map_filtered)}
@property
def field_metadata(self):
return self.cache.field_metadata
def _get_id(self, idx, index_is_id=True):
if index_is_id and not self.cache.has_id(idx):
raise IndexError('No book with id %s present'%idx)
return idx if index_is_id else self.index_to_id(idx)
def has_id(self, book_id):
return self.cache.has_id(book_id)
def __getitem__(self, row):
return TableRow(self._map_filtered[row], self)
def __len__(self):
return len(self._map_filtered)
def __iter__(self):
for book_id in self._map_filtered:
yield TableRow(book_id, self)
def iterall(self):
for book_id in self.iterallids():
yield TableRow(book_id, self)
def iterallids(self):
yield from sorted(self._map)
def tablerow_for_id(self, book_id):
return TableRow(book_id, self)
def get_field_map_field(self, row, col, index_is_id=True):
'''
Supports the legacy FIELD_MAP interface for getting metadata. Do not use
in new code.
'''
getter = self._field_getters[col]
return getter(row, index_is_id=index_is_id)
def index_to_id(self, idx):
return self._map_filtered[idx]
def id_to_index(self, book_id):
try:
return self._real_map_filtered_id_to_row[book_id]
except KeyError:
raise ValueError(f'No such book_id {book_id}')
row = index_to_id
def index(self, book_id, cache=False):
if cache:
return self._map.index(book_id)
return self.id_to_index(book_id)
def _get(self, field, idx, index_is_id=True, default_value=None, fmt=lambda x:x):
id_ = idx if index_is_id else self.index_to_id(idx)
if index_is_id and not self.cache.has_id(id_):
raise IndexError('No book with id %s present'%idx)
return fmt(self.cache.field_for(field, id_, default_value=default_value))
def get_series_sort(self, idx, index_is_id=True, default_value=''):
book_id = idx if index_is_id else self.index_to_id(idx)
with self.cache.safe_read_lock:
lang_map = self.cache.fields['languages'].book_value_map
lang = lang_map.get(book_id, None) or None
if lang:
lang = lang[0]
return title_sort(self.cache._field_for('series', book_id, default_value=''),
order=tweaks['title_series_sorting'], lang=lang)
def get_ondevice(self, idx, index_is_id=True, default_value=''):
id_ = idx if index_is_id else self.index_to_id(idx)
return self.cache.field_for('ondevice', id_, default_value=default_value)
def get_marked(self, idx, index_is_id=True, default_value=None):
id_ = idx if index_is_id else self.index_to_id(idx)
return self.marked_ids.get(id_, default_value)
def all_marked_labels(self):
return set(self.marked_ids.values()) - {'true'}
def get_author_data(self, idx, index_is_id=True, default_value=None):
id_ = idx if index_is_id else self.index_to_id(idx)
with self.cache.safe_read_lock:
ids = self.cache._field_ids_for('authors', id_)
adata = self.cache._author_data(ids)
ans = [':::'.join((adata[aid]['name'], adata[aid]['sort'], adata[aid]['link'])) for aid in ids if aid in adata]
return ':#:'.join(ans) if ans else default_value
def get_virtual_libraries_for_books(self, ids):
return self.cache.virtual_libraries_for_books(
ids, virtual_fields={'marked':MarkedVirtualField(self.marked_ids),
'in_tag_browser': InTagBrowserVirtualField(self.tag_browser_ids)})
def _do_sort(self, ids_to_sort, fields=(), subsort=False):
fields = [(sanitize_sort_field_name(self.field_metadata, x), bool(y)) for x, y in fields]
keys = self.field_metadata.sortable_field_keys()
fields = [x for x in fields if x[0] in keys]
if subsort and 'sort' not in [x[0] for x in fields]:
fields += [('sort', True)]
if not fields:
fields = [('timestamp', False)]
return self.cache.multisort(
fields, ids_to_sort=ids_to_sort,
virtual_fields={'marked':MarkedVirtualField(self.marked_ids),
'in_tag_browser': InTagBrowserVirtualField(self.tag_browser_ids)})
def multisort(self, fields=[], subsort=False, only_ids=None):
sorted_book_ids = self._do_sort(self._map if only_ids is None else only_ids, fields=fields, subsort=subsort)
if only_ids is None:
self._map = tuple(sorted_book_ids)
self.full_map_is_sorted = True
self.add_to_sort_history(fields)
if len(self._map_filtered) == len(self._map):
self._map_filtered = tuple(self._map)
else:
fids = frozenset(self._map_filtered)
self._map_filtered = tuple(i for i in self._map if i in fids)
else:
smap = {book_id:i for i, book_id in enumerate(sorted_book_ids)}
only_ids.sort(key=smap.get)
def incremental_sort(self, fields=(), subsort=False):
if len(self._map) == len(self._map_filtered):
return self.multisort(fields=fields, subsort=subsort)
self._map_filtered = tuple(self._do_sort(self._map_filtered, fields=fields, subsort=subsort))
self.full_map_is_sorted = False
self.add_to_sort_history(fields)
def search(self, query, return_matches=False, sort_results=True):
ans = self.search_getting_ids(query, self.search_restriction,
set_restriction_count=True, sort_results=sort_results)
if return_matches:
return ans
self._map_filtered = tuple(ans)
def _build_restriction_string(self, restriction):
if self.base_restriction:
if restriction:
return f'({self.base_restriction}) and ({restriction})'
else:
return self.base_restriction
else:
return restriction
def search_getting_ids(self, query, search_restriction,
set_restriction_count=False, use_virtual_library=True, sort_results=True):
if use_virtual_library:
search_restriction = self._build_restriction_string(search_restriction)
q = ''
if not query or not query.strip():
q = search_restriction
else:
q = query
if search_restriction:
q = f'({search_restriction}) and ({query})'
if not q:
if set_restriction_count:
self.search_restriction_book_count = len(self._map)
rv = list(self._map)
if sort_results and not self.full_map_is_sorted:
rv = self._do_sort(rv, fields=self.sort_history)
self._map = tuple(rv)
self.full_map_is_sorted = True
return rv
matches = self.cache.search(
query, search_restriction, virtual_fields={'marked':MarkedVirtualField(self.marked_ids),
'in_tag_browser': InTagBrowserVirtualField(self.tag_browser_ids)})
if len(matches) == len(self._map):
rv = list(self._map)
else:
rv = [x for x in self._map if x in matches]
if sort_results and not self.full_map_is_sorted:
# We need to sort the search results
if matches.issubset(frozenset(self._map_filtered)):
rv = [x for x in self._map_filtered if x in matches]
else:
rv = self._do_sort(rv, fields=self.sort_history)
if len(matches) == len(self._map):
# We have sorted all ids, update self._map
self._map = tuple(rv)
self.full_map_is_sorted = True
if set_restriction_count and q == search_restriction:
self.search_restriction_book_count = len(rv)
return rv
def get_search_restriction(self):
return self.search_restriction
def set_search_restriction(self, s):
self.search_restriction = s
def get_base_restriction(self):
return self.base_restriction
def set_base_restriction(self, s):
self.base_restriction = s
def get_base_restriction_name(self):
return self.base_restriction_name
def set_base_restriction_name(self, s):
self.base_restriction_name = s
def get_search_restriction_name(self):
return self.search_restriction_name
def set_search_restriction_name(self, s):
self.search_restriction_name = s
def search_restriction_applied(self):
return bool(self.search_restriction) or bool(self.base_restriction)
def get_search_restriction_book_count(self):
return self.search_restriction_book_count
def change_search_locations(self, newlocs):
self.cache.change_search_locations(newlocs)
def set_in_tag_browser(self, id_set):
self.tag_browser_ids = id_set
def get_in_tag_browser(self):
return self.tag_browser_ids
def set_marked_ids(self, id_dict):
'''
ids in id_dict are "marked". They can be searched for by
using the search term ``marked:true``. Pass in an empty dictionary or
set to clear marked ids.
:param id_dict: Either a dictionary mapping ids to values or a set
of ids. In the latter case, the value is set to 'true' for all ids. If
a mapping is provided, then the search can be used to search for
particular values: ``marked:value``
'''
old_marked_ids = set(self.marked_ids)
if not hasattr(id_dict, 'items'):
# Simple list. Make it a dict entry of string 'true'
self.marked_ids = {k: (self.marked_ids[k] if k in self.marked_ids else 'true')
for k in id_dict}
else:
# Ensure that all the items in the dict are text
self.marked_ids = {k: str(v) for k, v in iteritems(id_dict)}
# This invalidates all searches in the cache even though the cache may
# be shared by multiple views. This is not ideal, but...
cmids = set(self.marked_ids)
changed_ids = old_marked_ids | cmids
self.cache.clear_search_caches(changed_ids)
self.cache.clear_caches(book_ids=changed_ids)
# Always call the listener because the labels might have changed even
# if the ids haven't.
for funcref in itervalues(self.marked_listeners):
func = funcref()
if func is not None:
func(old_marked_ids, cmids)
def toggle_marked_ids(self, book_ids):
book_ids = set(book_ids)
mids = set(self.marked_ids)
common = mids.intersection(book_ids)
self.set_marked_ids((mids | book_ids) - common)
def add_marked_ids(self, book_ids):
self.set_marked_ids(set(self.marked_ids) | set(book_ids))
def refresh(self, field=None, ascending=True, clear_caches=True, do_search=True):
self._map = tuple(sorted(self.cache.all_book_ids()))
self._map_filtered = tuple(self._map)
self.full_map_is_sorted = True
self.sort_history = [('id', True)]
if clear_caches:
self.cache.clear_caches()
if field is not None:
self.sort(field, ascending)
if do_search and (self.search_restriction or self.base_restriction):
self.search('', return_matches=False)
def refresh_ids(self, ids):
self.cache.clear_caches(book_ids=ids)
# The ids list can contain invalid ids (deleted etc). We want to filter
# those out while keeping the valid ones.
return [self._real_map_filtered_id_to_row[id_] for id_ in ids if id_ in self._real_map_filtered_id_to_row] or None
def remove(self, book_id):
try:
self._map = tuple(bid for bid in self._map if bid != book_id)
except ValueError:
pass
try:
self._map_filtered = tuple(bid for bid in self._map_filtered if bid != book_id)
except ValueError:
pass
def books_deleted(self, ids):
for book_id in ids:
self.remove(book_id)
def books_added(self, ids):
ids = tuple(ids)
self._map = ids + self._map
self._map_filtered = ids + self._map_filtered
if prefs['mark_new_books']:
self.toggle_marked_ids(ids)
| 19,082 | Python | .py | 405 | 36.804938 | 123 | 0.604497 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,075 | fields.py | kovidgoyal_calibre/src/calibre/db/fields.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import sys
from collections import Counter, defaultdict
from functools import partial
from threading import Lock
from typing import Iterable
from calibre.db.tables import MANY_MANY, MANY_ONE, ONE_ONE, null
from calibre.db.utils import atof, force_to_bool
from calibre.db.write import Writer
from calibre.ebooks.metadata import author_to_author_sort, rating_to_stars, title_sort
from calibre.utils.config_base import tweaks
from calibre.utils.date import UNDEFINED_DATE, clean_date_for_sort, parse_date
from calibre.utils.icu import sort_key
from calibre.utils.localization import calibre_langcode_to_name
from polyglot.builtins import iteritems
rendering_composite_name = '__rendering_composite__'
def bool_sort_key(bools_are_tristate):
return (lambda x:{True: 1, False: 2, None: 3}.get(x, 3)) if bools_are_tristate else lambda x:{True: 1, False: 2, None: 2}.get(x, 2)
def sort_value_for_undefined_numbers():
t = tweaks['value_for_undefined_numbers_when_sorting']
try:
if t == 'minimum':
return float('-inf')
if t == 'maximum':
return float('inf')
return float(t)
except Exception:
print('***** Bad value in undefined sort number tweak', t, file=sys.stderr)
return 0
def numeric_sort_key(defval, x):
# It isn't clear whether this function can ever be called with a non-numeric
# argument, but we check just in case
return x if type(x) in (int, float) else defval
def IDENTITY(x):
return x
class InvalidLinkTable(Exception):
def __init__(self, name):
Exception.__init__(self, name)
self.field_name = name
class Field:
is_many = False
is_many_many = False
is_composite = False
def __init__(self, name, table, bools_are_tristate, get_template_functions):
self.name, self.table = name, table
dt = self.metadata['datatype']
self.has_text_data = dt in {'text', 'comments', 'series', 'enumeration'}
self.table_type = self.table.table_type
self._sort_key = (sort_key if dt in ('text', 'series', 'enumeration') else IDENTITY)
# This will be compared to the output of sort_key() which is a
# bytestring, therefore it is safer to have it be a bytestring.
# Coercing an empty bytestring to unicode will never fail, but the
# output of sort_key cannot be coerced to unicode
self._default_sort_key = b''
if dt in {'int', 'float', 'rating'}:
self._default_sort_key = sort_value_for_undefined_numbers()
self._sort_key = partial(numeric_sort_key, self._default_sort_key)
elif dt == 'bool':
self._default_sort_key = None
self._sort_key = bool_sort_key(bools_are_tristate)
elif dt == 'datetime':
self._default_sort_key = UNDEFINED_DATE
if tweaks['sort_dates_using_visible_fields']:
fmt = None
if name in {'timestamp', 'pubdate', 'last_modified'}:
fmt = tweaks['gui_%s_display_format' % name]
elif self.metadata['is_custom']:
fmt = self.metadata.get('display', {}).get('date_format', None)
self._sort_key = partial(clean_date_for_sort, fmt=fmt)
elif dt == 'comments' or name == 'identifiers':
self._default_sort_key = ''
if self.name == 'languages':
self._sort_key = lambda x:sort_key(calibre_langcode_to_name(x))
self.is_multiple = (bool(self.metadata['is_multiple']) or self.name ==
'formats')
self.sort_sort_key = True
if self.is_multiple and '&' in self.metadata['is_multiple']['list_to_ui']:
self._sort_key = lambda x: sort_key(author_to_author_sort(x))
self.sort_sort_key = False
self.default_value = {} if name == 'identifiers' else () if self.is_multiple else None
self.category_formatter = str
if dt == 'rating':
if self.metadata['display'].get('allow_half_stars', False):
self.category_formatter = lambda x: rating_to_stars(x, True)
else:
self.category_formatter = rating_to_stars
elif name == 'languages':
self.category_formatter = calibre_langcode_to_name
self.writer = Writer(self)
self.series_field = None
self.get_template_functions = get_template_functions
@property
def metadata(self):
return self.table.metadata
def for_book(self, book_id, default_value=None):
'''
Return the value of this field for the book identified by book_id.
When no value is found, returns ``default_value``.
'''
raise NotImplementedError()
def ids_for_book(self, book_id):
'''
Return a tuple of items ids for items associated with the book
identified by book_ids. Returns an empty tuple if no such items are
found.
'''
raise NotImplementedError()
def books_for(self, item_id):
'''
Return the ids of all books associated with the item identified by
item_id as a set. An empty set is returned if no books are found.
'''
raise NotImplementedError()
def __iter__(self):
'''
Iterate over the ids for all values in this field.
WARNING: Some fields such as composite fields and virtual
fields like ondevice do not have ids for their values, in such
cases this is an empty iterator.
'''
return iter(())
def sort_keys_for_books(self, get_metadata, lang_map):
'''
Return a function that maps book_id to sort_key. The sort key is suitable for
use in sorting the list of all books by this field, via the python cmp
method.
'''
raise NotImplementedError()
def iter_searchable_values(self, get_metadata, candidates, default_value=None):
'''
Return a generator that yields items of the form (value, set of books
ids that have this value). Here, value is a searchable value. Returned
books_ids are restricted to the set of ids in candidates.
'''
raise NotImplementedError()
def get_categories(self, tag_class, book_rating_map, lang_map, book_ids=None):
ans = []
if not self.is_many:
return ans
id_map = self.table.id_map
special_sort = hasattr(self, 'category_sort_value')
for item_id, item_book_ids in iteritems(self.table.col_book_map):
if book_ids is not None:
item_book_ids = item_book_ids.intersection(book_ids)
if item_book_ids:
ratings = tuple(r for r in (book_rating_map.get(book_id, 0) for
book_id in item_book_ids) if r > 0)
avg = sum(ratings)/len(ratings) if ratings else 0
try:
name = self.category_formatter(id_map[item_id])
except KeyError:
# db has entries in the link table without entries in the
# id table, for example, see
# https://bugs.launchpad.net/bugs/1218783
raise InvalidLinkTable(self.name)
sval = (self.category_sort_value(item_id, item_book_ids, lang_map)
if special_sort else name)
c = tag_class(name, id=item_id, sort=sval, avg=avg,
id_set=item_book_ids, count=len(item_book_ids))
ans.append(c)
return ans
class OneToOneField(Field):
def for_book(self, book_id, default_value=None):
return self.table.book_col_map.get(book_id, default_value)
def ids_for_book(self, book_id):
return (book_id,)
def books_for(self, item_id):
return {item_id}
def __iter__(self):
return iter(self.table.book_col_map)
def sort_keys_for_books(self, get_metadata, lang_map):
bcmg = self.table.book_col_map.get
dk = self._default_sort_key
sk = self._sort_key
if sk is IDENTITY:
if dk is not None:
def none_safe_key(book_id):
ans = bcmg(book_id, dk)
if ans is None:
ans = dk
return ans
return none_safe_key
return lambda book_id:bcmg(book_id, dk)
return lambda book_id:sk(bcmg(book_id, dk))
def iter_searchable_values(self, get_metadata, candidates, default_value=None):
cbm = self.table.book_col_map
for book_id in candidates:
yield cbm.get(book_id, default_value), {book_id}
class CompositeField(OneToOneField):
is_composite = True
SIZE_SUFFIX_MAP = {suffix:i for i, suffix in enumerate(('', 'K', 'M', 'G', 'T', 'P', 'E'))}
def __init__(self, name, table, bools_are_tristate, get_template_functions):
OneToOneField.__init__(self, name, table, bools_are_tristate, get_template_functions)
self._render_cache = {}
self._lock = Lock()
m = self.metadata
self._composite_name = '#' + m['label']
try:
self.splitter = m['is_multiple'].get('cache_to_list', None)
except AttributeError:
self.splitter = None
composite_sort = m.get('display', {}).get('composite_sort', None)
if composite_sort == 'number':
self._default_sort_key = 0
self._undefined_number_sort_key = sort_value_for_undefined_numbers()
self._sort_key = self.number_sort_key
elif composite_sort == 'date':
self._default_sort_key = UNDEFINED_DATE
self._filter_date = lambda x: x
if tweaks['sort_dates_using_visible_fields']:
fmt = m.get('display', {}).get('date_format', None)
self._filter_date = partial(clean_date_for_sort, fmt=fmt)
self._sort_key = self.date_sort_key
elif composite_sort == 'bool':
self._default_sort_key = None
self._bool_sort_key = bool_sort_key(bools_are_tristate)
self._sort_key = self.bool_sort_key
elif self.splitter is not None:
self._default_sort_key = ()
self._sort_key = self.multiple_sort_key
else:
self._sort_key = sort_key
def multiple_sort_key(self, val):
val = (sort_key(x.strip()) for x in (val or '').split(self.splitter))
return tuple(sorted(val))
def number_sort_key(self, val):
try:
p = 1
if val and val.endswith('B'):
p = 1 << (10 * self.SIZE_SUFFIX_MAP.get(val[-2:-1], 0))
val = val[:(-2 if p > 1 else -1)].strip()
val = atof(val) * p
except (TypeError, AttributeError, ValueError, KeyError):
val = self._undefined_number_sort_key
return val
def date_sort_key(self, val):
try:
val = self._filter_date(parse_date(val))
except (TypeError, ValueError, AttributeError, KeyError):
val = UNDEFINED_DATE
return val
def bool_sort_key(self, val):
return self._bool_sort_key(force_to_bool(val))
def __render_composite(self, book_id, mi, formatter, template_cache):
' INTERNAL USE ONLY. DO NOT USE THIS OUTSIDE THIS CLASS! '
ans = formatter.safe_format(
self.metadata['display']['composite_template'], mi, _('TEMPLATE ERROR'),
mi, column_name=self._composite_name, template_cache=template_cache,
template_functions=self.get_template_functions(),
global_vars={rendering_composite_name:'1'}).strip()
with self._lock:
self._render_cache[book_id] = ans
return ans
def _render_composite_with_cache(self, book_id, mi, formatter, template_cache):
''' INTERNAL USE ONLY. DO NOT USE METHOD DIRECTLY. INSTEAD USE
db.composite_for() OR mi.get(). Those methods make sure there is no
risk of infinite recursion when evaluating templates that refer to
themselves. '''
with self._lock:
ans = self._render_cache.get(book_id, None)
if ans is None:
return self.__render_composite(book_id, mi, formatter, template_cache)
return ans
def clear_caches(self, book_ids=None):
with self._lock:
if book_ids is None:
self._render_cache.clear()
else:
for book_id in book_ids:
self._render_cache.pop(book_id, None)
def get_value_with_cache(self, book_id, get_metadata):
with self._lock:
ans = self._render_cache.get(book_id, None)
if ans is None:
mi = get_metadata(book_id)
return self.__render_composite(book_id, mi, mi.formatter, mi.template_cache)
return ans
def sort_keys_for_books(self, get_metadata, lang_map):
gv = self.get_value_with_cache
sk = self._sort_key
if sk is IDENTITY:
return lambda book_id:gv(book_id, get_metadata)
return lambda book_id:sk(gv(book_id, get_metadata))
def iter_searchable_values(self, get_metadata, candidates, default_value=None):
val_map = defaultdict(set)
splitter = self.splitter
for book_id in candidates:
vals = self.get_value_with_cache(book_id, get_metadata)
vals = (vv.strip() for vv in vals.split(splitter)) if splitter else (vals,)
found = False
for v in vals:
if v:
val_map[v].add(book_id)
found = True
if not found:
# Convert columns with no value to None to ensure #x:false
# searches work. We do it outside the loop to avoid generating
# None for is_multiple columns containing text like "a,,,b".
val_map[None].add(book_id)
yield from iteritems(val_map)
def iter_counts(self, candidates, get_metadata=None):
val_map = defaultdict(set)
splitter = self.splitter
for book_id in candidates:
vals = self.get_value_with_cache(book_id, get_metadata)
if splitter:
length = len(list(vv.strip() for vv in vals.split(splitter) if vv.strip()))
elif vals.strip():
length = 1
else:
length = 0
val_map[length].add(book_id)
yield from iteritems(val_map)
def get_composite_categories(self, tag_class, book_rating_map, book_ids,
is_multiple, get_metadata):
ans = []
id_map = defaultdict(set)
for book_id in book_ids:
val = self.get_value_with_cache(book_id, get_metadata)
vals = [x.strip() for x in val.split(is_multiple)] if is_multiple else [val]
for val in vals:
if val:
id_map[val].add(book_id)
for item_id, item_book_ids in iteritems(id_map):
ratings = tuple(r for r in (book_rating_map.get(book_id, 0) for
book_id in item_book_ids) if r > 0)
avg = sum(ratings)/len(ratings) if ratings else 0
c = tag_class(item_id, id=item_id, sort=item_id, avg=avg,
id_set=item_book_ids, count=len(item_book_ids))
ans.append(c)
return ans
def get_books_for_val(self, value, get_metadata, book_ids):
is_multiple = self.table.metadata['is_multiple'].get('cache_to_list', None)
ans = set()
for book_id in book_ids:
val = self.get_value_with_cache(book_id, get_metadata)
vals = {x.strip() for x in val.split(is_multiple)} if is_multiple else [val]
if value in vals:
ans.add(book_id)
return ans
class OnDeviceField(OneToOneField):
def __init__(self, name, table, bools_are_tristate, get_template_functions):
self.name = name
self.book_on_device_func = None
self.is_multiple = False
self.cache = {}
self._lock = Lock()
self._metadata = {
'table':None, 'column':None, 'datatype':'text', 'is_multiple':{},
'kind':'field', 'name':_('On Device'), 'search_terms':['ondevice'],
'is_custom':False, 'is_category':False, 'is_csp': False, 'display':{}}
@property
def metadata(self):
return self._metadata
def clear_caches(self, book_ids=None):
with self._lock:
if book_ids is None:
self.cache.clear()
else:
for book_id in book_ids:
self.cache.pop(book_id, None)
def book_on_device(self, book_id):
with self._lock:
ans = self.cache.get(book_id, null)
if ans is null and callable(self.book_on_device_func):
ans = self.book_on_device_func(book_id)
with self._lock:
self.cache[book_id] = ans
return None if ans is null else ans
def set_book_on_device_func(self, func):
self.book_on_device_func = func
def for_book(self, book_id, default_value=None):
loc = []
count = 0
on = self.book_on_device(book_id)
if on is not None:
m, a, b, count = on[:4]
if m is not None:
loc.append(_('Main'))
if a is not None:
loc.append(_('Card A'))
if b is not None:
loc.append(_('Card B'))
return ', '.join(loc) + ((' (%s books)'%count) if count > 1 else '')
def __iter__(self):
return iter(())
def sort_keys_for_books(self, get_metadata, lang_map):
return self.for_book
def iter_searchable_values(self, get_metadata, candidates, default_value=None):
val_map = defaultdict(set)
for book_id in candidates:
val_map[self.for_book(book_id, default_value=default_value)].add(book_id)
yield from iteritems(val_map)
class LazySortMap:
__slots__ = ('default_sort_key', 'sort_key_func', 'id_map', 'cache')
def __init__(self, default_sort_key, sort_key_func, id_map):
self.default_sort_key = default_sort_key
self.sort_key_func = sort_key_func
self.id_map = id_map
self.cache = {None:default_sort_key}
def __call__(self, item_id):
try:
return self.cache[item_id]
except KeyError:
try:
val = self.cache[item_id] = self.sort_key_func(self.id_map[item_id])
except KeyError:
val = self.cache[item_id] = self.default_sort_key
return val
class ManyToOneField(Field):
is_many = True
def for_book(self, book_id, default_value=None):
ids = self.table.book_col_map.get(book_id, None)
if ids is not None:
ans = self.table.id_map[ids]
else:
ans = default_value
return ans
def ids_for_book(self, book_id):
id_ = self.table.book_col_map.get(book_id, None)
if id_ is None:
return ()
return (id_,)
def books_for(self, item_id):
return self.table.col_book_map.get(item_id, set())
def __iter__(self):
return iter(self.table.id_map)
def sort_keys_for_books(self, get_metadata, lang_map):
sk_map = LazySortMap(self._default_sort_key, self._sort_key, self.table.id_map)
bcmg = self.table.book_col_map.get
return lambda book_id:sk_map(bcmg(book_id, None))
def iter_searchable_values(self, get_metadata, candidates, default_value=None):
cbm = self.table.col_book_map
empty = set()
for item_id, val in iteritems(self.table.id_map):
book_ids = cbm.get(item_id, empty).intersection(candidates)
if book_ids:
yield val, book_ids
@property
def book_value_map(self):
try:
return {book_id:self.table.id_map[item_id] for book_id, item_id in
iteritems(self.table.book_col_map)}
except KeyError:
raise InvalidLinkTable(self.name)
def item_ids_for_names(self, db, item_names: Iterable[str], case_sensitive: bool = False) -> dict[str, int]:
return self.table.item_ids_for_names(db, item_names, case_sensitive)
class ManyToManyField(Field):
is_many = True
is_many_many = True
def __init__(self, *args, **kwargs):
Field.__init__(self, *args, **kwargs)
def item_ids_for_names(self, db, item_names: Iterable[str], case_sensitive: bool = False) -> dict[str, int]:
return self.table.item_ids_for_names(db, item_names, case_sensitive)
def for_book(self, book_id, default_value=None):
ids = self.table.book_col_map.get(book_id, ())
if ids:
ans = (self.table.id_map[i] for i in ids)
if self.table.sort_alpha:
ans = tuple(sorted(ans, key=sort_key))
else:
ans = tuple(ans)
else:
ans = default_value
return ans
def ids_for_book(self, book_id):
return self.table.book_col_map.get(book_id, ())
def books_for(self, item_id):
return self.table.col_book_map.get(item_id, set())
def __iter__(self):
return iter(self.table.id_map)
def sort_keys_for_books(self, get_metadata, lang_map):
sk_map = LazySortMap(self._default_sort_key, self._sort_key, self.table.id_map)
bcmg = self.table.book_col_map.get
dsk = (self._default_sort_key,)
if self.sort_sort_key:
def sk(book_id):
return tuple(sorted(sk_map(x) for x in bcmg(book_id, ()))) or dsk
else:
def sk(book_id):
return tuple(sk_map(x) for x in bcmg(book_id, ())) or dsk
return sk
def iter_searchable_values(self, get_metadata, candidates, default_value=None):
cbm = self.table.col_book_map
empty = set()
for item_id, val in iteritems(self.table.id_map):
book_ids = cbm.get(item_id, empty).intersection(candidates)
if book_ids:
yield val, book_ids
def iter_counts(self, candidates, get_metadata=None):
val_map = defaultdict(set)
cbm = self.table.book_col_map
for book_id in candidates:
val_map[len(cbm.get(book_id, ()))].add(book_id)
yield from iteritems(val_map)
@property
def book_value_map(self):
try:
return {book_id:tuple(self.table.id_map[item_id] for item_id in item_ids)
for book_id, item_ids in iteritems(self.table.book_col_map)}
except KeyError:
raise InvalidLinkTable(self.name)
class IdentifiersField(ManyToManyField):
def for_book(self, book_id, default_value=None):
ids = self.table.book_col_map.get(book_id, None)
if ids:
ids = ids.copy()
else:
try:
ids = default_value.copy() # in case default_value is a mutable dict
except AttributeError:
ids = default_value
return ids
def sort_keys_for_books(self, get_metadata, lang_map):
'Sort by identifier keys'
bcmg = self.table.book_col_map.get
dv = {self._default_sort_key:None}
return lambda book_id: tuple(sorted(bcmg(book_id, dv)))
def iter_searchable_values(self, get_metadata, candidates, default_value=()):
bcm = self.table.book_col_map
for book_id in candidates:
val = bcm.get(book_id, default_value)
if val:
yield val, {book_id}
def get_categories(self, tag_class, book_rating_map, lang_map, book_ids=None):
ans = []
for id_key, item_book_ids in iteritems(self.table.col_book_map):
if book_ids is not None:
item_book_ids = item_book_ids.intersection(book_ids)
if item_book_ids:
c = tag_class(id_key, id_set=item_book_ids, count=len(item_book_ids))
ans.append(c)
return ans
class AuthorsField(ManyToManyField):
def author_data(self, author_id):
return {
'name': self.table.id_map[author_id],
'sort': self.table.asort_map[author_id],
'link': self.table.link_map[author_id],
}
def category_sort_value(self, item_id, book_ids, lang_map):
return self.table.asort_map[item_id]
def db_author_sort_for_book(self, book_id):
return self.author_sort_field.for_book(book_id)
def author_sort_for_book(self, book_id):
return ' & '.join(self.table.asort_map[k] for k in
self.table.book_col_map[book_id])
class FormatsField(ManyToManyField):
def for_book(self, book_id, default_value=None):
return self.table.book_col_map.get(book_id, default_value)
def format_fname(self, book_id, fmt):
return self.table.fname_map[book_id][fmt.upper()]
def format_size(self, book_id, fmt):
return self.table.size_map.get(book_id, {}).get(fmt.upper(), None)
def iter_searchable_values(self, get_metadata, candidates, default_value=None):
val_map = defaultdict(set)
cbm = self.table.book_col_map
for book_id in candidates:
vals = cbm.get(book_id, ())
for val in vals:
val_map[val].add(book_id)
for val, book_ids in iteritems(val_map):
yield val, book_ids
def get_categories(self, tag_class, book_rating_map, lang_map, book_ids=None):
ans = []
for fmt, item_book_ids in iteritems(self.table.col_book_map):
if book_ids is not None:
item_book_ids = item_book_ids.intersection(book_ids)
if item_book_ids:
c = tag_class(fmt, id_set=item_book_ids, count=len(item_book_ids))
ans.append(c)
return ans
class LazySeriesSortMap:
__slots__ = ('default_sort_key', 'sort_key_func', 'id_map', 'cache')
def __init__(self, default_sort_key, sort_key_func, id_map):
self.default_sort_key = default_sort_key
self.sort_key_func = sort_key_func
self.id_map = id_map
self.cache = {}
def __call__(self, item_id, lang):
try:
return self.cache[(item_id, lang)]
except KeyError:
try:
val = self.cache[(item_id, lang)] = self.sort_key_func(self.id_map[item_id], lang)
except KeyError:
val = self.cache[(item_id, lang)] = self.default_sort_key
return val
class SeriesField(ManyToOneField):
def sort_keys_for_books(self, get_metadata, lang_map):
sso = tweaks['title_series_sorting']
ssk = self._sort_key
ts = title_sort
def sk(val, lang):
return ssk(ts(val, order=sso, lang=lang))
sk_map = LazySeriesSortMap(self._default_sort_key, sk, self.table.id_map)
bcmg = self.table.book_col_map.get
lang_map = {k:v[0] if v else None for k, v in iteritems(lang_map)}
def key(book_id):
lang = lang_map.get(book_id, None)
return sk_map(bcmg(book_id, None), lang)
return key
def category_sort_value(self, item_id, book_ids, lang_map):
lang = None
tss = tweaks['title_series_sorting']
if tss != 'strictly_alphabetic':
c = Counter()
for book_id in book_ids:
l = lang_map.get(book_id, None)
if l:
c[l[0]] += 1
if c:
lang = c.most_common(1)[0][0]
val = self.table.id_map[item_id]
return title_sort(val, order=tss, lang=lang)
def iter_searchable_values_for_sort(self, candidates, lang_map, default_value=None):
cbm = self.table.col_book_map
sso = tweaks['title_series_sorting']
ts = title_sort
empty = set()
lang_map = {k:v[0] if v else None for k, v in iteritems(lang_map)}
for item_id, val in iteritems(self.table.id_map):
book_ids = cbm.get(item_id, empty).intersection(candidates)
if book_ids:
lang_counts = Counter()
for book_id in book_ids:
lang = lang_map.get(book_id)
if lang:
lang_counts[lang[0]] += 1
lang = lang_counts.most_common(1)[0][0] if lang_counts else None
yield ts(val, order=sso, lang=lang), book_ids
class TagsField(ManyToManyField):
def get_news_category(self, tag_class, book_ids=None):
news_id = None
ans = []
for item_id, val in iteritems(self.table.id_map):
if val == _('News'):
news_id = item_id
break
if news_id is None:
return ans
news_books = self.table.col_book_map[news_id]
if book_ids is not None:
news_books = news_books.intersection(book_ids)
if not news_books:
return ans
for item_id, item_book_ids in iteritems(self.table.col_book_map):
item_book_ids = item_book_ids.intersection(news_books)
if item_book_ids:
name = self.category_formatter(self.table.id_map[item_id])
if name == _('News'):
continue
c = tag_class(name, id=item_id, sort=name,
id_set=item_book_ids, count=len(item_book_ids))
ans.append(c)
return ans
def create_field(name, table, bools_are_tristate, get_template_functions):
cls = {
ONE_ONE: OneToOneField,
MANY_ONE: ManyToOneField,
MANY_MANY: ManyToManyField,
}[table.table_type]
if name == 'authors':
cls = AuthorsField
elif name == 'ondevice':
cls = OnDeviceField
elif name == 'formats':
cls = FormatsField
elif name == 'identifiers':
cls = IdentifiersField
elif name == 'tags':
cls = TagsField
elif table.metadata['datatype'] == 'composite':
cls = CompositeField
elif table.metadata['datatype'] == 'series':
cls = SeriesField
return cls(name, table, bools_are_tristate, get_template_functions)
| 30,540 | Python | .py | 680 | 34.4 | 135 | 0.588196 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,076 | categories.py | kovidgoyal_calibre/src/calibre/db/categories.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import copy
from collections import OrderedDict
from functools import partial
from calibre.ebooks.metadata import author_to_author_sort
from calibre.utils.config_base import prefs, tweaks
from calibre.utils.icu import collation_order, sort_key
from calibre.utils.icu import lower as icu_lower
from calibre.utils.icu import upper as icu_upper
from polyglot.builtins import iteritems, native_string_type
CATEGORY_SORTS = ('name', 'popularity', 'rating') # This has to be a tuple not a set
class Tag:
__slots__ = ('name', 'original_name', 'id', 'count', 'state', 'is_hierarchical',
'is_editable', 'is_searchable', 'id_set', 'avg_rating', 'sort',
'use_sort_as_name', 'category', 'search_expression', 'original_categories')
def __init__(self, name, id=None, count=0, state=0, avg=0, sort=None,
category=None, id_set=None, search_expression=None,
is_editable=True, is_searchable=True, use_sort_as_name=False,
original_categories=None):
self.name = self.original_name = name
self.id = id
self.count = count
self.state = state
self.is_hierarchical = ''
self.is_editable = is_editable
self.is_searchable = is_searchable
self.id_set = id_set if id_set is not None else set()
self.avg_rating = avg/2.0 if avg is not None else 0
self.sort = sort
self.use_sort_as_name = use_sort_as_name
self.category = category
self.search_expression = search_expression
self.original_categories = None
@property
def string_representation(self):
return '%s:%s:%s:%s:%s:%s'%(self.name, self.count, self.id, self.state,
self.category, self.original_categories)
def __str__(self):
return self.string_representation
def __repr__(self):
return native_string_type(self)
__calibre_serializable__ = True
def as_dict(self):
return {k: getattr(self, k) for k in self.__slots__}
@classmethod
def from_dict(cls, d):
ans = cls('')
for k in cls.__slots__:
setattr(ans, k, d[k])
return ans
def find_categories(field_metadata):
for category, cat in field_metadata.iter_items():
if (cat['is_category'] and cat['kind'] not in {'user', 'search'}):
yield (category, cat['is_multiple'].get('cache_to_list', None), False)
elif (cat['datatype'] == 'composite' and
cat['display'].get('make_category', False)):
yield (category, cat['is_multiple'].get('cache_to_list', None), True)
def create_tag_class(category, fm):
cat = fm[category]
dt = cat['datatype']
is_editable = category not in {'news', 'rating', 'languages', 'formats',
'identifiers'} and dt != 'composite'
if (tweaks['categories_use_field_for_author_name'] == 'author_sort' and
(category == 'authors' or
(cat['display'].get('is_names', False) and
cat['is_custom'] and cat['is_multiple'] and
dt == 'text'))):
use_sort_as_name = True
else:
use_sort_as_name = False
return partial(Tag, use_sort_as_name=use_sort_as_name,
is_editable=is_editable, category=category)
def clean_user_categories(dbcache):
user_cats = dbcache.pref('user_categories', {})
new_cats = {}
for k in user_cats:
comps = [c.strip() for c in k.split('.') if c.strip()]
if len(comps) == 0:
i = 1
while True:
if str(i) not in user_cats:
new_cats[str(i)] = user_cats[k]
break
i += 1
else:
new_cats['.'.join(comps)] = user_cats[k]
try:
if new_cats != user_cats:
dbcache.set_pref('user_categories', new_cats)
except:
pass
return new_cats
def is_standard_category(key):
return not (key.startswith('@') or key == 'search')
def category_display_order(ordered_cats, all_cats):
# ordered_cats is the desired order. all_cats is the list of keys returned
# by get_categories, which is in the default order
cat_ord = []
all_cat_set = frozenset(all_cats)
# Do the standard categories first
# Verify all the columns in ordered_cats are actually in all_cats
for key in ordered_cats:
if is_standard_category(key) and key in all_cat_set:
cat_ord.append(key)
# Add any new standard cats at the end of the list
for key in all_cats:
if key not in cat_ord and is_standard_category(key):
cat_ord.append(key)
# Now add the non-standard cats (user cats and search)
for key in all_cats:
if not is_standard_category(key):
cat_ord.append(key)
return cat_ord
numeric_collation = prefs['numeric_collation']
def sort_key_for_popularity(x, hierarchical_categories=None):
return (-getattr(x, 'count', 0), sort_key(x.sort or x.name))
def sort_key_for_rating(x, hierarchical_categories=None):
return (-getattr(x, 'avg_rating', 0.0), sort_key(x.sort or x.name))
# When sorting by name, treat the period in hierarchical categories as a tab so
# that the value sorts above similarly-named items. Example: "foo.bar" should
# sort above "foo a.bar". Without this substitution "foo.bar" sorts below "foo
# a.bar" because '.' sorts higher than space.
def sort_key_for_name_and_first_letter(x, hierarchical_categories=()):
v1 = icu_upper(x.sort or x.name)
if x.category in hierarchical_categories:
v1 = v1.replace('.', '\t')
v2 = v1 or ' '
# The idea is that '9999999999' is larger than any digit so all digits
# will sort in front. Non-digits will sort according to their ICU first letter
c = v2[0]
return (c if numeric_collation and c.isdigit() else '9999999999',
collation_order(v2), sort_key(v1))
def sort_key_for_name(x, hierarchical_categories=()):
v = x.sort or x.name
if x.category not in hierarchical_categories:
return sort_key(v)
return sort_key(v.replace('.', '\t'))
category_sort_keys = {True:{}, False: {}}
category_sort_keys[True]['popularity'] = category_sort_keys[False]['popularity'] = sort_key_for_popularity
category_sort_keys[True]['rating'] = category_sort_keys[False]['rating'] = sort_key_for_rating
category_sort_keys[True]['name'] = sort_key_for_name_and_first_letter
category_sort_keys[False]['name'] = sort_key_for_name
# Various parts of calibre depend on the order of fields in the returned
# dict being in the default display order: standard fields, custom in alpha order,
# user categories, then saved searches. This works because the backend adds
# custom columns to field metadata in the right order.
def get_categories(dbcache, sort='name', book_ids=None, first_letter_sort=False):
if sort not in CATEGORY_SORTS:
raise ValueError('sort ' + sort + ' not a valid value')
hierarchical_categories = frozenset(dbcache.pref('categories_using_hierarchy', ()))
fm = dbcache.field_metadata
book_rating_map = dbcache.fields['rating'].book_value_map
lang_map = dbcache.fields['languages'].book_value_map
categories = OrderedDict()
book_ids = frozenset(book_ids) if book_ids else book_ids
pm_cache = {}
def get_metadata(book_id):
ans = pm_cache.get(book_id)
if ans is None:
ans = pm_cache[book_id] = dbcache._get_proxy_metadata(book_id)
return ans
bids = None
first_letter_sort = bool(first_letter_sort)
for category, is_multiple, is_composite in find_categories(fm):
tag_class = create_tag_class(category, fm)
sort_on, reverse = sort, False
if is_composite:
if bids is None:
bids = dbcache._all_book_ids() if book_ids is None else book_ids
cats = dbcache.fields[category].get_composite_categories(
tag_class, book_rating_map, bids, is_multiple, get_metadata)
elif category == 'news':
cats = dbcache.fields['tags'].get_news_category(tag_class, book_ids)
else:
cat = fm[category]
brm = book_rating_map
dt = cat['datatype']
if dt == 'rating':
if category != 'rating':
brm = dbcache.fields[category].book_value_map
if sort_on == 'name':
sort_on, reverse = 'rating', True
cats = dbcache.fields[category].get_categories(
tag_class, brm, lang_map, book_ids)
if (category != 'authors' and dt == 'text' and
cat['is_multiple'] and cat['display'].get('is_names', False)):
for item in cats:
item.sort = author_to_author_sort(item.sort)
cats.sort(key=partial(category_sort_keys[first_letter_sort][sort_on],
hierarchical_categories=hierarchical_categories),
reverse=reverse)
categories[category] = cats
# Needed for legacy databases that have multiple ratings that
# map to n stars
for r in categories['rating']:
for x in tuple(categories['rating']):
if r.name == x.name and r.id != x.id:
r.id_set |= x.id_set
r.count = len(r.id_set)
categories['rating'].remove(x)
break
# User categories
user_categories = clean_user_categories(dbcache).copy()
# First add any grouped search terms to the user categories
muc = dbcache.pref('grouped_search_make_user_categories', [])
gst = dbcache.pref('grouped_search_terms', {})
for c in gst:
if c not in muc:
continue
uc = []
for sc in gst[c]:
for t in categories.get(sc, ()):
uc.append([t.name, sc, 0])
user_categories[c] = uc
if user_categories:
# We want to use same node in the user category as in the source
# category. To do that, we need to find the original Tag node. There is
# a time/space tradeoff here. By converting the tags into a map, we can
# do the verification in the category loop much faster, at the cost of
# temporarily duplicating the categories lists.
taglist = {}
for c, items in iteritems(categories):
taglist[c] = dict(map(lambda t:(icu_lower(t.name), t), items))
# Add the category values to the user categories
for user_cat in sorted(user_categories, key=sort_key):
items = []
names_seen = {}
user_cat_is_gst = user_cat in gst
for name, label, ign in user_categories[user_cat]:
n = icu_lower(name)
if label in taglist and n in taglist[label]:
if user_cat_is_gst:
# for gst items, make copy and consolidate the tags by name.
if n in names_seen:
# We must combine this node into a previous one with
# the same name ignoring case. As part of the process,
# remember the source categories and correct the
# average rating
t = names_seen[n]
other_tag = taglist[label][n]
t.id_set |= other_tag.id_set
t.count = len(t.id_set)
t.original_categories.add(other_tag.category)
total_rating = 0
count = 0
for id_ in t.id_set:
rating = book_rating_map.get(id_, 0)
if rating:
total_rating += rating/2
count += 1
if total_rating and count:
t.avg_rating = total_rating/count
else:
# Must deepcopy so we don't share the id_set between nodes
t = copy.deepcopy(taglist[label][n])
t.original_categories = {t.category}
names_seen[n] = t
items.append(t)
else:
items.append(taglist[label][n])
# else: do nothing, to not include nodes w zero counts
cat_name = '@' + user_cat # add the '@' to avoid name collision
items.sort(key=partial(category_sort_keys[False][sort],
hierarchical_categories=hierarchical_categories))
categories[cat_name] = items
# ### Finally, the saved searches category ####
items = []
queries = dbcache._search_api.saved_searches.queries
for srch in sorted(queries, key=sort_key):
items.append(Tag(srch, sort=srch, search_expression=queries[srch],
category='search', is_editable=False))
if len(items):
categories['search'] = items
return categories
| 13,365 | Python | .py | 277 | 37.267148 | 106 | 0.591376 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,077 | exim.py | kovidgoyal_calibre/src/calibre/db/notes/exim.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2023, Kovid Goyal <kovid at kovidgoyal.net>
import base64
import os
from urllib.parse import unquote, urlparse
from html5_parser import parse
from lxml import html
from calibre import guess_extension, guess_type
from calibre.db.constants import RESOURCE_URL_SCHEME
from calibre.ebooks.chardet import xml_to_unicode
from calibre.ebooks.oeb.transforms.rasterize import data_url
from calibre.utils.cleantext import clean_xml_chars
from calibre.utils.filenames import get_long_path_name, make_long_path_useable
from calibre.utils.html2text import html2text
def parse_html(raw):
try:
return parse(raw, maybe_xhtml=False, sanitize_names=True)
except Exception:
return parse(clean_xml_chars(raw), maybe_xhtml=False, sanitize_names=True)
def export_note(note_doc: str, get_resource) -> str:
root = parse_html(note_doc)
return html.tostring(expand_note_resources(root, get_resource), encoding='unicode')
def expand_note_resources(root, get_resource):
for img in root.xpath('//img[@src]'):
img.attrib.pop('data-pre-import-src', None)
try:
purl = urlparse(img.get('src'))
except Exception:
continue
if purl.scheme == RESOURCE_URL_SCHEME:
rhash = f'{purl.hostname}:{purl.path[1:]}'
x = get_resource(rhash)
if x:
img.set('src', data_url(guess_type(x['name'])[0], x['data']))
img.set('data-filename', x['name'])
return root
def import_note(shtml: str | bytes, basedir: str, add_resource) -> tuple[str, str, set[str]]:
shtml = xml_to_unicode(shtml, strip_encoding_pats=True, assume_utf8=True)[0]
basedir = os.path.normcase(get_long_path_name(os.path.abspath(basedir)) + os.sep)
root = parse_html(shtml)
resources = set()
def ar(img, path_or_data, name):
rhash = add_resource(path_or_data, name)
scheme, digest = rhash.split(':', 1)
img.set('src', f'{RESOURCE_URL_SCHEME}://{scheme}/{digest}')
resources.add(rhash)
for img in root.xpath('//img[@src]'):
src = img.attrib.pop('src')
img.set('data-pre-import-src', src)
if src.startswith('data:'):
d = src.split(':', 1)[-1]
menc, payload = d.partition(',')[::2]
mt, enc = menc.partition(';')[::2]
if enc != 'base64':
continue
try:
d = base64.standard_b64decode(payload)
except Exception:
continue
ar(img, d, img.get('data-filename') or ('image' + guess_extension(mt, strict=False)))
continue
try:
purl = urlparse(src)
except Exception:
continue
if purl.scheme in ('', 'file'):
path = unquote(purl.path)
if not os.path.isabs(path):
if not basedir:
continue
path = os.path.join(basedir, path)
q = os.path.normcase(get_long_path_name(os.path.abspath(path)))
if q.startswith(basedir) and os.path.exists(make_long_path_useable(path)):
ar(img, make_long_path_useable(path), os.path.basename(path))
shtml = html.tostring(root, encoding='unicode')
for img in root.xpath('//img[@src]'):
del img.attrib['src']
return shtml, html2text(shtml, default_image_alt=' '), resources
| 3,431 | Python | .py | 78 | 35.487179 | 97 | 0.623952 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,078 | connect.py | kovidgoyal_calibre/src/calibre/db/notes/connect.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2023, Kovid Goyal <kovid at kovidgoyal.net>
import json
import os
import shutil
import time
from collections import defaultdict
from contextlib import suppress
from itertools import count, repeat
from typing import Optional
import apsw
import xxhash
from calibre import sanitize_file_name
from calibre.constants import iswindows
from calibre.db import FTSQueryError
from calibre.db.annotations import unicode_normalize
from calibre.utils.copy_files import WINDOWS_SLEEP_FOR_RETRY_TIME
from calibre.utils.filenames import copyfile_using_links, make_long_path_useable
from calibre.utils.icu import lower as icu_lower
from .schema_upgrade import SchemaUpgrade
from ..constants import NOTES_DB_NAME, NOTES_DIR_NAME
if iswindows:
from calibre_extensions import winutil
class cmt(str):
pass
copy_marked_up_text = cmt()
SEP = b'\0\x1c\0'
DOC_NAME = 'doc.html'
METADATA_EXT = '.metadata'
def hash_data(data: bytes) -> str:
return 'xxh64:' + xxhash.xxh3_64_hexdigest(data)
def hash_key(key: str) -> str:
return xxhash.xxh3_64_hexdigest(key.encode('utf-8'))
def remove_with_retry(x, is_dir=False):
x = make_long_path_useable(x)
f = (shutil.rmtree if is_dir else os.remove)
try:
f(x)
except FileNotFoundError:
return
except OSError as e:
if iswindows and e.winerror == winutil.ERROR_SHARING_VIOLATION:
time.sleep(WINDOWS_SLEEP_FOR_RETRY_TIME)
f(x)
class Notes:
max_retired_items = 256
def __init__(self, backend):
self.temp_table_counter = count()
conn = backend.get_connection()
libdir = os.path.dirname(os.path.abspath(conn.db_filename('main')))
self.notes_dir = os.path.join(libdir, NOTES_DIR_NAME)
self.resources_dir = os.path.join(self.notes_dir, 'resources')
self.backup_dir = os.path.join(self.notes_dir, 'backup')
self.retired_dir = os.path.join(self.notes_dir, 'retired')
if not os.path.exists(self.notes_dir):
os.makedirs(self.notes_dir, exist_ok=True)
if iswindows:
winutil.set_file_attributes(self.notes_dir, winutil.FILE_ATTRIBUTE_HIDDEN | winutil.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED)
os.makedirs(self.resources_dir, exist_ok=True)
os.makedirs(self.backup_dir, exist_ok=True)
os.makedirs(self.retired_dir, exist_ok=True)
self.reopen(backend)
for cat in backend.deleted_fields:
self.delete_field(conn, cat)
def reopen(self, backend):
conn = backend.get_connection()
conn.notes_dbpath = os.path.join(self.notes_dir, NOTES_DB_NAME)
conn.execute("ATTACH DATABASE ? AS notes_db", (conn.notes_dbpath,))
self.allowed_fields = set()
triggers = []
for table in backend.tables.values():
m = table.metadata
if not table.supports_notes or m.get('datatype') == 'rating':
continue
self.allowed_fields.add(table.name)
triggers.append(
f'CREATE TEMP TRIGGER IF NOT EXISTS notes_db_{table.name.replace("#", "_")}_deleted_trigger AFTER DELETE ON main.{m["table"]} BEGIN\n'
f" DELETE FROM notes WHERE colname = '{table.name}' AND item = OLD.id;\n"
'END;'
)
self.allowed_fields = frozenset(self.allowed_fields)
SchemaUpgrade(conn, '\n'.join(triggers))
def delete_field(self, conn, field_name):
note_ids = conn.get('SELECT id from notes_db.notes WHERE colname=?', (field_name,))
if note_ids:
conn.execute(
'DELETE FROM notes_db.notes_resources_link WHERE note IN (SELECT id FROM notes_db.notes WHERE colname=?)', (field_name,)
)
conn.execute('DELETE FROM notes_db.notes WHERE colname=?', (field_name,))
self.remove_unreferenced_resources(conn)
def remove_unreferenced_resources(self, conn):
found = False
for (rhash,) in conn.get('SELECT hash FROM notes_db.resources WHERE hash NOT IN (SELECT resource FROM notes_db.notes_resources_link)'):
found = True
remove_with_retry(self.path_for_resource(rhash))
if found:
conn.execute('DELETE FROM notes_db.resources WHERE hash NOT IN (SELECT resource FROM notes_db.notes_resources_link)')
def path_for_resource(self, resource_hash: str) -> str:
hashalg, digest = resource_hash.split(':', 1)
prefix = digest[:2]
# Cant use colons in filenames on windows safely
return os.path.join(self.resources_dir, prefix, f'{hashalg}-{digest}')
def remove_resources(self, conn, note_id, resources_to_potentially_remove, delete_from_link_table=True):
if not isinstance(resources_to_potentially_remove, tuple):
resources_to_potentially_remove = tuple(resources_to_potentially_remove)
if delete_from_link_table:
conn.executemany('''
DELETE FROM notes_db.notes_resources_link WHERE note=? AND resource=?
''', tuple((note_id, x) for x in resources_to_potentially_remove))
stmt = '''
WITH resources_table(value) AS (VALUES {})
SELECT value FROM resources_table WHERE value NOT IN (SELECT resource FROM notes_db.notes_resources_link)
'''.format(','.join(repeat('(?)', len(resources_to_potentially_remove))))
for (x,) in conn.execute(stmt, resources_to_potentially_remove):
p = self.path_for_resource(x)
remove_with_retry(p)
remove_with_retry(p + METADATA_EXT)
def note_id_for(self, conn, field_name, item_id):
return conn.get('SELECT id FROM notes_db.notes WHERE item=? AND colname=?', (item_id, field_name), all=False)
def resources_used_by(self, conn, note_id):
if note_id is not None:
for (h,) in conn.execute('SELECT resource from notes_db.notes_resources_link WHERE note=?', (note_id,)):
yield h
def set_backup_for(self, field_name, item_id, item_value, marked_up_text, searchable_text, resource_hashes):
path = make_long_path_useable(os.path.join(self.backup_dir, field_name, str(item_id)))
try:
f = open(path, 'wb')
except FileNotFoundError:
os.makedirs(os.path.dirname(path), exist_ok=True)
f = open(path, 'wb')
with f:
f.write(marked_up_text.encode('utf-8'))
f.write(SEP)
f.write(searchable_text.encode('utf-8'))
f.write(SEP)
f.write('\n'.join(resource_hashes).encode('utf-8'))
f.write(SEP)
f.write(item_value.encode('utf-8'))
def path_to_retired_dir_for_item(self, field_name, item_id, item_value):
key = icu_lower(item_value or '')
return os.path.join(self.retired_dir, hash_key(f'{field_name} {key}'))
def retire_entry(self, field_name, item_id, item_value, resources, note_id):
path = make_long_path_useable(os.path.join(self.backup_dir, field_name, str(item_id)))
if os.path.exists(path):
destdir = self.path_to_retired_dir_for_item(field_name, item_id, item_value)
os.makedirs(make_long_path_useable(destdir), exist_ok=True)
dest = os.path.join(destdir, DOC_NAME)
os.replace(path, make_long_path_useable(dest))
with open(make_long_path_useable(os.path.join(destdir, 'note_id')), 'w') as nif:
nif.write(str(note_id))
for rhash, rname in resources:
rpath = make_long_path_useable(self.path_for_resource(rhash))
if os.path.exists(rpath):
rdest = os.path.join(destdir, 'res-'+rname)
with suppress(shutil.SameFileError):
copyfile_using_links(rpath, make_long_path_useable(rdest), dest_is_dir=False)
self.trim_retired_dir()
def unretire(self, conn, field_name, item_id, item_value) -> int:
srcdir = make_long_path_useable(self.path_to_retired_dir_for_item(field_name, item_id, item_value))
note_id = -1
if not os.path.exists(srcdir) or self.note_id_for(conn, field_name, item_id) is not None:
return note_id
with open(os.path.join(srcdir, DOC_NAME), 'rb') as src:
try:
a, b, _ = src.read().split(SEP, 2)
except Exception:
return note_id
marked_up_text, searchable_text = a.decode('utf-8'), b.decode('utf-8')
resources = set()
for x in os.listdir(srcdir):
if x.startswith('res-'):
rname = x.split('-', 1)[1]
with open(os.path.join(srcdir, x), 'rb') as rsrc:
resources.add(self.add_resource(conn, rsrc, rname, update_name=False))
note_id = self.set_note(conn, field_name, item_id, item_value, marked_up_text, resources, searchable_text, add_item_value_to_searchable_text=False)
if note_id > -1:
remove_with_retry(srcdir, is_dir=True)
return note_id
def remove_retired_entry(self, field_name, item_id, item_value):
srcdir = self.path_to_retired_dir_for_item(field_name, item_id, item_value)
remove_with_retry(srcdir, is_dir=True)
def set_note(
self, conn, field_name, item_id, item_value, marked_up_text='', used_resource_hashes=(),
searchable_text=copy_marked_up_text, ctime=None, mtime=None, add_item_value_to_searchable_text=True
):
if searchable_text is copy_marked_up_text:
searchable_text = marked_up_text
if add_item_value_to_searchable_text:
searchable_text = item_value + '\n' + searchable_text
note_id = self.note_id_for(conn, field_name, item_id)
old_resources = frozenset(self.resources_used_by(conn, note_id))
if not marked_up_text:
if note_id is not None:
conn.execute('DELETE FROM notes_db.notes WHERE id=?', (note_id,))
resources = ()
if old_resources:
resources = conn.get(
'SELECT hash,name FROM notes_db.resources WHERE hash IN ({})'.format(','.join(repeat('?', len(old_resources)))),
tuple(old_resources))
self.retire_entry(field_name, item_id, item_value, resources, note_id)
if old_resources:
self.remove_resources(conn, note_id, old_resources, delete_from_link_table=False)
return -1
new_resources = frozenset(used_resource_hashes)
resources_to_potentially_remove = old_resources - new_resources
resources_to_add = new_resources - old_resources
if note_id is None:
self.remove_retired_entry(field_name, item_id, item_value)
if ctime is not None or mtime is not None:
now = time.time()
if ctime is None:
ctime = now
if mtime is None:
mtime = now
note_id = conn.get('''
INSERT INTO notes_db.notes (item,colname,doc,searchable_text,ctime,mtime) VALUES (?,?,?,?,?,?) RETURNING notes.id;
''', (item_id, field_name, marked_up_text, searchable_text, ctime, mtime), all=False)
else:
note_id = conn.get('''
INSERT INTO notes_db.notes (item,colname,doc,searchable_text) VALUES (?,?,?,?) RETURNING notes.id;
''', (item_id, field_name, marked_up_text, searchable_text), all=False)
else:
conn.execute('UPDATE notes_db.notes SET doc=?,searchable_text=? WHERE id=?', (marked_up_text, searchable_text, note_id))
if resources_to_potentially_remove:
self.remove_resources(conn, note_id, resources_to_potentially_remove)
if resources_to_add:
conn.executemany('''
INSERT INTO notes_db.notes_resources_link (note,resource) VALUES (?,?);
''', tuple((note_id, x) for x in resources_to_add))
self.set_backup_for(field_name, item_id, item_value, marked_up_text, searchable_text, used_resource_hashes)
return note_id
def get_note(self, conn, field_name, item_id):
return conn.get('SELECT doc FROM notes_db.notes WHERE item=? AND colname=?', (item_id, field_name), all=False)
def get_note_data(self, conn, field_name, item_id):
ans = None
for (note_id, doc, searchable_text, ctime, mtime) in conn.execute(
'SELECT id,doc,searchable_text,ctime,mtime FROM notes_db.notes WHERE item=? AND colname=?', (item_id, field_name)
):
ans = {
'id': note_id, 'doc': doc, 'searchable_text': searchable_text,
'ctime': ctime, 'mtime': mtime,
'resource_hashes': frozenset(self.resources_used_by(conn, note_id)),
}
break
return ans
def get_all_items_that_have_notes(self, conn, field_name=None):
if field_name:
return {item_id for (item_id,) in conn.execute('SELECT item FROM notes_db.notes WHERE colname=?', (field_name,))}
ans = defaultdict(set)
for (note_id, field_name) in conn.execute('SELECT item, colname FROM notes_db.notes'):
ans[field_name].add(note_id)
return ans
def rename_note(self, conn, field_name, old_item_id, new_item_id, new_item_value):
note_id = self.note_id_for(conn, field_name, old_item_id)
if note_id is None:
return
new_note = self.get_note(conn, field_name, new_item_id)
if new_note:
return
old_note = self.get_note_data(conn, field_name, old_item_id)
if not old_note or not old_note['doc']:
return
self.set_note(conn, field_name, new_item_id, new_item_value, old_note['doc'], old_note['resource_hashes'], old_note['searchable_text'])
def trim_retired_dir(self):
items = []
for d in os.scandir(make_long_path_useable(self.retired_dir)):
items.append(d.path)
extra = len(items) - self.max_retired_items
if extra > 0:
def key(path):
path = os.path.join(path, 'note_id')
with suppress(OSError):
with open(path) as f:
return os.stat(path, follow_symlinks=False).st_mtime_ns, int(f.read())
items.sort(key=key)
for path in items[:extra]:
remove_with_retry(path, is_dir=True)
def add_resource(self, conn, path_or_stream_or_data, name, update_name=True, mtime=None):
if isinstance(path_or_stream_or_data, bytes):
data = path_or_stream_or_data
elif isinstance(path_or_stream_or_data, str):
with open(path_or_stream_or_data, 'rb') as f:
data = f.read()
else:
data = path_or_stream_or_data.read()
resource_hash = hash_data(data)
path = self.path_for_resource(resource_hash)
path = make_long_path_useable(path)
exists = False
try:
s = os.stat(path, follow_symlinks=False)
except OSError:
pass
else:
exists = s.st_size == len(data)
if not exists:
try:
f = open(path, 'wb')
except FileNotFoundError:
os.makedirs(os.path.dirname(path), exist_ok=True)
f = open(path, 'wb')
with f:
f.write(data)
if mtime is not None:
os.utime(f.name, (mtime, mtime))
name = sanitize_file_name(name)
base_name, ext = os.path.splitext(name)
c = 0
for (existing_name,) in conn.execute('SELECT name FROM notes_db.resources WHERE hash=?', (resource_hash,)):
if existing_name != name and update_name:
while True:
try:
conn.execute('UPDATE notes_db.resources SET name=? WHERE hash=?', (name, resource_hash))
with open(path + METADATA_EXT, 'w') as fn:
fn.write(json.dumps({'name':name}))
break
except apsw.ConstraintError:
c += 1
name = f'{base_name}-{c}{ext}'
break
else:
while True:
try:
conn.get('INSERT INTO notes_db.resources (hash,name) VALUES (?,?)', (resource_hash, name), all=False)
with open(path + METADATA_EXT, 'w') as fn:
fn.write(json.dumps({'name':name}))
break
except apsw.ConstraintError:
c += 1
name = f'{base_name}-{c}{ext}'
return resource_hash
def get_resource_data(self, conn, resource_hash) -> Optional[dict]:
ans = None
for (name,) in conn.execute('SELECT name FROM notes_db.resources WHERE hash=?', (resource_hash,)):
path = self.path_for_resource(resource_hash)
path = make_long_path_useable(path)
os.listdir(os.path.dirname(path))
with suppress(FileNotFoundError), open(path, 'rb') as f:
mtime = os.stat(f.fileno()).st_mtime
ans = {'name': name, 'data': f.read(), 'hash': resource_hash, 'mtime': mtime}
break
return ans
def all_notes(self, conn, restrict_to_fields=(), limit=None, snippet_size=64, return_text=True, process_each_result=None) -> list[dict]:
if snippet_size is None:
snippet_size = 64
char_size = snippet_size * 8
query = 'SELECT {0}.id, {0}.colname, {0}.item, substr({0}.searchable_text, 0, {1}) FROM {0} '.format('notes', char_size)
if restrict_to_fields:
query += ' WHERE notes_db.notes.colname IN ({})'.format(','.join(repeat('?', len(restrict_to_fields))))
query += ' ORDER BY mtime DESC'
if limit is not None:
query += f' LIMIT {limit}'
for record in conn.execute(query, tuple(restrict_to_fields)):
result = {
'id': record[0],
'field': record[1],
'item_id': record[2],
'text': record[3] if return_text else '',
}
if process_each_result is not None:
result = process_each_result(result)
ret = yield result
if ret is True:
break
def search(self,
conn, fts_engine_query, use_stemming, highlight_start, highlight_end, snippet_size, restrict_to_fields=(),
return_text=True, process_each_result=None, limit=None
):
if not fts_engine_query:
yield from self.all_notes(
conn, restrict_to_fields, limit=limit, snippet_size=snippet_size, return_text=return_text, process_each_result=process_each_result)
return
fts_engine_query = unicode_normalize(fts_engine_query)
fts_table = 'notes_fts' + ('_stemmed' if use_stemming else '')
hl_data = ()
if return_text:
text = 'notes.searchable_text'
if highlight_start is not None and highlight_end is not None:
if snippet_size is not None:
text = f'''snippet("{fts_table}", 0, ?, ?, '…', {max(1, min(snippet_size, 64))})'''
else:
text = f'''highlight("{fts_table}", 0, ?, ?)'''
hl_data = (highlight_start, highlight_end)
text = ', ' + text
else:
text = ''
query = 'SELECT {0}.id, {0}.colname, {0}.item {1} FROM {0} '.format('notes', text)
query += f' JOIN {fts_table} ON notes_db.notes.id = {fts_table}.rowid'
query += ' WHERE '
if restrict_to_fields:
query += ' notes_db.notes.colname IN ({}) AND '.format(','.join(repeat('?', len(restrict_to_fields))))
query += f' "{fts_table}" MATCH ?'
query += f' ORDER BY {fts_table}.rank '
if limit is not None:
query += f' LIMIT {limit}'
try:
for record in conn.execute(query, hl_data + restrict_to_fields + (fts_engine_query,)):
result = {
'id': record[0],
'field': record[1],
'item_id': record[2],
'text': record[3] if return_text else '',
}
if process_each_result is not None:
result = process_each_result(result)
ret = yield result
if ret is True:
break
except apsw.SQLError as e:
raise FTSQueryError(fts_engine_query, query, e) from e
def export_non_db_data(self, zf):
import zipfile
def add_dir(which):
for dirpath, _, filenames in os.walk(make_long_path_useable(which)):
for f in filenames:
path = os.path.join(dirpath, f)
with open(path, 'rb') as src:
zi = zipfile.ZipInfo.from_file(path, arcname=os.path.relpath(path, self.notes_dir))
with zf.open(zi, 'w') as dest:
shutil.copyfileobj(src, dest)
add_dir(self.backup_dir)
add_dir(self.resources_dir)
def vacuum(self, conn):
conn.execute('VACUUM notes_db')
def restore(self, conn, tables, report_progress):
resources = {}
errors = []
for subdir in os.listdir(make_long_path_useable(self.resources_dir)):
try:
subitems = os.listdir(make_long_path_useable(os.path.join(self.resources_dir, subdir)))
except NotADirectoryError:
continue
for rf in subitems:
if not rf.endswith(METADATA_EXT):
name_path = os.path.join(self.resources_dir, subdir, rf + METADATA_EXT)
name = 'unnamed'
with suppress(OSError), open(make_long_path_useable(name_path)) as n:
name = json.loads(n.read())['name']
resources[rf.replace('-', ':', 1)] = name
items = {}
for f in os.listdir(make_long_path_useable(self.backup_dir)):
if f in self.allowed_fields:
items[f] = []
for x in os.listdir(make_long_path_useable(os.path.join(self.backup_dir, f))):
with suppress(Exception):
items[f].append(int(x))
known_resources = frozenset(resources)
conn.executemany('INSERT OR REPLACE INTO notes_db.resources (hash,name) VALUES (?,?)', tuple(resources.items()))
i, total = 0, sum(len(x) for x in items.values())
report_progress(None, total)
for field, entries in items.items():
table = tables[field]
rmap = {v: k for k, v in table.id_map.items()}
for old_item_id in entries:
i += 1
try:
with open(make_long_path_useable(os.path.join(self.backup_dir, field, str(old_item_id))), 'rb') as f:
raw = f.read()
st = os.stat(f.fileno())
except OSError as e:
errors.append(_('Failed to read from document for {path} with error: {error}').format(path=f'{field}:{old_item_id}', error=e))
report_progress('', i)
continue
parts = raw.split(SEP, 3)
try:
if len(parts) == 4:
doc, searchable_text, res, old_item_val = (str(x, 'utf-8') for x in parts)
else:
doc, searchable_text, res = (str(x, 'utf-8') for x in parts)
old_item_val = searchable_text.split('\n', 1)[0]
except Exception as err:
errors.append(_('Failed to parse document for: {0} with error: {1}').format(old_item_id, err))
report_progress('', i)
continue
item_id = rmap.get(old_item_val)
if item_id is None:
errors.append(_(
'The item {old_item_val} does not exist in the {field} column in the restored database, could not restore its notes'
).format(old_item_val=old_item_val, field=field))
report_progress('', i)
continue
report_progress(old_item_val, i)
resources = frozenset(res.splitlines())
missing_resources = resources - known_resources
if missing_resources:
errors.append(_('Some resources for {} were missing').format(old_item_val))
resources &= known_resources
try:
self.set_note(conn, field, item_id, old_item_val, doc, resources, searchable_text, ctime=st.st_ctime, mtime=st.st_mtime)
except Exception as e:
errors.append(_('Failed to set note for {path} with error: {error}').format(path=old_item_val, error=e))
return errors
def export_note(self, conn, field_name, item_id):
nd = self.get_note_data(conn, field_name, item_id)
if nd is None:
return ''
from .exim import export_note
def get_resource(rhash):
return self.get_resource_data(conn, rhash)
return export_note(nd['doc'], get_resource)
def import_note(self, conn, field_name, item_id, item_value, html, basedir, ctime=None, mtime=None):
from .exim import import_note
def add_resource(path_or_stream_or_data, name):
return self.add_resource(conn, path_or_stream_or_data, name)
doc, searchable_text, resources = import_note(html, basedir, add_resource)
return self.set_note(
conn, field_name, item_id, item_value, marked_up_text=doc, used_resource_hashes=resources, searchable_text=searchable_text,
ctime=ctime, mtime=mtime
)
| 26,198 | Python | .py | 509 | 39.084479 | 155 | 0.578309 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,079 | schema_upgrade.py | kovidgoyal_calibre/src/calibre/db/notes/schema_upgrade.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2023, Kovid Goyal <kovid at kovidgoyal.net>
from calibre.utils.resources import get_path as P
class SchemaUpgrade:
def __init__(self, conn, triggers_sql):
self.conn = conn
conn.execute('BEGIN EXCLUSIVE TRANSACTION')
try:
if self.user_version == 0:
notes_sqlite = P('notes_sqlite.sql', data=True, allow_user_override=False).decode('utf-8')
conn.execute(notes_sqlite)
while True:
uv = self.user_version
meth = getattr(self, f'upgrade_version_{uv}', None)
if meth is None:
break
print(f'Upgrading Notes database to version {uv+1}...')
meth()
self.user_version = uv + 1
conn.execute(triggers_sql)
except (Exception, BaseException):
conn.execute('ROLLBACK')
raise
else:
conn.execute('COMMIT')
self.conn = None
@property
def user_version(self):
return self.conn.get('PRAGMA notes_db.user_version', all=False) or 0
@user_version.setter
def user_version(self, val):
self.conn.execute(f'PRAGMA notes_db.user_version={val}')
| 1,275 | Python | .py | 32 | 29.15625 | 106 | 0.581245 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,080 | filesystem.py | kovidgoyal_calibre/src/calibre/db/tests/filesystem.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os
import time
import unittest
from io import BytesIO
from calibre.constants import iswindows
from calibre.db.tests.base import BaseTest
from calibre.ptempfile import TemporaryDirectory
def read(x, mode='r'):
with open(x, mode) as f:
return f.read()
class FilesystemTest(BaseTest):
def get_filesystem_data(self, cache, book_id):
fmts = cache.field_for('formats', book_id)
ans = {}
for fmt in fmts:
buf = BytesIO()
if cache.copy_format_to(book_id, fmt, buf):
ans[fmt] = buf.getvalue()
buf = BytesIO()
if cache.copy_cover_to(book_id, buf):
ans['cover'] = buf.getvalue()
return ans
def test_metadata_move(self):
'Test the moving of files when title/author change'
cl = self.cloned_library
cache = self.init_cache(cl)
ae, af, sf = self.assertEqual, self.assertFalse, cache.set_field
# Test that changing metadata on a book with no formats/cover works
ae(sf('title', {3:'moved1'}), {3})
ae(sf('authors', {3:'moved1'}), {3})
ae(sf('title', {3:'Moved1'}), {3})
ae(sf('authors', {3:'Moved1'}), {3})
ae(cache.field_for('title', 3), 'Moved1')
ae(cache.field_for('authors', 3), ('Moved1',))
# Now try with a book that has covers and formats
orig_data = self.get_filesystem_data(cache, 1)
orig_fpath = cache.format_abspath(1, 'FMT1')
ae(sf('title', {1:'moved'}), {1})
ae(sf('authors', {1:'moved'}), {1})
ae(sf('title', {1:'Moved'}), {1})
ae(sf('authors', {1:'Moved'}), {1})
ae(cache.field_for('title', 1), 'Moved')
ae(cache.field_for('authors', 1), ('Moved',))
cache2 = self.init_cache(cl)
for c in (cache, cache2):
data = self.get_filesystem_data(c, 1)
ae(set(orig_data), set(data))
ae(orig_data, data, 'Filesystem data does not match')
ae(c.field_for('path', 1), 'Moved/Moved (1)')
ae(c.field_for('path', 3), 'Moved1/Moved1 (3)')
fpath = c.format_abspath(1, 'FMT1').replace(os.sep, '/').split('/')
ae(fpath[-3:], ['Moved', 'Moved (1)', 'Moved - Moved.fmt1'])
af(os.path.exists(os.path.dirname(orig_fpath)), 'Original book folder still exists')
# Check that the filesystem reflects fpath (especially on
# case-insensitive systems).
for x in range(1, 4):
base = os.sep.join(fpath[:-x])
part = fpath[-x:][0]
self.assertIn(part, os.listdir(base))
initial_side_data = {}
def init_cache():
nonlocal cache, initial_side_data
cache = self.init_cache(self.cloned_library)
bookdir = os.path.dirname(cache.format_abspath(1, '__COVER_INTERNAL__'))
with open(os.path.join(bookdir, 'a.side'), 'w') as f:
f.write('a.side')
os.mkdir(os.path.join(bookdir, 'subdir'))
with open(os.path.join(bookdir, 'subdir', 'a.fmt1'), 'w') as f:
f.write('a.fmt1')
initial_side_data = side_data()
def side_data(book_id=1):
bookdir = os.path.dirname(cache.format_abspath(book_id, '__COVER_INTERNAL__'))
return {
'a.side': read(os.path.join(bookdir, 'a.side')),
'a.fmt1': read(os.path.join(bookdir, 'subdir', 'a.fmt1')),
}
def check_that_filesystem_and_db_entries_match(book_id):
bookdir = os.path.dirname(cache.format_abspath(book_id, '__COVER_INTERNAL__'))
if iswindows:
from calibre_extensions import winutil
bookdir = winutil.get_long_path_name(bookdir)
bookdir_contents = set(os.listdir(bookdir))
expected_contents = {'cover.jpg', 'a.side', 'subdir'}
for fmt, fname in cache.fields['formats'].table.fname_map[book_id].items():
expected_contents.add(fname + '.' + fmt.lower())
ae(expected_contents, bookdir_contents)
fs_path = bookdir.split(os.sep)[-2:]
db_path = cache.field_for('path', book_id).split('/')
ae(db_path, fs_path)
ae(initial_side_data, side_data(book_id))
# test only formats being changed
init_cache()
ef = set()
for efx in cache.list_extra_files(1):
ef.add(efx.relpath)
self.assertTrue(os.path.exists(efx.file_path))
self.assertEqual(ef, {'a.side', 'subdir/a.fmt1'})
fname = cache.fields['formats'].table.fname_map[1]['FMT1']
cache.fields['formats'].table.fname_map[1]['FMT1'] = 'some thing else'
cache.fields['formats'].table.fname_map[1]['FMT2'] = fname.upper()
cache.backend.update_path(1, cache.field_for('title', 1), cache.field_for('authors', 1)[0], cache.fields['path'], cache.fields['formats'])
check_that_filesystem_and_db_entries_match(1)
# test a case only change
init_cache()
title = cache.field_for('title', 1)
self.assertNotEqual(title, title.upper())
cache.set_field('title', {1: title.upper()})
check_that_filesystem_and_db_entries_match(1)
# test a title change
init_cache()
cache.set_field('title', {1: 'new changed title'})
check_that_filesystem_and_db_entries_match(1)
# test an author change
cache.set_field('authors', {1: ('new changed author',)})
check_that_filesystem_and_db_entries_match(1)
# test a double change
from calibre.ebooks.metadata.book.base import Metadata
cache.set_metadata(1, Metadata('t1', ('a1', 'a2')))
check_that_filesystem_and_db_entries_match(1)
# check that empty author folders are removed
for x in os.scandir(cache.backend.library_path):
if x.is_dir():
self.assertTrue(os.listdir(x.path))
def test_rename_of_extra_files(self):
cl = self.cloned_library
cache = self.init_cache(cl)
cache.add_extra_files(1, {'a': BytesIO(b'aaa'), 'b': BytesIO(b'bbb')})
def relpaths():
return {e.relpath for e in cache.list_extra_files(1)}
self.assertEqual(relpaths(), {'a', 'b'})
self.assertEqual(cache.rename_extra_files(1, {'a': 'data/c'}), {'a'})
self.assertEqual(relpaths(), {'data/c', 'b'})
self.assertEqual(cache.rename_extra_files(1, {'b': 'B'}), {'b'})
self.assertEqual(relpaths(), {'data/c', 'B'})
self.assertEqual(cache.rename_extra_files(1, {'B': 'data/c'}), set())
self.assertEqual(cache.rename_extra_files(1, {'B': 'data/c'}, replace=True), {'B'})
@unittest.skipUnless(iswindows, 'Windows only')
def test_windows_atomic_move(self):
'Test book file open in another process when changing metadata'
cl = self.cloned_library
cache = self.init_cache(cl)
fpath = cache.format_abspath(1, 'FMT1')
with open(fpath, 'rb') as f:
with self.assertRaises(IOError):
cache.set_field('title', {1:'Moved'})
with self.assertRaises(IOError):
cache.remove_books({1})
self.assertNotEqual(cache.field_for('title', 1), 'Moved', 'Title was changed despite file lock')
# Test on folder with hardlinks
from calibre.ptempfile import TemporaryDirectory
from calibre.utils.filenames import WindowsAtomicFolderMove, hardlink_file
raw = b'xxx'
with TemporaryDirectory() as tdir1, TemporaryDirectory() as tdir2:
a, b = os.path.join(tdir1, 'a'), os.path.join(tdir1, 'b')
a = os.path.join(tdir1, 'a')
with open(a, 'wb') as f:
f.write(raw)
hardlink_file(a, b)
wam = WindowsAtomicFolderMove(tdir1)
wam.copy_path_to(a, os.path.join(tdir2, 'a'))
wam.copy_path_to(b, os.path.join(tdir2, 'b'))
wam.delete_originals()
self.assertEqual([], os.listdir(tdir1))
self.assertEqual({'a', 'b'}, set(os.listdir(tdir2)))
self.assertEqual(raw, read(os.path.join(tdir2, 'a'), 'rb'))
self.assertEqual(raw, read(os.path.join(tdir2, 'b'), 'rb'))
def test_library_move(self):
' Test moving of library '
from calibre.ptempfile import TemporaryDirectory
cache = self.init_cache()
self.assertIn('metadata.db', cache.get_top_level_move_items()[0])
all_ids = cache.all_book_ids()
fmt1 = cache.format(1, 'FMT1')
cov = cache.cover(1)
odir = cache.backend.library_path
with TemporaryDirectory('moved_lib') as tdir:
cache.move_library_to(tdir)
self.assertIn('moved_lib', cache.backend.library_path)
self.assertIn('moved_lib', cache.backend.dbpath)
self.assertEqual(fmt1, cache.format(1, 'FMT1'))
self.assertEqual(cov, cache.cover(1))
cache.reload_from_db()
self.assertEqual(all_ids, cache.all_book_ids())
cache.backend.close()
self.assertFalse(os.path.exists(odir))
os.mkdir(odir) # needed otherwise tearDown() fails
def test_long_filenames(self):
' Test long file names '
cache = self.init_cache()
cache.set_field('title', {1:'a'*10000})
self.assertLessEqual(len(cache.field_for('path', 1)), cache.backend.PATH_LIMIT * 2)
cache.set_field('authors', {1:'b'*10000})
self.assertLessEqual(len(cache.field_for('path', 1)), cache.backend.PATH_LIMIT * 2)
fpath = cache.format_abspath(1, cache.formats(1)[0])
self.assertLessEqual(len(fpath), len(cache.backend.library_path) + cache.backend.PATH_LIMIT * 4)
def test_reserved_names(self):
' Test that folders are not created with a windows reserve name '
cache = self.init_cache()
cache.set_field('authors', {1:'con'})
p = cache.field_for('path', 1).replace(os.sep, '/').split('/')
self.assertNotIn('con', p)
def test_fname_change(self):
' Test the changing of the filename but not the folder name '
cache = self.init_cache()
title = 'a'*30 + 'bbb'
cache.backend.PATH_LIMIT = 100
cache.set_field('title', {3:title})
cache.add_format(3, 'TXT', BytesIO(b'xxx'))
cache.backend.PATH_LIMIT = 40
cache.set_field('title', {3:title})
fpath = cache.format_abspath(3, 'TXT')
self.assertEqual(sorted([os.path.basename(fpath)]), sorted(os.listdir(os.path.dirname(fpath))))
def test_export_import(self):
from calibre.db.cache import import_library
from calibre.utils.exim import Exporter, Importer
with TemporaryDirectory('export_lib') as tdir:
for part_size in (8, 1, 1024):
exporter = Exporter(tdir, part_size=part_size + Exporter.tail_size())
files = {
'a': b'a' * 7, 'b': b'b' * 7, 'c': b'c' * 2, 'd': b'd' * 9, 'e': b'e' * 3,
}
for key, data in files.items():
exporter.add_file(BytesIO(data), key)
exporter.commit()
importer = Importer(tdir)
for key, expected in files.items():
with importer.start_file(key, key) as f:
actual = f.read()
self.assertEqual(expected, actual, key)
self.assertFalse(importer.corrupted_files)
cache = self.init_cache()
bookdir = os.path.dirname(cache.format_abspath(1, '__COVER_INTERNAL__'))
with open(os.path.join(bookdir, 'exf'), 'w') as f:
f.write('exf')
os.mkdir(os.path.join(bookdir, 'sub'))
with open(os.path.join(bookdir, 'sub', 'recurse'), 'w') as f:
f.write('recurse')
self.assertEqual({ef.relpath for ef in cache.list_extra_files(1, pattern='sub/**/*')}, {'sub/recurse'})
self.assertEqual({ef.relpath for ef in cache.list_extra_files(1)}, {'exf', 'sub/recurse'})
for part_size in (512, 1027, None):
with TemporaryDirectory('export_lib') as tdir, TemporaryDirectory('import_lib') as idir:
exporter = Exporter(tdir, part_size=part_size if part_size is None else (part_size + Exporter.tail_size()))
cache.export_library('l', exporter)
exporter.commit()
importer = Importer(tdir)
ic = import_library('l', importer, idir)
self.assertFalse(importer.corrupted_files)
self.assertEqual(cache.all_book_ids(), ic.all_book_ids())
for book_id in cache.all_book_ids():
self.assertEqual(cache.cover(book_id), ic.cover(book_id), 'Covers not identical for book: %d' % book_id)
for fmt in cache.formats(book_id):
self.assertEqual(cache.format(book_id, fmt), ic.format(book_id, fmt))
self.assertEqual(cache.format_metadata(book_id, fmt)['mtime'], cache.format_metadata(book_id, fmt)['mtime'])
bookdir = os.path.dirname(ic.format_abspath(1, '__COVER_INTERNAL__'))
self.assertEqual('exf', read(os.path.join(bookdir, 'exf')))
self.assertEqual('recurse', read(os.path.join(bookdir, 'sub', 'recurse')))
r1 = cache.add_notes_resource(b'res1', 'res.jpg', mtime=time.time()-113)
r2 = cache.add_notes_resource(b'res2', 'res.jpg', mtime=time.time()-1115)
cache.set_notes_for('authors', 2, 'some notes', resource_hashes=(r1, r2))
cache.add_format(1, 'TXT', BytesIO(b'testing exim'))
cache.fts_indexing_sleep_time = 0.001
cache.enable_fts()
cache.set_fts_num_of_workers(4)
st = time.monotonic()
while cache.fts_indexing_left > 0 and time.monotonic() - st < 15:
time.sleep(0.05)
if cache.fts_indexing_left > 0:
raise ValueError('FTS indexing did not complete')
self.assertEqual(cache.fts_search('exim')[0]['id'], 1)
with TemporaryDirectory('export_lib') as tdir, TemporaryDirectory('import_lib') as idir:
exporter = Exporter(tdir)
cache.export_library('l', exporter)
exporter.commit()
importer = Importer(tdir)
ic = import_library('l', importer, idir)
self.assertFalse(importer.corrupted_files)
self.assertEqual(ic.fts_search('exim')[0]['id'], 1)
self.assertEqual(cache.notes_for('authors', 2), ic.notes_for('authors', 2))
a, b = cache.get_notes_resource(r1), ic.get_notes_resource(r1)
at, bt, = a.pop('mtime'), b.pop('mtime')
self.assertEqual(a, b)
self.assertLess(abs(at-bt), 2)
def test_find_books_in_directory(self):
from calibre.db.adding import compile_rule, find_books_in_directory
def strip(files):
return frozenset({os.path.basename(x) for x in files})
def q(one, two):
one, two = {strip(a) for a in one}, {strip(b) for b in two}
self.assertEqual(one, two)
def r(action='ignore', match_type='startswith', query=''):
return {'action':action, 'match_type':match_type, 'query':query}
def c(*rules):
return tuple(map(compile_rule, rules))
files = ['added.epub', 'ignored.md', 'non-book.other']
q(['added.epub ignored.md'.split()], find_books_in_directory('', True, listdir_impl=lambda x: files))
q([['added.epub'], ['ignored.md']], find_books_in_directory('', False, listdir_impl=lambda x, **k: files))
for rules in (
c(r(query='ignored.'), r(action='add', match_type='endswith', query='.OTHER')),
c(r(match_type='glob', query='*.md'), r(action='add', match_type='matches', query=r'.+\.other$')),
c(r(match_type='not_startswith', query='IGnored.', action='add'), r(query='ignored.md')),
):
q(['added.epub non-book.other'.split()], find_books_in_directory('', True, compiled_rules=rules, listdir_impl=lambda x: files))
| 16,323 | Python | .py | 306 | 42.362745 | 146 | 0.586623 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,081 | reading.py | kovidgoyal_calibre/src/calibre/db/tests/reading.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import datetime
import os
from io import BytesIO
from time import time
from calibre.db.tests.base import BaseTest
from calibre.utils.date import utc_tz
from calibre.utils.localization import calibre_langcode_to_name
from polyglot.builtins import iteritems, itervalues
def p(x):
return datetime.datetime.strptime(x, '%Y-%m-%d').replace(tzinfo=utc_tz)
class ReadingTest(BaseTest):
def test_read(self): # {{{
'Test the reading of data from the database'
cache = self.init_cache(self.library_path)
tests = {
3 : {
'title': 'Unknown',
'sort': 'Unknown',
'authors': ('Unknown',),
'author_sort': 'Unknown',
'series' : None,
'series_index': 1.0,
'rating': None,
'tags': (),
'formats':(),
'identifiers': {},
'timestamp': datetime.datetime(2011, 9, 7, 19, 54, 41,
tzinfo=utc_tz),
'pubdate': datetime.datetime(2011, 9, 7, 19, 54, 41,
tzinfo=utc_tz),
'last_modified': datetime.datetime(2011, 9, 7, 19, 54, 41,
tzinfo=utc_tz),
'publisher': None,
'languages': (),
'comments': None,
'#enum': None,
'#authors':(),
'#date':None,
'#rating':None,
'#series':None,
'#series_index': None,
'#tags':(),
'#yesno':None,
'#comments': None,
'size':None,
},
2 : {
'title': 'Title One',
'sort': 'One',
'authors': ('Author One',),
'author_sort': 'One, Author',
'series' : 'A Series One',
'series_index': 1.0,
'tags':('Tag One', 'Tag Two'),
'formats': ('FMT1',),
'rating': 4.0,
'identifiers': {'test':'one'},
'timestamp': datetime.datetime(2011, 9, 5, 21, 6,
tzinfo=utc_tz),
'pubdate': datetime.datetime(2011, 9, 5, 21, 6,
tzinfo=utc_tz),
'publisher': 'Publisher One',
'languages': ('eng',),
'comments': '<p>Comments One</p>',
'#enum':'One',
'#authors':('Custom One', 'Custom Two'),
'#date':datetime.datetime(2011, 9, 5, 6, 0,
tzinfo=utc_tz),
'#rating':2.0,
'#series':'My Series One',
'#series_index': 1.0,
'#tags':('My Tag One', 'My Tag Two'),
'#yesno':True,
'#comments': '<div>My Comments One<p></p></div>',
'size':9,
},
1 : {
'title': 'Title Two',
'sort': 'Title Two',
'authors': ('Author Two', 'Author One'),
'author_sort': 'Two, Author & One, Author',
'series' : 'A Series One',
'series_index': 2.0,
'rating': 6.0,
'tags': ('Tag One', 'News'),
'formats':('FMT1', 'FMT2'),
'identifiers': {'test':'two'},
'timestamp': datetime.datetime(2011, 9, 6, 6, 0,
tzinfo=utc_tz),
'pubdate': datetime.datetime(2011, 8, 5, 6, 0,
tzinfo=utc_tz),
'publisher': 'Publisher Two',
'languages': ('deu',),
'comments': '<p>Comments Two</p>',
'#enum':'Two',
'#authors':('My Author Two',),
'#date':datetime.datetime(2011, 9, 1, 6, 0,
tzinfo=utc_tz),
'#rating':4.0,
'#series':'My Series Two',
'#series_index': 3.0,
'#tags':('My Tag Two',),
'#yesno':False,
'#comments': '<div>My Comments Two<p></p></div>',
'size':9,
},
}
for book_id, test in iteritems(tests):
for field, expected_val in iteritems(test):
val = cache.field_for(field, book_id)
if isinstance(val, tuple) and 'authors' not in field and 'languages' not in field:
val, expected_val = set(val), set(expected_val)
self.assertEqual(expected_val, val,
'Book id: %d Field: %s failed: %r != %r'%(
book_id, field, expected_val, val))
# }}}
def test_sorting(self): # {{{
'Test sorting'
cache = self.init_cache()
ae = self.assertEqual
lmap = {x:cache.field_for('languages', x) for x in (1, 2, 3)}
lq = sorted(lmap, key=lambda x: calibre_langcode_to_name((lmap[x] or ('',))[0]))
for field, order in iteritems({
'title' : [2, 1, 3],
'authors': [2, 1, 3],
'series' : [3, 1, 2],
'tags' : [3, 1, 2],
'rating' : [3, 2, 1],
# 'identifiers': [3, 2, 1], There is no stable sort since 1 and
# 2 have the same identifier keys
# 'last_modified': [3, 2, 1], There is no stable sort as two
# records have the exact same value
'timestamp': [2, 1, 3],
'pubdate' : [1, 2, 3],
'publisher': [3, 2, 1],
'languages': lq,
'comments': [3, 2, 1],
'#enum' : [3, 2, 1],
'#authors' : [3, 2, 1],
'#date': [3, 1, 2],
'#rating':[3, 2, 1],
'#series':[3, 2, 1],
'#tags':[3, 2, 1],
'#yesno':[2, 1, 3],
'#comments':[3, 2, 1],
'id': [1, 2, 3],
}):
x = list(reversed(order))
ae(order, cache.multisort([(field, True)],
ids_to_sort=x),
'Ascending sort of %s failed'%field)
ae(x, cache.multisort([(field, False)],
ids_to_sort=order),
'Descending sort of %s failed'%field)
# Test sorting of is_multiple fields.
# Author like fields should be sorted by generating sort names from the
# actual values in entry order
for field in ('authors', '#authors'):
ae(
cache.set_field(field, {1:('aa bb', 'bb cc', 'cc dd'), 2:('bb aa', 'xx yy'), 3: ('aa bb', 'bb aa')}), {1, 2, 3})
ae([2, 3, 1], cache.multisort([(field, True)], ids_to_sort=(1, 2, 3)))
ae([1, 3, 2], cache.multisort([(field, False)], ids_to_sort=(1, 2, 3)))
# All other is_multiple fields should be sorted by sorting the values
# for each book and using that as the sort key
for field in ('tags', '#tags'):
ae(
cache.set_field(field, {1:('b', 'a'), 2:('c', 'y'), 3: ('b', 'z')}), {1, 2, 3})
ae([1, 3, 2], cache.multisort([(field, True)], ids_to_sort=(1, 2, 3)))
ae([2, 3, 1], cache.multisort([(field, False)], ids_to_sort=(1, 2, 3)))
# Test tweak to sort dates by visible format
from calibre.utils.config_base import Tweak
ae(cache.set_field('pubdate', {1:p('2001-3-3'), 2:p('2002-2-3'), 3:p('2003-1-3')}), {1, 2, 3})
ae([1, 2, 3], cache.multisort([('pubdate', True)]))
with Tweak('gui_pubdate_display_format', 'MMM'), Tweak('sort_dates_using_visible_fields', True):
c2 = self.init_cache()
ae([3, 2, 1], c2.multisort([('pubdate', True)]))
# Test bool sorting when not tristate
cache.set_pref('bools_are_tristate', False)
c2 = self.init_cache()
ae([2, 3, 1], c2.multisort([('#yesno', True), ('id', False)]))
# Test subsorting
ae([3, 2, 1], cache.multisort([('identifiers', True),
('title', True)]), 'Subsort failed')
from calibre.ebooks.metadata.book.base import Metadata
for i in range(7):
cache.create_book_entry(Metadata('title%d' % i), apply_import_tags=False)
cache.create_custom_column('one', 'CC1', 'int', False)
cache.create_custom_column('two', 'CC2', 'int', False)
cache.create_custom_column('three', 'CC3', 'int', False)
cache.close()
cache = self.init_cache()
cache.set_field('#one', {(i+(5*m)):m for m in (0, 1) for i in range(1, 6)})
cache.set_field('#two', {i+(m*3):m for m in (0, 1, 2) for i in (1, 2, 3)})
cache.set_field('#two', {10:2})
cache.set_field('#three', {i:i for i in range(1, 11)})
ae(list(range(1, 11)), cache.multisort([('#one', True), ('#two', True)], ids_to_sort=sorted(cache.all_book_ids())))
ae([4, 5, 1, 2, 3, 7,8, 9, 10, 6], cache.multisort([('#one', True), ('#two', False)], ids_to_sort=sorted(cache.all_book_ids())))
ae([5, 4, 3, 2, 1, 10, 9, 8, 7, 6], cache.multisort([('#one', True), ('#two', False), ('#three', False)], ids_to_sort=sorted(cache.all_book_ids())))
# }}}
def test_get_metadata(self): # {{{
'Test get_metadata() returns the same data for both backends'
from calibre.library.database2 import LibraryDatabase2
old = LibraryDatabase2(self.library_path)
old_metadata = {i:old.get_metadata(
i, index_is_id=True, get_cover=True, cover_as_data=True) for i in
range(1, 4)}
for mi in itervalues(old_metadata):
mi.format_metadata = dict(mi.format_metadata)
if mi.formats:
mi.formats = tuple(mi.formats)
old.conn.close()
old = None
cache = self.init_cache(self.library_path)
new_metadata = {i:cache.get_metadata(
i, get_cover=True, cover_as_data=True) for i in range(1, 4)}
cache = None
for mi2, mi1 in zip(list(new_metadata.values()), list(old_metadata.values())):
self.compare_metadata(mi1, mi2)
# }}}
def test_serialize_metadata(self): # {{{
from calibre.library.field_metadata import fm_as_dict
from calibre.utils.serialize import json_dumps, json_loads, msgpack_dumps, msgpack_loads
cache = self.init_cache(self.library_path)
fm = cache.field_metadata
for d, l in ((json_dumps, json_loads), (msgpack_dumps, msgpack_loads)):
fm2 = l(d(fm))
self.assertEqual(fm_as_dict(fm), fm_as_dict(fm2))
for i in range(1, 4):
mi = cache.get_metadata(i, get_cover=True, cover_as_data=True)
rmi = msgpack_loads(msgpack_dumps(mi))
self.compare_metadata(mi, rmi, exclude='format_metadata has_cover formats id'.split())
rmi = json_loads(json_dumps(mi))
self.compare_metadata(mi, rmi, exclude='format_metadata has_cover formats id'.split())
# }}}
def test_get_cover(self): # {{{
'Test cover() returns the same data for both backends'
from calibre.library.database2 import LibraryDatabase2
old = LibraryDatabase2(self.library_path)
covers = {i: old.cover(i, index_is_id=True) for i in old.all_ids()}
old.conn.close()
old = None
cache = self.init_cache(self.library_path)
for book_id, cdata in iteritems(covers):
self.assertEqual(cdata, cache.cover(book_id), 'Reading of cover failed')
f = cache.cover(book_id, as_file=True)
try:
self.assertEqual(cdata, f.read() if f else f, 'Reading of cover as file failed')
finally:
if f:
f.close()
if cdata:
with open(cache.cover(book_id, as_path=True), 'rb') as f:
self.assertEqual(cdata, f.read(), 'Reading of cover as path failed')
else:
self.assertEqual(cdata, cache.cover(book_id, as_path=True),
'Reading of null cover as path failed')
buf = BytesIO()
self.assertFalse(cache.copy_cover_to(99999, buf), 'copy_cover_to() did not return False for non-existent book_id')
self.assertFalse(cache.copy_cover_to(3, buf), 'copy_cover_to() did not return False for non-existent cover')
# }}}
def test_searching(self): # {{{
'Test searching returns the same data for both backends'
from calibre.library.database2 import LibraryDatabase2
old = LibraryDatabase2(self.library_path)
oldvals = {query:set(old.search_getting_ids(query, '')) for query in (
# Date tests
'date:9/6/2011', 'date:true', 'date:false', 'pubdate:1/9/2011',
'#date:true', 'date:<100_daysago', 'date:>9/6/2011',
'#date:>9/1/2011', '#date:=2011',
# Number tests
'rating:3', 'rating:>2', 'rating:=2', 'rating:true',
'rating:false', 'rating:>4', 'tags:#<2', 'tags:#>7',
'cover:false', 'cover:true', '#float:>11', '#float:<1k',
'#float:10.01', '#float:false', 'series_index:1',
'series_index:<3',
# Bool tests
'#yesno:true', '#yesno:false', '#yesno:_yes', '#yesno:_no',
'#yesno:_empty',
# Keypair tests
'identifiers:true', 'identifiers:false', 'identifiers:test',
'identifiers:test:false', 'identifiers:test:one',
'identifiers:t:n', 'identifiers:=test:=two', 'identifiers:x:y',
'identifiers:z',
# Text tests
'title:="Title One"', 'title:~title', '#enum:=one', '#enum:tw',
'#enum:false', '#enum:true', 'series:one', 'tags:one', 'tags:true',
'tags:false', 'uuid:2', 'one', '20.02', '"publisher one"',
'"my comments one"', 'series_sort:one',
# User categories
'@Good Authors:One', '@Good Series.good tags:two',
# Cover/Formats
'cover:true', 'cover:false', 'formats:true', 'formats:false',
'formats:#>1', 'formats:#=1', 'formats:=fmt1', 'formats:=fmt2',
'formats:=fmt1 or formats:fmt2', '#formats:true', '#formats:false',
'#formats:fmt1', '#formats:fmt2', '#formats:fmt1 and #formats:fmt2',
)}
old.conn.close()
old = None
cache = self.init_cache(self.cloned_library)
for query, ans in iteritems(oldvals):
nr = cache.search(query, '')
self.assertEqual(ans, nr,
'Old result: %r != New result: %r for search: %s'%(
ans, nr, query))
# Test searching by id, which was introduced in the new backend
self.assertEqual(cache.search('id:1', ''), {1})
self.assertEqual(cache.search('id:>1', ''), {2, 3})
# Numeric/rating searches with relops in the old db were incorrect, so
# test them specifically here
cache.set_field('rating', {1:4, 2:2, 3:5})
self.assertEqual(cache.search('rating:>2'), set())
self.assertEqual(cache.search('rating:>=2'), {1, 3})
self.assertEqual(cache.search('rating:<2'), {2})
self.assertEqual(cache.search('rating:<=2'), {1, 2, 3})
self.assertEqual(cache.search('rating:<=2'), {1, 2, 3})
self.assertEqual(cache.search('rating:=2'), {1, 3})
self.assertEqual(cache.search('rating:2'), {1, 3})
self.assertEqual(cache.search('rating:!=2'), {2})
cache.field_metadata.all_metadata()['#rating']['display']['allow_half_stars'] = True
cache.set_field('#rating', {1:3, 2:4, 3:9})
self.assertEqual(cache.search('#rating:1'), set())
self.assertEqual(cache.search('#rating:1.5'), {1})
self.assertEqual(cache.search('#rating:>4'), {3})
self.assertEqual(cache.search('#rating:2'), {2})
# template searches
# Test text search
self.assertEqual(cache.search('template:"{#formats}#@#:t:fmt1"'), {1,2})
self.assertEqual(cache.search('template:"{authors}#@#:t:=Author One"'), {2})
cache.set_field('pubdate', {1:p('2001-02-06'), 2:p('2001-10-06'), 3:p('2001-06-06')})
cache.set_field('timestamp', {1:p('2002-02-06'), 2:p('2000-10-06'), 3:p('2001-06-06')})
# Test numeric compare search
self.assertEqual(cache.search("template:\"program: "
"floor(days_between(field(\'pubdate\'), "
"field(\'timestamp\')))#@#:n:>0\""), {2,3})
# Test date search
self.assertEqual(cache.search('template:{pubdate}#@#:d:<2001-09-01"'), {1,3})
# Test boolean search
self.assertEqual(cache.search('template:{series}#@#:b:true'), {1,2})
self.assertEqual(cache.search('template:{series}#@#:b:false'), {3})
# test primary search
cache.set_field('title', {1: "Gravity’s Raiñbow"})
self.assertEqual(cache.search('title:"Gravity\'s Rainbow"'), {1})
# Note that the old db searched uuid for un-prefixed searches, the new
# db does not, for performance
# }}}
def test_get_categories(self): # {{{
'Check that get_categories() returns the same data for both backends'
from calibre.library.database2 import LibraryDatabase2
old = LibraryDatabase2(self.library_path)
old_categories = old.get_categories()
old.conn.close()
cache = self.init_cache(self.library_path)
new_categories = cache.get_categories()
self.assertEqual(set(old_categories), set(new_categories),
'The set of old categories is not the same as the set of new categories')
def compare_category(category, old, new):
for attr in ('name', 'original_name', 'id', 'count',
'is_hierarchical', 'is_editable', 'is_searchable',
'id_set', 'avg_rating', 'sort', 'use_sort_as_name',
'category'):
oval, nval = getattr(old, attr), getattr(new, attr)
if (
(category in {'rating', '#rating'} and attr in {'id_set', 'sort'}) or
(category == 'series' and attr == 'sort') or # Sorting is wrong in old
(category == 'identifiers' and attr == 'id_set') or
(category == '@Good Series') or # Sorting is wrong in old
(category == 'news' and attr in {'count', 'id_set'}) or
(category == 'formats' and attr == 'id_set')
):
continue
self.assertEqual(oval, nval,
'The attribute %s for %s in category %s does not match. Old is %r, New is %r'
%(attr, old.name, category, oval, nval))
for category in old_categories:
old, new = old_categories[category], new_categories[category]
self.assertEqual(len(old), len(new),
'The number of items in the category %s is not the same'%category)
for o, n in zip(old, new):
compare_category(category, o, n)
# }}}
def test_get_formats(self): # {{{
'Test reading ebook formats using the format() method'
from calibre.db.cache import NoSuchFormat
from calibre.library.database2 import LibraryDatabase2
old = LibraryDatabase2(self.library_path)
ids = old.all_ids()
lf = {i:set(old.formats(i, index_is_id=True).split(',')) if old.formats(
i, index_is_id=True) else set() for i in ids}
formats = {i:{f:old.format(i, f, index_is_id=True) for f in fmts} for
i, fmts in iteritems(lf)}
old.conn.close()
old = None
cache = self.init_cache(self.library_path)
for book_id, fmts in iteritems(lf):
self.assertEqual(fmts, set(cache.formats(book_id)),
'Set of formats is not the same')
for fmt in fmts:
old = formats[book_id][fmt]
self.assertEqual(old, cache.format(book_id, fmt),
'Old and new format disagree')
with cache.format(book_id, fmt, as_file=True) as f:
self.assertEqual(old, f.read(),
'Failed to read format as file')
with open(cache.format(book_id, fmt, as_path=True,
preserve_filename=True), 'rb') as f:
self.assertEqual(old, f.read(),
'Failed to read format as path')
with open(cache.format(book_id, fmt, as_path=True), 'rb') as f:
self.assertEqual(old, f.read(),
'Failed to read format as path')
buf = BytesIO()
self.assertRaises(NoSuchFormat, cache.copy_format_to, 99999, 'X', buf, 'copy_format_to() failed to raise an exception for non-existent book')
self.assertRaises(NoSuchFormat, cache.copy_format_to, 1, 'X', buf, 'copy_format_to() failed to raise an exception for non-existent format')
fmt = cache.formats(1)[0]
path = cache.format_abspath(1, fmt)
changed_path = os.path.join(os.path.dirname(path), 'x' + os.path.basename(path))
os.rename(path, changed_path)
self.assertEqual(cache.format_abspath(1, fmt), path)
self.assertFalse(os.path.exists(changed_path))
# }}}
def test_author_sort_for_authors(self): # {{{
'Test getting the author sort for authors from the db'
cache = self.init_cache()
table = cache.fields['authors'].table
table.set_sort_names({next(iter(table.id_map)): 'Fake Sort'}, cache.backend)
authors = tuple(itervalues(table.id_map))
nval = cache.author_sort_from_authors(authors)
self.assertIn('Fake Sort', nval)
db = self.init_old()
self.assertEqual(db.author_sort_from_authors(authors), nval)
db.close()
del db
# }}}
def test_get_next_series_num(self): # {{{
'Test getting the next series number for a series'
cache = self.init_cache()
cache.set_field('series', {3:'test series'})
cache.set_field('series_index', {3:13})
table = cache.fields['series'].table
series = tuple(itervalues(table.id_map))
nvals = {s:cache.get_next_series_num_for(s) for s in series}
db = self.init_old()
self.assertEqual({s:db.get_next_series_num_for(s) for s in series}, nvals)
db.close()
# }}}
def test_has_book(self): # {{{
'Test detecting duplicates'
from calibre.ebooks.metadata.book.base import Metadata
cache = self.init_cache()
db = self.init_old()
for title in itervalues(cache.fields['title'].table.book_col_map):
for x in (db, cache):
self.assertTrue(x.has_book(Metadata(title)))
self.assertTrue(x.has_book(Metadata(title.upper())))
self.assertFalse(x.has_book(Metadata(title + 'XXX')))
self.assertFalse(x.has_book(Metadata(title[:1])))
db.close()
# }}}
def test_datetime(self): # {{{
' Test the reading of datetimes stored in the db '
from calibre.db.tables import UNDEFINED_DATE, _c_speedup, c_parse
from calibre.utils.date import parse_date
# First test parsing of string to UTC time
for raw in ('2013-07-22 15:18:29+05:30', ' 2013-07-22 15:18:29+00:00', '2013-07-22 15:18:29', '2003-09-21 23:30:00-06:00'):
self.assertTrue(_c_speedup(raw))
ctime = c_parse(raw)
pytime = parse_date(raw, assume_utc=True)
self.assertEqual(ctime, pytime)
self.assertEqual(c_parse(2003).year, 2003)
for x in (None, '', 'abc'):
self.assertEqual(UNDEFINED_DATE, c_parse(x))
# }}}
def test_restrictions(self): # {{{
' Test searching with and without restrictions '
cache = self.init_cache()
se = self.assertSetEqual
se(cache.all_book_ids(), cache.search(''))
se({1, 2}, cache.search('', 'not authors:=Unknown'))
se(set(), cache.search('authors:=Unknown', 'not authors:=Unknown'))
se({2}, cache.search('not authors:"=Author Two"', 'not authors:=Unknown'))
se({2}, cache.search('not authors:"=Author Two"', book_ids={1, 2}))
se({2}, cache.search('not authors:"=Author Two"', 'not authors:=Unknown', book_ids={1,2,3}))
se(set(), cache.search('authors:=Unknown', 'not authors:=Unknown', book_ids={1,2,3}))
se(cache.all_book_ids(), cache.books_in_virtual_library(''))
se(cache.all_book_ids(), cache.books_in_virtual_library('does not exist'))
cache.set_pref('virtual_libraries', {'1':'title:"=Title One"', '12':'id:1 or id:2'})
se({2}, cache.books_in_virtual_library('1'))
se({1,2}, cache.books_in_virtual_library('12'))
se({1}, cache.books_in_virtual_library('12', 'id:1'))
se({2}, cache.books_in_virtual_library('1', 'id:1 or id:2'))
# }}}
def test_search_caching(self): # {{{
' Test caching of searches '
from calibre.db.search import LRUCache
class TestCache(LRUCache):
hit_counter = 0
miss_counter = 0
def get(self, key, default=None):
ans = LRUCache.get(self, key, default=default)
if ans is not None:
self.hit_counter += 1
else:
self.miss_counter += 1
@property
def cc(self):
self.hit_counter = self.miss_counter = 0
@property
def counts(self):
return self.hit_counter, self.miss_counter
cache = self.init_cache()
cache._search_api.cache = c = TestCache()
ae = self.assertEqual
def test(hit, result, *args, **kw):
c.cc
num = kw.get('num', 2)
ae(cache.search(*args), result)
ae(c.counts, (num, 0) if hit else (0, num))
c.cc
test(False, {3}, 'Unknown')
test(True, {3}, 'Unknown')
test(True, {3}, 'Unknown')
cache._search_api.MAX_CACHE_UPDATE = 0
cache.set_field('title', {3:'xxx'})
test(False, {3}, 'Unknown') # cache cleared
test(True, {3}, 'Unknown')
c.limit = 5
for i in range(6):
test(False, set(), 'nomatch_%s' % i)
test(False, {3}, 'Unknown') # cached search expired
test(False, {3}, '', 'unknown', num=1)
test(True, {3}, '', 'unknown', num=1)
test(True, {3}, 'Unknown', 'unknown', num=1)
cache._search_api.MAX_CACHE_UPDATE = 100
test(False, {2, 3}, 'title:=xxx or title:"=Title One"')
cache.set_field('publisher', {3:'ppppp', 2:'other'})
# Test cache update worked
test(True, {2, 3}, 'title:=xxx or title:"=Title One"')
# }}}
def test_proxy_metadata(self): # {{{
' Test the ProxyMetadata object used for composite columns '
from calibre.ebooks.metadata.book.base import STANDARD_METADATA_FIELDS
cache = self.init_cache()
for book_id in cache.all_book_ids():
mi = cache.get_metadata(book_id, get_user_categories=True)
pmi = cache.get_proxy_metadata(book_id)
self.assertSetEqual(set(mi.custom_field_keys()), set(pmi.custom_field_keys()))
for field in STANDARD_METADATA_FIELDS | {'#series_index'}:
if field == 'formats':
def f(x):
return (x if x is None else tuple(x))
else:
def f(x):
return x
self.assertEqual(f(getattr(mi, field)), f(getattr(pmi, field)),
f'Standard field: {field} not the same for book {book_id}')
self.assertEqual(mi.format_field(field), pmi.format_field(field),
f'Standard field format: {field} not the same for book {book_id}')
def f(x):
try:
x.pop('rec_index', None)
except:
pass
return x
if field not in {'#series_index'}:
v = pmi.get_standard_metadata(field)
self.assertTrue(v is None or isinstance(v, dict))
self.assertEqual(f(mi.get_standard_metadata(field, False)), f(v),
'get_standard_metadata() failed for field %s' % field)
for field, meta in cache.field_metadata.custom_iteritems():
if meta['datatype'] != 'composite':
self.assertEqual(f(getattr(mi, field)), f(getattr(pmi, field)),
f'Custom field: {field} not the same for book {book_id}')
self.assertEqual(mi.format_field(field), pmi.format_field(field),
f'Custom field format: {field} not the same for book {book_id}')
# Test handling of recursive templates
cache.create_custom_column('comp2', 'comp2', 'composite', False, display={'composite_template':'{title}'})
cache.create_custom_column('comp1', 'comp1', 'composite', False, display={'composite_template':'foo{#comp2}'})
cache.close()
cache = self.init_cache()
mi, pmi = cache.get_metadata(1), cache.get_proxy_metadata(1)
self.assertEqual(mi.get('#comp1'), pmi.get('#comp1'))
# Test overridden Metadata methods
self.assertTrue(pmi.has_key('tags') == mi.has_key('tags'))
self.assertFalse(pmi.has_key('taggs'), 'taggs attribute')
self.assertTrue(pmi.has_key('taggs') == mi.has_key('taggs'))
self.assertSetEqual(set(pmi.custom_field_keys()), set(mi.custom_field_keys()))
self.assertEqual(pmi.get_extra('#series', 0), 3)
self.assertEqual(pmi.get_extra('#series', 0), mi.get_extra('#series', 0))
self.assertDictEqual(pmi.get_identifiers(), {'test': 'two'})
self.assertDictEqual(pmi.get_identifiers(), mi.get_identifiers())
self.assertTrue(pmi.has_identifier('test'))
self.assertTrue(pmi.has_identifier('test') == mi.has_identifier('test'))
self.assertListEqual(list(pmi.custom_field_keys()), list(mi.custom_field_keys()))
# ProxyMetadata has the virtual fields while Metadata does not.
self.assertSetEqual(set(pmi.all_field_keys())-{'id', 'series_sort', 'path',
'in_tag_browser', 'sort', 'ondevice',
'au_map', 'marked', '#series_index'},
set(mi.all_field_keys()))
# mi.get_standard_metadata() doesn't include the rec_index metadata key
fm_pmi = pmi.get_standard_metadata('series')
fm_pmi.pop('rec_index')
self.assertDictEqual(fm_pmi, mi.get_standard_metadata('series', make_copy=False))
# The ProxyMetadata versions don't include the values. Note that the mi
# version of get_standard_metadata won't return custom columns while the
# ProxyMetadata version will
fm_mi = mi.get_user_metadata('#series', make_copy=False)
fm_mi.pop('#extra#')
fm_mi.pop('#value#')
self.assertDictEqual(pmi.get_standard_metadata('#series'), fm_mi)
self.assertDictEqual(pmi.get_user_metadata('#series'), fm_mi)
fm_mi = mi.get_all_user_metadata(make_copy=False)
for one in fm_mi:
fm_mi[one].pop('#extra#', None)
fm_mi[one].pop('#value#', None)
self.assertDictEqual(pmi.get_all_user_metadata(make_copy=False), fm_mi)
# Check the unimplemented methods
self.assertRaises(NotImplementedError, lambda: 'foo' in pmi)
self.assertRaises(NotImplementedError, pmi.set, 'a', 'a')
self.assertRaises(NotImplementedError, pmi.set_identifiers, 'a', 'a')
self.assertRaises(NotImplementedError, pmi.set_identifier, 'a', 'a')
self.assertRaises(NotImplementedError, pmi.all_non_none_fields)
self.assertRaises(NotImplementedError, pmi.set_all_user_metadata, {})
self.assertRaises(NotImplementedError, pmi.set_user_metadata, 'a', {})
self.assertRaises(NotImplementedError, pmi.remove_stale_user_metadata, {})
self.assertRaises(NotImplementedError, pmi.template_to_attribute, {}, {})
self.assertRaises(NotImplementedError, pmi.smart_update, {})
# }}}
def test_marked_field(self): # {{{
' Test the marked field '
db = self.init_legacy()
db.set_marked_ids({3:1, 2:3})
ids = [1,2,3]
db.multisort([('marked', True)], only_ids=ids)
self.assertListEqual([1, 3, 2], ids)
db.multisort([('marked', False)], only_ids=ids)
self.assertListEqual([2, 3, 1], ids)
# }}}
def test_composites(self): # {{{
' Test sorting and searching in composite columns '
cache = self.init_cache()
cache.create_custom_column('mult', 'CC1', 'composite', True, display={'composite_template': 'b,a,c'})
cache.create_custom_column('single', 'CC2', 'composite', False, display={'composite_template': 'b,a,c'})
cache.create_custom_column('number', 'CC3', 'composite', False, display={'composite_template': '{#float}', 'composite_sort':'number'})
cache.create_custom_column('size', 'CC4', 'composite', False, display={'composite_template': '{#float:human_readable()}', 'composite_sort':'number'})
cache.create_custom_column('ccdate', 'CC5', 'composite', False,
display={'composite_template': "{:'format_date(raw_field('pubdate'), 'dd-MM-yy')'}", 'composite_sort':'date'})
cache.create_custom_column('bool', 'CC6', 'composite', False, display={'composite_template': '{#yesno}', 'composite_sort':'bool'})
cache.create_custom_column('ccm', 'CC7', 'composite', True, display={'composite_template': '{#tags}'})
cache.create_custom_column('ccp', 'CC8', 'composite', True, display={'composite_template': '{publisher}'})
cache.create_custom_column('ccf', 'CC9', 'composite', True, display={'composite_template': "{:'approximate_formats()'}"})
cache = self.init_cache()
# Test searching
self.assertEqual({1,2,3}, cache.search('#mult:=a'))
self.assertEqual(set(), cache.search('#mult:=b,a,c'))
self.assertEqual({1,2,3}, cache.search('#single:=b,a,c'))
self.assertEqual(set(), cache.search('#single:=b'))
# Test numeric sorting
cache.set_field('#float', {1:2, 2:10, 3:0.0001})
self.assertEqual([3, 1, 2], cache.multisort([('#number', True)]))
cache.set_field('#float', {1:3, 2:2*1024, 3:1*1024*1024})
self.assertEqual([1, 2, 3], cache.multisort([('#size', True)]))
# Test date sorting
cache.set_field('pubdate', {1:p('2001-02-06'), 2:p('2001-10-06'), 3:p('2001-06-06')})
self.assertEqual([1, 3, 2], cache.multisort([('#ccdate', True)]))
# Test bool sorting
self.assertEqual([2, 1, 3], cache.multisort([('#bool', True)]))
# Test is_multiple sorting
cache.set_field('#tags', {1:'b, a, c', 2:'a, b, c', 3:'a, c, b'})
self.assertEqual([1, 2, 3], cache.multisort([('#ccm', True)]))
# Test that lock downgrading during update of search cache works
self.assertEqual(cache.search('#ccp:One'), {2})
cache.set_field('publisher', {2:'One', 1:'One'})
self.assertEqual(cache.search('#ccp:One'), {1, 2})
self.assertEqual(cache.search('#ccf:FMT1'), {1, 2})
cache.remove_formats({1:('FMT1',)})
self.assertEqual('FMT2', cache.field_for('#ccf', 1))
# }}}
def test_find_identical_books(self): # {{{
' Test find_identical_books '
from calibre.db.utils import find_identical_books
from calibre.ebooks.metadata.book.base import Metadata
# 'find_identical_books': [(,), (Metadata('unknown'),), (Metadata('xxxx'),)],
cache = self.init_cache(self.library_path)
cache.set_field('languages', {1: ('fra', 'deu')})
data = cache.data_for_find_identical_books()
lm = cache.get_metadata(1)
lm2 = cache.get_metadata(1)
lm2.languages = ['eng']
for mi, books in (
(Metadata('title one', ['author one']), {2}),
(Metadata('Unknown', ['Unknown']), {3}),
(Metadata('title two', ['author one']), {1}),
(lm, {1}),
(lm2, set()),
):
self.assertEqual(books, cache.find_identical_books(mi))
self.assertEqual(books, find_identical_books(mi, data))
# }}}
def test_last_read_positions(self): # {{{
cache = self.init_cache(self.library_path)
self.assertFalse(cache.get_last_read_positions(1, 'x', 'u'))
self.assertRaises(Exception, cache.set_last_read_position, 12, 'x', cfi='c')
epoch = time()
cache.set_last_read_position(1, 'EPUB', 'user', 'device', 'cFi', epoch, 0.3)
self.assertFalse(cache.get_last_read_positions(1, 'x', 'u'))
self.assertEqual(cache.get_last_read_positions(1, 'ePuB', 'user'), [{'epoch':epoch, 'device':'device', 'cfi':'cFi', 'pos_frac':0.3}])
cache.set_last_read_position(1, 'EPUB', 'user', 'device')
self.assertFalse(cache.get_last_read_positions(1, 'ePuB', 'user'))
# }}}
def test_storing_conversion_options(self): # {{{
cache = self.init_cache(self.library_path)
opts = {1: b'binary', 2: 'unicode'}
cache.set_conversion_options(opts, 'PIPE')
for book_id, val in iteritems(opts):
got = cache.conversion_options(book_id, 'PIPE')
if not isinstance(val, bytes):
val = val.encode('utf-8')
self.assertEqual(got, val)
# }}}
def test_template_db_functions(self): # {{{
from calibre.ebooks.metadata.book.formatter import SafeFormat
formatter = SafeFormat()
db = self.init_cache(self.library_path)
db.create_custom_column('mult', 'CC1', 'composite', True, display={'composite_template': 'b,a,c'})
# need an empty metadata object to pass to the formatter
db = self.init_legacy(self.library_path)
mi = db.get_metadata(1)
# test counting books matching the search
v = formatter.safe_format('program: book_count("series:true", 0)', {}, 'TEMPLATE ERROR', mi)
self.assertEqual(v, '2')
# test counting books when none match the search
v = formatter.safe_format('program: book_count("series:afafaf", 0)', {}, 'TEMPLATE ERROR', mi)
self.assertEqual(v, '0')
# test is_multiple values
v = formatter.safe_format('program: book_values("tags", "tags:true", ",", 0)', {}, 'TEMPLATE ERROR', mi)
self.assertEqual(set(v.split(',')), {'Tag One', 'News', 'Tag Two'})
# test not is_multiple values
v = formatter.safe_format('program: book_values("series", "series:true", ",", 0)', {}, 'TEMPLATE ERROR', mi)
self.assertEqual(v, 'A Series One')
# test returning values for a column not searched for
v = formatter.safe_format('program: book_values("tags", "series:\\"A Series One\\"", ",", 0)', {}, 'TEMPLATE ERROR', mi)
self.assertEqual(set(v.split(',')), {'Tag One', 'News', 'Tag Two'})
# test getting a singleton value from books where the column is empty
v = formatter.safe_format('program: book_values("series", "series:false", ",", 0)', {}, 'TEMPLATE ERROR', mi)
self.assertEqual(v, '')
# test getting a multiple value from books where the column is empty
v = formatter.safe_format('program: book_values("tags", "tags:false", ",", 0)', {}, 'TEMPLATE ERROR', mi)
self.assertEqual(v, '')
# test fetching an unknown column
v = formatter.safe_format('program: book_values("taaags", "tags:false", ",", 0)', {}, 'TEMPLATE ERROR', mi)
self.assertEqual(v, "TEMPLATE ERROR The column taaags doesn't exist")
# test finding all books
v = formatter.safe_format('program: book_values("id", "title:true", ",", 0)', {}, 'TEMPLATE ERROR', mi)
self.assertEqual(set(v.split(',')), {'1', '2', '3'})
# test getting value of a composite
v = formatter.safe_format('program: book_values("#mult", "id:1", ",", 0)', {}, 'TEMPLATE ERROR', mi)
self.assertEqual(set(v.split(',')), {'b', 'c', 'a'})
# test getting value of a custom float
v = formatter.safe_format('program: book_values("#float", "title:true", ",", 0)', {}, 'TEMPLATE ERROR', mi)
self.assertEqual(set(v.split(',')), {'20.02', '10.01'})
# test getting value of an int (rating)
v = formatter.safe_format('program: book_values("rating", "title:true", ",", 0)', {}, 'TEMPLATE ERROR', mi)
self.assertEqual(set(v.split(',')), {'4', '6'})
# }}}
def test_python_templates(self): # {{{
from calibre.ebooks.metadata.book.formatter import SafeFormat
formatter = SafeFormat()
# need an empty metadata object to pass to the formatter
db = self.init_legacy(self.library_path)
mi = db.get_metadata(1)
# test counting books matching a search
template = '''python:
def evaluate(book, ctx):
ids = ctx.db.new_api.search("series:true")
return str(len(ids))
'''
v = formatter.safe_format(template, {}, 'TEMPLATE ERROR', mi)
self.assertEqual(v, '2')
# test counting books when none match the search
template = '''python:
def evaluate(book, ctx):
ids = ctx.db.new_api.search("series:afafaf")
return str(len(ids))
'''
v = formatter.safe_format(template, {}, 'TEMPLATE ERROR', mi)
self.assertEqual(v, '0')
# test is_multiple values
template = '''python:
def evaluate(book, ctx):
tags = ctx.db.new_api.all_field_names('tags')
return ','.join(list(tags))
'''
v = formatter.safe_format(template, {}, 'TEMPLATE ERROR', mi)
self.assertEqual(set(v.split(',')), {'Tag One', 'News', 'Tag Two'})
# test using a custom context class
template = '''python:
def evaluate(book, ctx):
tags = ctx.db.new_api.all_field_names('tags')
return ','.join(list(ctx.helper_function(tags)))
'''
from calibre.utils.formatter import PythonTemplateContext
class CustomContext(PythonTemplateContext):
def helper_function(self, arg):
s = set(arg)
s.add('helper called')
return s
v = formatter.safe_format(template, {}, 'TEMPLATE ERROR', mi,
python_context_object=CustomContext())
self.assertEqual(set(v.split(',')), {'Tag One', 'News', 'Tag Two','helper called'})
# test is_multiple values
template = '''python:
def evaluate(book, ctx):
tags = ctx.db.new_api.all_field_names('tags')
return ','.join(list(tags))
'''
v = formatter.safe_format(template, {}, 'TEMPLATE ERROR', mi)
self.assertEqual(set(v.split(',')), {'Tag One', 'News', 'Tag Two'})
# test calling a python stored template from a GPM template
from calibre.utils.formatter_functions import load_user_template_functions, unload_user_template_functions
load_user_template_functions('aaaaa',
[['python_stored_template',
"",
0,
'''python:
def evaluate(book, ctx):
tags = set(ctx.db.new_api.all_field_names('tags'))
tags.add(ctx.arguments[0])
return ','.join(list(tags))
'''
]], None)
v = formatter.safe_format('program: python_stored_template("one argument")', {},
'TEMPLATE ERROR', mi)
unload_user_template_functions('aaaaa')
self.assertEqual(set(v.split(',')), {'Tag One', 'News', 'Tag Two', 'one argument'})
# }}}
| 44,816 | Python | .py | 839 | 40.922527 | 157 | 0.548002 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,082 | locking.py | kovidgoyal_calibre/src/calibre/db/tests/locking.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import random
import time
from threading import Thread
from calibre.db.locking import LockingError, RWLockWrapper, SHLock
from calibre.db.tests.base import BaseTest
def wait_for(period):
# time.sleep() is not useful for very small values on windows because the
# default timer has a resolutions of about 16ms see
# https://stackoverflow.com/questions/40594587/why-time-sleep-is-so-slow-in-windows
deadline = time.perf_counter() + period
while time.perf_counter() < deadline:
pass
class TestLock(BaseTest):
"""Tests for db locking """
def test_owns_locks(self):
lock = SHLock()
self.assertFalse(lock.owns_lock())
lock.acquire(shared=True)
self.assertTrue(lock.owns_lock())
lock.release()
self.assertFalse(lock.owns_lock())
lock.acquire(shared=False)
self.assertTrue(lock.owns_lock())
lock.release()
self.assertFalse(lock.owns_lock())
done = []
def test():
if not lock.owns_lock():
done.append(True)
lock.acquire()
t = Thread(target=test)
t.daemon = True
t.start()
t.join(1)
self.assertEqual(len(done), 1)
lock.release()
def test_multithread_deadlock(self):
lock = SHLock()
def two_shared():
r = RWLockWrapper(lock)
with r:
time.sleep(0.2)
with r:
pass
def one_exclusive():
time.sleep(0.1)
w = RWLockWrapper(lock, is_shared=False)
with w:
pass
threads = [Thread(target=two_shared), Thread(target=one_exclusive)]
for t in threads:
t.daemon = True
t.start()
for t in threads:
t.join(5)
live = [t for t in threads if t.is_alive()]
self.assertListEqual(live, [], 'ShLock hung')
def test_upgrade(self):
lock = SHLock()
lock.acquire(shared=True)
self.assertRaises(LockingError, lock.acquire, shared=False)
lock.release()
def test_downgrade(self):
lock = SHLock()
lock.acquire(shared=False)
self.assertRaises(LockingError, lock.acquire, shared=True)
lock.release()
def test_recursive(self):
lock = SHLock()
lock.acquire(shared=True)
lock.acquire(shared=True)
self.assertEqual(lock.is_shared, 2)
lock.release()
lock.release()
self.assertFalse(lock.is_shared)
lock.acquire(shared=False)
lock.acquire(shared=False)
self.assertEqual(lock.is_exclusive, 2)
lock.release()
lock.release()
self.assertFalse(lock.is_exclusive)
def test_release(self):
lock = SHLock()
self.assertRaises(LockingError, lock.release)
def get_lock(shared):
lock.acquire(shared=shared)
time.sleep(1)
lock.release()
threads = [Thread(target=get_lock, args=(x,)) for x in (True,
False)]
for t in threads:
t.daemon = True
t.start()
self.assertRaises(LockingError, lock.release)
t.join(15)
self.assertFalse(t.is_alive())
self.assertFalse(lock.is_shared)
self.assertFalse(lock.is_exclusive)
def test_acquire(self):
lock = SHLock()
def get_lock(shared):
lock.acquire(shared=shared)
time.sleep(1)
lock.release()
shared = Thread(target=get_lock, args=(True,))
shared.daemon = True
shared.start()
time.sleep(0.1)
self.assertTrue(lock.acquire(shared=True, blocking=False))
lock.release()
self.assertFalse(lock.acquire(shared=False, blocking=False))
lock.acquire(shared=False)
shared.join(1)
self.assertFalse(shared.is_alive())
lock.release()
self.assertTrue(lock.acquire(shared=False, blocking=False))
lock.release()
exclusive = Thread(target=get_lock, args=(False,))
exclusive.daemon = True
exclusive.start()
time.sleep(0.1)
self.assertFalse(lock.acquire(shared=False, blocking=False))
self.assertFalse(lock.acquire(shared=True, blocking=False))
lock.acquire(shared=True)
exclusive.join(1)
self.assertFalse(exclusive.is_alive())
lock.release()
lock.acquire(shared=False)
lock.release()
lock.acquire(shared=True)
lock.release()
self.assertFalse(lock.is_shared)
self.assertFalse(lock.is_exclusive)
def test_contention(self):
lock = SHLock()
done = []
def lots_of_acquires():
for _ in range(1000):
shared = random.choice([True,False])
lock.acquire(shared=shared)
lock.acquire(shared=shared)
wait_for(random.random() * 0.0001)
lock.release()
wait_for(random.random() * 0.0001)
lock.acquire(shared=shared)
wait_for(random.random() * 0.0001)
lock.release()
lock.release()
done.append(True)
threads = [Thread(target=lots_of_acquires) for _ in range(2)]
for t in threads:
t.daemon = True
t.start()
end_at = time.monotonic() + 20
for t in threads:
left = end_at - time.monotonic()
if left <= 0:
break
t.join(left)
live = [t for t in threads if t.is_alive()]
self.assertEqual(len(live), 0, f'ShLock hung or very slow, {len(live)} threads alive')
self.assertEqual(len(done), len(threads), 'SHLock locking failed')
self.assertFalse(lock.is_shared)
self.assertFalse(lock.is_exclusive)
def find_tests():
import unittest
return unittest.defaultTestLoader.loadTestsFromTestCase(TestLock)
def run_tests():
from calibre.utils.run_tests import run_tests
run_tests(find_tests)
| 6,203 | Python | .py | 173 | 26.242775 | 94 | 0.592667 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,083 | profiling.py | kovidgoyal_calibre/src/calibre/db/tests/profiling.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import cProfile
import os
from tempfile import gettempdir
from calibre.db.legacy import LibraryDatabase
db = None
def initdb(path):
global db
db = LibraryDatabase(os.path.expanduser(path))
def show_stats(path):
from pstats import Stats
s = Stats(path)
s.sort_stats('cumulative')
s.print_stats(30)
def main():
stats = os.path.join(gettempdir(), 'read_db.stats')
pr = cProfile.Profile()
initdb('~/test library')
all_ids = db.new_api.all_book_ids() # noqa
pr.enable()
for book_id in all_ids:
db.new_api._composite_for('#isbn', book_id)
db.new_api._composite_for('#formats', book_id)
pr.disable()
pr.dump_stats(stats)
show_stats(stats)
print('Stats saved to', stats)
if __name__ == '__main__':
main()
| 902 | Python | .py | 31 | 24.967742 | 61 | 0.666667 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,084 | legacy.py | kovidgoyal_calibre/src/calibre/db/tests/legacy.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import inspect
import numbers
import time
from functools import partial
from io import BytesIO
from operator import itemgetter
from calibre.db.constants import NOTES_DIR_NAME
from calibre.db.tests.base import BaseTest
from calibre.library.field_metadata import fm_as_dict
from polyglot import reprlib
from polyglot.builtins import iteritems
# Utils {{{
class ET:
def __init__(self, func_name, args, kwargs={}, old=None, legacy=None):
self.func_name = func_name
self.args, self.kwargs = args, kwargs
self.old, self.legacy = old, legacy
def __call__(self, test):
old = self.old or test.init_old(test.cloned_library)
legacy = self.legacy or test.init_legacy(test.cloned_library)
oldres = getattr(old, self.func_name)(*self.args, **self.kwargs)
newres = getattr(legacy, self.func_name)(*self.args, **self.kwargs)
test.assertEqual(oldres, newres, 'Equivalence test for {} with args: {} and kwargs: {} failed'.format(
self.func_name, reprlib.repr(self.args), reprlib.repr(self.kwargs)))
self.retval = newres
return newres
def get_defaults(spec):
num = len(spec.defaults or ())
if not num:
return {}
return dict(zip(spec.args[-num:], spec.defaults))
def compare_argspecs(old, new, attr):
# We dont compare the names of the non-keyword arguments as they are often
# different and they dont affect the usage of the API.
ok = len(old.args) == len(new.args) and get_defaults(old) == get_defaults(new)
if not ok:
raise AssertionError(f'The argspec for {attr} does not match. {old!r} != {new!r}')
def run_funcs(self, db, ndb, funcs):
for func in funcs:
meth, args = func[0], func[1:]
if callable(meth):
meth(*args)
else:
if meth[0] in {'!', '@', '#', '+', '$', '-', '%'}:
if meth[0] != '+':
fmt = {'!':dict, '@':lambda x:frozenset(x or ()), '#':lambda x:set((x or '').split(',')),
'$':lambda x:{tuple(y) for y in x}, '-':lambda x:None,
'%':lambda x: set((x or '').split(','))}[meth[0]]
else:
fmt = args[-1]
args = args[:-1]
meth = meth[1:]
else:
def fmt(x):
return x
res1, res2 = fmt(getattr(db, meth)(*args)), fmt(getattr(ndb, meth)(*args))
self.assertEqual(res1, res2, f'The method: {meth}() returned different results for argument {args}')
# }}}
class LegacyTest(BaseTest):
''' Test the emulation of the legacy interface. '''
def test_library_wide_properties(self): # {{{
'Test library wide properties'
def to_unicode(x):
if isinstance(x, bytes):
return x.decode('utf-8')
if isinstance(x, dict):
# We ignore the key rec_index, since it is not stable for
# custom columns (it is created by iterating over a dict)
return {k.decode('utf-8') if isinstance(k, bytes) else k:to_unicode(v)
for k, v in iteritems(x) if k != 'rec_index'}
return x
def get_props(db):
props = ('user_version', 'is_second_db', 'library_id',
'custom_column_label_map', 'custom_column_num_map', 'library_path', 'dbpath')
fprops = ('last_modified', )
ans = {x:getattr(db, x) for x in props}
ans.update({x:getattr(db, x)() for x in fprops})
ans['all_ids'] = frozenset(db.all_ids())
ans['field_metadata'] = fm_as_dict(db.field_metadata)
return to_unicode(ans)
old = self.init_old()
oldvals = get_props(old)
old.close()
del old
db = self.init_legacy()
newvals = get_props(db)
self.assertEqual(oldvals, newvals)
db.close()
# }}}
def test_get_property(self): # {{{
'Test the get_property interface for reading data'
def get_values(db):
ans = {}
for label, loc in iteritems(db.FIELD_MAP):
if isinstance(label, numbers.Integral):
label = '#'+db.custom_column_num_map[label]['label']
label = str(label)
ans[label] = tuple(db.get_property(i, index_is_id=True, loc=loc)
for i in db.all_ids())
if label in ('id', 'title', '#tags'):
with self.assertRaises(IndexError):
db.get_property(9999, loc=loc)
with self.assertRaises(IndexError):
db.get_property(9999, index_is_id=True, loc=loc)
if label in {'tags', 'formats'}:
# Order is random in the old db for these
ans[label] = tuple(set(x.split(',')) if x else x for x in ans[label])
if label == 'series_sort':
# The old db code did not take book language into account
# when generating series_sort values
ans[label] = None
return ans
db = self.init_legacy()
new_vals = get_values(db)
db.close()
old = self.init_old()
old_vals = get_values(old)
old.close()
old = None
self.assertEqual(old_vals, new_vals)
# }}}
def test_refresh(self): # {{{
' Test refreshing the view after a change to metadata.db '
db = self.init_legacy()
db2 = self.init_legacy()
# Ensure that the following change will actually update the timestamp
# on filesystems with one second resolution (OS X)
time.sleep(1)
self.assertEqual(db2.data.cache.set_field('title', {1:'xxx'}), {1})
db2.close()
del db2
self.assertNotEqual(db.title(1, index_is_id=True), 'xxx')
db.check_if_modified()
self.assertEqual(db.title(1, index_is_id=True), 'xxx')
# }}}
def test_legacy_getters(self): # {{{
' Test various functions to get individual bits of metadata '
old = self.init_old()
getters = ('path', 'abspath', 'title', 'title_sort', 'authors', 'series',
'publisher', 'author_sort', 'authors', 'comments',
'comment', 'publisher', 'rating', 'series_index', 'tags',
'timestamp', 'uuid', 'pubdate', 'ondevice',
'metadata_last_modified', 'languages')
oldvals = {g:tuple(getattr(old, g)(x) for x in range(3)) + tuple(getattr(old, g)(x, True) for x in (1,2,3)) for g in getters}
old_rows = {tuple(r)[:5] for r in old}
old.close()
db = self.init_legacy()
newvals = {g:tuple(getattr(db, g)(x) for x in range(3)) + tuple(getattr(db, g)(x, True) for x in (1,2,3)) for g in getters}
new_rows = {tuple(r)[:5] for r in db}
for x in (oldvals, newvals):
x['tags'] = tuple(set(y.split(',')) if y else y for y in x['tags'])
self.assertEqual(oldvals, newvals)
self.assertEqual(old_rows, new_rows)
# }}}
def test_legacy_direct(self): # {{{
'Test read-only methods that are directly equivalent in the old and new interface'
from datetime import timedelta
from calibre.ebooks.metadata.book.base import Metadata
ndb = self.init_legacy(self.cloned_library)
db = self.init_old()
newstag = ndb.new_api.get_item_id('tags', 'news')
self.assertEqual(dict(db.prefs), dict(ndb.prefs))
for meth, args in iteritems({
'find_identical_books': [(Metadata('title one', ['author one']),), (Metadata('unknown'),), (Metadata('xxxx'),)],
'get_books_for_category': [('tags', newstag), ('#formats', 'FMT1')],
'get_next_series_num_for': [('A Series One',)],
'get_id_from_uuid':[('ddddd',), (db.uuid(1, True),)],
'cover':[(0,), (1,), (2,)],
'get_author_id': [('author one',), ('unknown',), ('xxxxx',)],
'series_id': [(0,), (1,), (2,)],
'publisher_id': [(0,), (1,), (2,)],
'@tags_older_than': [
('News', None), ('Tag One', None), ('xxxx', None), ('Tag One', None, 'News'), ('News', None, 'xxxx'),
('News', None, None, ['xxxxxxx']), ('News', None, 'Tag One', ['Author Two', 'Author One']),
('News', timedelta(0), None, None), ('News', timedelta(100000)),
],
'format':[(1, 'FMT1', True), (2, 'FMT1', True), (0, 'xxxxxx')],
'has_format':[(1, 'FMT1', True), (2, 'FMT1', True), (0, 'xxxxxx')],
'sizeof_format':[(1, 'FMT1', True), (2, 'FMT1', True), (0, 'xxxxxx')],
'@format_files':[(0,),(1,),(2,)],
'formats':[(0,),(1,),(2,)],
'max_size':[(0,),(1,),(2,)],
'format_hash':[(1, 'FMT1'),(1, 'FMT2'), (2, 'FMT1')],
'author_sort_from_authors': [(['Author One', 'Author Two', 'Unknown'],)],
'has_book':[(Metadata('title one'),), (Metadata('xxxx1111'),)],
'has_id':[(1,), (2,), (3,), (9999,)],
'id':[(1,), (2,), (0,),],
'index':[(1,), (2,), (3,), ],
'row':[(1,), (2,), (3,), ],
'is_empty':[()],
'count':[()],
'all_author_names':[()],
'all_tag_names':[()],
'all_series_names':[()],
'all_publisher_names':[()],
'!all_authors':[()],
'!all_tags2':[()],
'@all_tags':[()],
'@get_all_identifier_types':[()],
'!all_publishers':[()],
'!all_titles':[()],
'!all_series':[()],
'standard_field_keys':[()],
'all_field_keys':[()],
'searchable_fields':[()],
'search_term_to_field_key':[('author',), ('tag',)],
'metadata_for_field':[('title',), ('tags',)],
'sortable_field_keys':[()],
'custom_field_keys':[(True,), (False,)],
'!get_usage_count_by_id':[('authors',), ('tags',), ('series',), ('publisher',), ('#tags',), ('languages',)],
'get_field':[(1, 'title'), (2, 'tags'), (0, 'rating'), (1, 'authors'), (2, 'series'), (1, '#tags')],
'all_formats':[()],
'get_authors_with_ids':[()],
'!get_tags_with_ids':[()],
'!get_series_with_ids':[()],
'!get_publishers_with_ids':[()],
'!get_ratings_with_ids':[()],
'!get_languages_with_ids':[()],
'tag_name':[(3,)],
'author_name':[(3,)],
'series_name':[(3,)],
'authors_sort_strings':[(0,), (1,), (2,)],
'author_sort_from_book':[(0,), (1,), (2,)],
'authors_with_sort_strings':[(0,), (1,), (2,)],
'book_on_device_string':[(1,), (2,), (3,)],
'books_in_series_of':[(0,), (1,), (2,)],
'books_with_same_title':[(Metadata(db.title(0)),), (Metadata(db.title(1)),), (Metadata('1234'),)],
}):
if meth[0] in {'!', '@'}:
fmt = {'!':dict, '@':frozenset}[meth[0]]
meth = meth[1:]
elif meth == 'get_authors_with_ids':
def fmt(val):
return {x[0]: tuple(x[1:]) for x in val}
else:
def fmt(x):
return x
for a in args:
self.assertEqual(fmt(getattr(db, meth)(*a)), fmt(getattr(ndb, meth)(*a)),
f'The method: {meth}() returned different results for argument {a}')
def f(x, y): # get_top_level_move_items is broken in the old db on case-insensitive file systems
x.discard('metadata_db_prefs_backup.json')
y.pop('full-text-search.db', None)
x.discard(NOTES_DIR_NAME)
y.pop(NOTES_DIR_NAME, None)
return x, y
self.assertEqual(f(*db.get_top_level_move_items()), f(*ndb.get_top_level_move_items()))
d1, d2 = BytesIO(), BytesIO()
db.copy_cover_to(1, d1, True)
ndb.copy_cover_to(1, d2, True)
self.assertTrue(d1.getvalue() == d2.getvalue())
d1, d2 = BytesIO(), BytesIO()
db.copy_format_to(1, 'FMT1', d1, True)
ndb.copy_format_to(1, 'FMT1', d2, True)
self.assertTrue(d1.getvalue() == d2.getvalue())
old = db.get_data_as_dict(prefix='test-prefix')
new = ndb.get_data_as_dict(prefix='test-prefix')
for o, n in zip(old, new):
o = {str(k) if isinstance(k, bytes) else k:set(v) if isinstance(v, list) else v for k, v in iteritems(o)}
n = {k:set(v) if isinstance(v, list) else v for k, v in iteritems(n)}
self.assertEqual(o, n)
ndb.search('title:Unknown')
db.search('title:Unknown')
self.assertEqual(db.row(3), ndb.row(3))
self.assertRaises(ValueError, ndb.row, 2)
self.assertRaises(ValueError, db.row, 2)
db.close()
# }}}
def test_legacy_conversion_options(self): # {{{
'Test conversion options API'
ndb = self.init_legacy()
db = self.init_old()
all_ids = ndb.new_api.all_book_ids()
op1 = {'xx': 'yy'}
def decode(x):
if isinstance(x, bytes):
x = x.decode('utf-8')
return x
for x in (
('has_conversion_options', all_ids),
('conversion_options', 1, 'PIPE'),
('set_conversion_options', 1, 'PIPE', op1),
('has_conversion_options', all_ids),
('conversion_options', 1, 'PIPE'),
('delete_conversion_options', 1, 'PIPE'),
('has_conversion_options', all_ids),
):
meth, args = x[0], x[1:]
self.assertEqual(
decode(getattr(db, meth)(*args)), decode(getattr(ndb, meth)(*args)),
f'The method: {meth}() returned different results for argument {args}'
)
db.close()
# }}}
def test_legacy_delete_using(self): # {{{
'Test delete_using() API'
ndb = self.init_legacy()
db = self.init_old()
cache = ndb.new_api
tmap = cache.get_id_map('tags')
t = next(iter(tmap))
pmap = cache.get_id_map('publisher')
p = next(iter(pmap))
run_funcs(self, db, ndb, (
('delete_tag_using_id', t),
('delete_publisher_using_id', p),
(db.refresh,),
('all_tag_names',), ('tags', 0), ('tags', 1), ('tags', 2),
('all_publisher_names',), ('publisher', 0), ('publisher', 1), ('publisher', 2),
))
db.close()
# }}}
def test_legacy_adding_books(self): # {{{
'Test various adding/deleting books methods'
import sqlite3
con = sqlite3.connect(":memory:")
try:
con.execute("create virtual table recipe using fts5(name, ingredients)")
except Exception:
self.skipTest('python sqlite3 module does not have FTS5 support')
con.close()
del con
from calibre.ebooks.metadata.book.base import Metadata
from calibre.ptempfile import TemporaryFile
legacy, old = self.init_legacy(self.cloned_library), self.init_old(self.cloned_library)
mi = Metadata('Added Book0', authors=('Added Author',))
with TemporaryFile(suffix='.aff') as name:
with open(name, 'wb') as f:
f.write(b'xxx')
T = partial(ET, 'add_books', ([name], ['AFF'], [mi]), old=old, legacy=legacy)
T()(self)
book_id = T(kwargs={'return_ids':True})(self)[1][0]
self.assertEqual(legacy.new_api.formats(book_id), ('AFF',))
T(kwargs={'add_duplicates':False})(self)
mi.title = 'Added Book1'
mi.uuid = 'uuu'
T = partial(ET, 'import_book', (mi,[name]), old=old, legacy=legacy)
book_id = T()(self)
self.assertNotEqual(legacy.uuid(book_id, index_is_id=True), old.uuid(book_id, index_is_id=True))
book_id = T(kwargs={'preserve_uuid':True})(self)
self.assertEqual(legacy.uuid(book_id, index_is_id=True), old.uuid(book_id, index_is_id=True))
self.assertEqual(legacy.new_api.formats(book_id), ('AFF',))
T = partial(ET, 'add_format', old=old, legacy=legacy)
T((0, 'AFF', BytesIO(b'fffff')))(self)
T((0, 'AFF', BytesIO(b'fffff')))(self)
T((0, 'AFF', BytesIO(b'fffff')), {'replace':True})(self)
with TemporaryFile(suffix='.opf') as name:
with open(name, 'wb') as f:
f.write(b'zzzz')
T = partial(ET, 'import_book', (mi,[name]), old=old, legacy=legacy)
book_id = T()(self)
self.assertFalse(legacy.new_api.formats(book_id))
mi.title = 'Added Book2'
T = partial(ET, 'create_book_entry', (mi,), old=old, legacy=legacy)
T()
T({'add_duplicates':False})
T({'force_id':1000})
with TemporaryFile(suffix='.txt') as name:
with open(name, 'wb') as f:
f.write(b'tttttt')
bid = legacy.add_catalog(name, 'My Catalog')
self.assertEqual(old.add_catalog(name, 'My Catalog'), bid)
cache = legacy.new_api
self.assertEqual(cache.formats(bid), ('TXT',))
self.assertEqual(cache.field_for('title', bid), 'My Catalog')
self.assertEqual(cache.field_for('authors', bid), ('calibre',))
self.assertEqual(cache.field_for('tags', bid), (_('Catalog'),))
self.assertTrue(bid < legacy.add_catalog(name, 'Something else'))
self.assertEqual(legacy.add_catalog(name, 'My Catalog'), bid)
self.assertEqual(old.add_catalog(name, 'My Catalog'), bid)
bid = legacy.add_news(name, {'title':'Events', 'add_title_tag':True, 'custom_tags':('one', 'two')})
self.assertEqual(cache.formats(bid), ('TXT',))
self.assertEqual(cache.field_for('authors', bid), ('calibre',))
self.assertEqual(cache.field_for('tags', bid), (_('News'), 'Events', 'one', 'two'))
self.assertTrue(legacy.cover(1, index_is_id=True))
origcov = legacy.cover(1, index_is_id=True)
self.assertTrue(legacy.has_cover(1))
legacy.remove_cover(1)
self.assertFalse(legacy.has_cover(1))
self.assertFalse(legacy.cover(1, index_is_id=True))
legacy.set_cover(3, origcov)
self.assertEqual(legacy.cover(3, index_is_id=True), origcov)
self.assertTrue(legacy.has_cover(3))
self.assertTrue(legacy.format(1, 'FMT1', index_is_id=True))
legacy.remove_format(1, 'FMT1', index_is_id=True)
self.assertIsNone(legacy.format(1, 'FMT1', index_is_id=True))
legacy.delete_book(1)
old.delete_book(1)
self.assertNotIn(1, legacy.all_ids())
legacy.dump_metadata((2,3))
old.close()
# }}}
def test_legacy_coverage(self): # {{{
' Check that the emulation of the legacy interface is (almost) total '
cl = self.cloned_library
db = self.init_old(cl)
ndb = self.init_legacy()
SKIP_ATTRS = {
'TCat_Tag', '_add_newbook_tag', '_clean_identifier', '_library_id_', '_set_authors',
'_set_title', '_set_custom', '_update_author_in_cache',
# Feeds are now stored in the config folder
'get_feeds', 'get_feed', 'update_feed', 'remove_feeds', 'add_feed', 'set_feeds',
# Obsolete/broken methods
'author_id', # replaced by get_author_id
'books_for_author', # broken
'books_in_old_database', 'sizeof_old_database', # unused
'migrate_old', # no longer supported
'remove_unused_series', # superseded by clean API
'move_library_to', # API changed, no code uses old API
# Added compiled_rules() for calibredb add
'find_books_in_directory', 'import_book_directory', 'import_book_directory_multiple', 'recursive_import',
# Internal API
'clean_user_categories', 'cleanup_tags', 'books_list_filter', 'conn', 'connect', 'construct_file_name',
'construct_path_name', 'clear_dirtied', 'initialize_database', 'initialize_dynamic',
'run_import_plugins', 'vacuum', 'set_path', 'row_factory', 'rows', 'rmtree', 'series_index_pat',
'import_old_database', 'dirtied_lock', 'dirtied_cache', 'dirty_books_referencing',
'windows_check_if_files_in_use', 'get_metadata_for_dump', 'get_a_dirtied_book', 'dirtied_sequence',
'format_filename_cache', 'format_metadata_cache', 'filter', 'create_version1', 'normpath', 'custom_data_adapters',
'custom_table_names', 'custom_columns_in_meta', 'custom_tables',
}
SKIP_ARGSPEC = {
'__init__',
}
missing = []
try:
total = 0
for attr in dir(db):
if attr in SKIP_ATTRS or attr.startswith('upgrade_version'):
continue
total += 1
if not hasattr(ndb, attr):
missing.append(attr)
continue
obj, nobj = getattr(db, attr), getattr(ndb, attr)
if attr not in SKIP_ARGSPEC:
try:
argspec = inspect.getfullargspec(obj)
nargspec = inspect.getfullargspec(nobj)
except (TypeError, ValueError):
pass
else:
compare_argspecs(argspec, nargspec, attr)
finally:
for db in (ndb, db):
db.close()
db.break_cycles()
if missing:
pc = len(missing)/total
raise AssertionError('{0:.1%} of API ({2} attrs) are missing: {1}'.format(pc, ', '.join(missing), len(missing)))
# }}}
def test_legacy_custom_data(self): # {{{
'Test the API for custom data storage'
legacy, old = self.init_legacy(self.cloned_library), self.init_old(self.cloned_library)
for name in ('name1', 'name2', 'name3'):
T = partial(ET, 'add_custom_book_data', old=old, legacy=legacy)
T((1, name, 'val1'))(self)
T((2, name, 'val2'))(self)
T((3, name, 'val3'))(self)
T = partial(ET, 'get_ids_for_custom_book_data', old=old, legacy=legacy)
T((name,))(self)
T = partial(ET, 'get_custom_book_data', old=old, legacy=legacy)
T((1, name, object()))
T((9, name, object()))
T = partial(ET, 'get_all_custom_book_data', old=old, legacy=legacy)
T((name, object()))
T((name+'!', object()))
T = partial(ET, 'delete_custom_book_data', old=old, legacy=legacy)
T((name, 1))
T = partial(ET, 'get_all_custom_book_data', old=old, legacy=legacy)
T((name, object()))
T = partial(ET, 'delete_all_custom_book_data', old=old, legacy=legacy)
T(name)
T = partial(ET, 'get_all_custom_book_data', old=old, legacy=legacy)
T((name, object()))
T = partial(ET, 'add_multiple_custom_book_data', old=old, legacy=legacy)
T(('n', {1:'val1', 2:'val2'}))(self)
T = partial(ET, 'get_all_custom_book_data', old=old, legacy=legacy)
T(('n', object()))
old.close()
# }}}
def test_legacy_setters(self): # {{{
'Test methods that are directly equivalent in the old and new interface'
from calibre.ebooks.metadata.book.base import Metadata
from calibre.utils.date import now
n = now()
ndb = self.init_legacy(self.cloned_library)
amap = ndb.new_api.get_id_map('authors')
sorts = [(aid, 's%d' % aid) for aid in amap]
db = self.init_old(self.cloned_library)
run_funcs(self, db, ndb, (
('+format_metadata', 1, 'FMT1', itemgetter('size')),
('+format_metadata', 1, 'FMT2', itemgetter('size')),
('+format_metadata', 2, 'FMT1', itemgetter('size')),
('get_tags', 0), ('get_tags', 1), ('get_tags', 2),
('is_tag_used', 'News'), ('is_tag_used', 'xchkjgfh'),
('bulk_modify_tags', (1,), ['t1'], ['News']),
('bulk_modify_tags', (2,), ['t1'], ['Tag One', 'Tag Two']),
('bulk_modify_tags', (3,), ['t1', 't2', 't3']),
(db.clean,),
('@all_tags',),
('@tags', 0), ('@tags', 1), ('@tags', 2),
('unapply_tags', 1, ['t1']),
('unapply_tags', 2, ['xxxx']),
('unapply_tags', 3, ['t2', 't3']),
(db.clean,),
('@all_tags',),
('@tags', 0), ('@tags', 1), ('@tags', 2),
('update_last_modified', (1,), True, n), ('update_last_modified', (3,), True, n),
('metadata_last_modified', 1, True), ('metadata_last_modified', 3, True),
('set_sort_field_for_author', sorts[0][0], sorts[0][1]),
('set_sort_field_for_author', sorts[1][0], sorts[1][1]),
('set_sort_field_for_author', sorts[2][0], sorts[2][1]),
('set_link_field_for_author', sorts[0][0], sorts[0][1]),
('set_link_field_for_author', sorts[1][0], sorts[1][1]),
('set_link_field_for_author', sorts[2][0], sorts[2][1]),
(db.refresh,),
('author_sort', 0), ('author_sort', 1), ('author_sort', 2),
))
omi = [db.get_metadata(x) for x in (0, 1, 2)]
nmi = [ndb.get_metadata(x) for x in (0, 1, 2)]
self.assertEqual([x.author_sort_map for x in omi], [x.author_sort_map for x in nmi])
db.close()
ndb = self.init_legacy(self.cloned_library)
db = self.init_old(self.cloned_library)
run_funcs(self, db, ndb, (
('set_authors', 1, ('author one',),), ('set_authors', 2, ('author two',), True, True, True),
('set_author_sort', 3, 'new_aus'),
('set_comment', 1, ''), ('set_comment', 2, None), ('set_comment', 3, '<p>a comment</p>'),
('set_has_cover', 1, True), ('set_has_cover', 2, True), ('set_has_cover', 3, 1),
('set_identifiers', 2, {'test':'', 'a':'b'}), ('set_identifiers', 3, {'id':'1', 'isbn':'9783161484100'}), ('set_identifiers', 1, {}),
('set_languages', 1, ('en',)),
('set_languages', 2, ()),
('set_languages', 3, ('deu', 'spa', 'fra')),
('set_pubdate', 1, None), ('set_pubdate', 2, '2011-1-7'),
('set_series', 1, 'a series one'), ('set_series', 2, 'another series [7]'), ('set_series', 3, 'a third series'),
('set_publisher', 1, 'publisher two'), ('set_publisher', 2, None), ('set_publisher', 3, 'a third puB'),
('set_rating', 1, 2.3), ('set_rating', 2, 0), ('set_rating', 3, 8),
('set_timestamp', 1, None), ('set_timestamp', 2, '2011-1-7'),
('set_uuid', 1, None), ('set_uuid', 2, 'a test uuid'),
('set_title', 1, 'title two'), ('set_title', 2, None), ('set_title', 3, 'The Test Title'),
('set_tags', 1, ['a1', 'a2'], True), ('set_tags', 2, ['b1', 'tag one'], False, False, False, True), ('set_tags', 3, ['A1']),
(db.refresh,),
('title', 0), ('title', 1), ('title', 2),
('title_sort', 0), ('title_sort', 1), ('title_sort', 2),
('authors', 0), ('authors', 1), ('authors', 2),
('author_sort', 0), ('author_sort', 1), ('author_sort', 2),
('has_cover', 3), ('has_cover', 1), ('has_cover', 2),
('get_identifiers', 0), ('get_identifiers', 1), ('get_identifiers', 2),
('pubdate', 0), ('pubdate', 1), ('pubdate', 2),
('timestamp', 0), ('timestamp', 1), ('timestamp', 2),
('publisher', 0), ('publisher', 1), ('publisher', 2),
('rating', 0), ('+rating', 1, lambda x: x or 0), ('rating', 2),
('series', 0), ('series', 1), ('series', 2),
('series_index', 0), ('series_index', 1), ('series_index', 2),
('uuid', 0), ('uuid', 1), ('uuid', 2),
('isbn', 0), ('isbn', 1), ('isbn', 2),
('@tags', 0), ('@tags', 1), ('@tags', 2),
('@all_tags',),
('@get_all_identifier_types',),
('set_title_sort', 1, 'Title Two'), ('set_title_sort', 2, None), ('set_title_sort', 3, 'The Test Title_sort'),
('set_series_index', 1, 2.3), ('set_series_index', 2, 0), ('set_series_index', 3, 8),
('set_identifier', 1, 'moose', 'val'), ('set_identifier', 2, 'test', ''), ('set_identifier', 3, '', ''),
(db.refresh,),
('series_index', 0), ('series_index', 1), ('series_index', 2),
('title_sort', 0), ('title_sort', 1), ('title_sort', 2),
('get_identifiers', 0), ('get_identifiers', 1), ('get_identifiers', 2),
('@get_all_identifier_types',),
('set_metadata', 1, Metadata('title', ('a1',)), False, False, False, True, True),
('set_metadata', 3, Metadata('title', ('a1',))),
(db.refresh,),
('title', 0), ('title', 1), ('title', 2),
('title_sort', 0), ('title_sort', 1), ('title_sort', 2),
('authors', 0), ('authors', 1), ('authors', 2),
('author_sort', 0), ('author_sort', 1), ('author_sort', 2),
('@tags', 0), ('@tags', 1), ('@tags', 2),
('@all_tags',),
('@get_all_identifier_types',),
))
db.close()
ndb = self.init_legacy(self.cloned_library)
db = self.init_old(self.cloned_library)
run_funcs(self, db, ndb, (
('set', 0, 'title', 'newtitle'),
('set', 0, 'tags', 't1,t2,tag one', True),
('set', 0, 'authors', 'author one & Author Two', True),
('set', 0, 'rating', 3.2),
('set', 0, 'publisher', 'publisher one', False),
(db.refresh,),
('title', 0),
('rating', 0),
('#tags', 0), ('#tags', 1), ('#tags', 2),
('authors', 0), ('authors', 1), ('authors', 2),
('publisher', 0), ('publisher', 1), ('publisher', 2),
('delete_tag', 'T1'), ('delete_tag', 'T2'), ('delete_tag', 'Tag one'), ('delete_tag', 'News'),
(db.clean,), (db.refresh,),
('@all_tags',),
('#tags', 0), ('#tags', 1), ('#tags', 2),
))
db.close()
ndb = self.init_legacy(self.cloned_library)
db = self.init_old(self.cloned_library)
run_funcs(self, db, ndb, (
('remove_all_tags', (1, 2, 3)),
(db.clean,),
('@all_tags',),
('@tags', 0), ('@tags', 1), ('@tags', 2),
))
db.close()
ndb = self.init_legacy(self.cloned_library)
db = self.init_old(self.cloned_library)
a = {v:k for k, v in iteritems(ndb.new_api.get_id_map('authors'))}['Author One']
t = {v:k for k, v in iteritems(ndb.new_api.get_id_map('tags'))}['Tag One']
s = {v:k for k, v in iteritems(ndb.new_api.get_id_map('series'))}['A Series One']
p = {v:k for k, v in iteritems(ndb.new_api.get_id_map('publisher'))}['Publisher One']
run_funcs(self, db, ndb, (
('rename_author', a, 'Author Two'),
('rename_tag', t, 'News'),
('rename_series', s, 'ss'),
('rename_publisher', p, 'publisher one'),
(db.clean,),
(db.refresh,),
('@all_tags',),
('tags', 0), ('tags', 1), ('tags', 2),
('series', 0), ('series', 1), ('series', 2),
('publisher', 0), ('publisher', 1), ('publisher', 2),
('series_index', 0), ('series_index', 1), ('series_index', 2),
('authors', 0), ('authors', 1), ('authors', 2),
('author_sort', 0), ('author_sort', 1), ('author_sort', 2),
))
db.close()
# }}}
def test_legacy_custom(self): # {{{
'Test the legacy API for custom columns'
ndb = self.init_legacy(self.cloned_library)
db = self.init_old(self.cloned_library)
# Test getting
run_funcs(self, db, ndb, (
('all_custom', 'series'), ('all_custom', 'tags'), ('all_custom', 'rating'), ('all_custom', 'authors'), ('all_custom', None, 7),
('get_next_cc_series_num_for', 'My Series One', 'series'), ('get_next_cc_series_num_for', 'My Series Two', 'series'),
('is_item_used_in_multiple', 'My Tag One', 'tags'),
('is_item_used_in_multiple', 'My Series One', 'series'),
('$get_custom_items_with_ids', 'series'), ('$get_custom_items_with_ids', 'tags'), ('$get_custom_items_with_ids', 'float'),
('$get_custom_items_with_ids', 'rating'), ('$get_custom_items_with_ids', 'authors'), ('$get_custom_items_with_ids', None, 7),
))
for label in ('tags', 'series', 'authors', 'comments', 'rating', 'date', 'yesno', 'isbn', 'enum', 'formats', 'float', 'comp_tags'):
for func in ('get_custom', 'get_custom_extra', 'get_custom_and_extra'):
run_funcs(self, db, ndb, [(func, idx, label) for idx in range(3)])
# Test renaming/deleting
t = {v:k for k, v in iteritems(ndb.new_api.get_id_map('#tags'))}['My Tag One']
t2 = {v:k for k, v in iteritems(ndb.new_api.get_id_map('#tags'))}['My Tag Two']
a = {v:k for k, v in iteritems(ndb.new_api.get_id_map('#authors'))}['My Author Two']
a2 = {v:k for k, v in iteritems(ndb.new_api.get_id_map('#authors'))}['Custom One']
s = {v:k for k, v in iteritems(ndb.new_api.get_id_map('#series'))}['My Series One']
run_funcs(self, db, ndb, (
('delete_custom_item_using_id', t, 'tags'),
('delete_custom_item_using_id', a, 'authors'),
('rename_custom_item', t2, 't2', 'tags'),
('rename_custom_item', a2, 'custom one', 'authors'),
('rename_custom_item', s, 'My Series Two', 'series'),
('delete_item_from_multiple', 'custom two', 'authors'),
(db.clean,),
(db.refresh,),
('all_custom', 'series'), ('all_custom', 'tags'), ('all_custom', 'authors'),
))
for label in ('tags', 'authors', 'series'):
run_funcs(self, db, ndb, [('get_custom_and_extra', idx, label) for idx in range(3)])
db.close()
ndb = self.init_legacy(self.cloned_library)
db = self.init_old(self.cloned_library)
# Test setting
run_funcs(self, db, ndb, (
('-set_custom', 1, 't1 & t2', 'authors'),
('-set_custom', 1, 't3 & t4', 'authors', None, True),
('-set_custom', 3, 'test one & test Two', 'authors'),
('-set_custom', 1, 'ijfkghkjdf', 'enum'),
('-set_custom', 3, 'One', 'enum'),
('-set_custom', 3, 'xxx', 'formats'),
('-set_custom', 1, 'my tag two', 'tags', None, False, False, None, True, True),
(db.clean,), (db.refresh,),
('all_custom', 'series'), ('all_custom', 'tags'), ('all_custom', 'authors'),
))
for label in ('tags', 'series', 'authors', 'comments', 'rating', 'date', 'yesno', 'isbn', 'enum', 'formats', 'float', 'comp_tags'):
for func in ('get_custom', 'get_custom_extra', 'get_custom_and_extra'):
run_funcs(self, db, ndb, [(func, idx, label) for idx in range(3)])
db.close()
ndb = self.init_legacy(self.cloned_library)
db = self.init_old(self.cloned_library)
# Test setting bulk
run_funcs(self, db, ndb, (
('set_custom_bulk', (1,2,3), 't1 & t2', 'authors'),
('set_custom_bulk', (1,2,3), 'a series', 'series', None, False, False, (9, 10, 11)),
('set_custom_bulk', (1,2,3), 't1', 'tags', None, True),
(db.clean,), (db.refresh,),
('all_custom', 'series'), ('all_custom', 'tags'), ('all_custom', 'authors'),
))
for label in ('tags', 'series', 'authors', 'comments', 'rating', 'date', 'yesno', 'isbn', 'enum', 'formats', 'float', 'comp_tags'):
for func in ('get_custom', 'get_custom_extra', 'get_custom_and_extra'):
run_funcs(self, db, ndb, [(func, idx, label) for idx in range(3)])
db.close()
ndb = self.init_legacy(self.cloned_library)
db = self.init_old(self.cloned_library)
# Test bulk multiple
run_funcs(self, db, ndb, (
('set_custom_bulk_multiple', (1,2,3), ['t1'], ['My Tag One'], 'tags'),
(db.clean,), (db.refresh,),
('all_custom', 'tags'),
('get_custom', 0, 'tags'), ('get_custom', 1, 'tags'), ('get_custom', 2, 'tags'),
))
db.close()
o = self.cloned_library
n = self.cloned_library
ndb, db = self.init_legacy(n), self.init_old(o)
ndb.create_custom_column('created', 'Created', 'text', True, True, {'moose':'cat'})
db.create_custom_column('created', 'Created', 'text', True, True, {'moose':'cat'})
db.close()
ndb, db = self.init_legacy(n), self.init_old(o)
self.assertEqual(db.custom_column_label_map['created'], ndb.backend.custom_field_metadata('created'))
num = db.custom_column_label_map['created']['num']
ndb.set_custom_column_metadata(num, is_editable=False, name='Crikey', display={})
db.set_custom_column_metadata(num, is_editable=False, name='Crikey', display={})
db.close()
ndb, db = self.init_legacy(n), self.init_old(o)
self.assertEqual(db.custom_column_label_map['created'], ndb.backend.custom_field_metadata('created'))
db.close()
ndb = self.init_legacy(n)
ndb.delete_custom_column('created')
ndb = self.init_legacy(n)
self.assertRaises(KeyError, ndb.custom_field_name, num=num)
# Test setting custom series
ndb = self.init_legacy(self.cloned_library)
ndb.set_custom(1, 'TS [9]', label='series')
self.assertEqual(ndb.new_api.field_for('#series', 1), 'TS')
self.assertEqual(ndb.new_api.field_for('#series_index', 1), 9)
# }}}
def test_legacy_saved_search(self): # {{{
' Test legacy saved search API '
db, ndb = self.init_old(), self.init_legacy()
run_funcs(self, db, ndb, (
('saved_search_set_all', {'one':'a', 'two':'b'}),
('saved_search_names',),
('saved_search_lookup', 'one'),
('saved_search_lookup', 'two'),
('saved_search_lookup', 'xxx'),
('saved_search_rename', 'one', '1'),
('saved_search_names',),
('saved_search_lookup', '1'),
('saved_search_delete', '1'),
('saved_search_names',),
('saved_search_add', 'n', 'm'),
('saved_search_names',),
('saved_search_lookup', 'n'),
))
db.close()
# }}}
| 39,222 | Python | .py | 757 | 40.178336 | 145 | 0.518039 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,085 | utils.py | kovidgoyal_calibre/src/calibre/db/tests/utils.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import os
import shutil
from calibre import walk
from calibre.db.tests.base import BaseTest
from calibre.db.utils import ThumbnailCache
class UtilsTest(BaseTest):
def setUp(self):
self.tdir = self.mkdtemp()
def tearDown(self):
shutil.rmtree(self.tdir)
def init_tc(self, name='1', max_size=1):
return ThumbnailCache(name=name, location=self.tdir, max_size=max_size, test_mode=True)
def basic_fill(self, c, num=5):
total = 0
for i in range(1, num+1):
sz = i * 1000
c.insert(i, i, (('%d'%i) * sz).encode('ascii'))
total += sz
return total
def test_thumbnail_cache(self): # {{{
' Test the operation of the thumbnail cache '
c = self.init_tc()
self.assertFalse(hasattr(c, 'total_size'), 'index read on initialization')
c.invalidate(666)
self.assertFalse(hasattr(c, 'total_size'), 'index read on invalidate')
self.assertEqual(self.basic_fill(c), c.total_size)
self.assertEqual(5, len(c))
for i in (3, 4, 2, 5, 1):
data, ts = c[i]
self.assertEqual(i, ts, 'timestamp not correct')
self.assertEqual((('%d'%i) * (i*1000)).encode('ascii'), data)
c.set_group_id('a')
self.basic_fill(c)
order = tuple(c.items)
ts = c.current_size
c.shutdown()
c = self.init_tc()
self.assertEqual(c.current_size, ts, 'size not preserved after restart')
self.assertEqual(order, tuple(c.items), 'order not preserved after restart')
c.shutdown()
c = self.init_tc()
c.invalidate((1,))
self.assertIsNone(c[1][1], 'invalidate before load_index() failed')
c.invalidate((2,))
self.assertIsNone(c[2][1], 'invalidate after load_index() failed')
c.set_group_id('a')
c[1]
c.set_size(0.001)
self.assertLessEqual(c.current_size, 1024, 'set_size() failed')
self.assertEqual(len(c), 1)
self.assertIn(1, c)
c.insert(9, 9, b'x' * (c.max_size-1))
self.assertEqual(len(c), 1)
self.assertLessEqual(c.current_size, c.max_size, 'insert() did not prune')
self.assertIn(9, c)
c.empty()
self.assertEqual(c.total_size, 0)
self.assertEqual(len(c), 0)
self.assertEqual(tuple(walk(c.location)), (os.path.join(c.location, 'version'),))
c = self.init_tc()
self.basic_fill(c)
self.assertEqual(len(c), 5)
c.set_thumbnail_size(200, 201)
self.assertIsNone(c[1][0])
self.assertEqual(len(c), 0)
self.assertEqual(tuple(walk(c.location)), (os.path.join(c.location, 'version'),))
# }}}
| 2,823 | Python | .py | 70 | 32.171429 | 95 | 0.598175 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,086 | add_remove.py | kovidgoyal_calibre/src/calibre/db/tests/add_remove.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import glob
import os
from contextlib import suppress
from datetime import timedelta
from io import BytesIO
from tempfile import NamedTemporaryFile
from calibre.db.constants import METADATA_FILE_NAME
from calibre.db.tests.base import IMG, BaseTest
from calibre.ptempfile import PersistentTemporaryFile
from calibre.utils.date import UNDEFINED_DATE, now, utcnow
from calibre.utils.img import image_from_path
from calibre.utils.resources import get_image_path
from polyglot.builtins import iteritems, itervalues
def import_test(replacement_data, replacement_fmt=None):
def func(path, fmt):
if not path.endswith('.'+fmt.lower()):
raise AssertionError('path extension does not match format')
ext = (replacement_fmt or fmt).lower()
with PersistentTemporaryFile('.'+ext) as f:
f.write(replacement_data)
return f.name
return func
class AddRemoveTest(BaseTest):
def test_add_format(self): # {{{
'Test adding formats to an existing book record'
af, ae, at = self.assertFalse, self.assertEqual, self.assertTrue
cache = self.init_cache()
table = cache.fields['formats'].table
NF = b'test_add_formatxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# Test that replace=False works
previous = cache.format(1, 'FMT1')
af(cache.add_format(1, 'FMT1', BytesIO(NF), replace=False))
ae(previous, cache.format(1, 'FMT1'))
# Test that replace=True works
lm = cache.field_for('last_modified', 1)
at(cache.add_format(1, 'FMT1', BytesIO(NF), replace=True))
ae(NF, cache.format(1, 'FMT1'))
ae(cache.format_metadata(1, 'FMT1')['size'], len(NF))
at(cache.field_for('size', 1) >= len(NF))
at(cache.field_for('last_modified', 1) > lm)
ae(('FMT2','FMT1'), cache.formats(1))
at(1 in table.col_book_map['FMT1'])
# Test adding a format to a record with no formats
at(cache.add_format(3, 'FMT1', BytesIO(NF), replace=True))
ae(NF, cache.format(3, 'FMT1'))
ae(cache.format_metadata(3, 'FMT1')['size'], len(NF))
ae(('FMT1',), cache.formats(3))
at(3 in table.col_book_map['FMT1'])
at(cache.add_format(3, 'FMTX', BytesIO(NF), replace=True))
at(3 in table.col_book_map['FMTX'])
ae(('FMT1','FMTX'), cache.formats(3))
# Test running on import plugins
import calibre.db.cache as c
orig = c.run_plugins_on_import
try:
c.run_plugins_on_import = import_test(b'replacement data')
at(cache.add_format(3, 'REPL', BytesIO(NF)))
ae(b'replacement data', cache.format(3, 'REPL'))
c.run_plugins_on_import = import_test(b'replacement data2', 'REPL2')
with NamedTemporaryFile(suffix='_test_add_format.repl') as f:
f.write(NF)
f.seek(0)
at(cache.add_format(3, 'REPL', BytesIO(NF)))
ae(b'replacement data', cache.format(3, 'REPL'))
ae(b'replacement data2', cache.format(3, 'REPL2'))
finally:
c.run_plugins_on_import = orig
# Test adding FMT with path
with NamedTemporaryFile(suffix='_test_add_format.fmt9') as f:
f.write(NF)
f.seek(0)
at(cache.add_format(2, 'FMT9', f))
ae(NF, cache.format(2, 'FMT9'))
ae(cache.format_metadata(2, 'FMT9')['size'], len(NF))
at(cache.field_for('size', 2) >= len(NF))
at(2 in table.col_book_map['FMT9'])
del cache
# Test that the old interface also shows correct format data
db = self.init_old()
ae(db.formats(3, index_is_id=True), ','.join(['FMT1', 'FMTX', 'REPL', 'REPL2']))
ae(db.format(3, 'FMT1', index_is_id=True), NF)
ae(db.format(1, 'FMT1', index_is_id=True), NF)
db.close()
del db
# }}}
def test_remove_formats(self): # {{{
'Test removal of formats from book records'
af, ae, at = self.assertFalse, self.assertEqual, self.assertTrue
cache = self.init_cache()
# Test removal of non-existing format does nothing
formats = {bid:tuple(cache.formats(bid)) for bid in (1, 2, 3)}
cache.remove_formats({1:{'NF'}, 2:{'NF'}, 3:{'NF'}})
nformats = {bid:tuple(cache.formats(bid)) for bid in (1, 2, 3)}
ae(formats, nformats)
# Test full removal of format
af(cache.format(1, 'FMT1') is None)
at(cache.has_format(1, 'FMT1'))
ap = cache.format_abspath(1, 'FMT1')
at(os.path.exists(ap))
cache.remove_formats({1:{'FMT1'}})
at(cache.format(1, 'FMT1') is None)
af(bool(cache.format_metadata(1, 'FMT1')))
af(bool(cache.format_metadata(1, 'FMT1', allow_cache=False)))
af('FMT1' in cache.formats(1))
af(cache.has_format(1, 'FMT1'))
af(os.path.exists(ap))
# Test db only removal
at(cache.has_format(1, 'FMT2'))
ap = cache.format_abspath(1, 'FMT2')
if ap and os.path.exists(ap):
cache.remove_formats({1:{'FMT2'}}, db_only=True)
af(bool(cache.format_metadata(1, 'FMT2')))
af(cache.has_format(1, 'FMT2'))
at(os.path.exists(ap))
# Test that the old interface agrees
db = self.init_old()
at(db.format(1, 'FMT1', index_is_id=True) is None)
db.close()
del db
# }}}
def test_create_book_entry(self): # {{{
'Test the creation of new book entries'
from calibre.ebooks.metadata.book.base import Metadata
cache = self.init_cache()
cache.set_field('authors', {1: 'Creator Two'})
cache.set_link_map('authors', {'Creator Two': 'original'})
mi = Metadata('Created One', authors=('Creator One', 'Creator Two'))
mi.link_maps = {'authors': {'Creator One': 'link1', 'Creator Two': 'changed'}}
book_id = cache.create_book_entry(mi)
self.assertIsNot(book_id, None)
def do_test(cache, book_id):
for field in ('path', 'uuid', 'author_sort', 'timestamp', 'pubdate', 'title', 'authors', 'series_index', 'sort'):
self.assertTrue(cache.field_for(field, book_id))
for field in ('size', 'cover'):
self.assertFalse(cache.field_for(field, book_id))
self.assertEqual(book_id, cache.fields['uuid'].table.uuid_to_id_map[cache.field_for('uuid', book_id)])
self.assertLess(now() - cache.field_for('timestamp', book_id), timedelta(seconds=30))
self.assertEqual(('Created One', ('Creator One', 'Creator Two')), (cache.field_for('title', book_id), cache.field_for('authors', book_id)))
self.assertEqual(cache.field_for('series_index', book_id), 1.0)
self.assertEqual(cache.field_for('pubdate', book_id), UNDEFINED_DATE)
self.assertEqual(cache.get_all_link_maps_for_book(book_id), {'authors': {'Creator One': 'link1', 'Creator Two': 'original'}})
do_test(cache, book_id)
# Test that the db contains correct data
cache = self.init_cache()
do_test(cache, book_id)
self.assertIs(None, cache.create_book_entry(mi, add_duplicates=False), 'Duplicate added incorrectly')
book_id = cache.create_book_entry(mi, cover=IMG)
self.assertIsNot(book_id, None)
self.assertEqual(IMG, cache.cover(book_id))
import calibre.db.cache as c
orig = c.prefs
c.prefs = {'new_book_tags':('newbook', 'newbook2')}
try:
book_id = cache.create_book_entry(mi)
self.assertEqual(('newbook', 'newbook2'), cache.field_for('tags', book_id))
mi.tags = ('one', 'two')
book_id = cache.create_book_entry(mi)
self.assertEqual(('one', 'two') + ('newbook', 'newbook2'), cache.field_for('tags', book_id))
mi.tags = ()
finally:
c.prefs = orig
mi.uuid = 'a preserved uuid'
book_id = cache.create_book_entry(mi, preserve_uuid=True)
self.assertEqual(mi.uuid, cache.field_for('uuid', book_id))
# }}}
def test_add_books(self): # {{{
'Test the adding of new books'
from calibre.ebooks.metadata.book.base import Metadata
cache = self.init_cache()
mi = Metadata('Created One', authors=('Creator One', 'Creator Two'))
FMT1, FMT2 = b'format1', b'format2'
format_map = {'FMT1':BytesIO(FMT1), 'FMT2':BytesIO(FMT2)}
ids, duplicates = cache.add_books([(mi, format_map)])
self.assertTrue(len(ids) == 1)
self.assertFalse(duplicates)
book_id = ids[0]
self.assertEqual(set(cache.formats(book_id)), {'FMT1', 'FMT2'})
self.assertEqual(cache.format(book_id, 'FMT1'), FMT1)
self.assertEqual(cache.format(book_id, 'FMT2'), FMT2)
# }}}
def test_remove_books(self): # {{{
'Test removal of books'
cl = self.cloned_library
cl2 = self.cloned_library
cl3 = self.cloned_library
cache = self.init_cache()
af, ae = self.assertFalse, self.assertEqual
authors = cache.fields['authors'].table
# Delete a single book, with no formats and check cleaning
self.assertIn('Unknown', set(itervalues(authors.id_map)))
olen = len(authors.id_map)
item_id = {v:k for k, v in iteritems(authors.id_map)}['Unknown']
cache.remove_books((3,))
for c in (cache, self.init_cache()):
table = c.fields['authors'].table
self.assertNotIn(3, c.all_book_ids())
self.assertNotIn('Unknown', set(itervalues(table.id_map)))
self.assertNotIn(item_id, table.asort_map)
self.assertNotIn(item_id, table.link_map)
ae(len(table.id_map), olen-1)
# Check that files are removed
fmtpath = cache.format_abspath(1, 'FMT1')
bookpath = os.path.dirname(fmtpath)
authorpath = os.path.dirname(bookpath)
os.mkdir(os.path.join(authorpath, '.DS_Store'))
open(os.path.join(authorpath, 'Thumbs.db'), 'wb').close()
item_id = {v:k for k, v in iteritems(cache.fields['#series'].table.id_map)}['My Series Two']
cache.remove_books((1,), permanent=True)
for x in (fmtpath, bookpath, authorpath):
af(os.path.exists(x), 'The file %s exists, when it should not' % x)
for c in (cache, self.init_cache()):
table = c.fields['authors'].table
self.assertNotIn(1, c.all_book_ids())
self.assertNotIn('Author Two', set(itervalues(table.id_map)))
self.assertNotIn(6, set(itervalues(c.fields['rating'].table.id_map)))
self.assertIn('A Series One', set(itervalues(c.fields['series'].table.id_map)))
self.assertNotIn('My Series Two', set(itervalues(c.fields['#series'].table.id_map)))
self.assertNotIn(item_id, c.fields['#series'].table.col_book_map)
self.assertNotIn(1, c.fields['#series'].table.book_col_map)
# Test emptying the db
cache.remove_books(cache.all_book_ids(), permanent=True)
for f in ('authors', 'series', '#series', 'tags'):
table = cache.fields[f].table
self.assertFalse(table.id_map)
self.assertFalse(table.book_col_map)
self.assertFalse(table.col_book_map)
# Test the delete service
# test basic delete book and cache expiry
cache = self.init_cache(cl)
fmtpath = cache.format_abspath(1, 'FMT1')
bookpath = os.path.dirname(fmtpath)
title = cache.field_for('title', 1)
os.mkdir(os.path.join(bookpath, 'xyz'))
open(os.path.join(bookpath, 'xyz', 'abc'), 'w').close()
authorpath = os.path.dirname(bookpath)
item_id = {v:k for k, v in iteritems(cache.fields['#series'].table.id_map)}['My Series Two']
cache.remove_books((1,))
for x in (fmtpath, bookpath, authorpath):
af(os.path.exists(x), 'The file %s exists, when it should not' % x)
b, f = cache.list_trash_entries()
self.assertEqual(len(b), 1)
self.assertEqual(len(f), 0)
self.assertEqual(b[0].title, title)
self.assertTrue(os.path.exists(b[0].cover_path))
cache.backend.expire_old_trash(1000)
self.assertTrue(os.path.exists(b[0].cover_path))
cache.backend.expire_old_trash(0)
self.assertFalse(os.path.exists(b[0].cover_path))
# test restoring of books
cache = self.init_cache(cl2)
cache.set_cover({1: image_from_path(get_image_path('lt.png', allow_user_override=False))})
fmtpath = cache.format_abspath(1, 'FMT1')
bookpath = os.path.dirname(fmtpath)
cache.set_annotations_for_book(1, 'FMT1', [({'title': 'else', 'type': 'bookmark', 'timestamp': utcnow().isoformat()}, 1)])
annots_before = cache.all_annotations_for_book(1)
fm_before = cache.format_metadata(1, 'FMT1', allow_cache=False), cache.format_metadata(1, 'FMT2', allow_cache=False)
os.mkdir(os.path.join(bookpath, 'xyz'))
open(os.path.join(bookpath, 'xyz', 'abc'), 'w').close()
with suppress(FileNotFoundError):
os.remove(os.path.join(bookpath, METADATA_FILE_NAME))
cache.remove_books((1,))
cache.move_book_from_trash(1)
b, f = cache.list_trash_entries()
self.assertEqual(len(b), 0)
self.assertEqual(len(f), 0)
self.assertEqual(fmtpath, cache.format_abspath(1, 'FMT1'))
self.assertEqual(fm_before, (cache.format_metadata(1, 'FMT1', allow_cache=False), cache.format_metadata(1, 'FMT2', allow_cache=False)))
self.assertEqual(annots_before, cache.all_annotations_for_book(1))
self.assertTrue(cache.cover(1))
self.assertTrue(os.path.exists(os.path.join(bookpath, 'xyz', 'abc')))
# test restoring of formats
cache = self.init_cache(cl3)
all_formats = cache.formats(1)
cache.remove_formats({1: all_formats})
self.assertFalse(cache.formats(1))
b, f = cache.list_trash_entries()
self.assertEqual(len(b), 0)
self.assertEqual(len(f), 1)
self.assertEqual(f[0].title, title)
self.assertTrue(f[0].cover_path)
for fmt in all_formats:
cache.move_format_from_trash(1, fmt)
self.assertEqual(all_formats, cache.formats(1))
self.assertFalse(os.listdir(os.path.join(cache.backend.trash_dir, 'f')))
# }}}
def test_original_fmt(self): # {{{
' Test management of original fmt '
af, ae, at = self.assertFalse, self.assertEqual, self.assertTrue
db = self.init_cache()
fmts = db.formats(1)
af(db.has_format(1, 'ORIGINAL_FMT1'))
at(db.save_original_format(1, 'FMT1'))
at(db.has_format(1, 'ORIGINAL_FMT1'))
raw = db.format(1, 'FMT1')
ae(raw, db.format(1, 'ORIGINAL_FMT1'))
db.add_format(1, 'FMT1', BytesIO(b'replacedfmt'))
self.assertNotEqual(db.format(1, 'FMT1'), db.format(1, 'ORIGINAL_FMT1'))
at(db.restore_original_format(1, 'ORIGINAL_FMT1'))
ae(raw, db.format(1, 'FMT1'))
af(db.has_format(1, 'ORIGINAL_FMT1'))
ae(set(fmts), set(db.formats(1, verify_formats=False)))
# }}}
def test_format_orphan(self): # {{{
' Test that adding formats does not create orphans if the file name algorithm changes '
cache = self.init_cache()
path = cache.format_abspath(1, 'FMT1')
base, name = os.path.split(path)
prefix = 'mushroomxx'
os.rename(path, os.path.join(base, prefix + name))
cache.fields['formats'].table.fname_map[1]['FMT1'] = prefix + os.path.splitext(name)[0]
old = glob.glob(os.path.join(base, '*.fmt1'))
cache.add_format(1, 'FMT1', BytesIO(b'xxxx'), run_hooks=False)
new = glob.glob(os.path.join(base, '*.fmt1'))
self.assertNotEqual(old, new)
self.assertEqual(len(old), len(new))
self.assertNotIn(prefix, cache.fields['formats'].format_fname(1, 'FMT1'))
# }}}
def test_copy_to_library(self): # {{{
from calibre.db.copy_to_library import copy_one_book
from calibre.ebooks.metadata import authors_to_string
from calibre.utils.date import EPOCH, utcnow
src_db = self.init_cache()
dest_db = self.init_cache(self.cloned_library)
def read(x, mode='r'):
with open(x, mode) as f:
return f.read()
def a(**kw):
ts = utcnow()
kw['timestamp'] = utcnow().isoformat()
return kw, (ts - EPOCH).total_seconds()
annot_list = [
a(type='bookmark', title='bookmark1 changed', seq=1),
a(type='highlight', highlighted_text='text1', uuid='1', seq=2),
a(type='highlight', highlighted_text='text2', uuid='2', seq=3, notes='notes2 some word changed again'),
]
src_db.set_annotations_for_book(1, 'FMT1', annot_list)
bookdir = os.path.dirname(src_db.format_abspath(1, '__COVER_INTERNAL__'))
with open(os.path.join(bookdir, 'exf'), 'w') as f:
f.write('exf')
os.mkdir(os.path.join(bookdir, 'sub'))
with open(os.path.join(bookdir, 'sub', 'recurse'), 'w') as f:
f.write('recurse')
def make_rdata(book_id=1, new_book_id=None, action='add'):
return {
'title': src_db.field_for('title', book_id),
'authors': list(src_db.field_for('authors', book_id)),
'author': authors_to_string(src_db.field_for('authors', book_id)),
'book_id': book_id, 'new_book_id': new_book_id, 'action': action
}
def compare_field(field, func=self.assertEqual):
func(src_db.field_for(field, rdata['book_id']), dest_db.field_for(field, rdata['new_book_id']))
def assert_has_extra_files(book_id):
bookdir = os.path.dirname(dest_db.format_abspath(book_id, '__COVER_INTERNAL__'))
self.assertEqual('exf', read(os.path.join(bookdir, 'exf')))
self.assertEqual('recurse', read(os.path.join(bookdir, 'sub', 'recurse')))
def assert_does_not_have_extra_files(book_id):
bookdir = os.path.dirname(dest_db.format_abspath(book_id, '__COVER_INTERNAL__'))
self.assertFalse(os.path.exists(os.path.join(bookdir, 'exf')))
self.assertFalse(os.path.exists(os.path.join(bookdir, 'sub', 'recurse')))
def clear_extra_files(book_id):
for ef in dest_db.list_extra_files(book_id):
os.remove(ef.file_path)
assert_does_not_have_extra_files(1)
rdata = copy_one_book(1, src_db, dest_db)
self.assertEqual(rdata, make_rdata(new_book_id=max(dest_db.all_book_ids())))
compare_field('timestamp')
compare_field('uuid', self.assertNotEqual)
self.assertEqual(src_db.all_annotations_for_book(1), dest_db.all_annotations_for_book(max(dest_db.all_book_ids())))
assert_has_extra_files(rdata['new_book_id'])
clear_extra_files(rdata['new_book_id'])
rdata = copy_one_book(1, src_db, dest_db, preserve_date=False, preserve_uuid=True)
self.assertEqual(rdata, make_rdata(new_book_id=max(dest_db.all_book_ids())))
compare_field('timestamp', self.assertNotEqual)
compare_field('uuid')
assert_has_extra_files(rdata['new_book_id'])
clear_extra_files(rdata['new_book_id'])
rdata = copy_one_book(1, src_db, dest_db, duplicate_action='ignore')
self.assertIsNone(rdata['new_book_id'])
self.assertEqual(rdata['action'], 'duplicate')
src_db.add_format(1, 'FMT1', BytesIO(b'replaced'), run_hooks=False)
assert_does_not_have_extra_files(1)
rdata = copy_one_book(1, src_db, dest_db, duplicate_action='add_formats_to_existing')
self.assertEqual(rdata['action'], 'automerge')
for new_book_id in (1, 4, 5):
self.assertEqual(dest_db.format(new_book_id, 'FMT1'), b'replaced')
assert_has_extra_files(new_book_id)
clear_extra_files(new_book_id)
src_db.add_format(1, 'FMT1', BytesIO(b'second-round'), run_hooks=False)
rdata = copy_one_book(1, src_db, dest_db, duplicate_action='add_formats_to_existing', automerge_action='ignore')
self.assertEqual(rdata['action'], 'automerge')
for new_book_id in (1, 4, 5):
self.assertEqual(dest_db.format(new_book_id, 'FMT1'), b'replaced')
assert_does_not_have_extra_files(new_book_id)
rdata = copy_one_book(1, src_db, dest_db, duplicate_action='add_formats_to_existing', automerge_action='new record')
self.assertEqual(rdata['action'], 'automerge')
for new_book_id in (1, 4, 5):
self.assertEqual(dest_db.format(new_book_id, 'FMT1'), b'replaced')
assert_does_not_have_extra_files(new_book_id)
self.assertEqual(dest_db.format(rdata['new_book_id'], 'FMT1'), b'second-round')
assert_has_extra_files(rdata['new_book_id'])
# }}}
def test_merging_extra_files(self): # {{{
db = self.init_cache()
def add_extra(book_id, relpath):
db.add_extra_files(book_id, {relpath: BytesIO(f'{book_id}:{relpath}'.encode())})
def extra_files_for(book_id):
ans = {}
for ef in db.list_extra_files(book_id):
with open(ef.file_path) as f:
ans[ef.relpath] = f.read()
return ans
add_extra(1, 'one'), add_extra(1, 'sub/one')
add_extra(2, 'one'), add_extra(2, 'sub/one'), add_extra(2, 'two/two')
add_extra(3, 'one'), add_extra(3, 'sub/one'), add_extra(3, 'three')
self.assertEqual(extra_files_for(1), {
'one': '1:one', 'sub/one': '1:sub/one',
})
db.merge_extra_files(1, (2, 3))
self.assertEqual(extra_files_for(1), {
'one': '1:one', 'sub/one': '1:sub/one',
'merge conflict/one': '2:one', 'sub/merge conflict/one': '2:sub/one', 'two/two': '2:two/two',
'three': '3:three', 'merge conflict 1/one': '3:one', 'sub/merge conflict 1/one': '3:sub/one',
})
# }}}
| 22,389 | Python | .py | 428 | 42.53271 | 151 | 0.604996 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,087 | __init__.py | kovidgoyal_calibre/src/calibre/db/tests/__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) |
27,088 | base.py | kovidgoyal_calibre/src/calibre/db/tests/base.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import atexit
import gc
import os
import shutil
import tempfile
import time
import unittest
from functools import partial
from io import BytesIO
from calibre.utils.resources import get_image_path as I
rmtree = partial(shutil.rmtree, ignore_errors=True)
IMG = b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00`\x00`\x00\x00\xff\xe1\x00\x16Exif\x00\x00II*\x00\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xdb\x00C\x00\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\xff\xdb\x00C\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\xff\xc0\x00\x11\x08\x00\x01\x00\x01\x03\x01"\x00\x02\x11\x01\x03\x11\x01\xff\xc4\x00\x15\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\n\xff\xc4\x00\x14\x10\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xc4\x00\x14\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xc4\x00\x14\x11\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xda\x00\x0c\x03\x01\x00\x02\x11\x03\x11\x00?\x00\xbf\x80\x01\xff\xd9' # noqa {{{ }}}
class BaseTest(unittest.TestCase):
longMessage = True
maxDiff = None
def setUp(self):
from calibre.utils.recycle_bin import nuke_recycle
nuke_recycle()
self.library_path = self.mkdtemp()
self.create_db(self.library_path)
def tearDown(self):
from calibre.utils.recycle_bin import restore_recyle
restore_recyle()
gc.collect(), gc.collect()
try:
shutil.rmtree(self.library_path)
except OSError:
# Try again in case something transient has a file lock on windows
gc.collect(), gc.collect()
time.sleep(2)
shutil.rmtree(self.library_path)
def create_db(self, library_path):
from calibre.library.database2 import LibraryDatabase2
if LibraryDatabase2.exists_at(library_path):
raise ValueError('A library already exists at %r'%library_path)
src = os.path.join(os.path.dirname(__file__), 'metadata.db')
dest = os.path.join(library_path, 'metadata.db')
shutil.copyfile(src, dest)
db = LibraryDatabase2(library_path)
db.set_cover(1, I('lt.png', data=True))
db.set_cover(2, I('polish.png', data=True))
db.add_format(1, 'FMT1', BytesIO(b'book1fmt1'), index_is_id=True)
db.add_format(1, 'FMT2', BytesIO(b'book1fmt2'), index_is_id=True)
db.add_format(2, 'FMT1', BytesIO(b'book2fmt1'), index_is_id=True)
db.conn.close()
return dest
def init_cache(self, library_path=None):
from calibre.db.backend import DB
from calibre.db.cache import Cache
backend = DB(library_path or self.library_path)
cache = Cache(backend)
cache.init()
return cache
def mkdtemp(self):
ans = tempfile.mkdtemp(prefix='db_test_')
atexit.register(rmtree, ans)
return ans
def init_old(self, library_path=None):
from calibre.library.database2 import LibraryDatabase2
return LibraryDatabase2(library_path or self.library_path)
def init_legacy(self, library_path=None):
from calibre.db.legacy import LibraryDatabase
return LibraryDatabase(library_path or self.library_path)
def clone_library(self, library_path):
if not hasattr(self, 'clone_dir'):
self.clone_dir = tempfile.mkdtemp()
atexit.register(rmtree, self.clone_dir)
self.clone_count = 0
self.clone_count += 1
dest = os.path.join(self.clone_dir, str(self.clone_count))
shutil.copytree(library_path, dest)
return dest
@property
def cloned_library(self):
return self.clone_library(self.library_path)
def compare_metadata(self, mi1, mi2, exclude=()):
allfk1 = mi1.all_field_keys()
allfk2 = mi2.all_field_keys()
self.assertEqual(allfk1, allfk2)
all_keys = {'format_metadata', 'id', 'application_id',
'author_sort_map', 'link_maps', 'book_size',
'ondevice_col', 'last_modified', 'has_cover',
'cover_data'}.union(allfk1)
for attr in all_keys:
if attr in {'user_metadata', 'book_size', 'ondevice_col', 'db_approx_formats'} or attr in exclude:
continue
attr1, attr2 = getattr(mi1, attr), getattr(mi2, attr)
if attr == 'formats':
attr1, attr2 = map(lambda x:tuple(x) if x else (), (attr1, attr2))
if isinstance(attr1, (tuple, list)) and 'authors' not in attr and 'languages' not in attr:
attr1, attr2 = set(attr1), set(attr2)
self.assertEqual(attr1, attr2,
'%s not the same: %r != %r'%(attr, attr1, attr2))
if attr.startswith('#') and attr + '_index' not in exclude:
attr1, attr2 = mi1.get_extra(attr), mi2.get_extra(attr)
self.assertEqual(attr1, attr2,
'%s {#extra} not the same: %r != %r'%(attr, attr1, attr2))
| 5,615 | Python | .py | 101 | 46.673267 | 1,208 | 0.65162 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,089 | writing.py | kovidgoyal_calibre/src/calibre/db/tests/writing.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os
from collections import namedtuple
from functools import partial
from io import BytesIO
from calibre.db.backend import FTSQueryError
from calibre.db.constants import RESOURCE_URL_SCHEME
from calibre.db.tests.base import IMG, BaseTest
from calibre.ebooks.metadata import author_to_author_sort, title_sort
from calibre.ebooks.metadata.book.base import Metadata
from calibre.utils.date import UNDEFINED_DATE
from polyglot.builtins import iteritems, itervalues
class WritingTest(BaseTest):
# Utils {{{
def create_getter(self, name, getter=None):
if getter is None:
if name.endswith('_index'):
def ans(db):
return partial(db.get_custom_extra, index_is_id=True, label=name[1:].replace('_index', ''))
else:
def ans(db):
return partial(db.get_custom, label=name[1:], index_is_id=True)
else:
def ans(db):
return partial(getattr(db, getter), index_is_id=True)
return ans
def create_setter(self, name, setter=None):
if setter is None:
def ans(db):
return partial(db.set_custom, label=name[1:], commit=True)
else:
def ans(db):
return partial(getattr(db, setter), commit=True)
return ans
def create_test(self, name, vals, getter=None, setter=None):
T = namedtuple('Test', 'name vals getter setter')
return T(name, vals, self.create_getter(name, getter),
self.create_setter(name, setter))
def run_tests(self, tests):
results = {}
for test in tests:
results[test] = []
for val in test.vals:
cl = self.cloned_library
cache = self.init_cache(cl)
cache.set_field(test.name, {1: val})
cached_res = cache.field_for(test.name, 1)
del cache
db = self.init_old(cl)
getter = test.getter(db)
sqlite_res = getter(1)
if test.name.endswith('_index'):
val = float(val) if val is not None else 1.0
self.assertEqual(sqlite_res, val,
'Failed setting for %s with value %r, sqlite value not the same. val: %r != sqlite_val: %r'%(
test.name, val, val, sqlite_res))
else:
test.setter(db)(1, val)
old_cached_res = getter(1)
self.assertEqual(old_cached_res, cached_res,
'Failed setting for %s with value %r, cached value not the same. Old: %r != New: %r'%(
test.name, val, old_cached_res, cached_res))
db.refresh()
old_sqlite_res = getter(1)
self.assertEqual(old_sqlite_res, sqlite_res,
'Failed setting for %s, sqlite value not the same: %r != %r'%(
test.name, old_sqlite_res, sqlite_res))
del db
# }}}
def test_one_one(self): # {{{
'Test setting of values in one-one fields'
tests = [self.create_test('#yesno', (True, False, 'true', 'false', None))]
for name, getter, setter in (
('#series_index', None, None),
('series_index', 'series_index', 'set_series_index'),
('#float', None, None),
):
vals = ['1.5', None, 0, 1.0]
tests.append(self.create_test(name, tuple(vals), getter, setter))
for name, getter, setter in (
('pubdate', 'pubdate', 'set_pubdate'),
('timestamp', 'timestamp', 'set_timestamp'),
('#date', None, None),
):
tests.append(self.create_test(
name, ('2011-1-12', UNDEFINED_DATE, None), getter, setter))
for name, getter, setter in (
('title', 'title', 'set_title'),
('uuid', 'uuid', 'set_uuid'),
('author_sort', 'author_sort', 'set_author_sort'),
('sort', 'title_sort', 'set_title_sort'),
('#comments', None, None),
('comments', 'comments', 'set_comment'),
):
vals = ['something', None]
if name not in {'comments', '#comments'}:
# Setting text column to '' returns None in the new backend
# and '' in the old. I think None is more correct.
vals.append('')
if name == 'comments':
# Again new behavior of deleting comment rather than setting
# empty string is more correct.
vals.remove(None)
tests.append(self.create_test(name, tuple(vals), getter, setter))
self.run_tests(tests)
# }}}
def test_many_one_basic(self): # {{{
'Test the different code paths for writing to a many-one field'
cl = self.cloned_library
cache = self.init_cache(cl)
f = cache.fields['publisher']
item_ids = {f.ids_for_book(1)[0], f.ids_for_book(2)[0]}
val = 'Changed'
self.assertEqual(cache.set_field('publisher', {1:val, 2:val}), {1, 2})
cache2 = self.init_cache(cl)
for book_id in (1, 2):
for c in (cache, cache2):
self.assertEqual(c.field_for('publisher', book_id), val)
self.assertFalse(item_ids.intersection(set(c.fields['publisher'].table.id_map)))
del cache2
self.assertFalse(cache.set_field('publisher', {1:val, 2:val}))
val = val.lower()
self.assertFalse(cache.set_field('publisher', {1:val, 2:val},
allow_case_change=False))
self.assertEqual(cache.set_field('publisher', {1:val, 2:val}), {1, 2})
cache2 = self.init_cache(cl)
for book_id in (1, 2):
for c in (cache, cache2):
self.assertEqual(c.field_for('publisher', book_id), val)
del cache2
self.assertEqual(cache.set_field('publisher', {1:'new', 2:'New'}), {1, 2})
self.assertEqual(cache.field_for('publisher', 1).lower(), 'new')
self.assertEqual(cache.field_for('publisher', 2).lower(), 'new')
self.assertEqual(cache.set_field('publisher', {1:None, 2:'NEW'}), {1, 2})
self.assertEqual(len(f.table.id_map), 1)
self.assertEqual(cache.set_field('publisher', {2:None}), {2})
self.assertEqual(len(f.table.id_map), 0)
cache2 = self.init_cache(cl)
self.assertEqual(len(cache2.fields['publisher'].table.id_map), 0)
del cache2
self.assertEqual(cache.set_field('publisher', {1:'one', 2:'two',
3:'three'}), {1, 2, 3})
self.assertEqual(cache.set_field('publisher', {1:''}), {1})
self.assertEqual(cache.set_field('publisher', {1:'two'}), {1})
self.assertEqual(tuple(map(f.for_book, (1,2,3))), ('two', 'two', 'three'))
self.assertEqual(cache.set_field('publisher', {1:'Two'}), {1, 2})
cache2 = self.init_cache(cl)
self.assertEqual(tuple(map(f.for_book, (1,2,3))), ('Two', 'Two', 'three'))
del cache2
# Enum
self.assertFalse(cache.set_field('#enum', {1:'Not allowed'}))
self.assertEqual(cache.set_field('#enum', {1:'One', 2:'One', 3:'Three'}), {1, 3})
self.assertEqual(cache.set_field('#enum', {1:None}), {1})
cache2 = self.init_cache(cl)
for c in (cache, cache2):
for i, val in iteritems({1:None, 2:'One', 3:'Three'}):
self.assertEqual(c.field_for('#enum', i), val)
del cache2
# Rating
self.assertFalse(cache.set_field('rating', {1:6, 2:4}))
self.assertEqual(cache.set_field('rating', {1:0, 3:2}), {1, 3})
self.assertEqual(cache.set_field('#rating', {1:None, 2:4, 3:8}), {1, 2, 3})
cache2 = self.init_cache(cl)
for c in (cache, cache2):
for i, val in iteritems({1:None, 2:4, 3:2}):
self.assertEqual(c.field_for('rating', i), val)
for i, val in iteritems({1:None, 2:4, 3:8}):
self.assertEqual(c.field_for('#rating', i), val)
del cache2
# Series
self.assertFalse(cache.set_field('series',
{1:'a series one', 2:'a series one'}, allow_case_change=False))
self.assertEqual(cache.set_field('series', {3:'Series [3]'}), {3})
self.assertEqual(cache.set_field('#series', {1:'Series', 3:'Series'}),
{1, 3})
self.assertEqual(cache.set_field('#series', {2:'Series [0]'}), {2})
cache2 = self.init_cache(cl)
for c in (cache, cache2):
for i, val in iteritems({1:'A Series One', 2:'A Series One', 3:'Series'}):
self.assertEqual(c.field_for('series', i), val)
cs_indices = {1:c.field_for('#series_index', 1), 3:c.field_for('#series_index', 3)}
for i in (1, 2, 3):
self.assertEqual(c.field_for('#series', i), 'Series')
for i, val in iteritems({1:2, 2:1, 3:3}):
self.assertEqual(c.field_for('series_index', i), val)
for i, val in iteritems({1:cs_indices[1], 2:0, 3:cs_indices[3]}):
self.assertEqual(c.field_for('#series_index', i), val)
del cache2
# }}}
def test_many_many_basic(self): # {{{
'Test the different code paths for writing to a many-many field'
cl = self.cloned_library
cache = self.init_cache(cl)
ae, af, sf = self.assertEqual, self.assertFalse, cache.set_field
# Tags
ae(sf('#tags', {1:cache.field_for('tags', 1), 2:cache.field_for('tags', 2)}),
{1, 2})
for name in ('tags', '#tags'):
f = cache.fields[name]
af(sf(name, {1:('News', 'tag one')}, allow_case_change=False))
ae(sf(name, {1:'tag one, News'}), {1, 2})
ae(sf(name, {3:('tag two', 'sep,sep2')}), {2, 3})
ae(len(f.table.id_map), 4)
ae(sf(name, {1:None}), {1})
cache2 = self.init_cache(cl)
for c in (cache, cache2):
ae(c.field_for(name, 3), ('tag two', 'sep;sep2'))
ae(len(c.fields[name].table.id_map), 3)
ae(len(c.fields[name].table.id_map), 3)
ae(c.field_for(name, 1), ())
ae(c.field_for(name, 2), ('tag two', 'tag one'))
del cache2
# Authors
ae(sf('#authors', {k:cache.field_for('authors', k) for k in (1,2,3)}),
{1,2,3})
for name in ('authors', '#authors'):
f = cache.fields[name]
ae(len(f.table.id_map), 3)
af(cache.set_field(name, {3:'Unknown'}))
ae(cache.set_field(name, {3:'Kovid Goyal & Divok Layog'}), {3})
ae(cache.set_field(name, {1:'', 2:'An, Author'}), {1,2})
cache2 = self.init_cache(cl)
for c in (cache, cache2):
ae(len(c.fields[name].table.id_map), 4 if name =='authors' else 3)
ae(c.field_for(name, 3), ('Kovid Goyal', 'Divok Layog'))
ae(c.field_for(name, 2), ('An, Author',))
ae(c.field_for(name, 1), (_('Unknown'),) if name=='authors' else ())
if name == 'authors':
ae(c.field_for('author_sort', 1), author_to_author_sort(_('Unknown')))
ae(c.field_for('author_sort', 2), author_to_author_sort('An, Author'))
ae(c.field_for('author_sort', 3), author_to_author_sort('Kovid Goyal') + ' & ' + author_to_author_sort('Divok Layog'))
del cache2
ae(cache.set_field('authors', {1:'KoviD GoyaL'}), {1, 3})
ae(cache.field_for('author_sort', 1), 'GoyaL, KoviD')
ae(cache.field_for('author_sort', 3), 'GoyaL, KoviD & Layog, Divok')
# Languages
f = cache.fields['languages']
ae(f.table.id_map, {1: 'eng', 2: 'deu'})
ae(sf('languages', {1:''}), {1})
ae(cache.field_for('languages', 1), ())
ae(sf('languages', {2:('und',)}), {2})
af(f.table.id_map)
ae(sf('languages', {1:'eng,fra,deu', 2:'es,Dutch', 3:'English'}), {1, 2, 3})
ae(cache.field_for('languages', 1), ('eng', 'fra', 'deu'))
ae(cache.field_for('languages', 2), ('spa', 'nld'))
ae(cache.field_for('languages', 3), ('eng',))
ae(sf('languages', {3:None}), {3})
ae(cache.field_for('languages', 3), ())
ae(sf('languages', {1:'deu,fra,eng'}), {1}, 'Changing order failed')
ae(sf('languages', {2:'deu,eng,eng'}), {2})
cache2 = self.init_cache(cl)
for c in (cache, cache2):
ae(cache.field_for('languages', 1), ('deu', 'fra', 'eng'))
ae(cache.field_for('languages', 2), ('deu', 'eng'))
del cache2
# Identifiers
f = cache.fields['identifiers']
ae(sf('identifiers', {3: 'one:1,two:2'}), {3})
ae(sf('identifiers', {2:None}), {2})
ae(sf('identifiers', {1: {'test':'1', 'two':'2'}}), {1})
cache2 = self.init_cache(cl)
for c in (cache, cache2):
ae(c.field_for('identifiers', 3), {'one':'1', 'two':'2'})
ae(c.field_for('identifiers', 2), {})
ae(c.field_for('identifiers', 1), {'test':'1', 'two':'2'})
del cache2
# Test setting of title sort
ae(sf('title', {1:'The Moose', 2:'Cat'}), {1, 2})
cache2 = self.init_cache(cl)
for c in (cache, cache2):
ae(c.field_for('sort', 1), title_sort('The Moose'))
ae(c.field_for('sort', 2), title_sort('Cat'))
# Test setting with the same value repeated
ae(sf('tags', {3: ('a', 'b', 'a')}), {3})
ae(sf('tags', {3: ('x', 'X')}), {3}, 'Failed when setting tag twice with different cases')
ae(('x',), cache.field_for('tags', 3))
# Test setting of authors with | in their names (for legacy database
# format compatibility | is replaced by ,)
ae(sf('authors', {3: ('Some| Author',)}), {3})
ae(('Some, Author',), cache.field_for('authors', 3))
# }}}
def test_dirtied(self): # {{{
'Test the setting of the dirtied flag and the last_modified column'
cl = self.cloned_library
cache = self.init_cache(cl)
ae, af, sf = self.assertEqual, self.assertFalse, cache.set_field
# First empty dirtied
cache.dump_metadata()
af(cache.dirtied_cache)
af(self.init_cache(cl).dirtied_cache)
prev = cache.field_for('last_modified', 3)
from datetime import timedelta
import calibre.db.cache as c
utime = prev+timedelta(days=1)
onowf = c.nowf
c.nowf = lambda: utime
try:
ae(sf('title', {3:'xxx'}), {3})
self.assertTrue(3 in cache.dirtied_cache)
ae(cache.field_for('last_modified', 3), utime)
cache.dump_metadata()
raw = cache.read_backup(3)
from calibre.ebooks.metadata.opf2 import OPF
opf = OPF(BytesIO(raw))
ae(opf.title, 'xxx')
finally:
c.nowf = onowf
# }}}
def test_backup(self): # {{{
'Test the automatic backup of changed metadata'
cl = self.cloned_library
cache = self.init_cache(cl)
ae, af, sf = self.assertEqual, self.assertFalse, cache.set_field
# First empty dirtied
cache.dump_metadata()
af(cache.dirtied_cache)
from calibre.db.backup import MetadataBackup
interval = 0.01
mb = MetadataBackup(cache, interval=interval, scheduling_interval=0)
mb.start()
try:
ae(sf('title', {1:'title1', 2:'title2', 3:'title3'}), {1,2,3})
ae(sf('authors', {1:'author1 & author2', 2:'author1 & author2', 3:'author1 & author2'}), {1,2,3})
ae(sf('tags', {1:'tag1', 2:'tag1,tag2', 3:'XXX'}), {1,2,3})
ae(cache.set_link_map('authors', {'author1': 'link1'}), {1,2,3})
ae(cache.set_link_map('tags', {'XXX': 'YYY', 'tag2': 'link2'}), {2,3})
count = 6
while cache.dirty_queue_length() and count > 0:
mb.join(2)
count -= 1
af(cache.dirty_queue_length())
finally:
mb.stop()
mb.join(2)
af(mb.is_alive())
from calibre.ebooks.metadata.opf2 import OPF
book_ids = (1,2,3)
def read_all_formats():
fbefore = {}
for book_id in book_ids:
ff = fbefore[book_id] = {}
for fmt in cache.formats(book_id):
ff[fmt] = cache.format(book_id, fmt)
return fbefore
def read_all_extra_files(book_id=1):
ans = {}
bp = cache.field_for('path', book_id)
for (relpath, fobj, stat_result) in cache.backend.iter_extra_files(book_id, bp, cache.fields['formats']):
ans[relpath] = fobj.read()
return ans
for book_id in book_ids:
raw = cache.read_backup(book_id)
opf = OPF(BytesIO(raw))
ae(opf.title, 'title%d'%book_id)
ae(opf.authors, ['author1', 'author2'])
tested_fields = 'title authors tags'.split()
before = {f:cache.all_field_for(f, book_ids) for f in tested_fields}
lbefore = tuple(cache.get_all_link_maps_for_book(i) for i in book_ids)
fbefore = read_all_formats()
bookdir = os.path.dirname(cache.format_abspath(1, '__COVER_INTERNAL__'))
with open(os.path.join(bookdir, 'exf'), 'w') as f:
f.write('exf')
os.mkdir(os.path.join(bookdir, 'sub'))
with open(os.path.join(bookdir, 'sub', 'recurse'), 'w') as f:
f.write('recurse')
ebefore = read_all_extra_files()
authors = sorted(cache.all_field_ids('authors'))
h1 = cache.add_notes_resource(b'resource1', 'r1.jpg')
h2 = cache.add_notes_resource(b'resource2', 'r2.jpg')
doc = f'simple notes for an author <img src="{RESOURCE_URL_SCHEME}://{h1.replace(":", "/",1)}"> '
cache.set_notes_for('authors', authors[0], doc, resource_hashes=(h1,))
doc += f'2 <img src="{RESOURCE_URL_SCHEME}://{h2.replace(":", "/",1)}">'
cache.set_notes_for('authors', authors[1], doc, resource_hashes=(h1,h2))
notes_before = {cache.get_item_name('authors', aid): cache.export_note('authors', aid) for aid in authors}
cache.close()
from calibre.db.restore import Restore
restorer = Restore(cl)
restorer.start()
restorer.join(60)
af(restorer.is_alive())
cache = self.init_cache(cl)
ae(before, {f:cache.all_field_for(f, book_ids) for f in tested_fields})
ae(lbefore, tuple(cache.get_all_link_maps_for_book(i) for i in book_ids))
ae(fbefore, read_all_formats())
ae(ebefore, read_all_extra_files())
authors = sorted(cache.all_field_ids('authors'))
notes_after = {cache.get_item_name('authors', aid): cache.export_note('authors', aid) for aid in authors}
ae(notes_before, notes_after)
# }}}
def test_set_cover(self): # {{{
' Test setting of cover '
cache = self.init_cache()
ae = self.assertEqual
# Test removing a cover
ae(cache.field_for('cover', 1), 1)
ae(cache.set_cover({1:None}), {1})
ae(cache.field_for('cover', 1), 0)
img = IMG
# Test setting a cover
ae(cache.set_cover({bid:img for bid in (1, 2, 3)}), {1, 2, 3})
old = self.init_old()
for book_id in (1, 2, 3):
ae(cache.cover(book_id), img, 'Cover was not set correctly for book %d' % book_id)
ae(cache.field_for('cover', book_id), 1)
ae(old.cover(book_id, index_is_id=True), img, 'Cover was not set correctly for book %d' % book_id)
self.assertTrue(old.has_cover(book_id))
old.close()
old.break_cycles()
del old
# }}}
def test_set_metadata(self): # {{{
' Test setting of metadata '
ae = self.assertEqual
cache = self.init_cache(self.cloned_library)
# Check that changing title/author updates the path
mi = cache.get_metadata(1)
old_path = cache.field_for('path', 1)
old_title, old_author = mi.title, mi.authors[0]
ae(old_path, f'{old_author}/{old_title} (1)')
mi.title, mi.authors = 'New Title', ['New Author']
cache.set_metadata(1, mi)
ae(cache.field_for('path', 1), f'{mi.authors[0]}/{mi.title} (1)')
p = cache.format_abspath(1, 'FMT1')
self.assertTrue(mi.authors[0] in p and mi.title in p)
# Compare old and new set_metadata()
db = self.init_old(self.cloned_library)
mi = db.get_metadata(1, index_is_id=True, get_cover=True, cover_as_data=True)
mi2 = db.get_metadata(3, index_is_id=True, get_cover=True, cover_as_data=True)
db.set_metadata(2, mi)
db.set_metadata(1, mi2, force_changes=True)
oldmi = db.get_metadata(2, index_is_id=True, get_cover=True, cover_as_data=True)
oldmi2 = db.get_metadata(1, index_is_id=True, get_cover=True, cover_as_data=True)
db.close()
del db
cache = self.init_cache(self.cloned_library)
cache.set_metadata(2, mi)
nmi = cache.get_metadata(2, get_cover=True, cover_as_data=True)
ae(oldmi.cover_data, nmi.cover_data)
self.compare_metadata(nmi, oldmi, exclude={'last_modified', 'format_metadata', 'formats'})
cache.set_metadata(1, mi2, force_changes=True)
nmi2 = cache.get_metadata(1, get_cover=True, cover_as_data=True)
self.compare_metadata(nmi2, oldmi2, exclude={'last_modified', 'format_metadata', 'formats'})
cache = self.init_cache(self.cloned_library)
mi = cache.get_metadata(1)
otags = mi.tags
mi.tags = [x.upper() for x in mi.tags]
cache.set_metadata(3, mi)
self.assertEqual(set(otags), set(cache.field_for('tags', 3)), 'case changes should not be allowed in set_metadata')
# test that setting authors without author sort results in an
# auto-generated authors sort
mi = Metadata('empty', ['a1', 'a2'])
cache.set_metadata(1, mi)
self.assertEqual(cache.get_item_ids('authors', ('a1', 'a2')), cache.get_item_ids('authors', ('a1', 'a2'), case_sensitive=True))
self.assertEqual(
set(cache.get_item_ids('authors', ('A1', 'a2')).values()),
set(cache.get_item_ids('authors', ('a1', 'a2'), case_sensitive=True).values()))
self.assertEqual('a1 & a2', cache.field_for('author_sort', 1))
cache.set_sort_for_authors({cache.get_item_id('authors', 'a1', case_sensitive=True): 'xy'})
self.assertEqual('xy & a2', cache.field_for('author_sort', 1))
mi = Metadata('empty', ['a1'])
cache.set_metadata(1, mi)
self.assertEqual('xy', cache.field_for('author_sort', 1))
# }}}
def test_conversion_options(self): # {{{
' Test saving of conversion options '
cache = self.init_cache()
all_ids = cache.all_book_ids()
self.assertFalse(cache.has_conversion_options(all_ids))
self.assertIsNone(cache.conversion_options(1))
op1, op2 = b"{'xx':'yy'}", b"{'yy':'zz'}"
cache.set_conversion_options({1:op1, 2:op2})
self.assertTrue(cache.has_conversion_options(all_ids))
self.assertEqual(cache.conversion_options(1), op1)
self.assertEqual(cache.conversion_options(2), op2)
cache.set_conversion_options({1:op2})
self.assertEqual(cache.conversion_options(1), op2)
cache.delete_conversion_options(all_ids)
self.assertFalse(cache.has_conversion_options(all_ids))
# }}}
def test_remove_items(self): # {{{
' Test removal of many-(many,one) items '
cache = self.init_cache()
tmap = cache.get_id_map('tags')
self.assertEqual(cache.remove_items('tags', tmap), {1, 2})
tmap = cache.get_id_map('#tags')
t = {v:k for k, v in iteritems(tmap)}['My Tag Two']
self.assertEqual(cache.remove_items('#tags', (t,)), {1, 2})
smap = cache.get_id_map('series')
self.assertEqual(cache.remove_items('series', smap), {1, 2})
smap = cache.get_id_map('#series')
s = {v:k for k, v in iteritems(smap)}['My Series Two']
self.assertEqual(cache.remove_items('#series', (s,)), {1})
for c in (cache, self.init_cache()):
self.assertFalse(c.get_id_map('tags'))
self.assertFalse(c.all_field_names('tags'))
for bid in c.all_book_ids():
self.assertFalse(c.field_for('tags', bid))
self.assertEqual(len(c.get_id_map('#tags')), 1)
self.assertEqual(c.all_field_names('#tags'), {'My Tag One'})
for bid in c.all_book_ids():
self.assertIn(c.field_for('#tags', bid), ((), ('My Tag One',)))
for bid in (1, 2):
self.assertEqual(c.field_for('series_index', bid), 1.0)
self.assertFalse(c.get_id_map('series'))
self.assertFalse(c.all_field_names('series'))
for bid in c.all_book_ids():
self.assertFalse(c.field_for('series', bid))
self.assertEqual(c.field_for('series_index', 1), 1.0)
self.assertEqual(c.all_field_names('#series'), {'My Series One'})
for bid in c.all_book_ids():
self.assertIn(c.field_for('#series', bid), (None, 'My Series One'))
# Now test with restriction
cache = self.init_cache()
cache.set_field('tags', {1:'a,b,c', 2:'b,a', 3:'x,y,z'})
cache.set_field('series', {1:'a', 2:'a', 3:'b'})
cache.set_field('series_index', {1:8, 2:9, 3:3})
tmap, smap = cache.get_id_map('tags'), cache.get_id_map('series')
self.assertEqual(cache.remove_items('tags', tmap, restrict_to_book_ids=()), set())
self.assertEqual(cache.remove_items('tags', tmap, restrict_to_book_ids={1}), {1})
self.assertEqual(cache.remove_items('series', smap, restrict_to_book_ids=()), set())
self.assertEqual(cache.remove_items('series', smap, restrict_to_book_ids=(1,)), {1})
c2 = self.init_cache()
for c in (cache, c2):
self.assertEqual(c.field_for('tags', 1), ())
self.assertEqual(c.field_for('tags', 2), ('b', 'a'))
self.assertNotIn('c', set(itervalues(c.get_id_map('tags'))))
self.assertEqual(c.field_for('series', 1), None)
self.assertEqual(c.field_for('series', 2), 'a')
self.assertEqual(c.field_for('series_index', 1), 1.0)
self.assertEqual(c.field_for('series_index', 2), 9)
# }}}
def test_rename_items(self): # {{{
' Test renaming of many-(many,one) items '
cl = self.cloned_library
cache = self.init_cache(cl)
# Check that renaming authors updates author sort and path
a = {v:k for k, v in iteritems(cache.get_id_map('authors'))}['Unknown']
self.assertEqual(cache.rename_items('authors', {a:'New Author'})[0], {3})
a = {v:k for k, v in iteritems(cache.get_id_map('authors'))}['Author One']
self.assertEqual(cache.rename_items('authors', {a:'Author Two'})[0], {1, 2})
for c in (cache, self.init_cache(cl)):
self.assertEqual(c.all_field_names('authors'), {'New Author', 'Author Two'})
self.assertEqual(c.field_for('author_sort', 3), 'Author, New')
self.assertIn('New Author/', c.field_for('path', 3))
self.assertEqual(c.field_for('authors', 1), ('Author Two',))
self.assertEqual(c.field_for('author_sort', 1), 'Two, Author')
t = {v:k for k, v in iteritems(cache.get_id_map('tags'))}['Tag One']
# Test case change
self.assertEqual(cache.rename_items('tags', {t:'tag one'}), ({1, 2}, {t:t}))
for c in (cache, self.init_cache(cl)):
self.assertEqual(c.all_field_names('tags'), {'tag one', 'Tag Two', 'News'})
self.assertEqual(set(c.field_for('tags', 1)), {'tag one', 'News'})
self.assertEqual(set(c.field_for('tags', 2)), {'tag one', 'Tag Two'})
# Test new name
self.assertEqual(cache.rename_items('tags', {t:'t1'})[0], {1,2})
for c in (cache, self.init_cache(cl)):
self.assertEqual(c.all_field_names('tags'), {'t1', 'Tag Two', 'News'})
self.assertEqual(set(c.field_for('tags', 1)), {'t1', 'News'})
self.assertEqual(set(c.field_for('tags', 2)), {'t1', 'Tag Two'})
# Test rename to existing
self.assertEqual(cache.rename_items('tags', {t:'Tag Two'})[0], {1,2})
for c in (cache, self.init_cache(cl)):
self.assertEqual(c.all_field_names('tags'), {'Tag Two', 'News'})
self.assertEqual(set(c.field_for('tags', 1)), {'Tag Two', 'News'})
self.assertEqual(set(c.field_for('tags', 2)), {'Tag Two'})
# Test on a custom column
t = {v:k for k, v in iteritems(cache.get_id_map('#tags'))}['My Tag One']
self.assertEqual(cache.rename_items('#tags', {t:'My Tag Two'})[0], {2})
for c in (cache, self.init_cache(cl)):
self.assertEqual(c.all_field_names('#tags'), {'My Tag Two'})
self.assertEqual(set(c.field_for('#tags', 2)), {'My Tag Two'})
# Test a Many-one field
s = {v:k for k, v in iteritems(cache.get_id_map('series'))}['A Series One']
# Test case change
self.assertEqual(cache.rename_items('series', {s:'a series one'}), ({1, 2}, {s:s}))
for c in (cache, self.init_cache(cl)):
self.assertEqual(c.all_field_names('series'), {'a series one'})
self.assertEqual(c.field_for('series', 1), 'a series one')
self.assertEqual(c.field_for('series_index', 1), 2.0)
# Test new name
self.assertEqual(cache.rename_items('series', {s:'series'})[0], {1, 2})
for c in (cache, self.init_cache(cl)):
self.assertEqual(c.all_field_names('series'), {'series'})
self.assertEqual(c.field_for('series', 1), 'series')
self.assertEqual(c.field_for('series', 2), 'series')
self.assertEqual(c.field_for('series_index', 1), 2.0)
s = {v:k for k, v in iteritems(cache.get_id_map('#series'))}['My Series One']
# Test custom column with rename to existing
self.assertEqual(cache.rename_items('#series', {s:'My Series Two'})[0], {2})
for c in (cache, self.init_cache(cl)):
self.assertEqual(c.all_field_names('#series'), {'My Series Two'})
self.assertEqual(c.field_for('#series', 2), 'My Series Two')
self.assertEqual(c.field_for('#series_index', 1), 3.0)
self.assertEqual(c.field_for('#series_index', 2), 4.0)
# Test renaming many-many items to multiple items
cache = self.init_cache(self.cloned_library)
t = {v:k for k, v in iteritems(cache.get_id_map('tags'))}['Tag One']
affected_books, id_map = cache.rename_items('tags', {t:'Something, Else, Entirely'})
self.assertEqual({1, 2}, affected_books)
tmap = cache.get_id_map('tags')
self.assertEqual('Something', tmap[id_map[t]])
self.assertEqual(1, len(id_map))
f1, f2 = cache.field_for('tags', 1), cache.field_for('tags', 2)
for f in (f1, f2):
for t in 'Something,Else,Entirely'.split(','):
self.assertIn(t, f)
self.assertNotIn('Tag One', f)
# Test with restriction
cache = self.init_cache()
cache.set_field('tags', {1:'a,b,c', 2:'x,y,z', 3:'a,x,z'})
tmap = {v:k for k, v in iteritems(cache.get_id_map('tags'))}
self.assertEqual(cache.rename_items('tags', {tmap['a']:'r'}, restrict_to_book_ids=()), (set(), {}))
self.assertEqual(cache.rename_items('tags', {tmap['a']:'r', tmap['b']:'q'}, restrict_to_book_ids=(1,))[0], {1})
self.assertEqual(cache.rename_items('tags', {tmap['x']:'X'}, restrict_to_book_ids=(2,))[0], {2})
c2 = self.init_cache()
for c in (cache, c2):
self.assertEqual(c.field_for('tags', 1), ('r', 'q', 'c'))
self.assertEqual(c.field_for('tags', 2), ('X', 'y', 'z'))
self.assertEqual(c.field_for('tags', 3), ('a', 'X', 'z'))
# }}}
def test_composite_cache(self): # {{{
' Test that the composite field cache is properly invalidated on writes '
cache = self.init_cache()
cache.create_custom_column('tc', 'TC', 'composite', False, display={
'composite_template':'{title} {author_sort} {title_sort} {formats} {tags} {series} {series_index}'})
cache = self.init_cache()
def test_invalidate():
c = self.init_cache()
for bid in cache.all_book_ids():
self.assertEqual(cache.field_for('#tc', bid), c.field_for('#tc', bid))
cache.set_field('title', {1:'xx', 3:'yy'})
test_invalidate()
cache.set_field('series_index', {1:9, 3:11})
test_invalidate()
cache.rename_items('tags', {cache.get_item_id('tags', 'Tag One'):'xxx', cache.get_item_id('tags', 'News'):'news'})
test_invalidate()
cache.remove_items('tags', (cache.get_item_id('tags', 'news'),))
test_invalidate()
cache.set_sort_for_authors({cache.get_item_id('authors', 'Author One'):'meow'})
test_invalidate()
cache.remove_formats({1:{'FMT1'}})
test_invalidate()
cache.add_format(1, 'ADD', BytesIO(b'xxxx'))
test_invalidate()
# }}}
def test_dump_and_restore(self): # {{{
' Test roundtripping the db through SQL '
import warnings
with warnings.catch_warnings():
# on python 3.10 apsw raises a deprecation warning which causes this test to fail on CI
warnings.simplefilter('ignore', DeprecationWarning)
cache = self.init_cache()
uv = int(cache.backend.user_version)
all_ids = cache.all_book_ids()
cache.dump_and_restore()
self.assertEqual(cache.set_field('title', {1:'nt'}), {1}, 'database connection broken')
cache = self.init_cache()
self.assertEqual(cache.all_book_ids(), all_ids, 'dump and restore broke database')
self.assertEqual(int(cache.backend.user_version), uv)
# }}}
def test_set_author_data(self): # {{{
cache = self.init_cache()
adata = cache.author_data()
ldata = {aid:str(aid) for aid in adata}
self.assertEqual({1,2,3}, cache.set_link_for_authors(ldata))
for c in (cache, self.init_cache()):
self.assertEqual(ldata, {aid:d['link'] for aid, d in iteritems(c.author_data())})
self.assertEqual({3}, cache.set_link_for_authors({aid:'xxx' if aid == max(adata) else str(aid) for aid in adata}),
'Setting the author link to the same value as before, incorrectly marked some books as dirty')
sdata = {aid:'%s, changed' % aid for aid in adata}
self.assertEqual({1,2,3}, cache.set_sort_for_authors(sdata))
for bid in (1, 2, 3):
self.assertIn(', changed', cache.field_for('author_sort', bid))
sdata = {aid:'%s, changed' % (aid*2 if aid == max(adata) else aid) for aid in adata}
self.assertEqual({3}, cache.set_sort_for_authors(sdata),
'Setting the author sort to the same value as before, incorrectly marked some books as dirty')
# }}}
def test_fix_case_duplicates(self): # {{{
' Test fixing of databases that have items in is_many fields that differ only by case '
ae = self.assertEqual
cache = self.init_cache()
conn = cache.backend.conn
conn.execute('INSERT INTO publishers (name) VALUES ("mūs")')
lid = conn.last_insert_rowid()
conn.execute('INSERT INTO publishers (name) VALUES ("MŪS")')
uid = conn.last_insert_rowid()
conn.execute('DELETE FROM books_publishers_link')
conn.execute('INSERT INTO books_publishers_link (book,publisher) VALUES (1, %d)' % lid)
conn.execute('INSERT INTO books_publishers_link (book,publisher) VALUES (2, %d)' % uid)
conn.execute('INSERT INTO books_publishers_link (book,publisher) VALUES (3, %d)' % uid)
cache.reload_from_db()
t = cache.fields['publisher'].table
for x in (lid, uid):
self.assertIn(x, t.id_map)
self.assertIn(x, t.col_book_map)
ae(t.book_col_map[1], lid)
ae(t.book_col_map[2], uid)
t.fix_case_duplicates(cache.backend)
for c in (cache, self.init_cache()):
t = c.fields['publisher'].table
self.assertNotIn(uid, t.id_map)
self.assertNotIn(uid, t.col_book_map)
for bid in (1, 2, 3):
ae(c.field_for('publisher', bid), "mūs")
c.close()
cache = self.init_cache()
conn = cache.backend.conn
conn.execute('INSERT INTO tags (name) VALUES ("mūūs")')
lid = conn.last_insert_rowid()
conn.execute('INSERT INTO tags (name) VALUES ("MŪŪS")')
uid = conn.last_insert_rowid()
conn.execute('INSERT INTO tags (name) VALUES ("mūŪS")')
mid = conn.last_insert_rowid()
conn.execute('INSERT INTO tags (name) VALUES ("t")')
norm = conn.last_insert_rowid()
conn.execute('DELETE FROM books_tags_link')
for book_id, vals in iteritems({1:(lid, uid), 2:(uid, mid), 3:(lid, norm)}):
conn.executemany('INSERT INTO books_tags_link (book,tag) VALUES (?,?)',
tuple((book_id, x) for x in vals))
cache.reload_from_db()
t = cache.fields['tags'].table
for x in (lid, uid, mid):
self.assertIn(x, t.id_map)
self.assertIn(x, t.col_book_map)
t.fix_case_duplicates(cache.backend)
for c in (cache, self.init_cache()):
t = c.fields['tags'].table
for x in (uid, mid):
self.assertNotIn(x, t.id_map)
self.assertNotIn(x, t.col_book_map)
ae(c.field_for('tags', 1), (t.id_map[lid],))
ae(c.field_for('tags', 2), (t.id_map[lid],), 'failed for book 2')
ae(c.field_for('tags', 3), (t.id_map[lid], t.id_map[norm]))
# }}}
def test_preferences(self): # {{{
' Test getting and setting of preferences, especially with mutable objects '
cache = self.init_cache()
changes = []
cache.backend.conn.setupdatehook(lambda typ, dbname, tblname, rowid: changes.append(rowid))
prefs = cache.backend.prefs
prefs['test mutable'] = [1, 2, 3]
self.assertEqual(len(changes), 1)
a = prefs['test mutable']
a.append(4)
self.assertIn(4, prefs['test mutable'])
prefs['test mutable'] = a
self.assertEqual(len(changes), 2)
prefs.load_from_db()
self.assertIn(4, prefs['test mutable'])
prefs['test mutable'] = {k:k for k in range(10)}
self.assertEqual(len(changes), 3)
prefs['test mutable'] = {k:k for k in reversed(range(10))}
self.assertEqual(len(changes), 3, 'The database was written to despite there being no change in value')
# }}}
def test_annotations(self): # {{{
'Test handling of annotations'
from calibre.utils.date import EPOCH, utcnow
cl = self.cloned_library
cache = self.init_cache(cl)
# First empty dirtied
cache.dump_metadata()
self.assertFalse(cache.dirtied_cache)
def a(**kw):
ts = utcnow()
kw['timestamp'] = utcnow().isoformat()
return kw, (ts - EPOCH).total_seconds()
annot_list = [
a(type='bookmark', title='bookmark1 changed', seq=1),
a(type='highlight', highlighted_text='text1', uuid='1', seq=2),
a(type='highlight', highlighted_text='text2', uuid='2', seq=3, notes='notes2 some word changed again'),
]
def map_as_list(amap):
ans = []
for items in amap.values():
ans.extend(items)
ans.sort(key=lambda x:x['seq'])
return ans
cache.set_annotations_for_book(1, 'moo', annot_list)
amap = cache.annotations_map_for_book(1, 'moo')
self.assertEqual(3, len(cache.all_annotations_for_book(1)))
self.assertEqual([x[0] for x in annot_list], map_as_list(amap))
self.assertFalse(cache.dirtied_cache)
cache.check_dirtied_annotations()
self.assertEqual(set(cache.dirtied_cache), {1})
cache.dump_metadata()
cache.check_dirtied_annotations()
self.assertFalse(cache.dirtied_cache)
# Test searching
results = cache.search_annotations('"changed"')
self.assertEqual([1, 3], [x['id'] for x in results])
results = cache.search_annotations('"changed"', annotation_type='bookmark')
self.assertEqual([1], [x['id'] for x in results])
results = cache.search_annotations('"Changed"') # changed and change stem differently in english and other euro languages
self.assertEqual([1, 3], [x['id'] for x in results])
results = cache.search_annotations('"SOMe"')
self.assertEqual([3], [x['id'] for x in results])
results = cache.search_annotations('"change"', use_stemming=False)
self.assertFalse(results)
results = cache.search_annotations('"bookmark1"', highlight_start='[', highlight_end=']')
self.assertEqual(results[0]['text'], '[bookmark1] changed')
results = cache.search_annotations('"word"', highlight_start='[', highlight_end=']', snippet_size=3)
self.assertEqual(results[0]['text'], '…some [word] changed…')
self.assertRaises(FTSQueryError, cache.search_annotations, 'AND OR')
fts_l = [a(type='bookmark', title='路坎坷走来', seq=1),]
cache.set_annotations_for_book(1, 'moo', fts_l)
results = cache.search_annotations('路', highlight_start='[', highlight_end=']')
self.assertEqual(results[0]['text'], '[路]坎坷走来')
annot_list[0][0]['title'] = 'changed title'
cache.set_annotations_for_book(1, 'moo', annot_list)
amap = cache.annotations_map_for_book(1, 'moo')
self.assertEqual([x[0] for x in annot_list], map_as_list(amap))
del annot_list[1]
cache.set_annotations_for_book(1, 'moo', annot_list)
amap = cache.annotations_map_for_book(1, 'moo')
self.assertEqual([x[0] for x in annot_list], map_as_list(amap))
cache.check_dirtied_annotations()
cache.dump_metadata()
from calibre.ebooks.metadata.opf2 import OPF
raw = cache.read_backup(1)
opf = OPF(BytesIO(raw))
cache.restore_annotations(1, list(opf.read_annotations()))
amap = cache.annotations_map_for_book(1, 'moo')
self.assertEqual([x[0] for x in annot_list], map_as_list(amap))
# }}}
def test_changed_events(self): # {{{
def ae(l, r):
# We need to sleep a bit to allow events to happen on its thread
import time
st = time.monotonic()
while time.monotonic() - st < 1:
time.sleep(0.01)
try:
self.assertEqual(l, r)
return
except Exception:
pass
self.assertEqual(l, r)
cache = self.init_cache(self.cloned_library)
ae(cache.all_book_ids(), {1, 2, 3})
event_set = set()
def event_func(t, library_id, *args):
nonlocal event_set, ae
event_set.update(args[0][1])
cache.add_listener(event_func)
# Test that setting metadata to itself doesn't generate any events
for id_ in cache.all_book_ids():
cache.set_metadata(id_, cache.get_metadata(id_))
ae(event_set, set())
# test setting a single field
cache.set_field('tags', {1:'foo'})
ae(event_set, {1})
# test setting multiple books. Book 1 shouldn't get an event because it
# isn't being changed
event_set = set()
cache.set_field('tags', {1:'foo', 2:'bar', 3:'mumble'})
ae(event_set, {2, 3})
# test setting a many-many field to empty
event_set = set()
cache.set_field('tags', {1:''})
ae(event_set, {1,})
event_set = set()
cache.set_field('tags', {1:''})
ae(event_set, set())
# test setting title
event_set = set()
cache.set_field('title', {1:'Book 1'})
ae(event_set, {1})
ae(cache.field_for('title', 1), 'Book 1')
# test setting series
event_set = set()
cache.set_field('series', {1:'GreatBooks [1]'})
cache.set_field('series', {2:'GreatBooks [0]'})
ae(event_set, {1,2})
ae(cache.field_for('series', 1), 'GreatBooks')
ae(cache.field_for('series_index', 1), 1.0)
ae(cache.field_for('series', 2), 'GreatBooks')
ae(cache.field_for('series_index', 2), 0.0)
# now series_index
event_set = set()
cache.set_field('series_index', {1:2})
ae(event_set, {1})
ae(cache.field_for('series_index', 1), 2.0)
event_set = set()
cache.set_field('series_index', {1:2, 2:3.5}) # book 1 isn't changed
ae(event_set, {2})
ae(cache.field_for('series_index', 1), 2.0)
ae(cache.field_for('series_index', 2), 3.5)
def test_link_maps(self):
cache = self.init_cache()
# Add two tags
cache.set_field('tags', {1:'foo'})
self.assertEqual(('foo',), cache.field_for('tags', 1), 'Setting tag foo failed')
cache.set_field('tags', {1:'foo, bar'})
self.assertEqual(('foo', 'bar'), cache.field_for('tags', 1), 'Adding second tag failed')
# Check adding a link
links = cache.get_link_map('tags')
self.assertDictEqual(links, {}, 'Initial tags link dict is not empty')
links['foo'] = 'url'
cache.set_link_map('tags', links)
links2 = cache.get_link_map('tags')
self.assertDictEqual(links2, links, 'tags link dict mismatch')
# Check getting links for a book and that links are correct
cache.set_field('publisher', {1:'random'})
cache.set_link_map('publisher', {'random': 'url2'})
links = cache.get_all_link_maps_for_book(1)
self.assertSetEqual({v for v in links.keys()}, {'tags', 'publisher'}, 'Wrong link keys')
self.assertSetEqual({v for v in links['tags'].keys()}, {'foo', }, 'Should be "foo"')
self.assertSetEqual({v for v in links['publisher'].keys()}, {'random', }, 'Should be "random"')
self.assertEqual('url', links['tags']['foo'], 'link for tag foo is wrong')
self.assertEqual('url2', links['publisher']['random'], 'link for publisher random is wrong')
# Check that renaming a tag keeps the link and clears the link map cache for the book
self.assertTrue(1 in cache.link_maps_cache, "book not in link_map_cache")
tag_id = cache.get_item_id('tags', 'foo')
cache.rename_items('tags', {tag_id: 'foobar'})
self.assertTrue(1 not in cache.link_maps_cache, "book still in link_map_cache")
links = cache.get_link_map('tags')
self.assertTrue('foobar' in links, "rename foo lost the link")
self.assertEqual(links['foobar'], 'url', "The link changed contents")
links = cache.get_all_link_maps_for_book(1)
self.assertTrue(1 in cache.link_maps_cache, "book not put back into link_map_cache")
self.assertDictEqual({'publisher': {'random': 'url2'}, 'tags': {'foobar': 'url'}},
links, "book links incorrect after tag rename")
# Check ProxyMetadata
mi = cache.get_proxy_metadata(1)
self.assertDictEqual({'publisher': {'random': 'url2'}, 'tags': {'foobar': 'url'}},
mi.link_maps, "ProxyMetadata didn't return the right link map")
# Now test deleting the links.
links = cache.get_link_map('tags')
to_del = {l:'' for l in links.keys()}
cache.set_link_map('tags', to_del)
self.assertEqual({}, cache.get_link_map('tags'), 'links on tags were not deleted')
links = cache.get_link_map('publisher')
to_del = {l:'' for l in links.keys()}
cache.set_link_map('publisher', to_del)
self.assertEqual({}, cache.get_link_map('publisher'), 'links on publisher were not deleted')
self.assertEqual({}, cache.get_all_link_maps_for_book(1), 'Not all links for book were deleted')
# }}}
| 49,072 | Python | .py | 940 | 41.411702 | 138 | 0.567556 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,090 | notes.py | kovidgoyal_calibre/src/calibre/db/tests/notes.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2023, Kovid Goyal <kovid at kovidgoyal.net>
import os
import shutil
import tempfile
import time
from operator import itemgetter
from calibre.db.tests.base import BaseTest
from calibre.utils.resources import get_image_path
def test_notes_restore(self: 'NotesTest'):
cache, notes = self.create_notes_db()
authors = sorted(cache.all_field_ids('authors'))
doc = 'simple notes for an author'
h1 = cache.add_notes_resource(b'resource1', 'r1.jpg')
h2 = cache.add_notes_resource(b'resource2', 'r1.jpg')
cache.set_notes_for('authors', authors[0], doc, resource_hashes=(h1, h2))
doc2 = 'simple notes for an author2'
cache.set_notes_for('authors', authors[1], doc2, resource_hashes=(h2,))
def test_notes_api(self: 'NotesTest'):
cache, notes = self.create_notes_db()
authors = sorted(cache.all_field_ids('authors'))
self.ae(cache.notes_for('authors', authors[0]), '')
doc = 'simple notes for an author'
h1 = cache.add_notes_resource(b'resource1', 'r1.jpg')
h2 = cache.add_notes_resource(b'resource2', 'r1.jpg')
self.ae(cache.get_notes_resource(h1)['name'], 'r1.jpg')
self.ae(cache.get_notes_resource(h2)['name'], 'r1-1.jpg')
note_id = cache.set_notes_for('authors', authors[0], doc, resource_hashes=(h1, h2))
self.ae(cache.notes_for('authors', authors[0]), doc)
self.ae(cache.notes_resources_used_by('authors', authors[0]), frozenset({h1, h2}))
self.ae(cache.get_notes_resource(h1)['data'], b'resource1')
self.ae(cache.get_notes_resource(h2)['data'], b'resource2')
doc2 = 'a different note to replace the first one'
self.ae(note_id, cache.set_notes_for('authors', authors[0], doc2, resource_hashes=(h1,)))
self.ae(cache.notes_for('authors', authors[0]), doc2)
self.ae(cache.notes_resources_used_by('authors', authors[0]), frozenset({h1}))
self.ae(cache.get_notes_resource(h1)['data'], b'resource1')
self.ae(cache.get_notes_resource(h2), None)
self.assertTrue(os.path.exists(notes.path_for_resource(h1)))
self.assertFalse(os.path.exists(notes.path_for_resource(h2)))
# check retirement
h2 = cache.add_notes_resource(b'resource2', 'r1.jpg')
self.ae(note_id, cache.set_notes_for('authors', authors[0], doc2, resource_hashes=(h1,h2)))
self.ae(-1, cache.set_notes_for('authors', authors[0], ''))
self.ae(cache.notes_for('authors', authors[0]), '')
self.ae(cache.notes_resources_used_by('authors', authors[0]), frozenset())
before = os.listdir(notes.retired_dir)
self.ae(len(before), 1)
h1 = cache.add_notes_resource(b'resource1', 'r1.jpg')
h2 = cache.add_notes_resource(b'resource2', 'r1.jpg')
nnote_id = cache.set_notes_for('authors', authors[1], doc, resource_hashes=(h1, h2))
self.assertNotEqual(note_id, nnote_id)
self.ae(-1, cache.set_notes_for('authors', authors[1], ''))
after = os.listdir(notes.retired_dir)
self.ae(len(after), 1)
self.assertNotEqual(before, after)
self.assertGreater(cache.unretire_note_for('authors', authors[1]), nnote_id)
self.assertFalse(os.listdir(notes.retired_dir))
self.ae(cache.notes_for('authors', authors[1]), doc)
self.ae(cache.notes_resources_used_by('authors', authors[1]), frozenset({h1, h2}))
self.ae(cache.get_notes_resource(h1)['data'], b'resource1')
self.ae(cache.get_notes_resource(h2)['data'], b'resource2')
# test that retired entries are removed when setting a non-empty value
h1 = cache.add_notes_resource(b'resource1', 'r1.jpg')
cache.set_notes_for('authors', authors[0], doc2, resource_hashes=(h1,))
self.ae(len(os.listdir(notes.retired_dir)), 0)
cache.set_notes_for('authors', authors[0], '', resource_hashes=())
self.ae(len(os.listdir(notes.retired_dir)), 1)
cache.set_notes_for('authors', authors[0], doc2, resource_hashes=(h1,))
self.ae(len(os.listdir(notes.retired_dir)), 0)
cache.set_notes_for('authors', authors[0], '', resource_hashes=())
self.ae(len(os.listdir(notes.retired_dir)), 1)
def test_cache_api(self: 'NotesTest'):
cache, notes = self.create_notes_db()
authors = cache.field_for('authors', 1)
author_id = cache.get_item_id('authors', authors[0])
doc = 'simple notes for an author'
h1 = cache.add_notes_resource(b'resource1', 'r1.jpg')
h2 = cache.add_notes_resource(b'resource2', 'r1.jpg')
cache.set_notes_for('authors', author_id, doc, resource_hashes=(h1, h2))
nd = cache.notes_data_for('authors', author_id)
self.ae(nd, {'id': 1, 'ctime': nd['ctime'], 'mtime': nd['ctime'], 'searchable_text': authors[0] + '\n' + doc,
'doc': doc, 'resource_hashes': frozenset({h1, h2})})
time.sleep(0.01)
cache.set_notes_for('authors', author_id, doc, resource_hashes=(h1, h2))
n2d = cache.notes_data_for('authors', author_id)
self.ae(nd['ctime'], n2d['ctime'])
self.assertGreater(n2d['mtime'], nd['mtime'])
# test renaming to a new author preserves notes
cache.rename_items('authors', {author_id: 'renamed author'})
raid = cache.get_item_id('authors', 'renamed author')
self.ae(cache.notes_resources_used_by('authors', raid), frozenset({h1, h2}))
self.ae(cache.get_notes_resource(h1)['data'], b'resource1')
self.ae(cache.get_notes_resource(h2)['data'], b'resource2')
# test renaming to an existing author preserves notes
cache.rename_items('authors', {raid: 'Author One'})
raid = cache.get_item_id('authors', 'Author One')
self.ae(cache.notes_resources_used_by('authors', raid), frozenset({h1, h2}))
self.ae(cache.get_notes_resource(h1)['data'], b'resource1')
self.ae(cache.get_notes_resource(h2)['data'], b'resource2')
# test removing author from db retires notes
cache.set_field('authors', {bid:('New Author',) for bid in cache.all_book_ids()})
self.ae(len(cache.all_field_ids('authors')), 1)
self.ae(len(os.listdir(notes.retired_dir)), 1)
# test re-using of retired note
cache.set_field('authors', {1:'Author One'})
author_id = cache.get_item_id('authors', 'Author One')
self.ae(cache.notes_resources_used_by('authors', author_id), frozenset({h1, h2}))
self.ae(cache.get_notes_resource(h1)['data'], b'resource1')
self.ae(cache.get_notes_resource(h2)['data'], b'resource2')
self.assertFalse(os.listdir(notes.retired_dir))
# test delete custom column with notes
tags = cache.field_for('#tags', 1)
tag_id = cache.get_item_id('#tags', tags[0])
h1 = cache.add_notes_resource(b'resource1t', 'r1.jpg')
h2 = cache.add_notes_resource(b'resource2t', 'r1.jpg')
cache.set_notes_for('#tags', tag_id, doc, resource_hashes=(h1, h2))
self.ae(cache.get_all_items_that_have_notes(), {'#tags': {tag_id}, 'authors': {author_id}})
self.ae(cache.notes_for('#tags', tag_id), doc)
cache.delete_custom_column('tags')
cache.close()
cache = self.init_cache(cache.backend.library_path)
self.ae(cache.notes_for('#tags', tag_id), '')
self.assertIsNone(cache.get_notes_resource(h1))
self.assertIsNone(cache.get_notes_resource(h2))
# test exim of note
doc = '<p>test simple exim <img src="r 1.png"> of note with resources <img src="r%202.png">. Works or not</p>'
with tempfile.TemporaryDirectory() as tdir:
idir = os.path.join(tdir, 'i')
os.mkdir(idir)
with open(os.path.join(idir, 'index.html'), 'w') as f:
f.write(doc)
shutil.copyfile(get_image_path('lt.png'), os.path.join(idir, 'r 1.png'))
shutil.copyfile(get_image_path('library.png'), os.path.join(idir, 'r 2.png'))
note_id = cache.import_note('authors', author_id, f.name)
self.assertGreater(note_id, 0)
self.assertIn('<p>test simple exim <img', cache.notes_for('authors', author_id))
res = tuple(cache.get_notes_resource(x) for x in cache.notes_resources_used_by('authors', author_id))
exported = cache.export_note('authors', author_id)
self.assertIn('<p>test simple exim <img src="', exported)
from html5_parser import parse
root = parse(exported)
self.ae(root.xpath('//img/@data-filename'), ['r 1.png', 'r 2.png'])
cache.set_notes_for('authors', author_id, '')
with open(os.path.join(tdir, 'e.html'), 'wb') as f:
f.write(exported.encode('utf-8'))
cache.import_note('authors', author_id, f.name)
note_id = cache.import_note('authors', author_id, f.name)
self.assertGreater(note_id, 0)
self.assertIn('<p>test simple exim <img', cache.notes_for('authors', author_id))
res2 = tuple(cache.get_notes_resource(x) for x in cache.notes_resources_used_by('authors', author_id))
for x in res:
del x['mtime']
for x in res2:
del x['mtime']
self.ae(sorted(res, key=itemgetter('name')), sorted(res2, key=itemgetter('name')))
def test_fts(self: 'NotesTest'):
cache, _ = self.create_notes_db()
authors = sorted(cache.all_field_ids('authors'))
cache.set_notes_for('authors', authors[0], 'Wunderbar wunderkind common')
cache.set_notes_for('authors', authors[1], 'Heavens to murgatroyd common')
tags = sorted(cache.all_field_ids('tags'))
cache.set_notes_for('tags', tags[0], 'Tag me baby, one more time common')
cache.set_notes_for('tags', tags[1], 'Jeepers, Batman! common')
def ids_for_search(x, restrict_to_fields=()):
return {
(x['field'], x['item_id']) for x in cache.search_notes(x, restrict_to_fields=restrict_to_fields)
}
self.ae(ids_for_search('wunderbar'), {('authors', authors[0])})
self.ae(ids_for_search('common'), {('authors', authors[0]), ('authors', authors[1]), ('tags', tags[0]), ('tags', tags[1])})
self.ae(ids_for_search('common', ('tags',)), {('tags', tags[0]), ('tags', tags[1])})
self.ae(ids_for_search(''), ids_for_search('common'))
self.ae(ids_for_search('', ('tags',)), ids_for_search('common', ('tags',)))
# test that searching by item value works
an = cache.get_item_name('authors', authors[0])
self.ae(ids_for_search(' AND '.join(an.split()), ('authors',)), {('authors', authors[0])})
class NotesTest(BaseTest):
ae = BaseTest.assertEqual
def create_notes_db(self):
cache = self.init_cache(self.cloned_library)
cache.backend.notes.max_retired_items = 1
return cache, cache.backend.notes
def test_notes(self):
test_fts(self)
test_cache_api(self)
test_notes_api(self)
| 10,485 | Python | .py | 186 | 50.580645 | 127 | 0.661088 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,091 | fts.py | kovidgoyal_calibre/src/calibre/db/tests/fts.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import builtins
import os
import sys
import tempfile
from apsw import Connection
from calibre.constants import plugins
from calibre.db.annotations import unicode_normalize
from calibre.db.tests.base import BaseTest
def print(*args, **kwargs):
kwargs['file'] = sys.__stdout__
builtins.print(*args, **kwargs)
class TestConn(Connection):
def __init__(self, remove_diacritics=True, language='en', stem_words=False):
from calibre_extensions.sqlite_extension import set_ui_language
set_ui_language(language)
super().__init__(':memory:')
plugins.load_apsw_extension(self, 'sqlite_extension')
options = []
options.append('remove_diacritics'), options.append('2' if remove_diacritics else '0')
options = ' '.join(options)
tok = 'porter ' if stem_words else ''
self.execute(f'''
CREATE VIRTUAL TABLE fts_table USING fts5(t, tokenize = '{tok}unicode61 {options}');
CREATE VIRTUAL TABLE fts_row USING fts5vocab(fts_table, row);
''')
def execute(self, *a):
return self.cursor().execute(*a)
def insert_text(self, text):
self.execute('INSERT INTO fts_table(t) VALUES (?)', (unicode_normalize(text),))
def term_row_counts(self):
return dict(self.execute('SELECT term,doc FROM fts_row'))
def search(self, query, highlight_start='>', highlight_end='<', snippet_size=4):
snippet_size=max(1, min(snippet_size, 64))
stmt = (
f"SELECT snippet(fts_table, 0, '{highlight_start}', '{highlight_end}', '…', {snippet_size})"
' FROM fts_table WHERE fts_table MATCH ? ORDER BY RANK'
)
return list(self.execute(stmt, (unicode_normalize(query),)))
def tokenize(text, flags=None, remove_diacritics=True):
from calibre_extensions.sqlite_extension import FTS5_TOKENIZE_DOCUMENT, tokenize
if flags is None:
flags = FTS5_TOKENIZE_DOCUMENT
return tokenize(unicode_normalize(text), remove_diacritics, flags)
class FTSTest(BaseTest):
ae = BaseTest.assertEqual
def setUp(self):
from calibre_extensions.sqlite_extension import set_ui_language
set_ui_language('en')
def tearDown(self):
from calibre_extensions.sqlite_extension import set_ui_language
set_ui_language('en')
def test_fts_tokenize(self): # {{{
from calibre_extensions.sqlite_extension import FTS5_TOKENIZE_DOCUMENT, FTS5_TOKENIZE_QUERY, set_ui_language
def t(x, s, e, f=0):
return {'text': x, 'start': s, 'end': e, 'flags': f}
def tt(text, *expected_tokens, for_query=False):
flags = FTS5_TOKENIZE_QUERY if for_query else FTS5_TOKENIZE_DOCUMENT
q = tuple(x['text'] for x in tokenize(text, flags=flags))
self.ae(q, expected_tokens)
self.ae(
tokenize("Some wörds"),
[t('some', 0, 4), t('wörds', 5, 11), t('words', 5, 11, 1)]
)
self.ae(
tokenize("don't 'bug'"),
[t("don't", 0, 5), t('bug', 7, 10)]
)
self.ae(
tokenize("a,b. c"),
[t("a", 0, 1), t('b', 2, 3), t('c', 5, 6)]
)
self.ae(
tokenize("a*b+c"),
[t("a", 0, 1), t('b', 2, 3), t('c', 4, 5)]
)
self.ae(
tokenize("a(b[{^c"),
[t("a", 0, 1), t('b', 2, 3), t('c', 6, 7)]
)
self.ae(
tokenize("aüòÄsmile"),
[t("a", 0, 1), t('üòÄ', 1, 5), t('smile', 5, 10)]
)
tt("‰Ω†don'tÂè´mess", '‰Ω†', "don't", 'Âè´', 'mess')
tt("‰Ω†don'tÂè´mess", '‰Ω†', "don't", 'Âè´', 'mess', for_query=True)
tt('你叫什么名字', '你', '叫', '什么', '名字')
tt('你叫abc', '你', '叫', 'abc')
tt('a你b叫什么名字', 'a', '你', 'b', '叫', '什么', '名字')
for lang in 'de fr es sv it en'.split():
set_ui_language(lang)
tt("don't 'its' wörds", "don't", 'its', 'wörds', 'words')
tt("l'hospital", "l'hospital")
tt("x'bug'", "x'bug")
set_ui_language('en')
# }}}
def test_fts_basic(self): # {{{
conn = TestConn()
conn.insert_text('two words, and a period. With another.')
conn.insert_text('and another re-init')
self.ae(conn.search("another"), [('and >another< re-init',), ('…With >another<.',)])
self.ae(conn.search("period"), [('…a >period<. With another.',)])
self.ae(conn.term_row_counts(), {'a': 1, 're': 1, 'init': 1, 'and': 2, 'another': 2, 'period': 1, 'two': 1, 'with': 1, 'words': 1})
conn = TestConn()
conn.insert_text('co·ªôl')
self.ae(conn.term_row_counts(), {'cool': 1, 'co·ªôl': 1})
self.ae(conn.search("cool"), [('>co·ªôl<',)])
self.ae(conn.search("co·ªôl"), [('>co·ªôl<',)])
conn = TestConn(remove_diacritics=False)
conn.insert_text('co·ªôl')
self.ae(conn.term_row_counts(), {'co·ªôl': 1})
conn = TestConn()
conn.insert_text("‰Ω†don'tÂè´mess")
self.ae(conn.term_row_counts(), {"don't": 1, 'mess': 1, '‰Ω†': 1, 'Âè´': 1})
self.ae(conn.search("mess"), [("‰Ω†don'tÂè´>mess<",)])
self.ae(conn.search('''"don't"'''), [("‰Ω†>don't<Âè´mess",)])
self.ae(conn.search("‰Ω†"), [(">‰Ω†<don'tÂè´mess",)])
import apsw
if apsw.sqlitelibversion() not in ('3.44.0', '3.44.1', '3.44.2'):
# see https://www.sqlite.org/forum/forumpost/d16aeb397d
self.ae(conn.search("Âè´"), [("‰Ω†don't>Âè´<mess",)])
# }}}
def test_fts_stemming(self): # {{{
from calibre_extensions.sqlite_extension import stem
self.ae(stem('run'), 'run')
self.ae(stem('connection'), 'connect')
self.ae(stem('maintenaient'), 'maintenai')
self.ae(stem('maintenaient', 'fr'), 'mainten')
self.ae(stem('continué', 'fr'), 'continu')
self.ae(stem('maître', 'FRA'), 'maîtr')
conn = TestConn(stem_words=True)
conn.insert_text('a simplistic connection')
self.ae(conn.term_row_counts(), {'a': 1, 'connect': 1, 'simplist': 1})
self.ae(conn.search("connection"), [('a simplistic >connection<',),])
self.ae(conn.search("connect"), [('a simplistic >connection<',),])
self.ae(conn.search("simplistic connect"), [('a >simplistic< >connection<',),])
self.ae(conn.search("simplist"), [('a >simplistic< connection',),])
# }}}
def test_fts_query_syntax(self): # {{{
conn = TestConn()
conn.insert_text('one two three')
for q in ('"one two three"', 'one + two + three', '"one two" + three'):
self.ae(conn.search(q), [('>one two three<',)])
self.ae(conn.search('two'), [('one >two< three',)])
for q in ('"one two thr" *', 'one + two + thr*'):
self.ae(conn.search(q), [('>one two three<',)])
self.ae(conn.search('^one'), [('>one< two three',)])
self.ae(conn.search('^"one"'), [('>one< two three',)])
self.ae(conn.search('^two'), [])
conn = TestConn()
conn.insert_text('one two three four five six seven')
self.ae(conn.search('NEAR(one four)'), [('>one< two three >four<…',)])
self.ae(conn.search('NEAR("one two" "three four")'), [('>one two< >three four<…',)])
self.ae(conn.search('NEAR(one six, 2)'), [])
conn.insert_text('moose cat')
self.ae(conn.search('moose OR one'), [('>moose< cat',), ('>one< two three four…',)])
self.ae(conn.search('(moose OR one) NOT cat'), [('>one< two three four…',)])
self.ae(conn.search('moose AND one'), [])
# }}}
def test_pdftotext(self):
pdf_data = '''\
%PDF-1.1
%¥±ë
1 0 obj
<< /Type /Catalog
/Pages 2 0 R
>>
endobj
2 0 obj
<< /Type /Pages
/Kids [3 0 R]
/Count 1
/MediaBox [0 0 300 144]
>>
endobj
3 0 obj
<< /Type /Page
/Parent 2 0 R
/Resources
<< /Font
<< /F1
<< /Type /Font
/Subtype /Type1
/BaseFont /Times-Roman
>>
>>
>>
/Contents 4 0 R
>>
endobj
4 0 obj
<< /Length 55 >>
stream
BT
/F1 18 Tf
0 0 Td
(Hello World) Tj
ET
endstream
endobj
xref
0 5
0000000000 65535 f
0000000018 00000 n
0000000077 00000 n
0000000178 00000 n
0000000457 00000 n
trailer
<< /Root 1 0 R
/Size 5
>>
startxref
565
%%EOF'''
with tempfile.TemporaryDirectory() as tdir:
pdf = os.path.join(tdir, 'test.pdf')
with open(pdf, 'w') as f:
f.write(pdf_data)
from calibre.db.fts.text import pdftotext
self.assertEqual(pdftotext(pdf).strip(), 'Hello World')
def find_tests():
import unittest
return unittest.defaultTestLoader.loadTestsFromTestCase(FTSTest)
def run_tests():
from calibre.utils.run_tests import run_tests
run_tests(find_tests)
| 9,046 | Python | .py | 227 | 32.295154 | 139 | 0.561937 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,092 | fts_api.py | kovidgoyal_calibre/src/calibre/db/tests/fts_api.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import builtins
import os
import shutil
import sys
import time
from io import BytesIO, StringIO
from unittest.mock import patch
from zipfile import ZipFile
from calibre.db.fts.text import html_to_text
from calibre.db.tests.base import BaseTest
def print(*args, **kwargs):
kwargs['file'] = sys.__stdout__
builtins.print(*args, **kwargs)
class FTSAPITest(BaseTest):
ae = BaseTest.assertEqual
def setUp(self):
super().setUp()
from calibre.db.cache import Cache
from calibre_extensions.sqlite_extension import set_ui_language
self.orig_sleep_time = Cache.fts_indexing_sleep_time
Cache.fts_indexing_sleep_time = 0
set_ui_language('en')
self.libraries_to_close = []
def tearDown(self):
[c.close() for c in self.libraries_to_close]
super().tearDown()
from calibre.db.cache import Cache
from calibre_extensions.sqlite_extension import set_ui_language
Cache.fts_indexing_sleep_time = self.orig_sleep_time
set_ui_language('en')
def new_library(self):
if os.path.exists(self.library_path):
try:
shutil.rmtree(self.library_path)
except PermissionError:
time.sleep(5)
shutil.rmtree(self.library_path)
os.makedirs(self.library_path)
self.create_db(self.library_path)
ans = self.init_cache()
self.libraries_to_close.append(ans)
return ans
def wait_for_fts_to_finish(self, fts, timeout=10):
if fts.pool.initialized:
st = time.monotonic()
while fts.all_currently_dirty() and time.monotonic() - st < timeout:
fts.pool.supervisor_thread.join(0.01)
def text_records(self, fts):
return fts.get_connection().get_dict('SELECT * FROM fts_db.books_text')
def make_txtz(self, txt, **extra):
buf = BytesIO()
with ZipFile(buf, mode='w') as zf:
zf.writestr('index.txt', txt)
for key, val in extra.items():
zf.writestr(key, val)
buf.seek(0)
return buf
def test_fts_pool(self):
cache = self.new_library()
fts = cache.enable_fts()
self.wait_for_fts_to_finish(fts)
self.assertFalse(fts.all_currently_dirty())
cache.add_format(1, 'TXT', BytesIO(b'a test text'))
self.wait_for_fts_to_finish(fts)
def q(rec, **kw):
self.ae({x: rec[x] for x in kw}, kw)
def check(**kw):
tr = self.text_records(fts)
self.ae(len(tr), 1)
q(tr[0], **kw)
check(id=1, book=1, format='TXT', searchable_text='a test text')
# check re-adding does not rescan
cache.add_format(1, 'TXT', BytesIO(b'a test text'))
self.wait_for_fts_to_finish(fts)
check(id=1, book=1, format='TXT', searchable_text='a test text')
# check updating rescans
cache.add_format(1, 'TXT', BytesIO(b'a test text2'))
self.wait_for_fts_to_finish(fts)
check(id=2, book=1, format='TXT', searchable_text='a test text2')
# check closing shuts down all workers
cache.close()
self.assertFalse(fts.pool.initialized.is_set())
# check enabling scans pre-exisintg
cache = self.new_library()
cache.add_format(1, 'TXTZ', self.make_txtz('a test te\u00adxt'.encode()))
fts = cache.enable_fts()
self.wait_for_fts_to_finish(fts)
check(id=1, book=1, format='TXTZ', searchable_text='a test text')
# check changing the format but not the text doesn't cause a rescan
cache.add_format(1, 'TXTZ', self.make_txtz(b'a test text', extra='xxx'))
self.wait_for_fts_to_finish(fts)
check(id=1, book=1, format='TXTZ', searchable_text='a test text')
# check max_duration
for w in fts.pool.workers:
w.max_duration = -1
with patch('sys.stderr', new_callable=StringIO):
cache.add_format(1, 'TXTZ', self.make_txtz(b'a timed out text'))
self.wait_for_fts_to_finish(fts)
check(id=2, book=1, format='TXTZ', err_msg='Extracting text from the TXTZ file of size 132 B took too long')
for w in fts.pool.workers:
w.max_duration = w.__class__.max_duration
# check shutdown when workers have hung
for w in fts.pool.workers:
w.code_to_exec = 'import time; time.sleep(100)'
cache.add_format(1, 'TXTZ', self.make_txtz(b'hung worker'))
workers = list(fts.pool.workers)
cache.close()
for w in workers:
self.assertFalse(w.is_alive())
def test_fts_search(self):
cache = self.new_library()
fts = cache.enable_fts()
self.wait_for_fts_to_finish(fts)
self.assertFalse(fts.all_currently_dirty())
cache.add_format(1, 'TXT', BytesIO(b'some long text to help with testing search.'))
cache.add_format(2, 'MD', BytesIO(b'some other long text that will also help with the testing of search'))
self.assertTrue(fts.all_currently_dirty())
self.wait_for_fts_to_finish(fts)
self.assertFalse(fts.all_currently_dirty())
self.ae({x['id'] for x in cache.fts_search('help')}, {1, 2})
self.ae({x['id'] for x in cache.fts_search('help', restrict_to_book_ids=(1, 3, 4, 5, 11))}, {1})
self.ae({x['format'] for x in cache.fts_search('help')}, {'TXT', 'MD'})
self.ae({x['id'] for x in cache.fts_search('also')}, {2})
self.ae({x['text'] for x in cache.fts_search('also', highlight_start='[', highlight_end=']')}, {
'some other long text that will [also] help with the testing of search'})
self.ae({x['text'] for x in cache.fts_search('also', highlight_start='[', highlight_end=']', snippet_size=3)}, {
'…will [also] help…'})
self.ae({x['text'] for x in cache.fts_search('also', return_text=False)}, {''})
fts = cache.reindex_fts()
self.assertTrue(fts.pool.initialized)
self.wait_for_fts_to_finish(fts)
self.assertFalse(fts.all_currently_dirty())
self.ae({x['id'] for x in cache.fts_search('help')}, {1, 2})
cache.remove_books((1,))
self.ae({x['id'] for x in cache.fts_search('help')}, {2})
cache.close()
def test_fts_triggers(self):
cache = self.init_cache()
# the cache fts jobs will clear dirtied flag so disable it
cache.queue_next_fts_job = lambda *a: None
fts = cache.enable_fts(start_pool=False)
self.ae(fts.all_currently_dirty(), [(1, 'FMT1'), (1, 'FMT2'), (2, 'FMT1')])
fts.dirty_existing()
self.ae(fts.all_currently_dirty(), [(1, 'FMT1'), (1, 'FMT2'), (2, 'FMT1')])
cache.remove_formats({2: ['FMT1']})
self.ae(fts.all_currently_dirty(), [(1, 'FMT1'), (1, 'FMT2')])
cache.remove_books((1,))
self.ae(fts.all_currently_dirty(), [])
cache.add_format(2, 'ADDED', BytesIO(b'data'))
self.ae(fts.all_currently_dirty(), [(2, 'ADDED')])
fts.clear_all_dirty()
self.ae(fts.all_currently_dirty(), [])
cache.add_format(2, 'ADDED', BytesIO(b'data2'))
self.ae(fts.all_currently_dirty(), [(2, 'ADDED')])
fts.add_text(2, 'ADDED', 'data2')
self.ae(fts.all_currently_dirty(), [])
cache.add_format(2, 'ADDED', BytesIO(b'data2'))
self.ae(fts.all_currently_dirty(), [(2, 'ADDED')])
fts.add_text(2, 'ADDED', 'data2')
self.ae(fts.all_currently_dirty(), [])
fts.dirty_existing()
j = fts.get_next_fts_job()
self.ae(j, (2, 'ADDED'))
self.ae(j, fts.get_next_fts_job())
fts.remove_dirty(*j)
self.assertNotEqual(j, fts.get_next_fts_job())
self.assertFalse(fts.all_currently_dirty())
cache.reindex_fts_book(2)
self.ae(fts.all_currently_dirty(), [(2, 'ADDED')])
def test_fts_to_text(self):
from calibre.ebooks.oeb.polish.parsing import parse
html = '''
<html><body>
<div>first_para</div><p>second_para</p>
<p>some <i>itali</i>c t<!- c -->ext</p>
<div>nested<p>blocks</p></div>
</body></html>
'''
root = parse(html)
self.ae(tuple(html_to_text(root)), ('first_para\n\nsecond_para\n\nsome italic text\n\nnested\n\nblocks',))
def find_tests():
import unittest
return unittest.defaultTestLoader.loadTestsFromTestCase(FTSAPITest)
def run_tests():
from calibre.utils.run_tests import run_tests
run_tests(find_tests)
| 8,611 | Python | .py | 188 | 37.319149 | 120 | 0.609509 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,093 | main.py | kovidgoyal_calibre/src/calibre/db/tests/main.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from calibre.utils.run_tests import find_tests_in_package, run_tests
def find_tests():
return find_tests_in_package('calibre.db.tests')
if __name__ == '__main__':
try:
import init_calibre # noqa
except ImportError:
pass
run_tests(find_tests)
| 429 | Python | .py | 13 | 29 | 68 | 0.672372 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,094 | pool.py | kovidgoyal_calibre/src/calibre/db/fts/pool.py | #!/usr/bin/env python
# License: GPL v3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net>
import os
import subprocess
import sys
import traceback
from contextlib import suppress
from queue import Queue
from threading import Event, Thread
from time import monotonic
from calibre import detect_ncpus, human_readable
from calibre.utils.ipc.simple_worker import start_pipe_worker
check_for_work = object()
quit = object()
class Job:
def __init__(self, book_id, fmt, path, fmt_size, fmt_hash, start_time):
self.book_id = book_id
self.fmt = fmt
self.fmt_size = fmt_size
self.fmt_hash = fmt_hash
self.path = path
self.start_time = start_time
class Result:
def __init__(self, job, err_msg=''):
self.book_id = job.book_id
self.fmt = job.fmt
self.fmt_size = job.fmt_size
self.fmt_hash = job.fmt_hash
self.ok = not bool(err_msg)
self.start_time = job.start_time
if self.ok:
with open(job.path + '.txt', 'rb') as src:
try:
self.text = src.read().decode('utf-8', 'replace')
except Exception:
self.ok = False
self.text = traceback.format_exc()
else:
self.text = err_msg
class Worker(Thread):
code_to_exec = 'from calibre.db.fts.text import main; main({!r})'
max_duration = 30 # minutes
poll_interval = 0.1 # seconds
def __init__(self, jobs_queue, supervise_queue):
super().__init__(name='FTSWorker', daemon=True)
self.currently_working = False
self.jobs_queue = jobs_queue
self.supervise_queue = supervise_queue
self.keep_going = True
self.working = False
def run(self):
while self.keep_going:
x = self.jobs_queue.get()
if x is quit:
break
self.working = True
try:
res = self.run_job(x)
if res is not None and self.keep_going:
self.supervise_queue.put(res)
except Exception:
tb = traceback.format_exc()
traceback.print_exc()
if self.keep_going:
self.supervise_queue.put(Result(x, tb))
finally:
self.working = False
def run_job(self, job):
time_limit = monotonic() + (self.max_duration * 60)
txtpath = job.path + '.txt'
errpath = job.path + '.error'
try:
with open(errpath, 'wb') as error:
p = start_pipe_worker(
self.code_to_exec.format(job.path),
stdout=subprocess.DEVNULL, stderr=error, stdin=subprocess.DEVNULL, priority='low',
)
while self.keep_going and monotonic() <= time_limit:
with suppress(subprocess.TimeoutExpired):
p.wait(self.poll_interval)
break
if p.returncode is None:
p.kill()
if not self.keep_going:
return
return Result(job, _('Extracting text from the {0} file of size {1} took too long').format(
job.fmt, human_readable(job.fmt_size)))
if os.path.exists(txtpath):
return Result(job)
with open(errpath, 'rb') as f:
err = f.read().decode('utf-8', 'replace')
return Result(job, err)
finally:
with suppress(OSError):
os.remove(job.path)
with suppress(OSError):
os.remove(txtpath)
with suppress(OSError):
os.remove(errpath)
class Pool:
def __init__(self, dbref):
self.max_workers = 1
self.jobs_queue = Queue()
self.supervise_queue = Queue()
self.workers = []
self.initialized = Event()
self.dbref = dbref
self.keep_going = True
def initialize(self):
if not self.initialized.is_set():
self.supervisor_thread = Thread(name='FTSSupervisor', daemon=True, target=self.supervise)
self.supervisor_thread.start()
self.expand_workers()
self.initialized.set()
def prune_dead_workers(self):
self.workers = [w for w in self.workers if w.is_alive()]
def expand_workers(self):
self.prune_dead_workers()
while len(self.workers) < self.max_workers:
self.workers.append(self.create_worker())
def create_worker(self):
w = Worker(self.jobs_queue, self.supervise_queue)
w.start()
return w
def shrink_workers(self):
self.prune_dead_workers()
extra = len(self.workers) - self.max_workers
while extra > 0:
self.jobs_queue.put(quit)
extra -= 1
# external API {{{
@property
def num_of_workers(self):
return len(self.workers)
@num_of_workers.setter
def num_of_workers(self, num):
self.initialize()
self.prune_dead_workers()
num = min(max(1, num), detect_ncpus())
if num != self.max_workers:
self.max_workers = num
if num > len(self.workers):
self.expand_workers()
elif num < len(self.workers):
self.shrink_workers()
@property
def num_of_idle_workers(self):
return sum(0 if w.working else 1 for w in self.workers)
def check_for_work(self):
self.initialize()
self.supervise_queue.put(check_for_work)
def add_job(self, book_id, fmt, path, fmt_size, fmt_hash, start_time):
self.initialize()
job = Job(book_id, fmt, path, fmt_size, fmt_hash, start_time)
self.jobs_queue.put(job)
def commit_result(self, result):
text = result.text
err_msg = ''
if not result.ok:
print(f'Failed to get text from book_id: {result.book_id} format: {result.fmt}', file=sys.stderr)
print(text, file=sys.stderr)
err_msg = text
text = ''
db = self.dbref()
if db is not None:
db.commit_fts_result(result.book_id, result.fmt, result.fmt_size, result.fmt_hash, text, err_msg, result.start_time)
def shutdown(self):
if self.initialized.is_set():
self.keep_going = False
for i in range(2):
self.supervise_queue.put(quit)
for w in self.workers:
w.keep_going = False
for i in range(2*len(self.workers)):
self.jobs_queue.put(quit)
self.initialized.clear()
def join(self):
with suppress(AttributeError):
self.supervisor_thread.join()
for w in self.workers:
w.join()
self.workers = []
# }}}
def do_check_for_work(self):
db = self.dbref()
if db is not None:
db.queue_next_fts_job()
def supervise(self):
while self.keep_going:
x = self.supervise_queue.get()
try:
if x is check_for_work:
self.do_check_for_work()
elif x is quit:
break
elif isinstance(x, Result):
self.commit_result(x)
self.do_check_for_work()
except Exception:
traceback.print_exc()
| 7,510 | Python | .py | 200 | 26.46 | 128 | 0.551814 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,095 | connect.py | kovidgoyal_calibre/src/calibre/db/fts/connect.py | #!/usr/bin/env python
# License: GPL v3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net>
import builtins
import hashlib
import os
import sys
from contextlib import suppress
from itertools import count
from threading import Lock
import apsw
from calibre.db import FTSQueryError
from calibre.db.annotations import unicode_normalize
from calibre.utils.date import EPOCH, utcnow
from .pool import Pool
from .schema_upgrade import SchemaUpgrade
def print(*args, **kwargs):
kwargs['file'] = sys.__stdout__
builtins.print(*args, **kwargs)
class FTS:
def __init__(self, dbref):
self.dbref = dbref
self.pool = Pool(dbref)
self.init_lock = Lock()
self.temp_table_counter = count()
def initialize(self, conn):
needs_dirty = False
with self.init_lock:
if conn.fts_dbpath is None:
main_db_path = os.path.abspath(conn.db_filename('main'))
dbpath = os.path.join(os.path.dirname(main_db_path), 'full-text-search.db')
conn.execute("ATTACH DATABASE ? AS fts_db", (dbpath,))
SchemaUpgrade(conn)
conn.execute('UPDATE fts_db.dirtied_formats SET in_progress=FALSE WHERE in_progress=TRUE')
num_dirty = conn.get('''SELECT COUNT(*) from fts_db.dirtied_formats''')[0][0]
if not num_dirty:
num_indexed = conn.get('''SELECT COUNT(*) from fts_db.books_text''')[0][0]
if not num_indexed:
needs_dirty = True
conn.fts_dbpath = dbpath
if needs_dirty:
self.dirty_existing()
def get_connection(self):
db = self.dbref()
if db is None:
raise RuntimeError('db has been garbage collected')
ans = db.backend.get_connection()
self.initialize(ans)
return ans
def dirty_existing(self):
conn = self.get_connection()
conn.execute('''
INSERT OR IGNORE INTO fts_db.dirtied_formats(book, format)
SELECT book, format FROM main.data;
''')
def number_dirtied(self):
conn = self.get_connection()
return conn.get('''SELECT COUNT(*) from fts_db.dirtied_formats''')[0][0]
def all_currently_dirty(self):
conn = self.get_connection()
return conn.get('''SELECT book, format from fts_db.dirtied_formats''', all=True)
def clear_all_dirty(self):
conn = self.get_connection()
conn.execute('DELETE FROM fts_db.dirtied_formats')
def vacuum(self):
conn = self.get_connection()
conn.execute('VACUUM fts_db')
def remove_dirty(self, book_id, fmt):
conn = self.get_connection()
conn.execute('DELETE FROM fts_db.dirtied_formats WHERE book=? AND format=?', (book_id, fmt.upper()))
def dirty_book(self, book_id, *fmts):
conn = self.get_connection()
for fmt in fmts:
conn.execute('INSERT OR IGNORE INTO fts_db.dirtied_formats (book, format) VALUES (?, ?)', (book_id, fmt.upper()))
def unindex(self, book_id, fmt=None):
conn = self.get_connection()
if fmt is None:
conn.execute('DELETE FROM books_text WHERE book=?', (book_id,))
else:
conn.execute('DELETE FROM books_text WHERE book=? AND format=?', (book_id, fmt.upper()))
def add_text(self, book_id, fmt, text, text_hash='', fmt_size=0, fmt_hash='', err_msg=''):
conn = self.get_connection()
ts = (utcnow() - EPOCH).total_seconds()
fmt = fmt.upper()
if err_msg:
conn.execute(
'INSERT OR REPLACE INTO fts_db.books_text '
'(book, timestamp, format, format_size, format_hash, err_msg) VALUES '
'(?, ?, ?, ?, ?, ?)', (
book_id, ts, fmt, fmt_size, fmt_hash, err_msg))
elif text:
conn.execute(
'INSERT OR REPLACE INTO fts_db.books_text '
'(book, timestamp, format, format_size, format_hash, searchable_text, text_size, text_hash) VALUES '
'(?, ?, ?, ?, ?, ?, ?, ?)', (
book_id, ts, fmt, fmt_size, fmt_hash, text, len(text), text_hash))
else:
conn.execute('DELETE FROM fts_db.dirtied_formats WHERE book=? AND format=?', (book_id, fmt))
def get_next_fts_job(self):
conn = self.get_connection()
for book_id, fmt in conn.get('SELECT book,format FROM fts_db.dirtied_formats WHERE in_progress=FALSE ORDER BY id'):
return book_id, fmt
return None, None
def commit_result(self, book_id, fmt, fmt_size, fmt_hash, text, err_msg=''):
conn = self.get_connection()
text_hash = ''
if text:
text_hash = hashlib.sha1(text.encode('utf-8')).hexdigest()
for x in conn.get('SELECT id FROM fts_db.books_text WHERE book=? AND format=? AND text_hash=?', (book_id, fmt, text_hash)):
text = ''
break
self.add_text(book_id, fmt, text, text_hash, fmt_size, fmt_hash, err_msg)
def queue_job(self, book_id, fmt, path, fmt_size, fmt_hash, start_time):
conn = self.get_connection()
fmt = fmt.upper()
for x in conn.get('SELECT id FROM fts_db.books_text WHERE book=? AND format=? AND format_size=? AND format_hash=?', (
book_id, fmt, fmt_size, fmt_hash)):
break
else:
self.pool.add_job(book_id, fmt, path, fmt_size, fmt_hash, start_time)
conn.execute('UPDATE fts_db.dirtied_formats SET in_progress=TRUE WHERE book=? AND format=?', (book_id, fmt))
return True
self.remove_dirty(book_id, fmt)
with suppress(OSError):
os.remove(path)
return False
def search(self,
fts_engine_query, use_stemming, highlight_start, highlight_end, snippet_size, restrict_to_book_ids,
return_text=True, process_each_result=None
):
if restrict_to_book_ids is not None and not restrict_to_book_ids:
return
fts_engine_query = unicode_normalize(fts_engine_query)
fts_table = 'books_fts' + ('_stemmed' if use_stemming else '')
data = []
if return_text:
text = 'books_text.searchable_text'
if highlight_start is not None and highlight_end is not None:
if snippet_size is not None:
text = f'''snippet("{fts_table}", 0, ?, ?, '…', {max(1, min(snippet_size, 64))})'''
else:
text = f'''highlight("{fts_table}", 0, ?, ?)'''
data.append(highlight_start)
data.append(highlight_end)
text = ', ' + text
else:
text = ''
query = 'SELECT {0}.id, {0}.book, {0}.format {1} FROM {0} '.format('books_text', text)
query += f' JOIN {fts_table} ON fts_db.books_text.id = {fts_table}.rowid'
query += ' WHERE '
conn = self.get_connection()
temp_table_name = ''
if restrict_to_book_ids:
temp_table_name = f'fts_restrict_search_{next(self.temp_table_counter)}'
conn.execute(f'CREATE TABLE temp.{temp_table_name}(x INTEGER)')
conn.executemany(f'INSERT INTO temp.{temp_table_name} VALUES (?)', tuple((x,) for x in restrict_to_book_ids))
query += f' fts_db.books_text.book IN temp.{temp_table_name} AND '
query += f' "{fts_table}" MATCH ?'
data.append(fts_engine_query)
query += f' ORDER BY {fts_table}.rank '
if temp_table_name:
query += f'; DROP TABLE temp.{temp_table_name}'
try:
for record in conn.execute(query, tuple(data)):
result = {
'id': record[0],
'book_id': record[1],
'format': record[2],
'text': record[3] if return_text else '',
}
if process_each_result is not None:
result = process_each_result(result)
ret = yield result
if ret is True:
break
except apsw.SQLError as e:
raise FTSQueryError(fts_engine_query, query, e) from e
def shutdown(self):
self.pool.shutdown()
| 8,300 | Python | .py | 178 | 35.932584 | 135 | 0.575963 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,096 | text.py | kovidgoyal_calibre/src/calibre/db/fts/text.py | #!/usr/bin/env python
# License: GPL v3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net>
import os
import re
import unicodedata
from calibre.customize.ui import plugin_for_input_format
from calibre.ebooks.oeb.base import XPNSMAP, barename
from calibre.ebooks.oeb.iterator.book import extract_book
from calibre.ebooks.oeb.polish.container import Container as ContainerBase
from calibre.ebooks.oeb.polish.utils import BLOCK_TAG_NAMES
from calibre.ptempfile import TemporaryDirectory
from calibre.utils.logging import default_log
class SimpleContainer(ContainerBase):
tweak_mode = True
skipped_tags = frozenset({'style', 'title', 'script', 'head', 'img', 'svg', 'math', 'rt', 'rp', 'rtc'})
def tag_to_text(tag):
if tag.text:
yield tag.text
for child in tag:
q = barename(child.tag).lower() if isinstance(child.tag, str) else ''
if not q or q in skipped_tags:
if child.tail:
yield child.tail
else:
if q in BLOCK_TAG_NAMES:
yield '\n\n'
yield from tag_to_text(child)
if tag.tail:
yield tag.tail
def html_to_text(root):
pat = re.compile(r'\n{3,}')
for body in root.xpath('h:body', namespaces=XPNSMAP):
body.tail = ''
yield pat.sub('\n\n', ''.join(tag_to_text(body)).strip())
def to_text(container, name):
root = container.parsed(name)
if hasattr(root, 'xpath'):
yield from html_to_text(root)
def is_fmt_ok(input_fmt):
input_fmt = input_fmt.upper()
input_plugin = plugin_for_input_format(input_fmt)
is_comic = bool(getattr(input_plugin, 'is_image_collection', False))
if not input_plugin or is_comic:
return False
return input_plugin
def pdftotext(path):
import subprocess
from calibre.ebooks.pdf.pdftohtml import PDFTOTEXT, popen
from calibre.utils.cleantext import clean_ascii_chars
cmd = [PDFTOTEXT] + '-enc UTF-8 -nodiag -eol unix'.split() + [os.path.basename(path), '-']
p = popen(cmd, cwd=os.path.dirname(path), stdout=subprocess.PIPE, stdin=subprocess.DEVNULL)
raw = p.stdout.read()
p.stdout.close()
if p.wait() != 0:
return ''
return clean_ascii_chars(raw).decode('utf-8', 'replace')
def extract_text(pathtoebook):
input_fmt = pathtoebook.rpartition('.')[-1].upper()
ans = ''
input_plugin = is_fmt_ok(input_fmt)
if not input_plugin:
return ans
input_plugin = plugin_for_input_format(input_fmt)
if input_fmt == 'PDF':
ans = pdftotext(pathtoebook)
else:
with TemporaryDirectory() as tdir:
texts = []
book_fmt, opfpath, input_fmt = extract_book(pathtoebook, tdir, log=default_log)
input_plugin = plugin_for_input_format(input_fmt)
is_comic = bool(getattr(input_plugin, 'is_image_collection', False))
if is_comic:
return ''
container = SimpleContainer(tdir, opfpath, default_log)
for name, is_linear in container.spine_names:
texts.extend(to_text(container, name))
ans = '\n\n\n'.join(texts)
return unicodedata.normalize('NFC', ans).replace('\u00ad', '')
def main(pathtoebook):
text = extract_text(pathtoebook)
with open(pathtoebook + '.txt', 'wb') as f:
f.write(text.encode('utf-8'))
| 3,347 | Python | .py | 82 | 34.219512 | 103 | 0.658236 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,097 | schema_upgrade.py | kovidgoyal_calibre/src/calibre/db/fts/schema_upgrade.py | #!/usr/bin/env python
# License: GPL v3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net>
from calibre.utils.resources import get_path as P
class SchemaUpgrade:
def __init__(self, conn):
self.conn = conn
conn.execute('BEGIN EXCLUSIVE TRANSACTION')
try:
if self.user_version == 0:
fts_sqlite = P('fts_sqlite.sql', data=True, allow_user_override=False).decode('utf-8')
conn.execute(fts_sqlite)
while True:
uv = self.user_version
meth = getattr(self, f'upgrade_version_{uv}', None)
if meth is None:
break
print(f'Upgrading FTS database to version {uv+1}...')
meth()
self.user_version = uv + 1
fts_triggers = P('fts_triggers.sql', data=True, allow_user_override=False).decode('utf-8')
conn.execute(fts_triggers)
except (Exception, BaseException):
conn.execute('ROLLBACK')
raise
else:
conn.execute('COMMIT')
self.conn = None
@property
def user_version(self):
return self.conn.get('PRAGMA fts_db.user_version', all=False) or 0
@user_version.setter
def user_version(self, val):
self.conn.execute(f'PRAGMA fts_db.user_version={val}')
| 1,353 | Python | .py | 33 | 30.242424 | 102 | 0.579909 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,098 | cmd_set_metadata.py | kovidgoyal_calibre/src/calibre/db/cli/cmd_set_metadata.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
import os
from calibre import prints
from calibre.ebooks.metadata.book.base import field_from_string
from calibre.ebooks.metadata.book.serialize import read_cover
from calibre.ebooks.metadata.opf import get_metadata
from calibre.srv.changes import metadata
from polyglot.builtins import iteritems
readonly = False
version = 0 # change this if you change signature of implementation()
def implementation(db, notify_changes, action, *args):
is_remote = notify_changes is not None
if action == 'field_metadata':
return db.field_metadata
if action == 'opf':
book_id, mi = args
with db.write_lock:
if not db.has_id(book_id):
return
changed_ids = db.set_metadata(book_id, mi, force_changes=True, allow_case_change=False)
if is_remote:
notify_changes(metadata(changed_ids))
return db.get_metadata(book_id)
if action == 'fields':
book_id, fvals = args
with db.write_lock:
if not db.has_id(book_id):
return
mi = db.get_metadata(book_id)
for field, val in fvals:
if field.endswith('_index'):
sname = mi.get(field[:-6])
if sname:
mi.set(field[:-6], sname, extra=val)
if field == 'series_index':
mi.series_index = val # extra has no effect for the builtin series field
elif field == 'cover':
if is_remote:
mi.cover_data = None, val[1]
else:
mi.cover = val
read_cover(mi)
else:
mi.set(field, val)
changed_ids = db.set_metadata(book_id, mi, force_changes=True, allow_case_change=True)
if is_remote:
notify_changes(metadata(changed_ids))
return db.get_metadata(book_id)
def option_parser(get_parser, args):
parser = get_parser(
_(
'''
%prog set_metadata [options] book_id [/path/to/metadata.opf]
Set the metadata stored in the calibre database for the book identified by
book_id from the OPF file metadata.opf. book_id is a book id number from the
search command. You can get a quick feel for the OPF format by using the
--as-opf switch to the show_metadata command. You can also set the metadata of
individual fields with the --field option. If you use the --field option, there
is no need to specify an OPF file.
'''
)
)
parser.add_option(
'-f',
'--field',
action='append',
default=[],
help=_(
'The field to set. Format is field_name:value, for example: '
'{0} tags:tag1,tag2. Use {1} to get a list of all field names. You '
'can specify this option multiple times to set multiple fields. '
'Note: For languages you must use the ISO639 language codes (e.g. '
'en for English, fr for French and so on). For identifiers, the '
'syntax is {0} {2}. For boolean (yes/no) fields use true and false '
'or yes and no.'
).format('--field', '--list-fields', 'identifiers:isbn:XXXX,doi:YYYYY')
)
parser.add_option(
'-l',
'--list-fields',
action='store_true',
default=False,
help=_(
'List the metadata field names that can be used'
' with the --field option'
)
)
return parser
def get_fields(dbctx):
fm = dbctx.run('set_metadata', 'field_metadata')
for key in sorted(fm.all_field_keys()):
m = fm[key]
if (key not in {'formats', 'series_sort', 'ondevice', 'path',
'last_modified'} and m['is_editable'] and m['name']):
yield key, m
if m['datatype'] == 'series':
si = m.copy()
si['name'] = m['name'] + ' Index'
si['datatype'] = 'float'
yield key + '_index', si
c = fm['cover'].copy()
c['datatype'] = 'text'
yield 'cover', c
def main(opts, args, dbctx):
if opts.list_fields:
ans = get_fields(dbctx)
prints('%-40s' % _('Title'), _('Field name'), '\n')
for key, m in ans:
prints('%-40s' % m['name'], key)
return 0
def verify_int(x):
try:
int(x)
return True
except:
return False
if len(args) < 1 or not verify_int(args[0]):
raise SystemExit(_(
'You must specify a record id as the '
'first argument'
))
if len(args) < 2 and not opts.field:
raise SystemExit(_('You must specify either a field or an OPF file'))
book_id = int(args[0])
if len(args) > 1:
opf = os.path.abspath(args[1])
if not os.path.exists(opf):
raise SystemExit(_('The OPF file %s does not exist') % opf)
with open(opf, 'rb') as stream:
mi = get_metadata(stream)[0]
if mi.cover:
mi.cover = os.path.join(os.path.dirname(opf), os.path.relpath(mi.cover, os.getcwd()))
final_mi = dbctx.run('set_metadata', 'opf', book_id, read_cover(mi))
if not final_mi:
raise SystemExit(_('No book with id: %s in the database') % book_id)
if opts.field:
fields = {k: v for k, v in get_fields(dbctx)}
fields['title_sort'] = fields['sort']
vals = {}
for x in opts.field:
field, val = x.partition(':')[::2]
if field == 'sort':
field = 'title_sort'
if field not in fields:
raise SystemExit(_('%s is not a known field' % field))
if field == 'cover':
val = dbctx.path(os.path.abspath(os.path.expanduser(val)))
else:
val = field_from_string(field, val, fields[field])
vals[field] = val
fvals = []
for field, val in sorted( # ensure series_index fields are set last
iteritems(vals), key=lambda k: 1 if k[0].endswith('_index') else 0):
if field.endswith('_index'):
try:
val = float(val)
except Exception:
raise SystemExit('The value %r is not a valid series index' % val)
fvals.append((field, val))
final_mi = dbctx.run('set_metadata', 'fields', book_id, fvals)
if not final_mi:
raise SystemExit(_('No book with id: %s in the database') % book_id)
prints(str(final_mi))
return 0
| 6,732 | Python | .py | 165 | 30.4 | 101 | 0.556506 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
27,099 | cmd_add_format.py | kovidgoyal_calibre/src/calibre/db/cli/cmd_add_format.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
import os
from io import BytesIO
from calibre.srv.changes import formats_added
readonly = False
version = 0 # change this if you change signature of implementation()
def implementation(db, notify_changes, book_id, data, fmt, replace):
is_remote = notify_changes is not None
if is_remote:
data = BytesIO(data[1])
relpath = ''
if fmt.startswith('.EXTRA_DATA_FILE:'):
relpath = fmt[len('.EXTRA_DATA_FILE:'):]
if relpath:
added = db.add_extra_files(book_id, {relpath: data}, replace=replace)[relpath]
else:
added = db.add_format(book_id, fmt, data, replace=replace)
if is_remote and added and not relpath:
notify_changes(formats_added({book_id: (fmt,)}))
return added
def option_parser(get_parser, args):
parser = get_parser(
_(
'''\
%prog add_format [options] id ebook_file
Add the e-book in ebook_file to the available formats for the logical book identified \
by id. You can get id by using the search command. If the format already exists, \
it is replaced, unless the do not replace option is specified.\
'''
)
)
parser.add_option(
'--dont-replace',
dest='replace',
default=True,
action='store_false',
help=_('Do not replace the format if it already exists')
)
parser.add_option(
'--as-extra-data-file',
default=False,
action='store_true',
help=_('Add the file as an extra data file to the book, not an ebook format')
)
return parser
def main(opts, args, dbctx):
if len(args) < 2:
raise SystemExit(_('You must specify an id and an e-book file'))
id, path, fmt = int(args[0]), args[1], os.path.splitext(args[1])[-1]
if opts.as_extra_data_file:
fmt = '.EXTRA_DATA_FILE:' + 'data/' + os.path.basename(args[1])
else:
fmt = fmt[1:].upper()
if not fmt:
raise SystemExit(_('e-book file must have an extension'))
if not dbctx.run('add_format', id, dbctx.path(path), fmt, opts.replace):
if opts.as_extra_data_file:
raise SystemExit(f'An extra data file with the filename {os.path.basename(args[1])} already exists')
raise SystemExit(_('A %(fmt)s file already exists for book: %(id)d, not replacing')%dict(fmt=fmt, id=id))
return 0
| 2,419 | Python | .py | 61 | 33.721311 | 113 | 0.65032 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |