id int64 0 458k | file_name stringlengths 4 119 | file_path stringlengths 14 227 | content stringlengths 24 9.96M | size int64 24 9.96M | language stringclasses 1 value | extension stringclasses 14 values | total_lines int64 1 219k | avg_line_length float64 2.52 4.63M | max_line_length int64 5 9.91M | alphanum_fraction float64 0 1 | repo_name stringlengths 7 101 | repo_stars int64 100 139k | repo_forks int64 0 26.4k | repo_open_issues int64 0 2.27k | repo_license stringclasses 12 values | repo_extraction_date stringclasses 433 values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
26,800 | adding.py | kovidgoyal_calibre/src/calibre/gui2/preferences/adding.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os
from qt.core import QDialog, QFormLayout, Qt, QVBoxLayout
from calibre.gui2 import choose_dir, error_dialog, gprefs, question_dialog
from calibre.gui2.auto_add import AUTO_ADDED
from calibre.gui2.preferences import AbortCommit, CommaSeparatedList, ConfigWidgetBase, test_widget
from calibre.gui2.preferences.adding_ui import Ui_Form
from calibre.gui2.widgets import FilenamePattern
from calibre.utils.config import prefs
class ConfigWidget(ConfigWidgetBase, Ui_Form):
def genesis(self, gui):
self.gui = gui
r = self.register
r('read_file_metadata', prefs)
r('swap_author_names', prefs)
r('add_formats_to_existing', prefs)
r('check_for_dupes_on_ctl', prefs)
r('preserve_date_on_ctl', gprefs)
r('manual_add_auto_convert', gprefs)
choices = [
(_('Ignore duplicate incoming formats'), 'ignore'),
(_('Overwrite existing duplicate formats'), 'overwrite'),
(_('Create new record for each duplicate format'), 'new record')]
r('automerge', gprefs, choices=choices)
r('new_book_tags', prefs, setting=CommaSeparatedList)
r('mark_new_books', prefs)
r('auto_add_path', gprefs, restart_required=True)
r('auto_add_everything', gprefs, restart_required=True)
r('auto_add_check_for_duplicates', gprefs)
r('auto_add_auto_convert', gprefs)
r('auto_convert_same_fmt', gprefs)
self.filename_pattern = FilenamePattern(self)
self.metadata_box.l = QVBoxLayout(self.metadata_box)
self.metadata_box.layout().insertWidget(0, self.filename_pattern)
self.filename_pattern.changed_signal.connect(self.changed_signal.emit)
self.auto_add_browse_button.clicked.connect(self.choose_aa_path)
for signal in ('Activated', 'Changed', 'DoubleClicked', 'Clicked'):
signal = getattr(self.opt_blocked_auto_formats, 'item'+signal)
signal.connect(self.blocked_auto_formats_changed)
self.tag_map_rules = self.add_filter_rules = self.author_map_rules = None
self.tag_map_rules_button.clicked.connect(self.change_tag_map_rules)
self.author_map_rules_button.clicked.connect(self.change_author_map_rules)
self.add_filter_rules_button.clicked.connect(self.change_add_filter_rules)
self.tabWidget.setCurrentIndex(0)
self.actions_tab.layout().setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
def change_tag_map_rules(self):
from calibre.gui2.tag_mapper import RulesDialog
d = RulesDialog(self)
if gprefs.get('tag_map_on_add_rules'):
d.rules = gprefs['tag_map_on_add_rules']
if d.exec() == QDialog.DialogCode.Accepted:
self.tag_map_rules = d.rules
self.changed_signal.emit()
def change_author_map_rules(self):
from calibre.gui2.author_mapper import RulesDialog
d = RulesDialog(self)
if gprefs.get('author_map_on_add_rules'):
d.rules = gprefs['author_map_on_add_rules']
if d.exec() == QDialog.DialogCode.Accepted:
self.author_map_rules = d.rules
self.changed_signal.emit()
def change_add_filter_rules(self):
from calibre.gui2.add_filters import RulesDialog
d = RulesDialog(self)
if gprefs.get('add_filter_rules'):
d.rules = gprefs['add_filter_rules']
if d.exec() == QDialog.DialogCode.Accepted:
self.add_filter_rules = d.rules
self.changed_signal.emit()
def choose_aa_path(self):
path = choose_dir(self, 'auto add path choose',
_('Choose a folder'))
if path:
self.opt_auto_add_path.setText(path)
self.opt_auto_add_path.save_history()
def initialize(self):
ConfigWidgetBase.initialize(self)
self.filename_pattern.blockSignals(True)
self.filename_pattern.initialize()
self.filename_pattern.blockSignals(False)
self.init_blocked_auto_formats()
self.opt_automerge.setEnabled(self.opt_add_formats_to_existing.isChecked())
self.tag_map_rules = self.add_filter_rules = self.author_map_rules = None
# Blocked auto formats {{{
def blocked_auto_formats_changed(self, *args):
fmts = self.current_blocked_auto_formats
old = gprefs['blocked_auto_formats']
if set(fmts) != set(old):
self.changed_signal.emit()
def init_blocked_auto_formats(self, defaults=False):
if defaults:
fmts = gprefs.defaults['blocked_auto_formats']
else:
fmts = gprefs['blocked_auto_formats']
viewer = self.opt_blocked_auto_formats
viewer.blockSignals(True)
exts = set(AUTO_ADDED)
viewer.clear()
for ext in sorted(exts):
viewer.addItem(ext)
item = viewer.item(viewer.count()-1)
item.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsUserCheckable)
item.setCheckState(Qt.CheckState.Checked if
ext in fmts else Qt.CheckState.Unchecked)
viewer.blockSignals(False)
@property
def current_blocked_auto_formats(self):
fmts = []
viewer = self.opt_blocked_auto_formats
for i in range(viewer.count()):
if viewer.item(i).checkState() == Qt.CheckState.Checked:
fmts.append(str(viewer.item(i).text()))
return fmts
# }}}
def restore_defaults(self):
ConfigWidgetBase.restore_defaults(self)
self.filename_pattern.initialize(defaults=True)
self.init_blocked_auto_formats(defaults=True)
self.tag_map_rules = []
self.author_map_rules = []
self.add_filter_rules = []
def commit(self):
path = str(self.opt_auto_add_path.text()).strip()
if path != gprefs['auto_add_path']:
if path:
path = os.path.abspath(path)
bname = os.path.basename(path)
self.opt_auto_add_path.setText(path)
if not os.path.isdir(path):
error_dialog(self, _('Invalid folder'),
_('You must specify an existing folder as your '
'auto-add folder. %s does not exist.')%path,
show=True)
raise AbortCommit('invalid auto-add folder')
if not os.access(path, os.R_OK|os.W_OK):
error_dialog(self, _('Invalid folder'),
_('You do not have read/write permissions for '
'the folder: %s')%path, show=True)
raise AbortCommit('invalid auto-add folder')
if bname and bname[0] in '._':
error_dialog(self, _('Invalid folder'),
_('Cannot use folders whose names start with a '
'period or underscore: %s')%os.path.basename(path), show=True)
raise AbortCommit('invalid auto-add folder')
if not question_dialog(self, _('Are you sure?'),
_('<b>WARNING:</b> Any files you place in %s will be '
'automatically deleted after being added to '
'calibre. Are you sure?')%path):
return
pattern = self.filename_pattern.commit()
prefs['filename_pattern'] = pattern
fmts = self.current_blocked_auto_formats
old = gprefs['blocked_auto_formats']
changed = set(fmts) != set(old)
if changed:
gprefs['blocked_auto_formats'] = self.current_blocked_auto_formats
if self.tag_map_rules is not None:
if self.tag_map_rules:
gprefs['tag_map_on_add_rules'] = self.tag_map_rules
else:
gprefs.pop('tag_map_on_add_rules', None)
if self.author_map_rules is not None:
if self.author_map_rules:
gprefs['author_map_on_add_rules'] = self.author_map_rules
else:
gprefs.pop('author_map_on_add_rules', None)
if self.add_filter_rules is not None:
if self.add_filter_rules:
gprefs['add_filter_rules'] = self.add_filter_rules
else:
gprefs.pop('add_filter_rules', None)
ret = ConfigWidgetBase.commit(self)
return changed or ret
def refresh_gui(self, gui):
# Ensure worker process reads updated settings
gui.spare_pool().shutdown()
# Update rules used int he auto adder
gui.auto_adder.read_rules()
if __name__ == '__main__':
from calibre.gui2 import Application
app = Application([])
test_widget('Import/Export', 'Adding')
| 8,979 | Python | .py | 185 | 37.351351 | 107 | 0.612201 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,801 | emailp.py | kovidgoyal_calibre/src/calibre/gui2/preferences/emailp.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2010, Kovid Goyal <kovid at kovidgoyal.net>
import re
import textwrap
from qt.core import QAbstractItemView, QAbstractTableModel, QFont, Qt
from calibre.gui2 import gprefs
from calibre.gui2.preferences import AbortCommit, ConfigWidgetBase, test_widget
from calibre.gui2.preferences.email_ui import Ui_Form
from calibre.startup import connect_lambda
from calibre.utils.config import ConfigProxy
from calibre.utils.icu import numeric_sort_key
from calibre.utils.smtp import config as smtp_prefs
from polyglot.builtins import as_unicode
class EmailAccounts(QAbstractTableModel): # {{{
def __init__(self, accounts, subjects, aliases={}, tags={}):
QAbstractTableModel.__init__(self)
self.accounts = accounts
self.subjects = subjects
self.aliases = aliases
self.tags = tags
self.sorted_on = (0, True)
self.account_order = list(self.accounts)
self.do_sort()
self.headers = [_('Email'), _('Formats'), _('Subject'),
_('Auto send'), _('Alias'), _('Auto send only tags')]
self.default_font = QFont()
self.default_font.setBold(True)
self.default_font = (self.default_font)
self.tooltips =[None] + list(map(textwrap.fill,
[_('Formats to email. The first matching format will be sent.'),
_('Subject of the email to use when sending. When left blank '
'the title will be used for the subject. Also, the same '
'templates used for "Save to disk" such as {title} and '
'{author_sort} can be used here.'),
'<p>'+_('If checked, downloaded news will be automatically '
'mailed to this email address '
'(provided it is in one of the listed formats and has not been filtered by tags).'),
_('Friendly name to use for this email address'),
_('If specified, only news with one of these tags will be sent to'
' this email address. All news downloads have their title as a'
' tag, so you can use this to easily control which news downloads'
' are sent to this email address.')
]))
def do_sort(self):
col = self.sorted_on[0]
if col == 0:
def key(account_key):
return numeric_sort_key(account_key)
elif col == 1:
def key(account_key):
return numeric_sort_key(self.accounts[account_key][0] or '')
elif col == 2:
def key(account_key):
return numeric_sort_key(self.subjects.get(account_key) or '')
elif col == 3:
def key(account_key):
return numeric_sort_key(as_unicode(self.accounts[account_key][0]) or '')
elif col == 4:
def key(account_key):
return numeric_sort_key(self.aliases.get(account_key) or '')
elif col == 5:
def key(account_key):
return numeric_sort_key(self.tags.get(account_key) or '')
self.account_order.sort(key=key, reverse=not self.sorted_on[1])
def sort(self, column, order=Qt.SortOrder.AscendingOrder):
nsort = (column, order == Qt.SortOrder.AscendingOrder)
if nsort != self.sorted_on:
self.sorted_on = nsort
self.beginResetModel()
try:
self.do_sort()
finally:
self.endResetModel()
def rowCount(self, *args):
return len(self.account_order)
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):
row, col = index.row(), index.column()
if row < 0 or row >= self.rowCount():
return None
account = self.account_order[row]
if account not in self.accounts:
return None
if role == Qt.ItemDataRole.UserRole:
return (account, self.accounts[account])
if role == Qt.ItemDataRole.ToolTipRole:
return self.tooltips[col]
if role in [Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.EditRole]:
if col == 0:
return (account)
if col == 1:
return ', '.join(x.strip() for x in (self.accounts[account][0] or '').split(','))
if col == 2:
return (self.subjects.get(account, ''))
if col == 4:
return (self.aliases.get(account, ''))
if col == 5:
return (self.tags.get(account, ''))
if role == Qt.ItemDataRole.FontRole and self.accounts[account][2]:
return self.default_font
if role == Qt.ItemDataRole.CheckStateRole and col == 3:
return (Qt.CheckState.Checked if self.accounts[account][1] else Qt.CheckState.Unchecked)
return None
def flags(self, index):
if index.column() == 3:
return QAbstractTableModel.flags(self, index)|Qt.ItemFlag.ItemIsUserCheckable
else:
return QAbstractTableModel.flags(self, index)|Qt.ItemFlag.ItemIsEditable
def setData(self, index, value, role):
if not index.isValid():
return False
row, col = index.row(), index.column()
account = self.account_order[row]
if col == 3:
self.accounts[account][1] ^= True
elif col == 2:
self.subjects[account] = as_unicode(value or '')
elif col == 4:
self.aliases.pop(account, None)
aval = as_unicode(value or '').strip()
if aval:
self.aliases[account] = aval
elif col == 5:
self.tags.pop(account, None)
aval = as_unicode(value or '').strip()
if aval:
self.tags[account] = aval
elif col == 1:
self.accounts[account][0] = re.sub(',+', ',', re.sub(r'\s+', ',', as_unicode(value or '').upper()))
elif col == 0:
na = as_unicode(value or '').strip()
from email.utils import parseaddr
addr = parseaddr(na)[-1]
if not addr or '@' not in na:
return False
self.accounts[na] = self.accounts.pop(account)
self.account_order[row] = na
if '@kindle.com' in addr:
self.accounts[na][0] = 'EPUB, TPZ'
self.dataChanged.emit(
self.index(index.row(), 0), self.index(index.row(), 3))
return True
def make_default(self, index):
if index.isValid():
self.beginResetModel()
row = index.row()
for x in self.accounts.values():
x[2] = False
self.accounts[self.account_order[row]][2] = True
self.endResetModel()
def add(self):
x = _('new email address')
y = x
c = 0
while y in self.accounts:
c += 1
y = x + str(c)
auto_send = len(self.accounts) < 1
self.beginResetModel()
self.accounts[y] = ['MOBI, EPUB', auto_send,
len(self.account_order) == 0]
self.account_order = list(self.accounts)
self.do_sort()
self.endResetModel()
return self.index(self.account_order.index(y), 0)
def remove_rows(self, *rows):
for row in sorted(rows, reverse=True):
try:
account = self.account_order[row]
except Exception:
continue
self.accounts.pop(account)
self.account_order = sorted(self.accounts)
has_default = False
for account in self.account_order:
if self.accounts[account][2]:
has_default = True
break
if not has_default and self.account_order:
self.accounts[self.account_order[0]][2] = True
self.beginResetModel()
self.endResetModel()
self.do_sort()
def remove(self, index):
if index.isValid():
self.remove(index.row())
# }}}
class ConfigWidget(ConfigWidgetBase, Ui_Form):
supports_restoring_to_defaults = False
def genesis(self, gui):
self.gui = gui
self.proxy = ConfigProxy(smtp_prefs())
r = self.register
r('add_comments_to_email', gprefs)
self.send_email_widget.initialize(self.preferred_to_address)
self.send_email_widget.changed_signal.connect(self.changed_signal.emit)
opts = self.send_email_widget.smtp_opts
self._email_accounts = EmailAccounts(opts.accounts, opts.subjects,
opts.aliases, opts.tags)
connect_lambda(self._email_accounts.dataChanged, self, lambda self: self.changed_signal.emit())
self.email_view.setModel(self._email_accounts)
self.email_view.sortByColumn(0, Qt.SortOrder.AscendingOrder)
self.email_view.setSortingEnabled(True)
self.email_add.clicked.connect(self.add_email_account)
self.email_make_default.clicked.connect(self.make_default)
self.email_view.resizeColumnsToContents()
self.email_remove.clicked.connect(self.remove_email_account)
def preferred_to_address(self):
if self._email_accounts.account_order:
return self._email_accounts.account_order[0]
def initialize(self):
ConfigWidgetBase.initialize(self)
# Initializing all done in genesis
def restore_defaults(self):
ConfigWidgetBase.restore_defaults(self)
# No defaults to restore to
def commit(self):
if self.email_view.state() == QAbstractItemView.State.EditingState:
# Ensure that the cell being edited is committed by switching focus
# to some other widget, which automatically closes the open editor
self.send_email_widget.setFocus(Qt.FocusReason.OtherFocusReason)
to_set = bool(self._email_accounts.accounts)
if not self.send_email_widget.set_email_settings(to_set):
raise AbortCommit('abort')
self.proxy['accounts'] = self._email_accounts.accounts
self.proxy['subjects'] = self._email_accounts.subjects
self.proxy['aliases'] = self._email_accounts.aliases
self.proxy['tags'] = self._email_accounts.tags
return ConfigWidgetBase.commit(self)
def make_default(self, *args):
self._email_accounts.make_default(self.email_view.currentIndex())
self.changed_signal.emit()
def add_email_account(self, *args):
index = self._email_accounts.add()
self.email_view.setCurrentIndex(index)
self.email_view.resizeColumnsToContents()
self.email_view.edit(index)
self.changed_signal.emit()
def remove_email_account(self, *args):
rows = set()
for idx in self.email_view.selectionModel().selectedIndexes():
rows.add(idx.row())
self._email_accounts.remove_rows(*rows)
self.changed_signal.emit()
def refresh_gui(self, gui):
from calibre.gui2.email import gui_sendmail
gui_sendmail.calculate_rate_limit()
if __name__ == '__main__':
from calibre.gui2 import Application
app = Application([])
test_widget('Sharing', 'Email')
| 11,453 | Python | .py | 256 | 34.285156 | 111 | 0.603244 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,802 | metadata_sources.py | kovidgoyal_calibre/src/calibre/gui2/preferences/metadata_sources.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from operator import attrgetter
from qt.core import (
QAbstractListModel,
QAbstractTableModel,
QCursor,
QDialog,
QDialogButtonBox,
QFrame,
QIcon,
QLabel,
QMenu,
QScrollArea,
Qt,
QVBoxLayout,
QWidget,
pyqtSignal,
)
from calibre.customize.ui import all_metadata_plugins, default_disabled_plugins, disable_plugin, enable_plugin, is_disabled
from calibre.ebooks.metadata.sources.prefs import msprefs
from calibre.gui2 import error_dialog, question_dialog
from calibre.gui2.preferences import ConfigWidgetBase, test_widget
from calibre.gui2.preferences.metadata_sources_ui import Ui_Form
from calibre.utils.localization import ngettext
from polyglot.builtins import iteritems
class SourcesModel(QAbstractTableModel): # {{{
def __init__(self, parent=None):
QAbstractTableModel.__init__(self, parent)
self.gui_parent = parent
self.plugins = []
self.enabled_overrides = {}
self.cover_overrides = {}
def initialize(self):
self.beginResetModel()
self.plugins = list(all_metadata_plugins())
self.plugins.sort(key=attrgetter('name'))
self.enabled_overrides = {}
self.cover_overrides = {}
self.endResetModel()
def rowCount(self, parent=None):
return len(self.plugins)
def columnCount(self, parent=None):
return 2
def headerData(self, section, orientation, role):
if orientation == Qt.Orientation.Horizontal and role == Qt.ItemDataRole.DisplayRole:
if section == 0:
return _('Source')
if section == 1:
return _('Cover priority')
return None
def data(self, index, role):
try:
plugin = self.plugins[index.row()]
except:
return None
col = index.column()
if role in (Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.EditRole):
if col == 0:
return plugin.name
elif col == 1:
orig = msprefs['cover_priorities'].get(plugin.name, 1)
return self.cover_overrides.get(plugin, orig)
elif role == Qt.ItemDataRole.CheckStateRole and col == 0:
orig = Qt.CheckState.Unchecked if is_disabled(plugin) else Qt.CheckState.Checked
return self.enabled_overrides.get(plugin, orig)
elif role == Qt.ItemDataRole.UserRole:
return plugin
elif (role == Qt.ItemDataRole.DecorationRole and col == 0 and not
plugin.is_configured()):
return QIcon.ic('list_remove.png')
elif role == Qt.ItemDataRole.ToolTipRole:
base = plugin.description + '\n\n'
if plugin.is_configured():
return base + _('This source is configured and ready to go')
return base + _('This source needs configuration')
return None
def setData(self, index, val, role):
try:
plugin = self.plugins[index.row()]
except:
return False
col = index.column()
ret = False
if col == 0 and role == Qt.ItemDataRole.CheckStateRole:
val = Qt.CheckState(val)
if val == Qt.CheckState.Checked and 'Douban' in plugin.name:
if not question_dialog(self.gui_parent,
_('Are you sure?'), '<p>'+
_('This plugin is useful only for <b>Chinese</b>'
' language books. It can return incorrect'
' results for books in English. Are you'
' sure you want to enable it?'),
show_copy_button=False):
return ret
self.enabled_overrides[plugin] = val
ret = True
if col == 1 and role == Qt.ItemDataRole.EditRole:
try:
self.cover_overrides[plugin] = max(1, int(val))
ret = True
except (ValueError, TypeError):
pass
if ret:
self.dataChanged.emit(index, index)
return ret
def flags(self, index):
col = index.column()
ans = QAbstractTableModel.flags(self, index)
if col == 0:
return ans | Qt.ItemFlag.ItemIsUserCheckable
return Qt.ItemFlag.ItemIsEditable | ans
def commit(self):
for plugin, val in iteritems(self.enabled_overrides):
if val == Qt.CheckState.Checked:
enable_plugin(plugin)
elif val == Qt.CheckState.Unchecked:
disable_plugin(plugin)
if self.cover_overrides:
cp = msprefs['cover_priorities']
for plugin, val in iteritems(self.cover_overrides):
if val == 1:
cp.pop(plugin.name, None)
else:
cp[plugin.name] = val
msprefs['cover_priorities'] = cp
self.enabled_overrides = {}
self.cover_overrides = {}
def restore_defaults(self):
self.beginResetModel()
self.enabled_overrides = {p: (Qt.CheckState.Unchecked if p.name in
default_disabled_plugins else Qt.CheckState.Checked) for p in self.plugins}
self.cover_overrides = {p:
msprefs.defaults['cover_priorities'].get(p.name, 1)
for p in self.plugins}
self.endResetModel()
# }}}
class FieldsModel(QAbstractListModel): # {{{
def __init__(self, parent=None):
QAbstractTableModel.__init__(self, parent)
self.fields = []
self.descs = {
'authors': _('Authors'),
'comments': _('Comments'),
'pubdate': _('Published date'),
'publisher': _('Publisher'),
'rating' : _('Rating'),
'tags' : _('Tags'),
'title': _('Title'),
'series': ngettext('Series', 'Series', 1),
'languages': _('Languages'),
}
self.overrides = {}
self.exclude = frozenset([
'series_index', 'language' # some plugins use language instead of languages
])
def rowCount(self, parent=None):
return len(self.fields)
def initialize(self):
fields = set()
for p in all_metadata_plugins():
fields |= p.touched_fields
self.beginResetModel()
self.fields = []
for x in fields:
if not x.startswith('identifier:') and x not in self.exclude:
self.fields.append(x)
self.fields.sort(key=lambda x:self.descs.get(x, x))
self.endResetModel()
def state(self, field, defaults=False):
src = msprefs.defaults if defaults else msprefs
return (Qt.CheckState.Unchecked if field in src['ignore_fields']
else Qt.CheckState.Checked)
def data(self, index, role):
try:
field = self.fields[index.row()]
except:
return None
if role == Qt.ItemDataRole.DisplayRole:
return self.descs.get(field, field)
if role == Qt.ItemDataRole.CheckStateRole:
return self.overrides.get(field, self.state(field))
return None
def flags(self, index):
ans = QAbstractListModel.flags(self, index)
return ans | Qt.ItemFlag.ItemIsUserCheckable
def restore_defaults(self):
self.beginResetModel()
self.overrides = {f: self.state(f, True) for f in self.fields}
self.endResetModel()
def select_all(self):
self.beginResetModel()
self.overrides = {f: Qt.CheckState.Checked for f in self.fields}
self.endResetModel()
def clear_all(self):
self.beginResetModel()
self.overrides = {f: Qt.CheckState.Unchecked for f in self.fields}
self.endResetModel()
def setData(self, index, val, role):
try:
field = self.fields[index.row()]
except:
return False
ret = False
if role == Qt.ItemDataRole.CheckStateRole:
self.overrides[field] = Qt.CheckState(val)
ret = True
if ret:
self.dataChanged.emit(index, index)
return ret
def commit(self):
ignored_fields = {x for x in msprefs['ignore_fields'] if x not in
self.overrides}
changed = {k for k, v in iteritems(self.overrides) if v ==
Qt.CheckState.Unchecked}
msprefs['ignore_fields'] = list(ignored_fields.union(changed))
def user_default_state(self, field):
return (Qt.CheckState.Unchecked if field in msprefs.get('user_default_ignore_fields',[])
else Qt.CheckState.Checked)
def select_user_defaults(self):
self.beginResetModel()
self.overrides = {f: self.user_default_state(f) for f in self.fields}
self.endResetModel()
def commit_user_defaults(self):
default_ignored_fields = {x for x in msprefs['user_default_ignore_fields'] if x not in
self.overrides}
changed = {k for k, v in iteritems(self.overrides) if v ==
Qt.CheckState.Unchecked}
msprefs['user_default_ignore_fields'] = list(default_ignored_fields.union(changed))
# }}}
class PluginConfig(QWidget): # {{{
finished = pyqtSignal()
def __init__(self, plugin, parent):
QWidget.__init__(self, parent)
self.plugin = plugin
self.l = l = QVBoxLayout()
self.setLayout(l)
self.c = c = QLabel(_('<b>Configure %(name)s</b><br>%(desc)s') % dict(
name=plugin.name, desc=plugin.description))
c.setAlignment(Qt.AlignmentFlag.AlignHCenter)
l.addWidget(c)
self.config_widget = plugin.config_widget()
self.sa = sa = QScrollArea(self)
sa.setWidgetResizable(True)
sa.setWidget(self.config_widget)
l.addWidget(sa)
self.bb = QDialogButtonBox(
QDialogButtonBox.StandardButton.Save|QDialogButtonBox.StandardButton.Cancel,
parent=self)
self.bb.accepted.connect(self.finished)
self.bb.rejected.connect(self.finished)
self.bb.accepted.connect(self.commit)
l.addWidget(self.bb)
self.f = QFrame(self)
self.f.setFrameShape(QFrame.Shape.HLine)
l.addWidget(self.f)
def commit(self):
self.plugin.save_settings(self.config_widget)
# }}}
class ConfigWidget(ConfigWidgetBase, Ui_Form):
def genesis(self, gui):
r = self.register
r('txt_comments', msprefs)
r('max_tags', msprefs)
r('wait_after_first_identify_result', msprefs)
r('wait_after_first_cover_result', msprefs)
r('swap_author_names', msprefs)
r('fewer_tags', msprefs)
r('keep_dups', msprefs)
r('append_comments', msprefs)
self.configure_plugin_button.clicked.connect(self.configure_plugin)
self.sources_model = SourcesModel(self)
self.sources_view.setModel(self.sources_model)
self.sources_model.dataChanged.connect(self.changed_signal)
self.fields_model = FieldsModel(self)
self.fields_view.setModel(self.fields_model)
self.fields_view.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.fields_view.customContextMenuRequested.connect(self.context_menu)
self.fields_model.dataChanged.connect(self.changed_signal)
self.select_all_button.clicked.connect(self.fields_model.select_all)
self.select_all_button.clicked.connect(self.changed_signal)
self.clear_all_button.clicked.connect(self.fields_model.clear_all)
self.clear_all_button.clicked.connect(self.changed_signal)
self.select_default_button.clicked.connect(self.fields_model.select_user_defaults)
self.select_default_button.clicked.connect(self.changed_signal)
self.set_as_default_button.clicked.connect(self.fields_model.commit_user_defaults)
self.tag_map_rules = self.author_map_rules = self.publisher_map_rules = None
m = QMenu(self)
m.addAction(_('Tags')).triggered.connect(self.change_tag_map_rules)
m.addAction(_('Authors')).triggered.connect(self.change_author_map_rules)
m.addAction(_('Publisher')).triggered.connect(self.change_publisher_map_rules)
self.map_rules_button.setMenu(m)
l = self.page.layout()
l.setStretch(0, 1)
l.setStretch(1, 1)
def context_menu(self, pos):
m = QMenu(self)
m.addAction(_('Select all'), self.fields_model.select_all)
m.addAction(_('Select none'), self.fields_model.clear_all)
m.addAction(_('Set as default'), self.fields_model.commit_user_defaults)
m.addAction(_('Select default'), self.fields_model.select_user_defaults)
m.exec(QCursor.pos())
def configure_plugin(self):
for index in self.sources_view.selectionModel().selectedRows():
plugin = self.sources_model.data(index, Qt.ItemDataRole.UserRole)
if plugin is not None:
return self.do_config(plugin)
error_dialog(self, _('No source selected'),
_('No source selected, cannot configure.'), show=True)
def do_config(self, plugin):
self.pc = PluginConfig(plugin, self)
self.stack.insertWidget(1, self.pc)
self.stack.setCurrentIndex(1)
self.pc.finished.connect(self.pc_finished)
def pc_finished(self):
try:
self.pc.finished.disconnect()
except:
pass
self.stack.setCurrentIndex(0)
self.stack.removeWidget(self.pc)
self.pc = None
def change_tag_map_rules(self):
from calibre.gui2.tag_mapper import RulesDialog
d = RulesDialog(self)
if msprefs.get('tag_map_rules'):
d.rules = list(msprefs['tag_map_rules'])
if d.exec() == QDialog.DialogCode.Accepted:
self.tag_map_rules = d.rules
self.changed_signal.emit()
def change_publisher_map_rules(self):
from calibre.gui2.publisher_mapper import RulesDialog
d = RulesDialog(self)
if msprefs.get('publisher_map_rules'):
d.rules = list(msprefs['publisher_map_rules'])
if d.exec() == QDialog.DialogCode.Accepted:
self.publisher_map_rules = d.rules
self.changed_signal.emit()
def change_author_map_rules(self):
from calibre.gui2.author_mapper import RulesDialog
d = RulesDialog(self)
if msprefs.get('author_map_rules'):
d.rules = list(msprefs['author_map_rules'])
if d.exec() == QDialog.DialogCode.Accepted:
self.author_map_rules = d.rules
self.changed_signal.emit()
def initialize(self):
ConfigWidgetBase.initialize(self)
self.sources_model.initialize()
self.sources_view.resizeColumnsToContents()
self.fields_model.initialize()
self.tag_map_rules = self.author_map_rules = self.publisher_map_rules = None
def restore_defaults(self):
ConfigWidgetBase.restore_defaults(self)
self.sources_model.restore_defaults()
self.fields_model.restore_defaults()
self.changed_signal.emit()
def commit(self):
self.sources_model.commit()
self.fields_model.commit()
if self.tag_map_rules is not None:
msprefs['tag_map_rules'] = self.tag_map_rules or []
if self.author_map_rules is not None:
msprefs['author_map_rules'] = self.author_map_rules or []
if self.publisher_map_rules is not None:
msprefs['publisher_map_rules'] = self.publisher_map_rules or []
return ConfigWidgetBase.commit(self)
if __name__ == '__main__':
from calibre.gui2 import Application
app = Application([])
test_widget('Sharing', 'Metadata download')
| 15,975 | Python | .py | 373 | 32.991957 | 123 | 0.619222 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,803 | columns.py | kovidgoyal_calibre/src/calibre/gui2/preferences/columns.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import copy
import sys
from contextlib import suppress
from qt.core import QAbstractItemView, QIcon, Qt, QTableWidgetItem
from calibre.gui2 import Application, error_dialog, gprefs, question_dialog
from calibre.gui2.preferences import ConfigWidgetBase, test_widget
from calibre.gui2.preferences.columns_ui import Ui_Form
from calibre.gui2.preferences.create_custom_column import CreateCustomColumn
class ConfigWidget(ConfigWidgetBase, Ui_Form):
restart_critical = True
def genesis(self, gui):
self.gui = gui
db = self.gui.library_view.model().db
self.custcols = copy.deepcopy(db.field_metadata.custom_field_metadata())
for k, cc in self.custcols.items():
cc['original_key'] = k
# Using max() in this way requires python 3.4+
self.initial_created_count = max((x['colnum'] for x in self.custcols.values()),
default=0) + 1
self.created_count = self.initial_created_count
self.column_up.clicked.connect(self.up_column)
self.column_down.clicked.connect(self.down_column)
self.opt_columns.setSelectionMode(QAbstractItemView.SingleSelection)
self.opt_columns.set_movement_functions(self.up_column, self.down_column)
self.del_custcol_button.clicked.connect(self.del_custcol)
self.add_custcol_button.clicked.connect(self.add_custcol)
self.add_col_button.clicked.connect(self.add_custcol)
self.edit_custcol_button.clicked.connect(self.edit_custcol)
self.opt_columns.currentItemChanged.connect(self.set_up_down_enabled)
for signal in ('Activated', 'Changed', 'DoubleClicked', 'Clicked'):
signal = getattr(self.opt_columns, 'item'+signal)
signal.connect(self.columns_changed)
self.show_all_button.clicked.connect(self.show_all)
self.hide_all_button.clicked.connect(self.hide_all)
def initialize(self):
ConfigWidgetBase.initialize(self)
self.init_columns()
def restore_defaults(self):
ConfigWidgetBase.restore_defaults(self)
self.init_columns(defaults=True)
self.changed_signal.emit()
def commit(self):
widths = []
for i in range(0, self.opt_columns.columnCount()):
widths.append(self.opt_columns.columnWidth(i))
gprefs.set('custcol-prefs-table-geometry', widths)
rr = ConfigWidgetBase.commit(self)
return self.apply_custom_column_changes() or rr
def init_columns(self, defaults=False):
# Set up columns
self.opt_columns.blockSignals(True)
self.model = model = self.gui.library_view.model()
colmap = list(model.column_map)
state = self.columns_state(defaults)
self.hidden_cols = state['hidden_columns']
positions = state['column_positions']
colmap.sort(key=lambda x: positions[x])
self.opt_columns.clear()
db = model.db
self.field_metadata = db.field_metadata
self.opt_columns.setColumnCount(6)
self.opt_columns.setHorizontalHeaderItem(0, QTableWidgetItem(_('Order')))
self.opt_columns.setHorizontalHeaderItem(1, QTableWidgetItem(_('Column header')))
self.opt_columns.setHorizontalHeaderItem(2, QTableWidgetItem(_('Lookup name')))
self.opt_columns.setHorizontalHeaderItem(3, QTableWidgetItem(_('Type')))
self.opt_columns.setHorizontalHeaderItem(4, QTableWidgetItem(_('Description')))
self.opt_columns.setHorizontalHeaderItem(5, QTableWidgetItem(_('Status')))
self.opt_columns.horizontalHeader().sectionClicked.connect(self.table_sorted)
self.opt_columns.verticalHeader().hide()
self.opt_columns.setRowCount(len(colmap))
self.column_desc = dict(map(lambda x:(CreateCustomColumn.column_types[x]['datatype'],
CreateCustomColumn.column_types[x]['text']),
CreateCustomColumn.column_types))
for row, key in enumerate(colmap):
self.setup_row(row, key, row)
self.initial_row_count = row
self.opt_columns.setSortingEnabled(True)
self.opt_columns.horizontalHeader().setSortIndicator(0, Qt.SortOrder.AscendingOrder)
self.restore_geometry()
self.opt_columns.cellDoubleClicked.connect(self.row_double_clicked)
self.opt_columns.setCurrentCell(0, 1)
self.set_up_down_enabled(self.opt_columns.currentItem(), None)
self.opt_columns.blockSignals(False)
def set_up_down_enabled(self, current_item, _):
h = self.opt_columns.horizontalHeader()
row = current_item.row()
if h.sortIndicatorSection() == 0 and h.sortIndicatorOrder() == Qt.SortOrder.AscendingOrder:
self.column_up.setEnabled(row > 0 and row <= self.initial_row_count)
self.column_down.setEnabled(row < self.initial_row_count)
def columns_changed(self, *args):
self.changed_signal.emit()
def columns_state(self, defaults=False):
if defaults:
return self.gui.library_view.get_default_state()
return self.gui.library_view.get_state()
def table_sorted(self, column):
h = self.opt_columns.horizontalHeader()
enabled = column == 0 and h.sortIndicatorOrder() == Qt.SortOrder.AscendingOrder
self.column_up.setEnabled(enabled)
self.column_down.setEnabled(enabled)
self.opt_columns.scrollTo(self.opt_columns.currentIndex())
self.set_up_down_enabled(self.opt_columns.currentItem(), _)
def row_double_clicked(self, r, c):
self.edit_custcol()
def restore_geometry(self):
geom = gprefs.get('custcol-prefs-table-geometry', None)
if geom is not None and len(geom) == self.opt_columns.columnCount():
with suppress(Exception):
for i in range(0, self.opt_columns.columnCount()):
self.opt_columns.setColumnWidth(i, geom[i])
return
self.opt_columns.resizeColumnsToContents()
def hide_all(self):
for row in range(self.opt_columns.rowCount()):
item = self.opt_columns.item(row, 0)
if item.checkState() != Qt.CheckState.PartiallyChecked:
item.setCheckState(Qt.CheckState.Unchecked)
self.changed_signal.emit()
def show_all(self):
for row in range(self.opt_columns.rowCount()):
item = self.opt_columns.item(row, 0)
if item.checkState() != Qt.CheckState.PartiallyChecked:
item.setCheckState(Qt.CheckState.Checked)
self.changed_signal.emit()
def setup_row(self, row, key, order, force_checked_to=None):
flags = Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable
if self.is_custom_key(key):
cc = self.custcols[key]
original_key = cc['original_key']
else:
cc = self.field_metadata[key]
original_key = key
self.opt_columns.setSortingEnabled(False)
item = QTableWidgetItem()
item.setData(Qt.ItemDataRole.DisplayRole, order)
item.setToolTip(str(order))
item.setData(Qt.ItemDataRole.UserRole, key)
item.setFlags(flags)
self.opt_columns.setItem(row, 0, item)
flags |= Qt.ItemFlag.ItemIsUserCheckable
if key == 'ondevice':
item.setFlags(flags & ~Qt.ItemFlag.ItemIsEnabled)
item.setCheckState(Qt.CheckState.PartiallyChecked)
else:
item.setFlags(flags)
if force_checked_to is None:
item.setCheckState(Qt.CheckState.Unchecked if key in self.hidden_cols else Qt.CheckState.Checked)
else:
item.setCheckState(force_checked_to)
item = QTableWidgetItem(cc['name'])
item.setToolTip(cc['name'])
item.setFlags(flags)
if self.is_custom_key(key):
item.setData(Qt.ItemDataRole.DecorationRole, (QIcon.ic('column.png')))
self.opt_columns.setItem(row, 1, item)
item = QTableWidgetItem(key)
item.setToolTip(key)
item.setFlags(flags)
self.opt_columns.setItem(row, 2, item)
if key == 'title':
coltype = _('Text')
elif key == 'ondevice':
coltype = _('Yes/No with text')
else:
dt = cc['datatype']
if cc['is_multiple']:
if key == 'authors' or cc.get('display', {}).get('is_names', False):
coltype = _('Ampersand separated text, shown in the Tag browser')
else:
coltype = self.column_desc['*' + dt]
else:
coltype = self.column_desc[dt]
item = QTableWidgetItem(coltype)
item.setToolTip(coltype)
item.setFlags(flags)
self.opt_columns.setItem(row, 3, item)
desc = cc['display'].get('description', "")
item = QTableWidgetItem(desc)
item.setToolTip(desc)
item.setFlags(flags)
self.opt_columns.setItem(row, 4, item)
if '*deleted' in cc:
col_status = _('Deleted column. Double-click to undelete it')
elif self.is_new_custom_column(cc):
col_status = _('New column')
elif original_key != key:
col_status = _('Edited. Lookup name was {}').format(original_key)
elif '*edited' in cc:
col_status = _('Edited')
else:
col_status = ''
item = QTableWidgetItem(col_status)
item.setToolTip(col_status)
item.setFlags(flags)
self.opt_columns.setItem(row, 5, item)
self.opt_columns.setSortingEnabled(True)
def recreate_row(self, row):
checked = self.opt_columns.item(row, 0).checkState()
title = self.opt_columns.item(row, 2).text()
self.setup_row(row, title, row, force_checked_to=checked)
def up_column(self):
self.opt_columns.setSortingEnabled(False)
row = self.opt_columns.currentRow()
if row > 0:
for i in range(0, self.opt_columns.columnCount()):
lower = self.opt_columns.takeItem(row-1, i)
upper = self.opt_columns.takeItem(row, i)
self.opt_columns.setItem(row, i, lower)
self.opt_columns.setItem(row-1, i, upper)
self.recreate_row(row-1)
self.recreate_row(row)
self.opt_columns.setCurrentCell(row-1, 1)
self.changed_signal.emit()
self.opt_columns.setSortingEnabled(True)
def down_column(self):
self.opt_columns.setSortingEnabled(False)
row = self.opt_columns.currentRow()
if row < self.opt_columns.rowCount()-1:
for i in range(0, self.opt_columns.columnCount()):
lower = self.opt_columns.takeItem(row, i)
upper = self.opt_columns.takeItem(row+1, i)
self.opt_columns.setItem(row+1, i, lower)
self.opt_columns.setItem(row, i, upper)
self.recreate_row(row+1)
self.recreate_row(row)
self.opt_columns.setCurrentCell(row+1, 1)
self.changed_signal.emit()
self.opt_columns.setSortingEnabled(True)
def is_new_custom_column(self, cc):
return 'colnum' in cc and cc['colnum'] >= self.initial_created_count
def set_new_custom_column(self, cc):
self.created_count += 1
cc['colnum'] = self.created_count
def del_custcol(self):
row = self.opt_columns.currentRow()
if row < 0:
return error_dialog(self, '', _('You must select a column to delete it'),
show=True)
key = str(self.opt_columns.item(row, 0).data(Qt.ItemDataRole.UserRole) or '')
if key not in self.custcols:
return error_dialog(self, '',
_('The selected column is not a custom column'), show=True)
if not question_dialog(self, _('Are you sure?'),
_('Do you really want to delete column %s and all its data?') %
self.custcols[key]['name'], show_copy_button=False):
return
if self.is_new_custom_column(self.custcols[key]):
del self.custcols[key] # A newly-added column was deleted
self.opt_columns.removeRow(row)
else:
self.custcols[key]['*deleted'] = True
self.setup_row(row, key, self.column_order_val(row))
self.changed_signal.emit()
def add_custcol(self):
model = self.gui.library_view.model()
CreateCustomColumn(self.gui, self, None, model.orig_headers)
if self.cc_column_key is None:
return
cc = self.custcols[self.cc_column_key]
self.set_new_custom_column(cc)
cc['original_key'] = self.cc_column_key
row = self.opt_columns.rowCount()
o = self.opt_columns
o.setRowCount(row + 1)
self.setup_row(row, self.cc_column_key, row)
# We need to find the new item after sorting
for i in range(0, o.rowCount()):
if self.column_order_val(i) == row:
o.setCurrentCell(i, 1)
o.scrollTo(o.currentIndex())
break
self.changed_signal.emit()
def label_to_lookup_name(self, label):
return '#' + label
def is_custom_key(self, key):
return key.startswith('#')
def column_order_val(self, row):
return int(self.opt_columns.item(row, 0).text())
def edit_custcol(self):
model = self.gui.library_view.model()
row = self.opt_columns.currentRow()
try:
key = str(self.opt_columns.item(row, 0).data(Qt.ItemDataRole.UserRole))
if key not in self.custcols:
return error_dialog(self, '',
_('The selected column is not a user-defined column'),
show=True)
cc = self.custcols[key]
if '*deleted' in cc:
if question_dialog(self, _('Undelete the column?'),
_('The column is to be deleted. Do you want to undelete it?'),
show_copy_button=False):
cc.pop('*deleted', None)
self.setup_row(row, key, self.column_order_val(row))
return
CreateCustomColumn(self.gui, self,
self.label_to_lookup_name(self.custcols[key]['label']),
model.orig_headers)
new_key = self.cc_column_key
if new_key is None:
return
if key != new_key:
self.custcols[new_key] = self.custcols[key]
self.custcols.pop(key, None)
cc = self.custcols[new_key]
if self.is_new_custom_column(cc):
cc.pop('*edited', None)
self.setup_row(row, new_key, self.column_order_val(row))
self.opt_columns.scrollTo(self.opt_columns.currentIndex())
self.changed_signal.emit()
except:
import traceback
traceback.print_exc()
def apply_custom_column_changes(self):
model = self.gui.library_view.model()
db = model.db
self.opt_columns.sortItems(0, Qt.SortOrder.AscendingOrder)
config_cols = [str(self.opt_columns.item(i, 0).data(Qt.ItemDataRole.UserRole) or '')
for i in range(self.opt_columns.rowCount())]
if not config_cols:
config_cols = ['title']
removed_cols = set(model.column_map) - set(config_cols)
hidden_cols = {str(self.opt_columns.item(i, 0).data(Qt.ItemDataRole.UserRole) or '')
for i in range(self.opt_columns.rowCount())
if self.opt_columns.item(i, 0).checkState()==Qt.CheckState.Unchecked}
hidden_cols = hidden_cols.union(removed_cols) # Hide removed cols
hidden_cols = list(hidden_cols.intersection(set(model.column_map)))
if 'ondevice' in hidden_cols:
hidden_cols.remove('ondevice')
def col_pos(x):
return config_cols.index(x) if x in config_cols else sys.maxsize
positions = {}
for i, col in enumerate(sorted(model.column_map, key=col_pos)):
positions[col] = i
state = {'hidden_columns': hidden_cols, 'column_positions':positions}
self.gui.library_view.apply_state(state)
self.gui.library_view.save_state()
must_restart = False
for cc in self.custcols.values():
if '*deleted' in cc:
db.delete_custom_column(label=cc['label'])
must_restart = True
elif '*edited' in cc:
db.set_custom_column_metadata(cc['colnum'], name=cc['name'],
label=cc['label'],
display=cc['display'],
notify=False)
if '*must_restart' in cc:
must_restart = True
elif self.is_new_custom_column(cc):
db.create_custom_column(label=cc['label'], name=cc['name'],
datatype=cc['datatype'], is_multiple=cc['is_multiple'],
display=cc['display'])
must_restart = True
return must_restart
if __name__ == '__main__':
app = Application([])
test_widget('Interface', 'Custom Columns')
| 17,613 | Python | .py | 362 | 37.146409 | 113 | 0.607558 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,804 | conversion.py | kovidgoyal_calibre/src/calibre/gui2/preferences/conversion.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import importlib
from qt.core import QHBoxLayout, QIcon, QListView, QScrollArea, QSize, QSizePolicy, QStackedWidget, QStringListModel, Qt, pyqtSignal
from calibre.customize.ui import input_format_plugins, output_format_plugins
from calibre.ebooks.conversion.plumber import Plumber
from calibre.gui2.convert import config_widget_for_input_plugin
from calibre.gui2.convert.heuristics import HeuristicsWidget
from calibre.gui2.convert.look_and_feel import LookAndFeelWidget
from calibre.gui2.convert.page_setup import PageSetupWidget
from calibre.gui2.convert.search_and_replace import SearchAndReplaceWidget
from calibre.gui2.convert.structure_detection import StructureDetectionWidget
from calibre.gui2.convert.toc import TOCWidget
from calibre.gui2.preferences import AbortCommit, ConfigWidgetBase, test_widget
from calibre.utils.logging import Log
class Model(QStringListModel):
def __init__(self, widgets):
QStringListModel.__init__(self)
self.widgets = widgets
self.setStringList([w.TITLE for w in widgets])
def data(self, index, role):
if role == Qt.ItemDataRole.DecorationRole:
w = self.widgets[index.row()]
if w.ICON:
return QIcon.ic(w.ICON)
return QStringListModel.data(self, index, role)
class ListView(QListView):
current_changed = pyqtSignal(object, object)
def __init__(self, parent=None):
QListView.__init__(self, parent)
self.setSizePolicy(QSizePolicy.Policy.MinimumExpanding, QSizePolicy.Policy.Expanding)
f = self.font()
f.setBold(True)
self.setFont(f)
self.setIconSize(QSize(48, 48))
self.setFlow(QListView.Flow.TopToBottom)
self.setSpacing(10)
def currentChanged(self, cur, prev):
QListView.currentChanged(self, cur, prev)
self.current_changed.emit(cur, prev)
class Base(ConfigWidgetBase):
restore_defaults_desc = _('Restore settings to default values. '
'Only settings for the currently selected section '
'are restored.')
def setupUi(self, x):
self.resize(720, 603)
self.l = l = QHBoxLayout(self)
self.list = lv = ListView(self)
l.addWidget(lv)
self.stack = s = QStackedWidget(self)
l.addWidget(s, stretch=10)
def genesis(self, gui):
log = Log()
log.outputs = []
self.plumber = Plumber('dummy.epub', 'dummy.epub', log, dummy=True,
merge_plugin_recs=False)
def widget_factory(cls):
plugin = getattr(cls, 'conv_plugin', None)
if plugin is None:
hfunc = self.plumber.get_option_help
else:
options = plugin.options.union(plugin.common_options)
def hfunc(name):
for rec in options:
if rec.option == name:
ans = getattr(rec, 'help', None)
if ans is not None:
return ans.replace('%default', str(rec.recommended_value))
return cls(self, self.plumber.get_option_by_name, hfunc, None, None)
self.load_conversion_widgets()
widgets = list(map(widget_factory, self.conversion_widgets))
self.model = Model(widgets)
self.list.setModel(self.model)
for w in widgets:
w.changed_signal.connect(self.changed_signal)
w.layout().setContentsMargins(6, 6, 6, 6)
sa = QScrollArea(self)
sa.setWidget(w)
sa.setWidgetResizable(True)
self.stack.addWidget(sa)
if isinstance(w, TOCWidget):
w.manually_fine_tune_toc.hide()
self.list.current_changed.connect(self.category_current_changed)
self.list.setCurrentIndex(self.model.index(0))
def initialize(self):
ConfigWidgetBase.initialize(self)
def restore_defaults(self):
ConfigWidgetBase.restore_defaults(self)
self.stack.currentWidget().widget().restore_defaults(self.plumber.get_option_by_name)
self.changed_signal.emit()
def commit(self):
for widget in self.model.widgets:
if not widget.pre_commit_check():
raise AbortCommit('abort')
widget.commit(save_defaults=True)
return ConfigWidgetBase.commit(self)
def category_current_changed(self, n, p):
self.stack.setCurrentIndex(n.row())
class CommonOptions(Base):
def load_conversion_widgets(self):
self.conversion_widgets = [LookAndFeelWidget, HeuristicsWidget,
PageSetupWidget,
StructureDetectionWidget, TOCWidget, SearchAndReplaceWidget,]
class InputOptions(Base):
def load_conversion_widgets(self):
self.conversion_widgets = []
for plugin in input_format_plugins():
pw = config_widget_for_input_plugin(plugin)
if pw is not None:
pw.conv_plugin = plugin
self.conversion_widgets.append(pw)
class OutputOptions(Base):
def load_conversion_widgets(self):
self.conversion_widgets = []
for plugin in output_format_plugins():
name = plugin.name.lower().replace(' ', '_')
try:
output_widget = importlib.import_module(
'calibre.gui2.convert.'+name)
pw = output_widget.PluginWidget
pw.conv_plugin = plugin
self.conversion_widgets.append(pw)
except ImportError:
continue
if __name__ == '__main__':
from calibre.gui2 import Application
app = Application([])
# test_widget('Conversion', 'Input Options')
test_widget('Conversion', 'Common Options')
# test_widget('Conversion', 'Output Options')
| 5,960 | Python | .py | 132 | 35.454545 | 132 | 0.648238 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,805 | sending.py | kovidgoyal_calibre/src/calibre/gui2/preferences/sending.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from calibre.gui2.preferences import AbortCommit, ConfigWidgetBase, test_widget
from calibre.gui2.preferences.sending_ui import Ui_Form
from calibre.library.save_to_disk import config
from calibre.utils.config import ConfigProxy, prefs
class ConfigWidget(ConfigWidgetBase, Ui_Form):
def genesis(self, gui):
self.gui = gui
self.proxy = ConfigProxy(config())
r = self.register
for x in ('send_timefmt',):
r(x, self.proxy)
choices = [(_('Manual management'), 'manual'),
(_('Only on send'), 'on_send'),
(_('Automatic management'), 'on_connect')]
r('manage_device_metadata', prefs, choices=choices)
if gui.device_manager.is_device_connected:
self.opt_manage_device_metadata.setEnabled(False)
self.opt_manage_device_metadata.setToolTip(
_('Cannot change metadata management while a device is connected'))
self.mm_label.setText(_('Metadata management (disabled while '
'device connected)'))
self.send_template.changed_signal.connect(self.changed_signal.emit)
def initialize(self):
ConfigWidgetBase.initialize(self)
self.send_template.blockSignals(True)
self.send_template.initialize('send_to_device', self.proxy['send_template'],
self.proxy.help('send_template'),
self.gui.library_view.model().db.field_metadata)
self.send_template.blockSignals(False)
def restore_defaults(self):
ConfigWidgetBase.restore_defaults(self)
self.send_template.set_value(self.proxy.defaults['send_template'])
def commit(self):
if not self.send_template.validate():
raise AbortCommit('abort')
self.send_template.save_settings(self.proxy, 'send_template')
return ConfigWidgetBase.commit(self)
if __name__ == '__main__':
from qt.core import QApplication
app = QApplication([])
test_widget('Import/Export', 'Sending')
| 2,170 | Python | .py | 45 | 39.644444 | 84 | 0.663662 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,806 | misc.py | kovidgoyal_calibre/src/calibre/gui2/preferences/misc.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import textwrap
from calibre import get_proxies
from calibre.gui2 import config, gprefs, open_local_file
from calibre.gui2.preferences import ConfigWidgetBase, Setting, test_widget
from calibre.gui2.preferences.misc_ui import Ui_Form
from polyglot.builtins import iteritems
class WorkersSetting(Setting):
def set_gui_val(self, val):
val = val//2
Setting.set_gui_val(self, val)
def get_gui_val(self):
val = Setting.get_gui_val(self)
return val * 2
class ConfigWidget(ConfigWidgetBase, Ui_Form):
def genesis(self, gui):
self.gui = gui
r = self.register
r('worker_limit', config, restart_required=True, setting=WorkersSetting)
r('enforce_cpu_limit', config, restart_required=True)
r('worker_max_time', gprefs)
self.opt_worker_limit.setToolTip(textwrap.fill(
_('The maximum number of jobs that will run simultaneously in '
'the background. This refers to CPU intensive tasks like '
' conversion. Lower this number'
' if you want calibre to use less CPU.')))
self.device_detection_button.clicked.connect(self.debug_device_detection)
self.icon_theme_button.clicked.connect(self.create_icon_theme)
self.button_open_config_dir.clicked.connect(self.open_config_dir)
self.user_defined_device_button.clicked.connect(self.user_defined_device)
proxies = get_proxies(debug=False)
txt = _('No proxies used')
if proxies:
lines = ['<br><code>%s: %s</code>'%(t, p) for t, p in
iteritems(proxies)]
txt = _('<b>Using proxies:</b>') + ''.join(lines)
self.proxies.setText(txt)
def create_icon_theme(self):
from calibre.gui2.icon_theme import create_theme
create_theme(parent=self)
def debug_device_detection(self, *args):
from calibre.gui2.preferences.device_debug import DebugDevice
d = DebugDevice(self.gui, self)
d.exec()
def user_defined_device(self, *args):
from calibre.gui2.preferences.device_user_defined import UserDefinedDevice
d = UserDefinedDevice(self)
d.exec()
def open_config_dir(self, *args):
from calibre.utils.config import config_dir
open_local_file(config_dir)
if __name__ == '__main__':
from qt.core import QApplication
app = QApplication([])
test_widget('Advanced', 'Misc')
| 2,619 | Python | .py | 58 | 37.241379 | 82 | 0.66195 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,807 | behavior.py | kovidgoyal_calibre/src/calibre/gui2/preferences/behavior.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import re
from functools import partial
from qt.core import QListWidgetItem, Qt
from calibre.constants import iswindows
from calibre.customize.ui import all_input_formats, available_output_formats
from calibre.ebooks import BOOK_EXTENSIONS
from calibre.ebooks.oeb.iterator import is_supported
from calibre.gui2 import config, dynamic, gprefs, info_dialog
from calibre.gui2.actions.choose_library import get_change_library_action_plugin
from calibre.gui2.preferences import ConfigWidgetBase, Setting, test_widget
from calibre.gui2.preferences.behavior_ui import Ui_Form
from calibre.utils.config import prefs
from calibre.utils.icu import sort_key
def input_order_drop_event(self, ev):
ret = self.opt_input_order.__class__.dropEvent(self.opt_input_order, ev)
if ev.isAccepted():
self.changed_signal.emit()
return ret
class OutputFormatSetting(Setting):
CHOICES_SEARCH_FLAGS = Qt.MatchFlag.MatchFixedString
class ConfigWidget(ConfigWidgetBase, Ui_Form):
def genesis(self, gui):
self.gui = gui
db = gui.library_view.model().db
r = self.register
choices = [(_('Low'), 'low'), (_('Normal'), 'normal'), (_('High'),
'high')] if iswindows else \
[(_('Normal'), 'normal'), (_('Low'), 'low'), (_('Very low'),
'high')]
r('worker_process_priority', prefs, choices=choices)
r('network_timeout', prefs)
r('new_version_notification', config)
r('upload_news_to_device', config)
r('delete_news_from_library_on_upload', config)
output_formats = sorted(available_output_formats())
output_formats.remove('oeb')
choices = [(x.upper(), x) for x in output_formats]
r('output_format', prefs, choices=choices, setting=OutputFormatSetting)
restrictions = sorted(db.prefs['virtual_libraries'], key=sort_key)
choices = [('', '')] + [(x, x) for x in restrictions]
# check that the virtual library still exists
vls = db.prefs['virtual_lib_on_startup']
if vls and vls not in restrictions:
db.prefs['virtual_lib_on_startup'] = ''
r('virtual_lib_on_startup', db.prefs, choices=choices)
self.reset_confirmation_button.clicked.connect(self.reset_confirmation_dialogs)
self.input_up_button.clicked.connect(self.up_input)
self.input_down_button.clicked.connect(self.down_input)
self.opt_input_order.set_movement_functions(self.up_input, self.down_input)
self.opt_input_order.dropEvent = partial(input_order_drop_event, self)
for signal in ('Activated', 'Changed', 'DoubleClicked', 'Clicked'):
signal = getattr(self.opt_internally_viewed_formats, 'item'+signal)
signal.connect(self.internally_viewed_formats_changed)
r('bools_are_tristate', db.prefs, restart_required=True)
r('numeric_collation', prefs, restart_required=True)
def initialize(self):
ConfigWidgetBase.initialize(self)
self.init_input_order()
self.init_internally_viewed_formats()
def restore_defaults(self):
ConfigWidgetBase.restore_defaults(self)
self.init_input_order(defaults=True)
self.init_internally_viewed_formats(defaults=True)
self.changed_signal.emit()
def commit(self):
input_map = prefs['input_format_order']
input_cols = [str(self.opt_input_order.item(i).data(Qt.ItemDataRole.UserRole) or '') for
i in range(self.opt_input_order.count())]
if input_map != input_cols:
prefs['input_format_order'] = input_cols
fmts = self.current_internally_viewed_formats
old = config['internally_viewed_formats']
if fmts != old:
config['internally_viewed_formats'] = fmts
ret = ConfigWidgetBase.commit(self)
# Signal a possible change of the VL at startup opt
get_change_library_action_plugin().rebuild_change_library_menus.emit()
return ret
# Internally viewed formats {{{
def internally_viewed_formats_changed(self, *args):
fmts = self.current_internally_viewed_formats
old = config['internally_viewed_formats']
if fmts != old:
self.changed_signal.emit()
def init_internally_viewed_formats(self, defaults=False):
if defaults:
fmts = config.defaults['internally_viewed_formats']
else:
fmts = config['internally_viewed_formats']
viewer = self.opt_internally_viewed_formats
viewer.blockSignals(True)
exts = set()
for ext in BOOK_EXTENSIONS:
ext = ext.lower()
ext = re.sub(r'(x{0,1})htm(l{0,1})', 'html', ext)
if ext == 'lrf' or is_supported('book.'+ext):
exts.add(ext)
viewer.clear()
for ext in sorted(exts):
viewer.addItem(ext.upper())
item = viewer.item(viewer.count()-1)
item.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsUserCheckable)
item.setCheckState(Qt.CheckState.Checked if
ext.upper() in fmts else Qt.CheckState.Unchecked)
viewer.blockSignals(False)
@property
def current_internally_viewed_formats(self):
fmts = []
viewer = self.opt_internally_viewed_formats
for i in range(viewer.count()):
if viewer.item(i).checkState() == Qt.CheckState.Checked:
fmts.append(str(viewer.item(i).text()))
return fmts
# }}}
# Input format order {{{
def init_input_order(self, defaults=False):
if defaults:
input_map = prefs.defaults['input_format_order']
else:
input_map = prefs['input_format_order']
all_formats = set()
self.opt_input_order.clear()
for fmt in all_input_formats().union({'ZIP', 'RAR'}):
all_formats.add(fmt.upper())
for format in input_map + list(all_formats.difference(input_map)):
item = QListWidgetItem(format, self.opt_input_order)
item.setData(Qt.ItemDataRole.UserRole, (format))
item.setFlags(Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsSelectable|Qt.ItemFlag.ItemIsDragEnabled)
def up_input(self, *args):
idx = self.opt_input_order.currentRow()
if idx > 0:
self.opt_input_order.insertItem(idx-1, self.opt_input_order.takeItem(idx))
self.opt_input_order.setCurrentRow(idx-1)
self.changed_signal.emit()
def down_input(self, *args):
idx = self.opt_input_order.currentRow()
if idx < self.opt_input_order.count()-1:
self.opt_input_order.insertItem(idx+1, self.opt_input_order.takeItem(idx))
self.opt_input_order.setCurrentRow(idx+1)
self.changed_signal.emit()
# }}}
def reset_confirmation_dialogs(self, *args):
for key in dynamic.keys():
if key.endswith('_again') and dynamic[key] is False:
dynamic[key] = True
gprefs['questions_to_auto_skip'] = []
info_dialog(self, _('Done'),
_('Confirmation dialogs have all been reset'), show=True)
if __name__ == '__main__':
from calibre.gui2 import Application
app = Application([])
test_widget('Interface', 'Behavior')
| 7,465 | Python | .py | 156 | 39.025641 | 111 | 0.647609 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,808 | main.py | kovidgoyal_calibre/src/calibre/gui2/preferences/main.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import re
import textwrap
from collections import OrderedDict
from functools import partial
from qt.core import (
QApplication,
QDialog,
QDialogButtonBox,
QFont,
QFrame,
QHBoxLayout,
QIcon,
QLabel,
QPainter,
QPointF,
QPushButton,
QScrollArea,
QSize,
QSizePolicy,
QStackedWidget,
QStatusTipEvent,
Qt,
QTabWidget,
QTextLayout,
QToolBar,
QVBoxLayout,
QWidget,
pyqtSignal,
)
from calibre.constants import __appname__, __version__
from calibre.customize.ui import preferences_plugins
from calibre.gui2 import gprefs, show_restart_warning
from calibre.gui2.dialogs.message_box import Icon
from calibre.gui2.preferences import AbortCommit, AbortInitialize, get_plugin, init_gui
ICON_SIZE = 32
# Title Bar {{{
class Message(QWidget):
def __init__(self, parent):
QWidget.__init__(self, parent)
self.layout = QTextLayout()
self.layout.setFont(self.font())
self.layout.setCacheEnabled(True)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
self.last_layout_rect = None
def setText(self, text):
self.layout.setText(text)
self.last_layout_rect = None
self.update()
def sizeHint(self):
return QSize(10, 10)
def do_layout(self):
ly = self.layout
ly.beginLayout()
w = self.width() - 5
height = 0
leading = self.fontMetrics().leading()
while True:
line = ly.createLine()
if not line.isValid():
break
line.setLineWidth(w)
height += leading
line.setPosition(QPointF(5, height))
height += line.height()
ly.endLayout()
def paintEvent(self, ev):
if self.last_layout_rect != self.rect():
self.do_layout()
p = QPainter(self)
br = self.layout.boundingRect()
y = 0
if br.height() < self.height():
y = (self.height() - br.height()) / 2
self.layout.draw(p, QPointF(0, y))
class TitleBar(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.l = l = QHBoxLayout(self)
self.icon = Icon(self, size=ICON_SIZE)
l.addWidget(self.icon)
self.title = QLabel('')
self.title.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
l.addWidget(self.title)
l.addStrut(25)
self.msg = la = Message(self)
l.addWidget(la)
self.default_message = __appname__ + ' ' + _('version') + ' ' + \
__version__ + ' ' + _('created by Kovid Goyal')
self.show_plugin()
self.show_msg()
def show_plugin(self, plugin=None):
self.icon.set_icon(QIcon.ic('lt.png' if plugin is None else plugin.icon))
self.title.setText('<h1>' + (_('Preferences') if plugin is None else plugin.gui_name))
def show_msg(self, msg=None):
msg = msg or self.default_message
self.msg.setText(' '.join(msg.splitlines()).strip())
# }}}
class Category(QWidget): # {{{
plugin_activated = pyqtSignal(object)
def __init__(self, name, plugins, gui_name, parent=None):
QWidget.__init__(self, parent)
self._layout = QVBoxLayout()
self.setLayout(self._layout)
self.label = QLabel(gui_name)
self.sep = QFrame(self)
self.bf = QFont()
self.bf.setBold(True)
self.label.setFont(self.bf)
self.sep.setFrameShape(QFrame.Shape.HLine)
self._layout.addWidget(self.label)
self._layout.addWidget(self.sep)
self.plugins = plugins
self.bar = QToolBar(self)
self.bar.setStyleSheet(
'QToolBar { border: none; background: none }')
lh = QApplication.instance().line_height
self.bar.setIconSize(QSize(2*lh, 2*lh))
self.bar.setMovable(False)
self.bar.setFloatable(False)
self.bar.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextUnderIcon)
self._layout.addWidget(self.bar)
self.actions = []
for p in plugins:
target = partial(self.triggered, p)
ac = self.bar.addAction(QIcon.ic(p.icon), p.gui_name.replace('&', '&&'), target)
ac.setToolTip(textwrap.fill(p.description))
ac.setWhatsThis(textwrap.fill(p.description))
ac.setStatusTip(p.description)
self.actions.append(ac)
w = self.bar.widgetForAction(ac)
w.setCursor(Qt.CursorShape.PointingHandCursor)
if hasattr(w, 'setAutoRaise'):
w.setAutoRaise(True)
w.setMinimumWidth(100)
def triggered(self, plugin, *args):
self.plugin_activated.emit(plugin)
# }}}
class Browser(QScrollArea): # {{{
show_plugin = pyqtSignal(object)
def __init__(self, parent=None):
QScrollArea.__init__(self, parent)
self.setWidgetResizable(True)
category_map, category_names = {}, {}
for plugin in preferences_plugins():
if plugin.category not in category_map:
category_map[plugin.category] = plugin.category_order
if category_map[plugin.category] < plugin.category_order:
category_map[plugin.category] = plugin.category_order
if plugin.category not in category_names:
category_names[plugin.category] = (plugin.gui_category if
plugin.gui_category else plugin.category)
self.category_names = category_names
categories = list(category_map.keys())
categories.sort(key=lambda x: category_map[x])
self.category_map = OrderedDict()
for c in categories:
self.category_map[c] = []
for plugin in preferences_plugins():
self.category_map[plugin.category].append(plugin)
for plugins in self.category_map.values():
plugins.sort(key=lambda x: x.name_order)
self.widgets = []
self._layout = QVBoxLayout()
self.container = QWidget(self)
self.container.setLayout(self._layout)
self.setWidget(self.container)
for name, plugins in self.category_map.items():
w = Category(name, plugins, self.category_names[name], parent=self)
self.widgets.append(w)
self._layout.addWidget(w)
w.plugin_activated.connect(self.show_plugin.emit)
self._layout.addStretch(1)
# }}}
must_restart_message = _('The changes you have made require calibre be '
'restarted immediately. You will not be allowed to '
'set any more preferences, until you restart.')
class Preferences(QDialog):
run_wizard_requested = pyqtSignal()
def __init__(self, gui, initial_plugin=None, close_after_initial=False):
QDialog.__init__(self, gui)
self.gui = gui
self.must_restart = False
self.do_restart = False
self.committed = False
self.close_after_initial = close_after_initial
self.restore_geometry(gprefs, 'preferences dialog geometry')
self.setWindowModality(Qt.WindowModality.ApplicationModal)
self.setWindowTitle(__appname__ + ' — ' + _('Preferences'))
self.setWindowIcon(QIcon.ic('config.png'))
self.l = l = QVBoxLayout(self)
self.stack = QStackedWidget(self)
self.bb = QDialogButtonBox(
QDialogButtonBox.StandardButton.Close | QDialogButtonBox.StandardButton.Apply |
QDialogButtonBox.StandardButton.Cancel
)
self.bb.button(QDialogButtonBox.StandardButton.Apply).clicked.connect(self.accept)
self.wizard_button = QPushButton(QIcon.ic('wizard.png'), _('Run Welcome &wizard'))
self.wizard_button.clicked.connect(self.run_wizard, type=Qt.ConnectionType.QueuedConnection)
self.wizard_button.setAutoDefault(False)
self.restore_defaults_button = rdb = QPushButton(QIcon.ic('clear_left.png'), _('Restore &defaults'))
rdb.clicked.connect(self.restore_defaults, type=Qt.ConnectionType.QueuedConnection)
rdb.setAutoDefault(False)
rdb.setVisible(False)
self.bb.rejected.connect(self.reject)
self.browser = Browser(self)
self.browser.show_plugin.connect(self.show_plugin)
self.stack.addWidget(self.browser)
self.scroll_area = QScrollArea(self)
self.stack.addWidget(self.scroll_area)
self.scroll_area.setWidgetResizable(True)
self.setContextMenuPolicy(Qt.ContextMenuPolicy.NoContextMenu)
self.title_bar = TitleBar(self)
for ac, tt in [(QDialogButtonBox.StandardButton.Apply, _('Save changes')),
(QDialogButtonBox.StandardButton.Cancel, _('Cancel and return to overview'))]:
self.bb.button(ac).setToolTip(tt)
l.addWidget(self.title_bar), l.addWidget(self.stack)
h = QHBoxLayout()
l.addLayout(h)
h.addWidget(self.wizard_button), h.addWidget(self.restore_defaults_button), h.addStretch(10), h.addWidget(self.bb)
if initial_plugin is not None:
category, name = initial_plugin[:2]
plugin = get_plugin(category, name)
if plugin is not None:
self.show_plugin(plugin)
if len(initial_plugin) > 2:
w = self.findChild(QWidget, initial_plugin[2])
if w is not None:
for c in self.showing_widget.children():
if isinstance(c, QTabWidget):
idx = c.indexOf(w)
if idx > -1:
c.setCurrentIndex(idx)
try:
self.showing_widget.initial_tab_changed()
except Exception:
pass
break
else:
self.hide_plugin()
def sizeHint(self):
return QSize(930, 720)
def event(self, ev):
if isinstance(ev, QStatusTipEvent):
msg = re.sub(r'</?[a-z1-6]+>', ' ', ev.tip())
self.title_bar.show_msg(msg)
return QDialog.event(self, ev)
def run_wizard(self):
self.run_wizard_requested.emit()
self.accept()
def set_tooltips_for_labels(self):
def process_child(child):
for g in child.children():
if isinstance(g, QLabel):
buddy = g.buddy()
if buddy is not None and hasattr(buddy, 'toolTip'):
htext = str(buddy.toolTip()).strip()
etext = str(g.toolTip()).strip()
if htext and not etext:
g.setToolTip(htext)
g.setWhatsThis(htext)
else:
process_child(g)
process_child(self.showing_widget)
def show_plugin(self, plugin):
self.showing_widget = plugin.create_widget(self.scroll_area)
self.showing_widget.genesis(self.gui)
try:
self.showing_widget.initialize()
except AbortInitialize:
return
self.set_tooltips_for_labels()
self.scroll_area.setWidget(self.showing_widget)
self.stack.setCurrentIndex(1)
self.showing_widget.show()
self.setWindowTitle(__appname__ + ' - ' + _('Preferences') + ' - ' + plugin.gui_name)
self.showing_widget.restart_now.connect(self.restart_now)
self.title_bar.show_plugin(plugin)
self.setWindowIcon(QIcon.ic(plugin.icon))
self.bb.button(QDialogButtonBox.StandardButton.Close).setVisible(False)
self.wizard_button.setVisible(False)
for button in (QDialogButtonBox.StandardButton.Apply, QDialogButtonBox.StandardButton.Cancel):
button = self.bb.button(button)
button.setVisible(True)
self.bb.button(QDialogButtonBox.StandardButton.Apply).setEnabled(False)
self.bb.button(QDialogButtonBox.StandardButton.Apply).setDefault(False), self.bb.button(QDialogButtonBox.StandardButton.Apply).setDefault(True)
self.restore_defaults_button.setEnabled(self.showing_widget.supports_restoring_to_defaults)
self.restore_defaults_button.setVisible(self.showing_widget.supports_restoring_to_defaults)
self.restore_defaults_button.setToolTip(
self.showing_widget.restore_defaults_desc if self.showing_widget.supports_restoring_to_defaults else
(_('Restoring to defaults not supported for') + ' ' + plugin.gui_name))
self.restore_defaults_button.setText(_('Restore &defaults'))
self.showing_widget.changed_signal.connect(self.changed_signal)
def changed_signal(self):
b = self.bb.button(QDialogButtonBox.StandardButton.Apply)
b.setEnabled(True)
def hide_plugin(self):
for sig in 'changed_signal restart_now'.split():
try:
getattr(self.showing_widget, sig).disconnect(getattr(self, sig))
except Exception:
pass
self.stack.setCurrentIndex(0)
self.showing_widget = QWidget(self.scroll_area)
self.scroll_area.setWidget(self.showing_widget)
self.setWindowTitle(__appname__ + ' - ' + _('Preferences'))
self.title_bar.show_plugin()
self.setWindowIcon(QIcon.ic('config.png'))
for button in (QDialogButtonBox.StandardButton.Apply, QDialogButtonBox.StandardButton.Cancel):
button = self.bb.button(button)
button.setVisible(False)
self.restore_defaults_button.setVisible(False)
self.bb.button(QDialogButtonBox.StandardButton.Close).setVisible(True)
self.bb.button(QDialogButtonBox.StandardButton.Close).setDefault(False), self.bb.button(QDialogButtonBox.StandardButton.Close).setDefault(True)
self.wizard_button.setVisible(True)
def restart_now(self):
try:
self.showing_widget.commit()
except AbortCommit:
return
self.do_restart = True
self.hide_plugin()
self.accept()
def commit(self, *args):
must_restart = self.showing_widget.commit()
rc = self.showing_widget.restart_critical
self.committed = True
do_restart = False
if must_restart:
self.must_restart = True
if rc:
msg = must_restart_message
else:
msg = _('Some of the changes you made require a restart.'
' Please restart calibre as soon as possible.')
do_restart = show_restart_warning(msg, parent=self)
self.showing_widget.refresh_gui(self.gui)
if do_restart:
self.do_restart = True
return self.close_after_initial or (must_restart and rc) or do_restart
def restore_defaults(self, *args):
self.showing_widget.restore_defaults()
def on_shutdown(self):
self.save_geometry(gprefs, 'preferences dialog geometry')
if self.committed:
self.gui.must_restart_before_config = self.must_restart
self.gui.tags_view.recount()
self.gui.create_device_menu()
self.gui.set_device_menu_items_state(bool(self.gui.device_connected))
self.gui.bars_manager.apply_settings()
self.gui.bars_manager.update_bars()
self.gui.build_context_menus()
def accept(self):
if self.stack.currentIndex() == 0:
self.on_shutdown()
return QDialog.accept(self)
try:
close = self.commit()
except AbortCommit:
return
if close:
self.on_shutdown()
return QDialog.accept(self)
self.hide_plugin()
def reject(self):
if self.stack.currentIndex() == 0 or self.close_after_initial:
self.on_shutdown()
return QDialog.reject(self)
self.hide_plugin()
if __name__ == '__main__':
from calibre.gui2 import Application
app = Application([])
app
gui = init_gui()
p = Preferences(gui)
p.exec()
gui.shutdown()
| 16,443 | Python | .py | 380 | 32.936842 | 151 | 0.618354 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,809 | server.py | kovidgoyal_calibre/src/calibre/gui2/preferences/server.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2010, Kovid Goyal <kovid at kovidgoyal.net>
import errno
import json
import numbers
import os
import sys
import textwrap
import time
from qt.core import (
QApplication,
QCheckBox,
QComboBox,
QDialog,
QDialogButtonBox,
QDoubleSpinBox,
QFormLayout,
QFrame,
QHBoxLayout,
QIcon,
QLabel,
QLayout,
QLineEdit,
QListWidget,
QPlainTextEdit,
QPushButton,
QScrollArea,
QSize,
QSizePolicy,
QSpinBox,
Qt,
QTabWidget,
QTimer,
QToolButton,
QUrl,
QVBoxLayout,
QWidget,
pyqtSignal,
sip,
)
from calibre import as_unicode
from calibre.constants import isportable, iswindows
from calibre.gui2 import choose_files, choose_save_file, config, error_dialog, gprefs, info_dialog, open_url, warning_dialog
from calibre.gui2.preferences import AbortCommit, ConfigWidgetBase, test_widget
from calibre.gui2.widgets import HistoryLineEdit
from calibre.srv.code import custom_list_template as default_custom_list_template
from calibre.srv.embedded import custom_list_template, search_the_net_urls
from calibre.srv.library_broker import load_gui_libraries
from calibre.srv.loop import parse_trusted_ips
from calibre.srv.opts import change_settings, options, server_config
from calibre.srv.users import UserManager, create_user_data, validate_password, validate_username
from calibre.utils.icu import primary_sort_key
from calibre.utils.localization import ngettext
from calibre.utils.shared_file import share_open
from polyglot.builtins import as_bytes
if iswindows and not isportable:
from calibre_extensions import winutil
def get_exe():
exe_base = os.path.abspath(os.path.dirname(sys.executable))
exe = os.path.join(exe_base, 'calibre.exe')
if isinstance(exe, bytes):
exe = os.fsdecode(exe)
return exe
def startup_shortcut_path():
startup_path = winutil.special_folder_path(winutil.CSIDL_STARTUP)
return os.path.join(startup_path, "calibre.lnk")
def create_shortcut(shortcut_path, target, description, *args):
quoted_args = None
if args:
quoted_args = []
for arg in args:
quoted_args.append(f'"{arg}"')
quoted_args = ' '.join(quoted_args)
winutil.manage_shortcut(shortcut_path, target, description, quoted_args)
def shortcut_exists_at(shortcut_path, target):
if not os.access(shortcut_path, os.R_OK):
return False
name = winutil.manage_shortcut(shortcut_path, None, None, None)
if name is None:
return False
return os.path.normcase(os.path.abspath(name)) == os.path.normcase(os.path.abspath(target))
def set_run_at_startup(run_at_startup=True):
if run_at_startup:
create_shortcut(startup_shortcut_path(), get_exe(), 'calibre - E-book management', '--start-in-tray')
else:
shortcut_path = startup_shortcut_path()
if os.path.exists(shortcut_path):
os.remove(shortcut_path)
def is_set_to_run_at_startup():
try:
return shortcut_exists_at(startup_shortcut_path(), get_exe())
except Exception:
import traceback
traceback.print_exc()
else:
set_run_at_startup = is_set_to_run_at_startup = None
# Advanced {{{
def init_opt(widget, opt, layout):
widget.name, widget.default_val = opt.name, opt.default
if opt.longdoc:
widget.setWhatsThis(opt.longdoc)
widget.setStatusTip(opt.longdoc)
widget.setToolTip(textwrap.fill(opt.longdoc))
layout.addRow(opt.shortdoc + ':', widget)
class Bool(QCheckBox):
changed_signal = pyqtSignal()
def __init__(self, name, layout):
opt = options[name]
QCheckBox.__init__(self)
self.stateChanged.connect(self.changed_signal.emit)
init_opt(self, opt, layout)
def get(self):
return self.isChecked()
def set(self, val):
self.setChecked(bool(val))
class Int(QSpinBox):
changed_signal = pyqtSignal()
def __init__(self, name, layout):
QSpinBox.__init__(self)
self.setRange(0, 99999)
opt = options[name]
self.valueChanged.connect(self.changed_signal.emit)
init_opt(self, opt, layout)
def get(self):
return self.value()
def set(self, val):
self.setValue(int(val))
class Float(QDoubleSpinBox):
changed_signal = pyqtSignal()
def __init__(self, name, layout):
QDoubleSpinBox.__init__(self)
self.setRange(0, 20000)
self.setDecimals(1)
opt = options[name]
self.valueChanged.connect(self.changed_signal.emit)
init_opt(self, opt, layout)
def get(self):
return self.value()
def set(self, val):
self.setValue(float(val))
class Text(QLineEdit):
changed_signal = pyqtSignal()
def __init__(self, name, layout):
QLineEdit.__init__(self)
self.setClearButtonEnabled(True)
opt = options[name]
self.textChanged.connect(self.changed_signal.emit)
init_opt(self, opt, layout)
def get(self):
return self.text().strip() or None
def set(self, val):
self.setText(str(val or ''))
class Path(QWidget):
changed_signal = pyqtSignal()
def __init__(self, name, layout):
QWidget.__init__(self)
self.dname = name
opt = options[name]
self.l = l = QHBoxLayout(self)
l.setContentsMargins(0, 0, 0, 0)
self.text = t = HistoryLineEdit(self)
t.initialize(f'server-opts-{name}')
t.setClearButtonEnabled(True)
t.currentTextChanged.connect(self.changed_signal.emit)
l.addWidget(t)
self.b = b = QToolButton(self)
l.addWidget(b)
b.setIcon(QIcon.ic('document_open.png'))
b.setToolTip(_("Browse for the file"))
b.clicked.connect(self.choose)
init_opt(self, opt, layout)
def get(self):
return self.text.text().strip() or None
def set(self, val):
self.text.setText(str(val or ''))
def choose(self):
ans = choose_files(self, 'choose_path_srv_opts_' + self.dname, _('Choose a file'), select_only_single_file=True)
if ans:
self.set(ans[0])
self.text.save_history()
class Choices(QComboBox):
changed_signal = pyqtSignal()
def __init__(self, name, layout):
QComboBox.__init__(self)
self.setEditable(False)
opt = options[name]
self.choices = opt.choices
self.addItems(opt.choices)
self.currentIndexChanged.connect(self.changed_signal.emit)
init_opt(self, opt, layout)
def get(self):
return self.currentText()
def set(self, val):
if val in self.choices:
self.setCurrentText(val)
else:
self.setCurrentIndex(0)
class AdvancedTab(QWidget):
changed_signal = pyqtSignal()
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.l = l = QFormLayout(self)
l.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
self.widgets = []
self.widget_map = {}
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
for name in sorted(options, key=lambda n: options[n].shortdoc.lower()):
if name in ('auth', 'port', 'allow_socket_preallocation', 'userdb'):
continue
opt = options[name]
if opt.choices:
w = Choices
elif isinstance(opt.default, bool):
w = Bool
elif isinstance(opt.default, numbers.Integral):
w = Int
elif isinstance(opt.default, numbers.Real):
w = Float
else:
w = Text
if name in ('ssl_certfile', 'ssl_keyfile'):
w = Path
w = w(name, l)
setattr(self, 'opt_' + name, w)
self.widgets.append(w)
self.widget_map[name] = w
def genesis(self):
opts = server_config()
for w in self.widgets:
w.set(getattr(opts, w.name))
w.changed_signal.connect(self.changed_signal.emit)
def restore_defaults(self):
for w in self.widgets:
w.set(w.default_val)
def get(self, name):
return self.widget_map[name].get()
@property
def settings(self):
return {w.name: w.get() for w in self.widgets}
@property
def has_ssl(self):
return bool(self.get('ssl_certfile')) and bool(self.get('ssl_keyfile'))
# }}}
class MainTab(QWidget): # {{{
changed_signal = pyqtSignal()
start_server = pyqtSignal()
stop_server = pyqtSignal()
test_server = pyqtSignal()
show_logs = pyqtSignal()
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.l = l = QVBoxLayout(self)
self.la = la = QLabel(
_(
'calibre contains an internet server that allows you to'
' access your book collection using a browser from anywhere'
' in the world. Any changes to the settings will only take'
' effect after a server restart.'
)
)
la.setWordWrap(True)
l.addWidget(la)
l.addSpacing(10)
self.fl = fl = QFormLayout()
l.addLayout(fl)
self.opt_port = sb = QSpinBox(self)
if options['port'].longdoc:
sb.setToolTip(options['port'].longdoc)
sb.setRange(1, 65535)
sb.valueChanged.connect(self.changed_signal.emit)
fl.addRow(options['port'].shortdoc + ':', sb)
l.addSpacing(25)
self.opt_auth = cb = QCheckBox(
_('Require &username and password to access the Content server')
)
l.addWidget(cb)
self.auth_desc = la = QLabel(self)
la.setStyleSheet('QLabel { font-size: small; font-style: italic }')
la.setWordWrap(True)
l.addWidget(la)
l.addSpacing(25)
self.opt_autolaunch_server = al = QCheckBox(
_('Run server &automatically when calibre starts')
)
l.addWidget(al)
l.addSpacing(25)
self.h = h = QHBoxLayout()
l.addLayout(h)
for text, name in [(_('&Start server'),
'start_server'), (_('St&op server'), 'stop_server'),
(_('&Test server'),
'test_server'), (_('Show server &logs'), 'show_logs')]:
b = QPushButton(text)
b.clicked.connect(getattr(self, name).emit)
setattr(self, name + '_button', b)
if name == 'show_logs':
h.addStretch(10)
h.addWidget(b)
self.ip_info = QLabel(self)
self.update_ip_info()
from calibre.gui2.ui import get_gui
gui = get_gui()
if gui is not None:
gui.iactions['Connect Share'].share_conn_menu.server_state_changed_signal.connect(self.update_ip_info)
l.addSpacing(10)
l.addWidget(self.ip_info)
if set_run_at_startup is not None:
self.run_at_start_button = b = QPushButton('', self)
self.set_run_at_start_text()
b.clicked.connect(self.toggle_run_at_startup)
l.addSpacing(10)
l.addWidget(b)
l.addSpacing(10)
l.addStretch(10)
def set_run_at_start_text(self):
is_autostarted = is_set_to_run_at_startup()
self.run_at_start_button.setText(
_('Do not start calibre automatically when computer is started') if is_autostarted else
_('Start calibre when the computer is started')
)
self.run_at_start_button.setToolTip('<p>' + (
_('''Currently calibre is set to run automatically when the
computer starts. Use this button to disable that.''') if is_autostarted else
_('''Start calibre in the system tray automatically when the computer starts''')))
def toggle_run_at_startup(self):
set_run_at_startup(not is_set_to_run_at_startup())
self.set_run_at_start_text()
def update_ip_info(self):
from calibre.gui2.ui import get_gui
gui = get_gui()
if gui is not None:
t = get_gui().iactions['Connect Share'].share_conn_menu.ip_text
t = t.strip().strip('[]')
self.ip_info.setText(_('Content server listening at: %s') % t)
def genesis(self):
opts = server_config()
self.opt_auth.setChecked(opts.auth)
self.opt_auth.stateChanged.connect(self.auth_changed)
self.opt_port.setValue(opts.port)
self.change_auth_desc()
self.update_button_state()
def change_auth_desc(self):
self.auth_desc.setText(
_('Remember to create at least one user account in the "User accounts" tab')
if self.opt_auth.isChecked() else _(
'Requiring a username/password prevents unauthorized people from'
' accessing your calibre library. It is also needed for some features'
' such as making any changes to the library as well as'
' last read position/annotation syncing.'
)
)
def auth_changed(self):
self.changed_signal.emit()
self.change_auth_desc()
def restore_defaults(self):
self.opt_auth.setChecked(options['auth'].default)
self.opt_port.setValue(options['port'].default)
def update_button_state(self):
from calibre.gui2.ui import get_gui
gui = get_gui()
if gui is not None:
is_running = gui.content_server is not None and gui.content_server.is_running
self.ip_info.setVisible(is_running)
self.update_ip_info()
self.start_server_button.setEnabled(not is_running)
self.stop_server_button.setEnabled(is_running)
self.test_server_button.setEnabled(is_running)
@property
def settings(self):
return {'auth': self.opt_auth.isChecked(), 'port': self.opt_port.value()}
# }}}
# Users {{{
class NewUser(QDialog):
def __init__(self, user_data, parent=None, username=None):
QDialog.__init__(self, parent)
self.user_data = user_data
self.setWindowTitle(
_('Change password for {}').format(username)
if username else _('Add new user')
)
self.l = l = QFormLayout(self)
l.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
self.uw = u = QLineEdit(self)
l.addRow(_('&Username:'), u)
if username:
u.setText(username)
u.setReadOnly(True)
l.addRow(QLabel(_('Set the password for this user')))
self.p1, self.p2 = p1, p2 = QLineEdit(self), QLineEdit(self)
l.addRow(_('&Password:'), p1), l.addRow(_('&Repeat password:'), p2)
for p in p1, p2:
p.setEchoMode(QLineEdit.EchoMode.PasswordEchoOnEdit)
p.setMinimumWidth(300)
if username:
p.setText(user_data[username]['pw'])
self.showp = sp = QCheckBox(_('&Show password'))
sp.stateChanged.connect(self.show_password)
l.addRow(sp)
self.bb = bb = QDialogButtonBox(
QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
)
l.addRow(bb)
bb.accepted.connect(self.accept), bb.rejected.connect(self.reject)
(self.uw if not username else self.p1).setFocus(Qt.FocusReason.OtherFocusReason)
def show_password(self):
for p in self.p1, self.p2:
p.setEchoMode(
QLineEdit.EchoMode.Normal
if self.showp.isChecked() else QLineEdit.EchoMode.PasswordEchoOnEdit
)
@property
def username(self):
return self.uw.text().strip()
@property
def password(self):
return self.p1.text()
def accept(self):
if not self.uw.isReadOnly():
un = self.username
if not un:
return error_dialog(
self,
_('Empty username'),
_('You must enter a username'),
show=True
)
if un in self.user_data:
return error_dialog(
self,
_('Username already exists'),
_(
'A user with the username {} already exists. Please choose a different username.'
).format(un),
show=True
)
err = validate_username(un)
if err:
return error_dialog(self, _('Username is not valid'), err, show=True)
p1, p2 = self.password, self.p2.text()
if p1 != p2:
return error_dialog(
self,
_('Password do not match'),
_('The two passwords you entered do not match!'),
show=True
)
if not p1:
return error_dialog(
self,
_('Empty password'),
_('You must enter a password for this user'),
show=True
)
err = validate_password(p1)
if err:
return error_dialog(self, _('Invalid password'), err, show=True)
return QDialog.accept(self)
class Library(QWidget):
restriction_changed = pyqtSignal(object, object)
def __init__(self, name, is_checked=False, path='', restriction='', parent=None, is_first=False, enable_on_checked=True):
QWidget.__init__(self, parent)
self.name = name
self.enable_on_checked = enable_on_checked
self.l = l = QVBoxLayout(self)
l.setSizeConstraint(QLayout.SizeConstraint.SetMinAndMaxSize)
if not is_first:
self.border = b = QFrame(self)
b.setFrameStyle(QFrame.Shape.HLine)
l.addWidget(b)
self.cw = cw = QCheckBox(name.replace('&', '&&'))
cw.setStyleSheet('QCheckBox { font-weight: bold }')
cw.setChecked(is_checked)
cw.stateChanged.connect(self.state_changed)
if path:
cw.setToolTip(path)
l.addWidget(cw)
self.la = la = QLabel(_('Further &restrict access to books in this library that match:'))
l.addWidget(la)
self.rw = rw = QLineEdit(self)
rw.setPlaceholderText(_('A search expression'))
rw.setToolTip(textwrap.fill(_(
'A search expression. If specified, access will be further restricted'
' to only those books that match this expression. For example:'
' tags:"=Share"')))
rw.setText(restriction or '')
rw.textChanged.connect(self.on_rchange)
la.setBuddy(rw)
l.addWidget(rw)
self.state_changed()
def state_changed(self):
c = self.cw.isChecked()
w = (self.enable_on_checked and c) or (not self.enable_on_checked and not c)
for x in (self.la, self.rw):
x.setEnabled(bool(w))
def on_rchange(self):
self.restriction_changed.emit(self.name, self.restriction)
@property
def is_checked(self):
return self.cw.isChecked()
@property
def restriction(self):
return self.rw.text().strip()
class ChangeRestriction(QDialog):
def __init__(self, username, restriction, parent=None):
QDialog.__init__(self, parent)
self.setWindowTitle(_('Change library access permissions for {}').format(username))
self.username = username
self._items = []
self.l = l = QFormLayout(self)
l.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
self.libraries = t = QWidget(self)
t.setObjectName('libraries')
t.l = QVBoxLayout(self.libraries)
self.atype = a = QComboBox(self)
a.addItems([_('All libraries'), _('Only the specified libraries'), _('All except the specified libraries')])
self.library_restrictions = restriction['library_restrictions'].copy()
if restriction['allowed_library_names']:
a.setCurrentIndex(1)
self.items = restriction['allowed_library_names']
elif restriction['blocked_library_names']:
a.setCurrentIndex(2)
self.items = restriction['blocked_library_names']
else:
a.setCurrentIndex(0)
a.currentIndexChanged.connect(self.atype_changed)
l.addRow(_('Allow access to:'), a)
self.msg = la = QLabel(self)
la.setWordWrap(True)
l.addRow(la)
self.la = la = QLabel(_('Specify the libraries below:'))
la.setWordWrap(True)
self.sa = sa = QScrollArea(self)
sa.setWidget(t), sa.setWidgetResizable(True)
l.addRow(la), l.addRow(sa)
self.atype_changed()
self.bb = bb = QDialogButtonBox(
QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
)
bb.accepted.connect(self.accept), bb.rejected.connect(self.reject)
l.addWidget(bb)
self.items = self.items
def sizeHint(self):
return QSize(800, 600)
def __iter__(self):
return iter(self._items)
@property
def items(self):
return frozenset(item.name for item in self if item.is_checked)
def clear(self):
for c in self:
self.libraries.l.removeWidget(c)
c.setParent(None)
c.restriction_changed.disconnect()
sip.delete(c)
self._items = []
@items.setter
def items(self, val):
self.clear()
checked_libraries = frozenset(val)
library_paths = load_gui_libraries(gprefs)
gui_libraries = {os.path.basename(l):l for l in library_paths}
lchecked_libraries = {l.lower() for l in checked_libraries}
seen = set()
items = []
for x in checked_libraries | set(gui_libraries):
xl = x.lower()
if xl not in seen:
seen.add(xl)
items.append((x, xl in lchecked_libraries))
items.sort(key=lambda x: primary_sort_key(x[0]))
enable_on_checked = self.atype.currentIndex() == 1
for i, (l, checked) in enumerate(items):
l = Library(
l, checked, path=gui_libraries.get(l, ''),
restriction=self.library_restrictions.get(l.lower(), ''),
parent=self.libraries, is_first=i == 0,
enable_on_checked=enable_on_checked
)
l.restriction_changed.connect(self.restriction_changed)
self.libraries.l.addWidget(l)
self._items.append(l)
def restriction_changed(self, name, val):
name = name.lower()
self.library_restrictions[name] = val
@property
def restriction(self):
ans = {'allowed_library_names': frozenset(), 'blocked_library_names': frozenset(), 'library_restrictions': {}}
if self.atype.currentIndex() != 0:
k = ['allowed_library_names', 'blocked_library_names'][self.atype.currentIndex() - 1]
ans[k] = self.items
ans['library_restrictions'] = self.library_restrictions
return ans
def accept(self):
if self.atype.currentIndex() != 0 and not self.items:
return error_dialog(self, _('No libraries specified'), _(
'You have not specified any libraries'), show=True)
return QDialog.accept(self)
def atype_changed(self):
ci = self.atype.currentIndex()
sheet = ''
if ci == 0:
m = _('<b>{} is allowed access to all libraries')
self.libraries.setEnabled(False), self.la.setEnabled(False)
else:
if ci == 1:
m = _('{} is allowed access only to the libraries whose names'
' <b>match</b> one of the names specified below.')
else:
m = _('{} is allowed access to all libraries, <b>except</b> those'
' whose names match one of the names specified below.')
sheet += f'QWidget#libraries {{ background-color: {QApplication.instance().emphasis_window_background_color} }}'
self.libraries.setEnabled(True), self.la.setEnabled(True)
self.items = self.items
self.msg.setText(m.format(self.username))
self.libraries.setStyleSheet(sheet)
class User(QWidget):
changed_signal = pyqtSignal()
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
self.l = l = QFormLayout(self)
l.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
self.username_label = la = QLabel('')
l.addWidget(la)
self.ro_text = _('Allow {} to make &changes (i.e. grant write access)')
self.rw = rw = QCheckBox(self)
rw.setToolTip(
_(
'If enabled, allows the user to make changes to the library.'
' Adding books/deleting books/editing metadata, etc.'
)
)
rw.stateChanged.connect(self.readonly_changed)
l.addWidget(rw)
self.access_label = la = QLabel(self)
l.addWidget(la), la.setWordWrap(True)
self.cpb = b = QPushButton(_('Change &password'))
l.addWidget(b)
b.clicked.connect(self.change_password)
self.restrict_button = b = QPushButton(self)
b.clicked.connect(self.change_restriction)
l.addWidget(b)
self.show_user()
def change_password(self):
d = NewUser(self.user_data, self, self.username)
if d.exec() == QDialog.DialogCode.Accepted:
self.user_data[self.username]['pw'] = d.password
self.changed_signal.emit()
def readonly_changed(self):
self.user_data[self.username]['readonly'] = not self.rw.isChecked()
self.changed_signal.emit()
def update_restriction(self):
username, user_data = self.username, self.user_data
r = user_data[username]['restriction']
if r['allowed_library_names']:
libs = r['allowed_library_names']
m = ngettext(
'{} is currently only allowed to access the library named: {}',
'{} is currently only allowed to access the libraries named: {}',
len(libs)
).format(username, ', '.join(libs))
b = _('Change the allowed libraries')
elif r['blocked_library_names']:
libs = r['blocked_library_names']
m = ngettext(
'{} is currently not allowed to access the library named: {}',
'{} is currently not allowed to access the libraries named: {}',
len(libs)
).format(username, ', '.join(libs))
b = _('Change the blocked libraries')
else:
m = _('{} is currently allowed access to all libraries')
b = _('Restrict the &libraries {} can access').format(self.username)
self.restrict_button.setText(b),
self.access_label.setText(m.format(username))
def show_user(self, username=None, user_data=None):
self.username, self.user_data = username, user_data
self.cpb.setVisible(username is not None)
self.username_label.setText(('<h2>' + username) if username else '')
if username:
self.rw.setText(self.ro_text.format(username))
self.rw.setVisible(True)
self.rw.blockSignals(True), self.rw.setChecked(
not user_data[username]['readonly']
), self.rw.blockSignals(False)
self.access_label.setVisible(True)
self.restrict_button.setVisible(True)
self.update_restriction()
else:
self.rw.setVisible(False)
self.access_label.setVisible(False)
self.restrict_button.setVisible(False)
def change_restriction(self):
d = ChangeRestriction(
self.username,
self.user_data[self.username]['restriction'].copy(),
parent=self
)
if d.exec() == QDialog.DialogCode.Accepted:
self.user_data[self.username]['restriction'] = d.restriction
self.update_restriction()
self.changed_signal.emit()
def sizeHint(self):
ans = QWidget.sizeHint(self)
ans.setWidth(400)
return ans
class Users(QWidget):
changed_signal = pyqtSignal()
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.l = l = QHBoxLayout(self)
self.lp = lp = QVBoxLayout()
l.addLayout(lp)
self.h = h = QHBoxLayout()
lp.addLayout(h)
self.add_button = b = QPushButton(QIcon.ic('plus.png'), _('&Add user'), self)
b.clicked.connect(self.add_user)
h.addWidget(b)
self.remove_button = b = QPushButton(
QIcon.ic('minus.png'), _('&Remove user'), self
)
b.clicked.connect(self.remove_user)
h.addStretch(2), h.addWidget(b)
self.user_list = w = QListWidget(self)
w.setSpacing(1)
w.doubleClicked.connect(self.current_user_activated)
w.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Expanding)
lp.addWidget(w)
self.user_display = u = User(self)
u.changed_signal.connect(self.changed_signal.emit)
l.addWidget(u)
def genesis(self):
self.user_data = UserManager().user_data
self.user_list.addItems(sorted(self.user_data, key=primary_sort_key))
self.user_list.setCurrentRow(0)
self.user_list.currentItemChanged.connect(self.current_item_changed)
self.current_item_changed()
def current_user_activated(self):
self.user_display.change_password()
def current_item_changed(self):
item = self.user_list.currentItem()
if item is None:
username = None
else:
username = item.text()
if username not in self.user_data:
username = None
self.display_user_data(username)
def add_user(self):
d = NewUser(self.user_data, parent=self)
if d.exec() == QDialog.DialogCode.Accepted:
un, pw = d.username, d.password
self.user_data[un] = create_user_data(pw)
self.user_list.insertItem(0, un)
self.user_list.setCurrentRow(0)
self.display_user_data(un)
self.changed_signal.emit()
def remove_user(self):
u = self.user_list.currentItem()
if u is not None:
self.user_list.takeItem(self.user_list.row(u))
un = u.text()
self.user_data.pop(un, None)
self.changed_signal.emit()
self.current_item_changed()
def display_user_data(self, username=None):
self.user_display.show_user(username, self.user_data)
# }}}
class CustomList(QWidget): # {{{
changed_signal = pyqtSignal()
def __init__(self, parent):
QWidget.__init__(self, parent)
self.default_template = default_custom_list_template()
self.l = l = QFormLayout(self)
l.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
self.la = la = QLabel('<p>' + _(
'Here you can create a template to control what data is shown when'
' using the <i>Custom list</i> mode for the book list'))
la.setWordWrap(True)
l.addRow(la)
self.thumbnail = t = QCheckBox(_('Show a cover &thumbnail'))
self.thumbnail_height = th = QSpinBox(self)
th.setSuffix(' px'), th.setRange(60, 600)
self.entry_height = eh = QLineEdit(self)
l.addRow(t), l.addRow(_('Thumbnail &height:'), th)
l.addRow(_('Entry &height:'), eh)
t.stateChanged.connect(self.changed_signal)
th.valueChanged.connect(self.changed_signal)
eh.textChanged.connect(self.changed_signal)
eh.setToolTip(textwrap.fill(_(
'The height for each entry. The special value "auto" causes a height to be calculated'
' based on the number of lines in the template. Otherwise, use a CSS length, such as'
' 100px or 15ex')))
t.stateChanged.connect(self.thumbnail_state_changed)
th.setVisible(False)
self.comments_fields = cf = QLineEdit(self)
l.addRow(_('&Long text fields:'), cf)
cf.setToolTip(textwrap.fill(_(
'A comma separated list of fields that will be added at the bottom of every entry.'
' These fields are interpreted as containing HTML, not plain text.')))
cf.textChanged.connect(self.changed_signal)
self.la1 = la = QLabel('<p>' + _(
'The template below will be interpreted as HTML and all {{fields}} will be replaced'
' by the actual metadata, if available. For custom columns use the column lookup'
' name, for example: #mytags. You can use {0} as a separator'
' to split a line into multiple columns.').format('|||'))
la.setWordWrap(True)
l.addRow(la)
self.template = t = QPlainTextEdit(self)
l.addRow(t)
t.textChanged.connect(self.changed_signal)
self.imex = bb = QDialogButtonBox(self)
b = bb.addButton(_('&Import template'), QDialogButtonBox.ButtonRole.ActionRole)
b.clicked.connect(self.import_template)
b = bb.addButton(_('E&xport template'), QDialogButtonBox.ButtonRole.ActionRole)
b.clicked.connect(self.export_template)
l.addRow(bb)
def import_template(self):
paths = choose_files(self, 'custom-list-template', _('Choose template file'),
filters=[(_('Template files'), ['json'])], all_files=False, select_only_single_file=True)
if paths:
with open(paths[0], 'rb') as f:
raw = f.read()
self.current_template = self.deserialize(raw)
def export_template(self):
path = choose_save_file(
self, 'custom-list-template', _('Choose template file'),
filters=[(_('Template files'), ['json'])], initial_filename='custom-list-template.json')
if path:
raw = self.serialize(self.current_template)
with open(path, 'wb') as f:
f.write(as_bytes(raw))
def thumbnail_state_changed(self):
is_enabled = bool(self.thumbnail.isChecked())
for w, x in [(self.thumbnail_height, True), (self.entry_height, False)]:
w.setVisible(is_enabled is x)
self.layout().labelForField(w).setVisible(is_enabled is x)
def genesis(self):
self.current_template = custom_list_template() or self.default_template
@property
def current_template(self):
return {
'thumbnail': self.thumbnail.isChecked(),
'thumbnail_height': self.thumbnail_height.value(),
'height': self.entry_height.text().strip() or 'auto',
'comments_fields': [x.strip() for x in self.comments_fields.text().split(',') if x.strip()],
'lines': [x.strip() for x in self.template.toPlainText().splitlines()]
}
@current_template.setter
def current_template(self, template):
self.thumbnail.setChecked(bool(template.get('thumbnail')))
try:
th = int(template['thumbnail_height'])
except Exception:
th = self.default_template['thumbnail_height']
self.thumbnail_height.setValue(th)
self.entry_height.setText(template.get('height') or 'auto')
self.comments_fields.setText(', '.join(template.get('comments_fields') or ()))
self.template.setPlainText('\n'.join(template.get('lines') or ()))
def serialize(self, template):
return json.dumps(template, sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=True)
def deserialize(self, raw):
return json.loads(raw)
def restore_defaults(self):
self.current_template = self.default_template
def commit(self):
template = self.current_template
if template == self.default_template:
try:
os.remove(custom_list_template.path)
except OSError as err:
if err.errno != errno.ENOENT:
raise
else:
raw = self.serialize(template)
with open(custom_list_template.path, 'wb') as f:
f.write(as_bytes(raw))
return True
# }}}
# Search the internet {{{
class URLItem(QWidget):
changed_signal = pyqtSignal()
def __init__(self, as_dict, parent=None):
QWidget.__init__(self, parent)
self.changed_signal.connect(parent.changed_signal)
self.l = l = QFormLayout(self)
self.type_widget = t = QComboBox(self)
l.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow)
t.addItems([_('Book'), _('Author')])
l.addRow(_('URL type:'), t)
self.name_widget = n = QLineEdit(self)
n.setClearButtonEnabled(True)
l.addRow(_('Name:'), n)
self.url_widget = w = QLineEdit(self)
w.setClearButtonEnabled(True)
l.addRow(_('URL:'), w)
if as_dict:
self.name = as_dict['name']
self.url = as_dict['url']
self.url_type = as_dict['type']
self.type_widget.currentIndexChanged.connect(self.changed_signal)
self.name_widget.textChanged.connect(self.changed_signal)
self.url_widget.textChanged.connect(self.changed_signal)
@property
def is_empty(self):
return not self.name or not self.url
@property
def url_type(self):
return 'book' if self.type_widget.currentIndex() == 0 else 'author'
@url_type.setter
def url_type(self, val):
self.type_widget.setCurrentIndex(1 if val == 'author' else 0)
@property
def name(self):
return self.name_widget.text().strip()
@name.setter
def name(self, val):
self.name_widget.setText((val or '').strip())
@property
def url(self):
return self.url_widget.text().strip()
@url.setter
def url(self, val):
self.url_widget.setText((val or '').strip())
@property
def as_dict(self):
return {'name': self.name, 'url': self.url, 'type': self.url_type}
def validate(self):
if self.is_empty:
return True
if '{author}' not in self.url:
error_dialog(self.parent(), _('Missing author placeholder'), _(
'The URL {0} does not contain the {1} placeholder').format(self.url, '{author}'), show=True)
return False
if self.url_type == 'book' and '{title}' not in self.url:
error_dialog(self.parent(), _('Missing title placeholder'), _(
'The URL {0} does not contain the {1} placeholder').format(self.url, '{title}'), show=True)
return False
return True
class SearchTheInternet(QWidget):
changed_signal = pyqtSignal()
def __init__(self, parent):
QWidget.__init__(self, parent)
self.sa = QScrollArea(self)
self.lw = QWidget(self)
self.l = QVBoxLayout(self.lw)
self.sa.setWidget(self.lw), self.sa.setWidgetResizable(True)
self.gl = gl = QVBoxLayout(self)
self.la = QLabel(_(
'Add new locations to search for books or authors using the "Search the internet" feature'
' of the Content server. The URLs should contain {author} which will be'
' replaced by the author name and, for book URLs, {title} which will'
' be replaced by the book title.'))
self.la.setWordWrap(True)
gl.addWidget(self.la)
self.h = QHBoxLayout()
gl.addLayout(self.h)
self.add_url_button = b = QPushButton(QIcon.ic('plus.png'), _('&Add URL'))
b.clicked.connect(self.add_url)
self.h.addWidget(b)
self.export_button = b = QPushButton(_('Export URLs'))
b.clicked.connect(self.export_urls)
self.h.addWidget(b)
self.import_button = b = QPushButton(_('Import URLs'))
b.clicked.connect(self.import_urls)
self.h.addWidget(b)
self.clear_button = b = QPushButton(_('Clear'))
b.clicked.connect(self.clear)
self.h.addWidget(b)
self.h.addStretch(10)
gl.addWidget(self.sa, stretch=10)
self.items = []
def genesis(self):
self.current_urls = search_the_net_urls() or []
@property
def current_urls(self):
return [item.as_dict for item in self.items if not item.is_empty]
def append_item(self, item_as_dict):
self.items.append(URLItem(item_as_dict, self))
self.l.addWidget(self.items[-1])
def clear(self):
[(self.l.removeWidget(w), w.setParent(None), w.deleteLater()) for w in self.items]
self.items = []
self.changed_signal.emit()
@current_urls.setter
def current_urls(self, val):
self.clear()
for entry in val:
self.append_item(entry)
def add_url(self):
self.items.append(URLItem(None, self))
self.l.addWidget(self.items[-1])
QTimer.singleShot(100, self.scroll_to_bottom)
def scroll_to_bottom(self):
sb = self.sa.verticalScrollBar()
if sb:
sb.setValue(sb.maximum())
self.items[-1].name_widget.setFocus(Qt.FocusReason.OtherFocusReason)
@property
def serialized_urls(self):
return json.dumps(self.current_urls, indent=2)
def commit(self):
for item in self.items:
if not item.validate():
return False
cu = self.current_urls
if cu:
with open(search_the_net_urls.path, 'wb') as f:
f.write(self.serialized_urls.encode('utf-8'))
else:
try:
os.remove(search_the_net_urls.path)
except OSError as err:
if err.errno != errno.ENOENT:
raise
return True
def export_urls(self):
path = choose_save_file(
self, 'search-net-urls', _('Choose URLs file'),
filters=[(_('URL files'), ['json'])], initial_filename='search-urls.json')
if path:
with open(path, 'wb') as f:
f.write(self.serialized_urls.encode('utf-8'))
def import_urls(self):
paths = choose_files(self, 'search-net-urls', _('Choose URLs file'),
filters=[(_('URL files'), ['json'])], all_files=False, select_only_single_file=True)
if paths:
with open(paths[0], 'rb') as f:
items = json.loads(f.read())
[self.append_item(x) for x in items]
self.changed_signal.emit()
# }}}
class ConfigWidget(ConfigWidgetBase):
def __init__(self, *args, **kw):
ConfigWidgetBase.__init__(self, *args, **kw)
self.l = l = QVBoxLayout(self)
l.setContentsMargins(0, 0, 0, 0)
self.tabs_widget = t = QTabWidget(self)
l.addWidget(t)
self.main_tab = m = MainTab(self)
t.addTab(m, _('&Main'))
m.start_server.connect(self.start_server)
m.stop_server.connect(self.stop_server)
m.test_server.connect(self.test_server)
m.show_logs.connect(self.view_server_logs)
self.opt_autolaunch_server = m.opt_autolaunch_server
self.users_tab = ua = Users(self)
t.addTab(ua, _('&User accounts'))
self.advanced_tab = a = AdvancedTab(self)
sa = QScrollArea(self)
sa.setWidget(a), sa.setWidgetResizable(True)
t.addTab(sa, _('&Advanced'))
self.custom_list_tab = clt = CustomList(self)
sa = QScrollArea(self)
sa.setWidget(clt), sa.setWidgetResizable(True)
t.addTab(sa, _('Book &list template'))
self.search_net_tab = SearchTheInternet(self)
t.addTab(self.search_net_tab, _('&Search the internet'))
for tab in self.tabs:
if hasattr(tab, 'changed_signal'):
tab.changed_signal.connect(self.changed_signal.emit)
@property
def tabs(self):
def w(x):
if isinstance(x, QScrollArea):
x = x.widget()
return x
return (
w(self.tabs_widget.widget(i)) for i in range(self.tabs_widget.count())
)
@property
def server(self):
return self.gui.content_server
def restore_defaults(self):
ConfigWidgetBase.restore_defaults(self)
for tab in self.tabs:
if hasattr(tab, 'restore_defaults'):
tab.restore_defaults()
def genesis(self, gui):
self.gui = gui
for tab in self.tabs:
tab.genesis()
r = self.register
r('autolaunch_server', config)
def start_server(self):
if not self.save_changes():
return
self.setCursor(Qt.CursorShape.BusyCursor)
try:
self.gui.start_content_server(check_started=False)
while (not self.server.is_running and self.server.exception is None):
time.sleep(0.1)
if self.server.exception is not None:
error_dialog(
self,
_('Failed to start Content server'),
as_unicode(self.gui.content_server.exception)
).exec()
self.gui.content_server = None
return
self.main_tab.update_button_state()
finally:
self.unsetCursor()
def stop_server(self):
self.server.stop()
self.stopping_msg = info_dialog(
self,
_('Stopping'),
_('Stopping server, this could take up to a minute, please wait...'),
show_copy_button=False
)
QTimer.singleShot(500, self.check_exited)
self.stopping_msg.exec()
def check_exited(self):
if getattr(self.server, 'is_running', False):
QTimer.singleShot(20, self.check_exited)
return
self.gui.content_server = None
self.main_tab.update_button_state()
self.stopping_msg.accept()
def test_server(self):
from calibre.utils.network import format_addr_for_url, get_fallback_server_addr
prefix = self.advanced_tab.get('url_prefix') or ''
protocol = 'https' if self.advanced_tab.has_ssl else 'http'
addr = self.advanced_tab.get('listen_on') or get_fallback_server_addr()
addr = {'0.0.0.0': '127.0.0.1', '::': '::1'}.get(addr, addr)
url = f'{protocol}://{format_addr_for_url(addr)}:{self.main_tab.opt_port.value()}{prefix}'
open_url(QUrl(url))
def view_server_logs(self):
from calibre.srv.embedded import log_paths
log_error_file, log_access_file = log_paths()
d = QDialog(self)
d.resize(QSize(800, 600))
layout = QVBoxLayout()
d.setLayout(layout)
layout.addWidget(QLabel(_('Error log:')))
el = QPlainTextEdit(d)
layout.addWidget(el)
try:
el.setPlainText(
share_open(log_error_file, 'rb').read().decode('utf8', 'replace')
)
except OSError:
el.setPlainText(_('No error log found'))
layout.addWidget(QLabel(_('Access log:')))
al = QPlainTextEdit(d)
layout.addWidget(al)
try:
al.setPlainText(
share_open(log_access_file, 'rb').read().decode('utf8', 'replace')
)
except OSError:
al.setPlainText(_('No access log found'))
loc = QLabel(_('The server log files are in: {}').format(os.path.dirname(log_error_file)))
loc.setWordWrap(True)
layout.addWidget(loc)
bx = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok)
layout.addWidget(bx)
bx.accepted.connect(d.accept)
b = bx.addButton(_('&Clear logs'), QDialogButtonBox.ButtonRole.ActionRole)
def clear_logs():
if getattr(self.server, 'is_running', False):
return error_dialog(d, _('Server running'), _(
'Cannot clear logs while the server is running. First stop the server.'), show=True)
if self.server:
self.server.access_log.clear()
self.server.log.clear()
else:
for x in (log_error_file, log_access_file):
try:
os.remove(x)
except OSError as err:
if err.errno != errno.ENOENT:
raise
el.setPlainText(''), al.setPlainText('')
b.clicked.connect(clear_logs)
d.show()
def save_changes(self):
settings = {}
for tab in self.tabs:
settings.update(getattr(tab, 'settings', {}))
users = self.users_tab.user_data
if settings['auth']:
if not users:
error_dialog(
self,
_('No users specified'),
_(
'You have turned on the setting to require passwords to access'
' the Content server, but you have not created any user accounts.'
' Create at least one user account in the "User accounts" tab to proceed.'
),
show=True
)
self.tabs_widget.setCurrentWidget(self.users_tab)
return False
if settings['trusted_ips']:
try:
tuple(parse_trusted_ips(settings['trusted_ips']))
except Exception as e:
error_dialog(
self, _('Invalid trusted IPs'), str(e), show=True)
return False
if not self.custom_list_tab.commit():
return False
if not self.search_net_tab.commit():
return False
ConfigWidgetBase.commit(self)
change_settings(**settings)
UserManager().user_data = users
return True
def commit(self):
if not self.save_changes():
raise AbortCommit()
warning_dialog(
self,
_('Restart needed'),
_('You need to restart the server for changes to'
' take effect'),
show=True
)
return False
def refresh_gui(self, gui):
if self.server:
self.server.user_manager.refresh()
self.server.ctx.custom_list_template = custom_list_template()
self.server.ctx.search_the_net_urls = search_the_net_urls()
if __name__ == '__main__':
from calibre.gui2 import Application
app = Application([])
test_widget('Sharing', 'Server')
| 51,090 | Python | .py | 1,231 | 31.51909 | 128 | 0.597676 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,810 | tweaks.py | kovidgoyal_calibre/src/calibre/gui2/preferences/tweaks.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2010, Kovid Goyal <kovid at kovidgoyal.net>
import textwrap
from collections import OrderedDict
from functools import partial
from operator import attrgetter
from qt.core import (
QAbstractItemView,
QAbstractListModel,
QApplication,
QComboBox,
QDialog,
QDialogButtonBox,
QFont,
QGridLayout,
QGroupBox,
QIcon,
QItemSelectionModel,
QLabel,
QListView,
QMenu,
QModelIndex,
QPlainTextEdit,
QPushButton,
QSizePolicy,
QSplitter,
Qt,
QVBoxLayout,
QWidget,
pyqtSignal,
)
from calibre import isbytestring, prepare_string_for_xml
from calibre.gui2 import error_dialog, info_dialog
from calibre.gui2.preferences import AbortCommit, ConfigWidgetBase, test_widget
from calibre.gui2.search_box import SearchBox2
from calibre.gui2.widgets import PythonHighlighter
from calibre.utils.config_base import default_tweaks_raw, exec_tweaks, normalize_tweak, read_custom_tweaks, write_custom_tweaks
from calibre.utils.icu import lower
from calibre.utils.search_query_parser import ParseException, SearchQueryParser
from polyglot.builtins import iteritems
ROOT = QModelIndex()
def format_doc(doc):
current_indent = default_indent = None
lines = ['']
for line in doc.splitlines():
if not line.strip():
lines.append('')
continue
line = line[1:]
indent = len(line) - len(line.lstrip())
if indent != current_indent:
lines.append('')
if default_indent is None:
default_indent = indent
current_indent = indent
if indent == default_indent:
if lines and lines[-1]:
lines[-1] += ' ' + line
else:
lines.append(line)
else:
lines.append(' ' + line.strip())
return '\n'.join(lines).lstrip()
class AdaptSQP(SearchQueryParser):
def __init__(self, *args, **kwargs):
pass
class Tweak: # {{{
def __init__(self, name, doc, var_names, defaults, custom):
translate = _
self.name = translate(name)
self.doc = doc.strip()
self.doc = ' ' + self.doc
self.var_names = var_names
if self.var_names:
self.doc = "%s: %s\n\n%s"%(_('ID'), self.var_names[0], format_doc(self.doc))
self.default_values = OrderedDict()
for x in var_names:
self.default_values[x] = defaults[x]
self.custom_values = OrderedDict()
for x in var_names:
if x in custom:
self.custom_values[x] = custom[x]
def __str__(self):
ans = ['#: ' + self.name]
for line in self.doc.splitlines():
if line:
ans.append('# ' + line)
for key, val in iteritems(self.default_values):
val = self.custom_values.get(key, val)
ans.append('%s = %r'%(key, val))
ans = '\n'.join(ans)
return ans
@property
def sort_key(self):
return 0 if self.is_customized else 1
@property
def is_customized(self):
for x, val in iteritems(self.default_values):
cval = self.custom_values.get(x, val)
if normalize_tweak(cval) != normalize_tweak(val):
return True
return False
@property
def edit_text(self):
from pprint import pformat
ans = ['# %s'%self.name]
for x, val in iteritems(self.default_values):
val = self.custom_values.get(x, val)
if isinstance(val, (list, tuple, dict, set, frozenset)):
ans.append(f'{x} = {pformat(val)}')
else:
ans.append('%s = %r'%(x, val))
return '\n\n'.join(ans)
def restore_to_default(self):
self.custom_values.clear()
def update(self, varmap):
self.custom_values.update(varmap)
# }}}
class Tweaks(QAbstractListModel, AdaptSQP): # {{{
def __init__(self, parent=None):
QAbstractListModel.__init__(self, parent)
SearchQueryParser.__init__(self, ['all'])
self.parse_tweaks()
def rowCount(self, *args):
return len(self.tweaks)
def data(self, index, role):
row = index.row()
try:
tweak = self.tweaks[row]
except:
return None
if role == Qt.ItemDataRole.DisplayRole:
return tweak.name
if role == Qt.ItemDataRole.FontRole and tweak.is_customized:
ans = QFont()
ans.setBold(True)
return ans
if role == Qt.ItemDataRole.ToolTipRole:
tt = _('This tweak has its default value')
if tweak.is_customized:
tt = '<p>'+_('This tweak has been customized')
tt += '<pre>'
for varn, val in iteritems(tweak.custom_values):
tt += '%s = %r\n\n'%(varn, val)
return textwrap.fill(tt)
if role == Qt.ItemDataRole.UserRole:
return tweak
return None
def parse_tweaks(self):
try:
custom_tweaks = read_custom_tweaks()
except:
print('Failed to load custom tweaks file')
import traceback
traceback.print_exc()
custom_tweaks = {}
default_tweaks = exec_tweaks(default_tweaks_raw())
defaults = default_tweaks_raw().decode('utf-8')
lines = defaults.splitlines()
pos = 0
self.tweaks = []
while pos < len(lines):
line = lines[pos]
if line.startswith('#:'):
pos = self.read_tweak(lines, pos, default_tweaks, custom_tweaks)
pos += 1
self.tweaks.sort(key=attrgetter('sort_key'))
default_keys = set(default_tweaks)
custom_keys = set(custom_tweaks)
self.plugin_tweaks = {}
for key in custom_keys - default_keys:
self.plugin_tweaks[key] = custom_tweaks[key]
def read_tweak(self, lines, pos, defaults, custom):
name = lines[pos][2:].strip()
doc, stripped_doc, leading, var_names = [], [], [], []
while True:
pos += 1
line = lines[pos]
if not line.startswith('#'):
break
line = line[1:]
doc.append(line.rstrip())
stripped_doc.append(line.strip())
leading.append(line[:len(line) - len(line.lstrip())])
translate = _
stripped_doc = translate('\n'.join(stripped_doc).strip())
final_doc = []
for prefix, line in zip(leading, stripped_doc.splitlines()):
final_doc.append(prefix + line)
doc = '\n'.join(final_doc)
while True:
try:
line = lines[pos]
except IndexError:
break
if not line.strip():
break
spidx1 = line.find(' ')
spidx2 = line.find('=')
spidx = spidx1 if spidx1 > 0 and (spidx2 == 0 or spidx2 > spidx1) else spidx2
if spidx > 0:
var = line[:spidx]
if var not in defaults:
raise ValueError('%r not in default tweaks dict'%var)
var_names.append(var)
pos += 1
if not var_names:
raise ValueError('Failed to find any variables for %r'%name)
self.tweaks.append(Tweak(name, doc, var_names, defaults, custom))
return pos
def restore_to_default(self, idx):
tweak = self.data(idx, Qt.ItemDataRole.UserRole)
if tweak is not None:
tweak.restore_to_default()
self.dataChanged.emit(idx, idx)
def restore_to_defaults(self):
for r in range(self.rowCount()):
self.restore_to_default(self.index(r))
self.plugin_tweaks = {}
def update_tweak(self, idx, varmap):
tweak = self.data(idx, Qt.ItemDataRole.UserRole)
if tweak is not None:
tweak.update(varmap)
self.dataChanged.emit(idx, idx)
def to_string(self):
ans = ['#!/usr/bin/env python',
'# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai', '',
'# This file was automatically generated by calibre, do not'
' edit it unless you know what you are doing.', '',
]
for tweak in self.tweaks:
ans.extend(['', str(tweak), ''])
if self.plugin_tweaks:
ans.extend(['', '',
'# The following are tweaks for installed plugins', ''])
for key, val in iteritems(self.plugin_tweaks):
ans.extend(['%s = %r'%(key, val), '', ''])
return '\n'.join(ans)
@property
def plugin_tweaks_string(self):
ans = []
for key, val in iteritems(self.plugin_tweaks):
ans.extend(['%s = %r'%(key, val), '', ''])
ans = '\n'.join(ans)
if isbytestring(ans):
ans = ans.decode('utf-8')
return ans
def set_plugin_tweaks(self, d):
self.plugin_tweaks = d
def universal_set(self):
return set(range(self.rowCount()))
def get_matches(self, location, query, candidates=None):
if candidates is None:
candidates = self.universal_set()
ans = set()
if not query:
return ans
query = lower(query)
for r in candidates:
dat = self.data(self.index(r), Qt.ItemDataRole.UserRole)
var_names = ' '.join(dat.default_values)
if query in lower(dat.name) or query in lower(var_names):
ans.add(r)
return ans
def find(self, query):
query = query.strip()
if not query:
return ROOT
matches = self.parse(query)
if not matches:
return ROOT
matches = list(sorted(matches))
return self.index(matches[0])
def find_next(self, idx, query, backwards=False):
query = query.strip()
if not query:
return idx
matches = self.parse(query)
if not matches:
return idx
loc = idx.row()
if loc not in matches:
return self.find(query)
if len(matches) == 1:
return ROOT
matches = list(sorted(matches))
i = matches.index(loc)
if backwards:
ans = i - 1 if i - 1 >= 0 else len(matches)-1
else:
ans = i + 1 if i + 1 < len(matches) else 0
ans = matches[ans]
return self.index(ans)
# }}}
class PluginTweaks(QDialog): # {{{
def __init__(self, raw, parent=None):
QDialog.__init__(self, parent)
self.setWindowTitle(_('Plugin tweaks'))
self.edit = QPlainTextEdit(self)
self.highlighter = PythonHighlighter(self.edit.document())
self.l = QVBoxLayout()
self.setLayout(self.l)
self.msg = QLabel(
_('Add/edit tweaks for any custom plugins you have installed. '
'Documentation for these tweaks should be available '
'on the website from where you downloaded the plugins.'))
self.msg.setWordWrap(True)
self.l.addWidget(self.msg)
self.l.addWidget(self.edit)
self.edit.setPlainText(raw)
self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel,
Qt.Orientation.Horizontal, self)
self.bb.accepted.connect(self.accept)
self.bb.rejected.connect(self.reject)
self.l.addWidget(self.bb)
self.resize(550, 300)
# }}}
class TweaksView(QListView):
current_changed = pyqtSignal(object, object)
def __init__(self, parent=None):
QListView.__init__(self, parent)
self.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Expanding)
self.setAlternatingRowColors(True)
self.setVerticalScrollMode(QAbstractItemView.ScrollMode.ScrollPerPixel)
self.setMinimumWidth(300)
self.setStyleSheet('QListView::item { padding-top: 0.75ex; padding-bottom: 0.75ex; }')
self.setWordWrap(True)
def currentChanged(self, cur, prev):
QListView.currentChanged(self, cur, prev)
self.current_changed.emit(cur, prev)
class ConfigWidget(ConfigWidgetBase):
def setupUi(self, x):
self.l = l = QVBoxLayout(self)
self.la1 = la = QLabel(
_("Values for the tweaks are shown below. Edit them to change the behavior of calibre."
" Your changes will only take effect <b>after a restart</b> of calibre."))
l.addWidget(la), la.setWordWrap(True)
self.splitter = s = QSplitter(self)
s.setChildrenCollapsible(False)
l.addWidget(s, 10)
self.lv = lv = QWidget(self)
lv.l = l2 = QVBoxLayout(lv)
l2.setContentsMargins(0, 0, 0, 0)
self.tweaks_view = tv = TweaksView(self)
l2.addWidget(tv)
self.plugin_tweaks_button = b = QPushButton(self)
b.setToolTip(_("Edit tweaks for any custom plugins you have installed"))
b.setText(_("&Plugin tweaks"))
l2.addWidget(b)
s.addWidget(lv)
self.lv1 = lv = QWidget(self)
s.addWidget(lv)
lv.g = g = QGridLayout(lv)
g.setContentsMargins(0, 0, 0, 0)
self.search = sb = SearchBox2(self)
sb.sizePolicy().setHorizontalStretch(10)
sb.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
sb.setMinimumContentsLength(10)
g.setColumnStretch(0, 100)
g.addWidget(self.search, 0, 0, 1, 1)
self.next_button = b = QPushButton(self)
b.setIcon(QIcon.ic("arrow-down.png"))
b.setText(_("&Next"))
g.addWidget(self.next_button, 0, 1, 1, 1)
self.previous_button = b = QPushButton(self)
b.setIcon(QIcon.ic("arrow-up.png"))
b.setText(_("&Previous"))
g.addWidget(self.previous_button, 0, 2, 1, 1)
self.hb = hb = QGroupBox(self)
hb.setTitle(_("Help"))
hb.l = l2 = QVBoxLayout(hb)
self.help = h = QPlainTextEdit(self)
l2.addWidget(h)
h.setReadOnly(True)
g.addWidget(hb, 1, 0, 1, 3)
self.eb = eb = QGroupBox(self)
g.addWidget(eb, 2, 0, 1, 3)
eb.setTitle(_("Edit tweak"))
eb.g = ebg = QGridLayout(eb)
self.edit_tweak = et = QPlainTextEdit(self)
et.setMinimumWidth(400)
et.setLineWrapMode(QPlainTextEdit.LineWrapMode.NoWrap)
ebg.addWidget(et, 0, 0, 1, 2)
self.restore_default_button = b = QPushButton(self)
b.setToolTip(_("Restore this tweak to its default value"))
b.setText(_("&Reset this tweak"))
ebg.addWidget(b, 1, 0, 1, 1)
self.apply_button = ab = QPushButton(self)
ab.setToolTip(_("Apply any changes you made to this tweak"))
ab.setText(_("&Apply changes to this tweak"))
ebg.addWidget(ab, 1, 1, 1, 1)
def genesis(self, gui):
self.gui = gui
self.tweaks_view.current_changed.connect(self.current_changed)
self.view = self.tweaks_view
self.highlighter = PythonHighlighter(self.edit_tweak.document())
self.restore_default_button.clicked.connect(self.restore_to_default)
self.apply_button.clicked.connect(self.apply_tweak)
self.plugin_tweaks_button.clicked.connect(self.plugin_tweaks)
self.splitter.setStretchFactor(0, 1)
self.splitter.setStretchFactor(1, 100)
self.next_button.clicked.connect(self.find_next)
self.previous_button.clicked.connect(self.find_previous)
self.search.initialize('tweaks_search_history', help_text=_('Search for tweak'))
self.search.search.connect(self.find)
self.view.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.view.customContextMenuRequested.connect(self.show_context_menu)
self.copy_icon = QIcon.ic('edit-copy.png')
def show_context_menu(self, point):
idx = self.tweaks_view.currentIndex()
if not idx.isValid():
return True
tweak = self.tweaks.data(idx, Qt.ItemDataRole.UserRole)
self.context_menu = QMenu(self)
self.context_menu.addAction(self.copy_icon,
_('Copy to clipboard'),
partial(self.copy_item_to_clipboard,
val="%s (%s: %s)"%(tweak.name,
_('ID'),
tweak.var_names[0])))
self.context_menu.popup(self.mapToGlobal(point))
return True
def copy_item_to_clipboard(self, val):
cb = QApplication.clipboard()
cb.clear()
cb.setText(val)
def plugin_tweaks(self):
raw = self.tweaks.plugin_tweaks_string
d = PluginTweaks(raw, self)
if d.exec() == QDialog.DialogCode.Accepted:
g, l = {}, {}
try:
exec(str(d.edit.toPlainText()), g, l)
except:
import traceback
return error_dialog(self, _('Failed'),
_('There was a syntax error in your tweak. Click '
'the "Show details" button for details.'), show=True,
det_msg=traceback.format_exc())
self.tweaks.set_plugin_tweaks(l)
self.changed()
def current_changed(self, *a):
current = self.tweaks_view.currentIndex()
if current.isValid():
self.tweaks_view.scrollTo(current)
tweak = self.tweaks.data(current, Qt.ItemDataRole.UserRole)
self.help.setPlainText(tweak.doc)
self.edit_tweak.setPlainText(tweak.edit_text)
def changed(self, *args):
self.changed_signal.emit()
def initialize(self):
self.tweaks = self._model = Tweaks()
self.tweaks_view.setModel(self.tweaks)
self.tweaks_view.setCurrentIndex(self.tweaks_view.model().index(0))
def restore_to_default(self, *args):
idx = self.tweaks_view.currentIndex()
if idx.isValid():
self.tweaks.restore_to_default(idx)
tweak = self.tweaks.data(idx, Qt.ItemDataRole.UserRole)
self.edit_tweak.setPlainText(tweak.edit_text)
self.changed()
def restore_defaults(self):
ConfigWidgetBase.restore_defaults(self)
self.tweaks.restore_to_defaults()
self.changed()
def apply_tweak(self):
idx = self.tweaks_view.currentIndex()
if idx.isValid():
l, g = {}, {}
try:
exec(str(self.edit_tweak.toPlainText()), g, l)
except:
import traceback
error_dialog(self.gui, _('Failed'),
_('There was a syntax error in your tweak. Click '
'the "Show details" button for details.'),
det_msg=traceback.format_exc(), show=True)
return
self.tweaks.update_tweak(idx, l)
self.changed()
def commit(self):
raw = self.tweaks.to_string()
if not isinstance(raw, bytes):
raw = raw.encode('utf-8')
try:
custom_tweaks = exec_tweaks(raw)
except:
import traceback
error_dialog(self, _('Invalid tweaks'),
_('The tweaks you entered are invalid, try resetting the'
' tweaks to default and changing them one by one until'
' you find the invalid setting.'),
det_msg=traceback.format_exc(), show=True)
raise AbortCommit('abort')
write_custom_tweaks(custom_tweaks)
ConfigWidgetBase.commit(self)
return True
def find(self, query):
if not query:
return
try:
idx = self._model.find(query)
except ParseException:
self.search.search_done(False)
return
self.search.search_done(True)
if not idx.isValid():
info_dialog(self, _('No matches'),
_('Could not find any tweaks matching <i>{}</i>').format(prepare_string_for_xml(query)),
show=True, show_copy_button=False)
return
self.highlight_index(idx)
def highlight_index(self, idx):
if not idx.isValid():
return
self.view.scrollTo(idx)
self.view.selectionModel().select(idx, QItemSelectionModel.SelectionFlag.ClearAndSelect)
self.view.setCurrentIndex(idx)
def find_next(self, *args):
idx = self.view.currentIndex()
if not idx.isValid():
idx = self._model.index(0)
idx = self._model.find_next(idx,
str(self.search.currentText()))
self.highlight_index(idx)
def find_previous(self, *args):
idx = self.view.currentIndex()
if not idx.isValid():
idx = self._model.index(0)
idx = self._model.find_next(idx,
str(self.search.currentText()), backwards=True)
self.highlight_index(idx)
if __name__ == '__main__':
from calibre.gui2 import Application
app = Application([])
# Tweaks()
# test_widget
test_widget('Advanced', 'Tweaks')
| 21,338 | Python | .py | 538 | 29.496283 | 127 | 0.582803 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,811 | pdf_covers.py | kovidgoyal_calibre/src/calibre/gui2/metadata/pdf_covers.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os
import shutil
import sys
from threading import Thread
from qt.core import (
QAbstractItemView,
QApplication,
QDialog,
QDialogButtonBox,
QLabel,
QListView,
QListWidget,
QListWidgetItem,
QPixmap,
QSize,
QStyledItemDelegate,
Qt,
QTimer,
QVBoxLayout,
pyqtSignal,
sip,
)
from calibre import as_unicode
from calibre.ebooks.metadata.archive import get_comic_images
from calibre.ebooks.metadata.pdf import page_images
from calibre.gui2 import error_dialog, file_icon_provider
from calibre.gui2.progress_indicator import WaitLayout
from calibre.libunzip import comic_exts
from calibre.ptempfile import PersistentTemporaryDirectory
class CoverDelegate(QStyledItemDelegate):
def paint(self, painter, option, index):
QStyledItemDelegate.paint(self, painter, option, index)
style = QApplication.style()
# Ensure the cover is rendered over any selection rect
style.drawItemPixmap(painter, option.rect, Qt.AlignmentFlag.AlignTop|Qt.AlignmentFlag.AlignHCenter,
QPixmap(index.data(Qt.ItemDataRole.DecorationRole)))
PAGES_PER_RENDER = 10
class PDFCovers(QDialog):
'Choose a cover from the first few pages of a PDF'
rendering_done = pyqtSignal()
def __init__(self, pdfpath, parent=None):
QDialog.__init__(self, parent)
self.pdfpath = pdfpath
self.ext = os.path.splitext(pdfpath)[1][1:].lower()
self.is_pdf = self.ext == 'pdf'
self.stack = WaitLayout(_('Rendering {} pages, please wait...').format('PDF' if self.is_pdf else _('comic book')), parent=self)
self.container = self.stack.after
self.container.l = l = QVBoxLayout(self.container)
self.la = la = QLabel(_('Choose a cover from the list of pages below'))
l.addWidget(la)
self.covers = c = QListWidget(self)
l.addWidget(c)
self.item_delegate = CoverDelegate(self)
c.setItemDelegate(self.item_delegate)
c.setIconSize(QSize(120, 160))
c.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
c.setViewMode(QListView.ViewMode.IconMode)
c.setUniformItemSizes(True)
c.setResizeMode(QListView.ResizeMode.Adjust)
c.itemDoubleClicked.connect(self.accept, type=Qt.ConnectionType.QueuedConnection)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel)
bb.accepted.connect(self.accept)
bb.rejected.connect(self.reject)
self.more_pages = b = bb.addButton(_('&More pages'), QDialogButtonBox.ButtonRole.ActionRole)
b.clicked.connect(self.start_rendering)
l.addWidget(bb)
self.rendering_done.connect(self.show_pages, type=Qt.ConnectionType.QueuedConnection)
self.first = 1
self.setWindowTitle(_('Choose cover from book'))
self.setWindowIcon(file_icon_provider().icon_from_ext(self.ext))
self.resize(QSize(800, 600))
self.tdir = PersistentTemporaryDirectory('_pdf_covers')
QTimer.singleShot(0, self.start_rendering)
def start_rendering(self):
self.hide_pages()
self.thread = Thread(target=self.render, daemon=True, name='RenderPages')
self.thread.start()
@property
def cover_path(self):
for item in self.covers.selectedItems():
return str(item.data(Qt.ItemDataRole.UserRole) or '')
if self.covers.count() > 0:
return str(self.covers.item(0).data(Qt.ItemDataRole.UserRole) or '')
def cleanup(self):
try:
shutil.rmtree(self.tdir)
except OSError:
pass
def render(self):
self.current_tdir = os.path.join(self.tdir, str(self.first))
self.error = None
try:
os.mkdir(self.current_tdir)
if self.is_pdf:
page_images(self.pdfpath, self.current_tdir, first=self.first, last=self.first + PAGES_PER_RENDER - 1)
else:
get_comic_images(self.pdfpath, self.current_tdir, first=self.first, last=self.first + PAGES_PER_RENDER - 1)
except Exception as e:
import traceback
traceback.print_exc()
if not self.covers.count():
self.error = as_unicode(e)
if not sip.isdeleted(self) and self.isVisible():
self.rendering_done.emit()
def hide_pages(self):
self.stack.start()
self.more_pages.setVisible(False)
def show_pages(self):
if self.error is not None:
error_dialog(self, _('Failed to render'),
_('Could not render this file'), show=True, det_msg=self.error)
self.reject()
return
self.stack.stop()
files = tuple(x for x in os.listdir(self.current_tdir) if os.path.splitext(x)[1][1:].lower() in comic_exts)
if not files and not self.covers.count():
error_dialog(self, _('Failed to render'),
_('This book has no pages'), show=True)
self.reject()
return
try:
dpr = self.devicePixelRatioF()
except AttributeError:
dpr = self.devicePixelRatio()
for i, f in enumerate(sorted(files)):
path = os.path.join(self.current_tdir, f)
p = QPixmap(path).scaled(
self.covers.iconSize()*dpr, aspectRatioMode=Qt.AspectRatioMode.IgnoreAspectRatio,
transformMode=Qt.TransformationMode.SmoothTransformation)
p.setDevicePixelRatio(dpr)
i = QListWidgetItem(_('page %d') % (self.first + i))
i.setData(Qt.ItemDataRole.DecorationRole, p)
i.setData(Qt.ItemDataRole.UserRole, path)
self.covers.addItem(i)
self.first += len(files)
if len(files) == PAGES_PER_RENDER:
self.more_pages.setVisible(True)
if __name__ == '__main__':
from calibre.gui2 import Application
app = Application([])
d = PDFCovers(sys.argv[-1])
d.exec()
print(d.cover_path)
del app
| 6,215 | Python | .py | 148 | 33.709459 | 135 | 0.655521 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,812 | bulk_download.py | kovidgoyal_calibre/src/calibre/gui2/metadata/bulk_download.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os
import shutil
import time
from threading import Thread
from qt.core import QDialog, QDialogButtonBox, QGridLayout, QIcon, QLabel, Qt
from calibre.ebooks.metadata.opf2 import metadata_to_opf
from calibre.gui2.threaded_jobs import ThreadedJob
from calibre.ptempfile import PersistentTemporaryDirectory, PersistentTemporaryFile
from calibre.startup import connect_lambda
from calibre.utils.ipc.simple_worker import WorkerError, fork_job
from calibre.utils.localization import ngettext
from polyglot.builtins import iteritems
# Start download {{{
class Job(ThreadedJob):
ignore_html_details = True
def consolidate_log(self):
self.consolidated_log = self.log.plain_text
self.log = None
def read_consolidated_log(self):
return self.consolidated_log
@property
def details(self):
if self.consolidated_log is None:
return self.log.plain_text
return self.read_consolidated_log()
@property
def log_file(self):
return open(self.download_debug_log, 'rb')
def show_config(parent):
from calibre.gui2.preferences import show_config_widget
from calibre.gui2.ui import get_gui
show_config_widget('Sharing', 'Metadata download', parent=parent,
gui=get_gui(), never_shutdown=True)
class ConfirmDialog(QDialog):
def __init__(self, ids, parent):
QDialog.__init__(self, parent)
self.setWindowTitle(_('Schedule download?'))
self.setWindowIcon(QIcon.ic('download-metadata.png'))
l = self.l = QGridLayout()
self.setLayout(l)
i = QLabel(self)
i.setPixmap(QIcon.ic('download-metadata.png').pixmap(128, 128))
l.addWidget(i, 0, 0)
t = ngettext(
'The download of metadata for the <b>selected book</b> will run in the background. Proceed?',
'The download of metadata for the <b>{} selected books</b> will run in the background. Proceed?',
len(ids)).format(len(ids))
t = QLabel(
'<p>'+ t +
'<p>'+_('You can monitor the progress of the download '
'by clicking the rotating spinner in the bottom right '
'corner.') +
'<p>'+_('When the download completes you will be asked for'
' confirmation before calibre applies the downloaded metadata.')
)
t.setWordWrap(True)
l.addWidget(t, 0, 1)
l.setColumnStretch(0, 1)
l.setColumnStretch(1, 100)
self.identify = self.covers = True
self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel)
self.bb.rejected.connect(self.reject)
b = self.bb.addButton(_('Download only &metadata'),
QDialogButtonBox.ButtonRole.AcceptRole)
b.clicked.connect(self.only_metadata)
b.setIcon(QIcon.ic('edit_input.png'))
b = self.bb.addButton(_('Download only &covers'),
QDialogButtonBox.ButtonRole.AcceptRole)
b.clicked.connect(self.only_covers)
b.setIcon(QIcon.ic('default_cover.png'))
b = self.b = self.bb.addButton(_('&Configure download'), QDialogButtonBox.ButtonRole.ActionRole)
b.setIcon(QIcon.ic('config.png'))
connect_lambda(b.clicked, self, lambda self: show_config(self))
l.addWidget(self.bb, 1, 0, 1, 2)
b = self.bb.addButton(_('Download &both'),
QDialogButtonBox.ButtonRole.AcceptRole)
b.clicked.connect(self.accept)
b.setDefault(True)
b.setAutoDefault(True)
b.setIcon(QIcon.ic('ok.png'))
self.resize(self.sizeHint())
b.setFocus(Qt.FocusReason.OtherFocusReason)
def only_metadata(self):
self.covers = False
self.accept()
def only_covers(self):
self.identify = False
self.accept()
def split_jobs(ids, batch_size=100):
ans = []
ids = list(ids)
while ids:
jids = ids[:batch_size]
ans.append(jids)
ids = ids[batch_size:]
return ans
def start_download(gui, ids, callback, ensure_fields=None):
d = ConfirmDialog(ids, gui)
ret = d.exec()
d.b.clicked.disconnect()
if ret != QDialog.DialogCode.Accepted:
return
tf = PersistentTemporaryFile('_metadata_bulk.log')
tf.close()
job = Job('metadata bulk download',
ngettext(
'Download metadata for one book',
'Download metadata for {} books', len(ids)).format(len(ids)),
download, (ids, tf.name, gui.current_db, d.identify, d.covers,
ensure_fields), {}, callback)
job.metadata_and_covers = (d.identify, d.covers)
job.download_debug_log = tf.name
gui.job_manager.run_threaded_job(job)
gui.status_bar.show_message(_('Metadata download started'), 3000)
# }}}
def get_job_details(job):
(aborted, good_ids, tdir, log_file, failed_ids, failed_covers, title_map,
lm_map, all_failed) = job.result
det_msg = []
for i in failed_ids | failed_covers:
title = title_map[i]
if i in failed_ids:
title += (' ' + _('(Failed metadata)'))
if i in failed_covers:
title += (' ' + _('(Failed cover)'))
det_msg.append(title)
det_msg = '\n'.join(det_msg)
return (aborted, good_ids, tdir, log_file, failed_ids, failed_covers,
all_failed, det_msg, lm_map)
class HeartBeat:
CHECK_INTERVAL = 300 # seconds
''' Check that the file count in tdir changes every five minutes '''
def __init__(self, tdir):
self.tdir = tdir
self.last_count = len(os.listdir(self.tdir))
self.last_time = time.time()
def __call__(self):
if time.time() - self.last_time > self.CHECK_INTERVAL:
c = len(os.listdir(self.tdir))
if c == self.last_count:
return False
self.last_count = c
self.last_time = time.time()
return True
class Notifier(Thread):
def __init__(self, notifications, title_map, tdir, total):
Thread.__init__(self)
self.daemon = True
self.notifications, self.title_map = notifications, title_map
self.tdir, self.total = tdir, total
self.seen = set()
self.keep_going = True
def run(self):
while self.keep_going:
try:
names = os.listdir(self.tdir)
except:
pass
else:
for x in names:
if x.endswith('.log'):
try:
book_id = int(x.partition('.')[0])
except:
continue
if book_id not in self.seen and book_id in self.title_map:
self.seen.add(book_id)
self.notifications.put((
float(len(self.seen))/self.total,
_('Processed %s')%self.title_map[book_id]))
time.sleep(1)
def download(all_ids, tf, db, do_identify, covers, ensure_fields,
log=None, abort=None, notifications=None):
batch_size = 10
batches = split_jobs(all_ids, batch_size=batch_size)
tdir = PersistentTemporaryDirectory('_metadata_bulk')
heartbeat = HeartBeat(tdir)
failed_ids = set()
failed_covers = set()
title_map = {}
lm_map = {}
ans = set()
all_failed = True
aborted = False
count = 0
notifier = Notifier(notifications, title_map, tdir, len(all_ids))
notifier.start()
try:
for ids in batches:
if abort.is_set():
log.error('Aborting...')
break
metadata = {i:db.get_metadata(i, index_is_id=True,
get_user_categories=False) for i in ids}
for i in ids:
title_map[i] = metadata[i].title
lm_map[i] = metadata[i].last_modified
metadata = {i:metadata_to_opf(mi, default_lang='und') for i, mi in
iteritems(metadata)}
try:
ret = fork_job('calibre.ebooks.metadata.sources.worker', 'main',
(do_identify, covers, metadata, ensure_fields, tdir),
abort=abort, heartbeat=heartbeat, no_output=True)
except WorkerError as e:
if e.orig_tb:
raise Exception('Failed to download metadata. Original '
'traceback: \n\n'+e.orig_tb)
raise
count += batch_size
fids, fcovs, allf = ret['result']
if not allf:
all_failed = False
failed_ids = failed_ids.union(fids)
failed_covers = failed_covers.union(fcovs)
ans = ans.union(set(ids) - fids)
for book_id in ids:
lp = os.path.join(tdir, '%d.log'%book_id)
if os.path.exists(lp):
with open(tf, 'ab') as dest, open(lp, 'rb') as src:
dest.write(('\n'+'#'*20 + ' Log for %s '%title_map[book_id] +
'#'*20+'\n').encode('utf-8'))
shutil.copyfileobj(src, dest)
if abort.is_set():
aborted = True
log('Download complete, with %d failures'%len(failed_ids))
return (aborted, ans, tdir, tf, failed_ids, failed_covers, title_map,
lm_map, all_failed)
finally:
notifier.keep_going = False
| 9,631 | Python | .py | 233 | 31.188841 | 109 | 0.587852 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,813 | config.py | kovidgoyal_calibre/src/calibre/gui2/metadata/config.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import numbers
import textwrap
from qt.core import QCheckBox, QComboBox, QDoubleSpinBox, QGridLayout, QGroupBox, QLabel, QLineEdit, QListView, QSpinBox, Qt, QVBoxLayout, QWidget
from calibre.gui2.preferences.metadata_sources import FieldsModel as FM
from calibre.utils.icu import sort_key
from polyglot.builtins import iteritems
class FieldsModel(FM): # {{{
def __init__(self, plugin):
FM.__init__(self)
self.plugin = plugin
self.exclude = frozenset(['title', 'authors']) | self.exclude
self.prefs = self.plugin.prefs
def initialize(self):
fields = self.plugin.touched_fields
self.beginResetModel()
self.fields = []
for x in fields:
if not x.startswith('identifier:') and x not in self.exclude:
self.fields.append(x)
self.fields.sort(key=lambda x:self.descs.get(x, x))
self.endResetModel()
def state(self, field, defaults=False):
src = self.prefs.defaults if defaults else self.prefs
return (Qt.CheckState.Unchecked if field in src['ignore_fields']
else Qt.CheckState.Checked)
def restore_defaults(self):
self.beginResetModel()
self.overrides = {f: self.state(f, True) for f in self.fields}
self.endResetModel()
def commit(self):
ignored_fields = {x for x in self.prefs['ignore_fields'] if x not in
self.overrides}
changed = {k for k, v in iteritems(self.overrides) if v ==
Qt.CheckState.Unchecked}
self.prefs['ignore_fields'] = list(ignored_fields.union(changed))
# }}}
class FieldsList(QListView):
def sizeHint(self):
return self.minimumSizeHint()
class ConfigWidget(QWidget):
def __init__(self, plugin):
QWidget.__init__(self)
self.plugin = plugin
self.overl = l = QVBoxLayout(self)
self.gb = QGroupBox(_('Metadata fields to download'), self)
if plugin.config_help_message:
self.pchm = QLabel(plugin.config_help_message)
self.pchm.setWordWrap(True)
self.pchm.setOpenExternalLinks(True)
l.addWidget(self.pchm, 10)
l.addWidget(self.gb)
self.gb.l = g = QVBoxLayout(self.gb)
g.setContentsMargins(0, 0, 0, 0)
self.fields_view = v = FieldsList(self)
g.addWidget(v)
v.setFlow(QListView.Flow.LeftToRight)
v.setWrapping(True)
v.setResizeMode(QListView.ResizeMode.Adjust)
self.fields_model = FieldsModel(self.plugin)
self.fields_model.initialize()
v.setModel(self.fields_model)
self.memory = []
self.widgets = []
self.l = QGridLayout()
self.l.setContentsMargins(0, 0, 0, 0)
l.addLayout(self.l, 100)
for opt in plugin.options:
self.create_widgets(opt)
def create_widgets(self, opt):
val = self.plugin.prefs[opt.name]
if opt.type == 'number':
c = QSpinBox if isinstance(opt.default, numbers.Integral) else QDoubleSpinBox
widget = c(self)
widget.setRange(min(widget.minimum(), 20 * val), max(widget.maximum(), 20 * val))
widget.setValue(val)
elif opt.type == 'string':
widget = QLineEdit(self)
widget.setText(val if val else '')
elif opt.type == 'bool':
widget = QCheckBox(opt.label, self)
widget.setChecked(bool(val))
elif opt.type == 'choices':
widget = QComboBox(self)
items = list(iteritems(opt.choices))
items.sort(key=lambda k_v: sort_key(k_v[1]))
for key, label in items:
widget.addItem(label, (key))
idx = widget.findData(val)
widget.setCurrentIndex(idx)
widget.opt = opt
widget.setToolTip(textwrap.fill(opt.desc))
self.widgets.append(widget)
r = self.l.rowCount()
if opt.type == 'bool':
self.l.addWidget(widget, r, 0, 1, self.l.columnCount())
else:
l = QLabel(opt.label)
l.setToolTip(widget.toolTip())
self.memory.append(l)
l.setBuddy(widget)
self.l.addWidget(l, r, 0, 1, 1)
self.l.addWidget(widget, r, 1, 1, 1)
def commit(self):
self.fields_model.commit()
for w in self.widgets:
if isinstance(w, (QSpinBox, QDoubleSpinBox)):
val = w.value()
elif isinstance(w, QLineEdit):
val = str(w.text())
elif isinstance(w, QCheckBox):
val = w.isChecked()
elif isinstance(w, QComboBox):
idx = w.currentIndex()
val = str(w.itemData(idx) or '')
self.plugin.prefs[w.opt.name] = val
| 4,941 | Python | .py | 119 | 31.865546 | 146 | 0.604375 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,814 | single_download.py | kovidgoyal_calibre/src/calibre/gui2/metadata/single_download.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
DEBUG_DIALOG = False
# Imports {{{
import os
import time
from io import BytesIO
from operator import attrgetter
from threading import Event, Thread
from qt.core import (
QAbstractItemView,
QAbstractListModel,
QAbstractTableModel,
QApplication,
QCursor,
QDialog,
QDialogButtonBox,
QGridLayout,
QHBoxLayout,
QIcon,
QItemSelectionModel,
QLabel,
QListView,
QMenu,
QModelIndex,
QPalette,
QPixmap,
QPushButton,
QRect,
QRectF,
QSize,
QSizePolicy,
QSplitter,
QStackedWidget,
QStringListModel,
QStyle,
QStyledItemDelegate,
Qt,
QTableView,
QTextBrowser,
QTextDocument,
QTimer,
QVBoxLayout,
QWidget,
pyqtSignal,
)
from calibre import force_unicode
from calibre.customize.ui import metadata_plugins
from calibre.db.constants import COVER_FILE_NAME, DATA_DIR_NAME
from calibre.ebooks.metadata import authors_to_string, rating_to_stars
from calibre.ebooks.metadata.book.base import Metadata
from calibre.ebooks.metadata.opf2 import OPF
from calibre.ebooks.metadata.sources.identify import urls_from_identifiers
from calibre.gui2 import choose_save_file, error_dialog, gprefs, rating_font
from calibre.gui2.progress_indicator import SpinAnimator
from calibre.gui2.widgets2 import HTMLDisplay
from calibre.library.comments import comments_to_html
from calibre.ptempfile import TemporaryDirectory
from calibre.utils.date import UNDEFINED_DATE, as_utc, format_date, fromordinal, utcnow
from calibre.utils.img import image_to_data, save_image
from calibre.utils.ipc.simple_worker import WorkerError, fork_job
from calibre.utils.logging import GUILog as Log
from calibre.utils.resources import get_image_path as I
from polyglot.builtins import iteritems, itervalues
from polyglot.queue import Empty, Queue
# }}}
class RichTextDelegate(QStyledItemDelegate): # {{{
def __init__(self, parent=None, max_width=160):
QStyledItemDelegate.__init__(self, parent)
self.max_width = max_width
self.dummy_model = QStringListModel([' '], self)
self.dummy_index = self.dummy_model.index(0)
def to_doc(self, index, option=None):
doc = QTextDocument()
if option is not None and option.state & QStyle.StateFlag.State_Selected:
p = option.palette
group = (QPalette.ColorGroup.Active if option.state & QStyle.StateFlag.State_Active else
QPalette.ColorGroup.Inactive)
c = p.color(group, QPalette.ColorRole.HighlightedText)
c = 'rgb(%d, %d, %d)'%c.getRgb()[:3]
doc.setDefaultStyleSheet(' * { color: %s }'%c)
doc.setHtml(index.data() or '')
return doc
def sizeHint(self, option, index):
doc = self.to_doc(index, option=option)
ans = doc.size().toSize()
if ans.width() > self.max_width - 10:
ans.setWidth(self.max_width)
ans.setHeight(ans.height()+10)
return ans
def paint(self, painter, option, index):
QStyledItemDelegate.paint(self, painter, option, self.dummy_index)
painter.save()
painter.setClipRect(QRectF(option.rect))
painter.translate(option.rect.topLeft())
self.to_doc(index, option).drawContents(painter)
painter.restore()
# }}}
class CoverDelegate(QStyledItemDelegate): # {{{
ICON_SIZE = 150, 200
needs_redraw = pyqtSignal()
def __init__(self, parent):
QStyledItemDelegate.__init__(self, parent)
self.animator = SpinAnimator(self)
self.animator.updated.connect(self.needs_redraw)
self.color = parent.palette().color(QPalette.ColorRole.WindowText)
self.spinner_width = 64
def start_animation(self):
self.animator.start()
def stop_animation(self):
self.animator.stop()
def paint(self, painter, option, index):
QStyledItemDelegate.paint(self, painter, option, index)
style = QApplication.style()
waiting = self.animator.is_running() and bool(index.data(Qt.ItemDataRole.UserRole))
if waiting:
rect = QRect(0, 0, self.spinner_width, self.spinner_width)
rect.moveCenter(option.rect.center())
self.animator.draw(painter, rect, self.color)
else:
# Ensure the cover is rendered over any selection rect
style.drawItemPixmap(painter, option.rect, Qt.AlignmentFlag.AlignTop|Qt.AlignmentFlag.AlignHCenter,
QPixmap(index.data(Qt.ItemDataRole.DecorationRole)))
# }}}
class ResultsModel(QAbstractTableModel): # {{{
COLUMNS = (
'#', _('Title'), _('Published'), _('Has cover'), _('Has summary')
)
HTML_COLS = (1, 2)
ICON_COLS = (3, 4)
def __init__(self, results, parent=None):
QAbstractTableModel.__init__(self, parent)
self.results = results
self.yes_icon = (QIcon.ic('ok.png'))
def rowCount(self, parent=None):
return len(self.results)
def columnCount(self, parent=None):
return len(self.COLUMNS)
def headerData(self, section, orientation, role):
if orientation == Qt.Orientation.Horizontal and role == Qt.ItemDataRole.DisplayRole:
try:
return (self.COLUMNS[section])
except:
return None
return None
def data_as_text(self, book, col):
if col == 0:
return str(book.gui_rank+1)
if col == 1:
t = book.title if book.title else _('Unknown')
a = authors_to_string(book.authors) if book.authors else ''
return f'<b>{t}</b><br><i>{a}</i>'
if col == 2:
d = format_date(book.pubdate, 'yyyy') if book.pubdate else _('Unknown')
p = book.publisher if book.publisher else ''
return f'<b>{d}</b><br><i>{p}</i>'
def data(self, index, role):
row, col = index.row(), index.column()
try:
book = self.results[row]
except:
return None
if role == Qt.ItemDataRole.DisplayRole and col not in self.ICON_COLS:
res = self.data_as_text(book, col)
if res:
return (res)
return None
elif role == Qt.ItemDataRole.DecorationRole and col in self.ICON_COLS:
if col == 3 and getattr(book, 'has_cached_cover_url', False):
return self.yes_icon
if col == 4 and book.comments:
return self.yes_icon
elif role == Qt.ItemDataRole.UserRole:
return book
elif role == Qt.ItemDataRole.ToolTipRole and col == 3:
return (
_('The "has cover" indication is not fully\n'
'reliable. Sometimes results marked as not\n'
'having a cover will find a cover in the download\n'
'cover stage, and vice versa.'))
return None
def sort(self, col, order=Qt.SortOrder.AscendingOrder):
if col == 0:
key = attrgetter('gui_rank')
elif col == 1:
key = attrgetter('title')
elif col == 2:
def dategetter(x):
x = getattr(x, 'pubdate', None)
if x is None:
x = UNDEFINED_DATE
return as_utc(x)
key = dategetter
elif col == 3:
key = attrgetter('has_cached_cover_url')
elif key == 4:
def key(x):
return bool(x.comments)
else:
def key(x):
return x
self.beginResetModel()
self.results.sort(key=key, reverse=order==Qt.SortOrder.AscendingOrder)
self.endResetModel()
# }}}
class ResultsView(QTableView): # {{{
show_details_signal = pyqtSignal(object)
book_selected = pyqtSignal(object)
def __init__(self, parent=None):
QTableView.__init__(self, parent)
self.rt_delegate = RichTextDelegate(self)
self.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
self.setAlternatingRowColors(True)
self.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
self.setIconSize(QSize(24, 24))
self.clicked.connect(self.show_details)
self.doubleClicked.connect(self.select_index)
self.setSortingEnabled(True)
def show_results(self, results):
self._model = ResultsModel(results, self)
self.setModel(self._model)
for i in self._model.HTML_COLS:
self.setItemDelegateForColumn(i, self.rt_delegate)
self.resizeRowsToContents()
self.resizeColumnsToContents()
self.setFocus(Qt.FocusReason.OtherFocusReason)
idx = self.model().index(0, 0)
if idx.isValid() and self.model().rowCount() > 0:
self.show_details(idx)
sm = self.selectionModel()
sm.select(idx, QItemSelectionModel.SelectionFlag.ClearAndSelect|QItemSelectionModel.SelectionFlag.Rows)
def resize_delegate(self):
self.rt_delegate.max_width = int(self.width()/2.1)
self.resizeColumnsToContents()
def resizeEvent(self, ev):
ret = super().resizeEvent(ev)
self.resize_delegate()
return ret
def currentChanged(self, current, previous):
ret = QTableView.currentChanged(self, current, previous)
self.show_details(current)
return ret
def show_details(self, index):
f = rating_font()
book = self.model().data(index, Qt.ItemDataRole.UserRole)
parts = [
'<center>',
'<h2>%s</h2>'%book.title,
'<div><i>%s</i></div>'%authors_to_string(book.authors),
]
if not book.is_null('series'):
series = book.format_field('series')
if series[1]:
parts.append('<div>%s: %s</div>'%series)
if not book.is_null('rating'):
style = 'style=\'font-family:"%s"\''%f
parts.append('<div %s>%s</div>'%(style, rating_to_stars(int(2 * book.rating))))
parts.append('</center>')
if book.identifiers:
urls = urls_from_identifiers(book.identifiers)
ids = ['<a href="%s">%s</a>'%(url, name) for name, ign, ign, url in urls]
if ids:
parts.append('<div><b>%s:</b> %s</div><br>'%(_('See at'), ', '.join(ids)))
if book.tags:
parts.append('<div>%s</div><div>\u00a0</div>'%', '.join(book.tags))
if book.comments:
parts.append(comments_to_html(book.comments))
self.show_details_signal.emit(''.join(parts))
def select_index(self, index):
if self.model() is None:
return
if not index.isValid():
index = self.model().index(0, 0)
book = self.model().data(index, Qt.ItemDataRole.UserRole)
self.book_selected.emit(book)
def get_result(self):
self.select_index(self.currentIndex())
def keyPressEvent(self, ev):
if ev.key() in (Qt.Key.Key_Left, Qt.Key.Key_Right):
ac = QAbstractItemView.CursorAction.MoveDown if ev.key() == Qt.Key.Key_Right else QAbstractItemView.CursorAction.MoveUp
index = self.moveCursor(ac, ev.modifiers())
if index.isValid() and index != self.currentIndex():
m = self.selectionModel()
m.select(index, QItemSelectionModel.SelectionFlag.Select|QItemSelectionModel.SelectionFlag.Current|QItemSelectionModel.SelectionFlag.Rows)
self.setCurrentIndex(index)
ev.accept()
return
return QTableView.keyPressEvent(self, ev)
# }}}
class Comments(HTMLDisplay): # {{{
def __init__(self, parent=None):
HTMLDisplay.__init__(self, parent)
self.setAcceptDrops(False)
self.wait_timer = QTimer(self)
self.wait_timer.timeout.connect(self.update_wait)
self.wait_timer.setInterval(800)
self.dots_count = 0
self.anchor_clicked.connect(self.link_activated)
def link_activated(self, url):
from calibre.gui2 import open_url
if url.scheme() in {'http', 'https'}:
open_url(url)
def show_wait(self):
self.dots_count = 0
self.wait_timer.start()
self.update_wait()
def update_wait(self):
self.dots_count += 1
self.dots_count %= 10
self.dots_count = self.dots_count or 1
self.setHtml(
'<h2>'+_('Please wait')+
'<br><span id="dots">{}</span></h2>'.format('.' * self.dots_count))
def show_data(self, html):
self.wait_timer.stop()
def color_to_string(col):
ans = '#000000'
if col.isValid():
col = col.toRgb()
if col.isValid():
ans = str(col.name())
return ans
c = color_to_string(QApplication.palette().color(QPalette.ColorGroup.Normal,
QPalette.ColorRole.WindowText))
templ = '''\
<html>
<head>
<style type="text/css">
body, td {background-color: transparent; color: %s }
a { text-decoration: none; }
div.description { margin-top: 0; padding-top: 0; text-indent: 0 }
table { margin-bottom: 0; padding-bottom: 0; }
</style>
</head>
<body>
<div class="description">
%%s
</div>
</body>
<html>
'''%(c,)
self.setHtml(templ%html)
# }}}
class IdentifyWorker(Thread): # {{{
def __init__(self, log, abort, title, authors, identifiers, caches):
Thread.__init__(self)
self.daemon = True
self.log, self.abort = log, abort
self.title, self.authors, self.identifiers = (title, authors,
identifiers)
self.results = []
self.error = None
self.caches = caches
def sample_results(self):
m1 = Metadata('The Great Gatsby', ['Francis Scott Fitzgerald'])
m2 = Metadata('The Great Gatsby - An extra long title to test resizing', ['F. Scott Fitzgerald'])
m1.has_cached_cover_url = True
m2.has_cached_cover_url = False
m1.comments = 'Some comments '*10
m1.tags = ['tag%d'%i for i in range(20)]
m1.rating = 4.4
m1.language = 'en'
m2.language = 'fr'
m1.pubdate = utcnow()
m2.pubdate = fromordinal(1000000)
m1.publisher = 'Publisher 1'
m2.publisher = 'Publisher 2'
return [m1, m2]
def run(self):
try:
if DEBUG_DIALOG:
self.results = self.sample_results()
else:
res = fork_job(
'calibre.ebooks.metadata.sources.worker',
'single_identify', (self.title, self.authors,
self.identifiers), no_output=True, abort=self.abort)
self.results, covers, caches, log_dump = res['result']
self.results = [OPF(BytesIO(r), basedir=os.getcwd(),
populate_spine=False).to_book_metadata() for r in self.results]
for r, cov in zip(self.results, covers):
r.has_cached_cover_url = cov
self.caches.update(caches)
self.log.load(log_dump)
for i, result in enumerate(self.results):
result.gui_rank = i
except WorkerError as e:
self.error = force_unicode(e.orig_tb)
except:
import traceback
self.error = force_unicode(traceback.format_exc())
# }}}
class IdentifyWidget(QWidget): # {{{
rejected = pyqtSignal()
results_found = pyqtSignal()
book_selected = pyqtSignal(object, object)
def __init__(self, log, parent=None):
QWidget.__init__(self, parent)
self.log = log
self.abort = Event()
self.caches = {}
self.l = l = QVBoxLayout(self)
names = ['<b>'+p.name+'</b>' for p in metadata_plugins(['identify']) if
p.is_configured()]
self.top = QLabel('<p>'+_('calibre is downloading metadata from: ') +
', '.join(names))
self.top.setWordWrap(True)
l.addWidget(self.top)
self.splitter = s = QSplitter(self)
s.setChildrenCollapsible(False)
l.addWidget(s, 100)
self.results_view = ResultsView(self)
self.results_view.book_selected.connect(self.emit_book_selected)
self.get_result = self.results_view.get_result
s.addWidget(self.results_view)
self.comments_view = Comments(self)
s.addWidget(self.comments_view)
s.setStretchFactor(0, 2)
s.setStretchFactor(1, 1)
self.results_view.show_details_signal.connect(self.comments_view.show_data)
self.query = QLabel('download starting...')
self.query.setWordWrap(True)
self.query.setTextFormat(Qt.TextFormat.PlainText)
l.addWidget(self.query)
self.comments_view.show_wait()
state = gprefs.get('metadata-download-identify-widget-splitter-state')
if state is not None:
s.restoreState(state)
def save_state(self):
gprefs['metadata-download-identify-widget-splitter-state'] = bytearray(self.splitter.saveState())
def emit_book_selected(self, book):
self.book_selected.emit(book, self.caches)
def start(self, title=None, authors=None, identifiers={}):
self.log.clear()
self.log('Starting download')
parts, simple_desc = [], ''
if title:
parts.append('title:'+title)
simple_desc += _('Title: %s ') % title
if authors:
parts.append('authors:'+authors_to_string(authors))
simple_desc += _('Authors: %s ') % authors_to_string(authors)
if identifiers:
x = ', '.join('%s:%s'%(k, v) for k, v in iteritems(identifiers))
parts.append(x)
if 'isbn' in identifiers:
simple_desc += 'ISBN: %s' % identifiers['isbn']
self.query.setText(simple_desc)
self.log(str(self.query.text()))
self.worker = IdentifyWorker(self.log, self.abort, title,
authors, identifiers, self.caches)
self.worker.start()
QTimer.singleShot(50, self.update)
def update(self):
if self.worker.is_alive():
QTimer.singleShot(50, self.update)
else:
self.process_results()
def process_results(self):
if self.worker.error is not None:
error_dialog(self, _('Download failed'),
_('Failed to download metadata. Click '
'Show Details to see details'),
show=True, det_msg=self.worker.error)
self.rejected.emit()
return
if not self.worker.results:
log = ''.join(self.log.plain_text)
error_dialog(self, _('No matches found'), '<p>' +
_('Failed to find any books that '
'match your search. Try making the search <b>less '
'specific</b>. For example, use only the author\'s '
'last name and a single distinctive word from '
'the title.<p>To see the full log, click "Show details".'),
show=True, det_msg=log)
self.rejected.emit()
return
self.results_view.show_results(self.worker.results)
self.results_found.emit()
def cancel(self):
self.abort.set()
# }}}
class CoverWorker(Thread): # {{{
def __init__(self, log, abort, title, authors, identifiers, caches):
Thread.__init__(self, name='CoverWorker')
self.daemon = True
self.log, self.abort = log, abort
self.title, self.authors, self.identifiers = (title, authors,
identifiers)
self.caches = caches
self.rq = Queue()
self.error = None
def fake_run(self):
images = ['donate.png', 'config.png', 'column.png', 'eject.png', ]
time.sleep(2)
for pl, im in zip(metadata_plugins(['cover']), images):
self.rq.put((pl.name, 1, 1, 'png', I(im, data=True)))
def run(self):
try:
if DEBUG_DIALOG:
self.fake_run()
else:
self.run_fork()
except WorkerError as e:
self.error = force_unicode(e.orig_tb)
except:
import traceback
self.error = force_unicode(traceback.format_exc())
def run_fork(self):
with TemporaryDirectory('_single_metadata_download') as tdir:
self.keep_going = True
t = Thread(target=self.monitor_tdir, args=(tdir,))
t.daemon = True
t.start()
try:
res = fork_job('calibre.ebooks.metadata.sources.worker',
'single_covers',
(self.title, self.authors, self.identifiers, self.caches,
tdir),
no_output=True, abort=self.abort)
self.log.append_dump(res['result'])
finally:
self.keep_going = False
t.join()
def scan_once(self, tdir, seen):
for x in list(os.listdir(tdir)):
if x in seen:
continue
if x.endswith('.cover') and os.path.exists(os.path.join(tdir,
x+'.done')):
name = x.rpartition('.')[0]
try:
plugin_name, width, height, fmt = name.split(',,')
width, height = int(width), int(height)
with open(os.path.join(tdir, x), 'rb') as f:
data = f.read()
except:
import traceback
traceback.print_exc()
else:
seen.add(x)
self.rq.put((plugin_name, width, height, fmt, data))
def monitor_tdir(self, tdir):
seen = set()
while self.keep_going:
time.sleep(1)
self.scan_once(tdir, seen)
# One last scan after the download process has ended
self.scan_once(tdir, seen)
# }}}
class CoversModel(QAbstractListModel): # {{{
def __init__(self, current_cover, parent=None):
QAbstractListModel.__init__(self, parent)
if current_cover is None:
ic = QIcon.ic('default_cover.png')
current_cover = ic.pixmap(ic.availableSizes()[0])
current_cover.setDevicePixelRatio(QApplication.instance().devicePixelRatio())
self.blank = QIcon.ic('blank.png').pixmap(*CoverDelegate.ICON_SIZE)
self.cc = current_cover
self.reset_covers(do_reset=False)
def reset_covers(self, do_reset=True):
self.covers = [self.get_item(_('Current cover'), self.cc)]
self.plugin_map = {}
for i, plugin in enumerate(metadata_plugins(['cover'])):
self.covers.append((plugin.name+'\n'+_('Searching...'),
(self.blank), None, True))
self.plugin_map[plugin] = [i+1]
if do_reset:
self.beginResetModel(), self.endResetModel()
def get_item(self, src, pmap, waiting=False):
sz = '%dx%d'%(pmap.width(), pmap.height())
text = (src + '\n' + sz)
scaled = pmap.scaled(
int(CoverDelegate.ICON_SIZE[0] * pmap.devicePixelRatio()), int(CoverDelegate.ICON_SIZE[1] * pmap.devicePixelRatio()),
Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
scaled.setDevicePixelRatio(pmap.devicePixelRatio())
return (text, (scaled), pmap, waiting)
def rowCount(self, parent=None):
return len(self.covers)
def data(self, index, role):
try:
text, pmap, cover, waiting = self.covers[index.row()]
except:
return None
if role == Qt.ItemDataRole.DecorationRole:
return pmap
if role == Qt.ItemDataRole.DisplayRole or role == Qt.ItemDataRole.ToolTipRole:
return text
if role == Qt.ItemDataRole.UserRole:
return waiting
return None
def plugin_for_index(self, index):
row = index.row() if hasattr(index, 'row') else index
for k, v in iteritems(self.plugin_map):
if row in v:
return k
def clear_failed(self):
# Remove entries that are still waiting
good = []
pmap = {}
def keygen(x):
pmap = x[2]
if pmap is None:
return 1
return pmap.width()*pmap.height()
dcovers = sorted(self.covers[1:], key=keygen, reverse=True)
cmap = {i:self.plugin_for_index(i) for i in range(len(self.covers))}
for i, x in enumerate(self.covers[0:1] + dcovers):
if not x[-1]:
good.append(x)
plugin = cmap[i]
if plugin is not None:
try:
pmap[plugin].append(len(good) - 1)
except KeyError:
pmap[plugin] = [len(good)-1]
self.covers = good
self.plugin_map = pmap
self.beginResetModel(), self.endResetModel()
def pointer_from_index(self, index):
row = index.row() if hasattr(index, 'row') else index
try:
return self.covers[row][2]
except IndexError:
pass
def index_from_pointer(self, pointer):
for r, (text, scaled, pmap, waiting) in enumerate(self.covers):
if pointer == pmap:
return self.index(r)
return self.index(0)
def load_pixmap(self, data):
pmap = QPixmap()
pmap.loadFromData(data)
pmap.setDevicePixelRatio(QApplication.instance().devicePixelRatio())
return pmap
def update_result(self, plugin_name, width, height, data):
if plugin_name.endswith('}'):
# multi cover plugin
plugin_name = plugin_name.partition('{')[0]
plugin = [plugin for plugin in self.plugin_map if plugin.name == plugin_name]
if not plugin:
return
plugin = plugin[0]
last_row = max(self.plugin_map[plugin])
pmap = self.load_pixmap(data)
if pmap.isNull():
return
self.beginInsertRows(QModelIndex(), last_row, last_row)
for rows in itervalues(self.plugin_map):
for i in range(len(rows)):
if rows[i] >= last_row:
rows[i] += 1
self.plugin_map[plugin].insert(-1, last_row)
self.covers.insert(last_row, self.get_item(plugin_name, pmap, waiting=False))
self.endInsertRows()
else:
# single cover plugin
idx = None
for plugin, rows in iteritems(self.plugin_map):
if plugin.name == plugin_name:
idx = rows[0]
break
if idx is None:
return
pmap = self.load_pixmap(data)
if pmap.isNull():
return
self.covers[idx] = self.get_item(plugin_name, pmap, waiting=False)
self.dataChanged.emit(self.index(idx), self.index(idx))
def cover_pixmap(self, index):
row = index.row()
if row > 0 and row < len(self.covers):
pmap = self.covers[row][2]
if pmap is not None and not pmap.isNull():
return pmap
# }}}
class CoversView(QListView): # {{{
chosen = pyqtSignal()
def __init__(self, current_cover, parent=None):
QListView.__init__(self, parent)
self.book_id = getattr(parent, 'book_id', 0)
self.m = CoversModel(current_cover, self)
self.setModel(self.m)
self.setFlow(QListView.Flow.LeftToRight)
self.setWrapping(True)
self.setResizeMode(QListView.ResizeMode.Adjust)
self.setGridSize(QSize(190, 260))
self.setIconSize(QSize(*CoverDelegate.ICON_SIZE))
self.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
self.setViewMode(QListView.ViewMode.IconMode)
self.delegate = CoverDelegate(self)
self.setItemDelegate(self.delegate)
self.delegate.needs_redraw.connect(self.redraw_spinners,
type=Qt.ConnectionType.QueuedConnection)
self.doubleClicked.connect(self.chosen, type=Qt.ConnectionType.QueuedConnection)
self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.customContextMenuRequested.connect(self.show_context_menu)
def redraw_spinners(self):
m = self.model()
for r in range(m.rowCount()):
idx = m.index(r)
if bool(m.data(idx, Qt.ItemDataRole.UserRole)):
m.dataChanged.emit(idx, idx)
def select(self, num):
current = self.model().index(num)
sm = self.selectionModel()
sm.select(current, QItemSelectionModel.SelectionFlag.SelectCurrent)
def start(self):
self.select(0)
self.delegate.start_animation()
def stop(self):
self.delegate.stop_animation()
def reset_covers(self):
self.m.reset_covers()
def clear_failed(self):
pointer = self.m.pointer_from_index(self.currentIndex())
self.m.clear_failed()
if pointer is None:
self.select(0)
else:
self.select(self.m.index_from_pointer(pointer).row())
def show_context_menu(self, point):
idx = self.currentIndex()
if idx and idx.isValid() and not idx.data(Qt.ItemDataRole.UserRole):
m = QMenu(self)
m.addAction(QIcon.ic('view.png'), _('View this cover at full size'), self.show_cover)
m.addAction(QIcon.ic('edit-copy.png'), _('Copy this cover to clipboard'), self.copy_cover)
m.addAction(QIcon.ic('save.png'), _('Save this cover to disk'), self.save_to_disk)
if self.book_id:
m.addAction(QIcon.ic('save.png'), _('Save this cover in the book extra files'), self.save_alternate_cover)
m.exec(QCursor.pos())
@property
def current_pixmap(self):
idx = self.currentIndex()
pmap = self.model().cover_pixmap(idx)
if pmap is None and idx.row() == 0:
pmap = self.model().cc
return pmap
def show_cover(self):
pmap = self.current_pixmap
if pmap is not None:
from calibre.gui2.image_popup import ImageView
d = ImageView(self, pmap, str(self.currentIndex().data(Qt.ItemDataRole.DisplayRole) or ''), geom_name='metadata_download_cover_popup_geom')
d(use_exec=True)
def copy_cover(self):
pmap = self.current_pixmap
if pmap is not None:
QApplication.clipboard().setPixmap(pmap)
def save_to_disk(self):
pmap = self.current_pixmap
if pmap:
path = choose_save_file(self, 'save-downloaded-cover-to-disk', _('Save cover image'), filters=[
(_('Images'), ['jpg', 'jpeg', 'png', 'webp'])], all_files=False, initial_filename=COVER_FILE_NAME)
if path:
save_image(pmap.toImage(), path)
def save_alternate_cover(self):
pmap = self.current_pixmap
if pmap:
from calibre.gui2.ui import get_gui
db = get_gui().current_db.new_api
existing = {x[0] for x in db.list_extra_files(self.book_id)}
h, ext = os.path.splitext(COVER_FILE_NAME)
template = f'{DATA_DIR_NAME}/{h}-{{:03d}}{ext}'
for i in range(1, 1000):
q = template.format(i)
if q not in existing:
cdata = image_to_data(pmap.toImage())
db.add_extra_files(self.book_id, {q: BytesIO(cdata)}, replace=False, auto_rename=True)
break
else:
error_dialog(self, _('Too many covers'), _(
'Could not save cover as there are too many existing covers'), show=True)
return
def keyPressEvent(self, ev):
if ev.key() in (Qt.Key.Key_Enter, Qt.Key.Key_Return):
self.chosen.emit()
ev.accept()
return
return QListView.keyPressEvent(self, ev)
# }}}
class CoversWidget(QWidget): # {{{
chosen = pyqtSignal()
finished = pyqtSignal()
def __init__(self, log, current_cover, parent=None):
QWidget.__init__(self, parent)
self.log = log
self.abort = Event()
self.l = l = QGridLayout()
self.setLayout(l)
self.msg = QLabel()
self.msg.setWordWrap(True)
self.book_id = getattr(parent, 'book_id', 0)
l.addWidget(self.msg, 0, 0)
self.covers_view = CoversView(current_cover, self)
self.covers_view.chosen.connect(self.chosen)
l.addWidget(self.covers_view, 1, 0)
self.continue_processing = True
def reset_covers(self):
self.covers_view.reset_covers()
def start(self, book, current_cover, title, authors, caches):
self.continue_processing = True
self.abort.clear()
self.book, self.current_cover = book, current_cover
self.title, self.authors = title, authors
self.log('Starting cover download for:', book.title)
self.log('Query:', title, authors, self.book.identifiers)
self.msg.setText('<p>'+
_('Downloading covers for <b>%s</b>, please wait...')%book.title)
self.covers_view.start()
self.worker = CoverWorker(self.log, self.abort, self.title,
self.authors, book.identifiers, caches)
self.worker.start()
QTimer.singleShot(50, self.check)
self.covers_view.setFocus(Qt.FocusReason.OtherFocusReason)
def check(self):
if self.worker.is_alive() and not self.abort.is_set():
QTimer.singleShot(50, self.check)
try:
self.process_result(self.worker.rq.get_nowait())
except Empty:
pass
else:
self.process_results()
def process_results(self):
while self.continue_processing:
try:
self.process_result(self.worker.rq.get_nowait())
except Empty:
break
if self.continue_processing:
self.covers_view.clear_failed()
if self.worker.error and self.worker.error.strip():
error_dialog(self, _('Download failed'),
_('Failed to download any covers, click'
' "Show details" for details.'),
det_msg=self.worker.error, show=True)
num = self.covers_view.model().rowCount()
if num < 2:
txt = _('Could not find any covers for <b>%s</b>')%self.book.title
else:
if num == 2:
txt = _('Found a cover for {title}').format(title=self.title)
else:
txt = _(
'Found <b>{num}</b> covers for {title}. When the download completes,'
' the covers will be sorted by size.').format(
title=self.title, num=num-1)
self.msg.setText(txt)
self.msg.setWordWrap(True)
self.covers_view.stop()
self.finished.emit()
def process_result(self, result):
if not self.continue_processing:
return
plugin_name, width, height, fmt, data = result
self.covers_view.model().update_result(plugin_name, width, height, data)
def cleanup(self):
self.covers_view.delegate.stop_animation()
self.continue_processing = False
def cancel(self):
self.cleanup()
self.abort.set()
def cover_pixmap(self):
idx = None
for i in self.covers_view.selectionModel().selectedIndexes():
if i.isValid():
idx = i
break
if idx is None:
idx = self.covers_view.currentIndex()
return self.covers_view.model().cover_pixmap(idx)
# }}}
class LogViewer(QDialog): # {{{
def __init__(self, log, parent=None):
QDialog.__init__(self, parent)
self.log = log
self.l = l = QVBoxLayout()
self.setLayout(l)
self.tb = QTextBrowser(self)
l.addWidget(self.tb)
self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
l.addWidget(self.bb)
self.copy_button = self.bb.addButton(_('Copy to clipboard'),
QDialogButtonBox.ButtonRole.ActionRole)
self.copy_button.clicked.connect(self.copy_to_clipboard)
self.copy_button.setIcon(QIcon.ic('edit-copy.png'))
self.bb.rejected.connect(self.reject)
self.bb.accepted.connect(self.accept)
self.setWindowTitle(_('Download log'))
self.setWindowIcon(QIcon.ic('debug.png'))
self.resize(QSize(800, 400))
self.keep_updating = True
self.last_html = None
self.finished.connect(self.stop)
QTimer.singleShot(100, self.update_log)
self.show()
def copy_to_clipboard(self):
QApplication.clipboard().setText(''.join(self.log.plain_text))
def stop(self, *args):
self.keep_updating = False
def update_log(self):
if not self.keep_updating:
return
html = self.log.html
if html != self.last_html:
self.last_html = html
self.tb.setHtml('<pre style="font-family:monospace">%s</pre>'%html)
QTimer.singleShot(1000, self.update_log)
# }}}
class FullFetch(QDialog): # {{{
def __init__(self, current_cover=None, parent=None):
QDialog.__init__(self, parent)
self.current_cover = current_cover
self.book_id = getattr(parent, 'book_id', 0)
self.log = Log()
self.book = self.cover_pixmap = None
self.setWindowTitle(_('Downloading metadata...'))
self.setWindowIcon(QIcon.ic('download-metadata.png'))
self.stack = QStackedWidget()
self.l = l = QVBoxLayout()
self.setLayout(l)
l.addWidget(self.stack)
self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel|QDialogButtonBox.StandardButton.Ok)
self.h = h = QHBoxLayout()
l.addLayout(h)
self.bb.rejected.connect(self.reject)
self.bb.accepted.connect(self.accept)
self.ok_button = self.bb.button(QDialogButtonBox.StandardButton.Ok)
self.ok_button.setEnabled(False)
self.ok_button.clicked.connect(self.ok_clicked)
self.prev_button = pb = QPushButton(QIcon.ic('back.png'), _('&Back'), self)
pb.clicked.connect(self.back_clicked)
pb.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
self.log_button = self.bb.addButton(_('&View log'), QDialogButtonBox.ButtonRole.ActionRole)
self.log_button.clicked.connect(self.view_log)
self.log_button.setIcon(QIcon.ic('debug.png'))
self.prev_button.setVisible(False)
h.addWidget(self.prev_button), h.addWidget(self.bb)
self.identify_widget = IdentifyWidget(self.log, self)
self.identify_widget.rejected.connect(self.reject)
self.identify_widget.results_found.connect(self.identify_results_found)
self.identify_widget.book_selected.connect(self.book_selected)
self.stack.addWidget(self.identify_widget)
self.covers_widget = CoversWidget(self.log, self.current_cover, parent=self)
self.covers_widget.chosen.connect(self.ok_clicked)
self.stack.addWidget(self.covers_widget)
if not self.restore_geometry(gprefs, 'metadata_single_gui_geom'):
self.resize(850, 600)
self.finished.connect(self.cleanup)
def view_log(self):
self._lv = LogViewer(self.log, self)
def book_selected(self, book, caches):
self.prev_button.setVisible(True)
self.book = book
self.stack.setCurrentIndex(1)
self.log('\n\n')
self.covers_widget.start(book, self.current_cover,
self.title, self.authors, caches)
self.ok_button.setFocus()
def back_clicked(self):
self.prev_button.setVisible(False)
self.stack.setCurrentIndex(0)
self.covers_widget.cancel()
self.covers_widget.reset_covers()
def accept(self):
# Prevent the usual dialog accept mechanisms from working
self.save_geometry(gprefs, 'metadata_single_gui_geom')
self.identify_widget.save_state()
if DEBUG_DIALOG:
if self.stack.currentIndex() == 2:
return QDialog.accept(self)
else:
if self.stack.currentIndex() == 1:
return QDialog.accept(self)
def reject(self):
self.save_geometry(gprefs, 'metadata_single_gui_geom')
self.identify_widget.cancel()
self.covers_widget.cancel()
return QDialog.reject(self)
def cleanup(self):
self.covers_widget.cleanup()
def identify_results_found(self):
self.ok_button.setEnabled(True)
def next_clicked(self, *args):
self.save_geometry(gprefs, 'metadata_single_gui_geom')
self.identify_widget.get_result()
def ok_clicked(self, *args):
self.cover_pixmap = self.covers_widget.cover_pixmap()
if self.stack.currentIndex() == 0:
self.next_clicked()
return
if DEBUG_DIALOG:
if self.cover_pixmap is not None:
self.w = QLabel()
self.w.setPixmap(self.cover_pixmap)
self.stack.addWidget(self.w)
self.stack.setCurrentIndex(2)
else:
QDialog.accept(self)
def start(self, title=None, authors=None, identifiers={}):
self.title, self.authors = title, authors
self.identify_widget.start(title=title, authors=authors,
identifiers=identifiers)
return self.exec()
# }}}
class CoverFetch(QDialog): # {{{
def __init__(self, current_cover=None, parent=None):
QDialog.__init__(self, parent)
self.current_cover = current_cover
self.book_id = getattr(parent, 'book_id', 0)
self.log = Log()
self.cover_pixmap = None
self.setWindowTitle(_('Downloading cover...'))
self.setWindowIcon(QIcon.ic('default_cover.png'))
self.l = l = QVBoxLayout()
self.setLayout(l)
self.covers_widget = CoversWidget(self.log, self.current_cover, parent=self)
self.covers_widget.chosen.connect(self.accept)
l.addWidget(self.covers_widget)
self.resize(850, 600)
self.finished.connect(self.cleanup)
self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel|QDialogButtonBox.StandardButton.Ok)
l.addWidget(self.bb)
self.log_button = self.bb.addButton(_('&View log'), QDialogButtonBox.ButtonRole.ActionRole)
self.log_button.clicked.connect(self.view_log)
self.log_button.setIcon(QIcon.ic('debug.png'))
self.bb.rejected.connect(self.reject)
self.bb.accepted.connect(self.accept)
self.restore_geometry(gprefs, 'single-cover-fetch-dialog-geometry')
def cleanup(self):
self.covers_widget.cleanup()
def reject(self):
self.save_geometry(gprefs, 'single-cover-fetch-dialog-geometry')
self.covers_widget.cancel()
return QDialog.reject(self)
def accept(self, *args):
self.save_geometry(gprefs, 'single-cover-fetch-dialog-geometry')
self.cover_pixmap = self.covers_widget.cover_pixmap()
QDialog.accept(self)
def start(self, title, authors, identifiers):
book = Metadata(title, authors)
book.identifiers = identifiers
self.covers_widget.start(book, self.current_cover,
title, authors, {})
return self.exec()
def view_log(self):
self._lv = LogViewer(self.log, self)
# }}}
if __name__ == '__main__':
from calibre.gui2 import Application
DEBUG_DIALOG = True
app = Application([])
d = FullFetch()
d.start(title='great gatsby', authors=['fitzgerald'], identifiers={})
| 44,537 | Python | .py | 1,056 | 31.892992 | 154 | 0.596866 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,815 | basic_widgets.py | kovidgoyal_calibre/src/calibre/gui2/metadata/basic_widgets.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os
import re
import shutil
import textwrap
import weakref
from datetime import date, datetime
from qt.core import (
QAbstractItemView,
QAction,
QApplication,
QComboBox,
QDateTime,
QDialog,
QDialogButtonBox,
QDoubleSpinBox,
QGridLayout,
QIcon,
QKeySequence,
QLabel,
QLineEdit,
QListWidgetItem,
QMenu,
QMessageBox,
QPixmap,
QPlainTextEdit,
QSize,
QSizePolicy,
Qt,
QToolButton,
QUndoCommand,
QUndoStack,
QUrl,
QVBoxLayout,
QWidget,
pyqtSignal,
)
from calibre import strftime
from calibre.constants import iswindows
from calibre.customize.ui import run_plugins_on_import
from calibre.db import SPOOL_SIZE
from calibre.ebooks import BOOK_EXTENSIONS
from calibre.ebooks.metadata import authors_to_sort_string, check_isbn, string_to_authors, title_sort
from calibre.ebooks.metadata.meta import get_metadata
from calibre.gui2 import choose_files_and_remember_all_files, choose_images, error_dialog, file_icon_provider, gprefs
from calibre.gui2.comments_editor import Editor
from calibre.gui2.complete2 import EditWithComplete
from calibre.gui2.dialogs.tag_editor import TagEditor
from calibre.gui2.languages import LanguagesEdit as LE
from calibre.gui2.widgets import EnLineEdit, ImageView, LineEditIndicators
from calibre.gui2.widgets import FormatList as _FormatList
from calibre.gui2.widgets2 import DateTimeEdit, Dialog, RatingEditor, RightClickButton, access_key, populate_standard_spinbox_context_menu
from calibre.library.comments import comments_to_html
from calibre.ptempfile import PersistentTemporaryFile, SpooledTemporaryFile
from calibre.utils.config import prefs, tweaks
from calibre.utils.date import (
UNDEFINED_DATE,
as_local_time,
internal_iso_format_string,
is_date_undefined,
local_tz,
parse_only_date,
qt_from_dt,
qt_to_dt,
utcfromtimestamp,
)
from calibre.utils.filenames import make_long_path_useable
from calibre.utils.icu import sort_key, strcmp
from calibre.utils.localization import ngettext
from polyglot.builtins import iteritems
def save_dialog(parent, title, msg, det_msg=''):
d = QMessageBox(parent)
d.setWindowTitle(title)
d.setText(msg)
d.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No | QMessageBox.StandardButton.Cancel)
return d.exec()
def clean_text(x):
return re.sub(r'\s', ' ', x.strip(), flags=re.ASCII)
'''
The interface common to all widgets used to set basic metadata
class BasicMetadataWidget:
LABEL = "label text"
def initialize(self, db, id_):
pass
def commit(self, db, id_):
return True
@property
def current_val(self):
return None
@current_val.setter
def current_val(self, val):
pass
'''
class ToMetadataMixin:
FIELD_NAME = None
allow_undo = False
def apply_to_metadata(self, mi):
mi.set(self.FIELD_NAME, self.current_val)
def set_value(self, val, allow_undo=True):
self.allow_undo = allow_undo
try:
self.current_val = val
finally:
self.allow_undo = False
def set_text(self, text):
if self.allow_undo:
self.selectAll(), self.insert(text)
else:
self.setText(text)
def set_edit_text(self, text):
if self.allow_undo:
orig, self.disable_popup = self.disable_popup, True
try:
self.lineEdit().selectAll(), self.lineEdit().insert(text)
finally:
self.disable_popup = orig
else:
self.setEditText(text)
def make_undoable(spinbox):
'Add a proper undo/redo capability to spinbox which must be a sub-class of QAbstractSpinBox'
class UndoCommand(QUndoCommand):
def __init__(self, widget, val):
QUndoCommand.__init__(self)
self.widget = weakref.ref(widget)
if hasattr(widget, 'dateTime'):
self.undo_val = widget.dateTime()
elif hasattr(widget, 'value'):
self.undo_val = widget.value()
if isinstance(val, date) and not isinstance(val, datetime):
val = parse_only_date(val.isoformat(), assume_utc=False, as_utc=False)
if isinstance(val, datetime):
val = qt_from_dt(val)
self.redo_val = val
def undo(self):
w = self.widget()
if hasattr(w, 'setDateTime'):
w.setDateTime(self.undo_val)
elif hasattr(w, 'setValue'):
w.setValue(self.undo_val)
def redo(self):
w = self.widget()
if hasattr(w, 'setDateTime'):
w.setDateTime(self.redo_val)
elif hasattr(w, 'setValue'):
w.setValue(self.redo_val)
class UndoableSpinbox(spinbox):
def __init__(self, parent=None):
spinbox.__init__(self, parent)
self.undo_stack = QUndoStack(self)
self.undo, self.redo = self.undo_stack.undo, self.undo_stack.redo
def keyPressEvent(self, ev):
if ev == QKeySequence.StandardKey.Undo:
self.undo()
return ev.accept()
if ev == QKeySequence.StandardKey.Redo:
self.redo()
return ev.accept()
return spinbox.keyPressEvent(self, ev)
def contextMenuEvent(self, ev):
m = QMenu(self)
if hasattr(self, 'setDateTime'):
m.addAction(_('Set date to undefined') + '\t' + QKeySequence(Qt.Key.Key_Minus).toString(QKeySequence.SequenceFormat.NativeText),
lambda : self.setDateTime(self.minimumDateTime()))
m.addAction(_('Set date to today') + '\t' + QKeySequence(Qt.Key.Key_Equal).toString(QKeySequence.SequenceFormat.NativeText),
lambda : self.setDateTime(QDateTime.currentDateTime()))
m.addAction(_('&Undo') + access_key(QKeySequence.StandardKey.Undo), self.undo).setEnabled(self.undo_stack.canUndo())
m.addAction(_('&Redo') + access_key(QKeySequence.StandardKey.Redo), self.redo).setEnabled(self.undo_stack.canRedo())
m.addSeparator()
populate_standard_spinbox_context_menu(self, m)
m.popup(ev.globalPos())
def set_spinbox_value(self, val):
if self.allow_undo:
cmd = UndoCommand(self, val)
self.undo_stack.push(cmd)
else:
self.undo_stack.clear()
if hasattr(self, 'setDateTime'):
if isinstance(val, date) and not isinstance(val, datetime) and not is_date_undefined(val):
val = parse_only_date(val.isoformat(), assume_utc=False, as_utc=False)
if isinstance(val, datetime):
val = qt_from_dt(val)
self.setDateTime(val)
elif hasattr(self, 'setValue'):
self.setValue(val)
return UndoableSpinbox
# Title {{{
class TitleEdit(EnLineEdit, ToMetadataMixin):
TITLE_ATTR = FIELD_NAME = 'title'
TOOLTIP = _('Change the title of this book')
LABEL = _('&Title:')
data_changed = pyqtSignal()
def __init__(self, parent):
self.dialog = parent
EnLineEdit.__init__(self, parent)
self.setToolTip(self.TOOLTIP)
self.setWhatsThis(self.TOOLTIP)
self.textChanged.connect(self.data_changed)
def get_default(self):
return _('Unknown')
def initialize(self, db, id_):
title = getattr(db, self.TITLE_ATTR)(id_, index_is_id=True)
self.current_val = title
self.original_val = self.current_val
@property
def changed(self):
return self.original_val != self.current_val
def commit(self, db, id_):
title = self.current_val
if self.changed:
# Only try to commit if changed. This allow setting of other fields
# to work even if some of the book files are opened in windows.
getattr(db, 'set_'+ self.TITLE_ATTR)(id_, title, notify=False)
@property
def current_val(self):
title = clean_text(str(self.text()))
if not title:
title = self.get_default()
return title.strip()
@current_val.setter
def current_val(self, val):
if hasattr(val, 'strip'):
val = val.strip()
if not val:
val = self.get_default()
self.set_text(val)
self.setCursorPosition(0)
def break_cycles(self):
self.dialog = None
class TitleSortEdit(TitleEdit, ToMetadataMixin, LineEditIndicators):
TITLE_ATTR = FIELD_NAME = 'title_sort'
TOOLTIP = _('Specify how this book should be sorted when by title.'
' For example, The Exorcist might be sorted as Exorcist, The.')
LABEL = _('Title &sort:')
def __init__(self, parent, title_edit, autogen_button, languages_edit):
TitleEdit.__init__(self, parent)
self.setup_status_actions()
self.title_edit = title_edit
self.languages_edit = languages_edit
base = self.TOOLTIP
ok_tooltip = '<p>' + textwrap.fill(base+'<br><br>' + _(
' The ok icon indicates that the current '
'title sort matches the current title'))
bad_tooltip = '<p>'+textwrap.fill(base + '<br><br>' + _(
' The error icon warns that the current '
'title sort does not match the current title. '
'No action is required if this is what you want.'))
self.tooltips = (ok_tooltip, bad_tooltip)
self.title_edit.textChanged.connect(self.update_state_and_val, type=Qt.ConnectionType.QueuedConnection)
self.textChanged.connect(self.update_state)
self.autogen_button = autogen_button
autogen_button.clicked.connect(self.auto_generate)
languages_edit.editTextChanged.connect(self.update_state)
languages_edit.currentIndexChanged.connect(self.update_state)
self.update_state()
@property
def changed(self):
return self.title_edit.changed or self.original_val != self.current_val
@property
def book_lang(self):
try:
book_lang = self.languages_edit.lang_codes[0]
except:
book_lang = None
return book_lang
def update_state_and_val(self):
# Handle case change if the title's case and nothing else was changed
ts = title_sort(self.title_edit.current_val, lang=self.book_lang)
if strcmp(ts, self.current_val) == 0:
self.current_val = ts
self.update_state()
def update_state(self, *args):
ts = title_sort(self.title_edit.current_val, lang=self.book_lang)
normal = ts == self.current_val
tt = self.tooltips[0 if normal else 1]
self.update_status_actions(normal, tt)
self.setToolTip(tt)
self.setWhatsThis(tt)
def auto_generate(self, *args):
self.set_value(title_sort(self.title_edit.current_val,
lang=self.book_lang))
def break_cycles(self):
try:
self.title_edit.textChanged.disconnect()
except:
pass
try:
self.textChanged.disconnect()
except:
pass
try:
self.autogen_button.clicked.disconnect()
except:
pass
# }}}
# Authors {{{
class AuthorsEdit(EditWithComplete, ToMetadataMixin):
TOOLTIP = ''
LABEL = _('&Author(s):')
FIELD_NAME = 'authors'
data_changed = pyqtSignal()
def __init__(self, parent, manage_authors):
self.dialog = parent
self.books_to_refresh = set()
EditWithComplete.__init__(self, parent)
self.set_clear_button_enabled(False)
self.setToolTip(self.TOOLTIP)
self.setWhatsThis(self.TOOLTIP)
self.setEditable(True)
self.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
self.manage_authors_signal = manage_authors
manage_authors.triggered.connect(self.manage_authors)
self.lineEdit().createStandardContextMenu = self.createStandardContextMenu
self.lineEdit().textChanged.connect(self.data_changed)
def createStandardContextMenu(self):
menu = QLineEdit.createStandardContextMenu(self.lineEdit())
menu.addSeparator()
menu.addAction(_('&Edit authors'), self.edit_authors)
return menu
def edit_authors(self):
all_authors = self.lineEdit().all_items
current_authors = self.current_val
from calibre.gui2.dialogs.authors_edit import AuthorsEdit
d = AuthorsEdit(all_authors, current_authors, self)
if d.exec() == QDialog.DialogCode.Accepted:
self.set_value(d.authors)
def manage_authors(self):
if self.original_val != self.current_val:
d = save_dialog(self, _('Authors changed'),
_('You have changed the authors for this book. You must save '
'these changes before you can use Manage authors. Do you '
'want to save these changes?'))
if d == QMessageBox.StandardButton.Cancel:
return
if d == QMessageBox.StandardButton.Yes:
try:
self.commit(self.db, self.id_)
except OSError as e:
e.locking_violation_msg = _('Could not change on-disk location of this book\'s files.')
raise
self.db.commit()
self.original_val = self.current_val
else:
self.current_val = self.original_val
first_author = self.current_val[0] if len(self.current_val) else None
first_author_id = self.db.get_author_id(first_author) if first_author else None
self.dialog.parent().do_author_sort_edit(self, first_author_id,
select_sort=False)
self.initialize(self.db, self.id_)
self.dialog.author_sort.initialize(self.db, self.id_)
self.dialog.author_sort.update_state()
def get_default(self):
return _('Unknown')
@property
def changed(self):
return self.original_val != self.current_val
def initialize(self, db, id_):
self.books_to_refresh = set()
self.set_separator('&')
self.set_space_before_sep(True)
self.set_add_separator(tweaks['authors_completer_append_separator'])
self.update_items_cache(db.new_api.all_field_names('authors'))
au = db.authors(id_, index_is_id=True)
if not au:
au = _('Unknown')
self.current_val = [a.strip().replace('|', ',') for a in au.split(',')]
self.original_val = self.current_val
self.id_ = id_
self.db = db
def commit(self, db, id_):
authors = self.current_val
if authors != self.original_val:
# Only try to commit if changed. This allow setting of other fields
# to work even if some of the book files are opened in windows.
self.books_to_refresh |= db.set_authors(id_, authors, notify=False,
allow_case_change=True)
@property
def current_val(self):
au = clean_text(str(self.text()))
if not au:
au = self.get_default()
return string_to_authors(au)
@current_val.setter
def current_val(self, val):
if not val:
val = [self.get_default()]
self.set_edit_text(' & '.join([x.strip() for x in val]))
self.lineEdit().setCursorPosition(0)
def break_cycles(self):
self.db = self.dialog = None
try:
self.manage_authors_signal.triggered.disconnect()
except:
pass
class AuthorSortEdit(EnLineEdit, ToMetadataMixin, LineEditIndicators):
TOOLTIP = _('Specify how the author(s) of this book should be sorted. '
'For example Charles Dickens should be sorted as Dickens, '
'Charles.\nIf the box is colored green, then text matches '
'the individual author\'s sort strings. If it is colored '
'red, then the authors and this text do not match.')
LABEL = _('Author s&ort:')
FIELD_NAME = 'author_sort'
data_changed = pyqtSignal()
def __init__(self, parent, authors_edit, autogen_button, db,
copy_a_to_as_action, copy_as_to_a_action, a_to_as, as_to_a):
EnLineEdit.__init__(self, parent)
self.setup_status_actions()
self.authors_edit = authors_edit
self.db = db
base = self.TOOLTIP
ok_tooltip = '<p>' + textwrap.fill(base+'<br><br>' + _(
' The ok icon indicates that the current '
'author sort matches the current author'))
bad_tooltip = '<p>'+textwrap.fill(base + '<br><br>'+ _(
' The error icon indicates that the current '
'author sort does not match the current author. '
'No action is required if this is what you want.'))
self.tooltips = (ok_tooltip, bad_tooltip)
self.authors_edit.editTextChanged.connect(self.update_state_and_val, type=Qt.ConnectionType.QueuedConnection)
self.textChanged.connect(self.update_state)
self.textChanged.connect(self.data_changed)
self.autogen_button = autogen_button
self.copy_a_to_as_action = copy_a_to_as_action
self.copy_as_to_a_action = copy_as_to_a_action
autogen_button.clicked.connect(self.auto_generate)
copy_a_to_as_action.triggered.connect(self.auto_generate)
copy_as_to_a_action.triggered.connect(self.copy_to_authors)
a_to_as.triggered.connect(self.author_to_sort)
as_to_a.triggered.connect(self.sort_to_author)
self.original_val = ''
self.first_time = True
self.update_state()
@property
def current_val(self):
return clean_text(str(self.text()))
@current_val.setter
def current_val(self, val):
if not val:
val = ''
self.set_text(val.strip())
self.setCursorPosition(0)
def update_state_and_val(self):
# Handle case change if the authors box changed
aus = authors_to_sort_string(self.authors_edit.current_val)
if not self.first_time and strcmp(aus, self.current_val) == 0:
self.current_val = aus
self.first_time = False
self.update_state()
def author_sort_from_authors(self, authors):
return self.db.new_api.author_sort_from_authors(authors, key_func=lambda x: x)
def update_state(self, *args):
au = str(self.authors_edit.text())
au = re.sub(r'\s+et al\.$', '', au)
au = self.author_sort_from_authors(string_to_authors(au))
normal = au == self.current_val
tt = self.tooltips[0 if normal else 1]
self.update_status_actions(normal, tt)
self.setToolTip(tt)
self.setWhatsThis(tt)
def copy_to_authors(self):
aus = self.current_val
meth = tweaks['author_sort_copy_method']
if aus:
ans = []
for one in [a.strip() for a in aus.split('&')]:
if not one:
continue
ln, _, rest = one.partition(',')
if rest:
if meth in ('invert', 'nocomma', 'comma'):
one = rest.strip() + ' ' + ln.strip()
ans.append(one)
self.authors_edit.set_value(ans)
def auto_generate(self, *args):
au = str(self.authors_edit.text())
au = re.sub(r'\s+et al\.$', '', au).strip()
authors = string_to_authors(au)
self.set_value(self.author_sort_from_authors(authors))
def author_to_sort(self, *args):
au = str(self.authors_edit.text())
au = re.sub(r'\s+et al\.$', '', au).strip()
if au:
self.set_value(au)
def sort_to_author(self, *args):
aus = self.current_val
if aus:
self.authors_edit.set_value([aus])
def initialize(self, db, id_):
self.current_val = db.author_sort(id_, index_is_id=True)
self.original_val = self.current_val
self.first_time = True
def commit(self, db, id_):
aus = self.current_val
if aus != self.original_val or self.authors_edit.original_val != self.authors_edit.current_val:
db.set_author_sort(id_, aus, notify=False, commit=False)
return True
def break_cycles(self):
self.db = None
try:
self.authors_edit.editTextChanged.disconnect()
except:
pass
try:
self.textChanged.disconnect()
except:
pass
try:
self.autogen_button.clicked.disconnect()
except:
pass
try:
self.copy_a_to_as_action.triggered.disconnect()
except:
pass
try:
self.copy_as_to_a_action.triggered.disconnect()
except:
pass
self.authors_edit = None
# }}}
# Series {{{
class SeriesEdit(EditWithComplete, ToMetadataMixin):
TOOLTIP = _('List of known series. You can add new series.')
LABEL = _('&Series:')
FIELD_NAME = 'series'
data_changed = pyqtSignal()
editor_requested = pyqtSignal()
def __init__(self, parent):
EditWithComplete.__init__(self, parent, sort_func=title_sort)
self.set_clear_button_enabled(False)
self.set_separator(None)
self.dialog = parent
self.setSizeAdjustPolicy(
QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
self.setToolTip(self.TOOLTIP)
self.setWhatsThis(self.TOOLTIP)
self.setEditable(True)
self.books_to_refresh = set()
self.lineEdit().textChanged.connect(self.data_changed)
@property
def current_val(self):
return clean_text(str(self.currentText()))
@current_val.setter
def current_val(self, val):
if not val:
val = ''
self.set_edit_text(val.strip())
self.lineEdit().setCursorPosition(0)
def initialize(self, db, id_):
self.books_to_refresh = set()
self.update_items_cache(db.new_api.all_field_names('series'))
series = db.new_api.field_for('series', id_)
self.current_val = self.original_val = series or ''
def commit(self, db, id_):
series = self.current_val
if series != self.original_val:
self.books_to_refresh |= db.set_series(id_, series, notify=False, commit=True, allow_case_change=True)
@property
def changed(self):
return self.current_val != self.original_val
def break_cycles(self):
self.dialog = None
def edit(self, db, id_):
if self.changed:
d = save_dialog(self, _('Series changed'),
_('You have changed the series. In order to use the category'
' editor, you must either discard or apply these '
'changes. Apply changes?'))
if d == QMessageBox.StandardButton.Cancel:
return
if d == QMessageBox.StandardButton.Yes:
self.commit(db, id_)
db.commit()
self.original_val = self.current_val
else:
self.current_val = self.original_val
from calibre.gui2.ui import get_gui
get_gui().do_tags_list_edit(self.current_val, 'series')
db = get_gui().current_db
self.update_items_cache(db.new_api.all_field_names('series'))
self.initialize(db, id_)
def keyPressEvent(self, ev):
if ev.key() == Qt.Key.Key_F2:
self.editor_requested.emit()
ev.accept()
return
return EditWithComplete.keyPressEvent(self, ev)
class SeriesIndexEdit(make_undoable(QDoubleSpinBox), ToMetadataMixin):
TOOLTIP = ''
LABEL = _('&Number:')
FIELD_NAME = 'series_index'
data_changed = pyqtSignal()
def __init__(self, parent, series_edit):
super().__init__(parent)
self.valueChanged.connect(self.data_changed)
self.dialog = parent
self.db = self.original_series_name = None
self.setMaximum(10000000)
self.series_edit = series_edit
series_edit.currentIndexChanged.connect(self.enable)
series_edit.editTextChanged.connect(self.enable)
series_edit.lineEdit().editingFinished.connect(self.increment)
self.enable()
def enable(self, *args):
self.setEnabled(bool(self.series_edit.current_val))
@property
def current_val(self):
return self.value()
@current_val.setter
def current_val(self, val):
if val is None:
val = 1.0
val = float(val)
self.set_spinbox_value(val)
def initialize(self, db, id_):
self.db = db
if self.series_edit.current_val:
val = db.series_index(id_, index_is_id=True)
else:
val = 1.0
self.current_val = val
self.original_val = self.current_val
self.original_series_name = self.series_edit.original_val
def commit(self, db, id_):
if self.series_edit.original_val != self.series_edit.current_val or self.current_val != self.original_val:
db.set_series_index(id_, self.current_val, notify=False, commit=False)
def increment(self):
if tweaks['series_index_auto_increment'] != 'no_change' and self.db is not None:
try:
series = self.series_edit.current_val
if series and series != self.original_series_name:
ns = 1.0
if tweaks['series_index_auto_increment'] != 'const':
ns = self.db.get_next_series_num_for(series)
self.current_val = ns
self.original_series_name = series
except:
import traceback
traceback.print_exc()
def reset_original(self):
self.original_series_name = self.series_edit.current_val
def break_cycles(self):
try:
self.series_edit.currentIndexChanged.disconnect()
except:
pass
try:
self.series_edit.editTextChanged.disconnect()
except:
pass
try:
self.series_edit.lineEdit().editingFinished.disconnect()
except:
pass
self.db = self.series_edit = self.dialog = None
# }}}
class BuddyLabel(QLabel): # {{{
def __init__(self, buddy):
QLabel.__init__(self, buddy.LABEL)
self.setBuddy(buddy)
self.setAlignment(Qt.AlignmentFlag.AlignRight|Qt.AlignmentFlag.AlignVCenter)
# }}}
# Formats {{{
class Format(QListWidgetItem):
def __init__(self, parent, ext, size, path=None, timestamp=None):
self.path = path
self.ext = ext
self.size = float(size)/(1024*1024)
text = '%s (%.2f MB)'%(self.ext.upper(), self.size)
QListWidgetItem.__init__(self, file_icon_provider().icon_from_ext(ext),
text, parent, QListWidgetItem.ItemType.UserType.value)
if timestamp is not None:
ts = timestamp.astimezone(local_tz)
t = strftime('%a, %d %b %Y [%H:%M:%S]', ts.timetuple())
text = _('Last modified: %s\n\nDouble click to view')%t
self.setToolTip(text)
self.setStatusTip(text)
class OrigAction(QAction):
restore_fmt = pyqtSignal(object)
def __init__(self, fmt, parent):
self.fmt = fmt.replace('ORIGINAL_', '')
QAction.__init__(self, _('Restore %s from the original')%self.fmt, parent)
self.triggered.connect(self._triggered)
def _triggered(self):
self.restore_fmt.emit(self.fmt)
class ViewAction(QAction):
view_fmt = pyqtSignal(object)
def __init__(self, item, parent):
self.item = item
QAction.__init__(self, _('&View {} format').format(item.ext.upper()), parent)
self.triggered.connect(self._triggered)
def _triggered(self):
self.view_fmt.emit(self.item)
class EditAction(QAction):
edit_fmt = pyqtSignal(object)
def __init__(self, item, parent):
self.item = item
QAction.__init__(self, _('&Edit')+' '+item.ext.upper(), parent)
self.triggered.connect(self._triggered)
def _triggered(self):
self.edit_fmt.emit(self.item)
class FormatList(_FormatList):
restore_fmt = pyqtSignal(object)
view_fmt = pyqtSignal(object)
edit_fmt = pyqtSignal(object)
def __init__(self, parent):
_FormatList.__init__(self, parent)
self.setContextMenuPolicy(Qt.ContextMenuPolicy.DefaultContextMenu)
def sizeHint(self):
sz = self.iconSize()
return QSize(sz.width() * 7, sz.height() * 3)
def contextMenuEvent(self, event):
from calibre.ebooks.oeb.polish.main import SUPPORTED as EDIT_SUPPORTED
item = self.itemFromIndex(self.currentIndex())
originals = [self.item(x).ext.upper() for x in range(self.count())]
originals = [x for x in originals if x.startswith('ORIGINAL_')]
if item or originals:
self.cm = cm = QMenu(self)
if item:
action = ViewAction(item, cm)
action.view_fmt.connect(self.view_fmt, type=Qt.ConnectionType.QueuedConnection)
cm.addAction(action)
if item.ext.upper() in EDIT_SUPPORTED:
action = EditAction(item, cm)
action.edit_fmt.connect(self.edit_fmt, type=Qt.ConnectionType.QueuedConnection)
cm.addAction(action)
if item and originals:
cm.addSeparator()
for fmt in originals:
action = OrigAction(fmt, cm)
action.restore_fmt.connect(self.restore_fmt)
cm.addAction(action)
cm.popup(event.globalPos())
event.accept()
def remove_format(self, fmt):
for i in range(self.count()):
f = self.item(i)
if f.ext.upper() == fmt.upper():
self.takeItem(i)
break
class FormatsManager(QWidget):
data_changed = pyqtSignal()
ICON_SIZE = 32
@property
def changed(self):
return self._changed
@changed.setter
def changed(self, val):
self._changed = val
if val:
self.data_changed.emit()
def __init__(self, parent, copy_fmt):
QWidget.__init__(self, parent)
self.dialog = parent
self.copy_fmt = copy_fmt
self._changed = False
self.l = l = QGridLayout()
l.setContentsMargins(0, 0, 0, 0)
self.setLayout(l)
self.cover_from_format_button = QToolButton(self)
self.cover_from_format_button.setToolTip(
_('Set the cover for the book from the selected format'))
self.cover_from_format_button.setIcon(QIcon.ic('default_cover.png'))
self.cover_from_format_button.setIconSize(QSize(self.ICON_SIZE, self.ICON_SIZE))
self.metadata_from_format_button = QToolButton(self)
self.metadata_from_format_button.setIcon(QIcon.ic('edit_input.png'))
self.metadata_from_format_button.setIconSize(QSize(self.ICON_SIZE, self.ICON_SIZE))
self.metadata_from_format_button.setToolTip(
_('Set metadata for the book from the selected format'))
self.add_format_button = QToolButton(self)
self.add_format_button.setIcon(QIcon.ic('add_book.png'))
self.add_format_button.setIconSize(QSize(self.ICON_SIZE, self.ICON_SIZE))
self.add_format_button.clicked.connect(self.add_format)
self.add_format_button.setToolTip(
_('Add a format to this book'))
self.remove_format_button = QToolButton(self)
self.remove_format_button.setIcon(QIcon.ic('trash.png'))
self.remove_format_button.setIconSize(QSize(self.ICON_SIZE, self.ICON_SIZE))
self.remove_format_button.clicked.connect(self.remove_format)
self.remove_format_button.setToolTip(
_('Remove the selected format from this book'))
self.formats = FormatList(self)
self.formats.setAcceptDrops(True)
self.formats.formats_dropped.connect(self.formats_dropped)
self.formats.restore_fmt.connect(self.restore_fmt)
self.formats.view_fmt.connect(self.show_format)
self.formats.edit_fmt.connect(self.edit_format)
self.formats.delete_format.connect(self.remove_format)
self.formats.itemDoubleClicked.connect(self.show_format)
self.formats.setDragDropMode(QAbstractItemView.DragDropMode.DropOnly)
self.formats.setIconSize(QSize(self.ICON_SIZE, self.ICON_SIZE))
l.addWidget(self.cover_from_format_button, 0, 0, 1, 1)
l.addWidget(self.metadata_from_format_button, 2, 0, 1, 1)
l.addWidget(self.add_format_button, 0, 2, 1, 1)
l.addWidget(self.remove_format_button, 2, 2, 1, 1)
l.addWidget(self.formats, 0, 1, 3, 1)
self.temp_files = []
def initialize(self, db, id_):
self.changed = False
self.formats.clear()
exts = db.formats(id_, index_is_id=True)
self.original_val = set()
if exts:
exts = exts.split(',')
for ext in exts:
if not ext:
ext = ''
size = db.sizeof_format(id_, ext, index_is_id=True)
timestamp = db.format_last_modified(id_, ext)
if size is None:
continue
Format(self.formats, ext, size, timestamp=timestamp)
self.original_val.add(ext.lower())
def apply_to_metadata(self, mi):
pass
def commit(self, db, id_):
if not self.changed:
return
old_extensions, new_extensions, paths = set(), set(), {}
for row in range(self.formats.count()):
fmt = self.formats.item(row)
ext, path = fmt.ext.lower(), fmt.path
if 'unknown' in ext.lower():
ext = None
if path:
new_extensions.add(ext)
paths[ext] = path
else:
old_extensions.add(ext)
for ext in new_extensions:
with SpooledTemporaryFile(SPOOL_SIZE) as spool:
with open(paths[ext], 'rb') as f:
shutil.copyfileobj(f, spool)
spool.seek(0)
db.add_format(id_, ext, spool, notify=False,
index_is_id=True)
dbfmts = db.formats(id_, index_is_id=True)
db_extensions = {fl.lower() for fl in (dbfmts.split(',') if dbfmts
else [])}
extensions = new_extensions.union(old_extensions)
for ext in db_extensions:
if ext not in extensions and ext in self.original_val:
db.remove_format(id_, ext, notify=False, index_is_id=True)
self.changed = False
return
def add_format(self, *args):
files = choose_files_and_remember_all_files(
self, 'add formats dialog', _("Choose formats for ") + self.dialog.title.current_val,
[(_('Books'), BOOK_EXTENSIONS)])
self._add_formats(files)
def restore_fmt(self, fmt):
pt = PersistentTemporaryFile(suffix='_restore_fmt.'+fmt.lower())
ofmt = 'ORIGINAL_'+fmt
with pt:
self.copy_fmt(ofmt, pt)
self._add_formats((pt.name,))
self.temp_files.append(pt.name)
self.changed = True
self.formats.remove_format(ofmt)
def _add_formats(self, paths):
added = False
if not paths:
return added
bad_perms = []
for _file in paths:
_file = make_long_path_useable(os.path.abspath(_file))
if iswindows:
from calibre.gui2.add import resolve_windows_links
x = list(resolve_windows_links([_file], hwnd=int(self.effectiveWinId())))
if x:
_file = x[0]
if not os.access(_file, os.R_OK):
bad_perms.append(_file)
continue
nfile = run_plugins_on_import(_file)
if nfile is not None:
_file = make_long_path_useable(nfile)
stat = os.stat(_file)
size = stat.st_size
ext = os.path.splitext(_file)[1].lower().replace('.', '')
timestamp = utcfromtimestamp(stat.st_mtime)
for row in range(self.formats.count()):
fmt = self.formats.item(row)
if fmt.ext.lower() == ext:
self.formats.takeItem(row)
break
Format(self.formats, ext, size, path=_file, timestamp=timestamp)
self.changed = True
added = True
if bad_perms:
error_dialog(self, _('No permission'),
_('You do not have '
'permission to read the following files:'),
det_msg='\n'.join(bad_perms), show=True)
return added
def formats_dropped(self, event, paths):
if self._add_formats(paths):
event.accept()
def remove_format(self, *args):
rows = self.formats.selectionModel().selectedRows(0)
for row in rows:
self.formats.takeItem(row.row())
self.changed = True
def show_format(self, item, *args):
self.dialog.do_view_format(item.path, item.ext)
def edit_format(self, item, *args):
from calibre.gui2.widgets import BusyCursor
with BusyCursor():
self.dialog.do_edit_format(item.path, item.ext)
def get_selected_format(self):
row = self.formats.currentRow()
fmt = self.formats.item(row)
if fmt is None:
if self.formats.count() == 1:
fmt = self.formats.item(0)
if fmt is None:
error_dialog(self, _('No format selected'),
_('No format selected')).exec()
return None
return fmt.ext.lower()
def get_format_path(self, db, id_, fmt):
for i in range(self.formats.count()):
f = self.formats.item(i)
ext = f.ext.lower()
if ext == fmt:
if f.path is None:
return db.format(id_, ext, as_path=True, index_is_id=True)
return f.path
def get_selected_format_metadata(self, db, id_):
old = prefs['read_file_metadata']
if not old:
prefs['read_file_metadata'] = True
try:
row = self.formats.currentRow()
fmt = self.formats.item(row)
if fmt is None:
if self.formats.count() == 1:
fmt = self.formats.item(0)
if fmt is None:
error_dialog(self, _('No format selected'),
_('No format selected')).exec()
return None, None
ext = fmt.ext.lower()
if fmt.path is None:
stream = db.format(id_, ext, as_file=True, index_is_id=True)
else:
stream = open(fmt.path, 'rb')
try:
with stream:
mi = get_metadata(stream, ext)
return mi, ext
except:
import traceback
error_dialog(self, _('Could not read metadata'),
_('Could not read metadata from %s format')%ext.upper(),
det_msg=traceback.format_exc(), show=True)
return None, None
finally:
if old != prefs['read_file_metadata']:
prefs['read_file_metadata'] = old
def break_cycles(self):
self.dialog = None
self.copy_fmt = None
for name in self.temp_files:
try:
os.remove(name)
except:
pass
self.temp_files = []
# }}}
class Cover(ImageView): # {{{
download_cover = pyqtSignal()
data_changed = pyqtSignal()
def __init__(self, parent):
ImageView.__init__(self, parent, show_size_pref_name='edit_metadata_cover_widget', default_show_size=True)
self.dialog = parent
self._cdata = None
self.draw_border = False
self.cdata_before_trim = self.cdata_before_generate = None
self.cover_changed.connect(self.set_pixmap_from_data)
class CB(RightClickButton):
def __init__(self, text, icon=None, action=None):
RightClickButton.__init__(self, parent)
self.setText(text)
if icon is not None:
self.setIcon(QIcon.ic(icon))
self.setSizePolicy(QSizePolicy.Policy.MinimumExpanding, QSizePolicy.Policy.Maximum)
self.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
if action is not None:
self.clicked.connect(action)
self.select_cover_button = CB(_('&Browse'), 'document_open.png', self.select_cover)
self.trim_cover_button = b = CB(_('Trim bord&ers'), 'trim.png')
b.setToolTip(_(
'Automatically detect and remove extra space at the cover\'s edges.\n'
'Pressing it repeatedly can sometimes remove stubborn borders.'))
b.m = m = QMenu(b)
b.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
m.addAction(QIcon.ic('trim.png'), _('Automatically trim borders'), self.trim_cover)
m.addSeparator()
m.addAction(_('Trim borders manually'), self.manual_trim_cover)
m.addAction(QIcon.ic('edit-undo.png'), _('Undo last trim'), self.undo_trim)
b.setMenu(m)
self.remove_cover_button = CB(_('&Remove'), 'trash.png', self.remove_cover)
self.download_cover_button = CB(_('Download co&ver'), 'arrow-down.png', self.download_cover)
self.generate_cover_button = b = CB(_('&Generate cover'), 'default_cover.png', self.generate_cover)
b.m = m = QMenu(b)
b.setMenu(m)
m.addAction(QIcon.ic('config.png'), _('Customize the styles and colors of the generated cover'), self.custom_cover)
m.addAction(QIcon.ic('edit-undo.png'), _('Undo last Generate cover'), self.undo_generate)
b.setPopupMode(QToolButton.ToolButtonPopupMode.DelayedPopup)
self.buttons = [self.select_cover_button, self.remove_cover_button,
self.trim_cover_button, self.download_cover_button,
self.generate_cover_button]
self.frame_size = (300, 400)
self.setSizePolicy(QSizePolicy(QSizePolicy.Policy.Preferred,
QSizePolicy.Policy.Preferred))
def undo_trim(self):
if self.cdata_before_trim:
self.current_val = self.cdata_before_trim
self.cdata_before_trim = None
def undo_generate(self):
if self.cdata_before_generate:
self.current_val = self.cdata_before_generate
self.cdata_before_generate = None
def frame_resized(self, ev):
sz = ev.size()
self.frame_size = (sz.width()//3, sz.height())
def sizeHint(self):
sz = QSize(self.frame_size[0], self.frame_size[1])
return sz
def select_cover(self, *args):
files = choose_images(
self, 'change cover dialog', _('Choose cover for ') + self.dialog.title.current_val)
if not files:
return
_file = files[0]
if _file:
_file = make_long_path_useable(os.path.abspath(_file))
if not os.access(_file, os.R_OK):
d = error_dialog(self, _('Cannot read'),
_('You do not have permission to read the file: ') + _file)
d.exec()
return
cover = None
try:
with open(_file, "rb") as f:
cover = f.read()
except OSError as e:
d = error_dialog(
self, _('Error reading file'),
_("<p>There was an error reading from file: <br /><b>") + _file + "</b></p><br />"+str(e))
d.exec()
if cover:
orig = self.current_val
self.current_val = cover
if self.current_val is None:
self.current_val = orig
error_dialog(self,
_("Not a valid picture"),
_file + _(" is not a valid picture"), show=True)
def remove_cover(self, *args):
self.current_val = None
def trim_cover(self, *args):
cdata = self.current_val
if not cdata:
return
from calibre.utils.img import image_from_data, image_to_data, remove_borders_from_image
img = image_from_data(cdata)
nimg = remove_borders_from_image(img)
if nimg is not img:
self.current_val = image_to_data(nimg, fmt='png')
self.cdata_before_trim = cdata
def manual_trim_cover(self):
cdata = self.current_val
from calibre.gui2.dialogs.trim_image import TrimImage
d = TrimImage(cdata, parent=self)
if d.exec() == QDialog.DialogCode.Accepted and d.image_data is not None:
self.current_val = d.image_data
self.cdata_before_trim = cdata
def generate_cover(self, *args):
from calibre.ebooks.covers import generate_cover
mi = self.dialog.to_book_metadata()
self.cdata_before_generate = self.current_val
self.current_val = generate_cover(mi)
def custom_cover(self):
from calibre.ebooks.covers import generate_cover
from calibre.gui2.covers import CoverSettingsDialog
mi = self.dialog.to_book_metadata()
d = CoverSettingsDialog(mi=mi, parent=self)
if d.exec() == QDialog.DialogCode.Accepted:
self.current_val = generate_cover(mi, prefs=d.prefs_for_rendering)
def set_pixmap_from_data(self, data):
if not data:
self.current_val = None
return
orig = self.current_val
self.current_val = data
if self.current_val is None:
error_dialog(self, _('Invalid cover'),
_('Could not change cover as the image is invalid.'),
show=True)
self.current_val = orig
def initialize(self, db, id_):
self._cdata = None
self.cdata_before_trim = None
self.current_val = db.cover(id_, index_is_id=True)
self.original_val = self.current_val
@property
def changed(self):
return self.current_val != self.original_val
@property
def current_val(self):
return self._cdata
@current_val.setter
def current_val(self, cdata):
self._cdata = None
self.cdata_before_trim = None
pm = QPixmap()
if cdata:
pm.loadFromData(cdata)
if pm.isNull():
pm = QApplication.instance().cached_qpixmap('default_cover.png', device_pixel_ratio=self.devicePixelRatio())
else:
self._cdata = cdata
pm.setDevicePixelRatio(getattr(self, 'devicePixelRatioF', self.devicePixelRatio)())
self.setPixmap(pm)
tt = _('This book has no cover')
if self._cdata:
tt = _('Cover size: %(width)d x %(height)d pixels') % \
dict(width=pm.width(), height=pm.height())
self.setToolTip(tt)
self.data_changed.emit()
def commit(self, db, id_):
if self.changed:
if self.current_val:
db.set_cover(id_, self.current_val, notify=False, commit=False)
else:
db.remove_cover(id_, notify=False, commit=False)
def break_cycles(self):
try:
self.cover_changed.disconnect()
except:
pass
self.dialog = self._cdata = self.current_val = self.original_val = None
def apply_to_metadata(self, mi):
from calibre.utils.imghdr import what
cdata = self.current_val
if cdata:
mi.cover_data = (what(None, cdata), cdata)
# }}}
class CommentsEdit(Editor, ToMetadataMixin): # {{{
FIELD_NAME = 'comments'
toolbar_prefs_name = 'metadata-comments-editor-widget-hidden-toolbars'
@property
def current_val(self):
return self.html
@current_val.setter
def current_val(self, val):
if not val or not val.strip():
val = ''
else:
val = comments_to_html(val)
self.set_html(val, self.allow_undo)
self.wyswyg_dirtied()
self.data_changed.emit()
def initialize(self, db, id_):
path = db.abspath(id_, index_is_id=True)
if path:
self.set_base_url(QUrl.fromLocalFile(os.path.join(path, 'metadata.html')))
self.current_val = db.comments(id_, index_is_id=True)
self.original_val = self.current_val
def commit(self, db, id_):
val = self.current_val
if val != self.original_val:
db.set_comment(id_, self.current_val, notify=False, commit=False)
# }}}
class RatingEdit(RatingEditor, ToMetadataMixin): # {{{
LABEL = _('&Rating:')
TOOLTIP = _('Rating of this book. 0-5 stars')
FIELD_NAME = 'rating'
data_changed = pyqtSignal()
def __init__(self, parent):
super().__init__(parent)
self.setToolTip(self.TOOLTIP)
self.setWhatsThis(self.TOOLTIP)
self.currentTextChanged.connect(self.data_changed)
@property
def current_val(self):
return self.rating_value
@current_val.setter
def current_val(self, val):
self.rating_value = val
def initialize(self, db, id_):
val = db.rating(id_, index_is_id=True)
self.current_val = val
self.original_val = self.current_val
def commit(self, db, id_):
if self.current_val != self.original_val:
db.set_rating(id_, self.current_val, notify=False, commit=False)
return True
def zero(self):
self.setCurrentIndex(0)
# }}}
class TagsEdit(EditWithComplete, ToMetadataMixin): # {{{
LABEL = _('Ta&gs:')
TOOLTIP = '<p>'+_('Tags categorize the book. This is particularly '
'useful while searching. <br><br>They can be any words '
'or phrases, separated by commas.')
FIELD_NAME = 'tags'
data_changed = pyqtSignal()
tag_editor_requested = pyqtSignal()
def __init__(self, parent):
EditWithComplete.__init__(self, parent)
self.set_clear_button_enabled(False)
self.set_elide_mode(Qt.TextElideMode.ElideMiddle)
self.currentTextChanged.connect(self.data_changed)
self.lineEdit().setMaxLength(655360) # see https://bugs.launchpad.net/bugs/1630944
self.books_to_refresh = set()
self.setToolTip(self.TOOLTIP)
self.setWhatsThis(self.TOOLTIP)
@property
def current_val(self):
return [clean_text(x) for x in str(self.text()).split(',')]
@current_val.setter
def current_val(self, val):
if not val:
val = []
self.set_edit_text(', '.join([x.strip() for x in val]))
self.setCursorPosition(0)
def initialize(self, db, id_):
self.books_to_refresh = set()
tags = db.tags(id_, index_is_id=True)
tags = tags.split(',') if tags else []
self.current_val = tags
self.update_items_cache(db.new_api.all_field_names('tags'))
self.original_val = self.current_val
self.db = db
@property
def changed(self):
return self.current_val != self.original_val
def edit(self, db, id_):
ctrl_or_shift_pressed = (QApplication.keyboardModifiers() &
(Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.ShiftModifier))
if self.changed:
d = save_dialog(self, _('Tags changed'),
_('You have changed the tags. In order to use the tags'
' editor, you must either discard or apply these '
'changes. Apply changes?'))
if d == QMessageBox.StandardButton.Cancel:
return
if d == QMessageBox.StandardButton.Yes:
self.commit(db, id_)
db.commit()
self.original_val = self.current_val
else:
self.current_val = self.original_val
if ctrl_or_shift_pressed:
from calibre.gui2.ui import get_gui
get_gui().do_tags_list_edit(None, 'tags')
self.update_items_cache(self.db.new_api.all_field_names('tags'))
self.initialize(self.db, id_)
else:
d = TagEditor(self, db, id_)
if d.exec() == QDialog.DialogCode.Accepted:
self.current_val = d.tags
self.update_items_cache(db.new_api.all_field_names('tags'))
def commit(self, db, id_):
if self.changed:
self.books_to_refresh |= db.set_tags(
id_, self.current_val, notify=False, commit=False,
allow_case_change=True)
return True
def keyPressEvent(self, ev):
if ev.key() == Qt.Key.Key_F2:
self.tag_editor_requested.emit()
ev.accept()
return
return EditWithComplete.keyPressEvent(self, ev)
# }}}
class LanguagesEdit(LE, ToMetadataMixin): # {{{
LABEL = _('&Languages:')
TOOLTIP = _('A comma separated list of languages for this book')
FIELD_NAME = 'languages'
data_changed = pyqtSignal()
def __init__(self, *args, **kwargs):
LE.__init__(self, *args, **kwargs)
self.set_clear_button_enabled(False)
self.textChanged.connect(self.data_changed)
self.setToolTip(self.TOOLTIP)
@property
def current_val(self):
return self.lang_codes
@current_val.setter
def current_val(self, val):
self.set_lang_codes(val, self.allow_undo)
def initialize(self, db, id_):
self.init_langs(db)
lc = []
langs = db.languages(id_, index_is_id=True)
if langs:
lc = [x.strip() for x in langs.split(',')]
self.current_val = lc
self.original_val = self.current_val
def validate_for_commit(self):
bad = self.validate()
if bad:
msg = ngettext('The language %s is not recognized', 'The languages %s are not recognized', len(bad)) % (', '.join(bad))
return _('Unknown language'), msg, ''
return None, None, None
def commit(self, db, id_):
cv = self.current_val
if cv != self.original_val:
db.set_languages(id_, cv)
self.update_recently_used()
# }}}
# Identifiers {{{
class Identifiers(Dialog):
def __init__(self, identifiers, parent=None):
Dialog.__init__(self, _('Edit Identifiers'), 'edit-identifiers-dialog', parent=parent)
self.text.setPlainText('\n'.join(f'{k}:{identifiers[k]}' for k in sorted(identifiers, key=sort_key)))
def setup_ui(self):
self.l = l = QVBoxLayout(self)
self.la = la = QLabel(_(
'Edit the book\'s identifiers. Every identifier must be on a separate line, and have the form type:value'))
la.setWordWrap(True)
self.text = t = QPlainTextEdit(self)
l.addWidget(la), l.addWidget(t)
l.addWidget(self.bb)
def get_identifiers(self, validate=False):
from calibre.ebooks.metadata.book.base import Metadata
mi = Metadata('xxx')
ans = {}
for line in self.text.toPlainText().splitlines():
if line.strip():
k, v = line.partition(':')[0::2]
k, v = mi._clean_identifier(k.strip(), v.strip())
if k and v:
if validate and k in ans:
error_dialog(self, _('Duplicate identifier'), _(
'The identifier of type: %s occurs more than once. Each type of identifier must be unique') % k, show=True)
return
ans[k] = v
elif validate:
error_dialog(self, _('Invalid identifier'), _(
'The identifier %s is invalid. Identifiers must be of the form type:value') % line.strip(), show=True)
return
return ans
def sizeHint(self):
return QSize(500, 400)
def accept(self):
if self.get_identifiers(validate=True) is None:
return
Dialog.accept(self)
class IdentifiersEdit(QLineEdit, ToMetadataMixin, LineEditIndicators):
LABEL = _('&Ids:')
BASE_TT = _('Edit the identifiers for this book. '
'For example: \n\n%s\n\nIf an identifier value contains a comma, you can use the | character to represent it.')%(
'isbn:1565927249, doi:10.1000/182, amazon:1565927249')
FIELD_NAME = 'identifiers'
data_changed = pyqtSignal()
def __init__(self, parent):
QLineEdit.__init__(self, parent)
self.setup_status_actions()
self.pat = re.compile(r'[^0-9a-zA-Z]')
self.textChanged.connect(self.validate)
self.textChanged.connect(self.data_changed)
def contextMenuEvent(self, ev):
m = self.createStandardContextMenu()
first = m.actions()[0]
ac = m.addAction(_('Edit identifiers in a dedicated window'), self.edit_identifiers)
m.insertAction(first, ac)
m.insertSeparator(first)
m.exec(ev.globalPos())
def edit_identifiers(self):
d = Identifiers(self.current_val, self)
if d.exec() == QDialog.DialogCode.Accepted:
self.current_val = d.get_identifiers()
@property
def current_val(self):
raw = str(self.text()).strip()
parts = [clean_text(x) for x in raw.split(',')]
ans = {}
for x in parts:
c = x.split(':')
if len(c) > 1:
itype = c[0].lower()
c = ':'.join(c[1:])
if itype == 'isbn':
v = check_isbn(c)
if v is not None:
c = v
ans[itype] = c
return ans
@current_val.setter
def current_val(self, val):
if not val:
val = {}
def keygen(x):
x = x[0]
if x == 'isbn':
x = '00isbn'
return x
for k in list(val):
if k == 'isbn':
v = check_isbn(k)
if v is not None:
val[k] = v
ids = sorted(iteritems(val), key=keygen)
txt = ', '.join(['%s:%s'%(k.lower(), vl) for k, vl in ids])
if self.allow_undo:
self.selectAll(), self.insert(txt.strip())
else:
self.setText(txt.strip())
self.setCursorPosition(0)
def initialize(self, db, id_):
self.original_val = db.get_identifiers(id_, index_is_id=True)
self.current_val = self.original_val
def commit(self, db, id_):
if self.original_val != self.current_val:
db.set_identifiers(id_, self.current_val, notify=False, commit=False)
def validate(self, *args):
identifiers = self.current_val
isbn = identifiers.get('isbn', '')
tt = self.BASE_TT
extra = ''
ok = None
if not isbn:
pass
elif check_isbn(isbn) is not None:
ok = True
extra = '\n\n'+_('This ISBN is valid')
else:
ok = False
extra = '\n\n' + _('This ISBN is invalid')
self.setToolTip(tt+extra)
self.update_status_actions(ok, self.toolTip())
def paste_identifier(self):
identifier_found = self.parse_clipboard_for_identifier()
if identifier_found:
return
text = str(QApplication.clipboard().text()).strip()
if text.startswith('http://') or text.startswith('https://'):
return self.paste_prefix('url')
try:
prefix = gprefs['paste_isbn_prefixes'][0]
except IndexError:
prefix = 'isbn'
self.paste_prefix(prefix)
def paste_prefix(self, prefix):
if prefix == 'isbn':
self.paste_isbn()
else:
text = str(QApplication.clipboard().text()).strip()
if text:
vals = self.current_val
vals[prefix] = text
self.current_val = vals
def paste_isbn(self):
text = str(QApplication.clipboard().text()).strip()
if not text or not check_isbn(text):
d = ISBNDialog(self, text)
if not d.exec():
return
text = d.text()
if not text:
return
text = check_isbn(text)
if text:
vals = self.current_val
vals['isbn'] = text
self.current_val = vals
if not text:
return
def parse_clipboard_for_identifier(self):
from calibre.ebooks.metadata.sources.prefs import msprefs
from calibre.utils.formatter import EvalFormatter
text = str(QApplication.clipboard().text()).strip()
if not text:
return False
rules = msprefs['id_link_rules']
if rules:
formatter = EvalFormatter()
vals = {'id' : '__ID_REGEX_PLACEHOLDER__'}
for key in rules.keys():
rule = rules[key]
for name, template in rule:
try:
url_pattern = formatter.safe_format(template, vals, '', vals)
url_pattern = re.escape(url_pattern).replace('__ID_REGEX_PLACEHOLDER__', '(?P<new_id>.+)')
if url_pattern.startswith('http:') or url_pattern.startswith('https:'):
url_pattern = '(?:http|https):' + url_pattern.partition(':')[2]
new_id = re.compile(url_pattern)
new_id = new_id.search(text).group('new_id')
if new_id:
vals = self.current_val
vals[key] = new_id
self.current_val = vals
return True
except Exception:
import traceback
traceback.print_exc()
continue
from calibre.customize.ui import all_metadata_plugins
for plugin in all_metadata_plugins():
try:
identifier = plugin.id_from_url(text)
if identifier:
vals = self.current_val
vals[identifier[0]] = identifier[1]
self.current_val = vals
return True
except Exception:
pass
return False
# }}}
class IndicatorLineEdit(QLineEdit, LineEditIndicators):
pass
class ISBNDialog(QDialog): # {{{
def __init__(self, parent, txt):
QDialog.__init__(self, parent)
l = QGridLayout()
self.setLayout(l)
self.setWindowTitle(_('Invalid ISBN'))
w = QLabel(_('Enter an ISBN'))
l.addWidget(w, 0, 0, 1, 2)
w = QLabel(_('ISBN:'))
l.addWidget(w, 1, 0, 1, 1)
self.line_edit = w = IndicatorLineEdit()
w.setup_status_actions()
w.setText(txt)
w.selectAll()
w.textChanged.connect(self.checkText)
l.addWidget(w, 1, 1, 1, 1)
w = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel)
l.addWidget(w, 2, 0, 1, 2)
w.accepted.connect(self.accept)
w.rejected.connect(self.reject)
self.checkText(self.text())
sz = self.sizeHint()
sz.setWidth(sz.width()+50)
self.resize(sz)
def accept(self):
isbn = str(self.line_edit.text())
if not check_isbn(isbn):
return error_dialog(self, _('Invalid ISBN'),
_('The ISBN you entered is not valid. Try again.'),
show=True)
QDialog.accept(self)
def checkText(self, txt):
isbn = str(txt)
ok = None
if not isbn:
pass
elif check_isbn(isbn) is not None:
extra = _('This ISBN is valid')
ok = True
else:
extra = _('This ISBN is invalid')
ok = False
self.line_edit.setToolTip(extra)
self.line_edit.update_status_actions(ok, extra)
def text(self):
return check_isbn(str(self.line_edit.text()))
# }}}
class PublisherEdit(EditWithComplete, ToMetadataMixin): # {{{
LABEL = _('&Publisher:')
FIELD_NAME = 'publisher'
data_changed = pyqtSignal()
editor_requested = pyqtSignal()
def __init__(self, parent):
EditWithComplete.__init__(self, parent)
self.set_clear_button_enabled(False)
self.currentTextChanged.connect(self.data_changed)
self.set_separator(None)
self.setSizeAdjustPolicy(
QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
self.books_to_refresh = set()
self.clear_button = QToolButton(parent)
self.clear_button.setIcon(QIcon.ic('trash.png'))
self.clear_button.setToolTip(_('Clear publisher'))
self.clear_button.clicked.connect(self.clearEditText)
@property
def current_val(self):
return clean_text(str(self.currentText()))
@current_val.setter
def current_val(self, val):
if not val:
val = ''
self.set_edit_text(val.strip())
self.lineEdit().setCursorPosition(0)
def initialize(self, db, id_):
self.books_to_refresh = set()
self.update_items_cache(db.new_api.all_field_names('publisher'))
self.current_val = db.new_api.field_for('publisher', id_)
# having this as a separate assignment ensures that original_val is not None
self.original_val = self.current_val
def commit(self, db, id_):
self.books_to_refresh |= db.set_publisher(id_, self.current_val,
notify=False, commit=False, allow_case_change=True)
return True
@property
def changed(self):
return self.original_val != self.current_val
def edit(self, db, id_):
if self.changed:
d = save_dialog(self, _('Publisher changed'),
_('You have changed the publisher. In order to use the Category'
' editor, you must either discard or apply these '
'changes. Apply changes?'))
if d == QMessageBox.StandardButton.Cancel:
return
if d == QMessageBox.StandardButton.Yes:
self.commit(db, id_)
db.commit()
self.original_val = self.current_val
else:
self.current_val = self.original_val
from calibre.gui2.ui import get_gui
get_gui().do_tags_list_edit(self.current_val, 'publisher')
db = get_gui().current_db
self.update_items_cache(db.new_api.all_field_names('publisher'))
self.initialize(db, id_)
def keyPressEvent(self, ev):
if ev.key() == Qt.Key.Key_F2:
self.editor_requested.emit()
ev.accept()
return
return EditWithComplete.keyPressEvent(self, ev)
# }}}
# DateEdit {{{
class DateEdit(make_undoable(DateTimeEdit), ToMetadataMixin):
TOOLTIP = ''
LABEL = _('&Date:')
FMT = 'dd MMM yyyy hh:mm:ss'
ATTR = FIELD_NAME = 'timestamp'
TWEAK = 'gui_timestamp_display_format'
data_changed = pyqtSignal()
def __init__(self, parent, create_clear_button=True):
super().__init__(parent)
self.setToolTip(self.TOOLTIP)
self.setWhatsThis(self.TOOLTIP)
self.dateTimeChanged.connect(self.data_changed)
fmt = tweaks[self.TWEAK]
if fmt is None:
fmt = self.FMT
elif fmt == 'iso':
fmt = internal_iso_format_string()
self.setDisplayFormat(fmt)
if create_clear_button:
self.clear_button = QToolButton(parent)
self.clear_button.setIcon(QIcon.ic('trash.png'))
self.clear_button.setToolTip(_('Clear date'))
self.clear_button.clicked.connect(self.reset_date)
def reset_date(self, *args):
self.current_val = None
@property
def current_val(self):
return qt_to_dt(self.dateTime(), as_utc=False)
@current_val.setter
def current_val(self, val):
if val is None or is_date_undefined(val):
val = UNDEFINED_DATE
self.setToolTip(self.TOOLTIP)
else:
val = as_local_time(val)
self.setToolTip(self.TOOLTIP + ' ' + _('Exact time: {}').format(val))
self.set_spinbox_value(val)
def initialize(self, db, id_):
self.current_val = getattr(db, self.ATTR)(id_, index_is_id=True)
self.original_val = self.current_val
def commit(self, db, id_):
if self.changed:
getattr(db, 'set_'+self.ATTR)(id_, self.current_val, commit=False,
notify=False)
return True
@property
def changed(self):
o, c = self.original_val, self.current_val
return o != c
def keyPressEvent(self, ev):
if ev.key() == Qt.Key.Key_Up and is_date_undefined(self.current_val):
self.setDateTime(QDateTime.currentDateTime())
elif ev.key() == Qt.Key.Key_Tab and is_date_undefined(self.current_val):
ev.ignore()
else:
return super().keyPressEvent(ev)
def wheelEvent(self, ev):
if is_date_undefined(self.current_val):
self.setDateTime(QDateTime.currentDateTime())
ev.accept()
else:
return super().wheelEvent(ev)
class PubdateEdit(DateEdit):
LABEL = _('P&ublished:')
FMT = 'MMM yyyy'
ATTR = FIELD_NAME = 'pubdate'
TWEAK = 'gui_pubdate_display_format'
# }}}
| 70,493 | Python | .py | 1,700 | 31.162353 | 144 | 0.590679 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,816 | __init__.py | kovidgoyal_calibre/src/calibre/gui2/metadata/__init__.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
| 146 | Python | .py | 4 | 35 | 58 | 0.678571 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,817 | single.py | kovidgoyal_calibre/src/calibre/gui2/metadata/single.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os
from datetime import datetime
from functools import partial
from qt.core import (
QAction,
QDialog,
QDialogButtonBox,
QFrame,
QGridLayout,
QGroupBox,
QHBoxLayout,
QIcon,
QInputDialog,
QKeySequence,
QMenu,
QPushButton,
QScrollArea,
QShortcut,
QSize,
QSizePolicy,
QSpacerItem,
QSplitter,
Qt,
QTabWidget,
QToolButton,
QVBoxLayout,
QWidget,
pyqtSignal,
)
from calibre.constants import ismacos
from calibre.db.constants import DATA_FILE_PATTERN
from calibre.ebooks.metadata import authors_to_string, string_to_authors
from calibre.ebooks.metadata.book.base import Metadata
from calibre.gui2 import error_dialog, gprefs, pixmap_to_data
from calibre.gui2.custom_column_widgets import Comments, get_custom_columns_to_display_in_editor, populate_metadata_page
from calibre.gui2.dialogs.confirm_delete import confirm
from calibre.gui2.metadata.basic_widgets import (
AuthorsEdit,
AuthorSortEdit,
BuddyLabel,
CommentsEdit,
Cover,
DateEdit,
FormatsManager,
IdentifiersEdit,
LanguagesEdit,
PubdateEdit,
PublisherEdit,
RatingEdit,
RightClickButton,
SeriesEdit,
SeriesIndexEdit,
TagsEdit,
TitleEdit,
TitleSortEdit,
)
from calibre.gui2.metadata.single_download import FullFetch
from calibre.gui2.widgets2 import CenteredToolButton
from calibre.library.comments import merge_comments as merge_two_comments
from calibre.utils.date import local_tz
from calibre.utils.localization import canonicalize_lang, ngettext
from polyglot.builtins import iteritems
BASE_TITLE = _('Edit metadata')
fetched_fields = ('title', 'title_sort', 'authors', 'author_sort', 'series',
'series_index', 'languages', 'publisher', 'tags', 'rating',
'comments', 'pubdate')
class ScrollArea(QScrollArea):
def __init__(self, widget=None, parent=None):
QScrollArea.__init__(self, parent)
self.setFrameShape(QFrame.Shape.NoFrame)
self.setWidgetResizable(True)
if widget is not None:
self.setWidget(widget)
class MetadataSingleDialogBase(QDialog):
view_format = pyqtSignal(object, object)
edit_format = pyqtSignal(object, object)
one_line_comments_toolbar = False
use_toolbutton_for_config_metadata = True
def __init__(self, db, parent=None, editing_multiple=False):
self.db = db
self.was_data_edited = False
self.changed = set()
self.books_to_refresh = set()
self.rows_to_refresh = set()
self.metadata_before_fetch = None
self.editing_multiple = editing_multiple
self.comments_edit_state_at_apply = {}
QDialog.__init__(self, parent)
self.setupUi()
def setupUi(self, *args): # {{{
self.download_shortcut = QShortcut(self)
self.download_shortcut.setKey(QKeySequence('Ctrl+D',
QKeySequence.SequenceFormat.PortableText))
p = self.parent()
if hasattr(p, 'keyboard'):
kname = 'Interface Action: Edit Metadata (Edit Metadata) : menu action : download'
sc = p.keyboard.keys_map.get(kname, None)
if sc:
self.download_shortcut.setKey(sc[0])
self.swap_title_author_shortcut = s = QShortcut(self)
s.setKey(QKeySequence('Alt+Down', QKeySequence.SequenceFormat.PortableText))
self.button_box = bb = QDialogButtonBox(self)
self.button_box.accepted.connect(self.accept)
self.button_box.rejected.connect(self.reject)
self.next_button = QPushButton(QIcon.ic('forward.png'), _('Next'),
self)
self.next_action = ac = QAction(self)
ac.triggered.connect(self.next_clicked)
self.addAction(ac)
ac.setShortcut(QKeySequence('Alt+Right'))
self.next_button.clicked.connect(self.next_clicked)
self.prev_button = QPushButton(QIcon.ic('back.png'), _('Previous'), self)
self.prev_button.clicked.connect(self.prev_clicked)
self.prev_action = ac = QAction(self)
ac.triggered.connect(self.prev_clicked)
ac.setShortcut(QKeySequence('Alt+Left'))
self.addAction(ac)
from calibre.gui2.actions.edit_metadata import DATA_FILES_ICON_NAME
self.data_files_button = QPushButton(QIcon.ic(DATA_FILES_ICON_NAME), _('Data files'), self)
self.data_files_button.setShortcut(QKeySequence('Alt+Space'))
self.data_files_button.setToolTip(_('Manage the extra data files associated with this book [{}]').format(
self.data_files_button.shortcut().toString(QKeySequence.SequenceFormat.NativeText)))
self.data_files_button.clicked.connect(self.manage_data_files)
self.button_box.addButton(self.prev_button, QDialogButtonBox.ButtonRole.ActionRole)
self.button_box.addButton(self.next_button, QDialogButtonBox.ButtonRole.ActionRole)
bb.setStandardButtons(QDialogButtonBox.StandardButton.Ok|QDialogButtonBox.StandardButton.Cancel)
bb.button(QDialogButtonBox.StandardButton.Ok).setDefault(True)
self.central_widget = QTabWidget(self)
self.l = QVBoxLayout(self)
self.setLayout(self.l)
self.l.addWidget(self.central_widget)
ll = self.button_box_layout = QHBoxLayout()
self.l.addLayout(ll)
ll.addWidget(self.data_files_button)
ll.addSpacing(10)
ll.addWidget(self.button_box)
self.setWindowIcon(QIcon.ic('edit_input.png'))
self.setWindowTitle(BASE_TITLE)
self.create_basic_metadata_widgets()
if len(get_custom_columns_to_display_in_editor(self.db)):
self.create_custom_metadata_widgets()
self.comments_edit_state_at_apply = {self.comments:None}
self.do_layout()
self.restore_geometry(gprefs, 'metasingle_window_geometry3')
self.restore_widget_settings()
# }}}
def sizeHint(self):
geom = self.screen().availableSize()
nh, nw = max(300, geom.height()-50), max(400, geom.width()-70)
return QSize(nw, nh)
def create_basic_metadata_widgets(self): # {{{
self.basic_metadata_widgets = []
self.languages = LanguagesEdit(self)
self.basic_metadata_widgets.append(self.languages)
self.title = TitleEdit(self)
self.title.textChanged.connect(self.update_window_title)
self.deduce_title_sort_button = QToolButton(self)
self.deduce_title_sort_button.setToolTip(
_('Automatically create the title sort entry based on the current '
'title entry.\nUsing this button to create title sort will '
'change title sort from red to green.'))
self.deduce_title_sort_button.setWhatsThis(
self.deduce_title_sort_button.toolTip())
self.title_sort = TitleSortEdit(self, self.title,
self.deduce_title_sort_button, self.languages)
self.basic_metadata_widgets.extend([self.title, self.title_sort])
self.deduce_author_sort_button = b = RightClickButton(self)
b.setToolTip('<p>' +
_('Automatically create the author sort entry based on the current '
'author entry. Using this button to create author sort will '
'change author sort from red to green. There is a menu of '
'functions available under this button. Click and hold '
'on the button to see it.') + '</p>')
if ismacos:
# Workaround for https://bugreports.qt-project.org/browse/QTBUG-41017
class Menu(QMenu):
def mouseReleaseEvent(self, ev):
ac = self.actionAt(ev.pos())
if ac is not None:
ac.trigger()
return QMenu.mouseReleaseEvent(self, ev)
b.m = m = Menu(b)
else:
b.m = m = QMenu(b)
ac = m.addAction(QIcon.ic('forward.png'), _('Set author sort from author'))
ac2 = m.addAction(QIcon.ic('back.png'), _('Set author from author sort'))
ac3 = m.addAction(QIcon.ic('user_profile.png'), _('Manage authors'))
ac4 = m.addAction(QIcon.ic('next.png'),
_('Copy author to author sort'))
ac5 = m.addAction(QIcon.ic('previous.png'),
_('Copy author sort to author'))
b.setMenu(m)
self.authors = AuthorsEdit(self, ac3)
self.author_sort = AuthorSortEdit(self, self.authors, b, self.db, ac,
ac2, ac4, ac5)
self.basic_metadata_widgets.extend([self.authors, self.author_sort])
self.swap_title_author_button = QToolButton(self)
self.swap_title_author_button.setIcon(QIcon.ic('swap.png'))
self.swap_title_author_button.setToolTip(_(
'Swap the author and title') + ' [%s]' % self.swap_title_author_shortcut.key().toString(QKeySequence.SequenceFormat.NativeText))
self.swap_title_author_button.clicked.connect(self.swap_title_author)
self.swap_title_author_shortcut.activated.connect(self.swap_title_author_button.click)
self.manage_authors_button = QToolButton(self)
self.manage_authors_button.setIcon(QIcon.ic('user_profile.png'))
self.manage_authors_button.setToolTip('<p>' + _(
'Open the Manage Authors editor. Use to rename authors and correct '
'individual author\'s sort values') + '</p>')
self.manage_authors_button.clicked.connect(self.authors.manage_authors)
self.series_editor_button = QToolButton(self)
self.series_editor_button.setToolTip(_('Open the Manage Series editor'))
self.series_editor_button.setIcon(QIcon.ic('chapters.png'))
self.series_editor_button.clicked.connect(self.series_editor)
self.series = SeriesEdit(self)
self.series.editor_requested.connect(self.series_editor)
self.clear_series_button = QToolButton(self)
self.clear_series_button.setToolTip(_('Clear series'))
self.clear_series_button.clicked.connect(self.series.clear)
self.series_index = SeriesIndexEdit(self, self.series)
self.basic_metadata_widgets.extend([self.series, self.series_index])
self.formats_manager = FormatsManager(self, self.copy_fmt)
# We want formats changes to be committed before title/author, as
# otherwise we could have data loss if the title/author changed and the
# user was trying to add an extra file from the old books directory.
self.basic_metadata_widgets.insert(0, self.formats_manager)
self.formats_manager.metadata_from_format_button.clicked.connect(
self.metadata_from_format)
self.formats_manager.cover_from_format_button.clicked.connect(
self.cover_from_format)
self.cover = Cover(self)
self.cover.download_cover.connect(self.download_cover)
self.basic_metadata_widgets.append(self.cover)
self.comments = CommentsEdit(self, self.one_line_comments_toolbar)
self.basic_metadata_widgets.append(self.comments)
self.rating = RatingEdit(self)
self.clear_ratings_button = QToolButton(self)
self.clear_ratings_button.setToolTip(_('Clear rating'))
self.clear_ratings_button.setIcon(QIcon.ic('trash.png'))
self.clear_ratings_button.clicked.connect(self.rating.zero)
self.basic_metadata_widgets.append(self.rating)
self.tags = TagsEdit(self)
self.tags_editor_button = QToolButton(self)
self.tags_editor_button.setToolTip(_('Open the Tag editor. If Ctrl or Shift is pressed, open the Manage Tags editor'))
self.tags_editor_button.setIcon(QIcon.ic('chapters.png'))
self.tags_editor_button.clicked.connect(self.tags_editor)
self.tags.tag_editor_requested.connect(self.tags_editor)
self.clear_tags_button = QToolButton(self)
self.clear_tags_button.setToolTip(_('Clear all tags'))
self.clear_tags_button.setIcon(QIcon.ic('trash.png'))
self.clear_tags_button.clicked.connect(self.tags.clear)
self.basic_metadata_widgets.append(self.tags)
self.identifiers = IdentifiersEdit(self)
self.basic_metadata_widgets.append(self.identifiers)
self.clear_identifiers_button = QToolButton(self)
self.clear_identifiers_button.setIcon(QIcon.ic('trash.png'))
self.clear_identifiers_button.setToolTip(_('Clear Ids'))
self.clear_identifiers_button.clicked.connect(self.identifiers.clear)
self.paste_isbn_button = b = RightClickButton(self)
b.setToolTip('<p>' +
_('Paste the contents of the clipboard into the '
'identifiers prefixed with an auto-detected prefix such as isbn: or url:. Or right click, '
'and choose a specific prefix to use.') + '</p>')
b.setIcon(QIcon.ic('edit-paste.png'))
b.clicked.connect(self.identifiers.paste_identifier)
b.setPopupMode(QToolButton.ToolButtonPopupMode.DelayedPopup)
b.setMenu(QMenu(b))
self.update_paste_identifiers_menu()
self.publisher_editor_button = QToolButton(self)
self.publisher_editor_button.setToolTip(_('Open the Manage Publishers editor'))
self.publisher_editor_button.setIcon(QIcon.ic('chapters.png'))
self.publisher_editor_button.clicked.connect(self.publisher_editor)
self.publisher = PublisherEdit(self)
self.publisher.editor_requested.connect(self.publisher_editor)
self.basic_metadata_widgets.append(self.publisher)
self.timestamp = DateEdit(self)
self.pubdate = PubdateEdit(self)
self.basic_metadata_widgets.extend([self.timestamp, self.pubdate])
self.fetch_metadata_button = b = CenteredToolButton(QIcon.ic('download-metadata.png'), _('&Download metadata'), self)
b.setPopupMode(QToolButton.ToolButtonPopupMode.DelayedPopup)
b.setToolTip(_('Download metadata for this book [%s]') % self.download_shortcut.key().toString(QKeySequence.SequenceFormat.NativeText))
self.fetch_metadata_button.clicked.connect(self.fetch_metadata)
self.fetch_metadata_menu = m = QMenu(self.fetch_metadata_button)
m.addAction(QIcon.ic('edit-undo.png'), _('Undo last metadata download'), self.undo_fetch_metadata)
self.fetch_metadata_button.setMenu(m)
self.download_shortcut.activated.connect(self.fetch_metadata_button.click)
if self.use_toolbutton_for_config_metadata:
self.config_metadata_button = QToolButton(self)
self.config_metadata_button.setIcon(QIcon.ic('config.png'))
else:
self.config_metadata_button = QPushButton(self)
self.config_metadata_button.setText(_('Configure download metadata'))
self.config_metadata_button.setIcon(QIcon.ic('config.png'))
self.config_metadata_button.clicked.connect(self.configure_metadata)
self.config_metadata_button.setToolTip(
_('Change how calibre downloads metadata'))
for w in self.basic_metadata_widgets:
w.data_changed.connect(self.data_changed)
# }}}
def update_paste_identifiers_menu(self):
m = self.paste_isbn_button.menu()
m.clear()
m.addAction(_('Edit list of prefixes'), self.edit_prefix_list)
m.addSeparator()
for prefix in gprefs['paste_isbn_prefixes'][1:]:
m.addAction(prefix, partial(self.identifiers.paste_prefix, prefix))
def edit_prefix_list(self):
prefixes, ok = QInputDialog.getMultiLineText(
self, _('Edit prefixes'), _('Enter prefixes, one on a line. The first prefix becomes the default.'),
'\n'.join(list(map(str, gprefs['paste_isbn_prefixes']))))
if ok:
gprefs['paste_isbn_prefixes'] = list(filter(None, (x.strip() for x in prefixes.splitlines()))) or gprefs.defaults['paste_isbn_prefixes']
self.update_paste_identifiers_menu()
def use_two_columns_for_custom_metadata(self):
raise NotImplementedError
def create_custom_metadata_widgets(self): # {{{
self.custom_metadata_widgets_parent = w = QWidget(self)
layout = QGridLayout()
w.setLayout(layout)
self.custom_metadata_widgets, self.__cc_spacers = \
populate_metadata_page(layout, self.db, None, parent=w, bulk=False,
two_column=self.use_two_columns_for_custom_metadata())
self.__custom_col_layouts = [layout]
for widget in self.custom_metadata_widgets:
widget.connect_data_changed(self.data_changed)
if isinstance(widget, Comments):
self.comments_edit_state_at_apply[widget] = None
# }}}
def set_custom_metadata_tab_order(self, before=None, after=None): # {{{
sto = QWidget.setTabOrder
if getattr(self, 'custom_metadata_widgets', []):
ans = self.custom_metadata_widgets
for i in range(len(ans)-1):
if before is not None and i == 0:
pass
if len(ans[i+1].widgets) == 2:
sto(ans[i].widgets[-1], ans[i+1].widgets[1])
else:
sto(ans[i].widgets[-1], ans[i+1].widgets[0])
for c in range(2, len(ans[i].widgets), 2):
sto(ans[i].widgets[c-1], ans[i].widgets[c+1])
if after is not None:
pass
# }}}
def do_view_format(self, path, fmt):
if path:
self.view_format.emit(None, path)
else:
self.view_format.emit(self.book_id, fmt)
def do_edit_format(self, path, fmt):
if self.was_data_edited:
from calibre.gui2.tweak_book import tprefs
tprefs.refresh() # In case they were changed in a Tweak Book process
from calibre.gui2 import question_dialog
if tprefs['update_metadata_from_calibre'] and question_dialog(
self, _('Save changed metadata?'),
_("You've changed the metadata for this book."
" Edit book is set to update embedded metadata when opened."
" You need to save your changes for them to be included."),
yes_text=_('&Save'), no_text=_("&Don't save"),
yes_icon='dot_green.png', no_icon='dot_red.png',
default_yes=True, skip_dialog_name='edit-metadata-save-before-edit-format'):
if self.apply_changes():
self.was_data_edited = False
self.edit_format.emit(self.book_id, fmt)
def copy_fmt(self, fmt, f):
self.db.copy_format_to(self.book_id, fmt, f, index_is_id=True)
def do_layout(self):
raise NotImplementedError()
def save_widget_settings(self):
pass
def restore_widget_settings(self):
pass
def data_changed(self):
self.was_data_edited = True
def manage_data_files(self):
from calibre.gui2.dialogs.data_files_manager import DataFilesManager
d = DataFilesManager(self.db, self.book_id, self)
d.exec()
self.update_data_files_button()
def __call__(self, id_):
self.book_id = id_
self.books_to_refresh = set()
self.metadata_before_fetch = None
for widget in self.basic_metadata_widgets:
widget.initialize(self.db, id_)
for widget in getattr(self, 'custom_metadata_widgets', []):
widget.initialize(id_)
if callable(self.set_current_callback):
self.set_current_callback(id_)
self.was_data_edited = False
self.update_data_files_button()
# Commented out as it doesn't play nice with Next, Prev buttons
# self.fetch_metadata_button.setFocus(Qt.FocusReason.OtherFocusReason)
# Miscellaneous interaction methods {{{
def update_data_files_button(self):
num_files = len(self.db.new_api.list_extra_files(self.book_id, pattern=DATA_FILE_PATTERN))
self.data_files_button.setText(_('{} Data &files').format(num_files))
def update_window_title(self, *args):
title = self.title.current_val
if len(title) > 50:
title = title[:50] + '\u2026'
self.setWindowTitle(BASE_TITLE + ' - ' +
title + ' -' +
_(' [%(num)d of %(tot)d]')%dict(num=self.current_row+1,
tot=len(self.row_list)))
def swap_title_author(self, *args):
title = self.title.current_val
self.title.current_val = authors_to_string(self.authors.current_val)
self.authors.current_val = string_to_authors(title)
self.title_sort.auto_generate()
self.author_sort.auto_generate()
def tags_editor(self, *args):
self.tags.edit(self.db, self.book_id)
def publisher_editor(self, *args):
self.publisher.edit(self.db, self.book_id)
def series_editor(self, *args):
self.series.edit(self.db, self.book_id)
def metadata_from_format(self, *args):
mi, ext = self.formats_manager.get_selected_format_metadata(self.db,
self.book_id)
if mi is not None:
self.update_from_mi(mi)
def choose_cover_from_pages(self, ext):
path = self.formats_manager.get_format_path(self.db, self.book_id, ext.lower())
from calibre.gui2.metadata.pdf_covers import PDFCovers
d = PDFCovers(path, parent=self)
if d.exec() == QDialog.DialogCode.Accepted:
cpath = d.cover_path
if cpath:
with open(cpath, 'rb') as f:
self.update_cover(f.read(), ext.upper())
d.cleanup()
def cover_from_format(self, *args):
ext = self.formats_manager.get_selected_format()
if ext is None:
return
if ext in ('pdf', 'cbz', 'cbr'):
return self.choose_cover_from_pages(ext)
try:
mi, ext = self.formats_manager.get_selected_format_metadata(self.db, self.book_id)
except OSError as e:
e.locking_violation_msg = _('Could not read from book file.')
raise
if mi is None:
return
cdata = None
if mi.cover and os.access(mi.cover, os.R_OK):
with open(mi.cover, 'rb') as f:
cdata = f.read()
elif mi.cover_data[1] is not None:
cdata = mi.cover_data[1]
if cdata is None:
error_dialog(self, _('Could not read cover'),
_('Could not read cover from %s format')%ext.upper()).exec()
return
self.update_cover(cdata, ext)
def update_cover(self, cdata, fmt):
orig = self.cover.current_val
self.cover.current_val = cdata
if self.cover.current_val is None:
self.cover.current_val = orig
return error_dialog(self, _('Could not read cover'),
_('The cover in the %s format is invalid')%fmt,
show=True)
return
def update_from_mi(self, mi, update_sorts=True, merge_tags=True, merge_comments=False):
fw = self.focusWidget()
if not mi.is_null('title'):
self.title.set_value(mi.title)
if update_sorts:
self.title_sort.auto_generate()
if not mi.is_null('authors'):
self.authors.set_value(mi.authors)
if not mi.is_null('author_sort'):
self.author_sort.set_value(mi.author_sort)
elif update_sorts and not mi.is_null('authors'):
self.author_sort.auto_generate()
if not mi.is_null('rating'):
self.rating.set_value(mi.rating * 2)
if not mi.is_null('publisher'):
self.publisher.set_value(mi.publisher)
if not mi.is_null('tags'):
old_tags = self.tags.current_val
tags = mi.tags if mi.tags else []
if old_tags and merge_tags:
ltags, lotags = {t.lower() for t in tags}, {t.lower() for t in
old_tags}
tags = [t for t in tags if t.lower() in ltags-lotags] + old_tags
self.tags.set_value(tags)
if not mi.is_null('identifiers'):
current = self.identifiers.current_val
current.update(mi.identifiers)
self.identifiers.set_value(current)
if not mi.is_null('pubdate'):
self.pubdate.set_value(mi.pubdate)
if not mi.is_null('series') and mi.series.strip():
self.series.set_value(mi.series)
if mi.series_index is not None:
self.series_index.reset_original()
self.series_index.set_value(float(mi.series_index))
if not mi.is_null('languages'):
langs = [canonicalize_lang(x) for x in mi.languages]
langs = [x for x in langs if x is not None]
if langs:
self.languages.set_value(langs)
if mi.comments and mi.comments.strip():
val = mi.comments
if val and merge_comments:
cval = self.comments.current_val
if cval:
val = merge_two_comments(cval, val)
self.comments.set_value(val)
if fw is not None:
fw.setFocus(Qt.FocusReason.OtherFocusReason)
def fetch_metadata(self, *args):
from calibre.ebooks.metadata.sources.update import update_sources
update_sources()
d = FullFetch(self.cover.pixmap(), self)
ret = d.start(title=self.title.current_val, authors=self.authors.current_val,
identifiers=self.identifiers.current_val)
if ret == QDialog.DialogCode.Accepted:
self.metadata_before_fetch = {f:getattr(self, f).current_val for f in fetched_fields}
from calibre.ebooks.metadata.sources.prefs import msprefs
mi = d.book
dummy = Metadata(_('Unknown'))
for f in msprefs['ignore_fields']:
if ':' not in f:
setattr(mi, f, getattr(dummy, f))
if mi is not None:
pd = mi.pubdate
if pd is not None:
# Put the downloaded published date into the local timezone
# as we discard time info and the date is timezone
# invariant. This prevents the as_local_timezone() call in
# update_from_mi from changing the pubdate
mi.pubdate = datetime(pd.year, pd.month, pd.day,
tzinfo=local_tz)
self.update_from_mi(mi, merge_comments=msprefs['append_comments'])
if d.cover_pixmap is not None:
self.metadata_before_fetch['cover'] = self.cover.current_val
self.cover.current_val = pixmap_to_data(d.cover_pixmap)
self.update_data_files_button()
def undo_fetch_metadata(self):
if self.metadata_before_fetch is None:
return error_dialog(self, _('No downloaded metadata'), _(
'There is no downloaded metadata to undo'), show=True)
for field, val in iteritems(self.metadata_before_fetch):
getattr(self, field).current_val = val
self.metadata_before_fetch = None
def configure_metadata(self):
from calibre.gui2.preferences import show_config_widget
gui = self.parent()
show_config_widget('Sharing', 'Metadata download', parent=self,
gui=gui, never_shutdown=True)
def download_cover(self, *args):
from calibre.ebooks.metadata.sources.update import update_sources
update_sources()
from calibre.gui2.metadata.single_download import CoverFetch
d = CoverFetch(self.cover.pixmap(), self)
ret = d.start(self.title.current_val, self.authors.current_val,
self.identifiers.current_val)
if ret == QDialog.DialogCode.Accepted:
if d.cover_pixmap is not None:
self.cover.current_val = pixmap_to_data(d.cover_pixmap)
self.update_data_files_button()
# }}}
def to_book_metadata(self):
mi = Metadata(_('Unknown'))
if self.db is None:
return mi
mi.set_all_user_metadata(self.db.field_metadata.custom_field_metadata())
for widget in self.basic_metadata_widgets:
widget.apply_to_metadata(mi)
for widget in getattr(self, 'custom_metadata_widgets', []):
widget.apply_to_metadata(mi)
return mi
def apply_changes(self):
self.changed.add(self.book_id)
if self.db is None:
# break_cycles has already been called, don't know why this should
# happen but a user reported it
return True
self.comments_edit_state_at_apply = {w:w.tab for w in self.comments_edit_state_at_apply}
for widget in self.basic_metadata_widgets:
if hasattr(widget, 'validate_for_commit'):
title, msg, det_msg = widget.validate_for_commit()
if title is not None:
error_dialog(self, title, msg, det_msg=det_msg, show=True)
return False
try:
widget.commit(self.db, self.book_id)
self.books_to_refresh |= getattr(widget, 'books_to_refresh', set())
except OSError as e:
e.locking_violation_msg = _('Could not change on-disk location of this book\'s files.')
raise
for widget in getattr(self, 'custom_metadata_widgets', []):
self.books_to_refresh |= widget.commit(self.book_id)
self.db.commit()
rows = self.db.refresh_ids(list(self.books_to_refresh))
if rows:
self.rows_to_refresh |= set(rows)
return True
def accept(self):
self.save_state()
if not self.apply_changes():
return
if self.editing_multiple and self.current_row != len(self.row_list) - 1:
num = len(self.row_list) - 1 - self.current_row
from calibre.gui2 import question_dialog
pm = ngettext('There is another book to edit in this set.',
'There are still {} more books to edit in this set.', num).format(num)
if not question_dialog(
self, _('Are you sure?'), pm + ' ' + _(
'Are you sure you want to stop? Use the "Next" button'
' instead of the "OK" button to move through books in the set.'),
yes_text=_('&Stop editing'), no_text=_('&Continue editing'),
yes_icon='dot_red.png', no_icon='dot_green.png',
default_yes=False, skip_dialog_name='edit-metadata-single-confirm-ok-on-multiple'):
return self.do_one(delta=1, apply_changes=False)
QDialog.accept(self)
def reject(self):
self.save_state()
if self.was_data_edited and not confirm(
title=_('Are you sure?'), name='confirm-cancel-edit-single-metadata', msg=_(
'You will lose all unsaved changes. Are you sure?'), parent=self):
return
QDialog.reject(self)
def save_state(self):
try:
self.save_geometry(gprefs, 'metasingle_window_geometry3')
self.save_widget_settings()
except:
# Weird failure, see https://bugs.launchpad.net/bugs/995271
import traceback
traceback.print_exc()
# Dialog use methods {{{
def start(self, row_list, current_row, view_slot=None, edit_slot=None,
set_current_callback=None):
self.row_list = row_list
self.current_row = current_row
if view_slot is not None:
self.view_format.connect(view_slot)
if edit_slot is not None:
self.edit_format.connect(edit_slot)
self.set_current_callback = set_current_callback
self.do_one(apply_changes=False)
ret = self.exec()
self.break_cycles()
return ret
def next_clicked(self):
fw = self.focusWidget()
if not self.apply_changes():
return
self.do_one(delta=1, apply_changes=False)
if fw is not None:
fw.setFocus(Qt.FocusReason.OtherFocusReason)
def prev_clicked(self):
fw = self.focusWidget()
if not self.apply_changes():
return
self.do_one(delta=-1, apply_changes=False)
if fw is not None:
fw.setFocus(Qt.FocusReason.OtherFocusReason)
def do_one(self, delta=0, apply_changes=True):
if apply_changes:
self.apply_changes()
self.current_row += delta
self.update_window_title()
prev = next_ = None
if self.current_row > 0:
prev = self.db.title(self.row_list[self.current_row-1])
if self.current_row < len(self.row_list) - 1:
next_ = self.db.title(self.row_list[self.current_row+1])
if next_ is not None:
tip = _('Save changes and edit the metadata of {0} [{1}]').format(
next_, self.next_action.shortcut().toString(QKeySequence.SequenceFormat.NativeText))
self.next_button.setToolTip(tip)
self.next_button.setEnabled(next_ is not None)
if prev is not None:
tip = _('Save changes and edit the metadata of {0} [{1}]').format(
prev, self.prev_action.shortcut().toString(QKeySequence.SequenceFormat.NativeText))
self.prev_button.setToolTip(tip)
self.prev_button.setEnabled(prev is not None)
self.button_box.button(QDialogButtonBox.StandardButton.Ok).setDefault(True)
self.button_box.button(QDialogButtonBox.StandardButton.Ok).setFocus(Qt.FocusReason.OtherFocusReason)
self(self.db.id(self.row_list[self.current_row]))
for w, state in iteritems(self.comments_edit_state_at_apply):
if state == 'code':
w.tab = 'code'
def break_cycles(self):
# Break any reference cycles that could prevent python
# from garbage collecting this dialog
self.set_current_callback = self.db = None
self.metadata_before_fetch = None
def disconnect(signal):
try:
signal.disconnect()
except:
pass # Fails if view format was never connected
disconnect(self.view_format)
disconnect(self.edit_format)
for b in ('next_button', 'prev_button'):
x = getattr(self, b, None)
if x is not None:
disconnect(x.clicked)
for widget in self.basic_metadata_widgets:
bc = getattr(widget, 'break_cycles', None)
if bc is not None and callable(bc):
bc()
for widget in getattr(self, 'custom_metadata_widgets', []):
widget.break_cycles()
# }}}
class Splitter(QSplitter):
frame_resized = pyqtSignal(object)
def resizeEvent(self, ev):
self.frame_resized.emit(ev)
return super().resizeEvent(ev)
class MetadataSingleDialog(MetadataSingleDialogBase): # {{{
def use_two_columns_for_custom_metadata(self):
return gprefs['edit_metadata_single_use_2_cols_for_custom_fields']
def do_layout(self):
if len(self.db.custom_column_label_map) == 0:
self.central_widget.tabBar().setVisible(False)
self.central_widget.clear()
self.tabs = []
self.labels = []
self.tabs.append(QWidget(self))
self.central_widget.addTab(ScrollArea(self.tabs[0], self), _("&Basic metadata"))
self.tabs[0].l = l = QVBoxLayout()
self.tabs[0].tl = tl = QGridLayout()
self.tabs[0].setLayout(l)
w = getattr(self, 'custom_metadata_widgets_parent', None)
if w is not None:
self.tabs.append(w)
self.central_widget.addTab(ScrollArea(w, self), _('&Custom metadata'))
l.addLayout(tl)
l.addItem(QSpacerItem(10, 15, QSizePolicy.Policy.Expanding,
QSizePolicy.Policy.Fixed))
sto = QWidget.setTabOrder
sto(self.button_box, self.fetch_metadata_button)
sto(self.fetch_metadata_button, self.config_metadata_button)
sto(self.config_metadata_button, self.title)
def create_row(row, one, two, three, col=1, icon='forward.png'):
ql = BuddyLabel(one)
tl.addWidget(ql, row, col+0, 1, 1)
self.labels.append(ql)
tl.addWidget(one, row, col+1, 1, 1)
if two is not None:
tl.addWidget(two, row, col+2, 1, 1)
two.setIcon(QIcon.ic(icon))
ql = BuddyLabel(three)
tl.addWidget(ql, row, col+3, 1, 1)
self.labels.append(ql)
tl.addWidget(three, row, col+4, 1, 1)
sto(one, two)
sto(two, three)
tl.addWidget(self.swap_title_author_button, 0, 0, 1, 1)
tl.addWidget(self.manage_authors_button, 1, 0, 1, 1)
sto(self.swap_title_author_button, self.title)
create_row(0, self.title, self.deduce_title_sort_button, self.title_sort)
sto(self.title_sort, self.manage_authors_button)
sto(self.manage_authors_button, self.authors)
create_row(1, self.authors, self.deduce_author_sort_button, self.author_sort)
tl.addWidget(self.series_editor_button, 2, 0, 1, 1)
sto(self.author_sort, self.series_editor_button)
sto(self.series_editor_button, self.series)
create_row(2, self.series, self.clear_series_button,
self.series_index, icon='trash.png')
tl.addWidget(self.formats_manager, 0, 6, 3, 1)
self.splitter = Splitter(Qt.Orientation.Horizontal, self)
self.splitter.addWidget(self.cover)
self.splitter.frame_resized.connect(self.cover.frame_resized)
l.addWidget(self.splitter)
self.tabs[0].gb = gb = QGroupBox(_('Change cover'), self)
gb.l = l = QGridLayout()
gb.setLayout(l)
for i, b in enumerate(self.cover.buttons[:3]):
l.addWidget(b, 0, i, 1, 1)
sto(b, self.cover.buttons[i+1])
gb.hl = QHBoxLayout()
for b in self.cover.buttons[3:]:
gb.hl.addWidget(b)
sto(self.cover.buttons[-2], self.cover.buttons[-1])
l.addLayout(gb.hl, 1, 0, 1, 3)
self.tabs[0].middle = w = QWidget(self)
w.l = l = QGridLayout()
w.setLayout(w.l)
self.splitter.addWidget(w)
def create_row2(row, widget, button=None, front_button=None):
row += 1
ql = BuddyLabel(widget)
if front_button:
ltl = QHBoxLayout()
ltl.addWidget(front_button)
ltl.addWidget(ql)
l.addLayout(ltl, row, 0, 1, 1)
else:
l.addWidget(ql, row, 0, 1, 1)
l.addWidget(widget, row, 1, 1, 2 if button is None else 1)
if button is not None:
l.addWidget(button, row, 2, 1, 1)
if button is not None:
sto(widget, button)
l.addWidget(gb, 0, 0, 1, 3)
self.tabs[0].spc_one = QSpacerItem(10, 10, QSizePolicy.Policy.Expanding,
QSizePolicy.Policy.Expanding)
l.addItem(self.tabs[0].spc_one, 1, 0, 1, 3)
sto(self.cover.buttons[-1], self.rating)
create_row2(1, self.rating, self.clear_ratings_button)
sto(self.rating, self.clear_ratings_button)
sto(self.clear_ratings_button, self.tags_editor_button)
sto(self.tags_editor_button, self.tags)
create_row2(2, self.tags, self.clear_tags_button, front_button=self.tags_editor_button)
sto(self.clear_tags_button, self.paste_isbn_button)
sto(self.paste_isbn_button, self.identifiers)
create_row2(3, self.identifiers, self.clear_identifiers_button,
front_button=self.paste_isbn_button)
sto(self.clear_identifiers_button, self.timestamp)
create_row2(4, self.timestamp, self.timestamp.clear_button)
sto(self.timestamp.clear_button, self.pubdate)
create_row2(5, self.pubdate, self.pubdate.clear_button)
sto(self.pubdate.clear_button, self.publisher_editor_button)
sto(self.publisher_editor_button, self.publisher)
create_row2(6, self.publisher, self.publisher.clear_button, front_button=self.publisher_editor_button)
sto(self.publisher.clear_button, self.languages)
create_row2(7, self.languages)
self.tabs[0].spc_two = QSpacerItem(10, 10, QSizePolicy.Policy.Expanding,
QSizePolicy.Policy.Expanding)
l.addItem(self.tabs[0].spc_two, 9, 0, 1, 3)
l.addWidget(self.fetch_metadata_button, 10, 0, 1, 2)
l.addWidget(self.config_metadata_button, 10, 2, 1, 1)
self.tabs[0].gb2 = gb = QGroupBox(_('Co&mments'), self)
gb.l = l = QVBoxLayout()
l.setContentsMargins(0, 0, 0, 0)
gb.setLayout(l)
l.addWidget(self.comments)
self.splitter.addWidget(gb)
self.set_custom_metadata_tab_order()
def save_widget_settings(self):
gprefs['basic_metadata_widget_splitter_state'] = bytearray(self.splitter.saveState())
def restore_widget_settings(self):
s = gprefs.get('basic_metadata_widget_splitter_state')
if s is not None:
self.splitter.restoreState(s)
# }}}
class DragTrackingWidget(QWidget): # {{{
def __init__(self, parent, on_drag_enter):
QWidget.__init__(self, parent)
self.on_drag_enter = on_drag_enter
def dragEnterEvent(self, ev):
self.on_drag_enter.emit()
# }}}
class MetadataSingleDialogAlt1(MetadataSingleDialogBase): # {{{
one_line_comments_toolbar = True
use_toolbutton_for_config_metadata = False
on_drag_enter = pyqtSignal()
def handle_drag_enter(self):
self.central_widget.setCurrentIndex(1)
def use_two_columns_for_custom_metadata(self):
return False
def do_layout(self):
self.central_widget.clear()
self.tabs = []
self.labels = []
sto = QWidget.setTabOrder
self.on_drag_enter.connect(self.handle_drag_enter)
self.tabs.append(DragTrackingWidget(self, self.on_drag_enter))
self.central_widget.addTab(ScrollArea(self.tabs[0], self), _("&Metadata"))
self.tabs[0].l = QGridLayout()
self.tabs[0].setLayout(self.tabs[0].l)
self.tabs.append(QWidget(self))
self.central_widget.addTab(ScrollArea(self.tabs[1], self), _("&Cover and formats"))
self.tabs[1].l = QGridLayout()
self.tabs[1].setLayout(self.tabs[1].l)
# accept drop events so we can automatically switch to the second tab to
# drop covers and formats
self.tabs[0].setAcceptDrops(True)
# Tab 0
tab0 = self.tabs[0]
tl = QGridLayout()
gb = QGroupBox(_('&Basic metadata'), self.tabs[0])
self.tabs[0].l.addWidget(gb, 0, 0, 1, 1)
gb.setLayout(tl)
self.button_box_layout.insertWidget(1, self.fetch_metadata_button)
self.button_box_layout.insertWidget(2, self.config_metadata_button)
sto(self.button_box, self.fetch_metadata_button)
sto(self.fetch_metadata_button, self.config_metadata_button)
sto(self.config_metadata_button, self.title)
def create_row(row, widget, tab_to, button=None, icon=None, span=1):
ql = BuddyLabel(widget)
tl.addWidget(ql, row, 1, 1, 1)
tl.addWidget(widget, row, 2, 1, 1)
if button is not None:
tl.addWidget(button, row, 3, span, 1)
if icon is not None:
button.setIcon(QIcon.ic(icon))
if tab_to is not None:
if button is not None:
sto(widget, button)
sto(button, tab_to)
else:
sto(widget, tab_to)
tl.addWidget(self.swap_title_author_button, 0, 0, 2, 1)
tl.addWidget(self.manage_authors_button, 2, 0, 1, 1)
tl.addWidget(self.series_editor_button, 6, 0, 1, 1)
tl.addWidget(self.tags_editor_button, 6, 0, 1, 1)
tl.addWidget(self.publisher_editor_button, 9, 0, 1, 1)
tl.addWidget(self.paste_isbn_button, 12, 0, 1, 1)
create_row(0, self.title, self.title_sort,
button=self.deduce_title_sort_button, span=2,
icon='auto_author_sort.png')
create_row(1, self.title_sort, self.authors)
create_row(2, self.authors, self.author_sort,
button=self.deduce_author_sort_button,
span=2, icon='auto_author_sort.png')
create_row(3, self.author_sort, self.series)
create_row(4, self.series, self.series_index,
button=self.clear_series_button, icon='trash.png')
create_row(5, self.series_index, self.tags)
create_row(6, self.tags, self.rating, button=self.clear_tags_button)
create_row(7, self.rating, self.pubdate, button=self.clear_ratings_button)
create_row(8, self.pubdate, self.publisher,
button=self.pubdate.clear_button, icon='trash.png')
create_row(9, self.publisher, self.languages, button=self.publisher.clear_button, icon='trash.png')
create_row(10, self.languages, self.timestamp)
create_row(11, self.timestamp, self.identifiers,
button=self.timestamp.clear_button, icon='trash.png')
create_row(12, self.identifiers, self.comments,
button=self.clear_identifiers_button, icon='trash.png')
sto(self.clear_identifiers_button, self.swap_title_author_button)
sto(self.swap_title_author_button, self.manage_authors_button)
sto(self.manage_authors_button, self.series_editor_button)
sto(self.series_editor_button, self.tags_editor_button)
sto(self.tags_editor_button, self.publisher_editor_button)
sto(self.publisher_editor_button, self.paste_isbn_button)
tl.addItem(QSpacerItem(1, 1, QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Expanding),
13, 1, 1 ,1)
w = getattr(self, 'custom_metadata_widgets_parent', None)
if w is not None:
gb = QGroupBox(_('C&ustom metadata'), tab0)
gbl = QVBoxLayout()
gb.setLayout(gbl)
sr = QScrollArea(tab0)
sr.setWidgetResizable(True)
sr.setFrameStyle(QFrame.Shape.NoFrame)
sr.setWidget(w)
gbl.addWidget(sr)
self.tabs[0].l.addWidget(gb, 0, 1, 1, 1)
sto(self.identifiers, gb)
w = QGroupBox(_('&Comments'), tab0)
sp = QSizePolicy()
sp.setVerticalStretch(10)
sp.setHorizontalPolicy(QSizePolicy.Policy.Expanding)
sp.setVerticalPolicy(QSizePolicy.Policy.Expanding)
w.setSizePolicy(sp)
l = QHBoxLayout()
w.setLayout(l)
l.addWidget(self.comments)
tab0.l.addWidget(w, 1, 0, 1, 2)
# Tab 1
tab1 = self.tabs[1]
wsp = QWidget(tab1)
wgl = QVBoxLayout()
wsp.setLayout(wgl)
# right-hand side of splitter
gb = QGroupBox(_('Change cover'), tab1)
l = QGridLayout()
gb.setLayout(l)
for i, b in enumerate(self.cover.buttons[:3]):
l.addWidget(b, 0, i, 1, 1)
sto(b, self.cover.buttons[i+1])
hl = QHBoxLayout()
for b in self.cover.buttons[3:]:
hl.addWidget(b)
sto(self.cover.buttons[-2], self.cover.buttons[-1])
l.addLayout(hl, 1, 0, 1, 3)
wgl.addWidget(gb)
wgl.addItem(QSpacerItem(10, 10, QSizePolicy.Policy.Expanding,
QSizePolicy.Policy.Expanding))
wgl.addItem(QSpacerItem(10, 10, QSizePolicy.Policy.Expanding,
QSizePolicy.Policy.Expanding))
wgl.addWidget(self.formats_manager)
self.splitter = Splitter(Qt.Orientation.Horizontal, tab1)
tab1.l.addWidget(self.splitter)
self.splitter.addWidget(self.cover)
self.splitter.addWidget(wsp)
self.formats_manager.formats.setMaximumWidth(10000)
self.formats_manager.formats.setIconSize(QSize(64, 64))
# }}}
class MetadataSingleDialogAlt2(MetadataSingleDialogBase): # {{{
one_line_comments_toolbar = True
use_toolbutton_for_config_metadata = False
def use_two_columns_for_custom_metadata(self):
return False
def do_layout(self):
self.central_widget.clear()
self.labels = []
sto = QWidget.setTabOrder
# The dialog is in three main parts. Basic and custom metadata in one
# panel on the left over another panel containing comments, separated
# by a splitter. The cover and format information is in a panel on the
# right, separated by another splitter.
main_splitter = self.main_splitter = Splitter(Qt.Orientation.Horizontal, self)
self.central_widget.tabBar().setVisible(False)
self.central_widget.addTab(ScrollArea(main_splitter, self), _("&Metadata"))
# Left side (metadata & comments)
# basic and custom split from comments
metadata_splitter = self.metadata_splitter = Splitter(Qt.Orientation.Vertical, self)
main_splitter.addWidget(metadata_splitter)
metadata_widget = QWidget()
metadata_layout = QHBoxLayout()
metadata_layout.setContentsMargins(3, 0, 0, 0)
metadata_widget.setLayout(metadata_layout)
metadata_splitter.addWidget(metadata_widget)
gb = QGroupBox(_('Basic metadata'), metadata_splitter)
metadata_layout.addWidget(gb)
# Basic metadata in col 0, custom in col 1
tl = QGridLayout()
gb.setLayout(tl)
self.button_box_layout.insertWidget(1, self.fetch_metadata_button)
self.button_box_layout.insertWidget(2, self.config_metadata_button)
sto(self.button_box, self.fetch_metadata_button)
sto(self.fetch_metadata_button, self.config_metadata_button)
sto(self.config_metadata_button, self.title)
def create_row(row, widget, tab_to, button=None, icon=None, span=1):
ql = BuddyLabel(widget)
tl.addWidget(ql, row, 1, 1, 1)
tl.addWidget(widget, row, 2, 1, 1)
if button is not None:
tl.addWidget(button, row, 3, span, 1)
if icon is not None:
button.setIcon(QIcon.ic(icon))
if tab_to is not None:
if button is not None:
sto(widget, button)
sto(button, tab_to)
else:
sto(widget, tab_to)
tl.addWidget(self.swap_title_author_button, 0, 0, 2, 1)
tl.addWidget(self.manage_authors_button, 2, 0, 2, 1)
tl.addWidget(self.series_editor_button, 4, 0, 1, 1)
tl.addWidget(self.tags_editor_button, 6, 0, 1, 1)
tl.addWidget(self.publisher_editor_button, 9, 0, 1, 1)
tl.addWidget(self.paste_isbn_button, 12, 0, 1, 1)
create_row(0, self.title, self.title_sort,
button=self.deduce_title_sort_button, span=2,
icon='auto_author_sort.png')
create_row(1, self.title_sort, self.authors)
create_row(2, self.authors, self.author_sort,
button=self.deduce_author_sort_button,
span=2, icon='auto_author_sort.png')
create_row(3, self.author_sort, self.series)
create_row(4, self.series, self.series_index,
button=self.clear_series_button, icon='trash.png')
create_row(5, self.series_index, self.tags)
create_row(6, self.tags, self.rating, button=self.clear_tags_button)
create_row(7, self.rating, self.pubdate, button=self.clear_ratings_button)
create_row(8, self.pubdate, self.publisher,
button=self.pubdate.clear_button, icon='trash.png')
create_row(9, self.publisher, self.languages,
button=self.publisher.clear_button, icon='trash.png')
create_row(10, self.languages, self.timestamp)
create_row(11, self.timestamp, self.identifiers,
button=self.timestamp.clear_button, icon='trash.png')
create_row(12, self.identifiers, self.comments,
button=self.clear_identifiers_button, icon='trash.png')
sto(self.clear_identifiers_button, self.swap_title_author_button)
sto(self.swap_title_author_button, self.manage_authors_button)
sto(self.manage_authors_button, self.series_editor_button)
sto(self.series_editor_button, self.tags_editor_button)
sto(self.tags_editor_button, self.publisher_editor_button)
sto(self.publisher_editor_button, self.paste_isbn_button)
tl.addItem(QSpacerItem(1, 1, QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Expanding),
13, 1, 1 ,1)
# Custom metadata in col 1
w = getattr(self, 'custom_metadata_widgets_parent', None)
if w is not None:
gb = QGroupBox(_('Custom metadata'), metadata_splitter)
gbl = QVBoxLayout()
gb.setLayout(gbl)
sr = QScrollArea(gb)
sr.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
sr.setWidgetResizable(True)
sr.setFrameStyle(QFrame.Shape.NoFrame)
sr.setWidget(w)
gbl.addWidget(sr)
metadata_layout.addWidget(gb)
sp = QSizePolicy()
sp.setVerticalStretch(10)
sp.setHorizontalPolicy(QSizePolicy.Policy.Minimum)
sp.setVerticalPolicy(QSizePolicy.Policy.Expanding)
gb.setSizePolicy(sp)
self.set_custom_metadata_tab_order()
# comments below metadata splitter. The mess of widgets is to get the
# contents margins right so things line up
cw = QWidget()
cl = QHBoxLayout()
cw.setLayout(cl)
cl.setContentsMargins(3, 0, 0, 0)
metadata_splitter.addWidget(cw)
# Now the real stuff
sp = QSizePolicy()
sp.setVerticalStretch(10)
sp.setHorizontalPolicy(QSizePolicy.Policy.Expanding)
sp.setVerticalPolicy(QSizePolicy.Policy.Expanding)
cw.setSizePolicy(sp)
gb = QGroupBox(_('Comments'), metadata_splitter)
gbl = QHBoxLayout()
gbl.setContentsMargins(0, 0, 0, 0)
gb.setLayout(gbl)
cl.addWidget(gb)
gbl.addWidget(self.comments)
# Cover & formats on right side
# First the cover & buttons
cover_group_box = QGroupBox(_('Cover'), main_splitter)
cover_layout = QVBoxLayout()
cover_layout.setContentsMargins(0, 0, 0, 0)
cover_group_box.setLayout(cover_layout)
cover_layout.addWidget(self.cover)
sto(self.manage_authors_button, self.cover.buttons[0])
# First row of cover buttons
hl = QHBoxLayout()
hl.setContentsMargins(0, 0, 0, 0)
for i, b in enumerate(self.cover.buttons[:3]):
hl.addWidget(b)
sto(b, self.cover.buttons[i+1])
cover_layout.addLayout(hl)
# Second row of cover buttons
hl = QHBoxLayout()
hl.setContentsMargins(0, 0, 0, 0)
for b in self.cover.buttons[3:]:
hl.addWidget(b)
cover_layout.addLayout(hl)
sto(self.cover.buttons[-2], self.cover.buttons[-1])
# Splitter for both cover & formats boxes
self.cover_and_formats = cover_and_formats = Splitter(Qt.Orientation.Vertical)
# Put a very small margin on the left so that the word "Cover" doesn't
# touch the splitter
cover_and_formats.setContentsMargins(1, 0, 0, 0)
cover_and_formats.addWidget(cover_group_box)
# Add the formats manager box
cover_and_formats.addWidget(self.formats_manager)
sto(self.cover.buttons[-1], self.formats_manager)
self.formats_manager.formats.setMaximumWidth(10000)
self.formats_manager.formats.setIconSize(QSize(32, 32))
main_splitter.addWidget(cover_and_formats)
def save_widget_settings(self):
gprefs['all_on_one_metadata_splitter_1_state'] = bytearray(self.metadata_splitter.saveState())
gprefs['all_on_one_metadata_splitter_2_state'] = bytearray(self.main_splitter.saveState())
gprefs['all_on_one_metadata_splitter_3_state'] = bytearray(self.cover_and_formats.saveState())
def restore_widget_settings(self):
s = gprefs.get('all_on_one_metadata_splitter_1_state')
if s is not None:
self.metadata_splitter.restoreState(s)
s = gprefs.get('all_on_one_metadata_splitter_2_state')
if s is not None:
self.main_splitter.restoreState(s)
s = gprefs.get('all_on_one_metadata_splitter_3_state')
if s is not None:
self.cover_and_formats.restoreState(s)
# }}}
editors = {'default': MetadataSingleDialog, 'alt1': MetadataSingleDialogAlt1,
'alt2': MetadataSingleDialogAlt2}
def edit_metadata(db, row_list, current_row, parent=None, view_slot=None, edit_slot=None,
set_current_callback=None, editing_multiple=False):
cls = gprefs.get('edit_metadata_single_layout', '')
if cls not in editors:
cls = 'default'
d = editors[cls](db, parent, editing_multiple=editing_multiple)
try:
d.start(row_list, current_row, view_slot=view_slot, edit_slot=edit_slot,
set_current_callback=set_current_callback)
return d.changed, d.rows_to_refresh
finally:
# possible workaround for bug reports of occasional ghost edit metadata dialog on windows
d.deleteLater()
if __name__ == '__main__':
from calibre.gui2 import Application
app = Application([])
from calibre.library import db
db = db()
row_list = list(range(len(db.data)))
edit_metadata(db, row_list, 0)
| 58,131 | Python | .py | 1,186 | 38.537943 | 148 | 0.628357 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,818 | diff.py | kovidgoyal_calibre/src/calibre/gui2/metadata/diff.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import os
import weakref
from collections import OrderedDict, namedtuple
from functools import partial
from qt.core import (
QAction,
QApplication,
QCheckBox,
QColor,
QDialog,
QDialogButtonBox,
QFont,
QGridLayout,
QHBoxLayout,
QIcon,
QKeySequence,
QLabel,
QMenu,
QPainter,
QPen,
QPixmap,
QScrollArea,
QSize,
QSizePolicy,
QStackedLayout,
Qt,
QToolButton,
QVBoxLayout,
QWidget,
pyqtSignal,
)
from calibre import fit_image
from calibre.ebooks.metadata import authors_to_sort_string, fmt_sidx, title_sort
from calibre.gui2 import gprefs, pixmap_to_data
from calibre.gui2.comments_editor import Editor
from calibre.gui2.complete2 import LineEdit as EditWithComplete
from calibre.gui2.dialogs.confirm_delete import confirm
from calibre.gui2.languages import LanguagesEdit as LE
from calibre.gui2.metadata.basic_widgets import PubdateEdit, RatingEdit
from calibre.gui2.widgets2 import RightClickButton
from calibre.ptempfile import PersistentTemporaryFile
from calibre.startup import connect_lambda
from calibre.utils.date import UNDEFINED_DATE
from calibre.utils.icu import lower as icu_lower
from calibre.utils.localization import ngettext
from polyglot.builtins import iteritems, itervalues
Widgets = namedtuple('Widgets', 'new old label button')
# Widgets {{{
class LineEdit(EditWithComplete):
changed = pyqtSignal()
def __init__(self, field, is_new, parent, metadata, extra):
EditWithComplete.__init__(self, parent)
self.is_new = is_new
self.field = field
self.metadata = metadata
if not is_new:
self.setReadOnly(True)
self.setClearButtonEnabled(False)
else:
sep = metadata['is_multiple']['list_to_ui'] if metadata['is_multiple'] else None
self.set_separator(sep)
self.textChanged.connect(self.changed)
@property
def value(self):
val = str(self.text()).strip()
ism = self.metadata['is_multiple']
if ism:
if not val:
val = []
else:
val = val.strip(ism['list_to_ui'].strip())
val = [x.strip() for x in val.split(ism['list_to_ui']) if x.strip()]
return val
@value.setter
def value(self, val):
ism = self.metadata['is_multiple']
if ism:
if not val:
val = ''
else:
val = ism['list_to_ui'].join(val)
self.setText(val)
self.setCursorPosition(0)
def from_mi(self, mi):
val = mi.get(self.field, default='') or ''
self.value = val
def to_mi(self, mi):
val = self.value
mi.set(self.field, val)
if self.field == 'title':
mi.set('title_sort', title_sort(val, lang=mi.language))
elif self.field == 'authors':
mi.set('author_sort', authors_to_sort_string(val))
@property
def current_val(self):
return str(self.text())
@current_val.setter
def current_val(self, val):
self.setText(val)
self.setCursorPosition(0)
def set_undoable(self, val):
self.selectAll()
self.insert(val)
self.setCursorPosition(0)
@property
def is_blank(self):
val = self.current_val.strip()
if self.field in {'title', 'authors'}:
return val in {'', _('Unknown')}
return not val
def same_as(self, other):
return self.current_val == other.current_val
class LanguagesEdit(LE):
changed = pyqtSignal()
def __init__(self, field, is_new, parent, metadata, extra):
LE.__init__(self, parent=parent)
self.is_new = is_new
self.field = field
self.metadata = metadata
self.textChanged.connect(self.changed)
if not is_new:
self.lineEdit().setReadOnly(True)
self.lineEdit().setClearButtonEnabled(False)
@property
def current_val(self):
return self.lang_codes
@current_val.setter
def current_val(self, val):
self.lang_codes = val
def from_mi(self, mi):
self.lang_codes = mi.languages
def to_mi(self, mi):
mi.languages = self.lang_codes
@property
def is_blank(self):
return not self.current_val
def same_as(self, other):
return self.current_val == other.current_val
def set_undoable(self, val):
self.set_lang_codes(val, True)
class RatingsEdit(RatingEdit):
changed = pyqtSignal()
def __init__(self, field, is_new, parent, metadata, extra):
RatingEdit.__init__(self, parent)
self.is_new = is_new
self.field = field
self.metadata = metadata
self.currentIndexChanged.connect(self.changed)
def from_mi(self, mi):
self.current_val = mi.get(self.field, default=0)
def to_mi(self, mi):
mi.set(self.field, self.current_val)
@property
def is_blank(self):
return self.current_val == 0
def same_as(self, other):
return self.current_val == other.current_val
class DateEdit(PubdateEdit):
changed = pyqtSignal()
def __init__(self, field, is_new, parent, metadata, extra):
PubdateEdit.__init__(self, parent, create_clear_button=False)
self.is_new = is_new
self.field = field
self.metadata = metadata
self.setDisplayFormat(extra)
self.dateTimeChanged.connect(self.changed)
if not is_new:
self.setReadOnly(True)
def from_mi(self, mi):
self.current_val = mi.get(self.field, default=None)
def to_mi(self, mi):
mi.set(self.field, self.current_val)
@property
def is_blank(self):
return self.current_val.year <= UNDEFINED_DATE.year
def same_as(self, other):
return self.text() == other.text()
def set_undoable(self, val):
self.set_value(val)
class SeriesEdit(LineEdit):
def __init__(self, *args, **kwargs):
LineEdit.__init__(self, *args, **kwargs)
self.dbref = None
self.item_selected.connect(self.insert_series_index)
def from_mi(self, mi):
series = mi.get(self.field, default='')
series_index = mi.get(self.field + '_index', default=1.0)
val = ''
if series:
val = f'{series} [{mi.format_series_index(series_index)}]'
self.setText(val)
self.setCursorPosition(0)
def to_mi(self, mi):
val = str(self.text()).strip()
try:
series_index = float(val.rpartition('[')[-1].rstrip(']').strip())
except:
series_index = 1.0
series = val.rpartition('[')[0].strip() or val.rpartition('[')[-1].strip() or None
mi.set(self.field, series)
mi.set(self.field + '_index', series_index)
def set_db(self, db):
self.dbref = weakref.ref(db)
def insert_series_index(self, series):
db = self.dbref()
if db is None or not series:
return
num = db.get_next_series_num_for(series)
sidx = fmt_sidx(num)
self.setText(self.text() + ' [%s]' % sidx)
class IdentifiersEdit(LineEdit):
def from_mi(self, mi):
self.as_dict = mi.identifiers
def to_mi(self, mi):
mi.set_identifiers(self.as_dict)
@property
def as_dict(self):
parts = (x.strip() for x in self.current_val.split(',') if x.strip())
return {k:v for k, v in iteritems({x.partition(':')[0].strip():x.partition(':')[-1].strip() for x in parts}) if k and v}
@as_dict.setter
def as_dict(self, val):
val = (f'{k}:{v}' for k, v in iteritems(val))
self.setText(', '.join(val))
self.setCursorPosition(0)
class CommentsEdit(Editor):
changed = pyqtSignal()
def __init__(self, field, is_new, parent, metadata, extra):
Editor.__init__(self, parent, one_line_toolbar=False)
self.set_minimum_height_for_editor(150)
self.is_new = is_new
self.field = field
self.metadata = metadata
self.hide_tabs()
if not is_new:
self.hide_toolbars()
self.set_readonly(True)
@property
def current_val(self):
return self.html
@current_val.setter
def current_val(self, val):
self.html = val or ''
self.changed.emit()
def set_undoable(self, val):
self.set_html(val, allow_undo=True)
self.changed.emit()
def from_mi(self, mi):
val = mi.get(self.field, default='')
self.current_val = val
def to_mi(self, mi):
mi.set(self.field, self.current_val)
def sizeHint(self):
return QSize(450, 200)
@property
def is_blank(self):
return not self.current_val.strip()
def same_as(self, other):
return self.current_val == other.current_val
class CoverView(QWidget):
changed = pyqtSignal()
zoom_requested = pyqtSignal(object)
def __init__(self, field, is_new, parent, metadata, extra):
QWidget.__init__(self, parent)
self.is_new = is_new
self.field = field
self.metadata = metadata
self.pixmap = None
ic = QIcon.ic('blank.png')
self.blank = ic.pixmap(ic.availableSizes()[0])
self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.MinimumExpanding)
self.sizePolicy().setHeightForWidth(True)
def mouseDoubleClickEvent(self, ev):
if self.pixmap and not self.pixmap.isNull():
self.zoom_requested.emit(self.pixmap)
@property
def is_blank(self):
return self.pixmap is None
@property
def current_val(self):
return self.pixmap
@current_val.setter
def current_val(self, val):
self.pixmap = val
self.changed.emit()
self.update()
def from_mi(self, mi):
p = getattr(mi, 'cover', None)
if p and os.path.exists(p):
pmap = QPixmap()
with open(p, 'rb') as f:
pmap.loadFromData(f.read())
if not pmap.isNull():
self.pixmap = pmap
self.update()
self.changed.emit()
return
cd = getattr(mi, 'cover_data', (None, None))
if cd and cd[1]:
pmap = QPixmap()
pmap.loadFromData(cd[1])
if not pmap.isNull():
self.pixmap = pmap
self.update()
self.changed.emit()
return
self.pixmap = None
self.update()
self.changed.emit()
def to_mi(self, mi):
mi.cover, mi.cover_data = None, (None, None)
if self.pixmap is not None and not self.pixmap.isNull():
with PersistentTemporaryFile('.jpg') as pt:
pt.write(pixmap_to_data(self.pixmap))
mi.cover = pt.name
def same_as(self, other):
return self.current_val == other.current_val
def sizeHint(self):
return QSize(225, 300)
def paintEvent(self, event):
pmap = self.blank if self.pixmap is None or self.pixmap.isNull() else self.pixmap
target = self.rect()
scaled, width, height = fit_image(pmap.width(), pmap.height(), target.width(), target.height())
target.setRect(target.x(), target.y(), width, height)
p = QPainter(self)
p.setRenderHints(QPainter.RenderHint.Antialiasing | QPainter.RenderHint.SmoothPixmapTransform)
p.drawPixmap(target, pmap)
if self.pixmap is not None and not self.pixmap.isNull():
sztgt = target.adjusted(0, 0, 0, -4)
f = p.font()
f.setBold(True)
p.setFont(f)
sz = '\u00a0%d x %d\u00a0'%(self.pixmap.width(), self.pixmap.height())
flags = int(Qt.AlignmentFlag.AlignBottom|Qt.AlignmentFlag.AlignRight|Qt.TextFlag.TextSingleLine)
szrect = p.boundingRect(sztgt, flags, sz)
p.fillRect(szrect.adjusted(0, 0, 0, 4), QColor(0, 0, 0, 200))
p.setPen(QPen(QColor(255,255,255)))
p.drawText(sztgt, flags, sz)
p.end()
# }}}
class CompareSingle(QWidget):
zoom_requested = pyqtSignal(object)
def __init__(
self, field_metadata, parent=None, revert_tooltip=None,
datetime_fmt='MMMM yyyy', blank_as_equal=True,
fields=('title', 'authors', 'series', 'tags', 'rating', 'publisher', 'pubdate', 'identifiers', 'languages', 'comments', 'cover'), db=None):
QWidget.__init__(self, parent)
self.l = l = QGridLayout()
# l.setContentsMargins(0, 0, 0, 0)
self.setLayout(l)
revert_tooltip = revert_tooltip or _('Revert %s')
self.current_mi = None
self.changed_font = QFont(QApplication.font())
self.changed_font.setBold(True)
self.changed_font.setItalic(True)
self.blank_as_equal = blank_as_equal
self.widgets = OrderedDict()
row = 0
for field in fields:
m = field_metadata[field]
dt = m['datatype']
extra = None
if 'series' in {field, dt}:
cls = SeriesEdit
elif field == 'identifiers':
cls = IdentifiersEdit
elif field == 'languages':
cls = LanguagesEdit
elif 'comments' in {field, dt}:
cls = CommentsEdit
elif 'rating' in {field, dt}:
cls = RatingsEdit
elif dt == 'datetime':
extra = datetime_fmt
cls = DateEdit
elif field == 'cover':
cls = CoverView
elif dt in {'text', 'enum'}:
cls = LineEdit
else:
continue
neww = cls(field, True, self, m, extra)
neww.setObjectName(field)
connect_lambda(neww.changed, self, lambda self: self.changed(self.sender().objectName()))
if isinstance(neww, EditWithComplete):
try:
neww.update_items_cache(db.new_api.all_field_names(field))
except ValueError:
pass # A one-one field like title
if isinstance(neww, SeriesEdit):
neww.set_db(db.new_api)
oldw = cls(field, False, self, m, extra)
newl = QLabel('&%s:' % m['name'])
newl.setBuddy(neww)
button = RightClickButton(self)
button.setIcon(QIcon.ic('back.png'))
button.setObjectName(field)
connect_lambda(button.clicked, self, lambda self: self.revert(self.sender().objectName()))
button.setToolTip(revert_tooltip % m['name'])
if field == 'identifiers':
button.m = m = QMenu(button)
button.setMenu(m)
button.setPopupMode(QToolButton.ToolButtonPopupMode.DelayedPopup)
m.addAction(button.toolTip()).triggered.connect(button.click)
m.actions()[0].setIcon(button.icon())
m.addAction(_('Merge identifiers')).triggered.connect(self.merge_identifiers)
m.actions()[1].setIcon(QIcon.ic('merge.png'))
elif field == 'tags':
button.m = m = QMenu(button)
button.setMenu(m)
button.setPopupMode(QToolButton.ToolButtonPopupMode.DelayedPopup)
m.addAction(button.toolTip()).triggered.connect(button.click)
m.actions()[0].setIcon(button.icon())
m.addAction(_('Merge tags')).triggered.connect(self.merge_tags)
m.actions()[1].setIcon(QIcon.ic('merge.png'))
if cls is CoverView:
neww.zoom_requested.connect(self.zoom_requested)
oldw.zoom_requested.connect(self.zoom_requested)
self.widgets[field] = Widgets(neww, oldw, newl, button)
for i, w in enumerate((newl, neww, button, oldw)):
c = i if i < 2 else i + 1
if w is oldw:
c += 1
l.addWidget(w, row, c)
row += 1
if 'comments' in self.widgets and not gprefs.get('diff_widget_show_comments_controls', True):
self.widgets['comments'].new.hide_toolbars()
def save_comments_controls_state(self):
if 'comments' in self.widgets:
vis = self.widgets['comments'].new.toolbars_visible
if vis != gprefs.get('diff_widget_show_comments_controls', True):
gprefs.set('diff_widget_show_comments_controls', vis)
def changed(self, field):
w = self.widgets[field]
if not w.new.same_as(w.old) and (not self.blank_as_equal or not w.new.is_blank):
w.label.setFont(self.changed_font)
else:
w.label.setFont(QApplication.font())
def revert(self, field):
widgets = self.widgets[field]
neww, oldw = widgets[:2]
if hasattr(neww, 'set_undoable'):
neww.set_undoable(oldw.current_val)
else:
neww.current_val = oldw.current_val
def merge_identifiers(self):
widgets = self.widgets['identifiers']
neww, oldw = widgets[:2]
val = neww.as_dict
val.update(oldw.as_dict)
neww.as_dict = val
def merge_tags(self):
widgets = self.widgets['tags']
neww, oldw = widgets[:2]
val = oldw.value
lval = {icu_lower(x) for x in val}
extra = [x for x in neww.value if icu_lower(x) not in lval]
if extra:
neww.value = val + extra
def __call__(self, oldmi, newmi):
self.current_mi = newmi
self.initial_vals = {}
for field, widgets in iteritems(self.widgets):
widgets.old.from_mi(oldmi)
widgets.new.from_mi(newmi)
self.initial_vals[field] = widgets.new.current_val
def apply_changes(self):
changed = False
for field, widgets in iteritems(self.widgets):
val = widgets.new.current_val
if val != self.initial_vals[field]:
widgets.new.to_mi(self.current_mi)
changed = True
if changed and not self.current_mi.languages:
# this is needed because blank language setting
# causes current UI language to be set
widgets = self.widgets['languages']
neww, oldw = widgets[:2]
if oldw.current_val:
self.current_mi.languages = oldw.current_val
return changed
class ZoomedCover(QWidget):
pixmap = None
def paintEvent(self, event):
pmap = self.pixmap
if pmap is None:
return
target = self.rect()
scaled, width, height = fit_image(pmap.width(), pmap.height(), target.width(), target.height())
dx = 0
if target.width() > width + 1:
dx += (target.width() - width) // 2
target.setRect(target.x() + dx, target.y(), width, height)
p = QPainter(self)
p.setRenderHints(QPainter.RenderHint.Antialiasing | QPainter.RenderHint.SmoothPixmapTransform)
p.drawPixmap(target, pmap)
class CoverZoom(QWidget):
def __init__(self, parent):
QWidget.__init__(self, parent)
self.l = l = QVBoxLayout(self)
self.cover = ZoomedCover(self)
l.addWidget(self.cover)
self.h = QHBoxLayout()
l.addLayout(self.h)
self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close, self)
self.size_label = QLabel(self)
self.h.addWidget(self.size_label)
self.h.addStretch(10)
self.h.addWidget(self.bb)
def set_pixmap(self, pixmap):
self.cover.pixmap = pixmap
self.size_label.setText(_('Cover size: {0}x{1}').format(pixmap.width(), pixmap.height()))
self.cover.update()
class CompareMany(QDialog):
def __init__(self, ids, get_metadata, field_metadata, parent=None,
window_title=None,
reject_button_tooltip=None,
accept_all_tooltip=None,
reject_all_tooltip=None,
revert_tooltip=None,
intro_msg=None,
action_button=None,
**kwargs):
QDialog.__init__(self, parent)
self.stack = s = QStackedLayout(self)
self.w = w = QWidget(self)
self.l = l = QVBoxLayout(w)
s.addWidget(w)
self.next_called = False
# initialize the previous items list, we will use it to store the watched items that were rejected or accepted
# when the user clicks on the next or reject button we will add the current item to the previous items list
# when the user presses the back button we will pop the last item from the previous items list and set it as current item
# also the popped item will be removed from the rejected or accepted items list (and will be unmarked if it was marked)
self.previous_items = []
self.setWindowIcon(QIcon.ic('auto_author_sort.png'))
self.get_metadata = get_metadata
self.ids = list(ids)
self.total = len(self.ids)
self.accepted = OrderedDict()
self.rejected_ids = set()
self.window_title = window_title or _('Compare metadata')
if intro_msg:
self.la = la = QLabel(intro_msg)
la.setWordWrap(True)
l.addWidget(la)
self.compare_widget = CompareSingle(field_metadata, parent=parent, revert_tooltip=revert_tooltip, **kwargs)
self.sa = sa = QScrollArea()
l.addWidget(sa)
sa.setWidget(self.compare_widget)
sa.setWidgetResizable(True)
self.cover_zoom = cz = CoverZoom(self)
cz.bb.rejected.connect(self.reject)
s.addWidget(cz)
self.compare_widget.zoom_requested.connect(self.show_zoomed_cover)
self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel)
bb.button(QDialogButtonBox.StandardButton.Cancel).setAutoDefault(False)
bb.rejected.connect(self.reject)
if self.total > 1:
self.aarb = b = bb.addButton(_('&Accept all remaining'), QDialogButtonBox.ButtonRole.YesRole)
b.setIcon(QIcon.ic('ok.png')), b.setAutoDefault(False)
if accept_all_tooltip:
b.setToolTip(accept_all_tooltip)
b.clicked.connect(self.accept_all_remaining)
self.rarb = b = bb.addButton(_('Re&ject all remaining'), QDialogButtonBox.ButtonRole.ActionRole)
b.setIcon(QIcon.ic('minus.png')), b.setAutoDefault(False)
if reject_all_tooltip:
b.setToolTip(reject_all_tooltip)
b.clicked.connect(self.reject_all_remaining)
self.sb = b = bb.addButton(_('R&eject'), QDialogButtonBox.ButtonRole.ActionRole)
ac = QAction(self)
ac.setShortcut(QKeySequence(Qt.KeyboardModifier.AltModifier | Qt.KeyboardModifier.ShiftModifier | Qt.Key.Key_Right))
ac.triggered.connect(b.click)
self.addAction(ac)
b.setToolTip(_('Reject changes and move to next [{}]').format(ac.shortcut().toString(QKeySequence.SequenceFormat.NativeText)))
connect_lambda(b.clicked, self, lambda self: self.next_item(False))
b.setIcon(QIcon.ic('minus.png')), b.setAutoDefault(False)
if reject_button_tooltip:
b.setToolTip(reject_button_tooltip)
self.next_action = ac = QAction(self)
ac.setShortcut(QKeySequence(Qt.KeyboardModifier.AltModifier | Qt.Key.Key_Right))
self.addAction(ac)
if action_button is not None:
self.acb = b = bb.addButton(action_button[0], QDialogButtonBox.ButtonRole.ActionRole)
b.setIcon(QIcon.ic(action_button[1]))
self.action_button_action = action_button[2]
b.clicked.connect(self.action_button_clicked)
# Add a Back button, which allows the user to go back to the previous book cancel any reject/edit/accept that was done to it, and review it again
# create a Back action that will be triggered when the user presses the back button or the back shortcut
self.back_action = QAction(self)
self.back_action.setShortcut(QKeySequence(Qt.KeyboardModifier.AltModifier | Qt.Key.Key_Left))
self.back_action.triggered.connect(self.previous_item)
self.addAction(self.back_action)
# create the back button, set it's name, tooltip, icon and action to call the previous_item method
self.back_button = bb.addButton(_('P&revious'), QDialogButtonBox.ButtonRole.ActionRole)
self.back_button.setToolTip(_('Move to previous {}').format(self.back_action.shortcut().toString(QKeySequence.SequenceFormat.NativeText)))
self.back_button.setIcon(QIcon.ic('back.png'))
self.back_button.clicked.connect(self.previous_item)
self.back_button.setDefault(True)
self.back_button.setAutoDefault(False)
self.nb = b = bb.addButton(_('&Next') if self.total > 1 else _('&OK'), QDialogButtonBox.ButtonRole.ActionRole)
if self.total > 1:
b.setToolTip(_('Move to next [%s]') % self.next_action.shortcut().toString(QKeySequence.SequenceFormat.NativeText))
self.next_action.triggered.connect(b.click)
b.setIcon(QIcon.ic('forward.png' if self.total > 1 else 'ok.png'))
connect_lambda(b.clicked, self, lambda self: self.next_item(True))
b.setDefault(True), b.setAutoDefault(True)
self.bbh = h = QHBoxLayout()
h.setContentsMargins(0, 0, 0, 0)
l.addLayout(h)
self.markq = m = QCheckBox(_('&Mark rejected books'))
m.setChecked(gprefs['metadata_diff_mark_rejected'])
connect_lambda(m.stateChanged[int], self, lambda self: gprefs.set('metadata_diff_mark_rejected', self.markq.isChecked()))
m.setToolTip(_('Mark rejected books in the book list after this dialog is closed'))
h.addWidget(m), h.addWidget(bb)
self.next_item(True)
geom = (parent or self).screen().availableSize()
width = max(700, min(950, geom.width()-50))
height = max(650, min(1000, geom.height()-100))
self.resize(QSize(width, height))
self.restore_geometry(gprefs, 'diff_dialog_geom')
b.setFocus(Qt.FocusReason.OtherFocusReason)
self.next_called = False
def show_zoomed_cover(self, pixmap):
self.cover_zoom.set_pixmap(pixmap)
self.stack.setCurrentIndex(1)
@property
def mark_rejected(self):
return self.markq.isChecked()
def action_button_clicked(self):
self.action_button_action(self.ids[0])
def accept(self):
self.save_geometry(gprefs, 'diff_dialog_geom')
self.compare_widget.save_comments_controls_state()
super().accept()
def reject(self):
if self.stack.currentIndex() == 1:
self.stack.setCurrentIndex(0)
return
if self.next_called and not confirm(_(
'All reviewed changes will be lost! Are you sure you want to Cancel?'),
'confirm-metadata-diff-dialog-cancel'):
return
self.save_geometry(gprefs, 'diff_dialog_geom')
self.compare_widget.save_comments_controls_state()
super().reject()
@property
def current_mi(self):
return self.compare_widget.current_mi
def show_current_item(self):
self.setWindowTitle(self.window_title + _(' [%(num)d of %(tot)d]') % dict(
num=(self.total - len(self.ids) + 1), tot=self.total))
oldmi, newmi = self.get_metadata(self.ids[0])
self.compare_widget(oldmi, newmi)
self.update_back_button_state()
def update_back_button_state(self):
enabled = bool(self.previous_items)
self.back_action.setEnabled(enabled)
self.back_button.setEnabled(enabled)
def next_item(self, accept):
self.next_called = True
if not self.ids:
return self.accept()
if self.current_mi is not None:
changed = self.compare_widget.apply_changes()
if self.current_mi is not None:
old_id = self.ids.pop(0)
# Save the current book that was just reviewed and accepted or rejected to the previous_items list
# this book can be displayed again if the user presses the back button
self.previous_items.append(old_id)
if not accept:
self.rejected_ids.add(old_id)
self.accepted[old_id] = (changed, self.current_mi) if accept else (False, None)
if not self.ids:
return self.accept()
self.show_current_item()
def previous_item(self):
if self.previous_items:
# get the last book id from the previous items list and remove it from the previous items list
# this book id is the last book id that was reviewed and accepted or rejected
last_previous_item = self.previous_items.pop()
# if this book id was rejected, remove it from the rejected ids set
if last_previous_item in self.rejected_ids:
self.rejected_ids.remove(last_previous_item)
self.markq.setChecked(False)
# if this book id was accepted, remove it from the accepted dictionary
elif last_previous_item in self.accepted:
self.accepted.pop(last_previous_item)
# move the last previous item to the beginning of the pending list
self.ids.insert(0, last_previous_item)
self.show_current_item()
def accept_all_remaining(self):
self.next_item(True)
for id_ in self.ids:
oldmi, newmi = self.get_metadata(id_)
self.accepted[id_] = (False, newmi)
self.ids = []
self.accept()
def reject_all_remaining(self):
from calibre.gui2.dialogs.confirm_delete import confirm
if not confirm(ngettext(
'Are you sure you want to reject the remaining result?',
'Are you sure you want to reject all {} remaining results?', len(self.ids)).format(len(self.ids)),
'confirm_metadata_review_reject', parent=self):
return
self.next_item(False)
for id_ in self.ids:
self.rejected_ids.add(id_)
oldmi, newmi = self.get_metadata(id_)
self.accepted[id_] = (False, None)
self.ids = []
self.accept()
def keyPressEvent(self, ev):
if ev.key() in (Qt.Key.Key_Enter, Qt.Key.Key_Return):
ev.accept()
return
return QDialog.keyPressEvent(self, ev)
if __name__ == '__main__':
from calibre.gui2 import Application
from calibre.library import db
app = Application([])
db = db()
ids = sorted(db.all_ids(), reverse=True)
ids = tuple(zip(ids[0::2], ids[1::2]))
gm = partial(db.get_metadata, index_is_id=True, get_cover=True, cover_as_data=True)
def get_metadata(x):
return list(map(gm, ids[x]))
d = CompareMany(list(range(len(ids))), get_metadata, db.field_metadata, db=db)
d.exec()
for changed, mi in itervalues(d.accepted):
if changed and mi is not None:
print(mi)
| 31,368 | Python | .py | 733 | 33.140518 | 153 | 0.612192 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,819 | search_result.py | kovidgoyal_calibre/src/calibre/gui2/store/search_result.py | __license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
class SearchResult:
DRM_LOCKED = 1
DRM_UNLOCKED = 2
DRM_UNKNOWN = 3
def __init__(self):
self.store_name = ''
self.cover_url = ''
self.cover_data = None
self.title = ''
self.author = ''
self.price = ''
self.detail_item = ''
self.drm = None
self.formats = ''
# key = format in upper case.
# value = url to download the file.
self.downloads = {}
self.affiliate = False
self.plugin_author = ''
self.create_browser = None
def __eq__(self, other):
return self.title == other.title and self.author == other.author and self.store_name == other.store_name and self.formats == other.formats
def __hash__(self):
return hash((self.title, self.author, self.store_name, self.formats))
def __str__(self):
items = []
for x in 'store_name title author price formats detail_item cover_url'.split():
items.append(f'\t{x}={getattr(self, x)!r}')
return 'SearchResult(\n%s\n)' % '\n'.join(items)
__repr__ = __str__
__unicode__ = __str__
| 1,251 | Python | .py | 34 | 29.470588 | 146 | 0.57438 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,820 | web_store.py | kovidgoyal_calibre/src/calibre/gui2/store/web_store.py | #!/usr/bin/env python
# License: GPL v3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net>
import json
import os
import shutil
from qt.core import QApplication, QHBoxLayout, QIcon, QLabel, QProgressBar, QPushButton, QSize, QUrl, QVBoxLayout, QWidget, pyqtSignal
from qt.webengine import QWebEngineDownloadRequest, QWebEnginePage, QWebEngineProfile, QWebEngineView
from calibre import random_user_agent, url_slash_cleaner
from calibre.constants import STORE_DIALOG_APP_UID, islinux, iswindows
from calibre.ebooks import BOOK_EXTENSIONS
from calibre.gui2 import Application, choose_save_file, error_dialog, gprefs, info_dialog, set_app_uid
from calibre.gui2.dialogs.confirm_delete import confirm
from calibre.gui2.listener import send_message_in_process
from calibre.gui2.main_window import MainWindow
from calibre.ptempfile import PersistentTemporaryDirectory, reset_base_dir
from calibre.startup import connect_lambda
from calibre.utils.webengine import setup_profile
from polyglot.binary import as_base64_bytes, from_base64_bytes
from polyglot.builtins import string_or_bytes
class DownloadItem(QWidget):
def __init__(self, download_id, filename, parent=None):
QWidget.__init__(self, parent)
self.l = l = QHBoxLayout(self)
self.la = la = QLabel(f'{filename}:\xa0')
la.setMaximumWidth(400)
l.addWidget(la)
self.pb = pb = QProgressBar(self)
pb.setRange(0, 0)
l.addWidget(pb)
self.download_id = download_id
def __call__(self, done, total):
self.pb.setRange(0, total)
self.pb.setValue(done)
class DownloadProgress(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.setVisible(False)
self.l = QVBoxLayout(self)
self.items = {}
def add_item(self, download_id, filename):
self.setVisible(True)
item = DownloadItem(download_id, filename, self)
self.l.addWidget(item)
self.items[download_id] = item
def update_item(self, download_id, done, total):
item = self.items.get(download_id)
if item is not None:
item(done, total)
def remove_item(self, download_id):
item = self.items.pop(download_id, None)
if item is not None:
self.l.removeWidget(item)
item.setVisible(False)
item.setParent(None)
item.deleteLater()
if not self.items:
self.setVisible(False)
def create_profile():
ans = getattr(create_profile, 'ans', None)
if ans is None:
ans = create_profile.ans = setup_profile(QWebEngineProfile('web_store', QApplication.instance()))
ans.setHttpUserAgent(random_user_agent(allow_ie=False))
return ans
class Central(QWidget):
home = pyqtSignal()
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.l = l = QVBoxLayout(self)
self.view = v = QWebEngineView(self)
self._page = QWebEnginePage(create_profile(), v)
v.setPage(self._page)
v.loadStarted.connect(self.load_started)
v.loadProgress.connect(self.load_progress)
v.loadFinished.connect(self.load_finished)
l.addWidget(v)
self.h = h = QHBoxLayout()
l.addLayout(h)
self.download_progress = d = DownloadProgress(self)
h.addWidget(d)
self.home_button = b = QPushButton(_('Home'))
b.clicked.connect(self.home)
h.addWidget(b)
self.back_button = b = QPushButton(_('Back'))
b.clicked.connect(v.back)
h.addWidget(b)
self.forward_button = b = QPushButton(_('Forward'))
b.clicked.connect(v.forward)
h.addWidget(b)
self.progress_bar = b = QProgressBar(self)
h.addWidget(b)
self.reload_button = b = QPushButton(_('Reload'))
b.clicked.connect(v.reload)
h.addWidget(b)
@property
def profile(self):
return self.view.page().profile()
def load_started(self):
self.progress_bar.setValue(0)
def load_progress(self, amt):
self.progress_bar.setValue(amt)
def load_finished(self, ok):
self.progress_bar.setValue(100)
class Main(MainWindow):
def __init__(self, data):
MainWindow.__init__(self, None)
self.setWindowIcon(QIcon.ic('store.png'))
self.setWindowTitle(data['window_title'])
self.download_data = {}
self.data = data
self.central = c = Central(self)
c.home.connect(self.go_home)
c.profile.downloadRequested.connect(self.download_requested)
self.setCentralWidget(c)
self.restore_geometry(gprefs, 'store_dialog_main_window_geometry')
self.go_to(data['detail_url'] or None)
def sizeHint(self):
return QSize(1024, 740)
def closeEvent(self, e):
self.save_geometry(gprefs, 'store_dialog_main_window_geometry')
MainWindow.closeEvent(self, e)
@property
def view(self):
return self.central.view
def go_home(self):
self.go_to()
def go_to(self, url=None):
url = url or self.data['base_url']
url = url_slash_cleaner(url)
self.view.load(QUrl(url))
def download_requested(self, download_item):
fname = download_item.downloadFileName()
download_id = download_item.id()
tdir = PersistentTemporaryDirectory()
self.download_data[download_id] = download_item
download_item.setDownloadDirectory(tdir)
connect_lambda(download_item.receivedBytesChanged, self, lambda self: self.download_progress(download_id))
connect_lambda(download_item.totalBytesChanged, self, lambda self: self.download_progress(download_id))
connect_lambda(download_item.isFinishedChanged, self, lambda self: self.download_finished(download_id))
download_item.accept()
self.central.download_progress.add_item(download_id, fname)
def download_progress(self, download_id):
download_item = self.download_data.get(download_id)
if download_item is not None:
self.central.download_progress.update_item(download_id, download_item.receivedBytes(), download_item.totalBytes())
def download_finished(self, download_id):
self.central.download_progress.remove_item(download_id)
download_item = self.download_data.pop(download_id)
fname = download_item.downloadFileName()
path = os.path.join(download_item.downloadDirectory(), fname)
if download_item.state() == QWebEngineDownloadRequest.DownloadState.DownloadInterrupted:
error_dialog(self, _('Download failed'), _(
'Download of {0} failed with error: {1}').format(fname, download_item.interruptReasonString()), show=True)
return
ext = fname.rpartition('.')[-1].lower()
if ext not in BOOK_EXTENSIONS:
if ext == 'acsm':
if not confirm('<p>' + _(
'This e-book is a DRMed EPUB file. '
'You will be prompted to save this file to your '
'computer. Once it is saved, open it with '
'<a href="https://www.adobe.com/solutions/ebook/digital-editions.html">'
'Adobe Digital Editions</a> (ADE).<p>ADE, in turn '
'will download the actual e-book, which will be a '
'.epub file. You can add this book to calibre '
'using "Add Books" and selecting the file from '
'the ADE library folder.'),
'acsm_download', self):
return
name = choose_save_file(self, 'web-store-download-unknown', _(
'File is not a supported e-book type. Save to disk?'), initial_filename=fname)
if name:
shutil.copyfile(path, name)
os.remove(path)
return
tags = self.data['tags']
if isinstance(tags, string_or_bytes):
tags = list(filter(None, [x.strip() for x in tags.split(',')]))
data = json.dumps({'path': path, 'tags': tags})
if not isinstance(data, bytes):
data = data.encode('utf-8')
try:
send_message_in_process(b'web-store:' + data)
except Exception as err:
error_dialog(self, _('Could not contact calibre'), _(
'No running calibre instance found. Please start calibre before trying to'
' download books.'), det_msg=str(err), show=True)
return
info_dialog(self, _('Download completed'), _(
'Download of {0} has been completed, the book was added to'
' your calibre library').format(fname), show=True)
def main(args):
# 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(STORE_DIALOG_APP_UID)
data = args[-1]
data = json.loads(from_base64_bytes(data))
override = 'calibre-gui' if islinux else None
app = Application(args, override_program_name=override)
m = Main(data)
m.show(), m.raise_and_focus()
app.exec()
del m
del app
if __name__ == '__main__':
sample_data = as_base64_bytes(
json.dumps({
'window_title': 'MobileRead',
'base_url': 'https://www.mobileread.com/',
'detail_url': 'http://www.mobileread.com/forums/showthread.php?t=54477',
'id':1,
'tags': '',
})
)
main(['store-dialog', sample_data])
| 9,833 | Python | .py | 219 | 36.086758 | 134 | 0.64158 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,821 | loader.py | kovidgoyal_calibre/src/calibre/gui2/store/loader.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import io
import re
import sys
import time
from collections import OrderedDict
from threading import Thread
from zlib import decompressobj
from calibre import prints
from calibre.constants import DEBUG, numeric_version
from calibre.gui2.store import StorePlugin
from calibre.utils.config import JSONConfig
from polyglot.builtins import iteritems, itervalues
from polyglot.urllib import urlencode
class VersionMismatch(ValueError):
def __init__(self, ver):
ValueError.__init__(self, 'calibre too old')
self.ver = ver
def download_updates(ver_map={}, server='https://code.calibre-ebook.com'):
from calibre.utils.https import get_https_resource_securely
data = {k:str(v) for k, v in iteritems(ver_map)}
data['ver'] = '1'
url = '%s/stores?%s'%(server, urlencode(data))
# We use a timeout here to ensure the non-daemonic update thread does not
# cause calibre to hang indefinitely during shutdown
raw = get_https_resource_securely(url, timeout=90.0)
while raw:
name, raw = raw.partition(b'\0')[0::2]
name = name.decode('utf-8')
d = decompressobj()
src = d.decompress(raw)
src = src.decode('utf-8').lstrip('\ufeff')
# Python complains if there is a coding declaration in a unicode string
src = re.sub(r'^#.*coding\s*[:=]\s*([-\w.]+)', '#', src, flags=re.MULTILINE)
# Translate newlines to \n
src = io.StringIO(src, newline=None).getvalue()
yield name, src
raw = d.unused_data
class Stores(OrderedDict):
CHECK_INTERVAL = 24 * 60 * 60
def builtins_loaded(self):
self.last_check_time = 0
self.version_map = {}
self.cached_version_map = {}
self.name_rmap = {}
for key, val in iteritems(self):
prefix, name = val.__module__.rpartition('.')[0::2]
if prefix == 'calibre.gui2.store.stores' and name.endswith('_plugin'):
module = sys.modules[val.__module__]
sv = getattr(module, 'store_version', None)
if sv is not None:
name = name.rpartition('_')[0]
self.version_map[name] = sv
self.name_rmap[name] = key
self.cache_file = JSONConfig('store/plugin_cache')
self.load_cache()
def load_cache(self):
# Load plugins from on disk cache
remove = set()
pat = re.compile(r'^store_version\s*=\s*(\d+)', re.M)
for name, src in iteritems(self.cache_file):
try:
key = self.name_rmap[name]
except KeyError:
# Plugin has been disabled
m = pat.search(src[:512])
if m is not None:
try:
self.cached_version_map[name] = int(m.group(1))
except (TypeError, ValueError):
pass
continue
try:
obj, ver = self.load_object(src, key)
except VersionMismatch as e:
self.cached_version_map[name] = e.ver
continue
except:
import traceback
prints('Failed to load cached store:', name)
traceback.print_exc()
else:
if not self.replace_plugin(ver, name, obj, 'cached'):
# Builtin plugin is newer than cached
remove.add(name)
if remove:
with self.cache_file:
for name in remove:
del self.cache_file[name]
def check_for_updates(self):
if hasattr(self, 'update_thread') and self.update_thread.is_alive():
return
if time.time() - self.last_check_time < self.CHECK_INTERVAL:
return
self.last_check_time = time.time()
try:
self.update_thread.start()
except (RuntimeError, AttributeError):
self.update_thread = Thread(target=self.do_update)
self.update_thread.start()
def join(self, timeout=None):
hasattr(self, 'update_thread') and self.update_thread.join(timeout)
def download_updates(self):
ver_map = {name:max(ver, self.cached_version_map.get(name, -1))
for name, ver in iteritems(self.version_map)}
try:
updates = download_updates(ver_map)
except:
import traceback
traceback.print_exc()
else:
yield from updates
def do_update(self):
replacements = {}
for name, src in self.download_updates():
try:
key = self.name_rmap[name]
except KeyError:
# Plugin has been disabled
replacements[name] = src
continue
try:
obj, ver = self.load_object(src, key)
except VersionMismatch as e:
self.cached_version_map[name] = e.ver
replacements[name] = src
continue
except:
import traceback
prints('Failed to load downloaded store:', name)
traceback.print_exc()
else:
if self.replace_plugin(ver, name, obj, 'downloaded'):
replacements[name] = src
if replacements:
with self.cache_file:
for name, src in iteritems(replacements):
self.cache_file[name] = src
def replace_plugin(self, ver, name, obj, source):
if ver > self.version_map[name]:
if DEBUG:
prints('Loaded', source, 'store plugin for:',
self.name_rmap[name], 'at version:', ver)
self[self.name_rmap[name]] = obj
self.version_map[name] = ver
return True
return False
def load_object(self, src, key):
namespace = {}
builtin = self[key]
exec(src, namespace)
ver = namespace['store_version']
cls = None
for x in itervalues(namespace):
if (isinstance(x, type) and issubclass(x, StorePlugin) and x is not
StorePlugin):
cls = x
break
if cls is None:
raise ValueError('No store plugin found')
if cls.minimum_calibre_version > numeric_version:
raise VersionMismatch(ver)
return cls(builtin.gui, builtin.name, config=builtin.config,
base_plugin=builtin.base_plugin), ver
if __name__ == '__main__':
st = time.time()
count = 0
for name, code in download_updates():
count += 1
print(name)
print(code.encode('utf-8'))
print('\n', '_'*80, '\n', sep='')
print('Time to download all %d plugins: %.2f seconds'%(count, time.time() - st))
| 7,007 | Python | .py | 176 | 28.852273 | 84 | 0.564227 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,822 | amazon_live.py | kovidgoyal_calibre/src/calibre/gui2/store/amazon_live.py | #!/usr/bin/env python
# License: GPL v3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net>
from urllib.parse import urlencode
from lxml import etree, html
from calibre.gui2.store.search_result import SearchResult
from calibre.scraper.simple import read_url
module_version = 1 # needed for live updates
def search_amazon(self, query, max_results=10, timeout=60, write_html_to=None):
field_keywords = self.FIELD_KEYWORDS
uquery = self.SEARCH_BASE_QUERY.copy()
uquery[field_keywords] = query
def asbytes(x):
if isinstance(x, str):
x = x.encode('utf-8')
return x
uquery = {asbytes(k):asbytes(v) for k, v in uquery.items()}
url = self.SEARCH_BASE_URL + '?' + urlencode(uquery)
counter = max_results
raw = read_url(self.scraper_storage, url, timeout=timeout)
if write_html_to is not None:
with open(write_html_to, 'w') as f:
f.write(raw)
doc = html.fromstring(raw)
for result in doc.xpath('//div[contains(@class, "s-result-list")]//div[@data-index and @data-asin]'):
kformat = ''.join(result.xpath(f'.//a[contains(text(), "{self.KINDLE_EDITION}")]//text()'))
# Even though we are searching digital-text only Amazon will still
# put in results for non Kindle books (author pages). So we need
# to explicitly check if the item is a Kindle book and ignore it
# if it isn't.
if 'kindle' not in kformat.lower():
continue
asin = result.get('data-asin')
if not asin:
continue
cover_url = ''.join(result.xpath('.//img/@src'))
title = etree.tostring(result.xpath('.//h2')[0], method='text', encoding='unicode')
adiv = result.xpath('.//div[contains(@class, "a-color-secondary")]')[0]
aparts = etree.tostring(adiv, method='text', encoding='unicode').split()
idx = aparts.index(self.BY)
author = ' '.join(aparts[idx+1:]).split('|')[0].strip()
price = ''
for span in result.xpath('.//span[contains(@class, "a-price")]/span[contains(@class, "a-offscreen")]'):
q = ''.join(span.xpath('./text()'))
if q:
price = q
break
counter -= 1
s = SearchResult()
s.cover_url = cover_url.strip()
s.title = title.strip()
s.author = author.strip()
s.detail_item = asin.strip()
s.price = price.strip()
s.formats = 'Kindle'
yield s
def parse_details_amazon(self, idata, search_result):
if idata.xpath('boolean(//div[@class="content"]//li/b[contains(text(), "' +
self.DRM_SEARCH_TEXT + '")])'):
if idata.xpath('boolean(//div[@class="content"]//li[contains(., "' +
self.DRM_FREE_TEXT + '") and contains(b, "' +
self.DRM_SEARCH_TEXT + '")])'):
search_result.drm = SearchResult.DRM_UNLOCKED
else:
search_result.drm = SearchResult.DRM_UNKNOWN
else:
search_result.drm = SearchResult.DRM_LOCKED
return True
def get_details_amazon(self, search_result, timeout):
url = self.DETAILS_URL + search_result.detail_item
raw = read_url(self.scraper_storage, url, timeout=timeout)
idata = html.fromstring(raw)
return parse_details_amazon(self, idata, search_result)
def get_store_link_amazon(self, detail_item):
return (self.DETAILS_URL + detail_item) if detail_item else self.STORE_LINK
| 3,477 | Python | .py | 74 | 38.702703 | 111 | 0.617612 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,823 | amazon_base.py | kovidgoyal_calibre/src/calibre/gui2/store/amazon_base.py | #!/usr/bin/env python
# License: GPL v3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net>
from threading import Lock
from time import monotonic
from qt.core import QUrl
from calibre.gui2 import open_url
lock = Lock()
cached_mod = None
cached_time = -10000000
def live_module():
global cached_time, cached_mod
with lock:
now = monotonic()
if now - cached_time > 3600:
cached_mod = None
if cached_mod is None:
from calibre.live import Strategy, load_module
cached_mod = load_module('calibre.gui2.store.amazon_live', strategy=Strategy.fast)
return cached_mod
def get_method(name):
return getattr(live_module(), name)
class AmazonStore:
minimum_calibre_version = (5, 40, 1)
SEARCH_BASE_URL = 'https://www.amazon.com/s/'
SEARCH_BASE_QUERY = {'i': 'digital-text'}
BY = 'by'
KINDLE_EDITION = 'Kindle Edition'
DETAILS_URL = 'https://amazon.com/dp/'
STORE_LINK = 'https://www.amazon.com/Kindle-eBooks'
DRM_SEARCH_TEXT = 'Simultaneous Device Usage'
DRM_FREE_TEXT = 'Unlimited'
FIELD_KEYWORDS = 'k'
def open(self, parent=None, detail_item=None, external=False):
store_link = get_method('get_store_link_amazon')(self, detail_item)
open_url(QUrl(store_link))
def search(self, query, max_results=10, timeout=60):
yield from get_method('search_amazon')(self, query, max_results=max_results, timeout=timeout)
def get_details(self, search_result, timeout):
return get_method('get_details_amazon')(self, search_result, timeout)
def develop_plugin(self):
import sys
for result in get_method('search_amazon')(self, ' '.join(sys.argv[1:]), write_html_to='/t/amazon.html'):
print(result)
| 1,783 | Python | .py | 43 | 35.55814 | 112 | 0.675362 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,824 | __init__.py | kovidgoyal_calibre/src/calibre/gui2/store/__init__.py | __license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from calibre.utils.filenames import ascii_filename
class StorePlugin: # {{{
'''
A plugin representing an online ebook repository (store). The store can
be a commercial store that sells ebooks or a source of free downloadable
ebooks.
Note that this class is the base class for these plugins, however, to
integrate the plugin with calibre's plugin system, you have to make a
wrapper class that references the actual plugin. See the
:mod:`calibre.customize.builtins` module for examples.
If two :class:`StorePlugin` objects have the same name, the one with higher
priority takes precedence.
Sub-classes must implement :meth:`open`, and :meth:`search`.
Regarding :meth:`open`. Most stores only make themselves available
though a web site thus most store plugins will open using
:class:`calibre.gui2.store.web_store_dialog.WebStoreDialog`. This will
open a modal window and display the store website in a QWebView.
Sub-classes should implement and use the :meth:`genesis` if they require
plugin specific initialization. They should not override or otherwise
reimplement :meth:`__init__`.
Once initialized, this plugin has access to the main calibre GUI via the
:attr:`gui` member. You can access other plugins by name, for example::
self.gui.istores['Amazon Kindle']
Plugin authors can use affiliate programs within their plugin. The
distribution of money earned from a store plugin is 70/30. 70% going
to the pluin author / maintainer and 30% going to the calibre project.
The easiest way to handle affiliate money payouts is to randomly select
between the author's affiliate id and calibre's affiliate id so that
70% of the time the author's id is used.
See declined.txt for a list of stores that do not want to be included.
'''
minimum_calibre_version = (0, 9, 14)
def __init__(self, gui, name, config=None, base_plugin=None):
self.gui = gui
self.name = name
self.base_plugin = base_plugin
if config is None:
from calibre.utils.config import JSONConfig
config = JSONConfig('store/stores/' + ascii_filename(self.name))
self.config = config
def create_browser(self):
'''
If the server requires special headers, such as a particular user agent
or a referrer, then implement this method in your plugin to return a
customized browser instance. See the Gutenberg plugin for an example.
Note that if you implement the open() method in your plugin and use the
WebStoreDialog class, remember to pass self.createbrowser in the
constructor of WebStoreDialog.
'''
raise NotImplementedError()
def open(self, gui, parent=None, detail_item=None, external=False):
'''
Open the store.
:param gui: The main GUI. This will be used to have the job
system start downloading an item from the store.
:param parent: The parent of the store dialog. This is used
to create modal dialogs.
:param detail_item: A plugin specific reference to an item
in the store that the user should be shown.
:param external: When False open an internal dialog with the
store. When True open the users default browser to the store's
web site. :param:`detail_item` should still be respected when external
is True.
'''
raise NotImplementedError()
def search(self, query, max_results=10, timeout=60):
'''
Searches the store for items matching query. This should
return items as a generator.
Don't be lazy with the search! Load as much data as possible in the
:class:`calibre.gui2.store.search_result.SearchResult` object.
However, if data (such as cover_url)
isn't available because the store does not display cover images then it's okay to
ignore it.
At the very least a :class:`calibre.gui2.store.search_result.SearchResult`
returned by this function must have the title, author and id.
If you have to parse multiple pages to get all of the data then implement
:meth:`get_deatils` for retrieving additional information.
Also, by default search results can only include ebooks. A plugin can offer users
an option to include physical books in the search results but this must be
disabled by default.
If a store doesn't provide search on it's own use something like a site specific
google search to get search results for this function.
:param query: The string query search with.
:param max_results: The maximum number of results to return.
:param timeout: The maximum amount of time in seconds to spend downloading data for search results.
:return: :class:`calibre.gui2.store.search_result.SearchResult` objects
item_data is plugin specific and is used in :meth:`open` to open to a specific place in the store.
'''
raise NotImplementedError()
def get_details(self, search_result, timeout=60):
'''
Delayed search for information about specific search items.
Typically, this will be used when certain information such as
formats, drm status, cover url are not part of the main search
results and the information is on another web page.
Using this function allows for the main information (title, author)
to be displayed in the search results while other information can
take extra time to load. Splitting retrieving data that takes longer
to load into a separate function will give the illusion of the search
being faster.
:param search_result: A search result that need details set.
:param timeout: The maximum amount of time in seconds to spend downloading details.
:return: True if the search_result was modified otherwise False
'''
return False
def update_cache(self, parent=None, timeout=60, force=False, suppress_progress=False):
'''
Some plugins need to keep an local cache of available books. This function
is called to update the caches. It is recommended to call this function
from :meth:`open`. Especially if :meth:`open` does anything other than
open a web page.
This function can be called at any time. It is up to the plugin to determine
if the cache really does need updating. Unless :param:`force` is True, then
the plugin must update the cache. The only time force should be True is if
this function is called by the plugin's configuration dialog.
if :param:`suppress_progress` is False it is safe to assume that this function
is being called from the main GUI thread so it is safe and recommended to use
a QProgressDialog to display what is happening and allow the user to cancel
the operation. if :param:`suppress_progress` is True then run the update
silently. In this case there is no guarantee what thread is calling this
function so no Qt related functionality that requires being run in the main
GUI thread should be run. E.G. Open a QProgressDialog.
:param parent: The parent object to be used by an GUI dialogs.
:param timeout: The maximum amount of time that should be spent in
any given network connection.
:param force: Force updating the cache even if the plugin has determined
it is not necessary.
:param suppress_progress: Should a progress indicator be shown.
:return: True if the cache was updated, False otherwise.
'''
return False
def do_genesis(self):
self.genesis()
def genesis(self):
'''
Plugin specific initialization.
'''
pass
def config_widget(self):
'''
See :class:`calibre.customize.Plugin` for details.
'''
raise NotImplementedError()
def save_settings(self, config_widget):
'''
See :class:`calibre.customize.Plugin` for details.
'''
raise NotImplementedError()
def customization_help(self, gui=False):
'''
See :class:`calibre.customize.Plugin` for details.
'''
raise NotImplementedError()
# }}}
| 8,527 | Python | .py | 158 | 45.917722 | 107 | 0.696598 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,825 | web_store_dialog.py | kovidgoyal_calibre/src/calibre/gui2/store/web_store_dialog.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net>
import json
from base64 import standard_b64encode
from itertools import count
counter = count()
class WebStoreDialog:
def __init__(
self, gui, base_url, parent=None, detail_url=None, create_browser=None
):
self.id = next(counter)
self.gui = gui
self.base_url = base_url
self.detail_url = detail_url
self.window_title = None
self.tags = None
def setWindowTitle(self, title):
self.window_title = title
def set_tags(self, tags):
self.tags = tags
def exec(self):
data = {
'base_url': self.base_url,
'detail_url': self.detail_url,
'window_title': self.window_title,
'tags': self.tags,
'id': self.id
}
data = json.dumps(data)
if not isinstance(data, bytes):
data = data.encode('utf-8')
data = standard_b64encode(data)
if isinstance(data, bytes):
data = data.decode('ascii')
args = ['store-dialog', data]
self.gui.job_manager.launch_gui_app(args[0], kwargs={'args': args})
exec_ = exec
| 1,226 | Python | .py | 37 | 25.297297 | 78 | 0.595763 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,826 | basic_config.py | kovidgoyal_calibre/src/calibre/gui2/store/basic_config.py | __license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from qt.core import QWidget
from calibre.gui2.store.basic_config_widget_ui import Ui_Form
class BasicStoreConfigWidget(QWidget, Ui_Form):
def __init__(self, store):
QWidget.__init__(self)
self.setupUi(self)
self.store = store
self.load_setings()
def load_setings(self):
config = self.store.config
self.open_external.setChecked(config.get('open_external', False))
self.tags.setText(config.get('tags', ''))
class BasicStoreConfig:
def customization_help(self, gui=False):
return 'Customize the behavior of this store.'
def config_widget(self):
return BasicStoreConfigWidget(self)
def save_settings(self, config_widget):
self.config['open_external'] = config_widget.open_external.isChecked()
tags = str(config_widget.tags.text())
self.config['tags'] = tags
| 1,005 | Python | .py | 24 | 35.458333 | 78 | 0.683557 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,827 | opensearch_store.py | kovidgoyal_calibre/src/calibre/gui2/store/opensearch_store.py | __license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from contextlib import closing
from qt.core import QUrl
from calibre import browser, guess_extension
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
from calibre.utils.opensearch.description import Description
from calibre.utils.opensearch.query import Query
from calibre.utils.xml_parse import safe_xml_fromstring
def open_search(url, query, max_results=10, timeout=60):
description = Description(url)
url_template = description.get_best_template()
if not url_template:
return
oquery = Query(url_template)
# set up initial values
oquery.searchTerms = query
oquery.count = max_results
url = oquery.url()
counter = max_results
br = browser()
with closing(br.open(url, timeout=timeout)) as f:
doc = safe_xml_fromstring(f.read())
for data in doc.xpath('//*[local-name() = "entry"]'):
if counter <= 0:
break
counter -= 1
s = SearchResult()
s.detail_item = ''.join(data.xpath('./*[local-name() = "id"]/text()')).strip()
for link in data.xpath('./*[local-name() = "link"]'):
rel = link.get('rel')
href = link.get('href')
type = link.get('type')
if rel and href and type:
if 'http://opds-spec.org/thumbnail' in rel:
s.cover_url = href
elif 'http://opds-spec.org/image/thumbnail' in rel:
s.cover_url = href
elif 'http://opds-spec.org/acquisition/buy' in rel:
s.detail_item = href
elif 'http://opds-spec.org/acquisition/sample' in rel:
pass
elif 'http://opds-spec.org/acquisition' in rel:
if type:
ext = guess_extension(type)
if ext:
ext = ext[1:].upper().strip()
s.downloads[ext] = href
s.formats = ', '.join(s.downloads.keys()).strip()
s.title = ' '.join(data.xpath('./*[local-name() = "title"]//text()')).strip()
s.author = ', '.join(data.xpath('./*[local-name() = "author"]//*[local-name() = "name"]//text()')).strip()
price_e = data.xpath('.//*[local-name() = "price"][1]')
if price_e:
price_e = price_e[0]
currency_code = price_e.get('currencycode', '')
price = ''.join(price_e.xpath('.//text()')).strip()
s.price = currency_code + ' ' + price
s.price = s.price.strip()
yield s
class OpenSearchOPDSStore(StorePlugin):
open_search_url = ''
web_url = ''
def open(self, parent=None, detail_item=None, external=False):
if not hasattr(self, 'web_url'):
return
if external or self.config.get('open_external', False):
open_url(QUrl(detail_item if detail_item else self.web_url))
else:
d = WebStoreDialog(self.gui, self.web_url, parent, detail_item, create_browser=self.create_browser)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
if not getattr(self, 'open_search_url', None):
return
yield from open_search(self.open_search_url, query, max_results=max_results, timeout=timeout)
| 3,785 | Python | .py | 80 | 35.55 | 118 | 0.564875 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,828 | store.py | kovidgoyal_calibre/src/calibre/gui2/store/config/store.py | __license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
'''
Config widget access functions for configuring the store action.
'''
def config_widget():
from calibre.gui2.store.config.search.search_widget import StoreConfigWidget
return StoreConfigWidget()
def save_settings(config_widget):
config_widget.save_settings()
| 400 | Python | .py | 11 | 33.818182 | 80 | 0.760417 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,829 | models.py | kovidgoyal_calibre/src/calibre/gui2/store/config/chooser/models.py | __license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from qt.core import QAbstractItemModel, QIcon, QModelIndex, QStyledItemDelegate, Qt
from calibre import fit_image
from calibre.customize.ui import disable_plugin, enable_plugin, is_disabled
from calibre.db.search import CONTAINS_MATCH, EQUALS_MATCH, REGEXP_MATCH, _match
from calibre.utils.config_base import prefs
from calibre.utils.icu import sort_key
from calibre.utils.search_query_parser import SearchQueryParser
class Delegate(QStyledItemDelegate):
def paint(self, painter, option, index):
icon = index.data(Qt.ItemDataRole.DecorationRole)
if icon and not icon.isNull():
QStyledItemDelegate.paint(self, painter, option, QModelIndex())
pw, ph = option.rect.width(), option.rect.height()
scaled, w, h = fit_image(option.decorationSize.width(), option.decorationSize.height(), pw, ph)
r = option.rect
if pw > w:
x = (pw - w) // 2
r = r.adjusted(x, 0, -x, 0)
if ph > h:
y = (ph - h) // 2
r = r.adjusted(0, y, 0, -y)
painter.drawPixmap(r, icon.pixmap(w, h))
else:
QStyledItemDelegate.paint(self, painter, option, index)
class Matches(QAbstractItemModel):
HEADERS = [_('Enabled'), _('Name'), _('No DRM'), _('Headquarters'), _('Affiliate'), _('Formats')]
HTML_COLS = (1,)
CENTERED_COLUMNS = (0, 2, 3, 4)
def __init__(self, plugins):
QAbstractItemModel.__init__(self)
self.NO_DRM_ICON = QIcon.ic('ok.png')
self.DONATE_ICON = QIcon.ic('donate.png')
self.all_matches = plugins
self.matches = plugins
self.filter = ''
self.search_filter = SearchFilter(self.all_matches)
self.sort_col = 1
self.sort_order = Qt.SortOrder.AscendingOrder
def get_plugin(self, index):
row = index.row()
if row < len(self.matches):
return self.matches[row]
else:
return None
def search(self, filter):
self.filter = filter.strip()
if not self.filter:
self.matches = self.all_matches
else:
try:
self.matches = list(self.search_filter.parse(self.filter))
except:
self.matches = self.all_matches
self.layoutChanged.emit()
self.sort(self.sort_col, self.sort_order)
def enable_all(self):
for i in range(len(self.matches)):
index = self.createIndex(i, 0)
self.setData(index, Qt.CheckState.Checked, Qt.ItemDataRole.CheckStateRole)
def enable_none(self):
for i in range(len(self.matches)):
index = self.createIndex(i, 0)
self.setData(index, Qt.CheckState.Unchecked, Qt.ItemDataRole.CheckStateRole)
def enable_invert(self):
for i in range(len(self.matches)):
self.toggle_plugin(self.createIndex(i, 0))
def toggle_plugin(self, index):
new_index = self.createIndex(index.row(), 0)
data = Qt.CheckState.Unchecked if is_disabled(self.get_plugin(index)) else Qt.CheckState.Checked
self.setData(new_index, data, Qt.ItemDataRole.CheckStateRole)
def index(self, row, column, parent=QModelIndex()):
return self.createIndex(row, column)
def parent(self, index):
if not index.isValid() or index.internalId() == 0:
return QModelIndex()
return self.createIndex(0, 0)
def rowCount(self, *args):
return len(self.matches)
def columnCount(self, *args):
return len(self.HEADERS)
def headerData(self, section, orientation, role):
if role != Qt.ItemDataRole.DisplayRole:
return None
text = ''
if orientation == Qt.Orientation.Horizontal:
if section < len(self.HEADERS):
text = self.HEADERS[section]
return (text)
else:
return (section+1)
def data(self, index, role):
row, col = index.row(), index.column()
result = self.matches[row]
if role in (Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.EditRole):
if col == 1:
return (f'<b>{result.name}</b><br><i>{result.description}</i>')
elif col == 3:
return (result.headquarters)
elif col == 5:
return (', '.join(result.formats).upper())
elif role == Qt.ItemDataRole.DecorationRole:
if col == 2:
if result.drm_free_only:
return (self.NO_DRM_ICON)
if col == 4:
if result.affiliate:
return (self.DONATE_ICON)
elif role == Qt.ItemDataRole.CheckStateRole:
if col == 0:
if is_disabled(result):
return Qt.CheckState.Unchecked
return Qt.CheckState.Checked
elif role == Qt.ItemDataRole.TextAlignmentRole:
if col in self.CENTERED_COLUMNS:
return int(Qt.AlignmentFlag.AlignHCenter) # https://bugreports.qt.io/browse/PYSIDE-1974
return Qt.AlignmentFlag.AlignLeft
elif role == Qt.ItemDataRole.ToolTipRole:
if col == 0:
if is_disabled(result):
return ('<p>' + _('This store is currently disabled and cannot be used in other parts of calibre.') + '</p>')
else:
return ('<p>' + _('This store is currently enabled and can be used in other parts of calibre.') + '</p>')
elif col == 1:
return ('<p>%s</p>' % result.description)
elif col == 2:
if result.drm_free_only:
return ('<p>' + _('This store only distributes e-books without DRM.') + '</p>')
else:
return ('<p>' + _('This store distributes e-books with DRM. It may have some titles without DRM, but you will need to check on a per title basis.') + '</p>') # noqa
elif col == 3:
return ('<p>' + _('This store is headquartered in %s. This is a good indication of what market the store caters to. However, this does not necessarily mean that the store is limited to that market only.') % result.headquarters + '</p>') # noqa
elif col == 4:
if result.affiliate:
return ('<p>' + _('Buying from this store supports the calibre developer: %s.') % result.author + '</p>')
elif col == 5:
return ('<p>' + _('This store distributes e-books in the following formats: %s') % ', '.join(result.formats) + '</p>')
return None
def setData(self, index, data, role):
if not index.isValid():
return False
col = index.column()
if col == 0:
if data in (Qt.CheckState.Checked, Qt.CheckState.Checked.value):
enable_plugin(self.get_plugin(index))
else:
disable_plugin(self.get_plugin(index))
self.dataChanged.emit(self.index(index.row(), 0), self.index(index.row(), self.columnCount() - 1))
return True
def flags(self, index):
if index.column() == 0:
return QAbstractItemModel.flags(self, index) | Qt.ItemFlag.ItemIsUserCheckable
return QAbstractItemModel.flags(self, index)
def data_as_text(self, match, col):
text = ''
if col == 0:
text = 'b' if is_disabled(match) else 'a'
elif col == 1:
text = match.name
elif col == 2:
text = 'a' if getattr(match, 'drm_free_only', True) else 'b'
elif col == 3:
text = getattr(match, 'headquarters', '')
elif col == 4:
text = 'a' if getattr(match, 'affiliate', False) else 'b'
return text
def sort(self, col, order, reset=True):
self.sort_col = col
self.sort_order = order
if not self.matches:
return
descending = order == Qt.SortOrder.DescendingOrder
self.matches.sort(key=lambda x: sort_key(str(self.data_as_text(x, col))), reverse=descending)
if reset:
self.beginResetModel(), self.endResetModel()
class SearchFilter(SearchQueryParser):
USABLE_LOCATIONS = [
'all',
'affiliate',
'description',
'drm',
'enabled',
'format',
'formats',
'headquarters',
'name',
]
def __init__(self, all_plugins=[]):
SearchQueryParser.__init__(self, locations=self.USABLE_LOCATIONS)
self.srs = set(all_plugins)
def universal_set(self):
return self.srs
def get_matches(self, location, query):
location = location.lower().strip()
if location == 'formats':
location = 'format'
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:]
if matchkind != REGEXP_MATCH: # leave case in regexps because it can be significant e.g. \S \W \D
query = query.lower()
if location not in self.USABLE_LOCATIONS:
return set()
matches = set()
all_locs = set(self.USABLE_LOCATIONS) - {'all'}
locations = all_locs if location == 'all' else [location]
q = {
'affiliate': lambda x: x.affiliate,
'description': lambda x: x.description.lower(),
'drm': lambda x: not x.drm_free_only,
'enabled': lambda x: not is_disabled(x),
'format': lambda x: ','.join(x.formats).lower(),
'headquarters': lambda x: x.headquarters.lower(),
'name': lambda x : x.name.lower(),
}
q['formats'] = q['format']
upf = prefs['use_primary_find_in_search']
for sr in self.srs:
for locvalue in locations:
accessor = q[locvalue]
if query == 'true':
if locvalue in ('affiliate', 'drm', 'enabled'):
if accessor(sr) == True: # noqa
matches.add(sr)
elif accessor(sr) is not None:
matches.add(sr)
continue
if query == 'false':
if locvalue in ('affiliate', 'drm', 'enabled'):
if accessor(sr) == False: # noqa
matches.add(sr)
elif accessor(sr) is None:
matches.add(sr)
continue
# this is bool, so can't match below
if locvalue in ('affiliate', 'drm', 'enabled'):
continue
try:
# Can't separate authors because comma is used for name sep and author sep
# Exact match might not get what you want. For that reason, turn author
# exactmatch searches into contains searches.
if locvalue == 'name' and matchkind == EQUALS_MATCH:
m = CONTAINS_MATCH
else:
m = matchkind
if locvalue == 'format':
vals = accessor(sr).split(',')
else:
vals = [accessor(sr)]
if _match(query, vals, m, use_primary_find_in_search=upf):
matches.add(sr)
break
except ValueError: # Unicode errors
import traceback
traceback.print_exc()
return matches
| 11,973 | Python | .py | 265 | 32.856604 | 260 | 0.552528 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,830 | adv_search_builder.py | kovidgoyal_calibre/src/calibre/gui2/store/config/chooser/adv_search_builder.py | __license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
import re
from qt.core import QDialog, QDialogButtonBox
from calibre.gui2.store.config.chooser.adv_search_builder_ui import Ui_Dialog
from calibre.library.caches import CONTAINS_MATCH, EQUALS_MATCH
from calibre.utils.localization import localize_user_manual_link
class AdvSearchBuilderDialog(QDialog, Ui_Dialog):
def __init__(self, parent):
QDialog.__init__(self, parent)
self.setupUi(self)
try:
self.sh_label.setText(self.sh_label.text() % localize_user_manual_link(
'https://manual.calibre-ebook.com/gui.html#the-search-interface'))
except TypeError:
pass # link already localized
self.buttonBox.accepted.connect(self.advanced_search_button_pushed)
self.tab_2_button_box.accepted.connect(self.accept)
self.tab_2_button_box.rejected.connect(self.reject)
self.clear_button.clicked.connect(self.clear_button_pushed)
self.adv_search_used = False
self.mc = ''
self.tabWidget.setCurrentIndex(0)
self.tabWidget.currentChanged[int].connect(self.tab_changed)
self.tab_changed(0)
def tab_changed(self, idx):
if idx == 1:
self.tab_2_button_box.button(QDialogButtonBox.StandardButton.Ok).setDefault(True)
else:
self.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setDefault(True)
def advanced_search_button_pushed(self):
self.adv_search_used = True
self.accept()
def clear_button_pushed(self):
self.name_box.setText('')
self.description_box.setText('')
self.headquarters_box.setText('')
self.format_box.setText('')
self.enabled_combo.setCurrentIndex(0)
self.drm_combo.setCurrentIndex(0)
self.affiliate_combo.setCurrentIndex(0)
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):
if self.adv_search_used:
return self.adv_search_string()
else:
return self.box_search_string()
def adv_search_string(self):
mk = self.matchkind.currentIndex()
if mk == CONTAINS_MATCH:
self.mc = ''
elif mk == EQUALS_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:
ans += (' or ' if ans else '') + 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 = '='
else:
self.mc = '~'
ans = []
self.box_last_values = {}
name = str(self.name_box.text()).strip()
if name:
ans.append('name:"' + self.mc + name + '"')
description = str(self.description_box.text()).strip()
if description:
ans.append('description:"' + self.mc + description + '"')
headquarters = str(self.headquarters_box.text()).strip()
if headquarters:
ans.append('headquarters:"' + self.mc + headquarters + '"')
format = str(self.format_box.text()).strip()
if format:
ans.append('format:"' + self.mc + format + '"')
enabled = str(self.enabled_combo.currentText()).strip()
if enabled:
ans.append('enabled:' + enabled)
drm = str(self.drm_combo.currentText()).strip()
if drm:
ans.append('drm:' + drm)
affiliate = str(self.affiliate_combo.currentText()).strip()
if affiliate:
ans.append('affiliate:' + affiliate)
if ans:
return ' and '.join(ans)
return ''
| 4,843 | Python | .py | 121 | 30.553719 | 93 | 0.57492 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,831 | chooser_dialog.py | kovidgoyal_calibre/src/calibre/gui2/store/config/chooser/chooser_dialog.py | __license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from qt.core import QDialog, QDialogButtonBox, QVBoxLayout
from calibre.gui2.store.config.chooser.chooser_widget import StoreChooserWidget
class StoreChooserDialog(QDialog):
def __init__(self, parent):
QDialog.__init__(self, parent)
self.setWindowTitle(_('Choose stores'))
button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
v = QVBoxLayout(self)
self.config_widget = StoreChooserWidget()
v.addWidget(self.config_widget)
v.addWidget(button_box)
self.resize(800, 600)
| 779 | Python | .py | 17 | 39.411765 | 79 | 0.713528 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,832 | results_view.py | kovidgoyal_calibre/src/calibre/gui2/store/config/chooser/results_view.py | __license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from functools import partial
from qt.core import QMenu, QSize, Qt, QTreeView
from calibre.customize.ui import store_plugins
from calibre.gui2.metadata.single_download import RichTextDelegate
from calibre.gui2.store.config.chooser.models import Delegate, Matches
class ResultsView(QTreeView):
def __init__(self, parent=None):
QTreeView.__init__(self,parent)
self._model = Matches([p for p in store_plugins()])
self.setModel(self._model)
self.setIconSize(QSize(24, 24))
self.rt_delegate = RichTextDelegate(self)
self.delegate = Delegate()
self.setItemDelegate(self.delegate)
for i in self._model.HTML_COLS:
self.setItemDelegateForColumn(i, self.rt_delegate)
for i in range(self._model.columnCount()):
self.resizeColumnToContents(i)
self.model().sort(1, Qt.SortOrder.AscendingOrder)
self.header().setSortIndicator(self.model().sort_col, self.model().sort_order)
def contextMenuEvent(self, event):
index = self.indexAt(event.pos())
if not index.isValid():
return
plugin = self.model().get_plugin(index)
menu = QMenu(self)
ca = menu.addAction(_('Configure...'), partial(self.configure_plugin, plugin))
if not plugin.is_customizable():
ca.setEnabled(False)
menu.exec(event.globalPos())
def configure_plugin(self, plugin):
plugin.do_user_config(self)
| 1,595 | Python | .py | 35 | 38.028571 | 86 | 0.678548 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,833 | chooser_widget.py | kovidgoyal_calibre/src/calibre/gui2/store/config/chooser/chooser_widget.py | __license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from qt.core import QComboBox, QDialog, QIcon, QLineEdit, QWidget
from calibre.gui2.store.config.chooser.adv_search_builder import AdvSearchBuilderDialog
from calibre.gui2.store.config.chooser.chooser_widget_ui import Ui_Form
class StoreChooserWidget(QWidget, Ui_Form):
def __init__(self):
QWidget.__init__(self)
self.setupUi(self)
self.query.initialize('store_config_chooser_query')
self.query.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
self.query.setMinimumContentsLength(25)
self.adv_search_action = ac = self.query.lineEdit().addAction(QIcon.ic('gear.png'), QLineEdit.ActionPosition.LeadingPosition)
ac.triggered.connect(self.build_adv_search)
ac.setToolTip(_('Advanced search'))
self.search.clicked.connect(self.do_search)
self.enable_all.clicked.connect(self.results_view.model().enable_all)
self.enable_none.clicked.connect(self.results_view.model().enable_none)
self.enable_invert.clicked.connect(self.results_view.model().enable_invert)
self.results_view.activated.connect(self.results_view.model().toggle_plugin)
def do_search(self):
self.results_view.model().search(str(self.query.text()))
def build_adv_search(self):
adv = AdvSearchBuilderDialog(self)
if adv.exec() == QDialog.DialogCode.Accepted:
self.query.setText(adv.search_string())
| 1,574 | Python | .py | 27 | 51.37037 | 133 | 0.729695 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,834 | search_widget.py | kovidgoyal_calibre/src/calibre/gui2/store/config/search/search_widget.py | __license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from qt.core import QWidget
from calibre.gui2 import JSONConfig
from calibre.gui2.store.config.search.search_widget_ui import Ui_Form
class StoreConfigWidget(QWidget, Ui_Form):
def __init__(self, config=None):
QWidget.__init__(self)
self.setupUi(self)
self.config = JSONConfig('store/search') if not config else config
# These default values should be the same as in
# calibre.gui2.store.search.search:SearchDialog.load_settings
# Seconds
self.opt_timeout.setValue(self.config.get('timeout', 75))
self.opt_hang_time.setValue(self.config.get('hang_time', 75))
self.opt_max_results.setValue(self.config.get('max_results', 10))
self.opt_open_external.setChecked(self.config.get('open_external', True))
# Number of threads to run for each type of operation
self.opt_search_thread_count.setValue(self.config.get('search_thread_count', 4))
self.opt_cache_thread_count.setValue(self.config.get('cache_thread_count', 2))
self.opt_cover_thread_count.setValue(self.config.get('cover_thread_count', 2))
self.opt_details_thread_count.setValue(self.config.get('details_thread_count', 4))
def save_settings(self):
self.config['timeout'] = self.opt_timeout.value()
self.config['hang_time'] = self.opt_hang_time.value()
self.config['max_results'] = self.opt_max_results.value()
self.config['open_external'] = self.opt_open_external.isChecked()
self.config['search_thread_count'] = self.opt_search_thread_count.value()
self.config['cache_thread_count'] = self.opt_cache_thread_count.value()
self.config['cover_thread_count'] = self.opt_cover_thread_count.value()
self.config['details_thread_count'] = self.opt_details_thread_count.value()
| 1,945 | Python | .py | 32 | 53.46875 | 90 | 0.695744 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,835 | mills_boon_uk_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/mills_boon_uk_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 4 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from contextlib import closing
try:
from urllib.parse import quote
except ImportError:
from urllib import quote
from lxml import html
from qt.core import QUrl
from calibre import browser, url_slash_cleaner
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
class MillsBoonUKStore(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
url = 'https://www.millsandboon.co.uk'
if external or self.config.get('open_external', False):
if detail_item:
url = detail_item
open_url(QUrl(url_slash_cleaner(url)))
else:
if detail_item:
detail_url = detail_item
else:
detail_url = None
d = WebStoreDialog(self.gui, url, parent, detail_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
base_url = 'https://www.millsandboon.co.uk'
url = base_url + '/search.aspx??format=ebook&searchText=' + quote(query)
br = browser()
counter = max_results
with closing(br.open(url, timeout=timeout)) as f:
doc = html.fromstring(f.read())
for data in doc.xpath('//article[contains(@class, "group")]'):
if counter <= 0:
break
id_ = ''.join(data.xpath('.//div[@class="img-wrapper"]/a/@href')).strip()
if not id_:
continue
cover_url = ''.join(data.xpath('.//div[@class="img-wrapper"]/a/img/@src'))
title = ''.join(data.xpath('.//div[@class="img-wrapper"]/a/img/@alt')).strip()
author = ''.join(data.xpath('.//a[@class="author"]/text()'))
price = ''.join(data.xpath('.//div[@class="type-wrapper"]/ul/li[child::span[text()="eBook"]]/a/text()'))
format_ = ''.join(data.xpath('.//p[@class="doc-meta-format"]/span[last()]/text()'))
drm = SearchResult.DRM_LOCKED
counter -= 1
s = SearchResult()
s.cover_url = cover_url
s.title = title.strip()
s.author = author.strip()
s.price = price
s.detail_item = id_
s.drm = drm
s.formats = format_
yield s
| 2,931 | Python | .py | 64 | 35.296875 | 120 | 0.584707 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,836 | amazon_in_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/amazon_in_plugin.py | #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 20 # Needed for dynamic plugin loading
from calibre.gui2.store import StorePlugin
try:
from calibre.gui2.store.amazon_base import AmazonStore
except ImportError:
class AmazonStore:
minimum_calibre_version = 9999, 0, 0
class Base(AmazonStore):
scraper_storage = []
SEARCH_BASE_URL = 'https://www.amazon.in/s/'
SEARCH_BASE_QUERY = {'url': 'search-alias=digital-text'}
DETAILS_URL = 'https://amazon.in/dp/'
STORE_LINK = 'https://www.amazon.in'
class AmazonKindleStore(Base, StorePlugin):
pass
if __name__ == '__main__':
Base().develop_plugin()
| 814 | Python | .py | 21 | 35.238095 | 82 | 0.723214 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,837 | weightless_books_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/weightless_books_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 1 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from contextlib import closing
try:
from urllib.parse import quote_plus
except ImportError:
from urllib import quote_plus
from lxml import html
from qt.core import QUrl
from calibre import browser, url_slash_cleaner
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
class WeightlessBooksStore(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
url = 'http://weightlessbooks.com/'
if external or self.config.get('open_external', False):
open_url(QUrl(url_slash_cleaner(detail_item if detail_item else url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_item)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
url = 'http://weightlessbooks.com/?s=' + quote_plus(query)
br = browser()
counter = max_results
with closing(br.open(url, timeout=timeout)) as f:
doc = html.fromstring(f.read())
for data in doc.xpath('//li[@class="product"]'):
if counter <= 0:
break
id = ''.join(data.xpath('.//div[@class="cover"]/a/@href'))
if not id:
continue
cover_url = ''.join(data.xpath('.//div[@class="cover"]/a/img/@src'))
price = ''.join(data.xpath('.//div[@class="buy_buttons"]/b[1]/text()'))
if not price:
continue
formats = ', '.join(data.xpath('.//select[@class="eStore_variation"]//option//text()'))
formats = formats.upper()
title = ''.join(data.xpath('.//h3/a/text()'))
author = ''.join(data.xpath('.//h3//text()'))
author = author.replace(title, '')
counter -= 1
s = SearchResult()
s.cover_url = cover_url
s.title = title.strip()
s.author = author.strip()
s.price = price.strip()
s.detail_item = id.strip()
s.drm = SearchResult.DRM_UNLOCKED
s.formats = formats
yield s
| 2,760 | Python | .py | 60 | 35.45 | 103 | 0.590519 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,838 | amazon_mx_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/amazon_mx_plugin.py | #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
store_version = 1 # Needed for dynamic plugin loading
from calibre.gui2.store import StorePlugin
try:
from calibre.gui2.store.amazon_base import AmazonStore
except ImportError:
class AmazonStore:
minimum_calibre_version = 9999, 0, 0
class Base(AmazonStore):
scraper_storage = []
SEARCH_BASE_URL = 'https://www.amazon.com.mx/s/'
SEARCH_BASE_QUERY = {'url': 'search-alias=digital-text'}
DETAILS_URL = 'https://amazon.com.mx/dp/'
STORE_LINK = 'https://www.amazon.com.mx'
class AmazonKindleStore(Base, StorePlugin):
pass
if __name__ == '__main__':
Base().develop_plugin()
| 742 | Python | .py | 20 | 33.45 | 71 | 0.713885 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,839 | nexto_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/nexto_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 7 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011-2023, Tomasz Długosz <tomek3d@gmail.com>'
__docformat__ = 'restructuredtext en'
import re
from base64 import standard_b64encode
from contextlib import closing
try:
from urllib.parse import quote_plus
except ImportError:
from urllib import quote_plus
from lxml import html
from qt.core import QUrl
from calibre import browser, url_slash_cleaner
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
def as_base64(data):
if not isinstance(data, bytes):
data = data.encode('utf-8')
ans = standard_b64encode(data)
if isinstance(ans, bytes):
ans = ans.decode('ascii')
return ans
class NextoStore(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
aff_root = 'https://www.a4b-tracking.com/pl/stat-click-text-link/35/58/'
url = 'http://www.nexto.pl/'
aff_url = aff_root + as_base64(url)
detail_url = None
if detail_item:
book_id = re.search(r'p[0-9]*\.xml\Z', detail_item)
book_id = book_id.group(0).replace('.xml','').replace('p','')
if book_id:
detail_url = aff_root + as_base64('http://www.nexto.pl/rf/pr?p=' + book_id)
if external or self.config.get('open_external', False):
open_url(QUrl(url_slash_cleaner(detail_url if detail_url else aff_url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_url if detail_url else aff_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
url = 'http://www.nexto.pl/szukaj.xml?search-clause=' + quote_plus(query) + '&scid=1015'
br = browser()
offset=0
counter = max_results
while counter:
with closing(br.open(url + '&_offset={}'.format(offset), timeout=timeout)) as f:
doc = html.fromstring(f.read())
for data in doc.xpath('//ul[@class="productslist"]/li'):
if counter <= 0:
break
id = ''.join(data.xpath('.//div[@class="col-2"]/a/@href'))
if not id:
continue
price = ''.join(data.xpath('.//strong[@class="nprice"]/text()'))
cover_url = ''.join(data.xpath('.//picture[@class="cover"]/img/@data-src'))
cover_url = re.sub(r'%2F', '/', cover_url)
cover_url = re.sub(r'widthMax=235&heightMax=335', 'widthMax=64&heightMax=64', cover_url)
title = ''.join(data.xpath('.//a[@class="title"]/text()'))
title = re.sub(r' – ebook', '', title)
author = ', '.join(data.xpath('.//div[@class="col-7"]//h4//a/text()'))
formats = ', '.join(data.xpath('.//ul[@class="formats"]/li//b/text()'))
DrmFree = data.xpath('.//ul[@class="formats"]/li//b[contains(@title, "znak")]')
counter -= 1
s = SearchResult()
s.cover_url = cover_url if cover_url[:4] == 'http' else 'http://www.nexto.pl' + cover_url
s.title = title.strip()
s.author = author.strip()
s.price = price.strip()
s.detail_item = id.strip()
s.drm = SearchResult.DRM_UNLOCKED if DrmFree else SearchResult.DRM_LOCKED
s.formats = formats.upper().strip()
yield s
if not doc.xpath('//div[@class="listnavigator"]//a[@class="next"]'):
break
offset+=10
| 4,124 | Python | .py | 82 | 38.756098 | 109 | 0.571998 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,840 | beam_ebooks_de_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/beam_ebooks_de_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 4 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
try:
from urllib.parse import quote
except ImportError:
from urllib2 import quote
from contextlib import closing
from lxml import html
from qt.core import QUrl
from calibre import browser
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
class BeamEBooksDEStore(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
url = 'https://www.beam-shop.de/'
if external or self.config.get('open_external', False):
if detail_item:
url = detail_item
open_url(QUrl(url))
else:
detail_url = None
if detail_item:
detail_url = detail_item
d = WebStoreDialog(self.gui, url, parent, detail_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
url = 'https://www.beam-shop.de/search?saltFieldLimitation=all&sSearch=' + quote(query)
br = browser()
counter = max_results
with closing(br.open(url, timeout=timeout)) as f:
doc = html.fromstring(f.read())
for data in doc.xpath('//div[contains(@class, "product--box")]'):
if counter <= 0:
break
id_ = ''.join(data.xpath('./div/div[contains(@class, "product--info")]/a/@href')).strip()
if not id_:
continue
cover_url = ''.join(data.xpath('./div/div[contains(@class, "product--info")]/a//img/@srcset'))
if cover_url:
cover_url = cover_url.split(',')[0].strip()
author = data.xpath('.//a[@class="product--author"]/text()')[0].strip()
title = data.xpath('.//a[@class="product--title"]/text()')[0].strip()
price = data.xpath('.//div[@class="product--price"]/span/text()')[0].strip()
counter -= 1
s = SearchResult()
s.cover_url = cover_url
s.title = title.strip()
s.author = author.strip()
s.price = price
s.drm = SearchResult.DRM_UNLOCKED
s.detail_item = id_
# s.formats = None
yield s
| 2,809 | Python | .py | 62 | 35.129032 | 110 | 0.588515 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,841 | rw2010_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/rw2010_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 1 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011, Tomasz Długosz <tomek3d@gmail.com>'
__docformat__ = 'restructuredtext en'
import re
from contextlib import closing
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
from lxml import html
from qt.core import QUrl
from calibre import browser, url_slash_cleaner
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
class RW2010Store(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
url = 'http://www.rw2010.pl/'
if external or self.config.get('open_external', False):
open_url(QUrl(url_slash_cleaner(detail_item if detail_item else url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_item)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
url = 'http://www.rw2010.pl/go.live.php/?launch_macro=catalogue-search-rd'
values={
'fkeyword': query,
'file_type':''
}
br = browser()
counter = max_results
with closing(br.open(url, data=urlencode(values), timeout=timeout)) as f:
doc = html.fromstring(f.read())
for data in doc.xpath('//div[@class="ProductDetail"]'):
if counter <= 0:
break
id = ''.join(data.xpath('.//div[@class="img"]/a/@href'))
if not id:
continue
with closing(br.open(id.strip(), timeout=timeout/4)) as nf:
idata = html.fromstring(nf.read())
cover_url = ''.join(idata.xpath('//div[@class="boxa"]//div[@class="img"]/img/@src'))
author = ''.join(idata.xpath('//div[@class="boxb"]//h3[text()="Autor: "]/span/text()'))
title = ''.join(idata.xpath('//div[@class="boxb"]/h2[1]/text()'))
title = re.sub(r'\(#.+\)', '', title)
formats = ''.join(idata.xpath('//div[@class="boxb"]//h3[text()="Format pliku: "]/span/text()'))
price = ''.join(idata.xpath('//div[@class="price-box"]/span/text()')) + ',00 zł'
counter -= 1
s = SearchResult()
s.cover_url = 'http://www.rw2010.pl/' + cover_url
s.title = title.strip()
s.author = author.strip()
s.price = price
s.detail_item = re.sub(r'%3D', '=', id)
s.drm = SearchResult.DRM_UNLOCKED
s.formats = formats[0:-2].upper()
yield s
| 3,081 | Python | .py | 64 | 37.390625 | 115 | 0.57958 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,842 | bn_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/bn_plugin.py | # -*- coding: utf-8 -*-
# License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 4 # Needed for dynamic plugin loading
from contextlib import closing
try:
from urllib.parse import quote_plus
except ImportError:
from urllib import quote_plus
from lxml import html
from qt.core import QUrl
from calibre import browser, url_slash_cleaner
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
def search_bn(query, max_results=10, timeout=60, write_html_to=''):
url = 'https://www.barnesandnoble.com/s/%s?keyword=%s&store=ebook&view=list' % (query.replace(' ', '-'), quote_plus(query))
br = browser()
counter = max_results
with closing(br.open(url, timeout=timeout)) as f:
raw = f.read()
if write_html_to:
with open(write_html_to, 'wb') as f:
f.write(raw)
doc = html.fromstring(raw)
for data in doc.xpath('//section[@id="gridView"]//div[contains(@class, "product-shelf-tile-book")]'):
if counter <= 0:
break
counter -= 1
cover_url = ''
cover_div = data.xpath('.//div[contains(@class, "product-shelf-image")]')
if cover_div:
cover_url = 'https:' + ''.join(cover_div[0].xpath('descendant::img/@src'))
title_div = data.xpath('.//div[contains(@class, "product-shelf-title")]')
if not title_div:
continue
title = ''.join(title_div[0].xpath('descendant::a/text()')).strip()
if not title:
continue
item_url = ''.join(title_div[0].xpath('descendant::a/@href')).strip()
if not item_url:
continue
item_url = 'https://www.barnesandnoble.com' + item_url
author = ''
author_div = data.xpath('.//div[contains(@class, "product-shelf-author")]')
if author_div:
author = ''.join(author_div[0].xpath('descendant::a/text()')).strip()
price = ''
price_div = data.xpath('.//div[contains(@class, "product-shelf-pricing")]/div[contains(@class, "current")]')
if price_div:
spans = price_div[0].xpath('descendant::span')
if spans:
price = ''.join(spans[-1].xpath('descendant::text()'))
if '\n' in price:
price = price.split('\n')[1].split(',')[0]
s = SearchResult()
s.cover_url = cover_url
s.title = title.strip()
s.author = author.strip()
s.price = price.strip()
s.detail_item = item_url.strip()
s.drm = SearchResult.DRM_UNKNOWN
s.formats = 'Nook'
yield s
class BNStore(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
url = "https://bn.com"
if external or self.config.get('open_external', False):
open_url(QUrl(url_slash_cleaner(detail_item if detail_item else url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_item)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
yield from search_bn(query, max_results, timeout)
if __name__ == '__main__':
import sys
for result in search_bn(' '.join(sys.argv[1:]), write_html_to='/t/bn.html'):
print(result)
| 3,813 | Python | .py | 82 | 36.512195 | 127 | 0.591644 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,843 | amazon_it_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/amazon_it_plugin.py | #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 15 # Needed for dynamic plugin loading
from contextlib import closing
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
from lxml import html
from qt.core import QUrl
from calibre import browser
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.search_result import SearchResult
SEARCH_BASE_URL = 'https://www.amazon.it/s/'
SEARCH_BASE_QUERY = {'url': 'search-alias=digital-text'}
BY = 'di'
KINDLE_EDITION = 'Formato Kindle'
DETAILS_URL = 'https://amazon.it/dp/'
STORE_LINK = 'https://www.amazon.it'
DRM_SEARCH_TEXT = 'Simultaneous Device Usage'
DRM_FREE_TEXT = 'Unlimited'
def get_user_agent():
return 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko'
def search_amazon(query, max_results=10, timeout=60,
write_html_to=None,
base_url=SEARCH_BASE_URL,
base_query=SEARCH_BASE_QUERY,
field_keywords='field-keywords'
):
uquery = base_query.copy()
uquery[field_keywords] = query
def asbytes(x):
if isinstance(x, type('')):
x = x.encode('utf-8')
return x
uquery = {asbytes(k):asbytes(v) for k, v in uquery.items()}
url = base_url + '?' + urlencode(uquery)
br = browser(user_agent=get_user_agent())
counter = max_results
with closing(br.open(url, timeout=timeout)) as f:
raw = f.read()
if write_html_to is not None:
with open(write_html_to, 'wb') as f:
f.write(raw)
doc = html.fromstring(raw)
try:
results = doc.xpath('//div[@id="atfResults" and @class]')[0]
except IndexError:
return
if 's-result-list-parent-container' in results.get('class', ''):
data_xpath = "descendant-or-self::li[@class and contains(concat(' ', normalize-space(@class), ' '), ' s-result-item ')]"
format_xpath = './/a[@title="%s"]/@title' % KINDLE_EDITION
asin_xpath = '@data-asin'
cover_xpath = "descendant-or-self::img[@class and contains(concat(' ', normalize-space(@class), ' '), ' s-access-image ')]/@src"
title_xpath = "descendant-or-self::h2[@class and contains(concat(' ', normalize-space(@class), ' '), ' s-access-title ')]//text()"
author_xpath = './/span[starts-with(text(), "%s ")]/following-sibling::span//text()' % BY
price_xpath = ('descendant::div[@class="a-row a-spacing-none" and'
' not(span[contains(@class, "kindle-unlimited")])]//span[contains(@class, "s-price")]//text()')
else:
return
for data in doc.xpath(data_xpath):
if counter <= 0:
break
# Even though we are searching digital-text only Amazon will still
# put in results for non Kindle books (author pages). Se we need
# to explicitly check if the item is a Kindle book and ignore it
# if it isn't.
format = ''.join(data.xpath(format_xpath))
if 'kindle' not in format.lower():
continue
# We must have an asin otherwise we can't easily reference the
# book later.
asin = data.xpath(asin_xpath)
if asin:
asin = asin[0]
else:
continue
cover_url = ''.join(data.xpath(cover_xpath))
title = ''.join(data.xpath(title_xpath))
author = ''.join(data.xpath(author_xpath))
try:
author = author.split('by ', 1)[1].split(" (")[0]
except:
pass
price = ''.join(data.xpath(price_xpath))
counter -= 1
s = SearchResult()
s.cover_url = cover_url.strip()
s.title = title.strip()
s.author = author.strip()
s.price = price.strip()
s.detail_item = asin.strip()
s.formats = 'Kindle'
yield s
class AmazonKindleStore(StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
store_link = (DETAILS_URL + detail_item) if detail_item else STORE_LINK
open_url(QUrl(store_link))
def search(self, query, max_results=10, timeout=60):
for result in search_amazon(query, max_results=max_results, timeout=timeout):
yield result
def get_details(self, search_result, timeout):
url = DETAILS_URL
br = browser(user_agent=get_user_agent())
with closing(br.open(url + search_result.detail_item, timeout=timeout)) as nf:
idata = html.fromstring(nf.read())
if idata.xpath('boolean(//div[@class="content"]//li/b[contains(text(), "' +
DRM_SEARCH_TEXT + '")])'):
if idata.xpath('boolean(//div[@class="content"]//li[contains(., "' +
DRM_FREE_TEXT + '") and contains(b, "' +
DRM_SEARCH_TEXT + '")])'):
search_result.drm = SearchResult.DRM_UNLOCKED
else:
search_result.drm = SearchResult.DRM_UNKNOWN
else:
search_result.drm = SearchResult.DRM_LOCKED
return True
if __name__ == '__main__':
import sys
for result in search_amazon(' '.join(sys.argv[1:]), write_html_to='/t/amazon.html'):
print(result)
| 5,699 | Python | .py | 124 | 35.604839 | 142 | 0.582507 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,844 | empik_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/empik_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 10 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011-2023, Tomasz Długosz <tomek3d@gmail.com>'
__docformat__ = 'restructuredtext en'
from base64 import b64encode
from contextlib import closing
try:
from urllib.parse import quote
except ImportError:
from urllib import quote
from lxml import html
from qt.core import QUrl
from calibre import browser, url_slash_cleaner
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
def as_base64(data):
if not isinstance(data, bytes):
data = data.encode('utf-8')
ans = b64encode(data)
if isinstance(ans, bytes):
ans = ans.decode('ascii')
return ans
class EmpikStore(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
aff_root = 'https://www.a4b-tracking.com/pl/stat-click-text-link/78/58/'
url = 'https://www.empik.com/ebooki'
aff_url = aff_root + as_base64(url)
detail_url = None
if detail_item:
detail_url = aff_root + as_base64(detail_item)
if external or self.config.get('open_external', False):
open_url(QUrl(url_slash_cleaner(detail_url if detail_url else aff_url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_url if detail_url else aff_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
url = 'https://www.empik.com/ebooki/ebooki,3501,s?sort=scoreDesc&resultsPP={}&q={}'.format(max_results, quote(query))
br = browser()
counter = max_results
with closing(br.open(url, timeout=timeout)) as f:
doc = html.fromstring(f.read())
for data in doc.xpath('//div[@class="search-content js-search-content"]/div'):
if counter <= 0:
break
id = ''.join(data.xpath('.//a[@class="img seoImage"]/@href'))
if not id:
continue
title = ''.join(data.xpath('.//h2[@class="product-title"]/a/strong/text()'))
author = ', '.join(data.xpath('.//a[@class="smartAuthor "]/text()'))
cover_url = ''.join(data.xpath('.//a/img[@class="lazy"]/@lazy-img'))
price = ''.join(data.xpath('.//div[@class="price ta-price-tile "]/text()'))
# with closing(br.open('https://empik.com' + id.strip(), timeout=timeout/4)) as nf:
# idata = html.fromstring(nf.read())
# crawled = idata.xpath('.//a[(@class="chosen hrefstyle") or (@class="connectionsLink hrefstyle")]/text()')
# formats = ','.join([re.sub('ebook, ','', x.strip()) for x in crawled if 'ebook' in x])
counter -= 1
s = SearchResult()
s.cover_url = cover_url
s.title = title.split(' - ')[0]
s.author = author.strip()
s.price = price.strip()
s.detail_item = 'https://empik.com' + id.strip()
# s.formats = formats.upper().strip()
yield s
| 3,525 | Python | .py | 71 | 39.929577 | 126 | 0.60286 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,845 | smashwords_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/smashwords_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 6 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
import random
import re
from contextlib import closing
try:
from urllib.parse import quote
except ImportError:
from urllib import quote
from lxml import html
from qt.core import QUrl
from calibre import browser, url_slash_cleaner
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
def search(query, max_results=10, timeout=60, save_raw=None):
url = 'https://www.smashwords.com/books/search?query=' + quote(query)
br = browser()
try:
br.set_simple_cookie('adultOff', 'erotica', '.smashwords.com', path='/')
except AttributeError:
pass # old version of mechanize
counter = max_results
with closing(br.open(url, timeout=timeout)) as f:
raw = f.read()
if save_raw:
with open(save_raw, 'wb') as r:
r.write(raw)
doc = html.fromstring(raw)
for data in doc.xpath('//div[@id="pageContent"]//div[contains(@class, "library-book")]'):
if counter <= 0:
break
data = html.fromstring(html.tostring(data))
id_a = ''.join(data.xpath('//span[contains(@class, "library-title")]/a/@href'))
if not id_a:
continue
cover_url = ''.join(data.xpath('//img[contains(@class, "book-list-image")]/@src'))
title = ''.join(data.xpath('.//span[contains(@class, "library-title")]//text()'))
author = ''.join(data.xpath('.//span[contains(@class, "library-by-line")]/a//text()'))
price = ''.join(data.xpath('.//div[@class="subnote"]//text()'))
if 'Price:' in price:
try:
price = price.partition('Price:')[2]
price = re.sub(r'\s', ' ', price).strip()
price = price.split(' ')[0].strip()
except Exception:
price = 'Unknown'
if price == 'Free!':
price = '$0.00'
counter -= 1
s = SearchResult()
s.cover_url = cover_url
s.title = title.strip()
s.author = author.strip()
s.price = price
s.detail_item = id_a
s.drm = SearchResult.DRM_UNLOCKED
yield s
class SmashwordsStore(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
url = 'https://www.smashwords.com/'
aff_id = '?ref=usernone'
# Use Kovid's affiliate id 30% of the time.
if random.randint(1, 10) in (1, 2, 3):
aff_id = '?ref=kovidgoyal'
detail_url = None
if detail_item:
detail_url = url + detail_item + aff_id
url = url + aff_id
if external or self.config.get('open_external', False):
open_url(QUrl(url_slash_cleaner(detail_url if detail_url else url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
for a in search(query, max_results=max_results, timeout=timeout):
yield a
def get_details(self, search_result, timeout):
url = 'https://www.smashwords.com/'
br = browser()
with closing(br.open(url + search_result.detail_item, timeout=timeout)) as nf:
idata = html.fromstring(nf.read())
search_result.formats = ', '.join(list(set(idata.xpath('//p//abbr//text()'))))
return True
if __name__ == '__main__':
import sys
for r in search(' '.join(sys.argv[1:]), save_raw='/t/raw.html'):
print(r)
| 4,169 | Python | .py | 96 | 34.260417 | 98 | 0.593325 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,846 | archive_org_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/archive_org_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 4 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.opensearch_store import OpenSearchOPDSStore, open_search
from calibre.gui2.store.search_result import SearchResult
SEARCH_URL = 'http://bookserver.archive.org/catalog/opensearch.xml'
def search(query, max_results=10, timeout=60):
for result in open_search(SEARCH_URL, query, max_results=max_results, timeout=timeout):
yield result
class ArchiveOrgStore(BasicStoreConfig, OpenSearchOPDSStore):
open_search_url = SEARCH_URL
web_url = 'http://www.archive.org/details/texts'
# http://bookserver.archive.org/catalog/
def search(self, query, max_results=10, timeout=60):
for s in search(query, max_results, timeout):
s.detail_item = 'http://www.archive.org/details/' + s.detail_item.split(':')[-1]
s.price = '$0.00'
s.drm = SearchResult.DRM_UNLOCKED
yield s
if __name__ == '__main__':
import sys
for s in search(' '.join(sys.argv[1:])):
print(s)
| 1,322 | Python | .py | 27 | 43.777778 | 92 | 0.701248 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,847 | amazon_de_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/amazon_de_plugin.py | #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 16 # Needed for dynamic plugin loading
from calibre.gui2.store import StorePlugin
try:
from calibre.gui2.store.amazon_base import AmazonStore
except ImportError:
class AmazonStore:
minimum_calibre_version = 9999, 0, 0
class Base(AmazonStore):
scraper_storage = []
SEARCH_BASE_URL = 'https://www.amazon.de/s/'
SEARCH_BASE_QUERY = {'url': 'search-alias=digital-text'}
BY = 'von'
KINDLE_EDITION = 'Kindle Ausgabe'
DETAILS_URL = 'https://amazon.de/dp/'
STORE_LINK = 'https://www.amazon.de'
class AmazonKindleStore(Base, StorePlugin):
pass
if __name__ == '__main__':
Base().develop_plugin()
| 868 | Python | .py | 23 | 34.043478 | 82 | 0.716168 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,848 | ozon_ru_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/ozon_ru_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 3 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011-2013, Roman Mukhin <ramses_ru at hotmail.com>'
__docformat__ = 'restructuredtext en'
from contextlib import closing
try:
from urllib.parse import quote_plus
except ImportError:
from urllib import quote_plus
from qt.core import QUrl
from calibre import browser, url_slash_cleaner
from calibre.ebooks.chardet import xml_to_unicode
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
shop_url = 'http://www.ozon.ru'
def parse_html(raw):
try:
from html5_parser import parse
except ImportError:
# Old versions of calibre
import html5lib
return html5lib.parse(raw, treebuilder='lxml', namespaceHTMLElements=False)
else:
return parse(raw)
def search(query, max_results=15, timeout=60):
url = 'http://www.ozon.ru/?context=search&text=%s&store=1,0&group=div_book' % quote_plus(query)
counter = max_results
br = browser()
with closing(br.open(url, timeout=timeout)) as f:
raw = xml_to_unicode(f.read(), strip_encoding_pats=True, assume_utf8=True)[0]
root = parse_html(raw)
for tile in root.xpath('//*[@class="bShelfTile inline"]'):
if counter <= 0:
break
counter -= 1
s = SearchResult(store_name='OZON.ru')
s.detail_item = shop_url + tile.xpath('descendant::a[@class="eShelfTile_Link"]/@href')[0]
s.title = tile.xpath('descendant::span[@class="eShelfTile_ItemNameText"]/@title')[0]
s.author = tile.xpath('descendant::span[@class="eShelfTile_ItemPerson"]/@title')[0]
s.price = ''.join(tile.xpath('descendant::div[contains(@class, "eShelfTile_Price")]/text()'))
s.cover_url = 'http:' + tile.xpath('descendant::img/@data-original')[0]
s.price = format_price_in_RUR(s.price)
yield s
class OzonRUStore(StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
url = detail_item or shop_url
if external or self.config.get('open_external', False):
open_url(QUrl(url_slash_cleaner(url)))
else:
d = WebStoreDialog(self.gui, shop_url, parent, url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=15, timeout=60):
for s in search(query, max_results=max_results, timeout=timeout):
yield s
def format_price_in_RUR(price):
'''
Try to format price according ru locale: '12 212,34 руб.'
@param price: price in format like 25.99
@return: formatted price if possible otherwise original value
@rtype: unicode
'''
price = price.replace('\xa0', '').replace(',', '.').strip() + ' py6'
return price
if __name__ == '__main__':
import sys
for r in search(sys.argv[-1]):
print(r)
| 3,204 | Python | .py | 73 | 37.082192 | 105 | 0.658073 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,849 | google_books_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/google_books_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 7 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from contextlib import closing
try:
from urllib.parse import quote_plus
except ImportError:
from urllib import quote_plus
from lxml import html
from qt.core import QUrl
from calibre import browser, url_slash_cleaner
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
def parse_html(raw):
try:
from html5_parser import parse
except ImportError:
# Old versions of calibre
import html5lib
return html5lib.parse(raw, treebuilder='lxml', namespaceHTMLElements=False)
else:
return parse(raw)
def search_google(query, max_results=10, timeout=60, write_html_to=None):
url = 'https://www.google.com/search?tbm=bks&q=' + quote_plus(query)
br = browser()
counter = max_results
with closing(br.open(url, timeout=timeout)) as f:
raw = f.read()
doc = parse_html(raw)
if write_html_to is not None:
praw = html.tostring(doc, encoding='utf-8')
open(write_html_to, 'wb').write(praw)
for data in doc.xpath('//div[@id="rso"]/div'):
if counter <= 0:
break
h3 = data.xpath('descendant::h3')
if not h3:
continue
h3 = h3[0]
a = h3.getparent()
id = a.get('href')
if not id:
continue
title = ''.join(data.xpath('.//h3//text()')).strip()
authors = data.xpath('descendant::a[@class="fl" and @href]//text()')
while authors and authors[-1].strip().lower() in ('preview', 'read', 'more editions'):
authors = authors[:-1]
if not authors:
continue
author = ' & '.join(authors)
counter -= 1
s = SearchResult()
s.title = title.strip()
s.author = author.strip()
s.detail_item = id.strip()
s.drm = SearchResult.DRM_UNKNOWN
yield s
class GoogleBooksStore(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
url = 'https://books.google.com/books'
if True or external or self.config.get('open_external', False):
open_url(QUrl(url_slash_cleaner(detail_item if detail_item else url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_item)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
for result in search_google(query, max_results=max_results, timeout=timeout):
yield result
def get_details(self, search_result, timeout):
br = browser()
with closing(br.open(search_result.detail_item, timeout=timeout)) as nf:
doc = parse_html(nf.read())
search_result.cover_url = ''.join(doc.xpath('//div[@class="sidebarcover"]//img/@src'))
# Try to get the set price.
price = ''.join(doc.xpath('//div[@id="gb-get-book-container"]//a/text()'))
if 'read' in price.lower():
price = 'Unknown'
elif 'free' in price.lower() or not price.strip():
price = '$0.00'
elif '-' in price:
a, b, price = price.partition(' - ')
search_result.price = price.strip()
search_result.formats = ', '.join(doc.xpath('//div[contains(@class, "download-panel-div")]//a/text()')).upper()
if not search_result.formats:
search_result.formats = _('Unknown')
return True
if __name__ == '__main__':
import sys
for result in search_google(' '.join(sys.argv[1:]), write_html_to='/t/google.html'):
print(result)
| 4,252 | Python | .py | 98 | 34.153061 | 123 | 0.602375 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,850 | woblink_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/woblink_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 15 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011-2019, Tomasz Długosz <tomek3d@gmail.com>'
__docformat__ = 'restructuredtext en'
from base64 import b64encode
try:
from urllib.parse import quote_plus, urlencode
except ImportError:
from urllib import quote_plus, urlencode
from lxml import html
from mechanize import Request
from qt.core import QUrl
from calibre import browser, url_slash_cleaner
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
def as_base64(data):
if not isinstance(data, bytes):
data = data.encode('utf-8')
ans = b64encode(data)
if isinstance(ans, bytes):
ans = ans.decode('ascii')
return ans
def search(query, max_results=10, timeout=60):
url = 'https://woblink.com/publication/ajax?mode=none&query=' + quote_plus(query)
if max_results > 10:
if max_results > 20:
url += '&limit=30'
else:
url += '&limit=20'
br = browser(user_agent='CalibreCrawler/1.0')
br.set_handle_gzip(True)
rq = Request(url, headers={
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest',
'Referrer':'https://woblink.com/ebooki-kategorie',
'Cache-Control':'max-age=0',
}, data=urlencode({
'nw_filtry_filtr_zakrescen_formularz[min]':'0',
'nw_filtry_filtr_zakrescen_formularz[max]':'350',
}))
r = br.open(rq)
raw = r.read()
doc = html.fromstring('<html><body>' + raw.decode('utf-8') + '</body></html>')
counter = max_results
for data in doc.xpath('//div[@class="nw_katalog_lista_ksiazka ebook " or @class="nw_katalog_lista_ksiazka ebook promocja"]'):
if counter <= 0:
break
id = ''.join(data.xpath('.//div[@class="nw_katalog_lista_ksiazka_okladka nw_okladka"]/a[1]/@href'))
if not id:
continue
cover_url = ''.join(data.xpath('.//div[@class="nw_katalog_lista_ksiazka_okladka nw_okladka"]/a[1]/img/@src'))
title = ''.join(data.xpath('.//h3[@class="nw_katalog_lista_ksiazka_detale_tytul"]/a[1]/text()'))
author = ', '.join(data.xpath('.//p[@class="nw_katalog_lista_ksiazka_detale_autor"]/a/text()'))
price = ''.join(data.xpath('.//div[@class="nw_opcjezakupu_cena"]/span[2]/text()'))
formats = ', '.join(data.xpath('.//p[@class="nw_katalog_lista_ksiazka_detale_format"]/span/text()'))
s = SearchResult()
s.cover_url = cover_url
s.title = title.strip()
s.author = author.strip()
s.price = price + ' zł'
s.detail_item = id.strip()
s.formats = formats
counter -= 1
s.drm = SearchResult.DRM_LOCKED if 'DRM' in formats else SearchResult.DRM_UNLOCKED
yield s
class WoblinkStore(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
aff_root = 'https://www.a4b-tracking.com/pl/stat-click-text-link/16/58/'
url = 'https://woblink.com/publication'
aff_url = aff_root + as_base64(url)
detail_url = None
if detail_item:
detail_url = aff_root + as_base64(detail_item)
if external or self.config.get('open_external', False):
open_url(QUrl(url_slash_cleaner(detail_url if detail_url else aff_url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_url if detail_url else aff_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
for s in search(query, max_results, timeout):
yield s
if __name__ == '__main__':
from pprint import pprint
pprint(list(search('Franciszek')))
| 4,123 | Python | .py | 91 | 38.43956 | 129 | 0.646281 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,851 | swiatebookow_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/swiatebookow_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 2 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2017-2019, Tomasz Długosz <tomek3d@gmail.com>'
__docformat__ = 'restructuredtext en'
from base64 import b64encode
from contextlib import closing
try:
from urllib.parse import quote
except ImportError:
from urllib import quote
from lxml import html
from qt.core import QUrl
from calibre import browser, url_slash_cleaner
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
def as_base64(data):
if not isinstance(data, bytes):
data = data.encode('utf-8')
ans = b64encode(data)
if isinstance(ans, bytes):
ans = ans.decode('ascii')
return ans
class SwiatEbookowStore(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
aff_root = 'https://www.a4b-tracking.com/pl/stat-click-text-link/181/58/'
url = 'https://www.swiatebookow.pl/'
aff_url = aff_root + as_base64(url)
detail_url = None
if detail_item:
detail_url = aff_root + as_base64(detail_item)
if external or self.config.get('open_external', False):
open_url(QUrl(url_slash_cleaner(detail_url if detail_url else aff_url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_url if detail_url else aff_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
br = browser()
page=1
counter = max_results
while counter:
with closing(br.open('https://www.swiatebookow.pl/ebooki/?q=' + quote(query) + '&page={}'.format(page), timeout=timeout)) as f:
doc = html.fromstring(f.read().decode('utf-8'))
for data in doc.xpath('//div[@class="category-item-container"]//div[@class="book-large"]'):
if counter <= 0:
break
id = ''.join(data.xpath('./a/@href'))
if not id:
continue
cover_url = ''.join(data.xpath('.//div[@class="cover-xs"]//img/@data-src'))
price = ''.join(data.xpath('.//span[@class="item-price"]/text()')+data.xpath('.//span[@class="sub-price"]/text()'))
title = ''.join(data.xpath('.//div[@class="largebox-book-info"]//h2/a/text()'))
author = ', '.join(data.xpath('.//div[@class="largebox-book-info"]/p/a/text()'))
counter -= 1
s = SearchResult()
s.cover_url = 'https://www.swiatebookow.pl' + cover_url
s.title = title.strip()
s.author = author.strip()
s.price = price
s.detail_item = 'https://www.swiatebookow.pl' + id
# s.formats = formats.upper()
s.drm = SearchResult.DRM_UNLOCKED
yield s
if not doc.xpath('//div[@class="paging_bootstrap pagination"]//a[@class="next"]'):
break
page+=1
| 3,488 | Python | .py | 72 | 37.569444 | 139 | 0.589154 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,852 | publio_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/publio_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 9 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2012-2017, Tomasz Długosz <tomek3d@gmail.com>'
__docformat__ = 'restructuredtext en'
try:
from urllib.parse import quote
except ImportError:
from urllib import quote
from base64 import b64encode
from contextlib import closing
from lxml import html
from qt.core import QUrl
from calibre import browser, url_slash_cleaner
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
def as_base64(data):
if not isinstance(data, bytes):
data = data.encode('utf-8')
ans = b64encode(data)
if isinstance(ans, bytes):
ans = ans.decode('ascii')
return ans
class PublioStore(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
aff_root = 'https://www.a4b-tracking.com/pl/stat-click-text-link/29/58/'
url = 'http://www.publio.pl/'
aff_url = aff_root + as_base64(url)
detail_url = None
if detail_item:
detail_url = aff_root + as_base64(detail_item)
if external or self.config.get('open_external', False):
open_url(QUrl(url_slash_cleaner(detail_url if detail_url else aff_url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_url if detail_url else aff_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=20, timeout=60):
br = browser()
counter = max_results
page = 1
while counter:
with closing(br.open('http://www.publio.pl/e-booki,strona{}.html?q={}'.format(page, quote(query)), timeout=timeout)) as f: # noqa
doc = html.fromstring(f.read())
for data in doc.xpath('//div[@class="products-list"]//div[@class="product-tile"]'):
if counter <= 0:
break
id = ''.join(data.xpath('.//a[@class="product-tile-cover"]/@href'))
if not id:
continue
cover_url = ''.join(data.xpath('.//img[@class="product-tile-cover-photo"]/@src'))
title = ''.join(data.xpath('.//span[@class="product-tile-title-long"]/text()'))
author = ', '.join(data.xpath('.//span[@class="product-tile-author"]/a/text()'))
price = ''.join(data.xpath('.//div[@class="product-tile-price-wrapper "]/a/ins/text()'))
formats = ''.join(data.xpath('.//a[@class="product-tile-cover"]/img/@alt')).split(' - ebook ')[1]
counter -= 1
s = SearchResult()
s.cover_url = 'http://www.publio.pl' + cover_url
s.title = title.strip()
s.author = author
s.price = price
s.detail_item = 'http://www.publio.pl' + id.strip()
s.formats = formats.upper().strip()
yield s
if not doc.xpath('boolean(//a[@class="next"])'):
break
page+=1
| 3,487 | Python | .py | 72 | 37.527778 | 142 | 0.58515 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,853 | manybooks_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/manybooks_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 2 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
import mimetypes
from contextlib import closing
from lxml import etree
from calibre import browser
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.opensearch_store import OpenSearchOPDSStore
from calibre.gui2.store.search_result import SearchResult
from calibre.utils.opensearch.description import Description
from calibre.utils.opensearch.query import Query
def search_manybooks(query, max_results=10, timeout=60, open_search_url='http://www.manybooks.net/opds/'):
'''
Manybooks uses a very strange opds feed. The opds
main feed is structured like a stanza feed. The
search result entries give very little information
and requires you to go to a detail link. The detail
link has the wrong type specified (text/html instead
of application/atom+xml).
'''
description = Description(open_search_url)
url_template = description.get_best_template()
if not url_template:
return
oquery = Query(url_template)
# set up initial values
oquery.searchTerms = query
oquery.count = max_results
url = oquery.url()
counter = max_results
br = browser()
with closing(br.open(url, timeout=timeout)) as f:
raw_data = f.read()
raw_data = raw_data.decode('utf-8', 'replace')
doc = etree.fromstring(raw_data, parser=etree.XMLParser(recover=True, no_network=True, resolve_entities=False))
for data in doc.xpath('//*[local-name() = "entry"]'):
if counter <= 0:
break
counter -= 1
s = SearchResult()
detail_links = data.xpath('./*[local-name() = "link" and @type = "text/html"]')
if not detail_links:
continue
detail_link = detail_links[0]
detail_href = detail_link.get('href')
if not detail_href:
continue
s.detail_item = 'http://manybooks.net/titles/' + detail_href.split('tid=')[-1] + '.html'
# These can have HTML inside of them. We are going to get them again later
# just in case.
s.title = ''.join(data.xpath('./*[local-name() = "title"]//text()')).strip()
s.author = ', '.join(data.xpath('./*[local-name() = "author"]//text()')).strip()
# Follow the detail link to get the rest of the info.
with closing(br.open(detail_href, timeout=timeout/4)) as df:
ddoc = etree.fromstring(df.read(), parser=etree.XMLParser(recover=True, no_network=True, resolve_entities=False))
ddata = ddoc.xpath('//*[local-name() = "entry"][1]')
if ddata:
ddata = ddata[0]
# This is the real title and author info we want. We got
# it previously just in case it's not specified here for some reason.
s.title = ''.join(ddata.xpath('./*[local-name() = "title"]//text()')).strip()
s.author = ', '.join(ddata.xpath('./*[local-name() = "author"]//text()')).strip()
if s.author.startswith(','):
s.author = s.author[1:]
if s.author.endswith(','):
s.author = s.author[:-1]
s.cover_url = ''.join(ddata.xpath('./*[local-name() = "link" and @rel = "http://opds-spec.org/thumbnail"][1]/@href')).strip()
for link in ddata.xpath('./*[local-name() = "link" and @rel = "http://opds-spec.org/acquisition"]'):
type = link.get('type')
href = link.get('href')
if type:
ext = mimetypes.guess_extension(type)
if ext:
ext = ext[1:].upper().strip()
s.downloads[ext] = href
s.price = '$0.00'
s.drm = SearchResult.DRM_UNLOCKED
s.formats = 'EPUB, PDB (eReader, PalmDoc, zTXT, Plucker, iSilo), FB2, ZIP, AZW, MOBI, PRC, LIT, PKG, PDF, TXT, RB, RTF, LRF, TCR, JAR'
yield s
class ManyBooksStore(BasicStoreConfig, OpenSearchOPDSStore):
open_search_url = 'http://www.manybooks.net/opds/'
web_url = 'http://manybooks.net'
def search(self, query, max_results=10, timeout=60):
for r in search_manybooks(query, max_results=max_results, timeout=timeout, open_search_url=self.open_search_url):
yield r
if __name__ == '__main__':
import sys
for result in search_manybooks(' '.join(sys.argv[1:])):
print(result)
| 4,880 | Python | .py | 93 | 41.430108 | 146 | 0.590842 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,854 | libri_de_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/libri_de_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 8 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from contextlib import closing
try:
from urllib.parse import quote
except ImportError:
from urllib import quote
from lxml import html
from qt.core import QUrl
from calibre import browser
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
class LibreDEStore(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
url = 'https://clk.tradedoubler.com/click?p=324630&a=3252627'
url_details = ('https://clk.tradedoubler.com/click?p=324630&a=3252627'
'&url=https%3A%2F%2Fwww.ebook.de%2Fshop%2Faction%2FproductDetails%3FartiId%3D{0}')
if external or self.config.get('open_external', False):
if detail_item:
url = url_details.format(detail_item)
open_url(QUrl(url))
else:
detail_url = None
if detail_item:
detail_url = url_details.format(detail_item)
d = WebStoreDialog(self.gui, url, parent, detail_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
url = ('http://www.ebook.de/de/pathSearch?nav=52122&searchString=' + quote(query))
br = browser()
counter = max_results
with closing(br.open(url, timeout=timeout)) as f:
doc = html.fromstring(f.read())
for data in doc.xpath('//div[@class="articlecontainer"]'):
if counter <= 0:
break
id_ = ''.join(data.xpath('.//div[@class="trackArtiId"]/text()'))
if not id_:
continue
details = data.xpath('./div[contains(@class, "articleinfobox")]')
if not details:
continue
details = details[0]
title = ''.join(details.xpath('./div[@class="title"]/a/text()')).strip()
author = ''.join(details.xpath('.//div[@class="author"]/text()')).strip()
if author.startswith('von'):
author = author[4:]
pdf = details.xpath(
'boolean(.//span[@class="bindername" and contains(text(), "pdf")]/text())')
epub = details.xpath(
'boolean(.//span[@class="bindername" and contains(text(), "epub")]/text())')
mobi = details.xpath(
'boolean(.//span[@class="bindername" and contains(text(), "mobipocket")]/text())')
cover_url = ''.join(data.xpath('.//div[@class="coverimg"]/a/img/@src'))
price = ''.join(data.xpath('.//div[@class="preis"]/text()')).replace('*', '').strip()
counter -= 1
s = SearchResult()
s.cover_url = cover_url
s.title = title.strip()
s.author = author.strip()
s.price = price
s.drm = SearchResult.DRM_UNKNOWN
s.detail_item = id_
formats = []
if epub:
formats.append('ePub')
if pdf:
formats.append('PDF')
if mobi:
formats.append('MOBI')
s.formats = ', '.join(formats)
yield s
| 3,848 | Python | .py | 81 | 35 | 106 | 0.5584 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,855 | ebookshoppe_uk_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/ebookshoppe_uk_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 1 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
try:
from urllib.parse import quote
except ImportError:
from urllib2 import quote
from contextlib import closing
from lxml import html
from qt.core import QUrl
from calibre import browser
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
class EBookShoppeUKStore(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
url_details = 'http://www.awin1.com/cread.php?awinmid=1414&awinaffid=120917&clickref=&p={0}'
url = 'http://www.awin1.com/awclick.php?mid=2666&id=120917'
if external or self.config.get('open_external', False):
if detail_item:
url = url_details.format(detail_item)
open_url(QUrl(url))
else:
detail_url = None
if detail_item:
detail_url = url_details.format(detail_item)
d = WebStoreDialog(self.gui, url, parent, detail_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
url = 'http://www.ebookshoppe.com/search.php?search_query=' + quote(query)
br = browser()
br.addheaders = [("Referer", "http://www.ebookshoppe.com/")]
counter = max_results
with closing(br.open(url, timeout=timeout)) as f:
doc = html.fromstring(f.read())
for data in doc.xpath('//ul[@class="ProductList"]/li'):
if counter <= 0:
break
id = ''.join(data.xpath('./div[@class="ProductDetails"]/'
'strong/a/@href')).strip()
if not id:
continue
cover_url = ''.join(data.xpath('./div[@class="ProductImage"]/a/img/@src'))
title = ''.join(data.xpath('./div[@class="ProductDetails"]/strong/a/text()'))
price = ''.join(data.xpath('./div[@class="ProductPriceRating"]/em/text()'))
counter -= 1
s = SearchResult()
s.cover_url = cover_url
s.title = title.strip()
s.price = price
s.drm = SearchResult.DRM_UNLOCKED
s.detail_item = id
self.get_author_and_formats(s, timeout)
if not s.author:
continue
yield s
def get_author_and_formats(self, search_result, timeout):
br = browser()
with closing(br.open(search_result.detail_item, timeout=timeout)) as nf:
idata = html.fromstring(nf.read())
author = ''.join(idata.xpath('//div[@id="ProductOtherDetails"]/dl/dd[1]/text()'))
if author:
search_result.author = author
formats = idata.xpath('//dl[@class="ProductAddToCart"]/dd/'
'ul[@class="ProductOptionList"]/li/label/text()')
if formats:
search_result.formats = ', '.join(formats)
search_result.drm = SearchResult.DRM_UNKNOWN
return True
| 3,597 | Python | .py | 76 | 36.092105 | 100 | 0.592011 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,856 | legimi_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/legimi_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 12 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011-2023, Tomasz Długosz <tomek3d@gmail.com>'
__docformat__ = 'restructuredtext en'
from base64 import b64encode
from contextlib import closing
try:
from urllib.parse import quote_plus
except ImportError:
from urllib import quote_plus
from lxml import html
from qt.core import QUrl
from calibre import browser, url_slash_cleaner
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
def as_base64(data):
if not isinstance(data, bytes):
data = data.encode('utf-8')
ans = b64encode(data)
if isinstance(ans, bytes):
ans = ans.decode('ascii')
return ans
class LegimiStore(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
aff_root = 'https://www.a4b-tracking.com/pl/stat-click-text-link/9/58/'
url = 'https://www.legimi.pl/ebooki/'
aff_url = aff_root + as_base64(url)
detail_url = None
if detail_item:
detail_url = aff_root + as_base64(detail_item)
if external or self.config.get('open_external', False):
open_url(QUrl(url_slash_cleaner(detail_url if detail_url else aff_url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_url if detail_url else aff_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
url = 'https://www.legimi.pl/ebooki/?sort=score&filters=ebooks&searchphrase=' + quote_plus(query)
br = browser()
counter = max_results
with closing(br.open(url, timeout=timeout)) as f:
doc = html.fromstring(f.read())
for data in doc.xpath('//div[@class="book-search row auto-clear"]/div'):
if counter <= 0:
break
id = ''.join(data.xpath('.//div[@class="panel-body"]/a/@href'))
if not id:
continue
cover_url = ''.join(data.xpath('.//div[@class="img-content"]/img/@data-src'))
title = ''.join(data.xpath('.//a[@class="book-title clampBookTitle"]/text()'))
author = ' '.join(data.xpath('.//div[@class="authors-container clampBookAuthors"]/a/text()'))
counter -= 1
s = SearchResult()
s.cover_url = cover_url
s.title = title.strip()
s.author = author.strip()
s.detail_item = 'https://www.legimi.pl' + id.strip()
s.drm = SearchResult.DRM_UNLOCKED
yield s
def get_details(self, search_result, timeout):
br = browser()
with closing(br.open(search_result.detail_item, timeout=timeout/2)) as nf:
idata = html.fromstring(nf.read())
price = ''.join(idata.xpath('.//section[@class="book-sale-options"]//li[@data-test="ebook-retail-option"]//p[@class="light-text"]/text()'))
search_result.price = price.split('bez abonamentu ')[-1]
return True
| 3,459 | Python | .py | 72 | 38.930556 | 151 | 0.62474 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,857 | kobo_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/kobo_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 12 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
try:
from urllib.parse import quote_plus
except ImportError:
from urllib import quote_plus
from lxml import etree, html
from calibre import url_slash_cleaner
from calibre.ebooks.metadata import authors_to_string
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
def read_url(url, timeout=60):
# Kobo uses Akamai which has some bot detection that uses network/tls
# protocol data. So use the Chromium network stack to make the request
from calibre.scraper.simple import read_url as ru
return ru(read_url.storage, url, timeout=timeout)
read_url.storage = []
def search_kobo(query, max_results=10, timeout=60, write_html_to=None):
from css_selectors import Select
url = 'https://www.kobobooks.com/search/search.html?q=' + quote_plus(query)
raw = read_url(url, timeout=timeout)
if write_html_to is not None:
with open(write_html_to, 'w') as f:
f.write(raw)
doc = html.fromstring(raw)
select = Select(doc)
for i, item in enumerate(select('[data-testid=search-results-items] [role=listitem]')):
if i == max_results:
break
for img in select('img[data-testid=cover]', item):
cover_url = img.get('src')
if cover_url.startswith('//'):
cover_url = 'https:' + cover_url
break
else:
cover_url = None
for a in select('h2 a[data-testid=title]', item):
title = etree.tostring(a, method='text', encoding='unicode').strip()
url = a.get('href')
break
else:
title = None
if title:
for p in select('p.subtitle', item):
title += ' - ' + etree.tostring(p, method='text', encoding='unicode').strip()
authors = []
for a in select('[data-testid=authors]', item):
authors.append(etree.tostring(a, method='text', encoding='unicode').strip())
authors = authors_to_string(authors)
for p in select('[data-testid=price-value]', item):
price = etree.tostring(p, method='text', encoding='unicode').strip()
break
else:
price = None
if title and authors and url:
s = SearchResult()
s.cover_url = cover_url
s.store_name = 'Kobo'
s.title = title
s.author = authors
s.price = price
s.detail_item = url
s.formats = 'EPUB'
s.drm = SearchResult.DRM_UNKNOWN
yield s
class KoboStore(BasicStoreConfig, StorePlugin):
minimum_calibre_version = (5, 40, 1)
def open(self, parent=None, detail_item=None, external=False):
if detail_item:
purl = detail_item
url = purl
else:
purl = None
url = 'https://kobo.com'
if external or self.config.get('open_external', False):
open_url(url_slash_cleaner(url))
else:
d = WebStoreDialog(self.gui, url, parent, purl)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
for result in search_kobo(query, max_results=max_results, timeout=timeout):
yield result
def get_details(self, search_result, timeout):
raw = read_url(search_result.detail_item, timeout=timeout)
idata = html.fromstring(raw)
if idata.xpath('boolean(//div[@class="bookitem-secondary-metadata"]//li[contains(text(), "Download options")])'):
if idata.xpath('boolean(//div[@class="bookitem-secondary-metadata"]//li[contains(text(), "DRM-Free")])'):
search_result.drm = SearchResult.DRM_UNLOCKED
if idata.xpath('boolean(//div[@class="bookitem-secondary-metadata"]//li[contains(text(), "Adobe DRM")])'):
search_result.drm = SearchResult.DRM_LOCKED
else:
search_result.drm = SearchResult.DRM_UNKNOWN
return True
if __name__ == '__main__':
import sys
for result in search_kobo(' '.join(sys.argv[1:]), write_html_to='/t/kobo.html'):
print(result)
| 4,676 | Python | .py | 106 | 35.443396 | 121 | 0.625303 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,858 | pragmatic_bookshelf_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/pragmatic_bookshelf_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 1 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.opensearch_store import OpenSearchOPDSStore
from calibre.gui2.store.search_result import SearchResult
class PragmaticBookshelfStore(BasicStoreConfig, OpenSearchOPDSStore):
open_search_url = 'http://pragprog.com/catalog/search-description'
web_url = 'http://pragprog.com/'
# http://pragprog.com/catalog.opds
def search(self, query, max_results=10, timeout=60):
for s in OpenSearchOPDSStore.search(self, query, max_results, timeout):
s.drm = SearchResult.DRM_UNLOCKED
s.formats = 'EPUB, PDF, MOBI'
yield s
| 940 | Python | .py | 18 | 47.444444 | 82 | 0.73523 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,859 | bubok_publishing_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/bubok_publishing_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 2 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2014, Rafael Vega <rafavega@gmail.com>'
__docformat__ = 'restructuredtext en'
from contextlib import closing
try:
from urllib.parse import quote_plus
except ImportError:
from urllib import quote_plus
from lxml import html
from qt.core import QUrl
from calibre import browser, url_slash_cleaner
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
class BubokPublishingStore(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
url = 'https://www.bubok.es/tienda'
if external or self.config.get('open_external', False):
open_url(QUrl(url_slash_cleaner(detail_item if detail_item else url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_item)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
url = 'http://www.bubok.es/resellers/calibre_search/' + quote_plus(query)
br = browser()
counter = max_results
with closing(br.open(url, timeout=timeout)) as f:
doc = html.fromstring(f.read())
for data in doc.xpath('//div[contains(@class, "libro")]'):
if counter <= 0:
break
id = ''.join(data.xpath('.//div[@class="url"]/text()'))
title = ''.join(data.xpath('.//div[@class="titulo"]/text()'))
author = ''.join(data.xpath('.//div[@class="autor"]/text()'))
price = ''.join(data.xpath('.//div[@class="precio"]/text()'))
formats = ''.join(data.xpath('.//div[@class="formatos"]/text()'))
cover = ''.join(data.xpath('.//div[@class="portada"]/text()'))
counter -= 1
s = SearchResult()
s.title = title.strip()
s.author = author.strip()
s.detail_item = id.strip()
s.price = price.strip()
s.drm = SearchResult.DRM_UNLOCKED
s.formats = formats.strip()
s.cover_url = cover.strip()
yield s
def get_details(self, search_result, timeout):
return True
| 2,647 | Python | .py | 56 | 37.678571 | 82 | 0.609728 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,860 | amazon_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/amazon_plugin.py | #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 20 # Needed for dynamic plugin loading
from calibre.gui2.store import StorePlugin
try:
from calibre.gui2.store.amazon_base import AmazonStore
except ImportError:
class AmazonStore:
minimum_calibre_version = 9999, 0, 0
class Base(AmazonStore):
scraper_storage = []
class AmazonKindleStore(Base, StorePlugin):
pass
if __name__ == '__main__':
Base().develop_plugin()
| 620 | Python | .py | 17 | 33.294118 | 82 | 0.752525 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,861 | litres_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/litres_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 2 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011, Roman Mukhin <ramses_ru at hotmail.com>'
__docformat__ = 'restructuredtext en'
import random
import re
try:
from urllib.parse import quote
except ImportError:
from urllib import quote
from contextlib import closing
from lxml import etree
from qt.core import QUrl
from calibre import browser, prints, url_slash_cleaner
from calibre.ebooks.chardet import xml_to_unicode
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
class LitResStore(BasicStoreConfig, StorePlugin):
shop_url = u'http://www.litres.ru'
# http://robot.litres.ru/pages/biblio_book/?art=174405
def open(self, parent=None, detail_item=None, external=False):
aff_id = u'?' + _get_affiliate_id()
url = self.shop_url + aff_id
detail_url = None
if detail_item:
# http://www.litres.ru/pages/biblio_book/?art=157074
detail_url = self.shop_url + u'/pages/biblio_book/' + aff_id +\
u'&art=' + quote(detail_item)
if external or self.config.get('open_external', False):
open_url(QUrl(url_slash_cleaner(detail_url if detail_url else url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
search_url = u'http://robot.litres.ru/pages/catalit_browser/?checkpoint=2000-01-02&'\
'search=%s&limit=0,%s'
search_url = search_url % (quote(query), max_results)
counter = max_results
br = browser()
br.addheaders.append(['Accept-Encoding','gzip'])
with closing(br.open(search_url, timeout=timeout)) as r:
ungzipResponse(r,br)
raw= xml_to_unicode(r.read(), strip_encoding_pats=True, assume_utf8=True)[0]
doc = etree.fromstring(raw, parser=etree.XMLParser(recover=True, no_network=True, resolve_entities=False))
for data in doc.xpath('//*[local-name() = "fb2-book"]'):
if counter <= 0:
break
counter -= 1
try:
sRes = self.create_search_result(data)
except Exception as e:
prints('ERROR: cannot parse search result #%s: %s'%(max_results - counter + 1, e))
continue
yield sRes
def get_details(self, search_result, timeout=60):
pass
def create_search_result(self, data):
xp_template = 'normalize-space(@{0})'
sRes = SearchResult()
sRes.drm = SearchResult.DRM_UNLOCKED
sRes.detail_item = data.xpath(xp_template.format('hub_id'))
sRes.title = data.xpath('string(.//title-info/book-title/text()|.//publish-info/book-name/text())')
# aut = concat('.//title-info/author/first-name', ' ')
authors = data.xpath('.//title-info/author/first-name/text()|'
'.//title-info/author/middle-name/text()|'
'.//title-info/author/last-name/text()')
sRes.author = u' '.join(map(type(u''), authors))
sRes.price = data.xpath(xp_template.format('price'))
# cover vs cover_preview
sRes.cover_url = data.xpath(xp_template.format('cover_preview'))
sRes.price = format_price_in_RUR(sRes.price)
types = data.xpath('//fb2-book//files/file/@type')
fmt_set = _parse_ebook_formats(' '.join(types))
sRes.formats = ', '.join(fmt_set)
return sRes
def format_price_in_RUR(price):
'''
Try to format price according ru locale: '12 212,34 руб.'
@param price: price in format like 25.99
@return: formatted price if possible otherwise original value
@rtype: unicode
'''
if price and re.match(r"^\d*?\.\d*?$", price):
try:
price = u'{:,.2F} \u20BD'.format(float(price)) # \u20BD => руб.
price = price.replace(',', ' ').replace('.', ',', 1)
except:
pass
return price
def ungzipResponse(r,b):
headers = r.info()
if headers.get('Content-Encoding', '')=='gzip':
import gzip
gz = gzip.GzipFile(fileobj=r, mode='rb')
data = gz.read()
gz.close()
# headers["Content-type"] = "text/html; charset=utf-8"
r.set_data(data)
b.set_response(r)
def _get_affiliate_id():
aff_id = u'3623565'
# Use Kovid's affiliate id 30% of the time.
if random.randint(1, 10) in (1, 2, 3):
aff_id = u'4084465'
return u'lfrom=' + aff_id
def _parse_ebook_formats(formatsStr):
'''
Creates a set with displayable names of the formats
:param formatsStr: string with comma separated book formats
as it provided by ozon.ru
:return: a list with displayable book formats
'''
formatsUnstruct = formatsStr.lower()
formats = set()
if 'fb2' in formatsUnstruct:
formats.add('FB2')
if 'html' in formatsUnstruct:
formats.add('HTML')
if 'txt' in formatsUnstruct:
formats.add('TXT')
if 'rtf' in formatsUnstruct:
formats.add('RTF')
if 'pdf' in formatsUnstruct:
formats.add('PDF')
if 'prc' in formatsUnstruct:
formats.add('PRC')
if 'lit' in formatsUnstruct:
formats.add('PRC')
if 'epub' in formatsUnstruct:
formats.add('ePub')
if 'rb' in formatsUnstruct:
formats.add('RB')
if 'isilo3' in formatsUnstruct:
formats.add('ISILO3')
if 'lrf' in formatsUnstruct:
formats.add('LRF')
if 'jar' in formatsUnstruct:
formats.add('JAR')
return formats
| 6,031 | Python | .py | 146 | 33.506849 | 118 | 0.624594 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,862 | virtualo_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/virtualo_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 12 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011-2023, Tomasz Długosz <tomek3d@gmail.com>'
__docformat__ = 'restructuredtext en'
import re
from base64 import b64encode
from contextlib import closing
try:
from urllib.parse import quote
except ImportError:
from urllib import quote
from lxml import html
from qt.core import QUrl
from calibre import browser, url_slash_cleaner
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
def as_base64(data):
if not isinstance(data, bytes):
data = data.encode('utf-8')
ans = b64encode(data)
if isinstance(ans, bytes):
ans = ans.decode('ascii')
return ans
class VirtualoStore(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
aff_root = 'https://www.a4b-tracking.com/pl/stat-click-text-link/12/58/'
url = 'http://virtualo.pl/ebooki/'
aff_url = aff_root + as_base64(url)
detail_url = None
if detail_item:
detail_url = aff_root + as_base64(detail_item)
if external or self.config.get('open_external', False):
open_url(QUrl(url_slash_cleaner(detail_url if detail_url else aff_url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_item)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=12, timeout=60):
url = 'http://virtualo.pl/?cat=1&q=' + quote(query)
br = browser()
no_drm_pattern = re.compile(r'Watermark|brak')
counter = max_results
with closing(br.open(url, timeout=timeout)) as f:
doc = html.fromstring(f.read())
for data in doc.xpath('//div[@class="products-list-wrapper"]//li[@class="product"]'):
if counter <= 0:
break
id = ''.join(data.xpath('.//div[@class="cover-wrapper"]//a/@href')).split(r'?q=')[0]
if not id:
continue
price = ''.join(data.xpath(
'.//div[@class="info"]//div[@class="price"]/div/text()|.//div[@class="info"]//div[@class="price price--no-promo"]/div/text()'))
cover_url = ''.join(data.xpath('.//img[@class="cover"]/@src'))
title = ''.join(data.xpath('.//h3[@class="title"]/a//text()'))
author = ', '.join(data.xpath('.//div[@class="info"]//div[@class="authors"]/a//text()'))
formats = [form.strip() for form in data.xpath('.//div[@class="text-wrapper"]//div[@class="format"]/span[@class="prompt_preview"]/text()')]
nodrm = no_drm_pattern.search(''.join(data.xpath('.//div[@class="protection"]/text()')))
counter -= 1
s = SearchResult()
s.cover_url = cover_url
s.title = title.strip()
s.author = author.strip()
s.price = re.sub(r'\.',',',price.strip())
s.detail_item = id
s.formats = ', '.join(list(filter(None, formats))).upper()
s.drm = SearchResult.DRM_UNLOCKED if nodrm else SearchResult.DRM_LOCKED
yield s
| 3,584 | Python | .py | 73 | 39.506849 | 155 | 0.601778 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,863 | ebooksgratuits_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/ebooksgratuits_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 1 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2012, Florent FAYOLLE <florent.fayolle69@gmail.com>'
__docformat__ = 'restructuredtext en'
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.opensearch_store import OpenSearchOPDSStore
from calibre.gui2.store.search_result import SearchResult
from calibre.utils.filenames import ascii_text
class EbooksGratuitsStore(BasicStoreConfig, OpenSearchOPDSStore):
open_search_url = 'http://www.ebooksgratuits.com/opds/opensearch.xml'
web_url = 'http://www.ebooksgratuits.com/'
def strip_accents(self, s):
return ascii_text(s)
def search(self, query, max_results=10, timeout=60):
query = self.strip_accents(type(u'')(query))
for s in OpenSearchOPDSStore.search(self, query, max_results, timeout):
if s.downloads:
s.drm = SearchResult.DRM_UNLOCKED
s.price = '$0.00'
yield s
| 1,108 | Python | .py | 22 | 44.454545 | 82 | 0.714286 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,864 | gutenberg_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/gutenberg_plugin.py | # -*- coding: utf-8 -*-
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 8 # Needed for dynamic plugin loading
import mimetypes
try:
from urllib.parse import quote_plus
except ImportError:
from urllib import quote_plus
from css_selectors import Select
from html5_parser import parse
from lxml import etree
from calibre import browser
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
def absurl(href):
if href.startswith('//'):
href = 'https:' + href
elif href.startswith('/'):
href = 'https://www.gutenberg.org' + href
return href
def search(query, max_results=10, timeout=60, write_raw_to=None):
url = 'https://www.gutenberg.org/ebooks/search/?query={}&submit_search=Search'.format(quote_plus(query))
counter = max_results
br = browser()
raw = br.open(url).read()
if write_raw_to is not None:
with open(write_raw_to, 'wb') as f:
f.write(raw)
root = parse(raw)
CSSSelect = Select(root)
for li in CSSSelect('li.booklink'):
if counter <= 0:
break
counter -= 1
s = SearchResult()
a = next(CSSSelect('a.link', li))
s.detail_item = absurl(a.get('href'))
s.title = etree.tostring(next(CSSSelect('span.title', li)), method='text', encoding='unicode').strip()
try:
s.author = etree.tostring(next(CSSSelect('span.subtitle', li)), method='text', encoding='unicode').strip()
except StopIteration:
s.author = ""
for img in CSSSelect('img.cover-thumb', li):
s.cover_url = absurl(img.get('src'))
break
# Get the formats and direct download links.
details_doc = parse(br.open_novisit(s.detail_item).read())
doc_select = Select(details_doc)
for tr in doc_select('table.files tr[typeof="pgterms:file"]'):
for a in doc_select('a.link', tr):
href = a.get('href')
type = a.get('type')
ext = mimetypes.guess_extension(type.split(';')[0]) if type else None
if href and ext:
url = absurl(href.split('?')[0])
ext = ext[1:].upper().strip()
if ext not in s.downloads:
s.downloads[ext] = url
break
s.formats = ', '.join(s.downloads.keys())
if not s.formats:
continue
yield s
class GutenbergStore(StorePlugin):
def search(self, query, max_results=10, timeout=60):
for result in search(query, max_results, timeout):
yield result
def open(self, parent=None, detail_item=None, external=False):
url = detail_item or absurl('/')
if external:
open_url(url)
return
d = WebStoreDialog(self.gui, url, parent, detail_item)
d.setWindowTitle(self.name)
d.exec()
if __name__ == '__main__':
import sys
for result in search(' '.join(sys.argv[1:]), write_raw_to='/t/gutenberg.html'):
print(result)
| 3,325 | Python | .py | 82 | 32.243902 | 118 | 0.614907 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,865 | amazon_fr_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/amazon_fr_plugin.py | #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 16 # Needed for dynamic plugin loading
from contextlib import closing
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
from lxml import etree, html
from qt.core import QUrl
from calibre import browser
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.search_result import SearchResult
SEARCH_BASE_URL = 'https://www.amazon.fr/s/'
SEARCH_BASE_QUERY = {'i': 'digital-text'}
BY = 'de'
KINDLE_EDITION = 'Format Kindle'
DETAILS_URL = 'https://amazon.fr/dp/'
STORE_LINK = 'https://www.amazon.fr'
DRM_SEARCH_TEXT = 'Simultaneous Device Usage'
DRM_FREE_TEXT = 'Unlimited'
def get_user_agent():
return 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko'
def search_amazon(query, max_results=10, timeout=60,
write_html_to=None,
base_url=SEARCH_BASE_URL,
base_query=SEARCH_BASE_QUERY,
field_keywords='k'
):
uquery = base_query.copy()
uquery[field_keywords] = query
def asbytes(x):
if isinstance(x, type('')):
x = x.encode('utf-8')
return x
uquery = {asbytes(k):asbytes(v) for k, v in uquery.items()}
url = base_url + '?' + urlencode(uquery)
br = browser(user_agent=get_user_agent())
counter = max_results
with closing(br.open(url, timeout=timeout)) as f:
raw = f.read()
if write_html_to is not None:
with open(write_html_to, 'wb') as f:
f.write(raw)
doc = html.fromstring(raw)
for result in doc.xpath('//div[contains(@class, "s-result-list")]//div[@data-index and @data-asin]'):
kformat = ''.join(result.xpath('.//a[contains(text(), "{}")]//text()'.format(KINDLE_EDITION)))
# Even though we are searching digital-text only Amazon will still
# put in results for non Kindle books (author pages). Se we need
# to explicitly check if the item is a Kindle book and ignore it
# if it isn't.
if 'kindle' not in kformat.lower():
continue
asin = result.get('data-asin')
if not asin:
continue
cover_url = ''.join(result.xpath('.//img/@src'))
title = etree.tostring(result.xpath('.//h2')[0], method='text', encoding='unicode')
adiv = result.xpath('.//div[contains(@class, "a-color-secondary")]')[0]
aparts = etree.tostring(adiv, method='text', encoding='unicode').split()
idx = aparts.index(BY)
author = ' '.join(aparts[idx+1:]).split('|')[0].strip()
price = ''
for span in result.xpath('.//span[contains(@class, "a-price")]/span[contains(@class, "a-offscreen")]'):
q = ''.join(span.xpath('./text()'))
if q:
price = q
break
counter -= 1
s = SearchResult()
s.cover_url = cover_url.strip()
s.title = title.strip()
s.author = author.strip()
s.detail_item = asin.strip()
s.price = price.strip()
s.formats = 'Kindle'
yield s
class AmazonKindleStore(StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
store_link = (DETAILS_URL + detail_item) if detail_item else STORE_LINK
open_url(QUrl(store_link))
def search(self, query, max_results=10, timeout=60):
for result in search_amazon(query, max_results=max_results, timeout=timeout):
yield result
def get_details(self, search_result, timeout):
url = DETAILS_URL
br = browser(user_agent=get_user_agent())
with closing(br.open(url + search_result.detail_item, timeout=timeout)) as nf:
idata = html.fromstring(nf.read())
if idata.xpath('boolean(//div[@class="content"]//li/b[contains(text(), "' +
DRM_SEARCH_TEXT + '")])'):
if idata.xpath('boolean(//div[@class="content"]//li[contains(., "' +
DRM_FREE_TEXT + '") and contains(b, "' +
DRM_SEARCH_TEXT + '")])'):
search_result.drm = SearchResult.DRM_UNLOCKED
else:
search_result.drm = SearchResult.DRM_UNKNOWN
else:
search_result.drm = SearchResult.DRM_LOCKED
return True
if __name__ == '__main__':
import sys
for result in search_amazon(' '.join(sys.argv[1:]), write_html_to='/t/amazon.html'):
print(result)
| 4,882 | Python | .py | 107 | 35.663551 | 115 | 0.588087 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,866 | ebook_nl_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/ebook_nl_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 2 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from contextlib import closing
try:
from urllib.parse import quote
except ImportError:
from urllib import quote
from lxml import html
from qt.core import QUrl
from calibre import browser
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
class EBookNLStore(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
url = 'http://www.ebook.nl/'
url_details = ('http://www.ebook.nl/store/{0}')
if external or self.config.get('open_external', False):
if detail_item:
url = url_details.format(detail_item)
open_url(QUrl(url))
else:
detail_url = None
if detail_item:
detail_url = url_details.format(detail_item)
d = WebStoreDialog(self.gui, url, parent, detail_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
url = ('http://www.ebook.nl/store/advanced_search_result.php?keywords=' + quote(query))
br = browser()
counter = max_results
with closing(br.open(url, timeout=timeout)) as f:
doc = html.fromstring(f.read())
for data in doc.xpath('//div[@id="books"]/div[@itemtype="http://schema.org/Book"]'):
if counter <= 0:
break
id = ''.join(data.xpath('./meta[@itemprop="url"]/@content')).strip()
if not id:
continue
cover_url = 'http://www.ebook.nl/store/' + ''.join(data.xpath('.//img[@itemprop="image"]/@src'))
title = ''.join(data.xpath('./span[@itemprop="name"]/a/text()')).strip()
author = ''.join(data.xpath('./span[@itemprop="author"]/a/text()')).strip()
if author == ' ':
author = ''
price = ''.join(data.xpath('.//span[@itemprop="price"]//text()'))
counter -= 1
s = SearchResult()
s.cover_url = cover_url
s.title = title.strip()
s.author = author.strip()
s.price = price
s.drm = SearchResult.DRM_UNKNOWN
s.detail_item = id
yield s
def get_details(self, search_result, timeout):
br = browser()
with closing(br.open(search_result.detail_item, timeout=timeout)) as nf:
idata = html.fromstring(nf.read())
formats = []
if idata.xpath('.//div[@id="book_detail_body"]/ul/li[strong[contains(., "Type")]]/span[contains(., "ePub")]'):
if idata.xpath('.//div[@id="book_detail_body"]/ul/li[strong[contains(., "Type")]]/span[contains(., "EPUB3")]'):
formats.append('EPUB3')
else:
formats.append('EPUB')
if idata.xpath('.//div[@id="book_detail_body"]/ul/li[strong[contains(., "Type")]]/span[contains(., "Pdf")]'):
formats.append('PDF')
search_result.formats = ', '.join(formats)
if idata.xpath('.//div[@id="book_detail_body"]/ul/li[strong[contains(., "Type")]]'
'//span[@class="ePubAdobeDRM" or @class="ePubwatermerk" or'
' @class="Pdfwatermark" or @class="PdfAdobeDRM"]'):
search_result.drm = SearchResult.DRM_LOCKED
if idata.xpath('.//div[@id="book_detail_body"]/ul/li[strong[contains(., "Type")]]//span[@class="ePubzonderDRM"]'):
search_result.drm = SearchResult.DRM_UNLOCKED
return True
| 4,164 | Python | .py | 82 | 39.207317 | 127 | 0.574416 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,867 | feedbooks_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/feedbooks_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 1 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.opensearch_store import OpenSearchOPDSStore
from calibre.gui2.store.search_result import SearchResult
class FeedbooksStore(BasicStoreConfig, OpenSearchOPDSStore):
open_search_url = 'http://assets0.feedbooks.net/opensearch.xml?t=1253087147'
web_url = 'http://feedbooks.com/'
# http://www.feedbooks.com/catalog
def search(self, query, max_results=10, timeout=60):
for s in OpenSearchOPDSStore.search(self, query, max_results, timeout):
if s.downloads:
s.drm = SearchResult.DRM_UNLOCKED
s.price = '$0.00'
else:
s.drm = SearchResult.DRM_LOCKED
s.formats = 'EPUB'
yield s
| 1,067 | Python | .py | 22 | 41.5 | 82 | 0.689489 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,868 | amazon_uk_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/amazon_uk_plugin.py | #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 20 # Needed for dynamic plugin loading
from calibre.gui2.store import StorePlugin
try:
from calibre.gui2.store.amazon_base import AmazonStore
except ImportError:
class AmazonStore:
minimum_calibre_version = 9999, 0, 0
class Base(AmazonStore):
scraper_storage = []
SEARCH_BASE_URL = 'https://www.amazon.co.uk/s/'
SEARCH_BASE_QUERY = {'url': 'search-alias=digital-text'}
DETAILS_URL = 'https://amazon.co.uk/dp/'
STORE_LINK = 'https://www.amazon.co.uk'
class AmazonKindleStore(Base, StorePlugin):
pass
if __name__ == '__main__':
Base().develop_plugin()
| 823 | Python | .py | 21 | 35.666667 | 82 | 0.722573 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,869 | chitanka_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/chitanka_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 2 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011, Alex Stanev <alex@stanev.org>'
__docformat__ = 'restructuredtext en'
from contextlib import closing
try:
from urllib.error import HTTPError
from urllib.parse import quote
except ImportError:
from urllib2 import HTTPError, quote
from lxml import html
from qt.core import QUrl
from calibre import browser, url_slash_cleaner
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
def parse_book_page(doc, base_url, counter):
for data in doc.xpath('//div[@class="booklist"]/div/div'):
if counter <= 0:
break
id = ''.join(data.xpath('.//div[@class="media-body"]/a[@class="booklink"]/@href')).strip()
if not id:
continue
counter -= 1
s = SearchResult()
s.cover_url = 'http:' + ''.join(
data.xpath('.//div[@class="media-left"]/a[@class="booklink"]/div/img/@src')).strip()
s.title = ''.join(data.xpath('.//div[@class="media-body"]/a[@class="booklink"]/i/text()')).strip()
alternative_headline = data.xpath('.//div[@class="media-body"]/div[@itemprop="alternativeHeadline"]/text()')
if len(alternative_headline) > 0:
s.title = "{} ({})".format(s.title, ''.join(alternative_headline).strip())
s.author = ', '.join(data.xpath('.//div[@class="media-body"]/div[@class="bookauthor"]/span/a/text()')).strip(', ')
s.detail_item = id
s.drm = SearchResult.DRM_UNLOCKED
s.downloads['FB2'] = base_url + ''.join(data.xpath(
'.//div[@class="media-body"]/div[@class="download-links"]/div/a[contains(@class,"dl-fb2")]/@href')).strip().replace(
'.zip', '')
s.downloads['EPUB'] = base_url + ''.join(data.xpath(
'.//div[@class="media-body"]/div[@class="download-links"]/div/a[contains(@class,"dl-epub")]/@href')).strip().replace(
'.zip', '')
s.downloads['TXT'] = base_url + ''.join(data.xpath(
'.//div[@class="media-body"]/div[@class="download-links"]/div/a[contains(@class,"dl-txt")]/@href')).strip().replace(
'.zip', '')
s.formats = 'FB2, EPUB, TXT'
yield s
return counter
class ChitankaStore(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
url = 'http://chitanka.info'
if external or self.config.get('open_external', False):
if detail_item:
url = url + detail_item
open_url(QUrl(url_slash_cleaner(url)))
else:
detail_url = None
if detail_item:
detail_url = url + detail_item
d = WebStoreDialog(self.gui, url, parent, detail_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
if isinstance(query, bytes):
query = query.decode('utf-8')
if len(query) < 3:
return
base_url = 'http://chitanka.info'
url = base_url + '/search?q=' + quote(query)
counter = max_results
# search for book title
br = browser()
try:
with closing(br.open(url, timeout=timeout)) as f:
f = f.read().decode('utf-8')
doc = html.fromstring(f)
counter = yield from parse_book_page(doc, base_url, counter)
if counter <= 0:
return
# search for author names
for data in doc.xpath('//ul[@class="superlist"][1]/li/dl/dt'):
author_url = ''.join(data.xpath('.//a[contains(@href,"/person/")]/@href'))
if author_url == '':
continue
br2 = browser()
with closing(br2.open(base_url + author_url, timeout=timeout)) as f:
f = f.read().decode('utf-8')
doc = html.fromstring(f)
counter = yield from parse_book_page(doc, base_url, counter)
if counter <= 0:
break
except HTTPError as e:
if e.code == 404:
return
else:
raise
| 4,659 | Python | .py | 99 | 36.262626 | 129 | 0.567711 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,870 | baen_webscription_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/baen_webscription_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 2 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from contextlib import closing
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
from lxml import html
from qt.core import QUrl
from calibre import browser
from calibre.ebooks.metadata import authors_to_string
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
def search(query, max_results=10, timeout=60):
url = 'http://www.baen.com/catalogsearch/result/?' + urlencode(
{'q':query.lower(), 'dir':'desc', 'order':'relevance'})
br = browser()
counter = max_results
with closing(br.open_novisit(url, timeout=timeout)) as f:
raw = f.read()
root = html.fromstring(raw)
for data in root.xpath('//div[@id="productMatches"]//table[@id="authorTable"]//tr[contains(@class, "IDCell")]'):
if counter <= 0:
break
try:
book_url = data.xpath('./td[1]/a/@href[1]')[0]
except IndexError:
continue
try:
title = data.xpath('./td[2]/a[1]/text()')[0].strip()
except IndexError:
continue
try:
cover_url = data.xpath('./td[1]//img[1]/@src')[0]
except IndexError:
cover_url = ''
tails = [(b.tail or '').strip() for b in data.xpath('./td[2]/br')]
authors = [x[2:].strip() for x in tails if x.startswith('by ')]
author = authors_to_string(authors)
price = ''.join(data.xpath('.//span[@class="variantprice"]/text()'))
a, b, price = price.partition('$')
price = b + price
counter -= 1
s = SearchResult()
s.cover_url = cover_url
s.title = title.strip()
s.author = author.strip()
s.price = price
s.detail_item = book_url.strip()
s.drm = SearchResult.DRM_UNLOCKED
s.formats = 'RB, MOBI, EPUB, LIT, LRF, RTF, HTML'
yield s
class BaenWebScriptionStore(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
url = 'http://www.baenebooks.com/'
if external or self.config.get('open_external', False):
open_url(QUrl(detail_item or url))
else:
d = WebStoreDialog(self.gui, url, parent, detail_item or url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
for result in search(query, max_results, timeout):
yield result
if __name__ == '__main__':
import sys
for result in search(' '.join(sys.argv[1:])):
print(result)
| 3,226 | Python | .py | 76 | 33.631579 | 120 | 0.60422 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,871 | amazon_es_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/amazon_es_plugin.py | #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 15 # Needed for dynamic plugin loading
from contextlib import closing
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
from lxml import html
from qt.core import QUrl
from calibre import browser
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.search_result import SearchResult
SEARCH_BASE_URL = 'https://www.amazon.es/s/'
SEARCH_BASE_QUERY = {'url': 'search-alias=digital-text'}
BY = 'de'
KINDLE_EDITION = 'Versión Kindle'
DETAILS_URL = 'https://amazon.es/dp/'
STORE_LINK = 'https://www.amazon.es'
DRM_SEARCH_TEXT = 'Simultaneous Device Usage'
DRM_FREE_TEXT = 'Unlimited'
def get_user_agent():
return 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko'
def search_amazon(query, max_results=10, timeout=60,
write_html_to=None,
base_url=SEARCH_BASE_URL,
base_query=SEARCH_BASE_QUERY,
field_keywords='field-keywords'
):
uquery = base_query.copy()
uquery[field_keywords] = query
def asbytes(x):
if isinstance(x, type('')):
x = x.encode('utf-8')
return x
uquery = {asbytes(k):asbytes(v) for k, v in uquery.items()}
url = base_url + '?' + urlencode(uquery)
br = browser(user_agent=get_user_agent())
counter = max_results
with closing(br.open(url, timeout=timeout)) as f:
raw = f.read()
if write_html_to is not None:
with open(write_html_to, 'wb') as f:
f.write(raw)
doc = html.fromstring(raw)
try:
results = doc.xpath('//div[@id="atfResults" and @class]')[0]
except IndexError:
return
if 's-result-list-parent-container' in results.get('class', ''):
data_xpath = "descendant-or-self::li[@class and contains(concat(' ', normalize-space(@class), ' '), ' s-result-item ')]"
format_xpath = './/a[@title="%s"]/@title' % KINDLE_EDITION
asin_xpath = '@data-asin'
cover_xpath = "descendant-or-self::img[@class and contains(concat(' ', normalize-space(@class), ' '), ' s-access-image ')]/@src"
title_xpath = "descendant-or-self::h2[@class and contains(concat(' ', normalize-space(@class), ' '), ' s-access-title ')]//text()"
author_xpath = './/span[starts-with(text(), "%s ")]/following-sibling::span//text()' % BY
price_xpath = ('descendant::div[@class="a-row a-spacing-none" and'
' not(span[contains(@class, "kindle-unlimited")])]//span[contains(@class, "s-price")]//text()')
else:
return
for data in doc.xpath(data_xpath):
if counter <= 0:
break
# Even though we are searching digital-text only Amazon will still
# put in results for non Kindle books (author pages). Se we need
# to explicitly check if the item is a Kindle book and ignore it
# if it isn't.
format = ''.join(data.xpath(format_xpath))
if 'kindle' not in format.lower():
continue
# We must have an asin otherwise we can't easily reference the
# book later.
asin = data.xpath(asin_xpath)
if asin:
asin = asin[0]
else:
continue
cover_url = ''.join(data.xpath(cover_xpath))
title = ''.join(data.xpath(title_xpath))
author = ''.join(data.xpath(author_xpath))
try:
author = author.split('by ', 1)[1].split(" (")[0]
except:
pass
price = ''.join(data.xpath(price_xpath))
counter -= 1
s = SearchResult()
s.cover_url = cover_url.strip()
s.title = title.strip()
s.author = author.strip()
s.price = price.strip()
s.detail_item = asin.strip()
s.formats = 'Kindle'
yield s
class AmazonKindleStore(StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
store_link = (DETAILS_URL + detail_item) if detail_item else STORE_LINK
open_url(QUrl(store_link))
def search(self, query, max_results=10, timeout=60):
for result in search_amazon(query, max_results=max_results, timeout=timeout):
yield result
def get_details(self, search_result, timeout):
url = DETAILS_URL
br = browser(user_agent=get_user_agent())
with closing(br.open(url + search_result.detail_item, timeout=timeout)) as nf:
idata = html.fromstring(nf.read())
if idata.xpath('boolean(//div[@class="content"]//li/b[contains(text(), "' +
DRM_SEARCH_TEXT + '")])'):
if idata.xpath('boolean(//div[@class="content"]//li[contains(., "' +
DRM_FREE_TEXT + '") and contains(b, "' +
DRM_SEARCH_TEXT + '")])'):
search_result.drm = SearchResult.DRM_UNLOCKED
else:
search_result.drm = SearchResult.DRM_UNKNOWN
else:
search_result.drm = SearchResult.DRM_LOCKED
return True
if __name__ == '__main__':
import sys
for result in search_amazon(' '.join(sys.argv[1:]), write_html_to='/t/amazon.html'):
print(result)
| 5,700 | Python | .py | 124 | 35.612903 | 142 | 0.582221 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,872 | biblio_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/biblio_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 2 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2012, Alex Stanev <alex@stanev.org>'
__docformat__ = 'restructuredtext en'
try:
from urllib.parse import quote_plus
except ImportError:
from urllib import quote_plus
from contextlib import closing
from lxml import html
from calibre import browser
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
class BiblioStore(BasicStoreConfig, StorePlugin):
web_url = 'https://biblio.bg'
def open(self, parent=None, detail_item=None, external=False):
if external or self.config.get('open_external', False):
open_url(detail_item)
else:
d = WebStoreDialog(self.gui, self.web_url, parent, detail_item)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
if isinstance(query, bytes):
query = query.decode('utf-8')
if len(query) < 3:
return
# do keyword search
url = '{}/книги?query={}&search_by=0'.format(self.web_url, quote_plus(query))
yield from self._do_search(url, max_results, timeout)
def get_details(self, search_result, timeout):
br = browser()
with closing(br.open(search_result.detail_item, timeout=timeout)) as nf:
idata = html.fromstring(nf.read())
search_result.formats = ''
search_result.drm = SearchResult.DRM_LOCKED
for option in idata.xpath('//ul[@class="order_product_options"]/li'):
option_type = option.text.strip() if option.text else ''
if option_type.startswith('Формат:'):
search_result.formats = ''.join(option.xpath('.//b/text()')).strip()
if option_type.startswith('Защита:'):
if ''.join(option.xpath('.//b/text()')).strip() == 'няма':
search_result.drm = SearchResult.DRM_UNLOCKED
if not search_result.author:
search_result.author = ', '.join(idata.xpath('//div[@class="row product_info"]/div/div/div[@class="item-author"]/a/text()')).strip(', ')
return True
def _do_search(self, url, max_results, timeout):
br = browser()
with closing(br.open(url, timeout=timeout)) as f:
page = f.read().decode('utf-8')
doc = html.fromstring(page)
for data in doc.xpath('//ul[contains(@class,"book_list")]/li'):
if max_results <= 0:
break
s = SearchResult()
s.detail_item = ''.join(data.xpath('.//a[@class="th"]/@href')).strip()
if not id:
continue
s.cover_url = ''.join(data.xpath('.//a[@class="th"]/img/@data-original')).strip()
s.title = ''.join(data.xpath('.//div[@class="item-title"]/a/text()')).strip()
s.author = ', '.join(data.xpath('.//div[@class="item-author"]/a/text()')).strip(', ')
price_list = data.xpath('.//div[@class="item-price"]')
for price_item in price_list:
if price_item.text.startswith('е-книга:'):
s.price = ''.join(price_item.xpath('.//span/text()'))
break
s.price = '0.00 лв.' if not s.price and not price_list else s.price
if not s.price:
# no e-book available
continue
max_results -= 1
yield s
| 3,951 | Python | .py | 78 | 38.871795 | 152 | 0.58089 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,873 | ebooks_com_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/ebooks_com_plugin.py | # -*- coding: utf-8 -*-
# License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 4 # Needed for dynamic plugin loading
import re
from contextlib import closing
try:
from urllib.parse import quote_plus
except ImportError:
from urllib import quote_plus
from qt.core import QUrl
from calibre import browser, url_slash_cleaner
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
def absolutize(url):
if url.startswith('/'):
url = 'https://www.ebooks.com' + url
return url
def search_ec(query, max_results=10, timeout=60, write_html_to=''):
import json
from urllib.parse import parse_qs, urlparse
url = 'https://www.ebooks.com/SearchApp/SearchResults.net?term=' + quote_plus(query)
br = browser()
with closing(br.open(url, timeout=timeout)) as f:
raw = f.read()
if write_html_to:
with open(write_html_to, 'wb') as d:
d.write(raw)
api = re.search(r'data-endpoint="(/api/search/.+?)"', raw.decode('utf-8')).group(1)
counter = max_results
url = absolutize(api)
cc = parse_qs(urlparse(url).query)['CountryCode'][0]
with closing(br.open(url, timeout=timeout)) as f:
raw = f.read()
if write_html_to:
with open(write_html_to + '.json', 'wb') as d:
d.write(raw)
data = json.loads(raw)
for book in data['books']:
if counter <= 0:
break
counter -= 1
s = SearchResult()
s.cover_url = absolutize(book['image_url'])
s.title = book['title']
s.author = ' & '.join(x['name'] for x in book['authors'])
s.price = book['price']
s.detail_item = absolutize(book['book_url'])
s.ebooks_com_api_url = 'https://www.ebooks.com/api/book/?bookId={}&countryCode={}'.format(book["id"], cc)
s.drm = SearchResult.DRM_UNKNOWN
yield s
def ec_details(search_result, timeout=30, write_data_to=''):
import json
br = browser()
with closing(br.open(search_result.ebooks_com_api_url, timeout=timeout)) as f:
raw = f.read()
if write_data_to:
with open(write_data_to, 'wb') as d:
d.write(raw)
data = json.loads(raw)
if 'drm' in data and 'drm_free' in data['drm']:
search_result.drm = SearchResult.DRM_UNLOCKED if data['drm']['drm_free'] else SearchResult.DRM_LOCKED
fmts = []
for x in data['information']['formats']:
x = x.split()[0]
fmts.append(x)
if fmts:
search_result.formats = ', '.join(fmts).upper()
class EbookscomStore(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
m_url = 'http://www.dpbolvw.net/'
h_click = 'click-4913808-10364500'
d_click = 'click-4913808-10281551'
url = m_url + h_click
detail_url = None
if detail_item:
detail_url = m_url + d_click + detail_item
if external or self.config.get('open_external', False):
open_url(QUrl(url_slash_cleaner(detail_url if detail_url else url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
yield from search_ec(query, max_results, timeout)
def get_details(self, search_result, timeout):
ec_details(search_result, timeout)
return True
if __name__ == '__main__':
import sys
results = tuple(search_ec(' '.join(sys.argv[1:]), write_html_to='/t/ec.html'))
for result in results:
print(result)
ec_details(results[0], write_data_to='/t/ecd.json')
print('-'*80)
print(results[0])
| 4,053 | Python | .py | 100 | 33.97 | 113 | 0.641749 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,874 | bubok_portugal_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/bubok_portugal_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 2 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2014, Rafael Vega <rafavega@gmail.com>'
__docformat__ = 'restructuredtext en'
from contextlib import closing
try:
from urllib.parse import quote_plus
except ImportError:
from urllib import quote_plus
from lxml import html
from qt.core import QUrl
from calibre import browser, url_slash_cleaner
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
class BubokPortugalStore(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
url = 'https://www.bubok.pt/tienda'
if external or self.config.get('open_external', False):
open_url(QUrl(url_slash_cleaner(detail_item if detail_item else url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_item)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
url = 'http://www.bubok.pt/resellers/calibre_search/' + quote_plus(query)
br = browser()
counter = max_results
with closing(br.open(url, timeout=timeout)) as f:
doc = html.fromstring(f.read())
for data in doc.xpath('//div[contains(@class, "libro")]'):
if counter <= 0:
break
id = ''.join(data.xpath('.//div[@class="url"]/text()'))
title = ''.join(data.xpath('.//div[@class="titulo"]/text()'))
author = ''.join(data.xpath('.//div[@class="autor"]/text()'))
price = ''.join(data.xpath('.//div[@class="precio"]/text()'))
formats = ''.join(data.xpath('.//div[@class="formatos"]/text()'))
cover = ''.join(data.xpath('.//div[@class="portada"]/text()'))
counter -= 1
s = SearchResult()
s.title = title.strip()
s.author = author.strip()
s.detail_item = id.strip()
s.price = price.strip()
s.drm = SearchResult.DRM_UNLOCKED
s.formats = formats.strip()
s.cover_url = cover.strip()
yield s
def get_details(self, search_result, timeout):
return True
| 2,645 | Python | .py | 56 | 37.642857 | 82 | 0.609424 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,875 | amazon_au_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/amazon_au_plugin.py | #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 20 # Needed for dynamic plugin loading
from calibre.gui2.store import StorePlugin
try:
from calibre.gui2.store.amazon_base import AmazonStore
except ImportError:
class AmazonStore:
minimum_calibre_version = 9999, 0, 0
class Base(AmazonStore):
scraper_storage = []
SEARCH_BASE_URL = 'https://www.amazon.com.au/s/'
SEARCH_BASE_QUERY = {'url': 'search-alias=digital-text'}
DETAILS_URL = 'https://amazon.com.au/dp/'
STORE_LINK = 'https://www.amazon.com.au'
class AmazonKindleStore(Base, StorePlugin):
pass
if __name__ == '__main__':
Base().develop_plugin()
| 826 | Python | .py | 21 | 35.809524 | 82 | 0.723618 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,876 | amazon_ca_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/amazon_ca_plugin.py | #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 20 # Needed for dynamic plugin loading
from calibre.gui2.store import StorePlugin
try:
from calibre.gui2.store.amazon_base import AmazonStore
except ImportError:
class AmazonStore:
minimum_calibre_version = 9999, 0, 0
class Base(AmazonStore):
scraper_storage = []
SEARCH_BASE_URL = 'https://www.amazon.ca/s/'
SEARCH_BASE_QUERY = {'url': 'search-alias=digital-text'}
DETAILS_URL = 'https://amazon.ca/dp/'
STORE_LINK = 'https://www.amazon.ca'
class AmazonKindleStore(Base, StorePlugin):
pass
if __name__ == '__main__':
Base().develop_plugin()
| 814 | Python | .py | 21 | 35.238095 | 82 | 0.723214 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,877 | ebookpoint_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/ebookpoint_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 9 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2011-2023, Tomasz Długosz <tomek3d@gmail.com>'
__docformat__ = 'restructuredtext en'
import re
from base64 import b64encode
from contextlib import closing
try:
from urllib.parse import quote_plus
except ImportError:
from urllib import quote_plus
from lxml import html
from qt.core import QUrl
from calibre import browser, url_slash_cleaner
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
def as_base64(data):
if not isinstance(data, bytes):
data = data.encode('utf-8')
ans = b64encode(data)
if isinstance(ans, bytes):
ans = ans.decode('ascii')
return ans
class EbookpointStore(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
aff_root = 'https://www.a4b-tracking.com/pl/stat-click-text-link/32/58/'
url = 'http://ebookpoint.pl/'
aff_url = aff_root + as_base64(url)
detail_url = None
if detail_item:
detail_url = aff_root + as_base64(detail_item)
if external or self.config.get('open_external', False):
open_url(QUrl(url_slash_cleaner(detail_url if detail_url else aff_url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_url if detail_url else aff_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=25, timeout=60):
url = 'http://ebookpoint.pl/search?qa=&szukaj=' + quote_plus(
query.decode('utf-8').encode('iso-8859-2')) + '&serwisyall=0&wprzyg=0&wsprzed=1&wyczerp=0&formaty=em-p'
br = browser()
counter = max_results
with closing(br.open(url, timeout=timeout)) as f:
doc = html.fromstring(f.read())
for data in doc.xpath('//ul[@class="list"]/li'):
if counter <= 0:
break
id = ''.join(data.xpath('./a/@href'))
if not id:
continue
formats = ', '.join(data.xpath('.//ul[@class="book-type book-type-points"]//span[@class="popup"]/span/text()'))
cover_url = ''.join(data.xpath('.//p[@class="cover "]/img/@data-src'))
title = ''.join(data.xpath('.//div[@class="book-info"]/h3/a[1]/text()'))
author = ''.join(data.xpath('.//p[@class="author"]//text()'))
price = ''.join(data.xpath('.//p[@class="price price-incart"]/a/ins/text()|.//p[@class="price price-add"]/a/text()'))
counter -= 1
s = SearchResult()
s.cover_url = cover_url
s.title = title.strip()
s.author = author.strip()
s.price = re.sub(r'\.',',',price)
s.detail_item = id.strip()
s.drm = SearchResult.DRM_UNLOCKED
s.formats = formats.upper()
yield s
| 3,335 | Python | .py | 71 | 37.591549 | 133 | 0.604752 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,878 | wolnelektury_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/wolnelektury_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
store_version = 4 # Needed for dynamic plugin loading
__license__ = 'GPL 3'
__copyright__ = '2012-2023, Tomasz Długosz <tomek3d@gmail.com>'
__docformat__ = 'restructuredtext en'
from contextlib import closing
try:
from urllib.parse import quote_plus
except ImportError:
from urllib import quote_plus
from lxml import html
from qt.core import QUrl
from calibre import browser, url_slash_cleaner
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.web_store_dialog import WebStoreDialog
class WolneLekturyStore(BasicStoreConfig, StorePlugin):
def open(self, parent=None, detail_item=None, external=False):
url = 'https://wolnelektury.pl'
detail_url = None
if detail_item:
detail_url = detail_item
if external or self.config.get('open_external', False):
open_url(QUrl(url_slash_cleaner(detail_url if detail_url else url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
def search(self, query, max_results=10, timeout=60):
url = 'https://wolnelektury.pl/szukaj?q=' + quote_plus(query)
br = browser()
counter = max_results
with closing(br.open(url, timeout=timeout)) as f:
doc = html.fromstring(f.read())
for data in doc.xpath('//div[@class="l-books__grid"]/article'):
if counter <= 0:
break
id = ''.join(data.xpath('.//figure/a/@href'))
if not id:
continue
title = ''.join(data.xpath('.//h2/a/text()'))
author = ', '.join(data.xpath('.//h3/a/text()'))
cover_url = ''.join(data.xpath('.//figure/a/img/@src'))
price = '0,00 zł'
counter -= 1
s = SearchResult()
s.cover_url = 'https://wolnelektury.pl' + cover_url.strip()
s.title = title.strip()
s.author = author
s.price = price
s.detail_item = 'https://wolnelektury.pl' + id
s.formats = ', '.join(s.downloads.keys())
s.drm = SearchResult.DRM_UNLOCKED
yield s
| 2,588 | Python | .py | 58 | 34.689655 | 82 | 0.602073 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,879 | cache_update_thread.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/mobileread/cache_update_thread.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
import time
from contextlib import closing
from threading import Thread
from lxml import html
from qt.core import QObject, pyqtSignal
from calibre import browser
from calibre.gui2.store.search_result import SearchResult
class CacheUpdateThread(Thread, QObject):
total_changed = pyqtSignal(int)
update_progress = pyqtSignal(int)
update_details = pyqtSignal(type(u''))
def __init__(self, config, seralize_books_function, timeout):
Thread.__init__(self)
QObject.__init__(self)
self.daemon = True
self.config = config
self.seralize_books = seralize_books_function
self.timeout = timeout
self._run = True
def abort(self):
self._run = False
def run(self):
url = 'https://www.mobileread.com/forums/ebooks.php?do=getlist&type=html'
self.update_details.emit(_('Checking last download date.'))
last_download = self.config.get('last_download', None)
# Don't update the book list if our cache is less than one week old.
if last_download and (time.time() - last_download) < 604800:
return
self.update_details.emit(_('Downloading book list from MobileRead.'))
# Download the book list HTML file from MobileRead.
br = browser()
raw_data = None
try:
with closing(br.open(url, timeout=self.timeout)) as f:
raw_data = f.read()
except:
return
if not raw_data or not self._run:
return
self.update_details.emit(_('Processing books.'))
# Turn books listed in the HTML file into SearchResults's.
books = []
try:
data = html.fromstring(raw_data)
raw_books = data.xpath('//ul/li')
self.total_changed.emit(len(raw_books))
for i, book_data in enumerate(raw_books):
self.update_details.emit(
_('%(num)s of %(tot)s books processed.') % dict(
num=i, tot=len(raw_books)))
book = SearchResult()
book.detail_item = ''.join(book_data.xpath('.//a/@href'))
book.formats = ''.join(book_data.xpath('.//i/text()'))
book.formats = book.formats.strip()
text = ''.join(book_data.xpath('.//a/text()'))
if ':' in text:
book.author, q, text = text.partition(':')
book.author = book.author.strip()
book.title = text.strip()
books.append(book)
if not self._run:
books = []
break
else:
self.update_progress.emit(i)
except:
pass
# Save the book list and it's create time.
if books:
self.config['book_list'] = self.seralize_books(books)
self.config['last_download'] = time.time()
| 3,189 | Python | .py | 76 | 31.342105 | 82 | 0.576277 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,880 | models.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/mobileread/models.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from operator import attrgetter
from qt.core import QAbstractItemModel, QModelIndex, Qt, pyqtSignal
from calibre.db.search import CONTAINS_MATCH, EQUALS_MATCH, REGEXP_MATCH, _match
from calibre.utils.config_base import prefs
from calibre.utils.icu import sort_key
from calibre.utils.search_query_parser import SearchQueryParser
class BooksModel(QAbstractItemModel):
total_changed = pyqtSignal(int)
HEADERS = [_('Title'), _('Author(s)'), _('Format')]
def __init__(self, all_books):
QAbstractItemModel.__init__(self)
self.books = all_books
self.all_books = all_books
self.filter = ''
self.search_filter = SearchFilter(all_books)
self.sort_col = 0
self.sort_order = Qt.SortOrder.AscendingOrder
def get_book(self, index):
row = index.row()
if row < len(self.books):
return self.books[row]
else:
return None
def search(self, filter):
self.filter = filter.strip()
if not self.filter:
self.books = self.all_books
else:
try:
self.books = list(self.search_filter.parse(self.filter))
except:
self.books = self.all_books
self.layoutChanged.emit()
self.sort(self.sort_col, self.sort_order)
self.total_changed.emit(self.rowCount())
def index(self, row, column, parent=QModelIndex()):
return self.createIndex(row, column)
def parent(self, index):
if not index.isValid() or index.internalId() == 0:
return QModelIndex()
return self.createIndex(0, 0)
def rowCount(self, *args):
return len(self.books)
def columnCount(self, *args):
return len(self.HEADERS)
def headerData(self, section, orientation, role):
if role != Qt.ItemDataRole.DisplayRole:
return None
text = ''
if orientation == Qt.Orientation.Horizontal:
if section < len(self.HEADERS):
text = self.HEADERS[section]
return (text)
else:
return (section+1)
def data(self, index, role):
row, col = index.row(), index.column()
result = self.books[row]
if role == Qt.ItemDataRole.DisplayRole:
if col == 0:
return (result.title)
elif col == 1:
return (result.author)
elif col == 2:
return (result.formats)
return None
def data_as_text(self, result, col):
text = ''
if col == 0:
text = result.title
elif col == 1:
text = result.author
elif col == 2:
text = result.formats
return text
def sort(self, col, order, reset=True):
self.sort_col = col
self.sort_order = order
if not self.books:
return
descending = order == Qt.SortOrder.DescendingOrder
self.books.sort(key=lambda x: sort_key(type(u'')(self.data_as_text(x, col))), reverse=descending)
if reset:
self.beginResetModel(), self.endResetModel()
class SearchFilter(SearchQueryParser):
USABLE_LOCATIONS = [
'all',
'author',
'authors',
'format',
'formats',
'title',
]
def __init__(self, all_books=[]):
SearchQueryParser.__init__(self, locations=self.USABLE_LOCATIONS)
self.srs = set(all_books)
def universal_set(self):
return self.srs
def get_matches(self, location, query):
location = location.lower().strip()
if location == 'authors':
location = 'author'
elif location == 'formats':
location = 'format'
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:]
if matchkind != REGEXP_MATCH: # leave case in regexps because it can be significant e.g. \S \W \D
query = query.lower()
if location not in self.USABLE_LOCATIONS:
return set()
matches = set()
all_locs = set(self.USABLE_LOCATIONS) - {'all'}
locations = all_locs if location == 'all' else [location]
q = {
'author': lambda x: x.author.lower(),
'format': attrgetter('formats'),
'title': lambda x: x.title.lower(),
}
for x in ('author', 'format'):
q[x+'s'] = q[x]
upf = prefs['use_primary_find_in_search']
for sr in self.srs:
for locvalue in locations:
accessor = q[locvalue]
if query == 'true':
if accessor(sr) is not None:
matches.add(sr)
continue
if query == 'false':
if accessor(sr) is None:
matches.add(sr)
continue
try:
# Can't separate authors because comma is used for name sep and author sep
# Exact match might not get what you want. For that reason, turn author
# exactmatch searches into contains searches.
if locvalue == 'author' and matchkind == EQUALS_MATCH:
m = CONTAINS_MATCH
else:
m = matchkind
vals = [accessor(sr)]
if _match(query, vals, m, use_primary_find_in_search=upf):
matches.add(sr)
break
except ValueError: # Unicode errors
import traceback
traceback.print_exc()
return matches
| 6,197 | Python | .py | 161 | 27.285714 | 106 | 0.551598 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,881 | adv_search_builder.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/mobileread/adv_search_builder.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
import re
from qt.core import QDialog, QDialogButtonBox
from calibre.gui2.store.stores.mobileread.adv_search_builder_ui import Ui_Dialog
from calibre.library.caches import CONTAINS_MATCH, EQUALS_MATCH
class AdvSearchBuilderDialog(QDialog, Ui_Dialog):
def __init__(self, parent):
QDialog.__init__(self, parent)
self.setupUi(self)
self.buttonBox.accepted.connect(self.advanced_search_button_pushed)
self.tab_2_button_box.accepted.connect(self.accept)
self.tab_2_button_box.rejected.connect(self.reject)
self.clear_button.clicked.connect(self.clear_button_pushed)
self.advanced_clear_button.clicked.connect(self.clear_advanced)
self.adv_search_used = False
self.mc = ''
self.tabWidget.setCurrentIndex(0)
self.tabWidget.currentChanged[int].connect(self.tab_changed)
self.tab_changed(0)
def tab_changed(self, idx):
if idx == 1:
self.tab_2_button_box.button(QDialogButtonBox.StandardButton.Ok).setDefault(True)
else:
self.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setDefault(True)
def advanced_search_button_pushed(self):
self.adv_search_used = True
self.accept()
def clear_button_pushed(self):
self.title_box.setText('')
self.author_box.setText('')
self.format_box.setText('')
def clear_advanced(self):
self.all.setText('')
self.phrase.setText('')
self.any.setText('')
self.none.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):
if self.adv_search_used:
return self.adv_search_string()
else:
return self.box_search_string()
def adv_search_string(self):
mk = self.matchkind.currentIndex()
if mk == CONTAINS_MATCH:
self.mc = ''
elif mk == EQUALS_MATCH:
self.mc = '='
else:
self.mc = '~'
all, any, phrase, none = list(map(lambda x: type(u'')(x.text()),
(self.all, self.any, self.phrase, self.none)))
all, any, none = list(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:
ans += (' or ' if ans else '') + any
return ans
def token(self):
txt = type(u'')(self.text.text()).strip()
if txt:
if self.negate.isChecked():
txt = '!'+txt
tok = self.FIELDS[type(u'')(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 = '='
else:
self.mc = '~'
ans = []
self.box_last_values = {}
title = type(u'')(self.title_box.text()).strip()
if title:
ans.append('title:"' + self.mc + title + '"')
author = type(u'')(self.author_box.text()).strip()
if author:
ans.append('author:"' + self.mc + author + '"')
format = type(u'')(self.format_box.text()).strip()
if format:
ans.append('format:"' + self.mc + format + '"')
if ans:
return ' and '.join(ans)
return ''
| 4,170 | Python | .py | 107 | 29.831776 | 93 | 0.564293 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,882 | store_dialog.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/mobileread/store_dialog.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from qt.core import QComboBox, QDialog, QIcon, Qt
from calibre.gui2.store.stores.mobileread.adv_search_builder import AdvSearchBuilderDialog
from calibre.gui2.store.stores.mobileread.models import BooksModel
from calibre.gui2.store.stores.mobileread.store_dialog_ui import Ui_Dialog
class MobileReadStoreDialog(QDialog, Ui_Dialog):
def __init__(self, plugin, *args):
QDialog.__init__(self, *args)
self.setupUi(self)
self.plugin = plugin
self.search_query.initialize('store_mobileread_search')
self.search_query.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
self.search_query.setMinimumContentsLength(25)
self.adv_search_button.setIcon(QIcon.ic('search.png'))
self._model = BooksModel(self.plugin.get_book_list())
self.results_view.setModel(self._model)
self.total.setText('%s' % self.results_view.model().rowCount())
self.search_button.clicked.connect(self.do_search)
self.adv_search_button.clicked.connect(self.build_adv_search)
self.results_view.activated.connect(self.open_store)
self.results_view.model().total_changed.connect(self.update_book_total)
self.finished.connect(self.dialog_closed)
self.restore_state()
def do_search(self):
self.results_view.model().search(type(u'')(self.search_query.text()))
def open_store(self, index):
result = self.results_view.model().get_book(index)
if result:
self.plugin.open(self, result.detail_item)
def update_book_total(self, total):
self.total.setText('%s' % total)
def build_adv_search(self):
adv = AdvSearchBuilderDialog(self)
if adv.exec() == QDialog.DialogCode.Accepted:
self.search_query.setText(adv.search_string())
def restore_state(self):
self.restore_geometry(self.plugin.config, 'dialog_geometry')
results_cwidth = self.plugin.config.get('dialog_results_view_column_width')
if results_cwidth:
for i, x in enumerate(results_cwidth):
if i >= self.results_view.model().columnCount():
break
self.results_view.setColumnWidth(i, x)
else:
for i in range(self.results_view.model().columnCount()):
self.results_view.resizeColumnToContents(i)
self.results_view.model().sort_col = self.plugin.config.get('dialog_sort_col', 0)
try:
so = Qt.SortOrder(self.plugin.config.get('dialog_sort_order', Qt.SortOrder.AscendingOrder))
except Exception:
so = Qt.SortOrder.AscendingOrder
self.results_view.model().sort_order = so
self.results_view.model().sort(self.results_view.model().sort_col, so)
self.results_view.header().setSortIndicator(self.results_view.model().sort_col, so)
def save_state(self):
self.save_geometry(self.plugin.config, 'dialog_geometry')
self.plugin.config['dialog_results_view_column_width'] = [self.results_view.columnWidth(i) for i in range(self.results_view.model().columnCount())]
self.plugin.config['dialog_sort_col'] = self.results_view.model().sort_col
self.plugin.config['dialog_sort_order'] = self.results_view.model().sort_order
def dialog_closed(self, result):
self.save_state()
| 3,605 | Python | .py | 65 | 46.953846 | 155 | 0.68608 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,883 | cache_progress_dialog.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/mobileread/cache_progress_dialog.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from qt.core import QDialog
from calibre.gui2.store.stores.mobileread.cache_progress_dialog_ui import Ui_Dialog
class CacheProgressDialog(QDialog, Ui_Dialog):
def __init__(self, parent=None, total=None):
QDialog.__init__(self, parent)
self.setupUi(self)
self.completed = 0
self.canceled = False
self.progress.setValue(0)
self.progress.setMinimum(0)
self.progress.setMaximum(total if total else 0)
def exec(self):
self.completed = 0
self.canceled = False
QDialog.exec(self)
exec_ = exec
def open(self):
self.completed = 0
self.canceled = False
QDialog.open(self)
def reject(self):
self.canceled = True
QDialog.reject(self)
def update_progress(self):
'''
completed is an int from 0 to total representing the number
records that have bee completed.
'''
self.set_progress(self.completed + 1)
def set_message(self, msg):
self.message.setText(msg)
def set_details(self, msg):
self.details.setText(msg)
def set_progress(self, completed):
'''
completed is an int from 0 to total representing the number
records that have bee completed.
'''
self.completed = completed
self.progress.setValue(self.completed)
def set_total(self, total):
self.progress.setMaximum(total)
| 1,674 | Python | .py | 47 | 28.489362 | 83 | 0.65239 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,884 | mobileread_plugin.py | kovidgoyal_calibre/src/calibre/gui2/store/stores/mobileread/mobileread_plugin.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
import os
from threading import Lock
from qt.core import QCoreApplication, QUrl
from calibre.constants import cache_dir
from calibre.gui2 import open_url
from calibre.gui2.store import StorePlugin
from calibre.gui2.store.basic_config import BasicStoreConfig
from calibre.gui2.store.search_result import SearchResult
from calibre.gui2.store.stores.mobileread.cache_progress_dialog import CacheProgressDialog
from calibre.gui2.store.stores.mobileread.cache_update_thread import CacheUpdateThread
from calibre.gui2.store.stores.mobileread.models import SearchFilter
from calibre.gui2.store.stores.mobileread.store_dialog import MobileReadStoreDialog
from calibre.gui2.store.web_store_dialog import WebStoreDialog
class MobileReadStore(BasicStoreConfig, StorePlugin):
def __init__(self, *args, **kwargs):
StorePlugin.__init__(self, *args, **kwargs)
self.lock = Lock()
@property
def cache(self):
if not hasattr(self, '_mr_cache'):
from calibre.utils.config import JSONConfig
self._mr_cache = JSONConfig('mobileread_get_books')
self._mr_cache.file_path = os.path.join(cache_dir(),
'mobileread_get_books.json')
self._mr_cache.refresh()
return self._mr_cache
def open(self, parent=None, detail_item=None, external=False):
url = 'https://www.mobileread.com/'
if external or self.config.get('open_external', False):
open_url(QUrl(detail_item if detail_item else url))
else:
if detail_item:
d = WebStoreDialog(self.gui, url, parent, detail_item)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
else:
self.update_cache(parent, 30)
d = MobileReadStoreDialog(self, parent)
d.setWindowTitle(self.name)
d.exec()
def search(self, query, max_results=10, timeout=60):
books = self.get_book_list()
if not books:
return
sf = SearchFilter(books)
matches = sf.parse(query.decode('utf-8', 'replace'))
for book in matches:
book.price = '$0.00'
book.drm = SearchResult.DRM_UNLOCKED
yield book
def update_cache(self, parent=None, timeout=10, force=False,
suppress_progress=False):
if self.lock.acquire(False):
try:
update_thread = CacheUpdateThread(self.cache, self.seralize_books, timeout)
if not suppress_progress:
progress = CacheProgressDialog(parent)
progress.set_message(_('Updating MobileRead book cache...'))
update_thread.total_changed.connect(progress.set_total)
update_thread.update_progress.connect(progress.set_progress)
update_thread.update_details.connect(progress.set_details)
progress.rejected.connect(update_thread.abort)
progress.open()
update_thread.start()
while update_thread.is_alive() and not progress.canceled:
QCoreApplication.processEvents()
if progress.isVisible():
progress.accept()
return not progress.canceled
else:
update_thread.start()
finally:
self.lock.release()
def get_book_list(self):
return self.deseralize_books(self.cache.get('book_list', []))
def seralize_books(self, books):
sbooks = []
for b in books:
data = {}
data['author'] = b.author
data['title'] = b.title
data['detail_item'] = b.detail_item
data['formats'] = b.formats
sbooks.append(data)
return sbooks
def deseralize_books(self, sbooks):
books = []
for s in sbooks:
b = SearchResult()
b.author = s.get('author', '')
b.title = s.get('title', '')
b.detail_item = s.get('detail_item', '')
b.formats = s.get('formats', '')
books.append(b)
return books
| 4,538 | Python | .py | 101 | 33.455446 | 91 | 0.602129 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,885 | models.py | kovidgoyal_calibre/src/calibre/gui2/store/search/models.py | __license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
import re
import string
from operator import attrgetter
from qt.core import QAbstractItemModel, QApplication, QIcon, QModelIndex, QPixmap, QSize, Qt, pyqtSignal
from calibre import force_unicode
from calibre.gui2 import FunctionDispatcher
from calibre.gui2.store.search.download_thread import CoverThreadPool, DetailsThreadPool
from calibre.gui2.store.search_result import SearchResult
from calibre.utils.icu import lower as icu_lower
from calibre.utils.icu import sort_key
from calibre.utils.localization import pgettext
from calibre.utils.search_query_parser import SearchQueryParser
def comparable_price(text):
if isinstance(text, (int, float)):
text = str(text)
if isinstance(text, bytes):
text = text.decode('utf-8', 'ignore')
text = text or ''
# this keep thousand and fraction separators
match = re.search(r'(?:\d|[,.](?=\d))(?:\d*(?:[,.\' ](?=\d))?)+', text)
if match:
# replace all separators with '.'
m = re.sub(r'[.,\' ]', '.', match.group())
# remove all separators accept fraction,
# leave only 2 digits in fraction
m = re.sub(r'\.(?!\d*$)', r'', m)
text = f'{float(m) * 100.:0>8.0f}'
return text
class Matches(QAbstractItemModel):
total_changed = pyqtSignal(int)
HEADERS = [_('Cover'), _('Title'), _('Price'), _('DRM'), pgettext('book store in the Get books calibre feature', 'Store'), _('Download'), _('Affiliate')]
HTML_COLS = (1, 4)
IMG_COLS = (0, 3, 5, 6)
def __init__(self, cover_thread_count=2, detail_thread_count=4):
QAbstractItemModel.__init__(self)
self.DRM_LOCKED_ICON = QIcon.ic('drm-locked.png')
self.DRM_UNLOCKED_ICON = QIcon.ic('drm-unlocked.png')
self.DRM_UNKNOWN_ICON = QIcon.ic('dialog_question.png')
self.DONATE_ICON = QIcon.ic('donate.png')
self.DOWNLOAD_ICON = QIcon.ic('arrow-down.png')
# All matches. Used to determine the order to display
# self.matches because the SearchFilter returns
# matches unordered.
self.all_matches = []
# Only the showing matches.
self.matches = []
self.query = ''
self.filterable_query = False
self.search_filter = SearchFilter()
self.cover_pool = CoverThreadPool(cover_thread_count)
self.details_pool = DetailsThreadPool(detail_thread_count)
self.filter_results_dispatcher = FunctionDispatcher(self.filter_results)
self.got_result_details_dispatcher = FunctionDispatcher(self.got_result_details)
self.sort_col = 2
self.sort_order = Qt.SortOrder.AscendingOrder
def closing(self):
self.cover_pool.abort()
self.details_pool.abort()
def clear_results(self):
self.all_matches = []
self.matches = []
self.all_matches = []
self.search_filter.clear_search_results()
self.query = ''
self.filterable_query = False
self.cover_pool.abort()
self.details_pool.abort()
self.total_changed.emit(self.rowCount())
self.beginResetModel(), self.endResetModel()
def add_result(self, result, store_plugin):
if result not in self.all_matches:
self.modelAboutToBeReset.emit()
self.all_matches.append(result)
self.search_filter.add_search_result(result)
if result.cover_url:
result.cover_queued = True
self.cover_pool.add_task(result, self.filter_results_dispatcher)
else:
result.cover_queued = False
self.details_pool.add_task(result, store_plugin, self.got_result_details_dispatcher)
self._filter_results()
self.modelReset.emit()
def get_result(self, index):
row = index.row()
if row < len(self.matches):
return self.matches[row]
else:
return None
def has_results(self):
return len(self.matches) > 0
def _filter_results(self):
# Only use the search filter's filtered results when there is a query
# and it is a filterable query. This allows for the stores best guess
# matches to come though.
if self.query and self.filterable_query:
self.matches = list(self.search_filter.parse(self.query))
else:
self.matches = list(self.search_filter.universal_set())
self.total_changed.emit(self.rowCount())
self.sort(self.sort_col, self.sort_order, False)
def filter_results(self):
self.modelAboutToBeReset.emit()
self._filter_results()
self.modelReset.emit()
def got_result_details(self, result):
if not result.cover_queued and result.cover_url:
result.cover_queued = True
self.cover_pool.add_task(result, self.filter_results_dispatcher)
if result in self.matches:
row = self.matches.index(result)
self.dataChanged.emit(self.index(row, 0), self.index(row, self.columnCount() - 1))
if result.drm not in (SearchResult.DRM_LOCKED, SearchResult.DRM_UNLOCKED, SearchResult.DRM_UNKNOWN):
result.drm = SearchResult.DRM_UNKNOWN
self.filter_results()
def set_query(self, query):
self.query = query
self.filterable_query = self.is_filterable_query(query)
def is_filterable_query(self, query):
# Remove control modifiers.
query = query.replace('\\', '')
query = query.replace('!', '')
query = query.replace('=', '')
query = query.replace('~', '')
query = query.replace('>', '')
query = query.replace('<', '')
# Store the query at this point for comparison later
mod_query = query
# Remove filter identifiers
# Remove the prefix.
for loc in ('all', 'author', 'author2', 'authors', 'title', 'title2'):
query = re.sub(r'%s:"(?P<a>[^\s"]+)"' % loc, r'\g<a>', query)
query = query.replace('%s:' % loc, '')
# Remove the prefix and search text.
for loc in ('cover', 'download', 'downloads', 'drm', 'format', 'formats', 'price', 'store'):
query = re.sub(r'%s:"[^"]"' % loc, '', query)
query = re.sub(r'%s:[^\s]*' % loc, '', query)
# Remove whitespace
query = re.sub(r'\s', '', query)
mod_query = re.sub(r'\s', '', mod_query)
# If mod_query and query are the same then there were no filter modifiers
# so this isn't a filterable query.
if mod_query == query:
return False
return True
def index(self, row, column, parent=QModelIndex()):
return self.createIndex(row, column)
def parent(self, index):
if not index.isValid() or index.internalId() == 0:
return QModelIndex()
return self.createIndex(0, 0)
def rowCount(self, *args):
return len(self.matches)
def columnCount(self, *args):
return len(self.HEADERS)
def headerData(self, section, orientation, role):
if role != Qt.ItemDataRole.DisplayRole:
return None
text = ''
if orientation == Qt.Orientation.Horizontal:
if section < len(self.HEADERS):
text = self.HEADERS[section]
return (text)
else:
return (section+1)
def data(self, index, role):
row, col = index.row(), index.column()
if row >= len(self.matches):
return None
result = self.matches[row]
if role == Qt.ItemDataRole.DisplayRole:
if col == 1:
t = result.title if result.title else _('Unknown')
a = result.author if result.author else ''
return (f'<b>{t}</b><br><i>{a}</i>')
elif col == 2:
return (result.price)
elif col == 4:
return (f'<span>{result.store_name}<br>{result.formats}</span>')
return None
elif role == Qt.ItemDataRole.DecorationRole:
if col == 0 and result.cover_data:
p = QPixmap()
p.loadFromData(result.cover_data)
p.setDevicePixelRatio(QApplication.instance().devicePixelRatio())
return p
if col == 3:
if result.drm == SearchResult.DRM_LOCKED:
return (self.DRM_LOCKED_ICON)
elif result.drm == SearchResult.DRM_UNLOCKED:
return (self.DRM_UNLOCKED_ICON)
elif result.drm == SearchResult.DRM_UNKNOWN:
return (self.DRM_UNKNOWN_ICON)
if col == 5:
if result.downloads:
return (self.DOWNLOAD_ICON)
if col == 6:
if result.affiliate:
return (self.DONATE_ICON)
elif role == Qt.ItemDataRole.ToolTipRole:
if col == 1:
return ('<p>%s</p>' % result.title)
elif col == 2:
if result.price:
return ('<p>' + _(
'Detected price as: %s. Check with the store before making a purchase'
' to verify this price is correct. This price often does not include'
' promotions the store may be running.') % result.price + '</p>')
return '<p>' + _(
'No price was found')
elif col == 3:
if result.drm == SearchResult.DRM_LOCKED:
return ('<p>' + _('This book as been detected as having DRM restrictions. This book may not work with your reader and you will have limitations placed upon you as to what you can do with this book. Check with the store before making any purchases to ensure you can actually read this book.') + '</p>') # noqa
elif result.drm == SearchResult.DRM_UNLOCKED:
return ('<p>' + _('This book has been detected as being DRM Free. You should be able to use this book on any device provided it is in a format calibre supports for conversion. However, before making a purchase double check the DRM status with the store. The store may not be disclosing the use of DRM.') + '</p>') # noqa
else:
return ('<p>' + _('The DRM status of this book could not be determined. There is a very high likelihood that this book is actually DRM restricted.') + '</p>') # noqa
elif col == 4:
return ('<p>%s</p>' % result.formats)
elif col == 5:
if result.downloads:
return ('<p>' + _('The following formats can be downloaded directly: %s.') % ', '.join(result.downloads.keys()) + '</p>')
elif col == 6:
if result.affiliate:
return ('<p>' + _('Buying from this store supports the calibre developer: %s.') % result.plugin_author + '</p>')
elif role == Qt.ItemDataRole.SizeHintRole:
return QSize(64, 64)
return None
def data_as_text(self, result, col):
text = ''
if col == 1:
text = result.title
elif col == 2:
text = comparable_price(result.price)
elif col == 3:
if result.drm == SearchResult.DRM_UNLOCKED:
text = 'a'
if result.drm == SearchResult.DRM_LOCKED:
text = 'b'
else:
text = 'c'
elif col == 4:
text = result.store_name
elif col == 5:
if result.downloads:
text = 'a'
else:
text = 'b'
elif col == 6:
if result.affiliate:
text = 'a'
else:
text = 'b'
return text
def sort(self, col, order, reset=True):
self.sort_col = col
self.sort_order = order
if not self.matches:
return
descending = order == Qt.SortOrder.DescendingOrder
self.all_matches.sort(
key=lambda x: sort_key(str(self.data_as_text(x, col))),
reverse=descending)
self.reorder_matches()
if reset:
self.beginResetModel(), self.endResetModel()
def reorder_matches(self):
def keygen(x):
try:
return self.all_matches.index(x)
except:
return 100000
self.matches = sorted(self.matches, key=keygen)
class SearchFilter(SearchQueryParser):
CONTAINS_MATCH = 0
EQUALS_MATCH = 1
REGEXP_MATCH = 2
IN_MATCH = 3
USABLE_LOCATIONS = [
'all',
'affiliate',
'author',
'author2',
'authors',
'cover',
'download',
'downloads',
'drm',
'format',
'formats',
'price',
'title',
'title2',
'store',
]
def __init__(self):
SearchQueryParser.__init__(self, locations=self.USABLE_LOCATIONS)
self.srs = set()
# remove joiner words surrounded by space or at string boundaries
self.joiner_pat = re.compile(r'(^|\s)(and|not|or|a|the|is|of)(\s|$)', re.IGNORECASE)
self.punctuation_table = {ord(x):' ' for x in string.punctuation}
def add_search_result(self, search_result):
self.srs.add(search_result)
def clear_search_results(self):
self.srs = set()
def universal_set(self):
return self.srs
def _match(self, query, value, matchkind):
for t in value:
try: # ignore regexp exceptions, required because search-ahead tries before typing is finished
t = icu_lower(t)
if matchkind == self.EQUALS_MATCH:
if query == t:
return True
elif matchkind == self.REGEXP_MATCH:
if re.search(query, t, re.I|re.UNICODE):
return True
elif matchkind == self.CONTAINS_MATCH:
if query in t:
return True
elif matchkind == self.IN_MATCH:
if t in query:
return True
except re.error:
pass
return False
def get_matches(self, location, query):
query = query.strip()
location = location.lower().strip()
if location == 'authors':
location = 'author'
elif location == 'downloads':
location = 'download'
elif location == 'formats':
location = 'format'
matchkind = self.CONTAINS_MATCH
if len(query) > 1:
if query.startswith('\\'):
query = query[1:]
elif query.startswith('='):
matchkind = self.EQUALS_MATCH
query = query[1:]
elif query.startswith('~'):
matchkind = self.REGEXP_MATCH
query = query[1:]
if matchkind != self.REGEXP_MATCH: # leave case in regexps because it can be significant e.g. \S \W \D
query = query.lower()
if location not in self.USABLE_LOCATIONS:
return set()
matches = set()
all_locs = set(self.USABLE_LOCATIONS) - {'all'}
locations = all_locs if location == 'all' else [location]
q = {
'affiliate': attrgetter('affiliate'),
'author': lambda x: x.author.lower(),
'cover': attrgetter('cover_url'),
'drm': attrgetter('drm'),
'download': attrgetter('downloads'),
'format': attrgetter('formats'),
'price': lambda x: comparable_price(x.price),
'store': lambda x: x.store_name.lower(),
'title': lambda x: x.title.lower(),
}
for x in ('author', 'download', 'format'):
q[x+'s'] = q[x]
q['author2'] = q['author']
q['title2'] = q['title']
# make the price in query the same format as result
if location == 'price':
query = comparable_price(query)
for sr in self.srs:
for locvalue in locations:
final_query = query
accessor = q[locvalue]
if query == 'true':
# True/False.
if locvalue == 'affiliate':
if accessor(sr):
matches.add(sr)
# Special that are treated as True/False.
elif locvalue == 'drm':
if accessor(sr) == SearchResult.DRM_LOCKED:
matches.add(sr)
# Testing for something or nothing.
else:
if accessor(sr) is not None:
matches.add(sr)
continue
if query == 'false':
# True/False.
if locvalue == 'affiliate':
if not accessor(sr):
matches.add(sr)
# Special that are treated as True/False.
elif locvalue == 'drm':
if accessor(sr) == SearchResult.DRM_UNLOCKED:
matches.add(sr)
# Testing for something or nothing.
else:
if accessor(sr) is None:
matches.add(sr)
continue
# this is bool or treated as bool, so can't match below.
if locvalue in ('affiliate', 'drm', 'download', 'downloads'):
continue
try:
# Can't separate authors because comma is used for name sep and author sep
# Exact match might not get what you want. For that reason, turn author
# exactmatch searches into contains searches.
if locvalue == 'author' and matchkind == self.EQUALS_MATCH:
m = self.CONTAINS_MATCH
else:
m = matchkind
if locvalue == 'format':
vals = accessor(sr).split(',')
elif locvalue in {'author2', 'title2'}:
m = self.IN_MATCH
vals = [x for x in self.field_trimmer(accessor(sr)).split() if x]
final_query = ' '.join(self.field_trimmer(icu_lower(query)).split())
else:
vals = [accessor(sr)]
if self._match(final_query, vals, m):
matches.add(sr)
break
except ValueError: # Unicode errors
import traceback
traceback.print_exc()
return matches
def field_trimmer(self, field):
''' Remove common joiner words and punctuation to improve matching,
punctuation is removed first, so that a.and.b becomes a b '''
field = force_unicode(field)
return self.joiner_pat.sub(' ', field.translate(self.punctuation_table))
| 19,299 | Python | .py | 435 | 31.970115 | 341 | 0.547619 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,886 | adv_search_builder.py | kovidgoyal_calibre/src/calibre/gui2/store/search/adv_search_builder.py | __license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
import re
from qt.core import QDialog, QDialogButtonBox
from calibre.gui2.store.search.adv_search_builder_ui import Ui_Dialog
from calibre.library.caches import CONTAINS_MATCH, EQUALS_MATCH
from calibre.utils.localization import localize_user_manual_link
class AdvSearchBuilderDialog(QDialog, Ui_Dialog):
def __init__(self, parent):
QDialog.__init__(self, parent)
self.setupUi(self)
try:
self.sh_label.setText(self.sh_label.text() % localize_user_manual_link(
'https://manual.calibre-ebook.com/gui.html#the-search-interface'))
except TypeError:
pass # link already localized
self.buttonBox.accepted.connect(self.advanced_search_button_pushed)
self.tab_2_button_box.accepted.connect(self.accept)
self.tab_2_button_box.rejected.connect(self.reject)
self.clear_button.clicked.connect(self.clear_button_pushed)
self.advanced_clear_button.clicked.connect(self.clear_advanced)
self.adv_search_used = False
self.mc = ''
self.tabWidget.setCurrentIndex(0)
self.tabWidget.currentChanged[int].connect(self.tab_changed)
self.tab_changed(0)
def tab_changed(self, idx):
if idx == 1:
self.tab_2_button_box.button(QDialogButtonBox.StandardButton.Ok).setDefault(True)
else:
self.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setDefault(True)
def advanced_search_button_pushed(self):
self.adv_search_used = True
self.accept()
def clear_button_pushed(self):
self.title_box.setText('')
self.author_box.setText('')
self.price_box.setText('')
self.format_box.setText('')
self.drm_combo.setCurrentIndex(0)
self.download_combo.setCurrentIndex(0)
self.affiliate_combo.setCurrentIndex(0)
def clear_advanced(self):
self.all.setText('')
self.phrase.setText('')
self.any.setText('')
self.none.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):
if self.adv_search_used:
return self.adv_search_string()
else:
return self.box_search_string()
def adv_search_string(self):
mk = self.matchkind.currentIndex()
if mk == CONTAINS_MATCH:
self.mc = ''
elif mk == EQUALS_MATCH:
self.mc = '='
else:
self.mc = '~'
all, any, phrase, none = list(map(lambda x: str(x.text()),
(self.all, self.any, self.phrase, self.none)))
all, any, none = list(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:
ans += (' or ' if ans else '') + 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 = '='
else:
self.mc = '~'
ans = []
self.box_last_values = {}
title = str(self.title_box.text()).strip()
if title:
ans.append('title:"' + self.mc + title + '"')
author = str(self.author_box.text()).strip()
if author:
ans.append('author:"' + self.mc + author + '"')
price = str(self.price_box.text()).strip()
if price:
ans.append('price:"' + self.mc + price + '"')
format = str(self.format_box.text()).strip()
if format:
ans.append('format:"' + self.mc + format + '"')
drm = '' if self.drm_combo.currentIndex() == 0 else 'true' if self.drm_combo.currentIndex() == 1 else 'false'
if drm:
ans.append('drm:' + drm)
download = '' if self.download_combo.currentIndex() == 0 else 'true' if self.download_combo.currentIndex() == 1 else 'false'
if download:
ans.append('download:' + download)
affiliate = '' if self.affiliate_combo.currentIndex() == 0 else 'true' if self.affiliate_combo.currentIndex() == 1 else 'false'
if affiliate:
ans.append('affiliate:' + affiliate)
if ans:
return ' and '.join(ans)
return ''
| 5,207 | Python | .py | 127 | 31.574803 | 135 | 0.575069 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,887 | download_thread.py | kovidgoyal_calibre/src/calibre/gui2/store/search/download_thread.py | __license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
import traceback
from contextlib import closing
from threading import Thread
from calibre import browser
from calibre.constants import DEBUG
from calibre.utils.img import scale_image
from polyglot.binary import from_base64_bytes
from polyglot.queue import Queue
class GenericDownloadThreadPool:
'''
add_task must be implemented in a subclass and must
GenericDownloadThreadPool.add_task must be called
at the end of the function.
'''
def __init__(self, thread_type, thread_count=1):
self.thread_type = thread_type
self.thread_count = thread_count
self.tasks = Queue()
self.results = Queue()
self.threads = []
def set_thread_count(self, thread_count):
self.thread_count = thread_count
def add_task(self):
'''
This must be implemented in a sub class and this function
must be called at the end of the add_task function in
the sub class.
The implementation of this function (in this base class)
starts any threads necessary to fill the pool if it is
not already full.
'''
for i in range(self.thread_count - self.running_threads_count()):
t = self.thread_type(self.tasks, self.results)
self.threads.append(t)
t.start()
def abort(self):
self.tasks = Queue()
self.results = Queue()
for t in self.threads:
t.abort()
self.threads = []
def has_tasks(self):
return not self.tasks.empty()
def get_result(self):
return self.results.get()
def get_result_no_wait(self):
return self.results.get_nowait()
def result_count(self):
return len(self.results)
def has_results(self):
return not self.results.empty()
def threads_running(self):
return self.running_threads_count() > 0
def running_threads_count(self):
count = 0
for t in self.threads:
if t.is_alive():
count += 1
return count
class SearchThreadPool(GenericDownloadThreadPool):
'''
Threads will run until there is no work or
abort is called. Create and start new threads
using start_threads(). Reset by calling abort().
Example:
sp = SearchThreadPool(3)
sp.add_task(...)
'''
def __init__(self, thread_count):
GenericDownloadThreadPool.__init__(self, SearchThread, thread_count)
def add_task(self, query, store_name, store_plugin, max_results, timeout):
self.tasks.put((query, store_name, store_plugin, max_results, timeout))
GenericDownloadThreadPool.add_task(self)
class SearchThread(Thread):
def __init__(self, tasks, results):
Thread.__init__(self)
self.daemon = True
self.tasks = tasks
self.results = results
self._run = True
def abort(self):
self._run = False
def run(self):
while self._run and not self.tasks.empty():
try:
query, store_name, store_plugin, max_results, timeout = self.tasks.get()
for res in store_plugin.search(query, max_results=max_results, timeout=timeout):
if not self._run:
return
res.store_name = store_name
res.affiliate = store_plugin.base_plugin.affiliate
res.plugin_author = store_plugin.base_plugin.author
res.create_browser = store_plugin.create_browser
self.results.put((res, store_plugin))
self.tasks.task_done()
except:
if DEBUG:
traceback.print_exc()
class CoverThreadPool(GenericDownloadThreadPool):
def __init__(self, thread_count):
GenericDownloadThreadPool.__init__(self, CoverThread, thread_count)
def add_task(self, search_result, update_callback, timeout=5):
self.tasks.put((search_result, update_callback, timeout))
GenericDownloadThreadPool.add_task(self)
def decode_data_url(url):
return from_base64_bytes(url.partition(',')[2])
class CoverThread(Thread):
def __init__(self, tasks, results):
Thread.__init__(self)
self.daemon = True
self.tasks = tasks
self.results = results
self._run = True
self.br = browser()
def abort(self):
self._run = False
def run(self):
while self._run and not self.tasks.empty():
try:
result, callback, timeout = self.tasks.get()
if result and result.cover_url:
if result.cover_url.startswith('data:'):
result.cover_data = decode_data_url(result.cover_url)
else:
with closing(self.br.open(result.cover_url, timeout=timeout)) as f:
result.cover_data = f.read()
result.cover_data = scale_image(result.cover_data, 256, 256)[2]
callback()
self.tasks.task_done()
except:
if DEBUG:
traceback.print_exc()
class DetailsThreadPool(GenericDownloadThreadPool):
def __init__(self, thread_count):
GenericDownloadThreadPool.__init__(self, DetailsThread, thread_count)
def add_task(self, search_result, store_plugin, update_callback, timeout=10):
self.tasks.put((search_result, store_plugin, update_callback, timeout))
GenericDownloadThreadPool.add_task(self)
class DetailsThread(Thread):
def __init__(self, tasks, results):
Thread.__init__(self)
self.daemon = True
self.tasks = tasks
self.results = results
self._run = True
def abort(self):
self._run = False
def run(self):
while self._run and not self.tasks.empty():
try:
result, store_plugin, callback, timeout = self.tasks.get()
if result:
store_plugin.get_details(result, timeout)
callback(result)
self.tasks.task_done()
except:
if DEBUG:
traceback.print_exc()
class CacheUpdateThreadPool(GenericDownloadThreadPool):
def __init__(self, thread_count):
GenericDownloadThreadPool.__init__(self, CacheUpdateThread, thread_count)
def add_task(self, store_plugin, timeout=10):
self.tasks.put((store_plugin, timeout))
GenericDownloadThreadPool.add_task(self)
class CacheUpdateThread(Thread):
def __init__(self, tasks, results):
Thread.__init__(self)
self.daemon = True
self.tasks = tasks
self._run = True
def abort(self):
self._run = False
def run(self):
while self._run and not self.tasks.empty():
try:
store_plugin, timeout = self.tasks.get()
store_plugin.update_cache(timeout=timeout, suppress_progress=True)
except:
if DEBUG:
traceback.print_exc()
| 7,232 | Python | .py | 183 | 29.704918 | 96 | 0.60841 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,888 | search.py | kovidgoyal_calibre/src/calibre/gui2/store/search/search.py | __license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
import re
from random import shuffle
from qt.core import QCheckBox, QDialog, QDialogButtonBox, QGridLayout, QIcon, QLabel, QSize, QStyle, Qt, QTabWidget, QTimer, QVBoxLayout, QWidget
from calibre.gui2 import JSONConfig, error_dialog, info_dialog
from calibre.gui2.dialogs.choose_format import ChooseFormatDialog
from calibre.gui2.ebook_download import show_download_info
from calibre.gui2.progress_indicator import ProgressIndicator
from calibre.gui2.store.config.chooser.chooser_widget import StoreChooserWidget
from calibre.gui2.store.config.search.search_widget import StoreConfigWidget
from calibre.gui2.store.search.adv_search_builder import AdvSearchBuilderDialog
from calibre.gui2.store.search.download_thread import CacheUpdateThreadPool, SearchThreadPool
from calibre.gui2.store.search.search_ui import Ui_Dialog
from calibre.utils.filenames import ascii_filename
def add_items_to_context_menu(self, menu):
menu.addSeparator()
ac = menu.addAction(_('Clear search &history'))
ac.triggered.connect(self.clear_history)
return menu
class SearchDialog(QDialog, Ui_Dialog):
SEARCH_TEXT = _('&Search')
STOP_TEXT = _('&Stop')
def __init__(self, gui, parent=None, query=''):
QDialog.__init__(self, parent)
self.setupUi(self)
s = self.style()
self.close.setIcon(s.standardIcon(QStyle.StandardPixmap.SP_DialogCloseButton))
self.config = JSONConfig('store/search')
self.search_title.initialize('store_search_search_title')
self.search_author.initialize('store_search_search_author')
self.search_edit.initialize('store_search_search')
self.search_title.add_items_to_context_menu = add_items_to_context_menu
self.search_author.add_items_to_context_menu = add_items_to_context_menu
self.search_edit.add_items_to_context_menu = add_items_to_context_menu
# Loads variables that store various settings.
# This needs to be called soon in __init__ because
# the variables it sets up are used later.
self.load_settings()
self.gui = gui
# Setup our worker threads.
self.search_pool = SearchThreadPool(self.search_thread_count)
self.cache_pool = CacheUpdateThreadPool(self.cache_thread_count)
self.results_view.model().cover_pool.set_thread_count(self.cover_thread_count)
self.results_view.model().details_pool.set_thread_count(self.details_thread_count)
self.results_view.setCursor(Qt.CursorShape.PointingHandCursor)
# needed for live updates of amazon_live.py
from calibre.live import start_worker
start_worker()
# Check for results and hung threads.
self.checker = QTimer()
self.progress_checker = QTimer()
self.hang_check = 0
# Update store caches silently.
for p in self.gui.istores.values():
self.cache_pool.add_task(p, self.timeout)
self.store_checks = {}
self.setup_store_checks()
# Set the search query
if isinstance(query, (bytes, str)):
self.search_edit.setText(query)
elif isinstance(query, dict):
if 'author' in query:
self.search_author.setText(query['author'])
if 'title' in query:
self.search_title.setText(query['title'])
# Create and add the progress indicator
self.pi = ProgressIndicator(self, 24)
self.button_layout.takeAt(0)
self.button_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.button_layout.insertWidget(0, self.pi, 0, Qt.AlignmentFlag.AlignCenter)
self.adv_search_button.setIcon(QIcon.ic('gear.png'))
self.adv_search_button.setToolTip(_('Advanced search'))
self.configure.setIcon(QIcon.ic('config.png'))
self.adv_search_button.clicked.connect(self.build_adv_search)
self.search.clicked.connect(self.toggle_search)
self.checker.timeout.connect(self.get_results)
self.progress_checker.timeout.connect(self.check_progress)
self.results_view.activated.connect(self.result_item_activated)
self.results_view.download_requested.connect(self.download_book)
self.results_view.open_requested.connect(self.open_store)
self.results_view.model().total_changed.connect(self.update_book_total)
self.select_all_stores.clicked.connect(self.stores_select_all)
self.select_invert_stores.clicked.connect(self.stores_select_invert)
self.select_none_stores.clicked.connect(self.stores_select_none)
self.configure.clicked.connect(self.do_config)
self.finished.connect(self.dialog_closed)
self.searching = False
self.progress_checker.start(100)
self.restore_state()
def setup_store_checks(self):
first_run = self.config.get('first_run', True)
# Add check boxes for each store so the user
# can disable searching specific stores on a
# per search basis.
existing = {}
for n in self.store_checks:
existing[n] = self.store_checks[n].isChecked()
self.store_checks = {}
stores_check_widget = QWidget()
store_list_layout = QGridLayout()
stores_check_widget.setLayout(store_list_layout)
icon = QIcon.ic('donate.png')
for i, x in enumerate(sorted(self.gui.istores.keys(), key=lambda x: x.lower())):
cbox = QCheckBox(x)
cbox.setChecked(existing.get(x, first_run))
store_list_layout.addWidget(cbox, i, 0, 1, 1)
if self.gui.istores[x].base_plugin.affiliate:
iw = QLabel(self)
iw.setToolTip('<p>' + _('Buying from this store supports the calibre developer: %s</p>') % self.gui.istores[x].base_plugin.author + '</p>')
iw.setPixmap(icon.pixmap(16, 16))
store_list_layout.addWidget(iw, i, 1, 1, 1)
self.store_checks[x] = cbox
store_list_layout.setRowStretch(store_list_layout.rowCount(), 10)
self.store_list.setWidget(stores_check_widget)
self.config['first_run'] = False
def build_adv_search(self):
adv = AdvSearchBuilderDialog(self)
if adv.exec() == QDialog.DialogCode.Accepted:
self.search_edit.setText(adv.search_string())
def resize_columns(self):
total = 600
# Cover
self.results_view.setColumnWidth(0, 85)
total = total - 85
# Title / Author
self.results_view.setColumnWidth(1,int(total*.40))
# Price
self.results_view.setColumnWidth(2,int(total*.12))
# DRM
self.results_view.setColumnWidth(3, int(total*.15))
# Store / Formats
self.results_view.setColumnWidth(4, int(total*.25))
# Download
self.results_view.setColumnWidth(5, 20)
# Affiliate
self.results_view.setColumnWidth(6, 20)
def toggle_search(self):
if self.searching:
self.search_pool.abort()
m = self.results_view.model()
m.details_pool.abort()
m.cover_pool.abort()
self.search.setText(self.SEARCH_TEXT)
self.checker.stop()
self.searching = False
else:
self.do_search()
# Prevent hitting the enter key twice in quick succession causing
# the search to start and stop
self.search.setEnabled(False)
QTimer.singleShot(1000, lambda :self.search.setEnabled(True))
def do_search(self):
# Stop all running threads.
self.checker.stop()
self.search_pool.abort()
# Clear the visible results.
self.results_view.model().clear_results()
# Don't start a search if there is nothing to search for.
query = []
if self.search_title.text():
query.append('title2:"~%s"' % str(self.search_title.text()).replace('"', ' '))
if self.search_author.text():
query.append('author2:"%s"' % str(self.search_author.text()).replace('"', ' '))
if self.search_edit.text():
query.append(str(self.search_edit.text()))
query = " ".join(query)
if not query.strip():
error_dialog(self, _('No query'),
_('You must enter a title, author or keyword to'
' search for.'), show=True)
return
self.searching = True
self.search.setText(self.STOP_TEXT)
# Give the query to the results model so it can do
# further filtering.
self.results_view.model().set_query(query)
# Plugins are in random order that does not change.
# Randomize the order of the plugin names every time
# there is a search. This way plugins closer
# to a don't have an unfair advantage over
# plugins further from a.
store_names = list(self.store_checks)
if not store_names:
return
# Remove all of our internal filtering logic from the query.
query = self.clean_query(query)
shuffle(store_names)
# Add plugins that the user has checked to the search pool's work queue.
self.gui.istores.join(4.0) # Wait for updated plugins to load
for n in store_names:
if self.store_checks[n].isChecked():
self.search_pool.add_task(query, n, self.gui.istores[n], self.max_results, self.timeout)
self.hang_check = 0
self.checker.start(100)
self.pi.startAnimation()
def clean_query(self, query):
query = query.lower()
# Remove control modifiers.
query = query.replace('\\', '')
query = query.replace('!', '')
query = query.replace('=', '')
query = query.replace('~', '')
query = query.replace('>', '')
query = query.replace('<', '')
# Remove the prefix.
for loc in ('all', 'author', 'author2', 'authors', 'title', 'title2'):
query = re.sub(r'%s:"(?P<a>[^\s"]+)"' % loc, r'\g<a>', query)
query = query.replace('%s:' % loc, '')
# Remove the prefix and search text.
for loc in ('cover', 'download', 'downloads', 'drm', 'format', 'formats', 'price', 'store'):
query = re.sub(r'%s:"[^"]"' % loc, '', query)
query = re.sub(r'%s:[^\s]*' % loc, '', query)
# Remove logic.
query = re.sub(r'(^|\s|")(and|not|or|a|the|is|of)(\s|$|")', r' ', query)
# Remove "
query = query.replace('"', '')
# Remove excess whitespace.
query = re.sub(r'\s+', ' ', query)
query = query.strip()
return query.encode('utf-8')
def save_state(self):
self.save_geometry(self.config, 'geometry')
self.config['store_splitter_state'] = bytearray(self.store_splitter.saveState())
self.config['results_view_column_width'] = [self.results_view.columnWidth(i) for i in range(self.results_view.model().columnCount())]
self.config['sort_col'] = self.results_view.model().sort_col
self.config['sort_order'] = self.results_view.model().sort_order.value
self.config['open_external'] = self.open_external.isChecked()
store_check = {}
for k, v in self.store_checks.items():
store_check[k] = v.isChecked()
self.config['store_checked'] = store_check
def restore_state(self):
self.restore_geometry(self.config, 'geometry')
splitter_state = self.config.get('store_splitter_state', None)
if splitter_state:
self.store_splitter.restoreState(splitter_state)
results_cwidth = self.config.get('results_view_column_width', None)
if results_cwidth:
for i, x in enumerate(results_cwidth):
if i >= self.results_view.model().columnCount():
break
self.results_view.setColumnWidth(i, x)
else:
self.resize_columns()
self.open_external.setChecked(self.should_open_external)
store_check = self.config.get('store_checked', None)
if store_check:
for n in store_check:
if n in self.store_checks:
self.store_checks[n].setChecked(store_check[n])
self.results_view.model().sort_col = self.config.get('sort_col', 2)
so = self.config.get('sort_order', Qt.SortOrder.AscendingOrder)
if isinstance(so, int):
so = Qt.SortOrder(so)
self.results_view.model().sort_order = so
self.results_view.header().setSortIndicator(self.results_view.model().sort_col, so)
def load_settings(self):
# Seconds
self.timeout = self.config.get('timeout', 75)
# Milliseconds
self.hang_time = self.config.get('hang_time', 75) * 1000
self.max_results = self.config.get('max_results', 15)
self.should_open_external = self.config.get('open_external', True)
# Number of threads to run for each type of operation
self.search_thread_count = self.config.get('search_thread_count', 4)
self.cache_thread_count = self.config.get('cache_thread_count', 2)
self.cover_thread_count = self.config.get('cover_thread_count', 2)
self.details_thread_count = self.config.get('details_thread_count', 4)
def do_config(self):
# Save values that need to be synced between the dialog and the
# search widget.
self.config['open_external'] = self.open_external.isChecked()
# Create the config dialog. It's going to put two config widgets
# into a QTabWidget for displaying all of the settings.
d = QDialog(self)
button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
v = QVBoxLayout(d)
button_box.accepted.connect(d.accept)
button_box.rejected.connect(d.reject)
d.setWindowTitle(_('Customize Get books search'))
tab_widget = QTabWidget(d)
v.addWidget(tab_widget)
v.addWidget(button_box)
chooser_config_widget = StoreChooserWidget()
search_config_widget = StoreConfigWidget(self.config)
tab_widget.addTab(chooser_config_widget, _('Choose s&tores'))
tab_widget.addTab(search_config_widget, _('Configure s&earch'))
# Restore dialog state.
self.restore_geometry(self.config, 'config_dialog_geometry')
tab_index = self.config.get('config_dialog_tab_index', 0)
tab_index = min(tab_index, tab_widget.count() - 1)
tab_widget.setCurrentIndex(tab_index)
d.exec()
# Save dialog state.
self.save_geometry(self.config, 'config_dialog_geometry')
self.config['config_dialog_tab_index'] = tab_widget.currentIndex()
search_config_widget.save_settings()
self.config_changed()
self.gui.load_store_plugins()
self.setup_store_checks()
def sizeHint(self):
return QSize(800, 600)
def config_changed(self):
self.load_settings()
self.open_external.setChecked(self.should_open_external)
self.search_pool.set_thread_count(self.search_thread_count)
self.cache_pool.set_thread_count(self.cache_thread_count)
self.results_view.model().cover_pool.set_thread_count(self.cover_thread_count)
self.results_view.model().details_pool.set_thread_count(self.details_thread_count)
def get_results(self):
# We only want the search plugins to run
# a maximum set amount of time before giving up.
self.hang_check += 1
if self.hang_check >= self.hang_time:
self.search_pool.abort()
self.checker.stop()
else:
# Stop the checker if not threads are running.
if not self.search_pool.threads_running() and not self.search_pool.has_tasks():
self.checker.stop()
while self.search_pool.has_results():
res, store_plugin = self.search_pool.get_result()
if res:
self.results_view.model().add_result(res, store_plugin)
if not self.search_pool.threads_running() and not self.results_view.model().has_results():
info_dialog(self, _('No matches'), _('Couldn\'t find any books matching your query.'), show=True, show_copy_button=False)
def update_book_total(self, total):
self.total.setText('%s' % total)
def result_item_activated(self, index):
result = self.results_view.model().get_result(index)
if result.downloads:
self.download_book(result)
else:
self.open_store(result)
def download_book(self, result):
d = ChooseFormatDialog(self, _('Choose format to download to your library.'), list(result.downloads.keys()))
if d.exec() == QDialog.DialogCode.Accepted:
ext = d.format()
fname = result.title[:60] + '.' + ext.lower()
fname = ascii_filename(fname)
show_download_info(result.title, parent=self)
self.gui.download_ebook(result.downloads[ext], filename=fname, create_browser=result.create_browser)
def open_store(self, result):
self.gui.istores[result.store_name].open(self, result.detail_item, self.open_external.isChecked())
def check_progress(self):
m = self.results_view.model()
if not self.search_pool.threads_running() and not m.cover_pool.threads_running() and not m.details_pool.threads_running():
self.pi.stopAnimation()
self.search.setText(self.SEARCH_TEXT)
self.searching = False
else:
self.searching = True
if str(self.search.text()) != self.STOP_TEXT:
self.search.setText(self.STOP_TEXT)
if not self.pi.isAnimated():
self.pi.startAnimation()
def stores_select_all(self):
for check in self.store_checks.values():
check.setChecked(True)
def stores_select_invert(self):
for check in self.store_checks.values():
check.setChecked(not check.isChecked())
def stores_select_none(self):
for check in self.store_checks.values():
check.setChecked(False)
def dialog_closed(self, result):
self.results_view.model().closing()
self.search_pool.abort()
self.cache_pool.abort()
self.save_state()
def exec(self):
if str(self.search_edit.text()).strip() or str(self.search_title.text()).strip() or str(self.search_author.text()).strip():
self.do_search()
return QDialog.exec(self)
exec_ = exec
if __name__ == '__main__':
import sys
from calibre.gui2 import Application
from calibre.gui2.preferences.main import init_gui
app = Application([])
app
gui = init_gui()
s = SearchDialog(gui, query=' '.join(sys.argv[1:]))
s.exec()
| 18,986 | Python | .py | 386 | 39.727979 | 155 | 0.63892 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,889 | results_view.py | kovidgoyal_calibre/src/calibre/gui2/store/search/results_view.py | __license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from functools import partial
from qt.core import QIcon, QMenu, QStyledItemDelegate, Qt, QTreeView, pyqtSignal
from calibre import fit_image
from calibre.gui2 import empty_index
from calibre.gui2.metadata.single_download import RichTextDelegate
from calibre.gui2.store.search.models import Matches
class ImageDelegate(QStyledItemDelegate):
def paint(self, painter, option, index):
QStyledItemDelegate.paint(self, painter, option, empty_index)
img = index.data(Qt.ItemDataRole.DecorationRole)
if img:
h = option.rect.height() - 4
w = option.rect.width()
if isinstance(img, QIcon):
img = img.pixmap(h - 4, h - 4)
dpr = img.devicePixelRatio()
else:
dpr = img.devicePixelRatio()
scaled, nw, nh = fit_image(img.width(), img.height(), w, h)
if scaled:
img = img.scaled(int(nw*dpr), int(nh*dpr), Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation)
iw, ih = int(img.width()/dpr), int(img.height()/dpr)
dx, dy = (option.rect.width() - iw) // 2, (option.rect.height() - ih) // 2
painter.drawPixmap(option.rect.adjusted(dx, dy, -dx, -dy), img)
class ResultsView(QTreeView):
download_requested = pyqtSignal(object)
open_requested = pyqtSignal(object)
def __init__(self, *args, **kwargs):
QTreeView.__init__(self,*args, **kwargs)
self._model = Matches()
self.setModel(self._model)
self.rt_delegate = RichTextDelegate(self)
self.img_delegate = ImageDelegate(self)
for i in self._model.HTML_COLS:
self.setItemDelegateForColumn(i, self.rt_delegate)
for i in self._model.IMG_COLS:
self.setItemDelegateForColumn(i, self.img_delegate)
def contextMenuEvent(self, event):
index = self.indexAt(event.pos())
if not index.isValid():
return
result = self.model().get_result(index)
menu = QMenu(self)
da = menu.addAction(_('Download...'), partial(self.download_requested.emit, result))
if not result.downloads:
da.setEnabled(False)
menu.addSeparator()
menu.addAction(_('Show in store'), partial(self.open_requested.emit, result))
menu.exec(event.globalPos())
| 2,505 | Python | .py | 52 | 39.076923 | 144 | 0.641215 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,890 | dialog.py | kovidgoyal_calibre/src/calibre/gui2/fts/dialog.py | #!/usr/bin/env python
# License: GPL v3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net>
import os
from qt.core import QAction, QDialogButtonBox, QHBoxLayout, QIcon, QLabel, QSize, QStackedWidget, Qt, QVBoxLayout
from calibre.gui2 import error_dialog, warning_dialog
from calibre.gui2.fts.scan import ScanStatus
from calibre.gui2.fts.search import ResultsPanel
from calibre.gui2.fts.utils import get_db
from calibre.gui2.ui import get_gui
from calibre.gui2.widgets2 import Dialog
class FTSDialog(Dialog):
def __init__(self, parent=None):
super().__init__(_('Search the text of all books in the library'), 'library-fts-dialog',
default_buttons=QDialogButtonBox.StandardButton.Close)
self.setWindowIcon(QIcon.ic('fts.png'))
self.setWindowFlags(self.windowFlags() | Qt.WindowType.WindowMinMaxButtonsHint)
self.view_action = ac = QAction(self)
ac.triggered.connect(self.view_current_book)
gui = get_gui()
if gui is not None:
ac.setShortcuts(gui.iactions['View'].menuless_qaction.shortcuts())
self.addAction(ac)
def view_current_book(self):
if not self.results_panel.view_current_result():
error_dialog(self, _('No result selected'), _('Cannot view book as no result is selected'), show=True)
def setup_ui(self):
l = QVBoxLayout(self)
self.fat_warning = fw = QLabel(
f'<span style="color:red; font-weight: bold">{_("WARNING")}:</span> ' +
_('The calibre library is on a FAT drive, indexing more than a few hundred books wont work.') +
f' <a href="xxx" style="text-decoration: none">{_("Learn more")}</a>')
# fw.setVisible(False)
fw.linkActivated.connect(self.show_fat_details)
l.addWidget(self.fat_warning)
self.stack = s = QStackedWidget(self)
l.addWidget(s)
h = QHBoxLayout()
h.setContentsMargins(0, 0, 0, 0)
l.addLayout(h)
self.indexing_label = il = QLabel(self)
il.setToolTip('<p>' + _(
'Indexing of all books in this library is not yet complete, so search results'
' will not be from all books. Click the <i>Show indexing status</i> button to see details.'))
h.addWidget(il), h.addStretch(), h.addWidget(self.bb)
self.scan_status = ss = ScanStatus(self)
ss.switch_to_search_panel.connect(self.show_results_panel)
self.results_panel = rp = ResultsPanel(self)
rp.switch_to_scan_panel.connect(self.show_scan_status)
s.addWidget(ss), s.addWidget(rp)
self.show_appropriate_panel()
self.update_indexing_label()
self.scan_status.indexing_progress_changed.connect(self.update_indexing_label)
self.addAction(self.results_panel.jump_to_current_book_action)
def show_fat_details(self):
warning_dialog(self, _('Library on a FAT drive'), _(
'The calibre library {} is on a FAT drive. These drives have a limit on the maximum file size. Therefore'
' indexing of more than a few hundred books will fail. You should move your calibre library to an NTFS'
' or exFAT drive.').format(get_db().backend.library_path), show=True)
def update_fat_warning(self):
db = get_db()
self.fat_warning.setVisible(db.is_fat_filesystem)
def show_appropriate_panel(self):
ss = self.scan_status
if ss.indexing_enabled and ss.indexing_progress.almost_complete:
self.show_results_panel()
else:
self.show_scan_status()
def update_indexing_label(self):
ip = self.scan_status.indexing_progress
if self.stack.currentWidget() is self.scan_status or ip.complete:
self.indexing_label.setVisible(False)
else:
self.indexing_label.setVisible(True)
try:
p = (ip.total - ip.left) / ip.total
except Exception:
self.indexing_label.setVisible(False)
else:
if p < 1:
q = f'{p:.0%}'
t = _('Indexing is almost complete') if q == '100%' else _('Indexing is only {} done').format(q)
ss = ''
if p < 0.9:
ss = 'QLabel { color: red }'
self.indexing_label.setStyleSheet(ss)
self.indexing_label.setText(t)
else:
self.indexing_label.setVisible(False)
def show_scan_status(self):
self.stack.setCurrentWidget(self.scan_status)
self.scan_status.specialize_button_box(self.bb)
self.update_indexing_label()
def show_results_panel(self):
self.stack.setCurrentWidget(self.results_panel)
self.results_panel.specialize_button_box(self.bb)
self.update_indexing_label()
self.results_panel.on_show()
def library_changed(self):
self.results_panel.clear_results()
self.scan_status.reset_indexing_state_for_current_db()
self.show_appropriate_panel()
self.update_fat_warning()
def sizeHint(self):
return QSize(1000, 680)
def show(self):
super().show()
self.scan_status.startup()
self.results_panel.on_show()
self.update_fat_warning()
def clear_search_history(self):
self.results_panel.clear_history()
def set_search_text(self, text):
self.results_panel.set_search_text(text)
if __name__ == '__main__':
from calibre.gui2 import Application
from calibre.library import db
get_db.db = db(os.path.expanduser('~/test library'))
app = Application([])
d = FTSDialog()
d.exec()
| 5,718 | Python | .py | 120 | 38.125 | 117 | 0.634684 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,891 | search.py | kovidgoyal_calibre/src/calibre/gui2/fts/search.py | #!/usr/bin/env python
# License: GPL v3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net>
import os
import re
import time
import traceback
from contextlib import suppress
from functools import partial
from itertools import count
from threading import Event, Thread
from qt.core import (
QAbstractItemModel,
QAbstractItemView,
QAction,
QCheckBox,
QDialog,
QDialogButtonBox,
QFont,
QHBoxLayout,
QIcon,
QKeySequence,
QLabel,
QMenu,
QModelIndex,
QPixmap,
QPushButton,
QRect,
QSize,
QSplitter,
QStackedWidget,
Qt,
QTreeView,
QVBoxLayout,
QWidget,
pyqtSignal,
)
from calibre import fit_image, prepare_string_for_xml
from calibre.db import FTSQueryError
from calibre.ebooks.metadata import authors_to_string, fmt_sidx
from calibre.gui2 import config, error_dialog, gprefs, info_dialog, question_dialog, safe_open_url
from calibre.gui2.fts.utils import get_db
from calibre.gui2.library.models import render_pin
from calibre.gui2.progress_indicator import ProgressIndicator
from calibre.gui2.ui import get_gui
from calibre.gui2.viewer.widgets import ResultsDelegate, SearchBox
from calibre.gui2.widgets import BusyCursor
from calibre.gui2.widgets2 import HTMLDisplay
from calibre.utils.localization import ngettext
ROOT = QModelIndex()
sanitize_text_pat = re.compile(r'\s+')
fts_url = 'https://www.sqlite.org/fts5.html#full_text_query_syntax'
def mark_books(*book_ids):
gui = get_gui()
if gui is not None:
gui.iactions['Mark Books'].add_ids(book_ids)
def jump_to_book(book_id, parent=None):
gui = get_gui()
if gui is not None:
parent = parent or gui
if gui.library_view.select_rows((book_id,)):
gui.raise_and_focus()
else:
if gprefs['fts_library_restrict_books']:
error_dialog(parent, _('Not found'), _('This book was not found in the calibre library'), show=True)
else:
error_dialog(parent, _('Not found'), _(
'This book is not currently visible in the calibre library.'
' If you have a search or Virtual library active, try clearing that.'
' Or click the "Restrict searched books" checkbox in this window to'
' only search currently visible books.'), show=True)
def show_in_viewer(book_id, text, fmt):
text = text.strip('…').replace('\x1d', '').replace('\xa0', ' ')
text = sanitize_text_pat.sub(' ', text)
gui = get_gui()
if gui is not None:
if fmt in config['internally_viewed_formats']:
gui.iactions['View'].view_format_by_id(book_id, fmt, open_at=f'search:{text}')
else:
gui.iactions['View'].view_format_by_id(book_id, fmt)
def open_book(results, match_index=None):
gui = get_gui()
if gui is None:
return
book_id = results.book_id
if match_index is None:
gui.iactions['View'].view_historical(book_id)
return
result_dict = results.result_dicts[match_index]
formats = results.formats[match_index]
from calibre.gui2.actions.view import preferred_format
show_in_viewer(book_id, result_dict['text'], preferred_format(formats))
class SearchDelegate(ResultsDelegate):
def result_data(self, result):
if not isinstance(result, dict):
return None, None, None, None, None
full_text = result['text']
parts = full_text.split('\x1d', 2)
before = after = ''
if len(parts) > 2:
before, text = parts[:2]
after = parts[2].replace('\x1d', '')
elif len(parts) == 2:
before, text = parts
else:
text = parts[0]
return False, before, text, after, False
class Results:
_title = _authors = _series = _series_index = None
def __init__(self, book_id):
self.book_id = book_id
self.text_map = {}
self.result_dicts = []
self.formats = []
def add_result_with_text(self, result):
text = result['text']
q = sanitize_text_pat.sub('', text)
fmt = result['format']
i = self.text_map.get(q)
if i is None:
i = self.text_map[q] = len(self.result_dicts)
self.result_dicts.append(result)
self.formats.append(set())
self.formats[i].add(fmt)
def __len__(self):
return len(self.result_dicts)
def __getitem__(self, x):
return self.result_dicts[x]
@property
def title(self):
if self._title is None:
with suppress(Exception):
self._title = get_db().field_for('title', self.book_id)
self._title = self._title or _('Unknown book')
return self._title
@property
def authors(self):
if self._authors is None:
with suppress(Exception):
self._authors = get_db().field_for('authors', self.book_id)
self._authors = self._authors or [_('Unknown author')]
return self._authors
@property
def cover(self):
try:
ans = get_db().cover(self.book_id, as_pixmap=True)
except Exception:
ans = QPixmap()
if ans.isNull():
ic = QIcon.ic('default_cover.png')
ans = ic.pixmap(ic.availableSizes()[0])
return ans
@property
def series(self):
if self._series is None:
try:
self._series = get_db().field_for('series', self.book_id)
except Exception:
self._series = ''
return self._series
@property
def series_index(self):
if self._series_index is None:
try:
self._series_index = get_db().field_for('series_index', self.book_id)
except Exception:
self._series_index = 1
return self._series_index
class ResultsModel(QAbstractItemModel):
result_found = pyqtSignal(int, object)
all_results_found = pyqtSignal(int)
search_started = pyqtSignal()
matches_found = pyqtSignal(int)
search_complete = pyqtSignal()
query_failed = pyqtSignal(str, str)
result_with_context_found = pyqtSignal(object, int)
def __init__(self, parent=None):
super().__init__(parent)
self.italic_font = parent.font() if parent else QFont()
self.italic_font.setItalic(True)
self.results = []
self.query_id_counter = count()
self.current_query_id = -1
self.current_thread_abort = Event()
self.current_thread = None
self.current_search_key = None
self.result_found.connect(self.result_with_text_found, type=Qt.ConnectionType.QueuedConnection)
self.all_results_found.connect(self.signal_search_complete, type=Qt.ConnectionType.QueuedConnection)
def all_book_ids(self):
for r in self.results:
yield r.book_id
def clear_results(self):
self.current_query_id = -1
self.current_thread_abort.set()
self.current_search_key = None
self.search_started.emit()
self.matches_found.emit(-1)
self.beginResetModel()
self.results = []
self.endResetModel()
self.search_complete.emit()
def abort_search(self):
self.current_thread_abort.set()
self.signal_search_complete(self.current_query_id)
self.current_search_key = None # so that re-doing the search works
def get_result(self, book_id, result_num):
idx = self.result_map[book_id]
results = self.results[idx]
return results.result_dicts[result_num]
def search(self, fts_engine_query, use_stemming=True, restrict_to_book_ids=None):
db = get_db()
failure = []
def construct(all_matches):
self.result_map = r = {}
sr = self.results = []
try:
for x in all_matches:
book_id = x['book_id']
results = r.get(book_id)
if results is None:
results = Results(book_id)
r[book_id] = len(sr)
sr.append(results)
except FTSQueryError as e:
failure.append(e)
sk = fts_engine_query, use_stemming, restrict_to_book_ids, id(db)
if sk == self.current_search_key:
return False
self.current_thread_abort.set()
self.current_search_key = sk
self.search_started.emit()
self.matches_found.emit(-1)
self.beginResetModel()
db.fts_search(
fts_engine_query, use_stemming=use_stemming, highlight_start='\x1d', highlight_end='\x1d', snippet_size=64,
restrict_to_book_ids=restrict_to_book_ids, result_type=construct, return_text=False
)
self.endResetModel()
if not failure:
self.matches_found.emit(len(self.results))
self.current_query_id = next(self.query_id_counter)
self.current_thread_abort = Event()
if failure:
self.current_thread = Thread(target=lambda *a: None)
self.all_results_found.emit(self.current_query_id)
if fts_engine_query.strip():
self.query_failed.emit(fts_engine_query, str(failure[0]))
else:
self.current_thread = Thread(
name='FTSQuery', daemon=True, target=self.search_text_in_thread, args=(
self.current_query_id, self.current_thread_abort, fts_engine_query,), kwargs=dict(
use_stemming=use_stemming, highlight_start='\x1d', highlight_end='\x1d', snippet_size=64,
restrict_to_book_ids=restrict_to_book_ids, return_text=True)
)
self.current_thread.start()
return True
def remove_book(self, book_id):
idx = self.result_map.get(book_id)
if idx is not None:
self.beginRemoveRows(ROOT, idx, idx)
del self.results[idx]
del self.result_map[book_id]
self.endRemoveRows()
self.matches_found.emit(len(self.results))
return True
return False
def search_text_in_thread(self, query_id, abort, *a, **kw):
db = get_db()
generator = db.fts_search(*a, **kw, result_type=lambda x: x)
for result in generator:
if abort.wait(0.01): # wait for some time so that other threads/processes that try to access the db can be scheduled
with suppress(StopIteration):
generator.send(True)
return
self.result_found.emit(query_id, result)
self.all_results_found.emit(query_id)
def result_with_text_found(self, query_id, result):
if query_id != self.current_query_id:
return
bid = result['book_id']
i = self.result_map.get(bid)
if i is not None:
parent = self.results[i]
parent_idx = self.index(i, 0)
r = len(parent)
self.beginInsertRows(parent_idx, r, r)
parent.add_result_with_text(result)
self.endInsertRows()
self.result_with_context_found.emit(parent, r)
def signal_search_complete(self, query_id):
if query_id == self.current_query_id:
self.current_query_id = -1
self.current_thread = None
self.search_complete.emit()
def index_to_entry(self, idx):
q = idx.internalId()
if q:
# search result
list_idx = q - 1
try:
q = self.results[list_idx]
return q[idx.row()]
except Exception:
traceback.print_exc()
return None
else:
ans = idx.row()
if -1 < ans < len(self.results):
return self.results[ans]
def index(self, row, column, parent=ROOT):
if parent.isValid():
return self.createIndex(row, column, parent.row() + 1)
return self.createIndex(row, column, 0)
def parent(self, index):
q = index.internalId()
if q:
return self.index(q - 1, 0)
return ROOT
def rowCount(self, parent=ROOT):
if parent.isValid():
x = self.index_to_entry(parent)
if isinstance(x, Results):
return len(x)
return 0
return len(self.results)
def columnCount(self, parent=ROOT):
return 1
def data(self, index, role=Qt.ItemDataRole.DisplayRole):
item = self.index_to_entry(index)
if item is None:
return
if isinstance(item, Results):
return self.data_for_book(item, role)
return self.data_for_match(item, role)
def flags(self, index):
item = self.index_to_entry(index)
if item is None:
return Qt.ItemFlag.NoItemFlags
if isinstance(item, Results):
return Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable
return Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemNeverHasChildren
def data_for_book(self, item, role):
if role == Qt.ItemDataRole.DisplayRole:
return item.title
if role == Qt.ItemDataRole.UserRole:
return item
if role == Qt.ItemDataRole.FontRole:
return self.italic_font
def data_for_match(self, item, role):
if role == Qt.ItemDataRole.UserRole:
return item
def data_for_index(self, index):
item = self.index_to_entry(index)
if item is None:
return None, None
if isinstance(item, Results):
return item, None
return self.index_to_entry(self.parent(index)), item
class ResultsView(QTreeView):
search_started = pyqtSignal()
matches_found = pyqtSignal(int)
search_complete = pyqtSignal()
current_changed = pyqtSignal(object, object)
result_with_context_found = pyqtSignal(object, int)
def __init__(self, parent=None):
super().__init__(parent)
self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.customContextMenuRequested.connect(self.show_context_menu)
self.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
self.setHeaderHidden(True)
self.m = ResultsModel(self)
self.m.result_with_context_found.connect(self.result_with_context_found)
self.m.search_complete.connect(self.search_complete)
self.m.search_started.connect(self.search_started)
self.m.search_started.connect(self.focus_self)
self.m.query_failed.connect(self.query_failed, type=Qt.ConnectionType.QueuedConnection)
self.m.matches_found.connect(self.matches_found)
self.setModel(self.m)
self.delegate = SearchDelegate(self)
self.setItemDelegate(self.delegate)
self.setUniformRowHeights(True)
def keyPressEvent(self, ev):
i = self.currentIndex()
ret = super().keyPressEvent(ev)
if self.currentIndex() != i:
self.scrollTo(self.currentIndex())
return ret
def currentChanged(self, current, previous):
results, individual_match = self.m.data_for_index(current)
if individual_match is not None:
individual_match = current.row()
self.current_changed.emit(results, individual_match)
def focus_self(self):
self.setFocus(Qt.FocusReason.OtherFocusReason)
def query_failed(self, query, err_msg):
error_dialog(self, _('Invalid search query'), _(
'The search query: {query} was not understood. See <a href="{fts_url}">here</a> for details on the'
' supported query syntax.').format(
query=query, fts_url=fts_url), det_msg=err_msg, show=True)
def search(self, *a):
gui = get_gui()
restrict = None
if gui and gprefs['fts_library_restrict_books']:
restrict = frozenset(gui.library_view.model().all_current_book_ids())
with BusyCursor():
self.m.search(*a, restrict_to_book_ids=restrict, use_stemming=gprefs['fts_library_use_stemmer'])
self.expandAll()
self.setCurrentIndex(self.m.index(0, 0))
def show_context_menu(self, pos):
index = self.indexAt(pos)
results, match = self.m.data_for_index(index)
m = QMenu(self)
if results:
m.addAction(QIcon.ic('lt.png'), _('Jump to this book in the library'), partial(jump_to_book, results.book_id, self))
m.addAction(QIcon.ic('marked.png'), _('Mark this book in the library'), partial(mark_books, results.book_id))
if match is not None:
match = index.row()
m.addAction(QIcon.ic('view.png'), _('View this book at this search result'), partial(open_book, results, match_index=match))
else:
m.addAction(QIcon.ic('view.png'), _('View this book'), partial(open_book, results))
m.addSeparator()
m.addAction(QIcon.ic('plus.png'), _('Expand all'), self.expandAll)
m.addAction(QIcon.ic('minus.png'), _('Collapse all'), self.collapseAll)
m.exec(self.mapToGlobal(pos))
def view_current_result(self):
idx = self.currentIndex()
if idx.isValid():
results, match = self.m.data_for_index(idx)
if results:
if match is not None:
match = idx.row()
open_book(results, match)
return True
return False
class Spinner(ProgressIndicator):
last_mouse_press_at = 0
clicked = pyqtSignal(object)
def __init__(self, *a):
super().__init__(*a)
self.setCursor(Qt.CursorShape.PointingHandCursor)
def sizeHint(self):
return QSize(8, 8)
def paintEvent(self, ev):
if self.isAnimated():
super().paintEvent(ev)
def mousePressEvent(self, ev):
if ev.button() == Qt.MouseButton.LeftButton:
self.last_mouse_press_at = time.monotonic()
ev.accept()
super().mousePressEvent(ev)
def mouseReleaseEvent(self, ev):
if ev.button() == Qt.MouseButton.LeftButton:
dt = time.monotonic() - self.last_mouse_press_at
self.last_mouse_press_at = 0
if dt < 0.5:
self.clicked.emit(ev)
ev.accept()
return
super().mouseReleaseEvent(ev)
class SearchInputPanel(QWidget):
search_signal = pyqtSignal(object)
clear_search = pyqtSignal()
request_stop_search = pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent)
QHBoxLayout(self)
self.layout().setContentsMargins(0, 0, 0, 0)
self.v1 = v1 = QVBoxLayout()
v1.setAlignment(Qt.AlignmentFlag.AlignTop)
self.layout().addLayout(v1)
self.search_box = sb = SearchBox(self)
sb.cleared.connect(self.clear_search)
sb.initialize('library-fts-search-box')
sb.lineEdit().returnPressed.connect(self.search_requested)
sb.lineEdit().setPlaceholderText(_('Enter words to search for'))
v1.addWidget(sb)
self.h1 = h1 = QHBoxLayout()
v1.addLayout(h1)
self.restrict = r = QCheckBox(_('&Restrict searched books'))
r.setToolTip('<p>' + _(
'Restrict search results to only the books currently showing in the main'
' library screen. This means that any Virtual libraries or search results'
' are applied.'))
r.setChecked(gprefs['fts_library_restrict_books'])
r.stateChanged.connect(lambda state: gprefs.set('fts_library_restrict_books', state != Qt.CheckState.Unchecked.value))
self.related = rw = QCheckBox(_('&Match on related words'))
rw.setToolTip('<p>' + _(
'With this option searching for words will also match on any related words (supported in several languages). For'
' example, in the English language: {0} matches {1} and {2} as well').format(
'<i>correction</i>', '<i>correcting</i>', '<i>corrected</i>'))
rw.setChecked(gprefs['fts_library_use_stemmer'])
rw.stateChanged.connect(lambda state: gprefs.set('fts_library_use_stemmer', state != Qt.CheckState.Unchecked.value))
self.summary = s = QLabel(self)
h1.addWidget(r), h1.addWidget(rw), h1.addStretch(), h1.addWidget(s)
self.search_button = sb = QPushButton(QIcon.ic('search.png'), _('&Search'), self)
sb.clicked.connect(self.search_requested)
self.v2 = v2 = QVBoxLayout()
v2.addWidget(sb)
self.pi = pi = Spinner(self)
pi.clicked.connect(self.request_stop_search)
v2.addWidget(pi)
self.layout().addLayout(v2)
def clear_history(self):
self.search_box.clear_history()
def set_search_text(self, text):
self.search_box.setText(text)
def start(self):
self.pi.start()
def stop(self):
self.pi.stop()
def search_requested(self):
text = self.search_box.text().strip()
self.search_signal.emit(text)
def matches_found(self, num):
if num < 0:
self.summary.setText('')
else:
self.summary.setText(ngettext('One book', '{num} books', num).format(num=num))
class ResultDetails(QWidget):
show_in_viewer = pyqtSignal(int, int, str)
remove_book_from_results = pyqtSignal(int)
def __init__(self, parent=None):
super().__init__(parent)
self.jump_action = ac = QAction(self)
ac.triggered.connect(self.jump_to_current_book)
ac.setShortcut(QKeySequence('Ctrl+S', QKeySequence.SequenceFormat.PortableText))
self.key = None
self.pixmap_label = pl = QLabel(self)
pl.setScaledContents(True)
self.book_info = bi = HTMLDisplay(self)
bi.setDefaultStyleSheet('a { text-decoration: none; }')
bi.anchor_clicked.connect(self.book_info_anchor_clicked)
self.results = r = HTMLDisplay(self)
r.setDefaultStyleSheet('a { text-decoration: none; }')
r.anchor_clicked.connect(self.results_anchor_clicked)
@property
def current_book_id(self):
return -1 if self.key is None else self.key[0]
@property
def current_individual_match(self):
return None if self.key is None else self.key[2]
def book_info_anchor_clicked(self, url):
if self.current_book_id > 0:
if url.host() == 'mark':
mark_books(self.current_book_id)
elif url.host() == 'jump':
jump_to_book(self.current_book_id)
elif url.host() == 'unindex':
db = get_db()
db.fts_unindex(self.current_book_id)
self.remove_book_from_results.emit(self.current_book_id)
elif url.host() == 'reindex':
db = get_db()
db.reindex_fts_book(self.current_book_id)
info_dialog(self, _('Scheduled for re-indexing'), _(
'This book has been scheduled for re-indexing, which typically takes a few seconds, if'
' no other books are being re-indexed. Once indexing is complete, you can re-run the search'
' to see updated results.'), show=True)
self.remove_book_from_results.emit(self.current_book_id)
def jump_to_current_book(self):
if self.current_book_id > -1:
jump_to_book(self.current_book_id)
def results_anchor_clicked(self, url):
if self.current_book_id > 0 and url.scheme() == 'book':
book_id, result_num, fmt = url.path().strip('/').split('/')
book_id, result_num = int(book_id), int(result_num)
self.show_in_viewer.emit(int(book_id), int(result_num), fmt)
def resizeEvent(self, ev):
self.do_layout()
def do_layout(self):
g = self.geometry()
max_width, max_height = g.width() // 2, g.height() // 3
p = self.pixmap_label.pixmap()
scaled, nw, nh = fit_image(p.width(), p.height(), max_width, max_height)
self.pixmap_label.setGeometry(QRect(0, 0, nw, nh))
w = g.width() - nw - 8
d = self.book_info.document()
d.setDocumentMargin(0)
d.setTextWidth(float(w))
ph = self.pixmap_label.height()
self.book_info.setGeometry(QRect(self.pixmap_label.geometry().right() + 8, 0, w, ph))
top = max(self.book_info.geometry().bottom(), self.pixmap_label.geometry().bottom())
self.results.setGeometry(QRect(0, top, g.width(), g.height() - top))
def show_result(self, results, individual_match=None):
key = results.book_id, len(results.result_dicts), individual_match
if key == self.key:
return False
old_current_book_id = self.current_book_id
self.key = key
if old_current_book_id != self.current_book_id:
self.pixmap_label.setPixmap(results.cover)
self.render_book_info(results)
self.render_results(results, individual_match)
self.do_layout()
return True
def result_with_context_found(self, results, individual_match):
if results.book_id == self.current_book_id:
return self.show_result(results, self.current_individual_match)
return False
def render_book_info(self, results):
t = results.title
if len(t) > 72:
t = t[:71] + '…'
text = f'<p><b>{prepare_string_for_xml(t)}</b><br>'
au = results.authors
if len(au) > 3:
au = list(au[:3]) + ['…']
text += f'{prepare_string_for_xml(authors_to_string(au))}</p>'
if results.series:
sidx = fmt_sidx(results.series_index or 0, use_roman=config['use_roman_numerals_for_series_number'])
series = results.series
if len(series) > 60:
series = series[:59] + '…'
series = prepare_string_for_xml(series)
text += '<p>' + _('{series_index} of {series}').format(series_index=sidx, series=series) + '</p>'
ict = '<img valign="bottom" src="calibre-icon:///{}" width=16 height=16>'
text += '<p><a href="calibre://jump" title="{1}">{2}\xa0{0}</a>\xa0\xa0\xa0 '.format(
_('Select'), '<p>' + _('Scroll to this book in the calibre library book list and select it [{}]').format(
self.jump_action.shortcut().toString(QKeySequence.SequenceFormat.NativeText)), ict.format('lt.png'))
text += '<a href="calibre://mark" title="{1}">{2}\xa0{0}</a></p>'.format(
_('Mark'), '<p>' + _(
'Put a pin on this book in the calibre library, for future reference.'
' You can search for marked books using the search term: {0}').format('<p>marked:true'), ict.format('marked.png'))
if get_db().has_id(results.book_id):
text += '<p><a href="calibre://reindex" title="{1}">{2}\xa0{0}</a>'.format(
_('Re-index'), _('Re-index this book. Useful if the book has been changed outside of calibre, and thus not automatically re-indexed.'),
ict.format('view-refresh.png'))
else:
text += '<p><a href="calibre://unindex" title="{1}">{2}\xa0{0}</a>'.format(
_('Un-index'), _('This book has been deleted from the library but is still present in the'
' full text search index. Remove it.'), ict.format('trash.png'))
text += '<p>' + _('This book may have more than one match, only a single match per book is shown.')
self.book_info.setHtml(text)
def render_results(self, results, individual_match=None):
html = []
space_pat = re.compile(r'\s+')
markup_pat = re.compile('\x1d')
def markup_text(text):
count = 0
def sub(m):
nonlocal count
count += 1
return '<b><i>' if count % 2 else '</i></b>'
return space_pat.sub(' ', markup_pat.sub(sub, text))
ci = self.current_individual_match
for i, (result, formats) in enumerate(zip(results.result_dicts, results.formats)):
if ci is not None and ci != i:
continue
text = result['text']
text = markup_text(prepare_string_for_xml(text))
html.append('<hr>')
for fmt in formats:
fmt = fmt.upper()
tt = _('Open the book, in the {fmt} format.\nWhen using the calibre E-book viewer, it will attempt to scroll\n'
'to this search result automatically.'
).format(fmt=fmt)
html.append(f'<a title="{tt}" href="book:///{self.current_book_id}/{i}/{fmt}">{fmt}</a>\xa0 ')
html.append(f'<p>{text}</p>')
self.results.setHtml('\n'.join(html))
def clear(self):
self.key = None
self.book_info.setHtml('')
self.results.setHtml('')
self.pixmap_label.setPixmap(QPixmap())
class DetailsPanel(QStackedWidget):
show_in_viewer = pyqtSignal(int, int, str)
remove_book_from_results = pyqtSignal(int)
def __init__(self, parent=None):
super().__init__(parent)
# help panel {{{
self.help_panel = hp = HTMLDisplay(self)
hp.setDefaultStyleSheet('a { text-decoration: none; }')
hp.setHtml('''
<style>
.wrapper { margin-left: 4px }
div { margin-top: 0.5ex }
.h { font-weight: bold; }
.bq { margin-left: 1em; margin-top: 0.5ex; margin-bottom: 0.5ex; font-style: italic }
p { margin: 0; }
</style><div class="wrapper">
''' + _('''
<div class="h">Search for single words</div>
<p>Simply type the word:</p>
<div class="bq">awesome<br>calibre</div>
<div class="h">Search for phrases</div>
<p>Enclose the phrase in quotes:</p>
<div class="bq">"early run"<br>"song of love"</div>
<div class="h">Boolean searches</div>
<div class="bq">(calibre AND ebook) NOT gun<br>simple NOT ("high bar" OR hard)</div>
<div class="h">Phrases near each other</div>
<div class="bq">NEAR("people" "in Asia" "try")<br>NEAR("Kovid" "calibre", 30)</div>
<p>Here, 30 is the most words allowed between near groups. Defaults to 10 when unspecified.</p>
<div style="margin-top: 1em"><a href="{fts_url}">Complete syntax reference</a></div>
''' + '</div>').format(fts_url=fts_url))
hp.setFocusPolicy(Qt.FocusPolicy.NoFocus)
hp.document().setDocumentMargin(0)
hp.anchor_clicked.connect(safe_open_url)
self.addWidget(hp)
# }}}
self.result_details = rd = ResultDetails(self)
rd.show_in_viewer.connect(self.show_in_viewer)
rd.remove_book_from_results.connect(self.remove_book_from_results)
self.addWidget(rd)
def sizeHint(self):
return QSize(400, 700)
def show_result(self, results=None, individual_match=None):
if results is None:
self.setCurrentIndex(0)
else:
self.setCurrentIndex(1)
self.result_details.show_result(results, individual_match)
def result_with_context_found(self, results, individual_match):
if self.currentIndex() == 1:
self.result_details.result_with_context_found(results, individual_match)
def clear(self):
self.setCurrentIndex(0)
self.result_details.clear()
class LeftPanel(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
QVBoxLayout(self)
def sizeHint(self):
return QSize(700, 700)
class ResultsPanel(QWidget):
switch_to_scan_panel = pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent)
if isinstance(parent, QDialog):
parent.finished.connect(self.shutdown)
self.l = l = QVBoxLayout(self)
l.setContentsMargins(0, 0, 0, 0)
self.splitter = s = QSplitter(self)
s.setChildrenCollapsible(False)
l.addWidget(s)
self.lp = lp = LeftPanel(self)
s.addWidget(lp)
l = lp.layout()
self.sip = sip = SearchInputPanel(parent=self)
sip.request_stop_search.connect(self.request_stop_search)
l.addWidget(sip)
self.results_view = rv = ResultsView(parent=self)
l.addWidget(rv)
self.search = rv.search
rv.search_started.connect(self.sip.start)
rv.matches_found.connect(self.sip.matches_found)
rv.search_complete.connect(self.sip.stop)
sip.search_signal.connect(self.search)
sip.clear_search.connect(self.clear_results)
self.details = d = DetailsPanel(self)
d.show_in_viewer.connect(self.show_in_viewer)
d.remove_book_from_results.connect(self.remove_book_from_results)
rv.current_changed.connect(d.show_result)
rv.search_started.connect(d.clear)
rv.result_with_context_found.connect(d.result_with_context_found)
s.addWidget(d)
st = gprefs.get('fts_search_splitter_state')
if st is not None:
s.restoreState(st)
@property
def jump_to_current_book_action(self):
return self.details.result_details.jump_action
def view_current_result(self):
return self.results_view.view_current_result()
def clear_history(self):
self.sip.clear_history()
def set_search_text(self, text):
self.sip.set_search_text(text)
def remove_book_from_results(self, book_id):
self.results_view.m.remove_book(book_id)
def show_in_viewer(self, book_id, result_num, fmt):
r = self.results_view.m.get_result(book_id, result_num)
show_in_viewer(book_id, r['text'], fmt)
def request_stop_search(self):
if question_dialog(self, _('Are you sure?'), _('Abort the current search?')):
self.results_view.m.abort_search()
def specialize_button_box(self, bb):
bb.clear()
bb.addButton(QDialogButtonBox.StandardButton.Close)
bb.addButton(_('Show &indexing status'), QDialogButtonBox.ButtonRole.ActionRole).clicked.connect(self.switch_to_scan_panel)
b = bb.addButton(_('&Mark all books'), QDialogButtonBox.ButtonRole.ActionRole)
b.setIcon(QIcon.ic('marked.png'))
m = QMenu(b)
m.addAction(QIcon.ic('marked.png'), _('Mark all matched books in the library'), partial(self.mark_books, 'mark'))
m.addAction(QIcon.ic('edit-select-all.png'), _('Select all matched books in the library'), partial(self.mark_books, 'select'))
if not hasattr(self, 'colored_pin'):
self.colored_pin = QIcon(render_pin())
m.addAction(QIcon(self.colored_pin), _('Mark and select all matched books'), partial(self.mark_books, 'mark-select'))
b.setMenu(m)
def mark_books(self, which):
gui = get_gui()
if gui is not None:
book_ids = tuple(self.results_view.model().all_book_ids())
if which == 'mark':
gui.iactions['Mark Books'].add_ids(book_ids)
elif which == 'select':
gui.library_view.select_rows(book_ids)
elif which == 'mark-select':
gui.iactions['Mark Books'].add_ids(book_ids)
gui.library_view.select_rows(book_ids)
def clear_results(self):
self.results_view.m.clear_results()
def shutdown(self):
b = self.splitter.saveState()
gprefs['fts_search_splitter_state'] = bytearray(b)
self.clear_results()
self.sip.search_box.setText('')
def on_show(self):
self.sip.search_box.setFocus(Qt.FocusReason.OtherFocusReason)
if __name__ == '__main__':
from calibre.gui2 import Application
from calibre.library import db
app = Application([])
d = QDialog()
d.sizeHint = lambda : QSize(1000, 680)
l = QVBoxLayout(d)
bb = QDialogButtonBox(d)
bb.accepted.connect(d.accept), bb.rejected.connect(d.reject)
get_db.db = db(os.path.expanduser('~/test library'))
w = ResultsPanel(parent=d)
l.addWidget(w)
l.addWidget(bb)
w.sip.search_box.setText('asimov')
w.sip.search_button.click()
d.exec()
| 36,225 | Python | .py | 823 | 34.600243 | 151 | 0.611784 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,892 | scan.py | kovidgoyal_calibre/src/calibre/gui2/fts/scan.py | #!/usr/bin/env python
# License: GPL v3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net>
import os
from qt.core import QCheckBox, QDialog, QDialogButtonBox, QHBoxLayout, QIcon, QLabel, QPushButton, QRadioButton, QVBoxLayout, QWidget, pyqtSignal
from calibre.db.listeners import EventType
from calibre.db.utils import IndexingProgress
from calibre.gui2.dialogs.confirm_delete import confirm
from calibre.gui2.fts.utils import get_db
from calibre.gui2.ui import get_gui
class ScanProgress(QWidget):
switch_to_search_panel = pyqtSignal()
def __init__(self, parent):
super().__init__(parent)
self.l = l = QVBoxLayout(self)
l.setContentsMargins(0, 0, 0, 0)
self.status_label = la = QLabel('\xa0')
la.setWordWrap(True)
l.addWidget(la)
self.h = h = QHBoxLayout()
l.addLayout(h)
self.wl = la = QLabel(_(
'Normally, calibre indexes books slowly, in the background,'
' to avoid overloading your computer. You can instead have'
' calibre speed up indexing. This is useful if you intend to leave your'
' computer running overnight to quickly finish the indexing.'
' Both your computer and calibre will be less responsive while'
' fast indexing is active. Closing this window will automatically reset to'
' slow indexing.'
))
la.setWordWrap(True)
l.addWidget(la)
self.h = h = QHBoxLayout()
l.addLayout(h)
h.addWidget(QLabel(_('Indexing speed:')))
self.slow_button = sb = QRadioButton(_('&Slow'), self)
sb.setChecked(True)
h.addWidget(sb)
self.fast_button = fb = QRadioButton(_('&Fast'), self)
h.addWidget(fb)
fb.toggled.connect(self.change_speed)
h.addStretch(10)
l.addStretch(10)
self.warn_label = la = QLabel('<p><span style="color: red">{}</span>: {}'.format(
_('WARNING'), _(
'Not all the books in this library have been indexed yet.'
' Searching will yield incomplete results.')))
la.setWordWrap(True)
l.addWidget(la)
self.switch_anyway = sa = QPushButton(self)
sa.clicked.connect(self.switch_to_search_panel)
h = QHBoxLayout()
h.setContentsMargins(0, 0, 0, 0)
h.addWidget(sa), h.addStretch(10)
l.addLayout(h)
@property
def indexing_progress(self):
return self.parent().indexing_progress
def change_speed(self):
db = get_db()
db.set_fts_speed(slow=not self.fast_button.isChecked())
def update(self, complete, left, total):
if complete:
t = _('All book files indexed')
self.warn_label.setVisible(False)
self.switch_anyway.setIcon(QIcon.ic('search.png'))
self.switch_anyway.setText(_('Start &searching'))
else:
done = total - left
p = done / (total or 1)
p = f'{p:.0%}'
if p == '100%':
p = _('almost 100%')
t = _('{0} of {1} book files, {2} have been indexed, {3}').format(done, total, p, self.indexing_progress.time_left)
self.warn_label.setVisible(True)
self.switch_anyway.setIcon(QIcon.ic('dialog_warning.png'))
self.switch_anyway.setText(_('Start &searching even with incomplete indexing'))
self.status_label.setText(t)
class ScanStatus(QWidget):
indexing_progress_changed = pyqtSignal(bool, int, int)
switch_to_search_panel = pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent)
if isinstance(parent, QDialog):
parent.finished.connect(self.shutdown)
self.indexing_progress = IndexingProgress()
self.l = l = QVBoxLayout(self)
l.setContentsMargins(0, 0, 0, 0)
self.enable_fts = b = QCheckBox(self)
b.setText(_('&Index books in this library to allow searching their full text'))
b.setChecked(self.db.is_fts_enabled())
l.addWidget(b)
self.enable_msg = la = QLabel('<p>' + _(
'In order to search the full text of books, the text must first be <i>indexed</i>. Once enabled, indexing is done'
' automatically, in the background, whenever new books are added to this calibre library.'))
la.setWordWrap(True)
l.addWidget(la)
self.scan_progress = sc = ScanProgress(self)
sc.switch_to_search_panel.connect(self.switch_to_search_panel)
self.indexing_progress_changed.connect(self.scan_progress.update)
l.addWidget(sc)
l.addStretch(10)
self.apply_fts_state()
self.enable_fts.toggled.connect(self.change_fts_state)
self.update_stats()
gui = get_gui()
if gui is None:
self.db.add_listener(self)
else:
gui.add_db_listener(self.gui_update_event)
def gui_update_event(self, db, event_type, event_data):
if event_type is EventType.indexing_progress_changed:
self.update_stats(event_data)
def __call__(self, event_type, library_id, event_data):
if event_type is EventType.indexing_progress_changed:
self.update_stats(event_data)
def update_stats(self, event_data=None):
event_data = event_data or self.db.fts_indexing_progress()
changed = self.indexing_progress.update(*event_data)
if changed:
self.indexing_progress_changed.emit(self.indexing_progress.complete, self.indexing_progress.left, self.indexing_progress.total)
def change_fts_state(self):
if not self.enable_fts.isChecked() and not confirm(_(
'Disabling indexing will mean that all books will have to be re-checked when re-enabling indexing. Are you sure?'
), 'disable-fts-indexing', self):
self.enable_fts.blockSignals(True)
self.enable_fts.setChecked(True)
self.enable_fts.blockSignals(False)
return
self.db.enable_fts(enabled=self.enable_fts.isChecked())
self.apply_fts_state()
def apply_fts_state(self):
b = self.enable_fts
f = b.font()
indexing_enabled = b.isChecked()
f.setBold(not indexing_enabled)
b.setFont(f)
self.enable_msg.setVisible(not indexing_enabled)
self.scan_progress.setVisible(indexing_enabled)
@property
def db(self):
return get_db()
def specialize_button_box(self, bb: QDialogButtonBox):
bb.clear()
bb.addButton(QDialogButtonBox.StandardButton.Close)
b = bb.addButton(_('Re-index'), QDialogButtonBox.ButtonRole.ActionRole)
b.setIcon(QIcon.ic('view-refresh.png'))
b.setToolTip(_('Re-index all books in this library'))
b.clicked.connect(self.reindex)
def reindex(self):
if not confirm(_(
'This will force calibre to re-index all the books in this library, which'
' can take a long time. Are you sure?'), 'fts-reindex-confirm', self):
return
from calibre.gui2.widgets import BusyCursor
with BusyCursor():
self.db.reindex_fts()
@property
def indexing_enabled(self):
return self.enable_fts.isChecked()
def reset_indexing_state_for_current_db(self):
self.enable_fts.blockSignals(True)
self.enable_fts.setChecked(self.db.is_fts_enabled())
self.enable_fts.blockSignals(False)
self.update_stats()
self.apply_fts_state()
def startup(self):
db = self.db
if db:
db.fts_start_measuring_rate(measure=True)
def shutdown(self):
self.scan_progress.slow_button.setChecked(True)
self.reset_indexing_state_for_current_db()
db = self.db
if db:
db.fts_start_measuring_rate(measure=False)
if __name__ == '__main__':
from calibre.gui2 import Application
from calibre.library import db
app = Application([])
d = QDialog()
l = QVBoxLayout(d)
bb = QDialogButtonBox(d)
bb.accepted.connect(d.accept), bb.rejected.connect(d.reject)
get_db.db = db(os.path.expanduser('~/test library'))
w = ScanStatus(parent=d)
l.addWidget(w)
l.addWidget(bb)
w.specialize_button_box(bb)
d.exec()
| 8,322 | Python | .py | 189 | 35.142857 | 145 | 0.634535 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,893 | utils.py | kovidgoyal_calibre/src/calibre/gui2/fts/utils.py | #!/usr/bin/env python
# License: GPL v3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net>
from calibre.gui2.ui import get_gui
def get_db():
if hasattr(get_db, 'db'):
return get_db.db.new_api
return get_gui().current_db.new_api
| 252 | Python | .py | 7 | 32.142857 | 72 | 0.701245 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,894 | models.py | kovidgoyal_calibre/src/calibre/gui2/library/models.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import functools
import numbers
import os
import re
import sys
import time
import traceback
from collections import defaultdict, namedtuple
from itertools import groupby
from qt.core import QAbstractTableModel, QApplication, QColor, QFont, QFontMetrics, QIcon, QImage, QModelIndex, QPainter, QPixmap, Qt, pyqtSignal
from calibre import fit_image, human_readable, isbytestring, prepare_string_for_xml, strftime
from calibre.constants import DEBUG, config_dir, dark_link_color, filesystem_encoding
from calibre.db.search import CONTAINS_MATCH, EQUALS_MATCH, REGEXP_MATCH, _match
from calibre.db.utils import force_to_bool
from calibre.ebooks.metadata import authors_to_string, fmt_sidx, string_to_authors
from calibre.ebooks.metadata.book.formatter import SafeFormat
from calibre.gui2 import error_dialog, is_dark_theme, simple_excepthook
from calibre.gui2.library import DEFAULT_SORT
from calibre.library.coloring import color_row_key
from calibre.library.save_to_disk import find_plugboard
from calibre.ptempfile import PersistentTemporaryFile
from calibre.utils.config import device_prefs, prefs, tweaks
from calibre.utils.date import UNDEFINED_DATE, dt_factory, is_date_undefined, qt_from_dt, qt_to_dt
from calibre.utils.icu import sort_key
from calibre.utils.localization import calibre_langcode_to_name, ngettext
from calibre.utils.resources import get_path as P
from calibre.utils.search_query_parser import ParseException, SearchQueryParser
from polyglot.builtins import iteritems, itervalues, string_or_bytes
Counts = namedtuple('Counts', 'library_total total current')
TIME_FMT = '%d %b %Y'
ALIGNMENT_MAP = {'left': Qt.AlignmentFlag.AlignLeft, 'right': Qt.AlignmentFlag.AlignRight, 'center':
Qt.AlignmentFlag.AlignHCenter}
def render_pin(color='green', save_to=None):
svg = P('pin-template.svg', data=True).replace(b'fill:#f39509', ('fill:' + color).encode('utf-8'))
pm = QPixmap()
dpr = QApplication.instance().devicePixelRatio()
pm.setDevicePixelRatio(dpr)
pm.loadFromData(svg, 'svg')
if save_to:
pm.save(save_to)
return pm
def group_numbers(numbers):
for k, g in groupby(enumerate(sorted(numbers)), lambda i_x:i_x[0] - i_x[1]):
first = None
for last in g:
if first is None:
first = last[1]
yield first, last[1]
class ColumnColor: # {{{
def __init__(self, formatter):
self.mi = None
self.formatter = formatter
def __call__(self, id_, key, fmt, db, color_cache, template_cache):
key += str(hash(fmt))
if id_ in color_cache and key in color_cache[id_]:
self.mi = None
color = color_cache[id_][key]
if color.isValid():
return color
return None
try:
if self.mi is None:
self.mi = db.new_api.get_proxy_metadata(id_)
color = QColor(self.formatter.safe_format(fmt, self.mi, '', self.mi,
column_name=key,
template_cache=template_cache))
color_cache[id_][key] = color
if color.isValid():
self.mi = None
return color
except:
pass
# }}}
def themed_icon_name(icon_dir, icon_name):
root,ext = os.path.splitext(icon_name)
# Remove any theme from the icon name
root = root.removesuffix('-for-dark-theme').removesuffix('-for-light-theme')
# Check if the correct themed icon exists.
theme_suffix = '-for-dark-theme' if is_dark_theme() else '-for-light-theme'
d = os.path.join(icon_dir, root + theme_suffix + ext)
if os.path.exists(d):
return d
# No themed icon exists. Try the original name
d = os.path.join(icon_dir, icon_name)
return d if os.path.exists(d) else None
class ColumnIcon: # {{{
def __init__(self, formatter, model):
self.mi = None
self.formatter = formatter
self.model = model
self.dpr = QApplication.instance().devicePixelRatio()
def __call__(self, id_, fmts, cache_index, db, icon_cache, icon_bitmap_cache,
template_cache):
if id_ in icon_cache and cache_index in icon_cache[id_]:
self.mi = None
return icon_cache[id_][cache_index]
try:
if self.mi is None:
self.mi = db.new_api.get_proxy_metadata(id_)
icons = []
for dex, (kind, fmt) in enumerate(fmts):
rule_icons = self.formatter.safe_format(fmt, self.mi, '', self.mi,
column_name=cache_index+str(dex),
template_cache=template_cache)
if not rule_icons:
continue
icon_list = [ic.strip() for ic in rule_icons.split(':') if ic.strip()]
icons.extend(icon_list)
if icon_list and not kind.endswith('_composed'):
break
if icons:
icon_string = ':'.join(icons)
if icon_string in icon_bitmap_cache:
icon_bitmap = icon_bitmap_cache[icon_string]
icon_cache[id_][cache_index] = icon_bitmap
return icon_bitmap
icon_bitmaps = []
total_width = 0
rh = max(2, self.model.row_height - 4)
dim = int(self.dpr * rh)
icon_dir = os.path.join(config_dir, 'cc_icons')
for icon in icons:
d = themed_icon_name(icon_dir, icon)
if d is not None:
bm = QPixmap(d)
scaled, nw, nh = fit_image(bm.width(), bm.height(), bm.width(), dim)
bm = bm.scaled(int(nw), int(nh), aspectRatioMode=Qt.AspectRatioMode.IgnoreAspectRatio,
transformMode=Qt.TransformationMode.SmoothTransformation)
bm.setDevicePixelRatio(self.dpr)
icon_bitmaps.append(bm)
total_width += bm.width()
if len(icon_bitmaps) > 1:
i = len(icon_bitmaps)
result = QPixmap(total_width + ((i-1)*2), dim)
result.setDevicePixelRatio(self.dpr)
result.fill(Qt.GlobalColor.transparent)
painter = QPainter(result)
x = 0
for bm in icon_bitmaps:
painter.drawPixmap(x, 0, bm)
x += int(bm.width() / self.dpr) + 2
painter.end()
else:
result = icon_bitmaps[0]
icon_cache[id_][cache_index] = result
icon_bitmap_cache[icon_string] = result
self.mi = None
return result
except:
pass
# }}}
class BooksModel(QAbstractTableModel): # {{{
about_to_be_sorted = pyqtSignal(object, name='aboutToBeSorted')
sorting_done = pyqtSignal(object, name='sortingDone')
database_changed = pyqtSignal(object, name='databaseChanged')
new_bookdisplay_data = pyqtSignal(object)
count_changed_signal = pyqtSignal(int)
searched = pyqtSignal(object)
search_done = pyqtSignal()
def __init__(self, parent=None, buffer=40):
QAbstractTableModel.__init__(self, parent)
base_font = parent.font() if parent else QApplication.instance().font()
self.bold_font = QFont(base_font)
self.bold_font.setBold(True)
self.italic_font = QFont(base_font)
self.italic_font.setItalic(True)
self.bi_font = QFont(self.bold_font)
self.bi_font.setItalic(True)
self.styled_columns = {}
self.orig_headers = {
'title' : _("Title"),
'ondevice' : _("On Device"),
'authors' : _("Author(s)"),
'size' : _("Size (MB)"),
'timestamp' : _("Date"),
'pubdate' : _('Published'),
'rating' : _('Rating'),
'publisher' : _("Publisher"),
'tags' : _("Tags"),
'series' : ngettext("Series", 'Series', 1),
'last_modified' : _('Modified'),
'languages' : _('Languages'),
'formats' : _('Formats'),
'id' : _('Id'),
'path' : _('Path'),
}
self.db = None
self.formatter = SafeFormat()
self._clear_caches()
self.column_color = ColumnColor(self.formatter)
self.column_icon = ColumnIcon(self.formatter, self)
self.book_on_device = None
self.editable_cols = ['title', 'authors', 'rating', 'publisher',
'tags', 'series', 'timestamp', 'pubdate',
'languages']
self.sorted_on = DEFAULT_SORT
self.sort_history = [self.sorted_on]
self.last_search = '' # The last search performed on this model
self.column_map = []
self.headers = {}
self.alignment_map = {}
self.buffer_size = buffer
self.metadata_backup = None
icon_height = (parent.fontMetrics() if hasattr(parent, 'fontMetrics') else QFontMetrics(QApplication.font())).lineSpacing()
self.bool_yes_icon = QIcon.ic('ok.png').pixmap(icon_height)
self.bool_no_icon = QIcon.ic('list_remove.png').pixmap(icon_height)
self.bool_blank_icon = QIcon.ic('blank.png').pixmap(icon_height)
# Qt auto-scales marked icon correctly, so we dont need to do it (and
# remember that the cover grid view needs a larger version of the icon,
# anyway)
self.marked_icon = QIcon.ic('marked.png')
self.bool_blank_icon_as_icon = QIcon(self.bool_blank_icon)
self.row_decoration = None
self.device_connected = False
self.ids_to_highlight = []
self.ids_to_highlight_set = set()
self.current_highlighted_idx = None
self.highlight_only = False
self.row_height = 0
self.marked_text_icons = {}
self.db_prefs = {'column_color_rules': (), 'column_icon_rules': ()}
self.read_config()
def marked_text_icon_for(self, label):
import random
ans = self.marked_text_icons.get(label)
if ans is not None:
return ans[1]
used_labels = self.db.data.all_marked_labels()
for qlabel in tuple(self.marked_text_icons):
if qlabel not in used_labels:
del self.marked_text_icons[qlabel]
used_colors = {x[0] for x in self.marked_text_icons.values()}
if QApplication.instance().is_dark_theme:
all_colors = {dark_link_color, 'lightgreen', 'red', 'maroon', 'cyan', 'pink'}
else:
all_colors = {'blue', 'green', 'red', 'maroon', 'cyan', 'pink'}
for c in all_colors - used_colors:
color = c
break
else:
color = random.choice(sorted(all_colors))
pm = render_pin(color)
ans = QIcon(pm)
self.marked_text_icons[label] = color, ans
return ans
@property
def default_image(self):
from calibre.gui2.ui import get_gui
gui = get_gui()
dpr = gui.devicePixelRatio() if gui else 0
return QApplication.instance().cached_qimage('default_cover.png', device_pixel_ratio=dpr)
def _clear_caches(self):
self.color_cache = defaultdict(dict)
self.icon_cache = defaultdict(dict)
self.icon_bitmap_cache = {}
self.cover_grid_emblem_cache = defaultdict(dict)
self.cover_grid_bitmap_cache = {}
self.color_row_fmt_cache = None
self.color_template_cache = {}
self.icon_template_cache = {}
self.cover_grid_template_cache = {}
def set_row_height(self, height):
self.row_height = height
def set_row_decoration(self, current_marked):
self.row_decoration = self.bool_blank_icon_as_icon if current_marked else None
def change_alignment(self, colname, alignment):
if colname in self.column_map and alignment in ('left', 'right', 'center'):
old = self.alignment_map.get(colname, 'left')
if old == alignment:
return
self.alignment_map.pop(colname, None)
if alignment != 'left':
self.alignment_map[colname] = alignment
col = self.column_map.index(colname)
for row in range(self.rowCount(QModelIndex())):
self.dataChanged.emit(self.index(row, col), self.index(row,
col))
def change_column_font(self, colname, font_type):
if colname in self.column_map and font_type in ('normal', 'bold', 'italic', 'bi'):
db = self.db.new_api
old = db.pref('styled_columns', {})
old.pop(colname, None)
self.styled_columns.pop(colname, None)
if font_type != 'normal':
self.styled_columns[colname] = getattr(self, f'{font_type}_font')
old[colname] = font_type
db.set_pref('styled_columns', old)
col = self.column_map.index(colname)
for row in range(self.rowCount(QModelIndex())):
self.dataChanged.emit(self.index(row, col), self.index(row,
col))
def is_custom_column(self, cc_label):
try:
return cc_label in self.custom_columns
except AttributeError:
return False
def read_config(self):
pass
def set_device_connected(self, is_connected):
self.device_connected = is_connected
def refresh_ondevice(self):
self.db.refresh_ondevice()
self.resort()
self.research()
def set_book_on_device_func(self, func):
self.book_on_device = func
def set_database(self, db):
self.ids_to_highlight = []
if db:
style_map = {'bold': self.bold_font, 'bi': self.bi_font, 'italic': self.italic_font}
self.styled_columns = {k: style_map.get(v, None) for k, v in iteritems(db.new_api.pref('styled_columns', {}))}
self.alignment_map = {}
self.ids_to_highlight_set = set()
self.current_highlighted_idx = None
self.db = db
self.update_db_prefs_cache()
self.custom_columns = self.db.field_metadata.custom_field_metadata()
self.column_map = list(self.orig_headers.keys()) + \
list(self.custom_columns)
def col_idx(name):
if name == 'ondevice':
return -1
if name not in self.db.field_metadata:
return 100000
return self.db.field_metadata[name]['rec_index']
self.column_map.sort(key=lambda x: col_idx(x))
for col in self.column_map:
if col in self.orig_headers:
self.headers[col] = self.orig_headers[col]
elif col in self.custom_columns:
self.headers[col] = self.custom_columns[col]['name']
self.build_data_convertors()
self.beginResetModel(), self.endResetModel()
self.database_changed.emit(db)
self.stop_metadata_backup()
self.start_metadata_backup()
def update_db_prefs_cache(self):
self.db_prefs = {
'column_icon_rules': tuple(self.db.new_api.pref('column_icon_rules', ())),
'column_color_rules': tuple(self.db.new_api.pref('column_color_rules', ())),
}
def start_metadata_backup(self):
from calibre.db.backup import MetadataBackup
self.metadata_backup = MetadataBackup(self.db)
self.metadata_backup.start()
def stop_metadata_backup(self):
if getattr(self, 'metadata_backup', None) is not None:
self.metadata_backup.stop()
# Would like to a join here, but the thread might be waiting to
# do something on the GUI thread. Deadlock.
def refresh_ids(self, ids, current_row=-1):
self._clear_caches()
rows = self.db.refresh_ids(ids)
if rows:
self.refresh_rows(rows, current_row=current_row)
def refresh_rows(self, rows, current_row=-1):
self._clear_caches()
cc = self.columnCount(QModelIndex()) - 1
for r in rows:
self.db.new_api.clear_extra_files_cache(self.db.id(r))
for first_row, last_row in group_numbers(rows):
self.dataChanged.emit(self.index(first_row, 0), self.index(last_row, cc))
if current_row >= 0 and first_row <= current_row <= last_row:
self.new_bookdisplay_data.emit(self.get_book_display_info(current_row))
def close(self):
if self.db is not None:
self.db.close()
self.db = None
self.beginResetModel(), self.endResetModel()
def add_books(self, paths, formats, metadata, add_duplicates=False,
return_ids=False):
ret = self.db.add_books(paths, formats, metadata,
add_duplicates=add_duplicates, return_ids=return_ids)
self.count_changed()
return ret
def add_news(self, path, arg):
ret = self.db.add_news(path, arg)
self.count_changed()
return ret
def add_catalog(self, path, title):
ret = self.db.add_catalog(path, title)
self.count_changed()
return ret
def count_changed(self, *args):
self._clear_caches()
self.count_changed_signal.emit(self.db.count())
def counts(self):
library_total = total = self.db.count()
if self.db.data.search_restriction_applied():
total = self.db.data.get_search_restriction_book_count()
return Counts(library_total, total, self.count())
def row_indices(self, index):
''' Return list indices of all cells in index.row()'''
return [self.index(index.row(), c) for c in range(self.columnCount(None))]
@property
def by_author(self):
return self.sorted_on[0] == 'authors'
def books_deleted(self):
self.count_changed()
self.beginResetModel(), self.endResetModel()
def delete_books(self, indices, permanent=False):
ids = list(map(self.id, indices))
self.delete_books_by_id(ids, permanent=permanent)
return ids
def delete_books_by_id(self, ids, permanent=False):
self.db.new_api.remove_books(ids, permanent=permanent)
self.ids_deleted(ids)
def ids_deleted(self, ids):
self.db.data.books_deleted(tuple(ids))
self.db.notify('delete', list(ids))
self.books_deleted()
def books_added(self, num):
if num > 0:
self.beginInsertRows(QModelIndex(), 0, num-1)
self.endInsertRows()
self.count_changed()
def set_highlight_only(self, toWhat):
self.highlight_only = toWhat
def get_current_highlighted_id(self):
if len(self.ids_to_highlight) == 0 or self.current_highlighted_idx is None:
return None
try:
return self.ids_to_highlight[self.current_highlighted_idx]
except:
return None
def get_next_highlighted_id(self, current_row, forward):
if len(self.ids_to_highlight) == 0 or self.current_highlighted_idx is None:
return None
if current_row is None:
row_ = self.current_highlighted_idx
else:
row_ = current_row
while True:
row_ += 1 if forward else -1
if row_ < 0:
row_ = self.count() - 1
elif row_ >= self.count():
row_ = 0
if self.id(row_) in self.ids_to_highlight_set:
break
try:
self.current_highlighted_idx = self.ids_to_highlight.index(self.id(row_))
except:
# This shouldn't happen ...
return None
return self.get_current_highlighted_id()
def highlight_ids(self, ids_to_highlight):
self.ids_to_highlight = ids_to_highlight
self.ids_to_highlight_set = set(self.ids_to_highlight)
if self.ids_to_highlight:
self.current_highlighted_idx = 0
else:
self.current_highlighted_idx = None
self.beginResetModel(), self.endResetModel()
def search(self, text, reset=True):
try:
if self.highlight_only:
self.db.search('')
if not text:
self.ids_to_highlight = []
self.ids_to_highlight_set = set()
self.current_highlighted_idx = None
else:
self.ids_to_highlight = self.db.search(text, return_matches=True)
self.ids_to_highlight_set = set(self.ids_to_highlight)
if self.ids_to_highlight:
self.current_highlighted_idx = 0
else:
self.current_highlighted_idx = None
else:
self.ids_to_highlight = []
self.ids_to_highlight_set = set()
self.current_highlighted_idx = None
self.db.search(text)
except ParseException as e:
self.searched.emit(e.msg)
return
self.last_search = text
if reset:
self.beginResetModel(), self.endResetModel()
if self.last_search:
# Do not issue search done for the null search. It is used to clear
# the search and count records for restrictions
self.searched.emit(True)
self.search_done.emit()
def sort(self, col, order=Qt.SortOrder.AscendingOrder, reset=True):
if not self.db:
return
if not isinstance(order, bool):
order = order == Qt.SortOrder.AscendingOrder
label = self.column_map[col]
self._sort(label, order, reset)
def sort_by_named_field(self, field, order, reset=True):
if field in list(self.db.field_metadata.keys()):
self._sort(field, order, reset)
def _sort(self, label, order, reset):
self.about_to_be_sorted.emit(self.db.id)
self.db.data.incremental_sort([(label, order)])
if reset:
self.beginResetModel(), self.endResetModel()
self.sorted_on = (label, order)
self.sort_history.insert(0, self.sorted_on)
self.sorting_done.emit(self.db.index)
def refresh(self, reset=True):
self.db.refresh(field=None)
self.resort(reset=reset)
def beginResetModel(self):
self._clear_caches()
QAbstractTableModel.beginResetModel(self)
def reset(self):
self.beginResetModel(), self.endResetModel()
def resort(self, reset=True):
if not self.db:
return
self.db.multisort(self.sort_history[:tweaks['maximum_resort_levels']])
if self.sort_history:
# There are ways to get here that don't set sorted_on, e.g., the
# sort_by action. I don't think sort_history can be empty, but it
# doesn't hurt to check
self.sorted_on = self.sort_history[0]
if reset:
self.beginResetModel(), self.endResetModel()
def research(self, reset=True):
self.search(self.last_search, reset=reset)
def columnCount(self, parent):
if parent and parent.isValid():
return 0
return len(self.column_map)
def rowCount(self, parent):
if parent and parent.isValid():
return 0
return len(self.db.data) if self.db else 0
def all_current_book_ids(self):
return self.db.data._map_filtered
def count(self):
return self.rowCount(None)
def get_book_display_info(self, idx):
mi = self.db.get_metadata(idx)
mi.size = mi._proxy_metadata.book_size
mi.cover_data = ('jpg', self.cover(idx))
mi.id = self.db.id(idx)
mi.field_metadata = self.db.field_metadata
mi.path = self.db.abspath(idx, create_dirs=False)
mi.format_files = self.db.new_api.format_files(self.db.data.index_to_id(idx))
mi.row_number = idx
try:
mi.marked = self.db.data.get_marked(idx, index_is_id=False)
except:
mi.marked = None
return mi
def current_changed(self, current, previous, emit_signal=True):
if current.isValid():
idx = current.row()
try:
self.db.id(idx)
except Exception:
# can happen if an out of band search is done causing the index
# to no longer be valid since this function is now called after
# an event loop tick.
return
try:
data = self.get_book_display_info(idx)
except Exception as e:
if sys.excepthook is simple_excepthook or sys.excepthook is sys.__excepthook__:
return # ignore failures during startup/shutdown
e.locking_violation_msg = _('Failed to read cover file for this book from the calibre library.')
raise
else:
if emit_signal:
self.new_bookdisplay_data.emit(data)
else:
return data
def get_book_info(self, index):
if isinstance(index, numbers.Integral):
index = self.index(index, 0)
# If index is not valid returns None
data = self.current_changed(index, None, False)
return data
def metadata_for(self, ids, get_cover=True):
'''
WARNING: if get_cover=True temp files are created for mi.cover.
Remember to delete them once you are done with them.
'''
ans = []
for id in ids:
mi = self.db.get_metadata(id, index_is_id=True, get_cover=get_cover)
ans.append(mi)
return ans
def get_metadata(self, rows, rows_are_ids=False, full_metadata=False):
metadata, _full_metadata = [], []
if not rows_are_ids:
rows = [self.db.id(row.row()) for row in rows]
for id in rows:
mi = self.db.get_metadata(id, index_is_id=True)
_full_metadata.append(mi)
au = authors_to_string(mi.authors if mi.authors else [_('Unknown')])
tags = mi.tags if mi.tags else []
if mi.series is not None:
tags.append(mi.series)
info = {
'title' : mi.title,
'authors' : au,
'author_sort' : mi.author_sort,
'cover' : self.db.cover(id, index_is_id=True),
'tags' : tags,
'comments': mi.comments,
}
if mi.series is not None:
info['tag order'] = {
mi.series:self.db.books_in_series_of(id, index_is_id=True)
}
metadata.append(info)
if full_metadata:
return metadata, _full_metadata
else:
return metadata
def get_preferred_formats_from_ids(
self, ids, formats,
set_metadata=False, specific_format=None, exclude_auto=False, mode='r+b',
use_plugboard=None, plugboard_formats=None, modified_metadata=None,
):
from calibre.ebooks.metadata.meta import set_metadata as _set_metadata
ans = []
need_auto = []
modified_metadata = [] if modified_metadata is None else modified_metadata
if specific_format is not None:
formats = [specific_format.lower()]
for id in ids:
format = None
fmts = self.db.formats(id, index_is_id=True)
if not fmts:
fmts = ''
db_formats = set(fmts.lower().split(','))
available_formats = {f.lower() for f in formats}
u = available_formats.intersection(db_formats)
for f in formats:
if f.lower() in u:
format = f
break
if format is not None:
pt = PersistentTemporaryFile(suffix='caltmpfmt.'+format)
self.db.copy_format_to(id, format, pt, index_is_id=True)
pt.seek(0)
newmi = None
if set_metadata:
try:
mi = self.db.get_metadata(id, get_cover=True,
index_is_id=True,
cover_as_data=True)
if use_plugboard and format.lower() in plugboard_formats:
plugboards = self.db.new_api.pref('plugboards', {})
cpb = find_plugboard(use_plugboard, format.lower(),
plugboards)
if cpb:
newmi = mi.deepcopy_metadata()
newmi.template_to_attribute(mi, cpb)
if newmi is not None:
_set_metadata(pt, newmi, format)
else:
_set_metadata(pt, mi, format)
except:
traceback.print_exc()
pt.close()
def to_uni(x):
if isbytestring(x):
x = x.decode(filesystem_encoding)
return x
ans.append(to_uni(os.path.abspath(pt.name)))
modified_metadata.append(newmi)
else:
need_auto.append(id)
if not exclude_auto:
ans.append(None)
modified_metadata.append(None)
return ans, need_auto
def get_preferred_formats(self, rows, formats, paths=False,
set_metadata=False, specific_format=None,
exclude_auto=False):
from calibre.ebooks.metadata.meta import set_metadata as _set_metadata
ans = []
need_auto = []
if specific_format is not None:
formats = [specific_format.lower()]
for row in (row.row() for row in rows):
format = None
fmts = self.db.formats(row)
if not fmts:
fmts = ''
db_formats = set(fmts.lower().split(','))
available_formats = {f.lower() for f in formats}
u = available_formats.intersection(db_formats)
for f in formats:
if f.lower() in u:
format = f
break
if format is not None:
pt = PersistentTemporaryFile(suffix='.'+format)
self.db.copy_format_to(id, format, pt, index_is_id=True)
pt.seek(0)
if set_metadata:
_set_metadata(pt, self.db.get_metadata(row, get_cover=True,
cover_as_data=True), format)
pt.close() if paths else pt.seek(0)
ans.append(pt)
else:
need_auto.append(row)
if not exclude_auto:
ans.append(None)
return ans, need_auto
def id(self, row):
return self.db.id(getattr(row, 'row', lambda:row)())
def authors(self, row_number):
return self.db.authors(row_number)
def title(self, row_number):
return self.db.title(row_number)
def rating(self, row_number):
ans = self.db.rating(row_number)
ans = ans/2 if ans else 0
return int(ans)
def cover(self, row_number):
data = None
try:
data = self.db.cover(row_number)
except IndexError: # Happens if database has not yet been refreshed
pass
except MemoryError:
raise ValueError(_('The cover for the book %s is too large, cannot load it.'
' Resize or delete it.') % self.db.title(row_number))
if not data:
return self.default_image
img = QImage()
img.loadFromData(data)
if img.isNull():
img = self.default_image
return img
def build_data_convertors(self):
rating_fields = {}
bool_fields = set()
def renderer(field, decorator=False):
idfunc = self.db.id
if field == 'id':
def func(idx):
return idfunc(idx)
return func
fffunc = self.db.new_api.fast_field_for
field_obj = self.db.new_api.fields[field]
m = field_obj.metadata.copy()
if 'display' not in m:
m['display'] = {}
dt = m['datatype']
if decorator == 'bool':
bool_fields.add(field)
bt = self.db.new_api.pref('bools_are_tristate')
bn = self.bool_no_icon
by = self.bool_yes_icon
if dt != 'bool':
def func(idx):
val = fffunc(field_obj, idfunc(idx))
if val is None:
return None
val = force_to_bool(val)
if val is None:
return None
return by if val else bn
else:
if m['display'].get('bools_show_icons', True):
def func(idx):
val = force_to_bool(fffunc(field_obj, idfunc(idx)))
if val is None:
return None if bt else bn
return by if val else bn
else:
def func(idx):
return None
elif field == 'size':
sz_mult = 1/(1024**2)
def func(idx):
val = fffunc(field_obj, idfunc(idx), default_value=0) or 0
if val == 0:
return None
ans = '%.1f' % (val * sz_mult)
return ('<0.1' if ans == '0.0' else ans)
elif field == 'languages':
def func(idx):
return (', '.join(calibre_langcode_to_name(x) for x in fffunc(field_obj, idfunc(idx))))
elif field == 'ondevice' and decorator:
by = self.bool_yes_icon
bb = self.bool_blank_icon
def func(idx):
return by if fffunc(field_obj, idfunc(idx)) else bb
elif dt in {'text', 'comments', 'composite', 'enumeration'}:
if m['is_multiple']:
jv = m['is_multiple']['list_to_ui']
do_sort = '&' not in jv
if field_obj.is_composite:
if do_sort:
sv = m['is_multiple']['cache_to_list']
def func(idx):
val = fffunc(field_obj, idfunc(idx), default_value='') or ''
return (jv.join(sorted((x.strip() for x in val.split(sv)), key=sort_key)))
else:
def func(idx):
return (fffunc(field_obj, idfunc(idx), default_value=''))
else:
if do_sort:
def func(idx):
return (jv.join(sorted(fffunc(field_obj, idfunc(idx), default_value=()), key=sort_key)))
else:
def func(idx):
return (jv.join(fffunc(field_obj, idfunc(idx), default_value=())))
else:
if dt in {'text', 'composite', 'enumeration'} and m['display'].get('use_decorations', False):
def func(idx):
text = fffunc(field_obj, idfunc(idx))
return (text) if force_to_bool(text) is None else None
else:
def func(idx):
return fffunc(field_obj, idfunc(idx), default_value='')
elif dt == 'datetime':
def func(idx):
val = fffunc(field_obj, idfunc(idx), default_value=UNDEFINED_DATE)
return None if is_date_undefined(val) else qt_from_dt(val)
elif dt == 'rating':
rating_fields[field] = m['display'].get('allow_half_stars', False)
def func(idx):
return int(fffunc(field_obj, idfunc(idx), default_value=0))
elif dt == 'series':
sidx_field = self.db.new_api.fields[field + '_index']
def func(idx):
book_id = idfunc(idx)
series = fffunc(field_obj, book_id, default_value=False)
if series:
return (f'{series} [{fmt_sidx(fffunc(sidx_field, book_id, default_value=1.0))}]')
return None
elif dt in {'int', 'float'}:
fmt = m['display'].get('number_format', None)
def func(idx):
val = fffunc(field_obj, idfunc(idx))
if val is None:
return None
if fmt:
try:
return (fmt.format(val))
except (TypeError, ValueError, AttributeError, IndexError, KeyError):
pass
return (val)
elif dt == 'bool':
if m['display'].get('bools_show_text', False):
def func(idx):
v = fffunc(field_obj, idfunc(idx))
return (None if v is None else (_('Yes') if v else _('No')))
else:
def func(idx):
return None
else:
def func(idx):
return None
return func
self.dc = {f:renderer(f) for f in self.orig_headers.keys()}
self.dc_decorator = {f:renderer(f, True) for f in ('ondevice',)}
for col in self.custom_columns:
self.dc[col] = renderer(col)
m = self.custom_columns[col]
dt = m['datatype']
mult = m['is_multiple']
if dt in {'text', 'composite', 'enumeration'} and not mult and m['display'].get('use_decorations', False):
self.dc_decorator[col] = renderer(col, 'bool')
elif dt == 'bool':
self.dc_decorator[col] = renderer(col, 'bool')
tc = self.dc.copy()
def stars_tooltip(func, allow_half=True):
def f(idx):
val = int(func(idx))
ans = str(val // 2)
if allow_half and val % 2:
ans += '.5'
return _('%s stars') % ans
return f
def bool_tooltip(key):
def f(idx):
return self.db.new_api.fast_field_for(self.db.new_api.fields[key],
self.db.id(idx))
return f
for f, allow_half in iteritems(rating_fields):
tc[f] = stars_tooltip(self.dc[f], allow_half)
for f in bool_fields:
tc[f] = bool_tooltip(f)
# build a index column to data converter map, to remove the string lookup in the data loop
self.column_to_dc_map = [self.dc[col] for col in self.column_map]
self.column_to_tc_map = [tc[col] for col in self.column_map]
self.column_to_dc_decorator_map = [self.dc_decorator.get(col, None) for col in self.column_map]
def data(self, index, role):
if self.db.new_api.is_doing_rebuild_or_vacuum:
return None
col = index.column()
# in obscure cases where custom columns are both edited and added, for a time
# the column map does not accurately represent the screen. In these cases,
# we will get asked to display columns we don't know about. Must test for this.
if col >= len(self.column_to_dc_map) or col < 0:
return None
if role == Qt.ItemDataRole.DisplayRole:
rules = self.db_prefs['column_icon_rules']
if rules:
key = self.column_map[col]
id_ = None
fmts = []
for kind, k, fmt in rules:
if k == key and kind in {'icon_only', 'icon_only_composed'}:
if id_ is None:
id_ = self.id(index)
self.column_icon.mi = None
fmts.append((kind, fmt))
if fmts:
cache_index = key + ':DisplayRole'
ccicon = self.column_icon(id_, fmts, cache_index, self.db,
self.icon_cache, self.icon_bitmap_cache,
self.icon_template_cache)
if ccicon is not None:
return None
self.icon_cache[id_][cache_index] = None
return self.column_to_dc_map[col](index.row())
elif role == Qt.ItemDataRole.ToolTipRole:
return self.column_to_tc_map[col](index.row())
elif role == Qt.ItemDataRole.EditRole:
return self.column_to_dc_map[col](index.row())
elif role == Qt.ItemDataRole.BackgroundRole:
if self.id(index) in self.ids_to_highlight_set:
return QColor('#027524') if QApplication.instance().is_dark_theme else QColor('#b4ecb4')
elif role == Qt.ItemDataRole.ForegroundRole:
key = self.column_map[col]
id_ = self.id(index)
self.column_color.mi = None
for k, fmt in self.db_prefs['column_color_rules']:
if k == key:
ccol = self.column_color(id_, key, fmt, self.db,
self.color_cache, self.color_template_cache)
if ccol is not None:
return ccol
if self.is_custom_column(key) and \
self.custom_columns[key]['datatype'] == 'enumeration':
cc = self.custom_columns[self.column_map[col]]['display']
colors = cc.get('enum_colors', [])
values = cc.get('enum_values', [])
txt = str(index.data(Qt.ItemDataRole.DisplayRole) or '')
if len(colors) > 0 and txt in values:
try:
color = QColor(colors[values.index(txt)])
if color.isValid():
self.column_color.mi = None
return (color)
except:
pass
if self.color_row_fmt_cache is None:
self.color_row_fmt_cache = tuple(fmt for key, fmt in
self.db_prefs['column_color_rules'] if key == color_row_key)
for fmt in self.color_row_fmt_cache:
ccol = self.column_color(id_, color_row_key, fmt, self.db,
self.color_cache, self.color_template_cache)
if ccol is not None:
return ccol
self.column_color.mi = None
return None
elif role == Qt.ItemDataRole.DecorationRole:
default_icon = None
if self.column_to_dc_decorator_map[col] is not None:
default_icon = self.column_to_dc_decorator_map[index.column()](index.row())
rules = self.db_prefs['column_icon_rules']
if rules:
key = self.column_map[col]
id_ = None
need_icon_with_text = False
fmts = []
for kind, k, fmt in rules:
if k == key and kind.startswith('icon'):
if id_ is None:
id_ = self.id(index)
self.column_icon.mi = None
fmts.append((kind, fmt))
if kind in ('icon', 'icon_composed'):
need_icon_with_text = True
if fmts:
cache_index = key + ':DecorationRole'
ccicon = self.column_icon(id_, fmts, cache_index, self.db,
self.icon_cache, self.icon_bitmap_cache,
self.icon_template_cache)
if ccicon is not None:
return ccicon
if need_icon_with_text and default_icon is None:
self.icon_cache[id_][cache_index] = self.bool_blank_icon
return self.bool_blank_icon
self.icon_cache[id_][cache_index] = None
return default_icon
elif role == Qt.ItemDataRole.TextAlignmentRole:
cname = self.column_map[index.column()]
ans = Qt.AlignmentFlag.AlignVCenter | ALIGNMENT_MAP[self.alignment_map.get(cname,
'left')]
return int(ans) # https://bugreports.qt.io/browse/PYSIDE-1974
elif role == Qt.ItemDataRole.FontRole and self.styled_columns:
cname = self.column_map[index.column()]
return self.styled_columns.get(cname)
# elif role == Qt.ItemDataRole.ToolTipRole and index.isValid():
# if self.column_map[index.column()] in self.editable_cols:
# return (_("Double click to <b>edit</b> me<br><br>"))
return None
def headerData(self, section, orientation, role):
if orientation == Qt.Orientation.Horizontal:
if section >= len(self.column_map): # same problem as in data, the column_map can be wrong
return None
if role == Qt.ItemDataRole.ToolTipRole:
ht = self.column_map[section]
title = self.headers[ht]
fm = self.db.field_metadata[self.column_map[section]]
if ht == 'timestamp': # change help text because users know this field as 'date'
ht = 'date'
if fm['is_category']:
is_cat = '<br><br>' + prepare_string_for_xml(_('Click in this column and press Q to Quickview books with the same "%s"') % ht)
else:
is_cat = ''
cust_desc = ''
if fm['is_custom']:
cust_desc = fm['display'].get('description', '')
if cust_desc:
cust_desc = ('<br><b>{}</b>'.format(_('Description:')) +
'<span style="white-space:pre-wrap"> ' +
prepare_string_for_xml(cust_desc) + '</span>')
return '<b>{}</b>: {}'.format(
prepare_string_for_xml(title),
_('The lookup/search name is <i>{0}</i>').format(ht) + cust_desc + is_cat
)
if role == Qt.ItemDataRole.DisplayRole:
return (self.headers[self.column_map[section]])
return None
if role == Qt.ItemDataRole.ToolTipRole and orientation == Qt.Orientation.Vertical:
col = self.db.field_metadata['marked']['rec_index']
marked = self.db.data[section][col]
if marked is not None:
s = _('Marked with text "{0}"').format(marked) if marked != 'true' else _('Marked without text')
else:
s = ''
if DEBUG:
col = self.db.field_metadata['uuid']['rec_index']
s += ('\n' if s else '') + _('This book\'s UUID is "{0}"').format(self.db.data[section][col])
return s
if role == Qt.ItemDataRole.DisplayRole: # orientation is vertical
return (section+1)
if role == Qt.ItemDataRole.DecorationRole:
try:
m = self.db.data.get_marked(self.db.data.index_to_id(section))
if m:
i = self.marked_icon if m == 'true' else self.marked_text_icon_for(m)
else:
i = self.row_decoration
return i
except (ValueError, IndexError):
pass
return None
def flags(self, index):
flags = QAbstractTableModel.flags(self, index)
if index.isValid():
colhead = self.column_map[index.column()]
if colhead in self.editable_cols:
flags |= Qt.ItemFlag.ItemIsEditable
elif self.is_custom_column(colhead):
if self.custom_columns[colhead]['is_editable']:
flags |= Qt.ItemFlag.ItemIsEditable
return flags
def set_custom_column_data(self, row, colhead, value):
cc = self.custom_columns[colhead]
typ = cc['datatype']
label=self.db.field_metadata.key_to_label(colhead)
s_index = None
if typ in ('text', 'comments'):
val = str(value or '').strip()
val = val if val else None
elif typ == 'enumeration':
val = str(value or '').strip()
if not val:
val = None
elif typ == 'bool':
val = value if value is None else bool(value)
elif typ == 'rating':
val = max(0, min(int(value or 0), 10))
elif typ in ('int', 'float'):
if value == 0:
val = '0'
else:
val = str(value or '').strip()
if not val:
val = None
elif typ == 'datetime':
val = value
if val is None:
val = None
else:
if not val.isValid():
return False
val = qt_to_dt(val, as_utc=False)
elif typ == 'series':
val = str(value or '').strip()
if val:
pat = re.compile(r'\[([.0-9]+)\]')
match = pat.search(val)
if match is not None:
s_index = float(match.group(1))
val = pat.sub('', val).strip()
elif val:
# it is OK to leave s_index == None when using 'no_change'
if tweaks['series_index_auto_increment'] != 'const' and \
tweaks['series_index_auto_increment'] != 'no_change':
s_index = self.db.get_next_cc_series_num_for(val,
label=label, num=None)
elif typ == 'composite':
tmpl = str(value or '').strip()
disp = cc['display']
disp['composite_template'] = tmpl
self.db.set_custom_column_metadata(cc['colnum'], display=disp,
update_last_modified=True)
self.refresh(reset=False)
self.research(reset=True)
return True
id = self.db.id(row)
books_to_refresh = {id}
books_to_refresh |= self.db.set_custom(id, val, extra=s_index,
label=label, num=None, append=False, notify=True,
allow_case_change=True)
self.refresh_ids(list(books_to_refresh), current_row=row)
return True
def setData(self, index, value, role):
from calibre.gui2.ui import get_gui
if get_gui().shutting_down:
return False
if role == Qt.ItemDataRole.EditRole:
from calibre.gui2.ui import get_gui
try:
return self._set_data(index, value)
except OSError as err:
import traceback
traceback.print_exc()
det_msg = traceback.format_exc()
gui = get_gui()
if gui.show_possible_sharing_violation(err, det_msg):
return False
error_dialog(get_gui(), _('Failed to set data'),
_('Could not set data, click "Show details" to see why.'),
det_msg=traceback.format_exc(), show=True)
except:
import traceback
traceback.print_exc()
error_dialog(get_gui(), _('Failed to set data'),
_('Could not set data, click "Show details" to see why.'),
det_msg=traceback.format_exc(), show=True)
return False
def _set_data(self, index, value):
row, col = index.row(), index.column()
column = self.column_map[col]
if self.is_custom_column(column):
if not self.set_custom_column_data(row, column, value):
return False
else:
if column not in self.editable_cols:
return False
val = (int(value) if column == 'rating' else
value if column in ('timestamp', 'pubdate')
else re.sub(r'\s', ' ', str(value or '').strip()))
id = self.db.id(row)
books_to_refresh = {id}
if column == 'rating':
val = max(0, min(int(val or 0), 10))
self.db.set_rating(id, val)
elif column == 'series':
val = val.strip()
if not val:
books_to_refresh |= self.db.set_series(id, val,
allow_case_change=True)
self.db.set_series_index(id, 1.0)
else:
pat = re.compile(r'\[([.0-9]+)\]')
match = pat.search(val)
if match is not None:
self.db.set_series_index(id, float(match.group(1)))
val = pat.sub('', val).strip()
elif val:
if tweaks['series_index_auto_increment'] != 'const' and \
tweaks['series_index_auto_increment'] != 'no_change':
ni = self.db.get_next_series_num_for(val)
if ni != 1:
self.db.set_series_index(id, ni)
if val:
books_to_refresh |= self.db.set_series(id, val,
allow_case_change=True)
elif column == 'timestamp':
if val is None or not val.isValid():
return False
self.db.set_timestamp(id, qt_to_dt(val, as_utc=False))
elif column == 'pubdate':
if val is None or not val.isValid():
return False
self.db.set_pubdate(id, qt_to_dt(val, as_utc=False))
elif column == 'languages':
val = val.split(',')
self.db.set_languages(id, val)
else:
if column == 'authors' and val:
val = authors_to_string(string_to_authors(val))
books_to_refresh |= self.db.set(row, column, val,
allow_case_change=True)
self.refresh_ids(list(books_to_refresh), row)
self.dataChanged.emit(index, index)
return True
# }}}
class OnDeviceSearch(SearchQueryParser): # {{{
USABLE_LOCATIONS = [
'all',
'author',
'authors',
'collections',
'format',
'formats',
'title',
'inlibrary',
'tags',
'search'
]
def __init__(self, model):
SearchQueryParser.__init__(self, locations=self.USABLE_LOCATIONS)
self.model = model
def universal_set(self):
return set(range(0, len(self.model.db)))
def get_matches(self, location, query):
location = location.lower().strip()
if location == 'authors':
location = 'author'
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:]
if matchkind != REGEXP_MATCH: # leave case in regexps because it can be significant e.g. \S \W \D
query = query.lower()
if location not in self.USABLE_LOCATIONS:
return set()
matches = set()
all_locs = set(self.USABLE_LOCATIONS) - {'all', 'tags', 'search'}
locations = all_locs if location == 'all' else [location]
q = {
'title' : lambda x : getattr(x, 'title').lower(),
'author': lambda x: ' & '.join(getattr(x, 'authors')).lower(),
'collections':lambda x: ','.join(getattr(x, 'device_collections')).lower(),
'format':lambda x: os.path.splitext(x.path)[1].lower(),
'inlibrary':lambda x : getattr(x, 'in_library'),
'tags':lambda x : getattr(x, 'tags', [])
}
for x in ('author', 'format'):
q[x+'s'] = q[x]
upf = prefs['use_primary_find_in_search']
for index, row in enumerate(self.model.db):
for locvalue in locations:
accessor = q[locvalue]
if query == 'true':
if accessor(row):
matches.add(index)
continue
if query == 'false':
if not accessor(row):
matches.add(index)
continue
if locvalue == 'inlibrary':
continue # this is bool, so can't match below
try:
# Can't separate authors because comma is used for name sep and author sep
# Exact match might not get what you want. For that reason, turn author
# exactmatch searches into contains searches.
if locvalue == 'author' and matchkind == EQUALS_MATCH:
m = CONTAINS_MATCH
else:
m = matchkind
vals = accessor(row)
if vals is None:
vals = ''
if isinstance(vals, string_or_bytes):
vals = vals.split(',') if locvalue == 'collections' else [vals]
if _match(query, vals, m, use_primary_find_in_search=upf):
matches.add(index)
break
except ValueError: # Unicode errors
traceback.print_exc()
return matches
# }}}
class DeviceDBSortKeyGen: # {{{
def __init__(self, attr, keyfunc, db):
self.attr = attr
self.db = db
self.keyfunc = keyfunc
def __call__(self, x):
try:
ans = self.keyfunc(getattr(self.db[x], self.attr))
except Exception:
ans = ''
return ans
# }}}
class DeviceBooksModel(BooksModel): # {{{
booklist_dirtied = pyqtSignal()
upload_collections = pyqtSignal(object)
resize_rows = pyqtSignal()
def __init__(self, parent):
BooksModel.__init__(self, parent)
self.db = []
self.map = []
self.sorted_map = []
self.sorted_on = DEFAULT_SORT
self.sort_history = [self.sorted_on]
self.unknown = _('Unknown')
self.column_map = ['inlibrary', 'title', 'authors', 'timestamp', 'size',
'collections']
self.headers = {
'inlibrary' : _('In Library'),
'title' : _('Title'),
'authors' : _('Author(s)'),
'timestamp' : _('Date'),
'size' : _('Size'),
'collections' : _('Collections')
}
self.marked_for_deletion = {}
self.search_engine = OnDeviceSearch(self)
self.editable = ['title', 'authors', 'collections']
self.book_in_library = None
self.sync_icon = QIcon.ic('sync.png')
def counts(self):
return Counts(len(self.db), len(self.db), len(self.map))
def count_changed(self, *args):
self.count_changed_signal.emit(len(self.db))
def mark_for_deletion(self, job, rows, rows_are_ids=False):
db_indices = rows if rows_are_ids else self.indices(rows)
db_items = [self.db[i] for i in db_indices if -1 < i < len(self.db)]
self.marked_for_deletion[job] = db_items
if rows_are_ids:
self.beginResetModel(), self.endResetModel()
else:
for row in rows:
indices = self.row_indices(row)
self.dataChanged.emit(indices[0], indices[-1])
def find_item_in_db(self, item):
idx = None
try:
idx = self.db.index(item)
except:
path = getattr(item, 'path', None)
if path:
for i, x in enumerate(self.db):
if getattr(x, 'path', None) == path:
idx = i
break
return idx
def deletion_done(self, job, succeeded=True):
db_items = self.marked_for_deletion.pop(job, [])
rows = []
for item in db_items:
idx = self.find_item_in_db(item)
if idx is not None:
try:
rows.append(self.map.index(idx))
except ValueError:
pass
for row in rows:
if not succeeded:
indices = self.row_indices(self.index(row, 0))
self.dataChanged.emit(indices[0], indices[-1])
self.count_changed()
def paths_deleted(self, paths):
self.map = list(range(0, len(self.db)))
self.resort(False)
self.research(True)
self.count_changed()
def is_row_marked_for_deletion(self, row):
try:
item = self.db[self.map[row]]
except IndexError:
return False
path = getattr(item, 'path', None)
for items in itervalues(self.marked_for_deletion):
for x in items:
if x is item or (path and path == getattr(x, 'path', None)):
return True
return False
def clear_ondevice(self, db_ids, to_what=None):
for data in self.db:
if data is None:
continue
app_id = getattr(data, 'application_id', None)
if app_id is not None and app_id in db_ids:
data.in_library = to_what
self.beginResetModel(), self.endResetModel()
def flags(self, index):
if self.is_row_marked_for_deletion(index.row()):
return Qt.ItemFlag.NoItemFlags
flags = QAbstractTableModel.flags(self, index)
if index.isValid():
cname = self.column_map[index.column()]
if cname in self.editable and \
(cname != 'collections' or
(callable(getattr(self.db, 'supports_collections', None)) and
self.db.supports_collections() and
device_prefs['manage_device_metadata']=='manual')):
flags |= Qt.ItemFlag.ItemIsEditable
return flags
def search(self, text, reset=True):
# This should not be here, but since the DeviceBooksModel does not
# implement count_changed and I am too lazy to fix that, this kludge
# will have to do
self.resize_rows.emit()
if not text or not text.strip():
self.map = list(range(len(self.db)))
else:
try:
matches = self.search_engine.parse(text)
except ParseException:
self.searched.emit(False)
return
self.map = []
for i in range(len(self.db)):
if i in matches:
self.map.append(i)
self.resort(reset=False)
if reset:
self.beginResetModel(), self.endResetModel()
self.last_search = text
if self.last_search:
self.searched.emit(True)
self.count_changed()
def research(self, reset=True):
self.search(self.last_search, reset)
def sort(self, col, order, reset=True):
if not isinstance(order, Qt.SortOrder):
order = Qt.SortOrder.AscendingOrder if order else Qt.SortOrder.DescendingOrder
descending = order != Qt.SortOrder.AscendingOrder
cname = self.column_map[col]
def author_key(x):
try:
ax = self.db[x].author_sort
if not ax:
raise Exception('')
except:
try:
ax = authors_to_string(self.db[x].authors)
except:
ax = ''
try:
return sort_key(ax)
except:
return ax
keygen = {
'title': ('title_sorter', lambda x: sort_key(x) if x else b''),
'authors' : author_key,
'size' : ('size', int),
'timestamp': ('datetime', functools.partial(dt_factory, assume_utc=True)),
'collections': ('device_collections', lambda x:sorted(x,
key=sort_key)),
'inlibrary': ('in_library', lambda x: x or ''),
}[cname]
keygen = keygen if callable(keygen) else DeviceDBSortKeyGen(
keygen[0], keygen[1], self.db)
self.map.sort(key=keygen, reverse=descending)
if len(self.map) == len(self.db):
self.sorted_map = list(self.map)
else:
self.sorted_map = list(range(len(self.db)))
self.sorted_map.sort(key=keygen, reverse=descending)
self.sorted_on = (self.column_map[col], not descending)
self.sort_history.insert(0, self.sorted_on)
if hasattr(keygen, 'db'):
keygen.db = None
if reset:
self.beginResetModel(), self.endResetModel()
def resort(self, reset=True):
if self.sorted_on:
self.sort(self.column_map.index(self.sorted_on[0]),
self.sorted_on[1], reset=False)
if reset:
self.beginResetModel(), self.endResetModel()
def columnCount(self, parent):
if parent and parent.isValid():
return 0
return len(self.column_map)
def rowCount(self, parent):
if parent and parent.isValid():
return 0
return len(self.map)
def set_database(self, db):
self.custom_columns = {}
self.db = db
self.map = list(range(0, len(db)))
self.research(reset=False)
self.resort()
self.count_changed()
def cover(self, row):
item = self.db[self.map[row]]
cdata = item.thumbnail
img = QImage()
if cdata is not None:
if hasattr(cdata, 'image_path'):
img.load(cdata.image_path)
elif cdata:
if isinstance(cdata, (tuple, list)):
img.loadFromData(cdata[-1])
else:
img.loadFromData(cdata)
if img.isNull():
img = self.default_image
return img
def get_book_display_info(self, idx):
from calibre.ebooks.metadata.book.base import Metadata
item = self.db[self.map[idx]]
cover = self.cover(idx)
if cover is self.default_image:
cover = None
title = item.title
if not title:
title = _('Unknown')
au = item.authors
if not au:
au = [_('Unknown')]
mi = Metadata(title, au)
mi.cover_data = ('jpg', cover)
fmt = _('Unknown')
ext = os.path.splitext(item.path)[1]
if ext:
fmt = ext[1:].lower()
mi.formats = [fmt]
mi.path = (item.path if item.path else None)
dt = dt_factory(item.datetime, assume_utc=True)
mi.timestamp = dt
mi.device_collections = list(item.device_collections)
mi.tags = list(getattr(item, 'tags', []))
mi.comments = getattr(item, 'comments', None)
series = getattr(item, 'series', None)
if series:
sidx = getattr(item, 'series_index', 0)
mi.series = series
mi.series_index = sidx
return mi
def current_changed(self, current, previous, emit_signal=True):
if current.isValid():
idx = current.row()
try:
self.db[self.map[idx]]
except Exception:
return # can happen if the device is ejected
try:
data = self.get_book_display_info(idx)
except Exception:
import traceback
error_dialog(None, _('Unhandled error'), _(
'Failed to read book data from calibre library. Click "Show details" for more information'), det_msg=traceback.format_exc(), show=True)
else:
if emit_signal:
self.new_bookdisplay_data.emit(data)
else:
return data
def paths(self, rows):
return [self.db[self.map[r.row()]].path for r in rows]
def id(self, row):
row = getattr(row, 'row', lambda:row)()
try:
return self.db[self.map[row]].path
except Exception:
return None
def paths_for_db_ids(self, db_ids, as_map=False):
res = defaultdict(list) if as_map else []
for r,b in enumerate(self.db):
if b.application_id in db_ids:
if as_map:
res[b.application_id].append(b)
else:
res.append((r,b))
return res
def get_collections_with_ids(self):
collections = set()
for book in self.db:
if book.device_collections is not None:
collections.update(set(book.device_collections))
self.collections = []
result = []
for i,collection in enumerate(collections):
result.append((i, collection))
self.collections.append(collection)
return result
def rename_collection(self, old_id, new_name):
old_name = self.collections[old_id]
for book in self.db:
if book.device_collections is None:
continue
if old_name in book.device_collections:
book.device_collections.remove(old_name)
if new_name not in book.device_collections:
book.device_collections.append(new_name)
def delete_collection_using_id(self, old_id):
old_name = self.collections[old_id]
for book in self.db:
if book.device_collections is None:
continue
if old_name in book.device_collections:
book.device_collections.remove(old_name)
def indices(self, rows):
'''
Return indices into underlying database from rows
'''
return [self.map[r.row()] for r in rows]
def data(self, index, role):
row, col = index.row(), index.column()
cname = self.column_map[col]
if role == Qt.ItemDataRole.DisplayRole or role == Qt.ItemDataRole.EditRole:
if cname == 'title':
text = self.db[self.map[row]].title
if not text:
text = self.unknown
return (text)
elif cname == 'authors':
au = self.db[self.map[row]].authors
if not au:
au = [_('Unknown')]
return (authors_to_string(au))
elif cname == 'size':
size = self.db[self.map[row]].size
if not isinstance(size, numbers.Number):
size = 0
return (human_readable(size))
elif cname == 'timestamp':
dt = self.db[self.map[row]].datetime
try:
dt = dt_factory(dt, assume_utc=True, as_utc=False)
except OverflowError:
dt = dt_factory(time.gmtime(), assume_utc=True,
as_utc=False)
return (strftime(TIME_FMT, dt.timetuple()))
elif cname == 'collections':
tags = self.db[self.map[row]].device_collections
if tags:
tags.sort(key=sort_key)
return (', '.join(tags))
elif DEBUG and cname == 'inlibrary':
return (self.db[self.map[row]].in_library)
elif role == Qt.ItemDataRole.ToolTipRole and index.isValid():
if col == 0 and hasattr(self.db[self.map[row]], 'in_library_waiting'):
return (_('Waiting for metadata to be updated'))
if self.is_row_marked_for_deletion(row):
return (_('Marked for deletion'))
if cname in ['title', 'authors'] or (
cname == 'collections' and (
callable(getattr(self.db, 'supports_collections', None)) and self.db.supports_collections())
):
return (_("Double click to <b>edit</b> me<br><br>"))
elif role == Qt.ItemDataRole.DecorationRole and cname == 'inlibrary':
if hasattr(self.db[self.map[row]], 'in_library_waiting'):
return (self.sync_icon)
elif self.db[self.map[row]].in_library:
return (self.bool_yes_icon)
elif self.db[self.map[row]].in_library is not None:
return (self.bool_no_icon)
elif role == Qt.ItemDataRole.TextAlignmentRole:
cname = self.column_map[index.column()]
ans = Qt.AlignmentFlag.AlignVCenter | ALIGNMENT_MAP[self.alignment_map.get(cname,
'left')]
return int(ans) # https://bugreports.qt.io/browse/PYSIDE-1974
return None
def headerData(self, section, orientation, role):
if role == Qt.ItemDataRole.ToolTipRole and orientation == Qt.Orientation.Horizontal:
cname = self.column_map[section]
text = self.headers[cname]
return '<b>{}</b>: {}'.format(
prepare_string_for_xml(text),
prepare_string_for_xml(_('The lookup/search name is')) + f' <i>{self.column_map[section]}</i>')
if DEBUG and role == Qt.ItemDataRole.ToolTipRole and orientation == Qt.Orientation.Vertical:
return (_('This book\'s UUID is "{0}"').format(self.db[self.map[section]].uuid))
if role != Qt.ItemDataRole.DisplayRole:
return None
if orientation == Qt.Orientation.Horizontal:
cname = self.column_map[section]
text = self.headers[cname]
return (text)
else:
return (section+1)
def setData(self, index, value, role):
from calibre.gui2.ui import get_gui
if get_gui().shutting_down:
return False
done = False
if role == Qt.ItemDataRole.EditRole:
row, col = index.row(), index.column()
cname = self.column_map[col]
if cname in ('size', 'timestamp', 'inlibrary'):
return False
val = str(value or '').strip()
idx = self.map[row]
if cname == 'collections':
tags = [i.strip() for i in val.split(',')]
tags = [t for t in tags if t]
self.db[idx].device_collections = tags
self.dataChanged.emit(index, index)
self.upload_collections.emit(self.db)
return True
if cname == 'title' :
self.db[idx].title = val
elif cname == 'authors':
self.db[idx].authors = string_to_authors(val)
self.dataChanged.emit(index, index)
self.booklist_dirtied.emit()
done = True
return done
def set_editable(self, editable):
# Cannot edit if metadata is sent on connect. Reason: changes will
# revert to what is in the library on next connect.
if isinstance(editable, list):
self.editable = editable
elif editable:
self.editable = ['title', 'authors', 'collections']
else:
self.editable = []
if device_prefs['manage_device_metadata']=='on_connect':
self.editable = []
# }}}
| 77,328 | Python | .py | 1,729 | 30.847311 | 155 | 0.526839 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,895 | delegates.py | kovidgoyal_calibre/src/calibre/gui2/library/delegates.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os
import sys
from datetime import datetime
from qt.core import (
QAbstractTextDocumentLayout,
QApplication,
QComboBox,
QDate,
QDateTime,
QDateTimeEdit,
QDialog,
QDoubleSpinBox,
QEvent,
QFont,
QFontInfo,
QIcon,
QKeySequence,
QLineEdit,
QLocale,
QMenu,
QPalette,
QSize,
QSpinBox,
QStyle,
QStyledItemDelegate,
QStyleOptionComboBox,
QStyleOptionSpinBox,
QStyleOptionViewItem,
Qt,
QTextDocument,
QUrl,
)
from calibre.constants import iswindows
from calibre.ebooks.metadata import rating_to_stars, title_sort
from calibre.gui2 import UNDEFINED_QDATETIME, gprefs, rating_font
from calibre.gui2.complete2 import EditWithComplete
from calibre.gui2.dialogs.comments_dialog import CommentsDialog, PlainTextDialog
from calibre.gui2.dialogs.tag_editor import TagEditor
from calibre.gui2.languages import LanguagesEdit
from calibre.gui2.markdown_editor import MarkdownEditDialog
from calibre.gui2.widgets import EnLineEdit
from calibre.gui2.widgets2 import DateTimeEdit as DateTimeEditBase
from calibre.gui2.widgets2 import RatingEditor, populate_standard_spinbox_context_menu
from calibre.library.comments import markdown
from calibre.utils.config import tweaks
from calibre.utils.date import format_date, internal_iso_format_string, is_date_undefined, now, qt_from_dt, qt_to_dt
from calibre.utils.icu import sort_key
class UpdateEditorGeometry:
def updateEditorGeometry(self, editor, option, index):
if editor is None:
return
fm = editor.fontMetrics()
# get the original size of the edit widget
opt = QStyleOptionViewItem(option)
self.initStyleOption(opt, index)
opt.showDecorationSelected = True
opt.decorationSize = QSize(0, 0) # We want the editor to cover the decoration
style = QApplication.style()
initial_geometry = style.subElementRect(QStyle.SubElement.SE_ItemViewItemText, opt, None)
orig_width = initial_geometry.width()
# Compute the required width: the width that can show all of the current value
if hasattr(self, 'get_required_width'):
new_width = self.get_required_width(editor, style, fm)
else:
# The line edit box seems to extend by the space consumed by an 'M'.
# So add that to the text
text = self.displayText(index.data(Qt.ItemDataRole.DisplayRole), QLocale()) + 'M'
srect = style.itemTextRect(fm, editor.geometry(), Qt.AlignmentFlag.AlignLeft, False, text)
new_width = srect.width()
# Now get the size of the combo/spinner arrows and add them to the needed width
if isinstance(editor, (QComboBox, QDateTimeEdit)):
r = style.subControlRect(QStyle.ComplexControl.CC_ComboBox, QStyleOptionComboBox(),
QStyle.SubControl.SC_ComboBoxArrow, editor)
new_width += r.width()
elif isinstance(editor, (QSpinBox, QDoubleSpinBox)):
r = style.subControlRect(QStyle.ComplexControl.CC_SpinBox, QStyleOptionSpinBox(),
QStyle.SubControl.SC_SpinBoxUp, editor)
new_width += r.width()
# Compute the maximum we can show if we consume the entire viewport
pin_view = self.table_widget.pin_view
is_pin_view, p = False, editor.parent()
while p is not None:
if p is pin_view:
is_pin_view = True
break
p = p.parent()
max_width = (pin_view if is_pin_view else self.table_widget).viewport().rect().width()
# What we have to display might not fit. If so, adjust down
new_width = new_width if new_width < max_width else max_width
# See if we need to change the editor's geometry
if new_width <= orig_width:
delta_x = 0
delta_width = 0
else:
# Compute the space available from the left edge of the widget to
# the right edge of the displayed table (the viewport) and the left
# edge of the widget to the left edge of the viewport. These are
# used to position the edit box
space_left = initial_geometry.x()
space_right = max_width - space_left
if editor.layoutDirection() == Qt.LayoutDirection.RightToLeft:
# If language is RtL, align to the cell's right edge if possible
cw = initial_geometry.width()
consume_on_left = min(space_left, new_width - cw)
consume_on_right = max(0, new_width - (consume_on_left + cw))
delta_x = -consume_on_left
delta_width = consume_on_right
else:
# If language is LtR, align to the left if possible
consume_on_right = min(space_right, new_width)
consume_on_left = max(0, new_width - consume_on_right)
delta_x = -consume_on_left
delta_width = consume_on_right - initial_geometry.width()
initial_geometry.adjust(delta_x, 0, delta_width, 0)
editor.setGeometry(initial_geometry)
class EditableTextDelegate:
def setEditorData(self, editor, index):
n = editor.metaObject().userProperty().name()
editor.setProperty(n, get_val_for_textlike_columns(index))
class DateTimeEdit(DateTimeEditBase): # {{{
def __init__(self, parent, format_):
DateTimeEditBase.__init__(self, parent)
self.setFrame(False)
if format_ == 'iso':
format_ = internal_iso_format_string()
self.setDisplayFormat(format_)
# }}}
# Number Editor {{{
def make_clearing_spinbox(spinbox):
class SpinBox(spinbox):
def contextMenuEvent(self, ev):
m = QMenu(self)
m.addAction(_('Set to undefined') + '\t' + QKeySequence(Qt.Key.Key_Space).toString(QKeySequence.SequenceFormat.NativeText),
self.clear_to_undefined)
m.addSeparator()
populate_standard_spinbox_context_menu(self, m)
m.popup(ev.globalPos())
def clear_to_undefined(self):
self.setValue(self.minimum())
def keyPressEvent(self, ev):
if ev.key() == Qt.Key.Key_Space:
self.clear_to_undefined()
else:
if self.value() == self.minimum():
self.clear()
return spinbox.keyPressEvent(self, ev)
return SpinBox
ClearingSpinBox = make_clearing_spinbox(QSpinBox)
ClearingDoubleSpinBox = make_clearing_spinbox(QDoubleSpinBox)
# }}}
# setter for text-like delegates. Return '' if CTRL is pushed {{{
def check_key_modifier(which_modifier):
v = QApplication.keyboardModifiers() & (Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.ShiftModifier)
return v == which_modifier
def get_val_for_textlike_columns(index_):
if check_key_modifier(Qt.KeyboardModifier.ControlModifier):
ct = ''
else:
ct = index_.data(Qt.ItemDataRole.DisplayRole) or ''
return str(ct)
# }}}
class RatingDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
def __init__(self, *args, **kwargs):
QStyledItemDelegate.__init__(self, *args)
self.is_half_star = kwargs.get('is_half_star', False)
self.table_widget = args[0]
self.rf = QFont(rating_font())
self.em = Qt.TextElideMode.ElideMiddle
delta = 0
if iswindows and sys.getwindowsversion().major >= 6:
delta = 2
self.rf.setPointSize(QFontInfo(QApplication.font()).pointSize()+delta)
def get_required_width(self, editor, style, fm):
return editor.sizeHint().width()
def displayText(self, value, locale):
return rating_to_stars(value, self.is_half_star)
def createEditor(self, parent, option, index):
return RatingEditor(parent, is_half_star=self.is_half_star)
def setEditorData(self, editor, index):
if check_key_modifier(Qt.KeyboardModifier.ControlModifier):
val = 0
else:
val = index.data(Qt.ItemDataRole.EditRole)
editor.rating_value = val
def setModelData(self, editor, model, index):
val = editor.rating_value
model.setData(index, val, Qt.ItemDataRole.EditRole)
def sizeHint(self, option, index):
option.font = self.rf
option.textElideMode = self.em
return QStyledItemDelegate.sizeHint(self, option, index)
def paint(self, painter, option, index):
option.font = self.rf
option.textElideMode = self.em
return QStyledItemDelegate.paint(self, painter, option, index)
# }}}
class DateDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
def __init__(self, parent, tweak_name='gui_timestamp_display_format',
default_format='dd MMM yyyy'):
QStyledItemDelegate.__init__(self, parent)
self.table_widget = parent
self.tweak_name = tweak_name
self.format = tweaks[self.tweak_name]
if self.format is None:
self.format = default_format
def displayText(self, val, locale):
d = qt_to_dt(val)
if is_date_undefined(d):
return ''
return format_date(d, self.format)
def createEditor(self, parent, option, index):
return DateTimeEdit(parent, self.format)
def setEditorData(self, editor, index):
if check_key_modifier(Qt.KeyboardModifier.ControlModifier):
val = UNDEFINED_QDATETIME
elif check_key_modifier(Qt.KeyboardModifier.ShiftModifier | Qt.KeyboardModifier.ControlModifier):
val = now()
else:
val = index.data(Qt.ItemDataRole.EditRole)
if is_date_undefined(val):
val = now()
if isinstance(val, datetime):
val = qt_from_dt(val)
editor.setDateTime(val)
# }}}
class PubDateDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
def __init__(self, *args, **kwargs):
QStyledItemDelegate.__init__(self, *args, **kwargs)
self.format = tweaks['gui_pubdate_display_format']
self.table_widget = args[0]
if self.format is None:
self.format = 'MMM yyyy'
def displayText(self, val, locale):
d = qt_to_dt(val)
if is_date_undefined(d):
return ''
return format_date(d, self.format)
def createEditor(self, parent, option, index):
return DateTimeEdit(parent, self.format)
def setEditorData(self, editor, index):
val = index.data(Qt.ItemDataRole.EditRole)
if check_key_modifier(Qt.KeyboardModifier.ControlModifier):
val = UNDEFINED_QDATETIME
elif check_key_modifier(Qt.KeyboardModifier.ShiftModifier | Qt.KeyboardModifier.ControlModifier):
val = now()
elif is_date_undefined(val):
val = QDate.currentDate()
if isinstance(val, QDateTime):
val = val.date()
editor.setDate(val)
# }}}
class TextDelegate(QStyledItemDelegate, UpdateEditorGeometry, EditableTextDelegate): # {{{
use_title_sort = False
def __init__(self, parent):
'''
Delegate for text data. If auto_complete_function needs to return a list
of text items to auto-complete with. If the function is None no
auto-complete will be used.
'''
QStyledItemDelegate.__init__(self, parent)
self.table_widget = parent
self.auto_complete_function = None
def set_auto_complete_function(self, f):
self.auto_complete_function = f
def createEditor(self, parent, option, index):
if self.auto_complete_function:
if self.use_title_sort:
editor = EditWithComplete(parent, sort_func=title_sort)
else:
editor = EditWithComplete(parent)
editor.set_separator(None)
editor.set_clear_button_enabled(False)
complete_items = [i[1] for i in self.auto_complete_function()]
editor.update_items_cache(complete_items)
else:
editor = EnLineEdit(parent)
return editor
def setModelData(self, editor, model, index):
if isinstance(editor, EditWithComplete):
val = editor.lineEdit().text()
model.setData(index, (val), Qt.ItemDataRole.EditRole)
else:
QStyledItemDelegate.setModelData(self, editor, model, index)
# }}}
class SeriesDelegate(TextDelegate): # {{{
use_title_sort = True
def initStyleOption(self, option, index):
TextDelegate.initStyleOption(self, option, index)
option.textElideMode = Qt.TextElideMode.ElideMiddle
# }}}
class CompleteDelegate(QStyledItemDelegate, UpdateEditorGeometry, EditableTextDelegate): # {{{
def __init__(self, parent, sep, items_func_name, space_before_sep=False):
QStyledItemDelegate.__init__(self, parent)
self.sep = sep
self.items_func_name = items_func_name
self.space_before_sep = space_before_sep
self.table_widget = parent
def set_database(self, db):
self.db = db
def createEditor(self, parent, option, index):
if self.db and hasattr(self.db, self.items_func_name):
m = index.model()
col = m.column_map[index.column()]
# If shifted, bring up the tag editor instead of the line editor.
if check_key_modifier(Qt.KeyboardModifier.ShiftModifier) and col != 'authors':
key = col if m.is_custom_column(col) else None
d = TagEditor(parent, self.db, m.id(index.row()), key=key)
if d.exec() == QDialog.DialogCode.Accepted:
m.setData(index, self.sep.join(d.tags), Qt.ItemDataRole.EditRole)
return None
editor = EditWithComplete(parent)
if col == 'tags':
editor.set_elide_mode(Qt.TextElideMode.ElideMiddle)
editor.set_separator(self.sep)
editor.set_clear_button_enabled(False)
editor.set_space_before_sep(self.space_before_sep)
if self.sep == '&':
editor.set_add_separator(tweaks['authors_completer_append_separator'])
if not m.is_custom_column(col):
all_items = getattr(self.db, self.items_func_name)()
else:
all_items = list(self.db.all_custom(
label=self.db.field_metadata.key_to_label(col)))
editor.update_items_cache(all_items)
else:
editor = EnLineEdit(parent)
return editor
def setModelData(self, editor, model, index):
if isinstance(editor, EditWithComplete):
val = editor.lineEdit().text()
model.setData(index, (val), Qt.ItemDataRole.EditRole)
else:
QStyledItemDelegate.setModelData(self, editor, model, index)
# }}}
class LanguagesDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
def __init__(self, parent):
QStyledItemDelegate.__init__(self, parent)
self.table_widget = parent
def createEditor(self, parent, option, index):
editor = LanguagesEdit(parent=parent)
editor.init_langs(index.model().db)
return editor
def setEditorData(self, editor, index):
editor.show_initial_value(get_val_for_textlike_columns(index))
def setModelData(self, editor, model, index):
val = ','.join(editor.lang_codes)
editor.update_recently_used()
model.setData(index, (val), Qt.ItemDataRole.EditRole)
# }}}
class CcDateDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
'''
Delegate for custom columns dates. Because this delegate stores the
format as an instance variable, a new instance must be created for each
column. This differs from all the other delegates.
'''
def __init__(self, parent):
QStyledItemDelegate.__init__(self, parent)
self.table_widget = parent
def set_format(self, _format):
if not _format:
self.format = 'dd MMM yyyy'
elif _format == 'iso':
self.format = internal_iso_format_string()
else:
self.format = _format
def displayText(self, val, locale):
d = qt_to_dt(val)
if is_date_undefined(d):
return ''
return format_date(d, self.format)
def createEditor(self, parent, option, index):
return DateTimeEdit(parent, self.format)
def setEditorData(self, editor, index):
if check_key_modifier(Qt.KeyboardModifier.ControlModifier):
val = UNDEFINED_QDATETIME
elif check_key_modifier(Qt.KeyboardModifier.ShiftModifier | Qt.KeyboardModifier.ControlModifier):
val = now()
else:
val = index.data(Qt.ItemDataRole.EditRole)
if is_date_undefined(val):
val = now()
if isinstance(val, datetime):
val = qt_from_dt(val)
editor.setDateTime(val)
def setModelData(self, editor, model, index):
val = editor.dateTime()
if is_date_undefined(val):
val = None
model.setData(index, (val), Qt.ItemDataRole.EditRole)
# }}}
class CcTextDelegate(QStyledItemDelegate, UpdateEditorGeometry, EditableTextDelegate): # {{{
'''
Delegate for text data.
'''
use_title_sort = False
def __init__(self, parent):
QStyledItemDelegate.__init__(self, parent)
self.table_widget = parent
def createEditor(self, parent, option, index):
m = index.model()
col = m.column_map[index.column()]
key = m.db.field_metadata.key_to_label(col)
if m.db.field_metadata[col]['datatype'] != 'comments':
if self.use_title_sort:
editor = EditWithComplete(parent, sort_func=title_sort)
else:
editor = EditWithComplete(parent)
editor.set_separator(None)
editor.set_clear_button_enabled(False)
complete_items = sorted(list(m.db.all_custom(label=key)), key=sort_key)
editor.update_items_cache(complete_items)
else:
editor = QLineEdit(parent)
text = index.data(Qt.ItemDataRole.DisplayRole)
if text:
editor.setText(text)
return editor
def setModelData(self, editor, model, index):
val = editor.text() or ''
if not isinstance(editor, EditWithComplete):
val = val.strip()
model.setData(index, val, Qt.ItemDataRole.EditRole)
# }}}
class CcSeriesDelegate(CcTextDelegate): # {{{
use_title_sort = True
def initStyleOption(self, option, index):
CcTextDelegate.initStyleOption(self, option, index)
option.textElideMode = Qt.TextElideMode.ElideMiddle
# }}}
class CcLongTextDelegate(QStyledItemDelegate): # {{{
'''
Delegate for comments data.
'''
def __init__(self, parent):
QStyledItemDelegate.__init__(self, parent)
self.document = QTextDocument()
def createEditor(self, parent, option, index):
m = index.model()
col = m.column_map[index.column()]
if check_key_modifier(Qt.KeyboardModifier.ControlModifier):
text = ''
else:
text = m.db.data[index.row()][m.custom_columns[col]['rec_index']]
d = PlainTextDialog(parent, text, column_name=m.custom_columns[col]['name'])
if d.exec() == QDialog.DialogCode.Accepted:
m.setData(index, d.text, Qt.ItemDataRole.EditRole)
return None
def setModelData(self, editor, model, index):
model.setData(index, (editor.textbox.html), Qt.ItemDataRole.EditRole)
# }}}
class CcMarkdownDelegate(QStyledItemDelegate): # {{{
'''
Delegate for markdown data.
'''
def __init__(self, parent):
super().__init__(parent)
self.document = QTextDocument()
def paint(self, painter, option, index):
self.initStyleOption(option, index)
style = QApplication.style() if option.widget is None else option.widget.style()
option.text = markdown(option.text)
self.document.setHtml(option.text)
style.drawPrimitive(QStyle.PrimitiveElement.PE_PanelItemViewItem, option, painter, widget=option.widget)
rect = style.subElementRect(QStyle.SubElement.SE_ItemViewItemDecoration, option, self.parent())
ic = option.icon
if rect.isValid() and not ic.isNull():
sz = ic.actualSize(option.decorationSize)
painter.drawPixmap(rect.topLeft(), ic.pixmap(sz))
ctx = QAbstractTextDocumentLayout.PaintContext()
ctx.palette = option.palette
if option.state & QStyle.StateFlag.State_Selected:
ctx.palette.setColor(QPalette.ColorRole.Text, ctx.palette.color(QPalette.ColorRole.HighlightedText))
textRect = style.subElementRect(QStyle.SubElement.SE_ItemViewItemText, option, self.parent())
painter.save()
painter.translate(textRect.topLeft())
painter.setClipRect(textRect.translated(-textRect.topLeft()))
self.document.documentLayout().draw(painter, ctx)
painter.restore()
def createEditor(self, parent, option, index):
m = index.model()
col = m.column_map[index.column()]
if check_key_modifier(Qt.KeyboardModifier.ControlModifier):
text = ''
else:
text = m.db.data[index.row()][m.custom_columns[col]['rec_index']]
path = m.db.abspath(index.row(), index_is_id=False)
base_url = QUrl.fromLocalFile(os.path.join(path, 'metadata.html')) if path else None
d = MarkdownEditDialog(parent, text, column_name=m.custom_columns[col]['name'],
base_url=base_url)
if d.exec() == QDialog.DialogCode.Accepted:
m.setData(index, (d.text), Qt.ItemDataRole.EditRole)
return None
def setModelData(self, editor, model, index):
model.setData(index, (editor.textbox.html), Qt.ItemDataRole.EditRole)
# }}}
class CcNumberDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
'''
Delegate for text/int/float data.
'''
def __init__(self, parent):
QStyledItemDelegate.__init__(self, parent)
self.table_widget = parent
def createEditor(self, parent, option, index):
m = index.model()
col = m.column_map[index.column()]
if m.custom_columns[col]['datatype'] == 'int':
editor = ClearingSpinBox(parent)
editor.setRange(-1000000, 100000000)
editor.setSpecialValueText(_('Undefined'))
editor.setSingleStep(1)
else:
editor = ClearingDoubleSpinBox(parent)
editor.setSpecialValueText(_('Undefined'))
editor.setRange(-1000000., 100000000.)
editor.setDecimals(int(m.custom_columns[col]['display'].get('decimals', 2)))
return editor
def setModelData(self, editor, model, index):
val = editor.value()
if val == editor.minimum():
val = None
model.setData(index, (val), Qt.ItemDataRole.EditRole)
editor.adjustSize()
def setEditorData(self, editor, index):
m = index.model()
val = m.db.data[index.row()][m.custom_columns[m.column_map[index.column()]]['rec_index']]
if check_key_modifier(Qt.KeyboardModifier.ControlModifier):
val = -1000000
elif val is None:
val = 0
editor.setValue(val)
def get_required_width(self, editor, style, fm):
val = editor.maximum()
text = editor.textFromValue(val)
srect = style.itemTextRect(fm, editor.geometry(), Qt.AlignmentFlag.AlignLeft, False,
text + 'M')
return srect.width()
# }}}
class CcEnumDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
'''
Delegate for text/int/float data.
'''
def __init__(self, parent):
QStyledItemDelegate.__init__(self, parent)
self.table_widget = parent
self.longest_text = ''
def createEditor(self, parent, option, index):
m = index.model()
col = m.column_map[index.column()]
editor = DelegateCB(parent)
editor.addItem('')
max_len = 0
self.longest_text = ''
for v in m.custom_columns[col]['display']['enum_values']:
editor.addItem(v)
if len(v) > max_len:
self.longest_text = v
return editor
def setModelData(self, editor, model, index):
val = str(editor.currentText())
if not val:
val = None
model.setData(index, (val), Qt.ItemDataRole.EditRole)
def get_required_width(self, editor, style, fm):
srect = style.itemTextRect(fm, editor.geometry(), Qt.AlignmentFlag.AlignLeft, False,
self.longest_text + 'M')
return srect.width()
def setEditorData(self, editor, index):
m = index.model()
val = m.db.data[index.row()][m.custom_columns[m.column_map[index.column()]]['rec_index']]
if val is None or check_key_modifier(Qt.KeyboardModifier.ControlModifier):
val = ''
idx = editor.findText(val)
if idx < 0:
editor.setCurrentIndex(0)
else:
editor.setCurrentIndex(idx)
# }}}
class CcCommentsDelegate(QStyledItemDelegate): # {{{
'''
Delegate for comments data.
'''
def __init__(self, parent):
QStyledItemDelegate.__init__(self, parent)
self.document = QTextDocument()
def paint(self, painter, option, index):
self.initStyleOption(option, index)
style = QApplication.style() if option.widget is None \
else option.widget.style()
self.document.setHtml(option.text)
style.drawPrimitive(QStyle.PrimitiveElement.PE_PanelItemViewItem, option, painter, widget=option.widget)
rect = style.subElementRect(QStyle.SubElement.SE_ItemViewItemDecoration, option, self.parent())
ic = option.icon
if rect.isValid() and not ic.isNull():
sz = ic.actualSize(option.decorationSize)
painter.drawPixmap(rect.topLeft(), ic.pixmap(sz))
ctx = QAbstractTextDocumentLayout.PaintContext()
ctx.palette = option.palette
if option.state & QStyle.StateFlag.State_Selected:
ctx.palette.setColor(QPalette.ColorRole.Text, ctx.palette.color(QPalette.ColorRole.HighlightedText))
textRect = style.subElementRect(QStyle.SubElement.SE_ItemViewItemText, option, self.parent())
painter.save()
painter.translate(textRect.topLeft())
painter.setClipRect(textRect.translated(-textRect.topLeft()))
self.document.documentLayout().draw(painter, ctx)
painter.restore()
def createEditor(self, parent, option, index):
m = index.model()
col = m.column_map[index.column()]
if check_key_modifier(Qt.KeyboardModifier.ControlModifier):
text = ''
else:
text = m.db.data[index.row()][m.custom_columns[col]['rec_index']]
editor = CommentsDialog(parent, text, column_name=m.custom_columns[col]['name'])
d = editor.exec()
if d:
m.setData(index, (editor.textbox.html), Qt.ItemDataRole.EditRole)
return None
def setModelData(self, editor, model, index):
model.setData(index, (editor.textbox.html), Qt.ItemDataRole.EditRole)
# }}}
class DelegateCB(QComboBox): # {{{
def __init__(self, parent):
QComboBox.__init__(self, parent)
def event(self, e):
if e.type() == QEvent.Type.ShortcutOverride:
e.accept()
return QComboBox.event(self, e)
# }}}
class CcBoolDelegate(QStyledItemDelegate, UpdateEditorGeometry): # {{{
def __init__(self, parent):
'''
Delegate for custom_column bool data.
'''
self.nuke_option_data = False
QStyledItemDelegate.__init__(self, parent)
self.table_widget = parent
def createEditor(self, parent, option, index):
editor = DelegateCB(parent)
items = [_('Yes'), _('No'), _('Undefined')]
icons = ['ok.png', 'list_remove.png', 'blank.png']
if not index.model().db.new_api.pref('bools_are_tristate'):
items = items[:-1]
icons = icons[:-1]
self.longest_text = ''
for icon, text in zip(icons, items):
editor.addItem(QIcon.ic(icon), text)
if len(text) > len(self.longest_text):
self.longest_text = text
return editor
def get_required_width(self, editor, style, fm):
srect = style.itemTextRect(fm, editor.geometry(), Qt.AlignmentFlag.AlignLeft, False,
self.longest_text + 'M')
return srect.width() + editor.iconSize().width()
def setModelData(self, editor, model, index):
val = {0:True, 1:False, 2:None}[editor.currentIndex()]
model.setData(index, val, Qt.ItemDataRole.EditRole)
def setEditorData(self, editor, index):
m = index.model()
val = m.db.data[index.row()][m.custom_columns[m.column_map[index.column()]]['rec_index']]
if not m.db.new_api.pref('bools_are_tristate'):
val = 1 if not val or check_key_modifier(Qt.KeyboardModifier.ControlModifier) else 0
else:
val = 2 if val is None or check_key_modifier(Qt.KeyboardModifier.ControlModifier) \
else 1 if not val else 0
editor.setCurrentIndex(val)
def initStyleOption(self, option, index):
ret = super().initStyleOption(option, index)
if self.nuke_option_data:
option.icon = QIcon()
option.text = ''
option.features &= ~QStyleOptionViewItem.ViewItemFeature.HasDisplay & ~QStyleOptionViewItem.ViewItemFeature.HasDecoration
return ret
def paint(self, painter, option, index):
text, icon = index.data(Qt.ItemDataRole.DisplayRole), index.data(Qt.ItemDataRole.DecorationRole)
if (not text and not icon) or text or not icon:
return super().paint(painter, option, index)
self.nuke_option_data = True
super().paint(painter, option, index)
self.nuke_option_data = False
style = option.styleObject.style() if option.styleObject else QApplication.instance().style()
style.drawItemPixmap(painter, option.rect, Qt.AlignmentFlag.AlignCenter, icon)
# }}}
class CcTemplateDelegate(QStyledItemDelegate): # {{{
def __init__(self, parent):
'''
Delegate for composite custom_columns.
'''
QStyledItemDelegate.__init__(self, parent)
self.disallow_edit = gprefs['edit_metadata_templates_only_F2_on_booklist']
def createEditor(self, parent, option, index):
if self.disallow_edit:
editor = QLineEdit(parent)
editor.setText(_('Template editing disabled'))
return editor
self.disallow_edit = gprefs['edit_metadata_templates_only_F2_on_booklist']
from calibre.gui2.dialogs.template_dialog import TemplateDialog
m = index.model()
mi = m.db.get_metadata(index.row(), index_is_id=False)
if check_key_modifier(Qt.KeyboardModifier.ControlModifier):
text = ''
else:
text = m.custom_columns[m.column_map[index.column()]]['display']['composite_template']
editor = TemplateDialog(parent, text, mi)
editor.setWindowTitle(_("Edit template"))
editor.textbox.setTabChangesFocus(False)
editor.textbox.setTabStopDistance(20)
d = editor.exec()
if d:
m.setData(index, (editor.rule[1]), Qt.ItemDataRole.EditRole)
return None
def setEditorData(self, editor, index):
editor.setText('editing templates disabled')
editor.setReadOnly(True)
def setModelData(self, editor, model, index):
pass
def allow_one_edit(self):
self.disallow_edit = False
def refresh(self):
self.disallow_edit = gprefs['edit_metadata_templates_only_F2_on_booklist']
# }}}
| 32,417 | Python | .py | 724 | 35.578729 | 135 | 0.638659 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,896 | annotations.py | kovidgoyal_calibre/src/calibre/gui2/library/annotations.py | #!/usr/bin/env python
# License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import codecs
import json
import os
import re
from functools import lru_cache, partial
from urllib.parse import quote
from qt.core import (
QAbstractItemView,
QApplication,
QCheckBox,
QComboBox,
QDateTime,
QDialog,
QDialogButtonBox,
QFont,
QFormLayout,
QFrame,
QHBoxLayout,
QIcon,
QKeySequence,
QLabel,
QLocale,
QMenu,
QPalette,
QPlainTextEdit,
QSize,
QSplitter,
Qt,
QTextBrowser,
QTimer,
QToolButton,
QTreeWidget,
QTreeWidgetItem,
QVBoxLayout,
QWidget,
pyqtSignal,
)
from calibre import prepare_string_for_xml
from calibre.constants import builtin_colors_dark, builtin_colors_light, builtin_decorations
from calibre.db.backend import FTSQueryError
from calibre.ebooks.metadata import authors_to_string, fmt_sidx
from calibre.gui2 import Application, choose_save_file, config, error_dialog, gprefs, is_dark_theme, safe_open_url
from calibre.gui2.dialogs.confirm_delete import confirm
from calibre.gui2.viewer.widgets import ResultsDelegate, SearchBox
from calibre.gui2.widgets import BusyCursor
from calibre.gui2.widgets2 import Dialog, RightClickButton
from calibre.startup import connect_lambda
from calibre.utils.localization import ngettext, pgettext
def render_timestamp(ts):
date = QDateTime.fromString(ts, Qt.DateFormat.ISODate).toLocalTime()
loc = QLocale.system()
return loc.toString(date, loc.dateTimeFormat(QLocale.FormatType.ShortFormat))
# rendering {{{
def render_highlight_as_text(hl, lines, as_markdown=False, link_prefix=None):
lines.append(hl['highlighted_text'])
date = render_timestamp(hl['timestamp'])
if as_markdown and link_prefix:
cfi = hl['start_cfi']
spine_index = (1 + hl['spine_index']) * 2
link = (link_prefix + quote(f'epubcfi(/{spine_index}{cfi})')).replace(')', '%29')
date = f'[{date}]({link})'
lines.append(date)
notes = hl.get('notes')
if notes:
lines.append('')
lines.append(notes)
lines.append('')
if as_markdown:
lines.append('-' * 20)
else:
lines.append('───')
lines.append('')
def render_bookmark_as_text(b, lines, as_markdown=False, link_prefix=None):
lines.append(b['title'])
date = render_timestamp(b['timestamp'])
if as_markdown and link_prefix and b['pos_type'] == 'epubcfi':
link = (link_prefix + quote(b['pos'])).replace(')', '%29')
date = f'[{date}]({link})'
lines.append(date)
lines.append('')
if as_markdown:
lines.append('-' * 20)
else:
lines.append('───')
lines.append('')
class ChapterGroup:
def __init__(self, title='', level=0):
self.title = title
self.subgroups = {}
self.annotations = []
self.level = level
def add_annot(self, a):
titles = a.get('toc_family_titles', (_('Unknown chapter'),))
node = self
for title in titles:
node = node.group_for_title(title)
node.annotations.append(a)
def group_for_title(self, title):
ans = self.subgroups.get(title)
if ans is None:
ans = ChapterGroup(title, self.level+1)
self.subgroups[title] = ans
return ans
def render_as_text(self, lines, as_markdown, link_prefix):
if self.title:
lines.append('#' * self.level + ' ' + self.title)
lines.append('')
for hl in self.annotations:
atype = hl.get('type', 'highlight')
if atype == 'bookmark':
render_bookmark_as_text(hl, lines, as_markdown=as_markdown, link_prefix=link_prefix)
else:
render_highlight_as_text(hl, lines, as_markdown=as_markdown, link_prefix=link_prefix)
for sg in self.subgroups.values():
sg.render_as_text(lines, as_markdown, link_prefix)
url_prefixes = 'http', 'https'
url_delimiters = (
'\x00-\x09\x0b-\x20\x7f-\xa0\xad\u0600-\u0605\u061c\u06dd\u070f\u08e2\u1680\u180e\u2000-\u200f\u2028-\u202f'
'\u205f-\u2064\u2066-\u206f\u3000\ud800-\uf8ff\ufeff\ufff9-\ufffb\U000110bd\U000110cd\U00013430-\U00013438'
'\U0001bca0-\U0001bca3\U0001d173-\U0001d17a\U000e0001\U000e0020-\U000e007f\U000f0000-\U000ffffd\U00100000-\U0010fffd'
)
url_pattern = r'\b(?:{})://[^{}]{{3,}}'.format('|'.join(url_prefixes), url_delimiters)
@lru_cache(maxsize=2)
def url_pat():
return re.compile(url_pattern, flags=re.I)
closing_bracket_map = {'(': ')', '[': ']', '{': '}', '<': '>', '*': '*', '"': '"', "'": "'"}
def url(text: str, s: int, e: int):
while text[e - 1] in '.,?!' and e > 1: # remove trailing punctuation
e -= 1
# truncate url at closing bracket/quote
if s > 0 and e <= len(text) and text[s-1] in closing_bracket_map:
q = closing_bracket_map[text[s-1]]
idx = text.find(q, s)
if idx > s:
e = idx
return s, e
def render_note_line(line):
urls = []
for m in url_pat().finditer(line):
s, e = url(line, m.start(), m.end())
urls.append((s, e))
if not urls:
yield prepare_string_for_xml(line)
return
pos = 0
for (s, e) in urls:
if s > pos:
yield prepare_string_for_xml(line[pos:s])
yield '<a href="{0}">{0}</a>'.format(prepare_string_for_xml(line[s:e], True))
if urls[-1][1] < len(line):
yield prepare_string_for_xml(line[urls[-1][1]:])
def render_notes(notes, tag='p'):
current_lines = []
for line in notes.splitlines():
if line:
current_lines.append(''.join(render_note_line(line)))
else:
if current_lines:
yield '<{0}>{1}</{0}>'.format(tag, '\n'.join(current_lines))
current_lines = []
if current_lines:
yield '<{0}>{1}</{0}>'.format(tag, '\n'.join(current_lines))
def friendly_username(user_type, user):
key = user_type, user
if key == ('web', '*'):
return _('Anonymous Content server user')
if key == ('local', 'viewer'):
return _('Local E-book viewer user')
return user
def annotation_title(atype, singular=False):
if singular:
return {'bookmark': _('Bookmark'), 'highlight': pgettext('type of annotation', 'Highlight')}.get(atype, atype)
return {'bookmark': _('Bookmarks'), 'highlight': _('Highlights')}.get(atype, atype)
class AnnotsResultsDelegate(ResultsDelegate):
add_ellipsis = False
emphasize_text = False
def result_data(self, result):
if not isinstance(result, dict):
return None, None, None, None, None
full_text = result['text'].replace('\x1f', ' ')
parts = full_text.split('\x1d', 2)
before = after = ''
if len(parts) > 2:
before, text = parts[:2]
after = parts[2].replace('\x1d', '')
elif len(parts) == 2:
before, text = parts
else:
text = parts[0]
return False, before, text, after, bool(result.get('annotation', {}).get('notes'))
# }}}
def sorted_items(items):
from calibre.ebooks.epub.cfi.parse import cfi_sort_key
def_spine = 999999999
defval = cfi_sort_key(f'/{def_spine}')
def sort_key(x):
x = x['annotation']
atype = x['type']
if atype == 'highlight':
cfi = x.get('start_cfi')
if cfi:
spine_idx = x.get('spine_index', def_spine)
cfi = f'/{spine_idx}{cfi}'
return cfi_sort_key(cfi)
elif atype == 'bookmark':
if x.get('pos_type') == 'epubcfi':
return cfi_sort_key(x['pos'], only_path=False)
return defval
return sorted(items, key=sort_key)
def css_for_highlight_style(style):
is_dark = is_dark_theme()
kind = style.get('kind')
ans = ''
if kind == 'color':
key = 'dark' if is_dark else 'light'
val = style.get(key)
if val is None:
which = style.get('which')
val = (builtin_colors_dark if is_dark else builtin_colors_light).get(which)
if val is None:
val = style.get('background-color')
if val is not None:
ans = f'background-color: {val}'
elif 'background-color' in style:
ans = 'background-color: ' + style['background-color']
if 'color' in style:
ans += '; color: ' + style["color"]
elif kind == 'decoration':
which = style.get('which')
if which is not None:
q = builtin_decorations.get(which)
if q is not None:
ans = q
else:
ans = '; '.join(f'{k}: {v}' for k, v in style.items())
return ans
class Export(Dialog): # {{{
prefs = gprefs
pref_name = 'annots_export_format'
def __init__(self, annots, parent=None):
self.annotations = annots
super().__init__(name='export-annotations', title=_('Export {} annotations').format(len(annots)), parent=parent)
def file_type_data(self):
return _('calibre annotation collection'), 'calibre_annotation_collection'
def initial_filename(self):
return _('annotations')
def setup_ui(self):
self.l = l = QFormLayout(self)
self.export_format = ef = QComboBox(self)
ef.addItem(_('Plain text'), 'txt')
ef.addItem(_('Markdown'), 'md')
ef.addItem(*self.file_type_data())
idx = ef.findData(self.prefs[self.pref_name])
if idx > -1:
ef.setCurrentIndex(idx)
ef.currentIndexChanged.connect(self.save_format_pref)
l.addRow(_('Format to export in:'), ef)
l.addRow(self.bb)
self.bb.clear()
self.bb.addButton(QDialogButtonBox.StandardButton.Cancel)
b = self.bb.addButton(_('Copy to clipboard'), QDialogButtonBox.ButtonRole.ActionRole)
b.clicked.connect(self.copy_to_clipboard)
b.setIcon(QIcon.ic('edit-copy.png'))
b = self.bb.addButton(_('Save to file'), QDialogButtonBox.ButtonRole.ActionRole)
b.clicked.connect(self.save_to_file)
b.setIcon(QIcon.ic('save.png'))
def save_format_pref(self):
self.prefs[self.pref_name] = self.export_format.currentData()
def copy_to_clipboard(self):
QApplication.instance().clipboard().setText(self.exported_data())
self.accept()
def save_to_file(self):
filters = [(self.export_format.currentText(), [self.export_format.currentData()])]
path = choose_save_file(
self, 'annots-export-save', _('File for exports'), filters=filters,
initial_filename=self.initial_filename() + '.' + filters[0][1][0])
if path:
data = self.exported_data().encode('utf-8')
with open(path, 'wb') as f:
f.write(codecs.BOM_UTF8)
f.write(data)
self.accept()
def exported_data(self):
fmt = self.export_format.currentData()
if fmt == 'calibre_annotation_collection':
return json.dumps({
'version': 1,
'type': 'calibre_annotation_collection',
'annotations': self.annotations,
}, ensure_ascii=False, sort_keys=True, indent=2)
lines = []
db = current_db()
bid_groups = {}
as_markdown = fmt == 'md'
library_id = getattr(db, 'server_library_id', None)
if library_id:
library_id = '_hex_-' + library_id.encode('utf-8').hex()
for a in self.annotations:
bid_groups.setdefault(a['book_id'], []).append(a)
for book_id, group in bid_groups.items():
root = ChapterGroup(level=1)
for a in group:
root.add_annot(a)
if library_id:
link_prefix = f'calibre://view-book/{library_id}/{book_id}/{a["format"]}?open_at='
else:
link_prefix = None
lines.append('# ' + db.field_for('title', book_id))
lines.append('')
root.render_as_text(lines, as_markdown, link_prefix)
lines.append('')
return '\n'.join(lines).strip()
# }}}
def current_db():
from calibre.gui2.ui import get_gui
return (getattr(current_db, 'ans', None) or get_gui().current_db).new_api
class ResultsList(QTreeWidget):
current_result_changed = pyqtSignal(object)
open_annotation = pyqtSignal(object, object, object)
show_book = pyqtSignal(object, object)
delete_requested = pyqtSignal()
export_requested = pyqtSignal()
edit_annotation = pyqtSignal(object, object)
def __init__(self, parent):
QTreeWidget.__init__(self, parent)
self.setHeaderHidden(True)
self.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.customContextMenuRequested.connect(self.show_context_menu)
self.delegate = AnnotsResultsDelegate(self)
self.setItemDelegate(self.delegate)
self.section_font = QFont(self.font())
self.itemDoubleClicked.connect(self.item_activated)
self.section_font.setItalic(True)
self.currentItemChanged.connect(self.current_item_changed)
self.number_of_results = 0
self.item_map = []
def show_context_menu(self, pos):
item = self.itemAt(pos)
if item is not None:
result = item.data(0, Qt.ItemDataRole.UserRole)
else:
result = None
items = self.selectedItems()
m = QMenu(self)
if isinstance(result, dict):
m.addAction(QIcon.ic('viewer.png'), _('Open in viewer'), partial(self.item_activated, item))
m.addAction(QIcon.ic('lt.png'), _('Show in calibre'), partial(self.show_in_calibre, item))
if result.get('annotation', {}).get('type') == 'highlight':
m.addAction(QIcon.ic('modified.png'), _('Edit notes'), partial(self.edit_notes, item))
if items:
m.addSeparator()
m.addAction(QIcon.ic('save.png'),
ngettext('Export selected item', 'Export {} selected items', len(items)).format(len(items)), self.export_requested.emit)
m.addAction(QIcon.ic('trash.png'),
ngettext('Delete selected item', 'Delete {} selected items', len(items)).format(len(items)), self.delete_requested.emit)
m.addSeparator()
m.addAction(QIcon.ic('plus.png'), _('Expand all'), self.expandAll)
m.addAction(QIcon.ic('minus.png'), _('Collapse all'), self.collapseAll)
m.exec(self.mapToGlobal(pos))
def edit_notes(self, item):
r = item.data(0, Qt.ItemDataRole.UserRole)
if isinstance(r, dict):
self.edit_annotation.emit(r['id'], r['annotation'])
def show_in_calibre(self, item):
r = item.data(0, Qt.ItemDataRole.UserRole)
if isinstance(r, dict):
self.show_book.emit(r['book_id'], r['format'])
def item_activated(self, item):
r = item.data(0, Qt.ItemDataRole.UserRole)
if isinstance(r, dict):
self.open_annotation.emit(r['book_id'], r['format'], r['annotation'])
def set_results(self, results, emphasize_text):
self.clear()
self.delegate.emphasize_text = emphasize_text
self.number_of_results = 0
self.item_map = []
book_id_map = {}
db = current_db()
for result in results:
book_id = result['book_id']
if book_id not in book_id_map:
book_id_map[book_id] = {'title': db.field_for('title', book_id), 'matches': []}
book_id_map[book_id]['matches'].append(result)
for book_id, entry in book_id_map.items():
section = QTreeWidgetItem([entry['title']], 1)
section.setFlags(Qt.ItemFlag.ItemIsEnabled)
section.setFont(0, self.section_font)
section.setData(0, Qt.ItemDataRole.UserRole, book_id)
self.addTopLevelItem(section)
section.setExpanded(True)
for result in sorted_items(entry['matches']):
item = QTreeWidgetItem(section, [' '], 2)
self.item_map.append(item)
item.setFlags(Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemNeverHasChildren)
item.setData(0, Qt.ItemDataRole.UserRole, result)
item.setData(0, Qt.ItemDataRole.UserRole + 1, self.number_of_results)
self.number_of_results += 1
if self.item_map:
self.setCurrentItem(self.item_map[0])
def current_item_changed(self, current, previous):
if current is not None:
r = current.data(0, Qt.ItemDataRole.UserRole)
if isinstance(r, dict):
self.current_result_changed.emit(r)
else:
self.current_result_changed.emit(None)
def show_next(self, backwards=False):
item = self.currentItem()
if item is None:
return
i = int(item.data(0, Qt.ItemDataRole.UserRole + 1))
i += -1 if backwards else 1
i %= self.number_of_results
self.setCurrentItem(self.item_map[i])
@property
def selected_annot_ids(self):
for item in self.selectedItems():
yield item.data(0, Qt.ItemDataRole.UserRole)['id']
@property
def selected_annotations(self):
for item in self.selectedItems():
x = item.data(0, Qt.ItemDataRole.UserRole)
ans = x['annotation'].copy()
for key in ('book_id', 'format'):
ans[key] = x[key]
yield ans
def keyPressEvent(self, ev):
if ev.matches(QKeySequence.StandardKey.Delete):
self.delete_requested.emit()
ev.accept()
return
if ev.key() == Qt.Key.Key_F2:
item = self.currentItem()
if item:
self.edit_notes(item)
ev.accept()
return
return QTreeWidget.keyPressEvent(self, ev)
@property
def tree_state(self):
ans = {'closed': set()}
item = self.currentItem()
if item is not None:
ans['current'] = item.data(0, Qt.ItemDataRole.UserRole)
for item in (self.topLevelItem(i) for i in range(self.topLevelItemCount())):
if not item.isExpanded():
ans['closed'].add(item.data(0, Qt.ItemDataRole.UserRole))
return ans
@tree_state.setter
def tree_state(self, state):
closed = state['closed']
for item in (self.topLevelItem(i) for i in range(self.topLevelItemCount())):
if item.data(0, Qt.ItemDataRole.UserRole) in closed:
item.setExpanded(False)
cur = state.get('current')
if cur is not None:
for item in self.item_map:
if item.data(0, Qt.ItemDataRole.UserRole) == cur:
self.setCurrentItem(item)
break
class Restrictions(QWidget):
restrictions_changed = pyqtSignal()
def __init__(self, parent):
self.restrict_to_book_ids = frozenset()
QWidget.__init__(self, parent)
v = QVBoxLayout(self)
v.setContentsMargins(0, 0, 0, 0)
h = QHBoxLayout()
h.setContentsMargins(0, 0, 0, 0)
v.addLayout(h)
self.rla = QLabel(_('Restrict to') + ': ')
h.addWidget(self.rla)
la = QLabel(_('Type:'))
h.addWidget(la)
self.types_box = tb = QComboBox(self)
tb.la = la
tb.currentIndexChanged.connect(self.restrictions_changed)
connect_lambda(tb.currentIndexChanged, tb, lambda tb: gprefs.set('browse_annots_restrict_to_type', tb.currentData()))
la.setBuddy(tb)
tb.setToolTip(_('Show only annotations of the specified type'))
h.addWidget(tb)
la = QLabel(_('User:'))
h.addWidget(la)
self.user_box = ub = QComboBox(self)
ub.la = la
ub.currentIndexChanged.connect(self.restrictions_changed)
connect_lambda(ub.currentIndexChanged, ub, lambda ub: gprefs.set('browse_annots_restrict_to_user', ub.currentData()))
la.setBuddy(ub)
ub.setToolTip(_('Show only annotations created by the specified user'))
h.addWidget(ub)
h.addStretch(10)
h = QHBoxLayout()
self.restrict_to_books_cb = cb = QCheckBox('')
self.update_book_restrictions_text()
cb.setToolTip(_('Only show annotations from books that have been selected in the calibre library'))
cb.setChecked(bool(gprefs.get('show_annots_from_selected_books_only', False)))
cb.stateChanged.connect(self.show_only_selected_changed)
h.addWidget(cb)
v.addLayout(h)
def update_book_restrictions_text(self):
if not self.restrict_to_book_ids:
t = _('&Show results from only selected books')
else:
t = ngettext(
'&Show results from only the selected book',
'&Show results from only the {} selected books',
len(self.restrict_to_book_ids)).format(len(self.restrict_to_book_ids))
self.restrict_to_books_cb.setText(t)
def show_only_selected_changed(self):
self.restrictions_changed.emit()
gprefs['show_annots_from_selected_books_only'] = bool(self.restrict_to_books_cb.isChecked())
def selection_changed(self, restrict_to_book_ids):
self.restrict_to_book_ids = frozenset(restrict_to_book_ids or set())
self.update_book_restrictions_text()
if self.restrict_to_books_cb.isChecked():
self.restrictions_changed.emit()
@property
def effective_restrict_to_book_ids(self):
return (self.restrict_to_book_ids or None) if self.restrict_to_books_cb.isChecked() else None
def re_initialize(self, db, restrict_to_book_ids=None):
self.restrict_to_book_ids = frozenset(restrict_to_book_ids or set())
self.update_book_restrictions_text()
tb = self.types_box
before = tb.currentData()
if not before:
before = gprefs['browse_annots_restrict_to_type']
tb.blockSignals(True)
tb.clear()
tb.addItem(' ', ' ')
for atype in db.all_annotation_types():
tb.addItem(annotation_title(atype), atype)
if before:
row = tb.findData(before)
if row > -1:
tb.setCurrentIndex(row)
tb.blockSignals(False)
tb_is_visible = tb.count() > 2
tb.setVisible(tb_is_visible), tb.la.setVisible(tb_is_visible)
tb = self.user_box
before = tb.currentData()
if not before:
before = gprefs['browse_annots_restrict_to_user']
tb.blockSignals(True)
tb.clear()
tb.addItem(' ', ' ')
for user_type, user in db.all_annotation_users():
display_name = friendly_username(user_type, user)
tb.addItem(display_name, f'{user_type}:{user}')
if before:
row = tb.findData(before)
if row > -1:
tb.setCurrentIndex(row)
tb.blockSignals(False)
ub_is_visible = tb.count() > 2
tb.setVisible(ub_is_visible), tb.la.setVisible(ub_is_visible)
self.rla.setVisible(tb_is_visible or ub_is_visible)
self.setVisible(True)
class BrowsePanel(QWidget):
current_result_changed = pyqtSignal(object)
open_annotation = pyqtSignal(object, object, object)
show_book = pyqtSignal(object, object)
delete_requested = pyqtSignal()
export_requested = pyqtSignal()
edit_annotation = pyqtSignal(object, object)
def __init__(self, parent):
QWidget.__init__(self, parent)
self.use_stemmer = parent.use_stemmer
self.current_query = None
l = QVBoxLayout(self)
h = QHBoxLayout()
l.addLayout(h)
self.search_box = sb = SearchBox(self)
sb.initialize('library-annotations-browser-search-box')
sb.cleared.connect(self.cleared, type=Qt.ConnectionType.QueuedConnection)
sb.lineEdit().returnPressed.connect(self.show_next)
sb.lineEdit().setPlaceholderText(_('Enter words to search for'))
h.addWidget(sb)
self.next_button = nb = QToolButton(self)
h.addWidget(nb)
nb.setFocusPolicy(Qt.FocusPolicy.NoFocus)
nb.setIcon(QIcon.ic('arrow-down.png'))
nb.clicked.connect(self.show_next)
nb.setToolTip(_('Find next match'))
self.prev_button = nb = QToolButton(self)
h.addWidget(nb)
nb.setFocusPolicy(Qt.FocusPolicy.NoFocus)
nb.setIcon(QIcon.ic('arrow-up.png'))
nb.clicked.connect(self.show_previous)
nb.setToolTip(_('Find previous match'))
self.restrictions = rs = Restrictions(self)
rs.restrictions_changed.connect(self.effective_query_changed)
self.use_stemmer.stateChanged.connect(self.effective_query_changed)
l.addWidget(rs)
self.results_list = rl = ResultsList(self)
rl.current_result_changed.connect(self.current_result_changed)
rl.open_annotation.connect(self.open_annotation)
rl.show_book.connect(self.show_book)
rl.edit_annotation.connect(self.edit_annotation)
rl.delete_requested.connect(self.delete_requested)
rl.export_requested.connect(self.export_requested)
l.addWidget(rl)
def re_initialize(self, restrict_to_book_ids=None):
db = current_db()
self.search_box.setFocus(Qt.FocusReason.OtherFocusReason)
self.restrictions.re_initialize(db, restrict_to_book_ids or set())
self.current_query = None
self.results_list.clear()
def selection_changed(self, restrict_to_book_ids):
self.restrictions.selection_changed(restrict_to_book_ids)
def sizeHint(self):
return QSize(450, 600)
@property
def restrict_to_user(self):
user = self.restrictions.user_box.currentData()
if user and ':' in user:
return user.split(':', 1)
@property
def effective_query(self):
text = self.search_box.lineEdit().text().strip()
atype = self.restrictions.types_box.currentData()
return {
'fts_engine_query': text,
'annotation_type': (atype or '').strip(),
'restrict_to_user': self.restrict_to_user,
'use_stemming': bool(self.use_stemmer.isChecked()),
'restrict_to_book_ids': self.restrictions.effective_restrict_to_book_ids,
}
def cleared(self):
self.current_query = None
self.effective_query_changed()
def do_find(self, backwards=False):
q = self.effective_query
if q == self.current_query:
self.results_list.show_next(backwards)
return
try:
with BusyCursor():
db = current_db()
if not q['fts_engine_query']:
results = db.all_annotations(
restrict_to_user=q['restrict_to_user'], limit=4096, annotation_type=q['annotation_type'],
ignore_removed=True, restrict_to_book_ids=q['restrict_to_book_ids'] or None
)
else:
q2 = q.copy()
q2['restrict_to_book_ids'] = q.get('restrict_to_book_ids') or None
results = db.search_annotations(
highlight_start='\x1d', highlight_end='\x1d', snippet_size=64,
ignore_removed=True, **q2
)
self.results_list.set_results(results, bool(q['fts_engine_query']))
self.current_query = q
except FTSQueryError as err:
return error_dialog(self, _('Invalid search expression'), '<p>' + _(
'The search expression: {0} is invalid. The search syntax used is the'
' SQLite Full text Search Query syntax, <a href="{1}">described here</a>.').format(
err.query, 'https://www.sqlite.org/fts5.html#full_text_query_syntax'),
det_msg=str(err), show=True)
def effective_query_changed(self):
self.do_find()
def refresh(self):
vbar = self.results_list.verticalScrollBar()
if vbar:
vpos = vbar.value()
self.current_query = None
self.do_find()
vbar = self.results_list.verticalScrollBar()
if vbar:
vbar.setValue(vpos)
def show_next(self):
self.do_find()
def show_previous(self):
self.do_find(backwards=True)
@property
def selected_annot_ids(self):
return self.results_list.selected_annot_ids
@property
def selected_annotations(self):
return self.results_list.selected_annotations
def save_tree_state(self):
return self.results_list.tree_state
def restore_tree_state(self, state):
self.results_list.tree_state = state
class Details(QTextBrowser):
def __init__(self, parent):
QTextBrowser.__init__(self, parent)
self.setFrameShape(QFrame.Shape.NoFrame)
self.setOpenLinks(False)
self.setAttribute(Qt.WidgetAttribute.WA_OpaquePaintEvent, False)
palette = self.palette()
palette.setBrush(QPalette.ColorRole.Base, Qt.GlobalColor.transparent)
self.setPalette(palette)
self.setAcceptDrops(False)
class DetailsPanel(QWidget):
open_annotation = pyqtSignal(object, object, object)
show_book = pyqtSignal(object, object)
edit_annotation = pyqtSignal(object, object)
delete_annotation = pyqtSignal(object)
def __init__(self, parent):
QWidget.__init__(self, parent)
self.current_result = None
l = QVBoxLayout(self)
self.text_browser = tb = Details(self)
tb.anchorClicked.connect(self.link_clicked)
l.addWidget(tb)
self.show_result(None)
def link_clicked(self, qurl):
if qurl.scheme() == 'calibre':
getattr(self, qurl.host())()
else:
safe_open_url(qurl)
def open_result(self):
if self.current_result is not None:
r = self.current_result
self.open_annotation.emit(r['book_id'], r['format'], r['annotation'])
def delete_result(self):
if self.current_result is not None:
r = self.current_result
self.delete_annotation.emit(r['id'])
def edit_result(self):
if self.current_result is not None:
r = self.current_result
self.edit_annotation.emit(r['id'], r['annotation'])
def show_in_library(self):
if self.current_result is not None:
self.show_book.emit(self.current_result['book_id'], self.current_result['format'])
def sizeHint(self):
return QSize(450, 600)
def set_controls_visibility(self, visible):
self.text_browser.setVisible(visible)
def update_notes(self, annot):
if self.current_result:
self.current_result['annotation'] = annot
self.show_result(self.current_result)
def show_result(self, result_or_none):
self.current_result = r = result_or_none
if r is None:
self.set_controls_visibility(False)
return
self.set_controls_visibility(True)
db = current_db()
book_id = r['book_id']
title, authors = db.field_for('title', book_id), db.field_for('authors', book_id)
authors = authors_to_string(authors)
series, sidx = db.field_for('series', book_id), db.field_for('series_index', book_id)
series_text = ''
if series:
use_roman_numbers = config['use_roman_numerals_for_series_number']
series_text = f'{fmt_sidx(sidx, use_roman=use_roman_numbers)} of {series}'
annot = r['annotation']
atype = annotation_title(annot['type'], singular=True)
book_format = r['format']
annot_text = ''
a = prepare_string_for_xml
highlight_css = ''
paras = []
def p(text, tag='p'):
paras.append('<{0}>{1}</{0}>'.format(tag, a(text)))
if annot['type'] == 'bookmark':
p(annot['title'])
elif annot['type'] == 'highlight':
for line in annot['highlighted_text'].splitlines():
p(line)
notes = annot.get('notes')
if notes:
paras.append('<h4>{} (<a title="{}" href="calibre://edit_result">{}</a>)</h4>'.format(
_('Notes'), _('Edit the notes of this highlight'), _('Edit')))
paras.extend(render_notes(notes))
else:
paras.append('<p><a title="{}" href="calibre://edit_result">{}</a></p>'.format(
_('Add notes to this highlight'), _('Add notes')))
if 'style' in annot:
highlight_css = css_for_highlight_style(annot['style'])
annot_text += '\n'.join(paras)
date = render_timestamp(annot['timestamp'])
text = '''
<style>a {{ text-decoration: none }}</style>
<h2 style="text-align: center">{title} [{book_format}]</h2>
<div style="text-align: center">{authors}</div>
<div style="text-align: center">{series}</div>
<div> </div>
<div> </div>
<div>{dt}: {date}</div>
<div>{ut}: {user}</div>
<div>
<a href="calibre://open_result" title="{ovtt}" style="margin-right: 20px">{ov}</a>
<span>\xa0\xa0\xa0</span>
<a title="{sictt}" href="calibre://show_in_library">{sic}</a>
</div>
<h3 style="text-align: left; {highlight_css}">{atype}</h3>
{text}
'''.format(
title=a(title), authors=a(authors), series=a(series_text), book_format=a(book_format),
atype=a(atype), text=annot_text, dt=_('Date'), date=a(date), ut=a(_('User')),
user=a(friendly_username(r['user_type'], r['user'])), highlight_css=highlight_css,
ov=a(_('Open in viewer')), sic=a(_('Show in calibre')),
ovtt=a(_('View the book at this annotation in the calibre E-book viewer')),
sictt=(_('Show this book in the main calibre book list')),
)
self.text_browser.setHtml(text)
class EditNotes(Dialog):
def __init__(self, notes, parent=None):
self.initial_notes = notes
Dialog.__init__(
self, _('Edit notes for highlight'), 'library-annotations-browser-edit-notes', parent=parent)
def setup_ui(self):
self.notes_edit = QPlainTextEdit(self)
if self.initial_notes:
self.notes_edit.setPlainText(self.initial_notes)
self.notes_edit.setMinimumWidth(400)
self.notes_edit.setMinimumHeight(300)
l = QVBoxLayout(self)
l.addWidget(self.notes_edit)
l.addWidget(self.bb)
@property
def notes(self):
return self.notes_edit.toPlainText()
class AnnotationsBrowser(Dialog):
open_annotation = pyqtSignal(object, object, object)
show_book = pyqtSignal(object, object)
def __init__(self, parent=None):
self.current_restriction = None
Dialog.__init__(self, _('Annotations browser'), 'library-annotations-browser', parent=parent, default_buttons=QDialogButtonBox.StandardButton.Close)
self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False)
self.setWindowIcon(QIcon.ic('highlight.png'))
def do_open_annotation(self, book_id, fmt, annot):
atype = annot['type']
if atype == 'bookmark':
if annot['pos_type'] == 'epubcfi':
self.open_annotation.emit(book_id, fmt, annot['pos'])
elif atype == 'highlight':
x = 2 * (annot['spine_index'] + 1)
self.open_annotation.emit(book_id, fmt, 'epubcfi(/{}{})'.format(x, annot['start_cfi']))
def keyPressEvent(self, ev):
if ev.key() not in (Qt.Key.Key_Enter, Qt.Key.Key_Return):
return Dialog.keyPressEvent(self, ev)
def setup_ui(self):
self.use_stemmer = us = QCheckBox(_('&Match on related words'))
us.setChecked(gprefs['browse_annots_use_stemmer'])
us.setToolTip('<p>' + _(
'With this option searching for words will also match on any related words (supported in several languages). For'
' example, in the English language: <i>correction</i> matches <i>correcting</i> and <i>corrected</i> as well'))
us.stateChanged.connect(lambda state: gprefs.set('browse_annots_use_stemmer', state != Qt.CheckState.Unchecked.value))
l = QVBoxLayout(self)
self.splitter = s = QSplitter(self)
l.addWidget(s)
s.setChildrenCollapsible(False)
self.browse_panel = bp = BrowsePanel(self)
bp.open_annotation.connect(self.do_open_annotation)
bp.show_book.connect(self.show_book)
bp.delete_requested.connect(self.delete_selected)
bp.export_requested.connect(self.export_selected)
bp.edit_annotation.connect(self.edit_annotation)
s.addWidget(bp)
self.details_panel = dp = DetailsPanel(self)
s.addWidget(dp)
dp.open_annotation.connect(self.do_open_annotation)
dp.show_book.connect(self.show_book)
dp.delete_annotation.connect(self.delete_annotation)
dp.edit_annotation.connect(self.edit_annotation)
bp.current_result_changed.connect(dp.show_result)
h = QHBoxLayout()
l.addLayout(h)
h.addWidget(us), h.addStretch(10), h.addWidget(self.bb)
self.delete_button = b = self.bb.addButton(_('&Delete all selected'), QDialogButtonBox.ButtonRole.ActionRole)
b.setToolTip(_('Delete the selected annotations'))
b.setIcon(QIcon.ic('trash.png'))
b.clicked.connect(self.delete_selected)
self.export_button = b = self.bb.addButton(_('&Export all selected'), QDialogButtonBox.ButtonRole.ActionRole)
b.setToolTip(_('Export the selected annotations'))
b.setIcon(QIcon.ic('save.png'))
b.clicked.connect(self.export_selected)
self.refresh_button = b = RightClickButton(self.bb)
self.bb.addButton(b, QDialogButtonBox.ButtonRole.ActionRole)
b.setText(_('&Refresh'))
b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
self.refresh_menu = m = QMenu(self)
m.addAction(_('Rebuild search index')).triggered.connect(self.rebuild)
b.setMenu(m)
b.setToolTip(_('Refresh annotations in case they have been changed since this window was opened'))
b.setIcon(QIcon.ic('restart.png'))
b.setPopupMode(QToolButton.ToolButtonPopupMode.DelayedPopup)
b.clicked.connect(self.refresh)
def delete_selected(self):
ids = frozenset(self.browse_panel.selected_annot_ids)
if not ids:
return error_dialog(self, _('No selected annotations'), _(
'No annotations have been selected'), show=True)
self.delete_annotations(ids)
def export_selected(self):
annots = tuple(self.browse_panel.selected_annotations)
if not annots:
return error_dialog(self, _('No selected annotations'), _(
'No annotations have been selected'), show=True)
Export(annots, self).exec()
def delete_annotations(self, ids):
if confirm(ngettext(
'Are you sure you want to <b>permanently</b> delete this annotation?',
'Are you sure you want to <b>permanently</b> delete these {} annotations?',
len(ids)).format(len(ids)), 'delete-annotation-from-browse', parent=self
):
db = current_db()
db.delete_annotations(ids)
self.browse_panel.refresh()
def delete_annotation(self, annot_id):
self.delete_annotations(frozenset({annot_id}))
def edit_annotation(self, annot_id, annot):
if annot.get('type') != 'highlight':
return error_dialog(self, _('Cannot edit'), _(
'Editing is only supported for the notes associated with highlights'), show=True)
notes = annot.get('notes')
d = EditNotes(notes, self)
if d.exec() == QDialog.DialogCode.Accepted:
notes = d.notes
if notes and notes.strip():
annot['notes'] = notes.strip()
else:
annot.pop('notes', None)
db = current_db()
db.update_annotations({annot_id: annot})
self.details_panel.update_notes(annot)
def show_dialog(self, restrict_to_book_ids=None):
if self.parent() is None:
self.browse_panel.effective_query_changed()
self.exec()
else:
self.reinitialize(restrict_to_book_ids)
self.show()
self.raise_and_focus()
QTimer.singleShot(80, self.browse_panel.effective_query_changed)
def selection_changed(self):
if self.isVisible() and self.parent():
gui = self.parent()
self.browse_panel.selection_changed(gui.library_view.get_selected_ids(as_set=True))
def reinitialize(self, restrict_to_book_ids=None):
self.current_restriction = restrict_to_book_ids
self.browse_panel.re_initialize(restrict_to_book_ids or set())
def refresh(self):
state = self.browse_panel.save_tree_state()
self.browse_panel.re_initialize(self.current_restriction)
self.browse_panel.effective_query_changed()
self.browse_panel.restore_tree_state(state)
def rebuild(self):
with BusyCursor():
current_db().reindex_annotations()
self.refresh()
if __name__ == '__main__':
from calibre.library import db
app = Application([])
current_db.ans = db(os.path.expanduser('~/test library'))
br = AnnotationsBrowser()
br.reinitialize()
br.show_dialog()
del br
del app
| 42,028 | Python | .py | 958 | 34.546973 | 156 | 0.611614 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,897 | caches.py | kovidgoyal_calibre/src/calibre/gui2/library/caches.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
from collections import OrderedDict
from threading import Lock, current_thread
from qt.core import QImage, QPixmap
from calibre.db.utils import ThumbnailCache as TC
from polyglot.builtins import itervalues
class ThumbnailCache(TC):
def __init__(self, max_size=1024, thumbnail_size=(100, 100), version=0):
TC.__init__(self, name='gui-thumbnail-cache', min_disk_cache=100, max_size=max_size,
thumbnail_size=thumbnail_size, version=version)
def set_database(self, db):
TC.set_group_id(self, db.library_id)
class CoverCache(dict):
'''
This is a RAM cache to speed up rendering of covers by storing them as
QPixmaps. It is possible that it is called from multiple threads, thus the
locking and staging. For example, it can be called by the db layer when a
book is removed either by the GUI or the content server.
'''
def __init__(self, limit=100):
self.items = OrderedDict()
self.lock = Lock()
self.limit = limit
self.pixmap_staging = []
self.gui_thread = current_thread()
def clear_staging(self):
' Must be called in the GUI thread '
self.pixmap_staging = []
def invalidate(self, book_ids):
with self.lock:
for book_id in book_ids:
self._pop(book_id)
def _pop(self, book_id):
val = self.items.pop(book_id, None)
if isinstance(val, QPixmap) and current_thread() is not self.gui_thread:
self.pixmap_staging.append(val)
def __getitem__(self, key):
' Must be called in the GUI thread '
with self.lock:
self.clear_staging()
ans = self.items.pop(key, False) # pop() so that item is moved to the top
if ans is not False:
if isinstance(ans, QImage):
# Convert to QPixmap, since rendering QPixmap is much
# faster
ans = QPixmap.fromImage(ans)
self.items[key] = ans
return ans
def set(self, key, val):
with self.lock:
self._pop(key) # pop() so that item is moved to the top
self.items[key] = val
if len(self.items) > self.limit:
del self.items[next(iter(self.items))]
def clear(self):
with self.lock:
if current_thread() is not self.gui_thread:
pixmaps = (x for x in itervalues(self.items) if isinstance(x, QPixmap))
self.pixmap_staging.extend(pixmaps)
self.items.clear()
def __hash__(self):
return id(self)
def set_limit(self, limit):
with self.lock:
self.limit = limit
if len(self.items) > self.limit:
extra = len(self.items) - self.limit
remove = tuple(self)[:extra]
for k in remove:
self._pop(k)
| 3,024 | Python | .py | 72 | 32.263889 | 92 | 0.599454 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,898 | __init__.py | kovidgoyal_calibre/src/calibre/gui2/library/__init__.py | #!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
DEFAULT_SORT = ('timestamp', False)
| 183 | Python | .py | 5 | 35 | 58 | 0.685714 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |
26,899 | notes.py | kovidgoyal_calibre/src/calibre/gui2/library/notes.py | #!/usr/bin/env python
# License: GPLv3 Copyright: 2023, Kovid Goyal <kovid at kovidgoyal.net>
import os
from functools import partial
from qt.core import (
QAbstractItemView,
QCheckBox,
QDialog,
QDialogButtonBox,
QFont,
QHBoxLayout,
QIcon,
QKeySequence,
QLabel,
QMenu,
QPushButton,
QSize,
QSplitter,
Qt,
QTimer,
QToolButton,
QTreeWidget,
QTreeWidgetItem,
QVBoxLayout,
QWidget,
pyqtSignal,
)
from calibre import sanitize_file_name
from calibre.db.backend import FTSQueryError
from calibre.db.cache import Cache
from calibre.gui2 import Application, choose_dir, error_dialog, gprefs
from calibre.gui2.dialogs.edit_category_notes import EditNoteDialog
from calibre.gui2.dialogs.show_category_note import Display
from calibre.gui2.viewer.widgets import ResultsDelegate, SearchBox
from calibre.gui2.widgets import BusyCursor
from calibre.gui2.widgets2 import Dialog, FlowLayout
from calibre.utils.localization import ngettext
def current_db() -> Cache:
from calibre.gui2.ui import get_gui
return (getattr(current_db, 'ans', None) or get_gui().current_db).new_api
class NotesResultsDelegate(ResultsDelegate):
add_ellipsis = True
emphasize_text = False
def result_data(self, result):
if not isinstance(result, dict):
return None, None, None, None, None
full_text = result['text'].replace('\n', ': ', 1)
parts = full_text.split('\x1d', 2)
before = after = ''
if len(parts) > 2:
before, text = parts[:2]
after = parts[2].replace('\x1d', '')
elif len(parts) == 2:
before, text = parts
else:
text = parts[0]
if len(parts) > 1 and before:
before = before.replace('\n', ': ', 1)
return False, before, text, after, False
class ResultsList(QTreeWidget):
current_result_changed = pyqtSignal(object)
note_edited = pyqtSignal(object, object)
export_requested = pyqtSignal()
def __init__(self, parent):
QTreeWidget.__init__(self, parent)
self.setHeaderHidden(True)
self.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.customContextMenuRequested.connect(self.show_context_menu)
self.delegate = NotesResultsDelegate(self)
self.setItemDelegate(self.delegate)
self.section_font = QFont(self.font())
self.itemDoubleClicked.connect(self.item_activated)
self.section_font.setItalic(True)
self.currentItemChanged.connect(self.current_item_changed)
self.number_of_results = 0
self.item_map = []
self.fi_map = {}
def update_item(self, field, item_id):
nd = current_db().notes_data_for(field, item_id)
if nd:
for category in (self.topLevelItem(i) for i in range(self.topLevelItemCount())):
for item in (category.child(c) for c in range(category.childCount())):
r = item.data(0, Qt.ItemDataRole.UserRole)
if r['id'] == nd['id']:
r['text'] = nd['searchable_text']
item.setData(0, Qt.ItemDataRole.UserRole, r)
return True
return False
def current_item_changed(self, current, previous):
if current is not None:
r = current.data(0, Qt.ItemDataRole.UserRole)
if isinstance(r, dict):
self.current_result_changed.emit(r)
else:
self.current_result_changed.emit(None)
def item_activated(self, item):
r = item.data(0, Qt.ItemDataRole.UserRole)
if isinstance(r, dict):
self.edit_note(item)
def selected_results(self):
for item in self.selectedItems():
r = item.data(0, Qt.ItemDataRole.UserRole)
if isinstance(r, dict):
yield r
def show_context_menu(self, pos):
m = QMenu(self)
item = self.itemAt(pos)
result = None
if item is not None:
result = item.data(0, Qt.ItemDataRole.UserRole)
if result is not None:
name = current_db().get_item_name(result['field'], result['item_id']) or ''
m.addAction(QIcon.ic('edit_input.png'), _('Edit notes for {}').format(name), partial(self.edit_note, item))
results = tuple(self.selected_results())
if len(results):
m.addAction(QIcon.ic('save.png'), _('Export selected'), self.export)
m.addSeparator()
m.addAction(_('Select all'), self.selectAll)
m.addAction(_('Select none'), self.clearSelection)
m.addSeparator()
m.addAction(QIcon.ic('plus.png'), _('Expand all'), self.expandAll)
m.addAction(QIcon.ic('minus.png'), _('Collapse all'), self.collapseAll)
m.exec(self.mapToGlobal(pos))
def export(self):
self.export_requested.emit()
def show_next(self, backwards=False):
item = self.currentItem()
if item is None:
return
i = int(item.data(0, Qt.ItemDataRole.UserRole + 1))
i += -1 if backwards else 1
i %= self.number_of_results
self.setCurrentItem(self.item_map[i])
def edit_note_for(self, field, item_id):
item = self.fi_map.get((field, item_id))
if item is not None:
self.edit_note(item)
def edit_note(self, item):
r = item.data(0, Qt.ItemDataRole.UserRole)
if isinstance(r, dict):
d = EditNoteDialog(r['field'], r['item_id'], current_db())
if d.exec() == QDialog.DialogCode.Accepted:
self.note_edited.emit(r['field'], r['item_id'])
def keyPressEvent(self, ev):
if ev.matches(QKeySequence.StandardKey.Delete):
self.delete_requested.emit()
ev.accept()
return
if ev.key() == Qt.Key.Key_F2:
item = self.currentItem()
if item:
self.edit_note(item)
ev.accept()
return
return QTreeWidget.keyPressEvent(self, ev)
@property
def tree_state(self):
ans = {'closed': set()}
item = self.currentItem()
if item is not None:
ans['current'] = item.data(0, Qt.ItemDataRole.UserRole)
for item in (self.topLevelItem(i) for i in range(self.topLevelItemCount())):
if not item.isExpanded():
ans['closed'].add(item.data(0, Qt.ItemDataRole.UserRole))
return ans
@tree_state.setter
def tree_state(self, state):
closed = state['closed']
for item in (self.topLevelItem(i) for i in range(self.topLevelItemCount())):
if item.data(0, Qt.ItemDataRole.UserRole) in closed:
item.setExpanded(False)
cur = state.get('current')
if cur is not None:
for item in self.item_map:
if item.data(0, Qt.ItemDataRole.UserRole) == cur:
self.setCurrentItem(item)
break
def set_results(self, results, emphasize_text):
self.clear()
self.delegate.emphasize_text = emphasize_text
self.number_of_results = 0
self.item_map = []
self.fi_map = {}
db = current_db()
fm = db.field_metadata
field_map = {f: {'title': fm[f].get('name') or f, 'matches': []} for f in db.field_supports_notes()}
for result in results:
field_map[result['field']]['matches'].append(result)
for field, entry in field_map.items():
if not entry['matches']:
continue
section = QTreeWidgetItem([entry['title']], 1)
section.setFlags(Qt.ItemFlag.ItemIsEnabled)
section.setFont(0, self.section_font)
section.setData(0, Qt.ItemDataRole.UserRole, field)
self.addTopLevelItem(section)
section.setExpanded(True)
for result in entry['matches']:
item = QTreeWidgetItem(section, [' '], 2)
self.item_map.append(item)
self.fi_map[(field, result['item_id'])] = item
item.setFlags(Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemNeverHasChildren)
item.setData(0, Qt.ItemDataRole.UserRole, result)
item.setData(0, Qt.ItemDataRole.UserRole + 1, self.number_of_results)
self.number_of_results += 1
if self.item_map:
self.setCurrentItem(self.item_map[0])
def sizeHint(self):
return QSize(500, 500)
class RestrictFields(QWidget):
restriction_changed = pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent)
self.l = l = FlowLayout(self)
l.setContentsMargins(0, 0, 0, 0)
self.restrict_label = QLabel(_('Restrict to:'))
self.restricted_fields = []
self.add_button = b = QToolButton(self)
b.setToolTip(_('Add categories to which to restrict results.\nWhen no categories are specified no restriction is in effect'))
b.setIcon(QIcon.ic('plus.png')), b.setText(_('Add')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
b.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
self.fields_menu = m = QMenu()
b.setMenu(m)
m.aboutToShow.connect(self.build_add_menu)
self.remove_button = b = QToolButton(self)
b.setIcon(QIcon.ic('minus.png')), b.setText(_('Remove')), b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
b.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
self.remove_fields_menu = m = QMenu()
b.setMenu(m)
m.aboutToShow.connect(self.build_remove_menu)
db = current_db()
fm = db.field_metadata
def field_name(field):
return fm[field].get('name') or field
self.field_names = {f:field_name(f) for f in db.field_supports_notes()}
self.field_labels = {f: QLabel(self.field_names[f], self) for f in sorted(self.field_names, key=self.field_names.get)}
for l in self.field_labels.values():
l.setVisible(False)
self.relayout()
def relayout(self):
for i in range(self.l.count()):
self.l.removeItem(self.l.itemAt(i))
for la in self.field_labels.values():
la.setVisible(False)
self.l.addWidget(self.restrict_label)
self.l.addWidget(self.add_button)
for field in self.restricted_fields:
w = self.field_labels[field]
w.setVisible(True)
self.l.addWidget(w)
self.remove_button.setVisible(bool(self.restricted_fields))
self.l.addWidget(self.remove_button)
self.l.update()
def build_add_menu(self):
m = self.fields_menu
m.clear()
for field in self.field_labels:
if field not in self.restricted_fields:
m.addAction(self.field_names[field], partial(self.add_field, field))
def build_remove_menu(self):
m = self.remove_fields_menu
m.clear()
for field in self.restricted_fields:
m.addAction(self.field_names[field], partial(self.remove_field, field))
def add_field(self, field):
self.restricted_fields.append(field)
self.relayout()
self.restriction_changed.emit()
def remove_field(self, field):
self.restricted_fields.remove(field)
self.relayout()
self.restriction_changed.emit()
class SearchInput(QWidget):
show_next_signal = pyqtSignal()
show_previous_signal = pyqtSignal()
search_changed = pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent)
self.l = l = QVBoxLayout(self)
l.setContentsMargins(0, 0, 0, 0)
h = QHBoxLayout()
l.addLayout(h)
self.search_box = sb = SearchBox(self)
sb.initialize('library-notes-browser-search-box')
sb.cleared.connect(self.cleared, type=Qt.ConnectionType.QueuedConnection)
sb.lineEdit().returnPressed.connect(self.search_changed)
sb.lineEdit().setPlaceholderText(_('Enter words to search for'))
h.addWidget(sb)
self.next_button = nb = QToolButton(self)
h.addWidget(nb)
nb.setFocusPolicy(Qt.FocusPolicy.NoFocus)
nb.setIcon(QIcon.ic('arrow-down.png'))
nb.clicked.connect(self.show_next)
nb.setToolTip(_('Find next match'))
self.prev_button = nb = QToolButton(self)
h.addWidget(nb)
nb.setFocusPolicy(Qt.FocusPolicy.NoFocus)
nb.setIcon(QIcon.ic('arrow-up.png'))
nb.clicked.connect(self.show_previous)
nb.setToolTip(_('Find previous match'))
self.restrict = r = RestrictFields(self)
r.restriction_changed.connect(self.search_changed)
l.addWidget(r)
@property
def current_query(self):
return {
'fts_engine_query': self.search_box.lineEdit().text().strip(),
'restrict_to_fields': tuple(self.restrict.restricted_fields),
'use_stemming': bool(self.parent().use_stemmer.isChecked()),
}
def cleared(self):
self.search_changed.emit()
def show_next(self):
self.show_next_signal.emit()
def show_previous(self):
self.show_previous_signal.emit()
class NoteDisplay(QWidget):
field = item_id = None
edit_requested = pyqtSignal(str, int)
def __init__(self, parent=None):
super().__init__(parent)
self.l = l = QVBoxLayout(self)
l.setContentsMargins(0, 0, 0, 0)
self.title = la = QLabel('')
l.addWidget(la)
la.setWordWrap(True)
self.html_display = hd = Display(self)
l.addWidget(hd)
self.edit_button = eb = QPushButton(QIcon.ic('edit_input.png'), _('Edit'))
eb.setFocusPolicy(Qt.FocusPolicy.NoFocus)
l.addWidget(eb)
eb.clicked.connect(self.edit)
eb.setVisible(False)
def edit(self):
if self.field and self.item_id:
self.edit_requested.emit(self.field, self.item_id)
def sizeHint(self):
return QSize(400, 500)
@property
def db(self):
return current_db()
def show_note(self, field='', item_id=0):
self.field, self.item_id = field, item_id
if field:
self.title.setText('<h2>{}</h2>'.format(self.db.get_item_name(field, item_id) or ''))
self.html_display.setHtml(self.db.notes_for(field, item_id))
self.edit_button.setVisible(True)
else:
self.title.setText('')
self.html_display.setHtml('')
self.edit_button.setVisible(False)
def current_result_changed(self, r):
if r is None:
self.show_note()
else:
self.show_note(r['field'], r['item_id'])
def refresh(self):
if self.field:
self.show_note(self.field, self.item_id)
class NotesBrowser(Dialog):
current_query = None
def __init__(self, parent=None):
super().__init__(_('Browse notes'), 'browse-notes-dialog', default_buttons=QDialogButtonBox.StandardButton.Close)
self.setWindowIcon(QIcon.ic('notes.png'))
def sizeHint(self):
return QSize(900, 600)
def setup_ui(self):
self.l = l = QVBoxLayout(self)
self.search_input = si = SearchInput(self)
si.search_changed.connect(self.search_changed)
l.addWidget(si)
self.splitter = s = QSplitter(self)
l.addWidget(s, stretch=100)
s.setChildrenCollapsible(False)
self.results_list = rl = ResultsList(self)
si.show_next_signal.connect(rl.show_next)
si.show_previous_signal.connect(partial(rl.show_next, backwards=True))
rl.note_edited.connect(self.note_edited)
s.addWidget(rl)
self.notes_display = nd = NoteDisplay(self)
rl.current_result_changed.connect(nd.current_result_changed)
rl.export_requested.connect(self.export_selected)
nd.edit_requested.connect(rl.edit_note_for)
s.addWidget(nd)
self.use_stemmer = us = QCheckBox(_('&Match on related words'))
us.setChecked(gprefs['browse_notes_use_stemmer'])
us.setToolTip('<p>' + _(
'With this option searching for words will also match on any related words (supported in several languages). For'
' example, in the English language: <i>correction</i> matches <i>correcting</i> and <i>corrected</i> as well'))
us.stateChanged.connect(lambda state: gprefs.set('browse_notes_use_stemmer', state != Qt.CheckState.Unchecked.value))
h = QHBoxLayout()
l.addLayout(h)
b = self.bb.addButton(_('Export'), QDialogButtonBox.ButtonRole.ActionRole)
b.setIcon(QIcon.ic('save.png'))
b.clicked.connect(self.export_selected)
b.setToolTip(_('Export the selected notes as HTML files'))
h.addWidget(us), h.addStretch(10), h.addWidget(self.bb)
from calibre.gui2.ui import get_gui
gui = get_gui()
if gui is not None:
b = self.bb.addButton(_('Search books'), QDialogButtonBox.ButtonRole.ActionRole)
b.setToolTip(_('Search the calibre library for books in the currently selected categories'))
b.clicked.connect(self.search_books)
b.setIcon(QIcon.ic('search.png'))
QTimer.singleShot(0, self.do_find)
def search_books(self):
vals = []
for item in self.results_list.selectedItems():
r = item.data(0, Qt.ItemDataRole.UserRole)
if isinstance(r, dict):
ival = r['text'].split('\n', 1)[0].replace('"', '\\"')
vals.append(ival)
if vals:
search_expression = ' OR '.join(f'{r["field"]}:"={ival}"' for ival in vals)
from calibre.gui2.ui import get_gui
get_gui().search.set_search_string(search_expression)
def export_selected(self):
results = tuple(self.results_list.selected_results())
if not results:
return error_dialog(self, _('No results selected'), _(
'No results selected, nothing to export'), show=True)
path = choose_dir(self, 'export-notes-dir', ngettext(
'Choose folder for exported note', 'Choose folder for {} exported notes', len(results)).format(len(results)))
if not path:
return
with BusyCursor():
db = current_db()
for r in results:
html = db.export_note(r['field'], r['item_id'])
item_val = db.get_item_name(r['field'], r['item_id'])
if item_val:
fname = sanitize_file_name(item_val) + '.html'
with open(os.path.join(path, fname), 'wb') as f:
f.write(html.encode('utf-8'))
def note_edited(self, field, item_id):
from calibre.gui2.ui import get_gui
self.notes_display.refresh()
self.results_list.update_item(field, item_id)
gui = get_gui()
if gui is not None:
gui.do_field_item_value_changed()
def search_changed(self):
if self.search_input.current_query != self.current_query:
self.do_find()
def do_find(self, backwards=False):
q = self.search_input.current_query
if q == self.current_query:
self.results_list.show_next(backwards)
return
try:
with BusyCursor():
results = current_db().search_notes(
highlight_start='\x1d', highlight_end='\x1d', snippet_size=64, **q
)
self.results_list.set_results(results, bool(q['fts_engine_query']))
self.current_query = q
except FTSQueryError as err:
return error_dialog(self, _('Invalid search expression'), '<p>' + _(
'The search expression: {0} is invalid. The search syntax used is the'
' SQLite Full text Search Query syntax, <a href="{1}">described here</a>.').format(
err.query, 'https://www.sqlite.org/fts5.html#full_text_query_syntax'),
det_msg=str(err), show=True)
def keyPressEvent(self, ev):
k = ev.key()
if k in (Qt.Key.Key_Enter, Qt.Key.Key_Return): # prevent enter from closing dialog
ev.ignore()
return
return super().keyPressEvent(ev)
if __name__ == '__main__':
from calibre.library import db
app = Application([])
current_db.ans = db(os.path.expanduser('~/test library'))
br = NotesBrowser()
br.exec()
del br
del app
| 20,781 | Python | .py | 477 | 33.9413 | 133 | 0.6147 | kovidgoyal/calibre | 19,243 | 2,250 | 4 | GPL-3.0 | 9/5/2024, 5:13:50 PM (Europe/Amsterdam) |