This commit is contained in:
Kovid Goyal
2026-02-13 21:57:17 +05:30
parent eb43668e76
commit 6fd2300a48
108 changed files with 194 additions and 201 deletions
+1 -1
View File
@@ -57,7 +57,7 @@ class BuenosAiresHerald(BasicNewsRecipe):
for feedobj in lfeeds:
feedtitle, feedurl = feedobj
self.report_progress(0, ('Fetching feed') + ' %s...' %
(feedtitle if feedtitle else feedurl))
(feedtitle or feedurl))
articles = []
soup = self.index_to_soup(feedurl)
for item in soup.findAll('div', attrs={'class': 'nota_texto_seccion'}):
+1 -1
View File
@@ -43,7 +43,7 @@ class BookforumMagazine(BasicNewsRecipe):
def parse_index(self):
soup = self.index_to_soup(
_issue_url if _issue_url else 'https://www.bookforum.com/print'
_issue_url or 'https://www.bookforum.com/print'
)
meta_ele = soup.find('meta', property='og:title')
if meta_ele:
+1 -1
View File
@@ -52,7 +52,7 @@ class ElMercurio(BasicNewsRecipe):
for feedobj in lfeeds:
feedtitle, feedurl = feedobj
self.report_progress(0, _('Fetching feed') + ' %s...' %
(feedtitle if feedtitle else feedurl))
(feedtitle or feedurl))
articles = []
soup = self.index_to_soup(feedurl)
arts = soup.find('div', attrs={'id': 'caja_listado_noticia_todas'})
+1 -1
View File
@@ -91,7 +91,7 @@ class InstapaperRecipe(BasicNewsRecipe):
lfeeds = self.get_feeds()
for feedobj in lfeeds:
feedtitle, feedurl = feedobj
self.report_progress(0, 'Fetching feed' + ' %s...' % (feedtitle if feedtitle else feedurl))
self.report_progress(0, 'Fetching feed' + ' %s...' % (feedtitle or feedurl))
articles = []
soup = self.index_to_soup(feedurl)
for item in soup.findAll('a', attrs={'class': 'article_title'}):
+1 -1
View File
@@ -69,7 +69,7 @@ class Veintitres(BasicNewsRecipe):
self.report_progress(
0,
_('Fetching feed') + ' %s...' %
(feedtitle if feedtitle else feedurl)
(feedtitle or feedurl)
)
articles = []
soup = self.index_to_soup(feedurl)
+1 -1
View File
@@ -58,7 +58,7 @@ class ThePrint(BasicNewsRecipe):
ans[current_section].append({'title': title, 'url': url, 'description': desc})
ret = []
for sec in secs:
if sec in ('On Camera',):
if sec == 'On Camera':
continue
arts = ans[sec]
if arts:
+1 -1
View File
@@ -157,7 +157,7 @@ class UpgradeSourceCode(Command):
files = []
for f in os.listdir(os.path.dirname(os.path.abspath(__file__))):
q = os.path.join('setup', f)
if f.endswith('.py') and f not in ('linux-installer.py',) and not os.path.isdir(q):
if f.endswith('.py') and f != 'linux-installer.py' and not os.path.isdir(q):
files.append(q)
for path in checkable_python_files(self.SRC):
q = path.replace(os.sep, '/')
+1 -1
View File
@@ -39,7 +39,7 @@ def api_url(path: str = '', use_api_url: str | None = None) -> str:
base = (pref('api_url') if use_api_url is None else use_api_url) or LMStudioAI.DEFAULT_URL
purl = urlparse(base)
# LM Studio typically mounts endpoints under /v1
base_path = purl.path if purl.path else '/v1'
base_path = purl.path or '/v1'
if not base_path.endswith('/v1'):
base_path = posixpath.join(base_path, 'v1')
+1 -1
View File
@@ -110,7 +110,7 @@ def get_data_as_dict(self, prefix=None, authors_as_string=False, ids=None, conve
x['id'] = db_id
x['formats'] = []
isbn = self.isbn(db_id, index_is_id=True)
x['isbn'] = isbn if isbn else ''
x['isbn'] = isbn or ''
if not x['authors']:
x['authors'] = _('Unknown')
x['authors'] = [i.replace('|', ',') for i in x['authors'].split(',')]
+1 -2
View File
@@ -70,8 +70,7 @@ class Table:
# Legacy
self.unserialize = lambda x: x.replace('|', ',') if x else ''
self.serialize = lambda x: x.replace(',', '|')
self.link_table = (link_table if link_table else
'books_{}_link'.format(self.metadata['table']))
self.link_table = (link_table or 'books_{}_link'.format(self.metadata['table']))
if self.supports_notes and dt == 'rating': # custom ratings table
self.supports_notes = False
+1 -1
View File
@@ -31,7 +31,7 @@ def single_text(x):
if not isinstance(x, str):
x = x.decode(preferred_encoding, 'replace')
x = x.strip()
return x if x else None
return x or None
series_index_pat = re.compile(r'(.*)\s+\[([.0-9]+)\]$')
+1 -1
View File
@@ -50,7 +50,7 @@ class JETBOOK(USBMS):
fileext = os.path.splitext(os.path.basename(fname))[1]
if fileext.lower() not in ('txt', 'pdf', 'fb2'):
return fname
title = mi.title if mi.title else 'Unknown'
title = mi.title or 'Unknown'
title = title.replace(' ', '_')
au = mi.format_authors()
if not au:
+1 -1
View File
@@ -121,7 +121,7 @@ class PALADIN(USBMS):
time_offsets[offset] = time_offsets[offset] + 1
try:
device_offset = max(time_offsets, key=lambda a: time_offsets.get(a))
device_offset = max(time_offsets, key=time_offsets.get)
debug_print(f'Device Offset: {device_offset} ms')
self.device_offset = device_offset
except ValueError:
+1 -1
View File
@@ -658,7 +658,7 @@ class XMLCache:
record.set('size', clean(str(os.stat(path).st_size)))
except Exception:
record.set('size', '0')
title = book.title if book.title else _('Unknown')
title = book.title or _('Unknown')
record_set('title', title)
ts = book.title_sort
if not ts:
+1 -1
View File
@@ -208,7 +208,7 @@ class PRST1(USBMS):
time_offsets[offset] = time_offsets[offset] + 1
try:
device_offset = max(time_offsets, key=lambda a: time_offsets.get(a))
device_offset = max(time_offsets, key=time_offsets.get)
debug_print(f'Device Offset: {device_offset} ms')
self.device_offset = device_offset
except ValueError:
+1 -2
View File
@@ -46,8 +46,7 @@ class DeviceConfig:
@classmethod
def _default_save_template(cls):
from calibre.library.save_to_disk import config
return cls.SAVE_TEMPLATE if cls.SAVE_TEMPLATE else \
config().parse().send_template
return cls.SAVE_TEMPLATE or config().parse().send_template
@classmethod
def _config_base_name(cls):
@@ -260,7 +260,7 @@ class HTMLInput(InputFormatPlugin):
link_ = link_.lstrip('/')
base = self.root_dir_for_absolute_links
try:
l = Link(link_, base if base else os.getcwd())
l = Link(link_, base or os.getcwd())
except Exception:
self.log.exception(f'Failed to process link: {link_!r}')
return None, None
+2 -2
View File
@@ -429,9 +429,9 @@ def book_designer_rules():
lambda match : '<span style="page-break-after:always"> </span>'),
# Create header tags
(re.compile(r'<h2[^><]*?id=BookTitle[^><]*?(align=)*(?(1)(\w+))*[^><]*?>[^><]*?</h2>', re.IGNORECASE),
lambda match : '<h1 id="BookTitle" align="{}">{}</h1>'.format(match.group(2) if match.group(2) else 'center', match.group(3))),
lambda match : '<h1 id="BookTitle" align="{}">{}</h1>'.format(match.group(2) or 'center', match.group(3))),
(re.compile(r'<h2[^><]*?id=BookAuthor[^><]*?(align=)*(?(1)(\w+))*[^><]*?>[^><]*?</h2>', re.IGNORECASE),
lambda match : '<h2 id="BookAuthor" align="{}">{}</h2>'.format(match.group(2) if match.group(2) else 'center', match.group(3))),
lambda match : '<h2 id="BookAuthor" align="{}">{}</h2>'.format(match.group(2) or 'center', match.group(3))),
(re.compile(r'<span[^><]*?id=title[^><]*?>(.*?)</span>', re.IGNORECASE|re.DOTALL),
lambda match : f'<h2 class="title">{match.group(1)}</h2>'),
(re.compile(r'<span[^><]*?id=subtitle[^><]*?>(.*?)</span>', re.IGNORECASE|re.DOTALL),
+1 -1
View File
@@ -166,7 +166,7 @@ def sony_metadata(oeb):
atitle = btitle + ' ' + str(d)
d += 1
auth = article.author if article.author else ''
auth = article.author or ''
desc = section.description
if not desc:
desc = ''
+1 -1
View File
@@ -274,7 +274,7 @@ class OEB2HTMLInlineCSSizer(OEB2HTML):
attribs = elem.attrib
style_a = f'{style}'
style_a = style_a if style_a else ''
style_a = style_a or ''
if tag == 'body':
# Change the body to a div so we can merge multiple files.
tag = 'div'
+4 -4
View File
@@ -167,9 +167,9 @@ class HTMLConverter:
lambda match : '<span style="page-break-after:always"> </span>'),
# Create header tags
(re.compile(r'<h2[^><]*?id=BookTitle[^><]*?(align=)*(?(1)(\w+))*[^><]*?>[^><]*?</h2>', re.IGNORECASE),
lambda match : '<h1 id="BookTitle" align="{}">{}</h1>'.format(match.group(2) if match.group(2) else 'center', match.group(3))),
lambda match : '<h1 id="BookTitle" align="{}">{}</h1>'.format(match.group(2) or 'center', match.group(3))),
(re.compile(r'<h2[^><]*?id=BookAuthor[^><]*?(align=)*(?(1)(\w+))*[^><]*?>[^><]*?</h2>', re.IGNORECASE),
lambda match : '<h2 id="BookAuthor" align="{}">{}</h2>'.format(match.group(2) if match.group(2) else 'center', match.group(3))),
lambda match : '<h2 id="BookAuthor" align="{}">{}</h2>'.format(match.group(2) or 'center', match.group(3))),
(re.compile(r'<span[^><]*?id=title[^><]*?>(.*?)</span>', re.IGNORECASE|re.DOTALL),
lambda match : f'<h2 class="title">{match.group(1)}</h2>'),
(re.compile(r'<span[^><]*?id=subtitle[^><]*?>(.*?)</span>', re.IGNORECASE|re.DOTALL),
@@ -683,7 +683,7 @@ class HTMLConverter:
if not item.fragment and item.abspath in self.tops:
self.book.addTocEntry(ascii_text, self.tops[item.abspath])
elif item.abspath:
url = item.abspath+(item.fragment if item.fragment else '')
url = item.abspath+(item.fragment or '')
if url in self.targets:
self.book.addTocEntry(ascii_text, self.targets[url])
@@ -1715,7 +1715,7 @@ class HTMLConverter:
if tag.has_attr('color'):
tag_css['color'] = tag['color']
self.process_children(tag, tag_css, tag_pseudo_css)
elif tagname in ['br']:
elif tagname == 'br':
self.line_break()
self.previous_text = '\n'
elif tagname in ['hr', 'tr']: # tr needed for nested tables
+2 -2
View File
@@ -191,8 +191,8 @@ class TextBlock(etree.XSLTExtension):
pidx = gp.index(p)
children = list(p)[idx:]
t = children[-1].tail
t = t if t else ''
children[-1].tail = t + (p.tail if p.tail else '')
t = t or ''
children[-1].tail = t + (p.tail or '')
p.tail = ''
pattrib = dict(**p.attrib) if p.tag == 'Span' else {}
for child in children:
+1 -1
View File
@@ -1695,7 +1695,7 @@ class Plot(LrsSimpleChar1, LrsContainer):
return elem
def toLrfContainer(self, lrfWriter, parent):
adj = self.adjustment if self.adjustment else 'bottom'
adj = self.adjustment or 'bottom'
params = (int(self.xsize), int(self.ysize), int(self.obj.objId),
Plot.ADJUSTMENT_VALUES[adj])
parent.appendLrfTag(LrfTag('Plot', params))
+1 -1
View File
@@ -56,7 +56,7 @@ def get_metadata(stream, extract_cover=True):
mi.cover_data = get_cover(pheader, hr)
if not mi.title:
mi.title = pheader.title if pheader.title else _('Unknown')
mi.title = pheader.title or _('Unknown')
return mi
+1 -1
View File
@@ -315,7 +315,7 @@ class MetadataHtmlTest(unittest.TestCase):
<!-- TAGS="tag d" -->
'''
if test in {'comment_multi'}:
if test == 'comment_multi':
raw += b'''\
<!-- TITLE="Another Comment Tag &amp;amp; Title &#9400;" -->
<!-- AUTHOR="John Quincy Adams" -->
+1 -1
View File
@@ -262,7 +262,7 @@ class MetadataUpdater:
new_record0.write(exth)
if self.encryption_type != 0:
new_record0.write(self.drm_block)
new_record0.write(new_title if new_title else title_in_file)
new_record0.write(new_title or title_in_file)
# Pad to a 4-byte boundary
trail = len(new_record0.getvalue()) % 4
+2 -2
View File
@@ -420,7 +420,7 @@ class Guide(ResourceCollection): # {{{
class MetadataField:
def __init__(self, name, is_dc=True, formatter=None, none_is=None,
renderer=lambda x: str(x)):
renderer=str):
self.name = name
self.is_dc = is_dc
self.formatter = formatter
@@ -1536,7 +1536,7 @@ class OPFCreator(Metadata):
metadata = M.metadata()
a = metadata.append
role = {}
a(DC_ELEM('title', self.title if self.title else _('Unknown'),
a(DC_ELEM('title', self.title or _('Unknown'),
opf_attrs=role))
for i, author in enumerate(self.authors):
fa = {'role':'aut'}
@@ -181,7 +181,7 @@ class ISBNMerge:
# First title/author
groups = {}
for result in self.results:
title = lower(result.title if result.title else '')
title = lower(result.title or '')
key = (title, tuple(lower(x) for x in result.authors))
if key not in groups:
groups[key] = []
+1 -2
View File
@@ -516,8 +516,7 @@ class FontRecord: # {{{
if self.font['err']:
raise ValueError('Failed to read font record: {} Headers: {}'.format(
self.font['err'], self.font['headers']))
self.payload = (self.font['font_data'] if self.font['font_data'] else
self.font['raw_data'])
self.payload = (self.font['font_data'] or self.font['raw_data'])
self.name = '{}.{}'.format(name, self.font['ext'])
def dump(self, folder):
+1 -2
View File
@@ -184,8 +184,7 @@ class MOBIFile:
if font['err']:
raise ValueError('Failed to read font record: {} Headers: {}'.format(
font['err'], font['headers']))
payload = (font['font_data'] if font['font_data'] else
font['raw_data'])
payload = (font['font_data'] or font['raw_data'])
prefix, ext = 'fonts', font['ext']
elif sig == b'CONT':
if payload == b'CONTBOUNDARY':
+2 -3
View File
@@ -173,7 +173,7 @@ class Mobi8Reader:
raw_ml = self.mobi6_reader.mobi_html
self.flows = []
self.flowinfo = []
ft = self.flow_table if self.flow_table else [(0, len(raw_ml))]
ft = self.flow_table or [(0, len(raw_ml))]
# now split the raw_ml into its flow pieces
for start, end in ft:
@@ -434,8 +434,7 @@ class Mobi8Reader:
if font['headers']:
self.log.debug('Font record headers: {}'.format(font['headers']))
with open(href.replace('/', os.sep), 'wb') as f:
f.write(font['font_data'] if font['font_data'] else
font['raw_data'])
f.write(font['font_data'] or font['raw_data'])
if font['encrypted']:
self.encrypted_fonts.append(href)
elif typ == b'CONT':
+2 -3
View File
@@ -288,7 +288,7 @@ class MobiWriter:
# 0x58 - 0x5b : Format version
# 0x5c - 0x5f : First image record number
record0.write(pack(b'>II',
6, first_image_record if first_image_record else len(self.records)))
6, first_image_record or len(self.records)))
# 0x60 - 0x63 : First HUFF/CDIC record number
# 0x64 - 0x67 : Number of HUFF/CDIC records
@@ -400,8 +400,7 @@ class MobiWriter:
self.records.append(self.kf8.record0)
self.records.extend(self.kf8.records[1:])
first_image_record = (first_image_record if first_image_record else
len(self.records))
first_image_record = (first_image_record or len(self.records))
header_fields = {k:getattr(self.kf8, k) for k in HEADER_FIELDS}
+1 -1
View File
@@ -116,7 +116,7 @@ class KF8Writer:
ref = urlnormalize(item.abshref(oref))
idx = self.resources.item_map.get(ref, None)
if idx is not None:
is_image = self.resources.records[idx-1][:4] not in {b'FONT'}
is_image = self.resources.records[idx-1][:4] != b'FONT'
idx = to_ref(idx)
if is_image:
self.used_images.add(ref)
+2 -2
View File
@@ -266,7 +266,7 @@ class Stylizer:
log=logging.getLogger('calibre.css'))
for elem in style_tags:
if (elem.tag in (XHTML('style'), SVG('style')) and elem.get('type', CSS_MIME) in OEB_STYLES and media_ok(elem.get('media'))):
text = elem.text if elem.text else ''
text = elem.text or ''
for x in elem:
t = getattr(x, 'text', None)
if t:
@@ -614,7 +614,7 @@ class Style:
self._bgcolor = False
else:
self._bgcolor = col
return self._bgcolor if self._bgcolor else None
return self._bgcolor or None
@property
def fontSize(self):
+2 -2
View File
@@ -312,9 +312,9 @@ def render_jacket(mi, output_profile,
rating = get_rating(mi.rating, output_profile.ratings_char, output_profile.empty_ratings_char)
tags = Tags((mi.tags if mi.tags else alt_tags), output_profile)
tags = Tags((mi.tags or alt_tags), output_profile)
comments = mi.comments if mi.comments else alt_comments
comments = mi.comments or alt_comments
comments = comments.strip()
if comments:
comments = comments_to_html(comments)
+4 -4
View File
@@ -200,7 +200,7 @@ class Split:
return url
if href in self.map:
anchor_map = self.map[href]
nhref = anchor_map[frag if frag else None]
nhref = anchor_map[frag or None]
nhref = self.current_item.relhref(nhref)
if frag:
nhref = '#'.join((unquote(nhref), frag))
@@ -478,7 +478,7 @@ class FlowSplitter:
for ref in self.oeb.guide.values():
href, frag = urldefrag(ref.href)
if href == self.item.href:
nhref = self.anchor_map[frag if frag else None]
nhref = self.anchor_map[frag or None]
if frag:
nhref = '#'.join((nhref, frag))
ref.href = nhref
@@ -487,7 +487,7 @@ class FlowSplitter:
if toc.href:
href, frag = urldefrag(toc.href)
if href == self.item.href:
nhref = self.anchor_map[frag if frag else None]
nhref = self.anchor_map[frag or None]
if frag:
nhref = '#'.join((nhref, frag))
toc.href = nhref
@@ -501,7 +501,7 @@ class FlowSplitter:
for page in self.oeb.pages:
href, frag = urldefrag(page.href)
if href == self.item.href:
nhref = self.anchor_map[frag if frag else None]
nhref = self.anchor_map[frag or None]
if frag:
nhref = '#'.join((nhref, frag))
page.href = nhref
@@ -74,8 +74,7 @@ class DetectStructure:
regexp = re.compile(opts.toc_filter)
for node in list(self.oeb.toc.iter()):
if not node.title or regexp.search(node.title) is not None:
self.log('Filtering', node.title if node.title else
'empty node', 'from TOC')
self.log('Filtering', node.title or 'empty node', 'from TOC')
self.oeb.toc.remove(node)
if opts.page_breaks_before is not None:
+1 -1
View File
@@ -25,7 +25,7 @@ class Writer(FormatWriter):
def write_content(self, oeb_book, out_stream, metadata=None):
from calibre.ebooks.compression.palmdoc import compress_doc
title = self.opts.title if self.opts.title else oeb_book.metadata.title[0].value if oeb_book.metadata.title != [] else _('Unknown')
title = self.opts.title or (oeb_book.metadata.title[0].value if oeb_book.metadata.title != [] else _('Unknown'))
txt_records, txt_length = self._generate_text(oeb_book)
header_record = self._header_record(txt_length, len(txt_records))
+1 -1
View File
@@ -24,7 +24,7 @@ class Writer(FormatWriter):
self.log = log
def write_content(self, oeb_book, out_stream, metadata=None):
title = self.opts.title if self.opts.title else oeb_book.metadata.title[0].value if oeb_book.metadata.title != [] else _('Unknown')
title = self.opts.title or (oeb_book.metadata.title[0].value if oeb_book.metadata.title != [] else _('Unknown'))
txt_records, txt_length = self._generate_text(oeb_book)
+1 -1
View File
@@ -341,7 +341,7 @@ class RequestInterceptor(QWebEngineUrlRequestInterceptor):
request_info.block(True)
return
qurl = request_info.requestUrl()
if qurl.scheme() not in (FAKE_PROTOCOL,):
if qurl.scheme() != FAKE_PROTOCOL:
self.log.warn(f'Blocking URL request {qurl.toString()} as it is not for a resource in the book')
request_info.block(True)
return
+1 -1
View File
@@ -38,7 +38,7 @@ class RequestInterceptor(QWebEngineUrlRequestInterceptor):
request_info.block(True)
return
qurl = request_info.requestUrl()
if qurl.scheme() not in (FAKE_PROTOCOL,):
if qurl.scheme() != FAKE_PROTOCOL:
default_log.warn(f'Blocking URL request {qurl.toString()} as it is not for a resource related to the HTML file being rendered')
request_info.block(True)
return
+2 -2
View File
@@ -234,12 +234,12 @@ class InterfaceAction(QObject):
ma.triggered.connect(action.trigger)
for a in ((action, ma) if attr == 'qaction' else (action,)):
a.setAutoRepeat(self.auto_repeat)
text = tooltip if tooltip else text
text = tooltip or text
a.setToolTip(text)
a.setStatusTip(text)
a.setWhatsThis(text)
shortcut_action = action
desc = tooltip if tooltip else None
desc = tooltip or None
if attr == 'qaction':
shortcut_action = ma
if shortcut is not None:
+2 -2
View File
@@ -553,10 +553,10 @@ class ChooseLibraryAction(InterfaceAction):
restrictions.insert(0, '')
for vl in restrictions:
if vl == vl_at_startup:
self.vl_to_apply_menu.addAction(QIcon.ic('ok.png'), vl if vl else _('No Virtual library'),
self.vl_to_apply_menu.addAction(QIcon.ic('ok.png'), vl or _('No Virtual library'),
Dispatcher(partial(self.change_vl_at_startup_requested, vl)))
else:
self.vl_to_apply_menu.addAction(vl if vl else _('No Virtual library'),
self.vl_to_apply_menu.addAction(vl or _('No Virtual library'),
Dispatcher(partial(self.change_vl_at_startup_requested, vl)))
# Allow the cloned actions in the OS X global menubar to update
for a in (self.qaction, self.menuless_qaction):
+1 -1
View File
@@ -237,7 +237,7 @@ class MarkBooksAction(InterfaceActionWithLibraryDrop):
if dialog.exec_() != QDialog.DialogCode.Accepted:
return
txt = dialog.text()
txt = txt if txt else 'true'
txt = txt or 'true'
db = self.gui.current_db
mids = db.data.marked_ids.copy()
for book_id in book_ids:
+24 -24
View File
@@ -350,10 +350,10 @@ class PluginWidget(QWidget, Ui_Form):
for opt in self.OPTION_FIELDS:
c_name, c_def, c_type = opt
opt_value = gprefs.get(self.name + '_' + c_name, c_def)
if c_type in ['check_box']:
if c_type == 'check_box':
getattr(self, c_name).setChecked(eval(str(opt_value)))
getattr(self, c_name).clicked.connect(partial(self.settings_changed, c_name))
elif c_type in ['combo_box']:
elif c_type == 'combo_box':
if opt_value is None:
index = 0
if c_name == 'genre_source_field':
@@ -368,13 +368,13 @@ class PluginWidget(QWidget, Ui_Form):
getattr(self, c_name).setCurrentIndex(index)
if c_name != 'preset_field':
getattr(self, c_name).currentIndexChanged.connect(partial(self.settings_changed, c_name))
elif c_type in ['line_edit']:
getattr(self, c_name).setText(opt_value if opt_value else '')
elif c_type == 'line_edit':
getattr(self, c_name).setText(opt_value or '')
getattr(self, c_name).editingFinished.connect(partial(self.settings_changed, c_name))
elif c_type in ['radio_button'] and opt_value is not None:
elif c_type == 'radio_button' and opt_value is not None:
getattr(self, c_name).setChecked(opt_value)
getattr(self, c_name).clicked.connect(partial(self.settings_changed, c_name))
elif c_type in ['spin_box']:
elif c_type == 'spin_box':
getattr(self, c_name).setValue(float(opt_value))
getattr(self, c_name).valueChanged.connect(partial(self.settings_changed, c_name))
if c_type == 'table_widget':
@@ -480,13 +480,13 @@ class PluginWidget(QWidget, Ui_Form):
if c_type in ['check_box', 'radio_button']:
opt_value = getattr(self, c_name).isChecked()
elif c_type in ['combo_box']:
elif c_type == 'combo_box':
opt_value = str(getattr(self, c_name).currentText()).strip()
elif c_type in ['line_edit']:
elif c_type == 'line_edit':
opt_value = str(getattr(self, c_name).text()).strip()
elif c_type in ['spin_box']:
elif c_type == 'spin_box':
opt_value = str(getattr(self, c_name).value())
elif c_type in ['table_widget']:
elif c_type == 'table_widget':
if c_name == 'prefix_rules_tw':
opt_value = self.prefix_rules_table.get_data()
prefix_rules_processed = True
@@ -652,11 +652,11 @@ class PluginWidget(QWidget, Ui_Form):
opt_value = options[c_name]
else:
continue
if c_type in ['check_box']:
if c_type == 'check_box':
getattr(self, c_name).setChecked(eval(str(opt_value)))
if c_name == 'generate_genres':
self.genre_source_field.setEnabled(eval(str(opt_value)))
elif c_type in ['combo_box']:
elif c_type == 'combo_box':
if opt_value is None:
index = 0
if c_name == 'genre_source_field':
@@ -669,11 +669,11 @@ class PluginWidget(QWidget, Ui_Form):
elif c_name == 'genre_source_field':
index = self.genre_source_field.findText(_('Tags'))
getattr(self, c_name).setCurrentIndex(index)
elif c_type in ['line_edit']:
getattr(self, c_name).setText(opt_value if opt_value else '')
elif c_type in ['radio_button'] and opt_value is not None:
elif c_type == 'line_edit':
getattr(self, c_name).setText(opt_value or '')
elif c_type == 'radio_button' and opt_value is not None:
getattr(self, c_name).setChecked(opt_value)
elif c_type in ['spin_box']:
elif c_type == 'spin_box':
getattr(self, c_name).setValue(float(opt_value))
if c_type == 'table_widget':
if c_name == 'exclusion_rules_tw':
@@ -765,15 +765,15 @@ class PluginWidget(QWidget, Ui_Form):
if c_type in ['check_box', 'radio_button']:
opt_value = getattr(self, c_name).isChecked()
elif c_type in ['combo_box']:
elif c_type == 'combo_box':
if c_name == 'preset_field':
continue
opt_value = str(getattr(self, c_name).currentText()).strip()
elif c_type in ['line_edit']:
elif c_type == 'line_edit':
opt_value = str(getattr(self, c_name).text()).strip()
elif c_type in ['spin_box']:
elif c_type == 'spin_box':
opt_value = str(getattr(self, c_name).value())
elif c_type in ['table_widget']:
elif c_type == 'table_widget':
if c_name == 'prefix_rules_tw':
opt_value = self.prefix_rules_table.get_data()
prefix_rules_processed = True
@@ -1024,7 +1024,7 @@ class GenericRulesTable(QTableWidget):
self.select_and_scroll_to_row(first_sel_row - 1)
def enabled_state_changed(self, row, col):
if col in [self.COLUMNS['ENABLED']['ordinal']]:
if col == self.COLUMNS['ENABLED']['ordinal']:
self.select_and_scroll_to_row(row)
self.settings_changed('enabled_state_changed')
if self.DEBUG:
@@ -1165,11 +1165,11 @@ class GenericRulesTable(QTableWidget):
values = self.db.all_custom(self.db.field_metadata.key_to_label(
self.eligible_custom_fields[str(source_field)]['field']))
values = sorted(values, key=sort_key)
elif self.eligible_custom_fields[str(source_field)]['datatype'] in ['bool']:
elif self.eligible_custom_fields[str(source_field)]['datatype'] == 'bool':
values = [_('True'),_('False'),_('unspecified')]
elif self.eligible_custom_fields[str(source_field)]['datatype'] in ['composite']:
elif self.eligible_custom_fields[str(source_field)]['datatype'] == 'composite':
values = [_('any value'),_('unspecified')]
elif self.eligible_custom_fields[str(source_field)]['datatype'] in ['datetime']:
elif self.eligible_custom_fields[str(source_field)]['datatype'] == 'datetime':
values = [_('any date'),_('unspecified')]
values_combo = ComboBox(self, values, pattern)
+1 -1
View File
@@ -894,7 +894,7 @@ class EditorWidget(QTextEdit, LineEditECM): # {{{
if data_dir:
path = os.path.relpath(path, base).replace(os.sep, '/')
d.url.setText(path)
b.clicked.connect(lambda: cf())
b.clicked.connect(cf)
d.brdf = b = QPushButton(_('&Data file'))
b.clicked.connect(lambda: cf(True))
b.setToolTip(_('A relative link to a data file associated with this book'))
+3 -3
View File
@@ -189,9 +189,9 @@ class Widget(QWidget):
elif isinstance(g, QCheckBox):
return bool(g.isChecked())
elif isinstance(g, XPathEdit):
return g.xpath if g.xpath else None
return g.xpath or None
elif isinstance(g, RegexEdit):
return g.regex if g.regex else None
return g.regex or None
else:
raise Exception(f"Can't get value from {type(g)}")
@@ -261,7 +261,7 @@ class Widget(QWidget):
elif isinstance(g, QCheckBox):
g.setCheckState(Qt.CheckState.Checked if bool(val) else Qt.CheckState.Unchecked)
elif isinstance(g, (XPathEdit, RegexEdit)):
g.edit.setText(val if val else '')
g.edit.setText(val or '')
else:
raise Exception(f"Can't set value {val!r} in {g.objectName()!s}")
self.post_set_value(g, val)
+4 -4
View File
@@ -90,15 +90,15 @@ class MetadataWidget(Widget, Ui_Form):
mi = self.db.get_metadata(self.book_id, index_is_id=True)
self.title.setText(mi.title), self.title.home(False)
self.publisher.show_initial_value(mi.publisher if mi.publisher else '')
self.publisher.show_initial_value(mi.publisher or '')
self.publisher.home(False)
self.author_sort.setText(mi.author_sort if mi.author_sort else '')
self.author_sort.setText(mi.author_sort or '')
self.author_sort.home(False)
self.tags.setText(', '.join(mi.tags if mi.tags else []))
self.tags.setText(', '.join(mi.tags or []))
self.tags.update_items_cache(self.db.new_api.all_field_names('tags'))
self.tags.home(False)
self.comment.html = comments_to_html(mi.comments) if mi.comments else ''
self.series.show_initial_value(mi.series if mi.series else '')
self.series.show_initial_value(mi.series or '')
self.series.home(False)
if mi.series_index is not None:
try:
@@ -267,7 +267,7 @@ class SearchAndReplaceWidget(Widget, Ui_Form):
if name in getattr(recs, 'disabled_options', []):
self.search_replace.setDisabled(True)
elif name.startswith('sr'):
legacy[name] = val if val else ''
legacy[name] = val or ''
else:
rest[name] = val
+1 -2
View File
@@ -1118,8 +1118,7 @@ class DeviceMixin: # {{{
func = {UserFeedback.ERROR:error_dialog,
UserFeedback.WARNING:warning_dialog,
UserFeedback.INFO:info_dialog}[ex.level]
return func(self, _('Failed'), ex.msg, det_msg=ex.details if
ex.details else '', show=True)
return func(self, _('Failed'), ex.msg, det_msg=ex.details or '', show=True)
try:
if 'Could not read 32 bytes on the control bus.' in \
+8 -7
View File
@@ -555,12 +555,13 @@ class MyBlockingBusy(QDialog): # {{{
class MetadataBulkDialog(QDialog, Ui_MetadataBulkDialog):
s_r_functions = {'': lambda x: x,
_('Lower Case'): lambda x: icu_lower(x),
_('Upper Case'): lambda x: icu_upper(x),
_('Title Case'): lambda x: titlecase(x),
_('Capitalize'): lambda x: capitalize(x),
}
s_r_functions = {
'': lambda x: x,
_('Lower Case'): icu_lower,
_('Upper Case'): icu_upper,
_('Title Case'): titlecase,
_('Capitalize'): capitalize,
}
s_r_match_modes = [_('Character match'),
_('Regular expression'),
@@ -784,7 +785,7 @@ class MetadataBulkDialog(QDialog, Ui_MetadataBulkDialog):
self.writable_fields = ['']
fm = self.db.field_metadata
for f in fm:
if (f in ['author_sort'] or
if (f == 'author_sort' or
(fm[f]['datatype'] in ['text', 'series', 'enumeration', 'comments', 'rating'] and
fm[f].get('search_terms', None) and
f not in ['formats', 'ondevice', 'series_sort', 'in_tag_browser']) or
+1 -1
View File
@@ -312,7 +312,7 @@ class Quickview(QDialog, Ui_Quickview):
if not self.is_pane:
if toggle_shortcut and self.close_button.shortcut() != toggle_shortcut:
toggle_sc = QShortcut(toggle_shortcut, self.close_button)
toggle_sc.activated.connect(lambda: self.close_button_clicked())
toggle_sc.activated.connect(self.close_button_clicked)
toggle_sc.setEnabled(True)
self.close_button.setToolTip(_('Alternate shortcut: ') +
toggle_shortcut.toString())
+4 -1
View File
@@ -402,9 +402,12 @@ class SearchDialog(QDialog):
else:
self.copy_current_template_search_button.setEnabled(False)
self.copy_current_template_search_button.clicked.connect(self.retrieve_template_search)
self.edit_template_button.clicked.connect(lambda: self.template_program_box.open_editor())
self.edit_template_button.clicked.connect(self.open_template_program_box_editor)
self.resize(self.sizeHint())
def open_template_program_box_editor(self):
self.template_program_box.open_editor()
def retrieve_template_search(self):
template, sep, query = re.split(r'#@#:([tdnb]):', self.current_search_text, flags=re.IGNORECASE)
self.template_value_box.setText(query)
+3 -5
View File
@@ -254,8 +254,7 @@ class TemplateHighlighter(QSyntaxHighlighter):
a(r'^program:', 'keymode')
a('|'.join([rf'\b{keyword}\b' for keyword in self.KEYWORDS_GPM]), 'keyword')
a('|'.join([rf'\b{builtin}\b' for builtin in
(builtin_functions if builtin_functions else
formatter_functions().get_builtins())]),
(builtin_functions or formatter_functions().get_builtins())]),
'builtin')
a(r'''(?<!:)'[^']*'|"[^"]*\"''', 'string')
else:
@@ -577,9 +576,8 @@ class TemplateDialog(QDialog, Ui_TemplateDialog):
self.setup_saved_template_editor(not dialog_is_st_editor, dialog_is_st_editor)
self.all_functions = all_functions if all_functions else formatter_functions().get_functions()
self.builtins = (builtin_functions if builtin_functions else
formatter_functions().get_builtins_and_aliases())
self.all_functions = all_functions or formatter_functions().get_functions()
self.builtins = (builtin_functions or formatter_functions().get_builtins_and_aliases())
# Set up the breakpoint bar
run_as_you_type = gprefs.get('template_editor_run_as_you_type')
+1 -1
View File
@@ -95,7 +95,7 @@ class ConfirmDialog(QDialog):
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))
connect_lambda(b.clicked, self, lambda self: show_config(self)) # noqa: PLW0108
l.addWidget(self.bb, 1, 0, 1, 2)
b = self.bb.addButton(_('Download &both'),
QDialogButtonBox.ButtonRole.AcceptRole)
+1 -1
View File
@@ -99,7 +99,7 @@ class ConfigWidget(QWidget):
widget.setValue(val)
elif opt.type == 'string':
widget = QLineEdit(self)
widget.setText(val if val else '')
widget.setText(val or '')
elif opt.type == 'bool':
widget = QCheckBox(opt.label, self)
widget.setChecked(bool(val))
+1 -1
View File
@@ -560,7 +560,7 @@ class MetadataSingleDialogBase(QDialog):
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 []
tags = mi.tags or []
if old_tags and merge_tags:
ltags, lotags = {t.lower() for t in tags}, {t.lower() for t in
old_tags}
+2 -2
View File
@@ -178,12 +178,12 @@ class ResultsModel(QAbstractTableModel): # {{{
if col == 0:
return str(book.gui_rank+1)
if col == 1:
t = book.title if book.title else _('Unknown')
t = book.title or _('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 ''
p = book.publisher or ''
return f'<b>{d}</b><br><i>{p}</i>'
def data(self, index, role):
+1 -1
View File
@@ -232,7 +232,7 @@ class Setting:
elif self.datatype == 'number':
self.gui_obj.setValue(val)
elif self.datatype == 'string':
self.gui_obj.setText(val if val else '')
self.gui_obj.setText(val or '')
elif self.datatype == 'choice':
if isinstance(self.gui_obj, EditWithComplete):
self.gui_obj.setText(val)
+1 -2
View File
@@ -190,8 +190,7 @@ class Browser(QScrollArea): # {{{
category_map[plugin.category] = plugin.category_order
category_map[plugin.category] = max(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)
category_names[plugin.category] = (plugin.gui_category or plugin.category)
self.category_names = category_names
@@ -348,7 +348,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
return False
def create_button_clicked(self, use_name=None, need_error_checks=True):
name = use_name if use_name else str(self.function_name.currentText())
name = use_name or str(self.function_name.currentText())
name = name.split(' -- ')[0]
if need_error_checks and self.check_errors_before_save(name, for_replace=False):
return
@@ -526,7 +526,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
def st_create_button_clicked(self, use_name=None):
self.changed_signal.emit()
name = use_name if use_name else str(self.te_name.currentText())
name = use_name or str(self.te_name.currentText())
for k,v in formatter_functions().get_functions().items():
if k == name and v.object_type is StoredObjectType.PythonFunction:
error_dialog(self.gui, _('Stored templates'),
+1 -1
View File
@@ -74,7 +74,7 @@ def set_menu(self, menu):
QAction.setMenu = set_menu
QAction.menu = lambda self: progress_indicator.menu_for_action(self)
QAction.menu = lambda self: progress_indicator.menu_for_action(self) # noqa: PLW0108
# Restore QModelIndex::child
+1 -1
View File
@@ -526,7 +526,7 @@ class SavedSearchBoxMixin: # {{{
def get_saved_search_text(self, search_name=None):
db = self.current_db
try:
current_search = search_name if search_name else self.search.currentText()
current_search = search_name or self.search.currentText()
if not current_search.startswith('search:'):
raise ValueError()
# This strange expression accounts for the four ways a search can be written:
+2 -2
View File
@@ -625,9 +625,9 @@ class SearchRestrictionMixin:
self.search_restriction.addItem(name)
txt = self._trim_restriction_name(last)
if compare_fix_amps(name, current_restriction):
a = current_menu.addAction(self.checked, txt if txt else self.no_restriction)
a = current_menu.addAction(self.checked, txt or self.no_restriction)
else:
a = current_menu.addAction(txt if txt else self.no_restriction)
a = current_menu.addAction(txt or self.no_restriction)
a.triggered.connect(partial(self.search_restriction_triggered, action=a, index=dex))
dex += 1
return a
+1 -1
View File
@@ -88,7 +88,7 @@ class OpenSearchOPDSStore(StorePlugin):
return
if external or self.config.get('open_external', False):
open_url(QUrl(detail_item if detail_item else self.web_url))
open_url(QUrl(detail_item or self.web_url))
else:
d = WebStoreDialog(self.gui, self.web_url, parent, detail_item, create_browser=self.create_browser)
d.setWindowTitle(self.name)
+2 -2
View File
@@ -202,8 +202,8 @@ class Matches(QAbstractItemModel):
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 ''
t = result.title or _('Unknown')
a = result.author or ''
return (f'<b>{t}</b><br><i>{a}</i>')
elif col == 2:
return (result.price)
+1 -1
View File
@@ -91,7 +91,7 @@ class BNStore(BasicStoreConfig, StorePlugin):
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)))
open_url(QUrl(url_slash_cleaner(detail_item or url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_item)
d.setWindowTitle(self.name)
@@ -34,7 +34,7 @@ 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)))
open_url(QUrl(url_slash_cleaner(detail_item or url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_item)
d.setWindowTitle(self.name)
@@ -34,7 +34,7 @@ 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)))
open_url(QUrl(url_slash_cleaner(detail_item or url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_item)
d.setWindowTitle(self.name)
@@ -54,9 +54,9 @@ class EbookpointStore(BasicStoreConfig, StorePlugin):
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)))
open_url(QUrl(url_slash_cleaner(detail_url or aff_url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_url if detail_url else aff_url)
d = WebStoreDialog(self.gui, url, parent, detail_url or aff_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
@@ -53,9 +53,9 @@ class EmpikStore(BasicStoreConfig, StorePlugin):
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)))
open_url(QUrl(url_slash_cleaner(detail_url or aff_url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_url if detail_url else aff_url)
d = WebStoreDialog(self.gui, url, parent, detail_url or aff_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
@@ -84,7 +84,7 @@ 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)))
open_url(QUrl(url_slash_cleaner(detail_item or url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_item)
d.setWindowTitle(self.name)
@@ -53,9 +53,9 @@ class LegimiStore(BasicStoreConfig, StorePlugin):
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)))
open_url(QUrl(url_slash_cleaner(detail_url or aff_url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_url if detail_url else aff_url)
d = WebStoreDialog(self.gui, url, parent, detail_url or aff_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
@@ -45,7 +45,7 @@ class LitResStore(BasicStoreConfig, StorePlugin):
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)))
open_url(QUrl(url_slash_cleaner(detail_url or url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_url)
d.setWindowTitle(self.name)
@@ -21,7 +21,7 @@ class CacheProgressDialog(QDialog, Ui_Dialog):
self.progress.setValue(0)
self.progress.setMinimum(0)
self.progress.setMaximum(total if total else 0)
self.progress.setMaximum(total or 0)
def exec(self):
self.completed = 0
@@ -42,7 +42,7 @@ class MobileReadStore(BasicStoreConfig, StorePlugin):
url = 'https://www.mobileread.com/'
if external or self.config.get('open_external', False):
open_url(QUrl(detail_item if detail_item else url))
open_url(QUrl(detail_item or url))
elif detail_item:
d = WebStoreDialog(self.gui, url, parent, detail_item)
d.setWindowTitle(self.name)
@@ -57,9 +57,9 @@ class NextoStore(BasicStoreConfig, StorePlugin):
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)))
open_url(QUrl(url_slash_cleaner(detail_url or aff_url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_url if detail_url else aff_url)
d = WebStoreDialog(self.gui, url, parent, detail_url or aff_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
@@ -51,9 +51,9 @@ class PublioStore(BasicStoreConfig, StorePlugin):
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)))
open_url(QUrl(url_slash_cleaner(detail_url or aff_url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_url if detail_url else aff_url)
d = WebStoreDialog(self.gui, url, parent, detail_url or aff_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
@@ -36,7 +36,7 @@ class RW2010Store(BasicStoreConfig, StorePlugin):
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)))
open_url(QUrl(url_slash_cleaner(detail_item or url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_item)
d.setWindowTitle(self.name)
@@ -103,7 +103,7 @@ class SmashwordsStore(BasicStoreConfig, StorePlugin):
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)))
open_url(QUrl(url_slash_cleaner(detail_url or url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_url)
d.setWindowTitle(self.name)
@@ -53,9 +53,9 @@ class SwiatEbookowStore(BasicStoreConfig, StorePlugin):
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)))
open_url(QUrl(url_slash_cleaner(detail_url or aff_url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_url if detail_url else aff_url)
d = WebStoreDialog(self.gui, url, parent, detail_url or aff_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
@@ -54,7 +54,7 @@ class VirtualoStore(BasicStoreConfig, StorePlugin):
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)))
open_url(QUrl(url_slash_cleaner(detail_url or aff_url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_item)
d.setWindowTitle(self.name)
@@ -35,7 +35,7 @@ class WeightlessBooksStore(BasicStoreConfig, StorePlugin):
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)))
open_url(QUrl(url_slash_cleaner(detail_item or url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_item)
d.setWindowTitle(self.name)
@@ -102,9 +102,9 @@ class WoblinkStore(BasicStoreConfig, StorePlugin):
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)))
open_url(QUrl(url_slash_cleaner(detail_url or aff_url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_url if detail_url else aff_url)
d = WebStoreDialog(self.gui, url, parent, detail_url or aff_url)
d.setWindowTitle(self.name)
d.set_tags(self.config.get('tags', ''))
d.exec()
@@ -40,7 +40,7 @@ class WolneLekturyStore(BasicStoreConfig, StorePlugin):
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)))
open_url(QUrl(url_slash_cleaner(detail_url or url)))
else:
d = WebStoreDialog(self.gui, url, parent, detail_url)
d.setWindowTitle(self.name)
+2 -2
View File
@@ -84,7 +84,7 @@ class TagTreeItem: # {{{
self.tag = Tag(data, category=category_key,
is_editable=category_key not in
['news', 'search', 'identifiers', 'languages'],
is_searchable=category_key not in ['search'])
is_searchable=category_key != 'search')
elif self.type == self.TAG:
self.tag = data
self.cached_average_rating = None
@@ -746,7 +746,7 @@ class TagsModel(QAbstractItemModel): # {{{
last_idx = 0
for idx,tag in enumerate(data[key]):
# Deal with items that don't have sorts, such as formats
t = tag.sort if tag.sort else tag.name
t = tag.sort or tag.name
c = icu_upper(t) if t else ' '
ordnum, ordlen = collation_order_for_partitioning(c)
if last_ordnum != ordnum:
+4 -1
View File
@@ -633,7 +633,10 @@ class TagsView(QTreeView): # {{{
if has_focus and gprefs['tag_browser_allow_keyboard_focus']:
# Reset the focus to the TB. Use the singleshot in case
# some of searching is done using queued signals.
QTimer.singleShot(0, lambda: self.setFocus())
QTimer.singleShot(0, self.set_focus)
def set_focus(self):
self.setFocus()
def conditional_clear(self, search_string):
if search_string != self.search_string:
+1 -1
View File
@@ -56,7 +56,7 @@ class RequestInterceptor(QWebEngineUrlRequestInterceptor):
request_info.block(True)
return
qurl = request_info.requestUrl()
if qurl.scheme() not in (FAKE_PROTOCOL,):
if qurl.scheme() != FAKE_PROTOCOL:
default_log.warn(f'Blocking URL request {qurl.toString()} as it is not for a resource in the book')
request_info.block(True)
return
+1 -1
View File
@@ -1114,7 +1114,7 @@ class DiffView(QWidget): # {{{
d = -1
elif key in (Qt.Key.Key_PageUp, Qt.Key.Key_PageDown):
amount = self.scrollbar.pageStep()
if key in (Qt.Key.Key_PageUp,):
if key == Qt.Key.Key_PageUp:
d = -1
elif key in (Qt.Key.Key_Home, Qt.Key.Key_End):
self.scrollbar.setValue(0 if key == Qt.Key.Key_Home else self.scrollbar.maximum())
+1 -1
View File
@@ -658,7 +658,7 @@ def launch_editor(path_to_edit, path_is_raw=False, syntax='html', callback=None)
ext = path_to_edit.rpartition('.')[-1].lower()
if ext in ('html', 'htm', 'xhtml', 'xhtm'):
syntax = 'html'
elif ext in ('css',):
elif ext == 'css':
syntax = 'css'
t = Editor(syntax)
t.data = raw
+1 -1
View File
@@ -1245,7 +1245,7 @@ class SavedSearches(QWidget):
def err():
error_dialog(self, _('Invalid data'), _(
'The file %s does not contain valid saved searches') % path, show=True)
if not isinstance(obj, dict) or 'version' not in obj or 'searches' not in obj or obj['version'] not in (1,):
if not isinstance(obj, dict) or 'version' not in obj or 'searches' not in obj or obj['version'] != 1:
return err()
searches = []
for item in obj['searches']:
+1 -1
View File
@@ -149,7 +149,7 @@ class AddDictionary(QDialog): # {{{
def k(dictionary):
return sort_key(calibre_langcode_to_name(dictionary['primary_locale'].langcode))
for data in sorted(catalog_online_dictionaries(), key=lambda x:k(x)):
for data in sorted(catalog_online_dictionaries(), key=k):
if languages.get(data['primary_locale'].langcode, {}).get(data['primary_locale'].countrycode, None):
continue
local = calibre_langcode_to_name(data['primary_locale'].langcode)
+1 -1
View File
@@ -179,7 +179,7 @@ class FilenamePattern(QWidget, Ui_Form): # {{{
self.pubdate.setText(_('No match'))
self.isbn.setText(_('No match') if mi.isbn is None else str(mi.isbn))
self.comments.setText(mi.comments if mi.comments else _('No match'))
self.comments.setText(mi.comments or _('No match'))
def pattern(self):
pat = str(self.re.lineEdit().text())
+2 -2
View File
@@ -323,9 +323,9 @@ class SendEmail(QWidget, Ui_Form):
return False
conf = smtp_prefs()
conf.set('from_', from_)
conf.set('relay_host', host if host else None)
conf.set('relay_host', host or None)
conf.set('relay_port', self.relay_port.value())
conf.set('relay_username', username if username else None)
conf.set('relay_username', username or None)
conf.set('relay_password', as_hex_unicode(password))
conf.set('encryption', enc_method)
return True
@@ -942,7 +942,7 @@ class CatalogBuilder:
if record['publisher']:
this_title['publisher'] = record['publisher']
this_title['rating'] = record['rating'] if record['rating'] else 0
this_title['rating'] = record['rating'] or 0
if is_date_undefined(record['pubdate']):
this_title['date'] = None
+2 -2
View File
@@ -230,7 +230,7 @@ class CustomColumns:
if num is not None:
data = self.custom_column_num_map[num]
# add future datatypes with an extra column here
if data['datatype'] not in ['series']:
if data['datatype'] != 'series':
return None
ign,lt = self.custom_table_names(data['num'])
idx = idx if index_is_id else self.id(idx)
@@ -689,7 +689,7 @@ class CustomColumns:
dt = 'INT'
elif datatype in ('text', 'comments', 'series', 'composite', 'enumeration'):
dt = 'TEXT'
elif datatype in ('float',):
elif datatype == 'float':
dt = 'REAL'
elif datatype == 'datetime':
dt = 'timestamp'
+3 -3
View File
@@ -1296,7 +1296,7 @@ ALTER TABLE books ADD COLUMN isbn TEXT DEFAULT "" COLLATE NOCASE;
rating = int(rating)
self.conn.execute('DELETE FROM books_ratings_link WHERE book=?',(id,))
rat = self.conn.get('SELECT id FROM ratings WHERE rating=?', (rating,), all=False)
rat = rat if rat else self.conn.execute('INSERT INTO ratings(rating) VALUES (?)', (rating,)).lastrowid
rat = rat or self.conn.execute('INSERT INTO ratings(rating) VALUES (?)', (rating,)).lastrowid
self.conn.execute('INSERT INTO books_ratings_link(book, rating) VALUES (?,?)', (id, rat))
self.conn.commit()
@@ -1350,7 +1350,7 @@ ALTER TABLE books ADD COLUMN isbn TEXT DEFAULT "" COLLATE NOCASE;
duplicates.append((path, format, mi, uri))
continue
series_index = 1 if mi.series_index is None else mi.series_index
aus = mi.author_sort if mi.author_sort else ', '.join(mi.authors)
aus = mi.author_sort or ', '.join(mi.authors)
obj = self.conn.execute('INSERT INTO books(title, uri, series_index, author_sort) VALUES (?, ?, ?, ?)',
(mi.title, uri, series_index, aus))
id = obj.lastrowid
@@ -1493,7 +1493,7 @@ class SearchToken:
if not text:
text = ''
else:
text = ' '.join([item[i] if item[i] else '' for i in self.FIELD_MAP.values()])
text = ' '.join([item[i] or '' for i in self.FIELD_MAP.values()])
return bool(self.pattern.search(text)) ^ self.negate
+4 -4
View File
@@ -204,7 +204,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
progress_callback(None, len(default_prefs))
for i, key in enumerate(default_prefs):
# be sure that prefs not to be copied are listed below
if not restore_all_prefs and key in frozenset(['news_to_be_synced']):
if not restore_all_prefs and key == 'news_to_be_synced':
continue
dbprefs[key] = default_prefs[key]
progress_callback(_('restored preference ') + key, i+1)
@@ -3465,7 +3465,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
return None
series_index = self.get_next_series_num_for(mi.series) \
if mi.series_index is None else mi.series_index
aus = mi.author_sort if mi.author_sort else self.author_sort_from_authors(mi.authors)
aus = mi.author_sort or self.author_sort_from_authors(mi.authors)
title = mi.title
if isbytestring(aus):
aus = aus.decode(preferred_encoding, 'replace')
@@ -3513,7 +3513,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
continue
series_index = self.get_next_series_num_for(mi.series) \
if mi.series_index is None else mi.series_index
aus = mi.author_sort if mi.author_sort else self.author_sort_from_authors(mi.authors)
aus = mi.author_sort or self.author_sort_from_authors(mi.authors)
title = mi.title
if isinstance(aus, bytes):
aus = aus.decode(preferred_encoding, 'replace')
@@ -3556,7 +3556,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
mi.title = _('Unknown')
if not mi.authors:
mi.authors = [_('Unknown')]
aus = mi.author_sort if mi.author_sort else self.author_sort_from_authors(mi.authors)
aus = mi.author_sort or self.author_sort_from_authors(mi.authors)
if isinstance(aus, bytes):
aus = aus.decode(preferred_encoding, 'replace')
title = mi.title if isinstance(mi.title, str) else \
+1 -1
View File
@@ -69,7 +69,7 @@ def build_search_box(num, search, sort, order, ctx, field_metadata, library_id):
num_select.tail = ' books matching '
form.append(num_select)
searchf = E.input(name='search', id='s', value=search if search else '')
searchf = E.input(name='search', id='s', value=search or '')
searchf.tail = _(' sorted by ')
form.append(searchf)
+2 -5
View File
@@ -10,10 +10,7 @@ import traceback
from collections.abc import Callable, Iterator
from contextlib import ExitStack
from itertools import chain, islice
from typing import Any, BinaryIO, NamedTuple, TypeVar
T = TypeVar('T')
R = TypeVar('R')
from typing import Any, BinaryIO, NamedTuple
try:
from itertools import batched
@@ -111,7 +108,7 @@ def run_jobs(*jobs: Job) -> Worker:
os._exit(os.EX_OK)
def forked_map(fn: Callable[[T], R], iterable: T, *iterables: T, timeout: int | float | None = None, num_workers: int = 0) -> Iterator[R]:
def forked_map[T, R](fn: Callable[[T], R], iterable: T, *iterables: T, timeout: int | float | None = None, num_workers: int = 0) -> Iterator[R]:
'''
Should be used only in worker processes that have no threads and that do not use/import any non fork safe libraries such as macOS
system libraries.

Some files were not shown because too many files have changed in this diff Show More