more work toward universal __future__s

This commit is contained in:
Eli Schwartz 2019-09-03 15:25:02 -04:00 committed by Kovid Goyal
parent db9ebeb2d5
commit 3a3ae2590e
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
51 changed files with 141 additions and 116 deletions

View File

@ -165,7 +165,7 @@ def resolve_styles(container, name, select=None, sheet_callback=None):
style_map = defaultdict(list)
pseudo_style_map = defaultdict(list)
rule_index_counter = count()
pseudo_pat = re.compile(u':{1,2}(%s)' % ('|'.join(INAPPROPRIATE_PSEUDO_CLASSES)), re.I)
pseudo_pat = re.compile(':{1,2}(%s)' % ('|'.join(INAPPROPRIATE_PSEUDO_CLASSES)), re.I)
def process_sheet(sheet, sheet_name):
if sheet_callback is not None:

View File

@ -1277,7 +1277,7 @@ class EpubContainer(Container):
break
if raw_unique_identifier is not None:
idpf_key = raw_unique_identifier
idpf_key = re.sub(u'[\u0020\u0009\u000d\u000a]', u'', idpf_key)
idpf_key = re.sub('[\u0020\u0009\u000d\u000a]', '', idpf_key)
idpf_key = hashlib.sha1(idpf_key.encode('utf-8')).digest()
key = None
for item in self.opf_xpath('//*[local-name()="metadata"]/*'

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
@ -37,7 +38,7 @@ Counts = namedtuple('Counts', 'library_total total current')
def human_readable(size, precision=1):
""" Convert a size in bytes into megabytes """
return ('%.'+str(precision)+'f') % ((size/(1024.*1024.)),)
return ('%.'+unicode_type(precision)+'f') % (size/(1024*1024))
TIME_FMT = '%d %b %Y'
@ -71,7 +72,7 @@ class ColumnColor(object): # {{{
self.formatter = formatter
def __call__(self, id_, key, fmt, db, color_cache, template_cache):
key += str(hash(fmt))
key += unicode_type(hash(fmt))
if id_ in color_cache and key in color_cache[id_]:
self.mi = None
color = color_cache[id_][key]
@ -112,7 +113,7 @@ class ColumnIcon(object): # {{{
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),
column_name=cache_index+unicode_type(dex),
template_cache=template_cache)
if not rule_icons:
continue
@ -774,14 +775,14 @@ class BooksModel(QAbstractTableModel): # {{{
return None if bt else bn
return by if val else bn
elif field == 'size':
sz_mult = 1.0/(1024**2)
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 = u'%.1f' % (val * sz_mult)
return (u'<0.1' if ans == u'0.0' else ans)
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))))
@ -874,7 +875,7 @@ class BooksModel(QAbstractTableModel): # {{{
def stars_tooltip(func, allow_half=True):
def f(idx):
ans = val = int(func(idx))
ans = str(val // 2)
ans = unicode_type(val // 2)
if allow_half and val % 2:
ans += '.5'
return _('%s stars') % ans
@ -1152,7 +1153,7 @@ class BooksModel(QAbstractTableModel): # {{{
return False
val = (int(value) if column == 'rating' else
value if column in ('timestamp', 'pubdate')
else re.sub(u'\\s', u' ', unicode_type(value or '').strip()))
else re.sub('\\s', ' ', unicode_type(value or '').strip()))
id = self.db.id(row)
books_to_refresh = {id}
if column == 'rating':

View File

@ -1,14 +1,13 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import absolute_import, division, print_function, unicode_literals
from __future__ import print_function
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import itertools, operator
from functools import partial
from polyglot.builtins import iteritems, map, unicode_type, range
from collections import OrderedDict
from PyQt5.Qt import (
@ -31,6 +30,7 @@ from calibre.gui2.library import DEFAULT_SORT
from calibre.constants import filesystem_encoding
from calibre import force_unicode
from calibre.utils.icu import primary_sort_key
from polyglot.builtins import iteritems, map, range, unicode_type
def restrict_column_width(self, col, old_size, new_size):

View File

@ -1,4 +1,4 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'

View File

@ -1,3 +1,5 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
@ -20,5 +22,3 @@ class BookView(QGraphicsView):
def resize_for(self, width, height):
self.preferred_size = QSize(width, height)

View File

@ -1,6 +1,8 @@
from __future__ import print_function
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
import collections, itertools, glob
from PyQt5.Qt import (
@ -8,10 +10,9 @@ from PyQt5.Qt import (
QBrush, QColor, QFontDatabase, QGraphicsItem, QGraphicsLineItem)
from calibre.gui2.lrf_renderer.text import TextBlock, FontLoader, COLOR, PixmapItem
from calibre.ebooks.lrf.objects import RuledLine as _RuledLine
from calibre.ebooks.lrf.objects import Canvas as __Canvas
from polyglot.builtins import unicode_type
class Color(QColor):
@ -417,7 +418,7 @@ class Document(QGraphicsScene):
fdata = QByteArray(lrf.font_map[font].data)
id = QFontDatabase.addApplicationFontFromData(fdata)
if id != -1:
font_map[font] = [str(i) for i in QFontDatabase.applicationFontFamilies(id)][0]
font_map[font] = [unicode_type(i) for i in QFontDatabase.applicationFontFamilies(id)][0]
if load_substitutions:
base = P('fonts/liberation/*.ttf')

View File

@ -1,6 +1,8 @@
from __future__ import print_function
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
import sys, logging, os, traceback, time
from PyQt5.Qt import (
@ -199,9 +201,9 @@ class Main(MainWindow, Ui_MainWindow):
print('Error rendering document', file=sys.stderr)
print(exception, file=sys.stderr)
print(self.renderer.formatted_traceback, file=sys.stderr)
msg = u'<p><b>%s</b>: '%(exception.__class__.__name__,) + as_unicode(exception) + u'</p>'
msg += u'<p>Failed to render document</p>'
msg += u'<p>Detailed <b>traceback</b>:<pre>'
msg = '<p><b>%s</b>: '%(exception.__class__.__name__,) + as_unicode(exception) + '</p>'
msg += '<p>Failed to render document</p>'
msg += '<p>Detailed <b>traceback</b>:<pre>'
msg += self.renderer.formatted_traceback + '</pre>'
d = ConversionErrorDialog(self, 'Error while rendering file', msg)
d.exec_()

View File

@ -1,6 +1,8 @@
from __future__ import print_function
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
import sys, collections, operator, copy, re, numbers
from PyQt5.Qt import (
@ -11,7 +13,7 @@ from calibre.ebooks.lrf.fonts import LIBERATION_FONT_MAP
from calibre.ebooks.hyphenate import hyphenate_word
from polyglot.builtins import unicode_type, string_or_bytes
WEIGHT_MAP = lambda wt : int((wt/10.)-1)
WEIGHT_MAP = lambda wt : int((wt/10)-1)
NULL = lambda a, b: a
COLOR = lambda a, b: QColor(*a)
WEIGHT = lambda a, b: WEIGHT_MAP(a)
@ -41,7 +43,7 @@ class Plot(PixmapItem):
def __init__(self, plot, dpi):
img = plot.refobj
xsize, ysize = dpi*plot.attrs['xsize']/720., dpi*plot.attrs['ysize']/720.
xsize, ysize = dpi*plot.attrs['xsize']/720, dpi*plot.attrs['ysize']/720
x0, y0, x1, y1 = img.x0, img.y0, img.x1, img.y1
data, encoding = img.data, img.encoding
PixmapItem.__init__(self, data, encoding, x0, y0, x1, y1, xsize, ysize)
@ -95,7 +97,7 @@ class Style(object):
map = collections.defaultdict(lambda : NULL)
def __init__(self, style, dpi):
self.fdpi = dpi/720.
self.fdpi = dpi/720
self.update(style.as_dict())
def update(self, *args, **kwds):
@ -154,7 +156,7 @@ class ParSkip(object):
self.height = parskip
def __str__(self):
return 'Parskip: '+str(self.height)
return 'Parskip: '+unicode_type(self.height)
class TextBlock(object):
@ -289,7 +291,7 @@ class TextBlock(object):
self.current_style.linespace,
self.opts.visual_debug)
if self.height > self.max_y+10:
raise TextBlock.HeightExceeded(str(self.current_line))
raise TextBlock.HeightExceeded(unicode_type(self.current_line))
self.lines.append(self.current_line)
self.current_line = None
@ -307,7 +309,7 @@ class TextBlock(object):
def process_text(self, raw):
for ent, rep in TextBlock.XML_ENTITIES.items():
raw = raw.replace(u'&%s;'%ent, rep)
raw = raw.replace('&%s;'%ent, rep)
while len(raw) > 0:
if self.current_line is None:
self.create_line()
@ -325,7 +327,7 @@ class TextBlock(object):
def __str__(self):
s = ''
for line in self:
s += str(line) + '\n'
s += unicode_type(line) + '\n'
return s
@ -563,7 +565,7 @@ class Line(QGraphicsItem):
return (textwidth-self.width)/2.
def __unicode__(self):
s = u''
s = ''
for tok in self.tokens:
if isinstance(tok, numbers.Number):
s += ' '

View File

@ -1,9 +1,7 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'

View File

@ -1175,7 +1175,7 @@ class Cover(ImageView): # {{{
except IOError 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))
_("<p>There was an error reading from file: <br /><b>") + _file + "</b></p><br />"+unicode_type(e))
d.exec_()
if cover:
orig = self.current_val

View File

@ -99,7 +99,7 @@ class PDFCovers(QDialog):
pass
def render(self):
self.current_tdir = os.path.join(self.tdir, str(self.first))
self.current_tdir = os.path.join(self.tdir, unicode_type(self.first))
self.error = None
try:
os.mkdir(self.current_tdir)

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
@ -214,7 +215,7 @@ class CommaSeparatedList(Setting):
def set_gui_val(self, val):
x = ''
if val:
x = u', '.join(val)
x = ', '.join(val)
self.gui_obj.setText(x)
def get_gui_val(self):

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
@ -22,6 +23,7 @@ from calibre.gui2.convert.structure_detection import StructureDetectionWidget
from calibre.gui2.convert.toc import TOCWidget
from calibre.customize.ui import input_format_plugins, output_format_plugins
from calibre.gui2.convert import config_widget_for_input_plugin
from polyglot.builtins import unicode_type
class Model(QStringListModel):
@ -91,7 +93,7 @@ class Base(ConfigWidgetBase):
if rec.option == name:
ans = getattr(rec, 'help', None)
if ans is not None:
return ans.replace('%default', str(rec.recommended_value))
return ans.replace('%default', unicode_type(rec.recommended_value))
return cls(self, self.plumber.get_option_by_name, hfunc, None, None)
self.load_conversion_widgets()

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid at kovidgoyal.net>'

View File

@ -1,6 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'

View File

@ -1,6 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'

View File

@ -1,6 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'

View File

@ -1,6 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import print_function
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
@ -24,7 +24,7 @@ from calibre.library.save_to_disk import plugboard_any_format_value, \
from calibre.srv.content import plugboard_content_server_value, plugboard_content_server_formats
from calibre.gui2.email import plugboard_email_value, plugboard_email_formats
from calibre.utils.formatter import validation_formatter
from polyglot.builtins import unicode_type
from polyglot.builtins import native_string_type, unicode_type
class ConfigWidget(ConfigWidgetBase, Ui_Form):
@ -99,10 +99,10 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
self.dest_widgets.append(w)
self.fields_layout.addWidget(w, 5+i, 1, 1, 1)
self.edit_device.currentIndexChanged[str].connect(self.edit_device_changed)
self.edit_format.currentIndexChanged[str].connect(self.edit_format_changed)
self.new_device.currentIndexChanged[str].connect(self.new_device_changed)
self.new_format.currentIndexChanged[str].connect(self.new_format_changed)
self.edit_device.currentIndexChanged[native_string_type].connect(self.edit_device_changed)
self.edit_format.currentIndexChanged[native_string_type].connect(self.edit_format_changed)
self.new_device.currentIndexChanged[native_string_type].connect(self.new_device_changed)
self.new_format.currentIndexChanged[native_string_type].connect(self.new_format_changed)
self.existing_plugboards.itemClicked.connect(self.existing_pb_clicked)
self.ok_button.clicked.connect(self.ok_clicked)
self.del_button.clicked.connect(self.del_clicked)
@ -300,7 +300,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
except Exception as err:
error_dialog(self, _('Invalid template'),
'<p>'+_('The template %s is invalid:')%s +
'<br>'+str(err), show=True)
'<br>'+unicode_type(err), show=True)
return
pb.append((s, self.dest_fields[d]))
comments_in_dests = comments_in_dests or self.dest_fields[d] == 'comments'

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
@ -204,7 +205,7 @@ class PluginModel(QAbstractItemModel, AdaptSQP): # {{{
plugin = self.index_to_plugin(index)
disabled = is_disabled(plugin)
if role == Qt.DisplayRole:
ver = '.'.join(map(str, plugin.version))
ver = '.'.join(map(unicode_type, plugin.version))
desc = '\n'.join(textwrap.wrap(plugin.description, 100))
ans='%s (%s) %s %s\n%s'%(plugin.name, ver, _('by'), plugin.author, desc)
c = plugin_customization(plugin)

View File

@ -1,6 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
@ -34,12 +34,12 @@ class SaveTemplate(QWidget, Ui_Form):
' by clicking the device icon and choosing "Configure this device".'))
rows = []
for var in variables:
rows.append(u'<tr><td>%s</td><td>&nbsp;</td><td>%s</td></tr>'%
rows.append('<tr><td>%s</td><td>&nbsp;</td><td>%s</td></tr>'%
(var, FORMAT_ARG_DESCS[var]))
rows.append(u'<tr><td>%s&nbsp;</td><td>&nbsp;</td><td>%s</td></tr>'%(
rows.append('<tr><td>%s&nbsp;</td><td>&nbsp;</td><td>%s</td></tr>'%(
_('Any custom field'),
_('The lookup name of any custom field (these names begin with "#").')))
table = u'<table>%s</table>'%(u'\n'.join(rows))
table = '<table>%s</table>'%('\n'.join(rows))
self.template_variables.setText(table)
self.field_metadata = field_metadata
@ -75,7 +75,7 @@ class SaveTemplate(QWidget, Ui_Form):
except Exception as err:
error_dialog(self, _('Invalid template'),
'<p>'+_('The template %s is invalid:')%tmpl +
'<br>'+str(err), show=True)
'<br>'+unicode_type(err), show=True)
return False
return True

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
@ -16,7 +17,7 @@ from calibre.gui2.widgets import PythonHighlighter
from calibre.utils.formatter_functions import (formatter_functions,
compile_user_function, compile_user_template_functions,
load_user_template_functions)
from polyglot.builtins import iteritems, unicode_type
from polyglot.builtins import iteritems, native_string_type, unicode_type
class ConfigWidget(ConfigWidgetBase, Ui_Form):
@ -89,7 +90,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
self.builtins = formatter_functions().get_builtins_and_aliases()
self.build_function_names_box()
self.function_name.currentIndexChanged[str].connect(self.function_index_changed)
self.function_name.currentIndexChanged[native_string_type].connect(self.function_index_changed)
self.function_name.editTextChanged.connect(self.function_name_edited)
self.argument_count.valueChanged.connect(self.enable_replace_button)
self.documentation.textChanged.connect(self.enable_replace_button)

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'

View File

@ -188,7 +188,7 @@ class TagsView(QTreeView): # {{{
border: 1px solid #bfcde4;
border-radius: 6px;
}
'''.replace('PAD', str(gprefs['tag_browser_item_padding'])) + (
'''.replace('PAD', unicode_type(gprefs['tag_browser_item_padding'])) + (
'' if gprefs['tag_browser_old_look'] else stylish_tb))
self.setAlternatingRowColors(gprefs['tag_browser_old_look'])
self.itemDelegate().old_look = gprefs['tag_browser_old_look']

View File

@ -17,7 +17,7 @@ from PyQt5.QtWebKit import QWebElement
from calibre.ebooks.oeb.display.webview import load_html
from calibre.gui2 import error_dialog, question_dialog, gprefs, secure_web_page
from calibre.utils.logging import default_log
from polyglot.builtins import unicode_type, range
from polyglot.builtins import native_string_type, range, unicode_type
from polyglot.binary import as_base64_unicode
@ -36,7 +36,7 @@ class Page(QWebPage): # {{{
self.setLinkDelegationPolicy(self.DelegateAllLinks)
def javaScriptConsoleMessage(self, msg, lineno, msgid):
self.log(u'JS:', unicode_type(msg))
self.log('JS:', unicode_type(msg))
def javaScriptAlert(self, frame, msg):
self.log(unicode_type(msg))
@ -45,11 +45,11 @@ class Page(QWebPage): # {{{
def shouldInterruptJavaScript(self):
return True
@pyqtSlot(QWebElement, str, str, float)
@pyqtSlot(QWebElement, native_string_type, native_string_type, float)
def onclick(self, elem, loc, totals, frac):
elem_id = unicode_type(elem.attribute('id')) or None
tag = unicode_type(elem.tagName()).lower()
self.elem_clicked.emit(tag, frac, elem_id, json.loads(str(loc)), json.loads(str(totals)))
self.elem_clicked.emit(tag, frac, elem_id, json.loads(unicode_type(loc)), json.loads(unicode_type(totals)))
def load_js(self):
if self.js is None:

View File

@ -9,7 +9,6 @@ __docformat__ = 'restructuredtext en'
import sys, os, textwrap
from threading import Thread
from functools import partial
from polyglot.builtins import map, unicode_type, range
from PyQt5.Qt import (QPushButton, QFrame, QMenu, QInputDialog, QCheckBox,
QDialog, QVBoxLayout, QDialogButtonBox, QSize, QStackedWidget, QWidget,
@ -24,6 +23,7 @@ from calibre.gui2.progress_indicator import ProgressIndicator
from calibre.gui2.toc.location import ItemEdit
from calibre.gui2.convert.xpath_wizard import XPathEdit
from calibre.utils.logging import GUILog
from polyglot.builtins import map, unicode_type, range
ICON_SIZE = 24
@ -80,7 +80,7 @@ class XPathDialog(QDialog): # {{{
if name:
saved = self.prefs.get('xpath_toc_settings', {})
# in JSON all keys have to be strings
saved[name] = {str(i):x for i, x in enumerate(xpaths)}
saved[name] = {unicode_type(i):x for i, x in enumerate(xpaths)}
self.prefs.set('xpath_toc_settings', saved)
self.setup_load_button()
@ -103,7 +103,7 @@ class XPathDialog(QDialog): # {{{
def load_settings(self, name):
saved = self.prefs.get('xpath_toc_settings', {}).get(name, {})
for i, w in enumerate(self.widgets):
txt = saved.get(str(i), '')
txt = saved.get(unicode_type(i), '')
w.edit.setText(txt)
def check(self):

View File

@ -520,7 +520,7 @@ class CharModel(QAbstractListModel):
return ['application/calibre_charcode_indices']
def mimeData(self, indexes):
data = ','.join(str(i.row()) for i in indexes)
data = ','.join(unicode_type(i.row()) for i in indexes)
md = QMimeData()
md.setData('application/calibre_charcode_indices', data.encode('utf-8'))
return md

View File

@ -118,7 +118,7 @@ def get_bulk_rename_settings(parent, number, msg=None, sanitize=sanitize_file_na
fmt = '%d'
if leading_zeros:
largest = num + number - 1
fmt = '%0{0}d'.format(len(str(largest)))
fmt = '%0{0}d'.format(len(unicode_type(largest)))
ans['prefix'] = prefix + fmt
ans['start'] = num
if allow_spine_order:

View File

@ -7,7 +7,6 @@ __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import time, textwrap, json
from bisect import bisect_right
from polyglot.builtins import map, unicode_type, filter
from threading import Thread
from functools import partial
@ -27,6 +26,7 @@ from calibre.gui2.viewer.documentview import apply_settings
from calibre.gui2.viewer.config import config
from calibre.gui2.widgets2 import HistoryLineEdit2
from calibre.utils.ipc.simple_worker import offload_worker
from polyglot.builtins import filter, map, native_string_type, unicode_type
from polyglot.urllib import urlparse
from polyglot.queue import Queue, Empty
from polyglot.binary import as_base64_unicode
@ -295,7 +295,7 @@ class WebPage(QWebPage):
mf.addToJavaScriptWindowObject("py_bridge", self)
mf.evaluateJavaScript(self.js)
@pyqtSlot(str, str, str)
@pyqtSlot(native_string_type, native_string_type, native_string_type)
def request_sync(self, tag_name, href, sourceline_address):
try:
self.sync_requested.emit(unicode_type(tag_name), unicode_type(href), json.loads(unicode_type(sourceline_address)))
@ -304,9 +304,9 @@ class WebPage(QWebPage):
def go_to_anchor(self, anchor, lnum):
self.mainFrame().evaluateJavaScript('window.calibre_preview_integration.go_to_anchor(%s, %s)' % (
json.dumps(anchor), json.dumps(str(lnum))))
json.dumps(anchor), json.dumps(unicode_type(lnum))))
@pyqtSlot(str, str)
@pyqtSlot(native_string_type, native_string_type)
def request_split(self, loc, totals):
actions['split-in-preview'].setChecked(False)
loc, totals = json.loads(unicode_type(loc)), json.loads(unicode_type(totals))

View File

@ -7,7 +7,6 @@ __copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>'
import time, textwrap, os
from threading import Thread
from polyglot.builtins import iteritems, map, range, filter
from operator import itemgetter
from functools import partial
from collections import defaultdict
@ -35,6 +34,7 @@ from calibre.gui2.progress_indicator import ProgressIndicator
from calibre.utils.icu import primary_contains, numeric_sort_key
from calibre.utils.unicode_names import character_name_from_code
from calibre.utils.localization import calibre_langcode_to_name, canonicalize_lang
from polyglot.builtins import filter, iteritems, map, range, unicode_type
# Utils {{{
@ -980,7 +980,7 @@ class CSSRulesModel(QAbstractItemModel):
self.rules = data['css']
self.num_unused = sum(1 for r in self.rules if r.count == 0)
try:
self.num_size = len(str(max(r.count for r in self.rules)))
self.num_size = len(unicode_type(max(r.count for r in self.rules)))
except ValueError:
self.num_size = 1
self.build_maps()
@ -1204,7 +1204,7 @@ class ClassesModel(CSSRulesModel):
self.rules = self.classes = tuple(data['classes'])
self.num_unused = sum(1 for ce in self.classes if ce.num_of_matches == 0)
try:
self.num_size = len(str(max(r.num_of_matches for r in self.classes)))
self.num_size = len(unicode_type(max(r.num_of_matches for r in self.classes)))
except ValueError:
self.num_size = 1
self.build_maps()

View File

@ -1,4 +1,6 @@
#!/usr/bin/env python2
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net'
__docformat__ = 'restructuredtext en'
@ -6,7 +8,6 @@ __docformat__ = 'restructuredtext en'
# Imports {{{
import math, json
from functools import partial
from polyglot.builtins import iteritems, map, unicode_type, string_or_bytes
from PyQt5.Qt import (
QSize, QSizePolicy, QUrl, Qt, QPainter, QPalette, QBrush,
@ -32,6 +33,7 @@ from calibre.gui2.viewer.footnote import Footnotes
from calibre.gui2.viewer.fake_net import NetworkAccessManager
from calibre.ebooks.oeb.display.webview import load_html
from calibre.constants import isxp, iswindows, DEBUG, __version__
from polyglot.builtins import iteritems, map, unicode_type, string_or_bytes
from polyglot.binary import as_base64_unicode
# }}}
@ -205,7 +207,7 @@ class Document(QWebPage): # {{{
evaljs('window.calibre_utils.setup_epub_reading_system(%s, %s, %s, %s)' % tuple(map(json.dumps, (
'calibre-desktop', __version__, 'paginated' if self.in_paged_mode else 'scrolling',
'dom-manipulation layout-changes mouse-events keyboard-events'.split()))))
self.javascript(u'window.mathjax.base = %s'%(json.dumps(self.nam.mathjax_base, ensure_ascii=False)))
self.javascript('window.mathjax.base = %s'%(json.dumps(self.nam.mathjax_base, ensure_ascii=False)))
for pl in self.all_viewer_plugins:
pl.load_javascript(evaljs)
evaljs('py_bridge.mark_element.connect(window.calibre_extract.mark)')
@ -299,7 +301,7 @@ class Document(QWebPage): # {{{
def column_boundaries(self):
if not self.loaded_javascript:
return (0, 1)
ans = self.javascript(u'JSON.stringify(paged_display.column_boundaries())')
ans = self.javascript('JSON.stringify(paged_display.column_boundaries())')
return tuple(int(x) for x in json.loads(ans))
def after_resize(self):
@ -359,7 +361,7 @@ class Document(QWebPage): # {{{
except (TypeError, ValueError):
return 0.0
if typ == 'string':
return ans or u''
return ans or ''
if typ in {bool, 'bool'}:
return bool(ans)
return ans
@ -656,11 +658,11 @@ class DocumentView(QWebView): # {{{
@property
def selected_text(self):
return self.document.selectedText().replace(u'\u00ad', u'').strip()
return self.document.selectedText().replace('\u00ad', '').strip()
@property
def selected_html(self):
return self.document.selectedHtml().replace(u'\u00ad', u'').strip()
return self.document.selectedHtml().replace('\u00ad', '').strip()
def selection_changed(self):
if self.manager is not None:
@ -669,10 +671,10 @@ class DocumentView(QWebView): # {{{
def _selectedText(self):
t = unicode_type(self.selectedText()).strip()
if not t:
return u''
return ''
if len(t) > 40:
t = t[:40] + u'...'
t = t.replace(u'&', u'&&')
t = t[:40] + '...'
t = t.replace('&', '&&')
return _("S&earch online for '%s'")%t
def popup_table(self):
@ -696,7 +698,7 @@ class DocumentView(QWebView): # {{{
table = None
parent = elem
while not parent.isNull():
if (unicode_type(parent.tagName()) == u'table' or unicode_type(parent.localName()) == u'table'):
if (unicode_type(parent.tagName()) == 'table' or unicode_type(parent.localName()) == 'table'):
table = parent
break
parent = parent.parent()
@ -937,7 +939,7 @@ class DocumentView(QWebView): # {{{
self.scrollbar.setRange(0, delta)
self.scrollbar.setValue(0)
self.scrollbar.setSingleStep(1)
self.scrollbar.setPageStep(int(delta/10.))
self.scrollbar.setPageStep(int(delta//10))
self.scrollbar.setVisible(delta > 0)
self.scrollbar.blockSignals(False)
self._ignore_scrollbar_signals = False
@ -1294,7 +1296,7 @@ class DocumentView(QWebView): # {{{
amt = dim * scroll_amount
mult = -1 if amt < 0 else 1
if self.document.wheel_scroll_fraction != 100:
amt = mult * max(1, abs(int(amt * self.document.wheel_scroll_fraction / 100.)))
amt = mult * max(1, abs(int(amt * self.document.wheel_scroll_fraction / 100)))
self.scroll_by(0, amt) if vertical else self.scroll_by(amt, 0)
if self.manager is not None:
@ -1334,7 +1336,7 @@ class DocumentView(QWebView): # {{{
if (not self.document.line_scrolling_stops_on_pagebreaks and self.document.at_bottom):
self.manager.next_document()
else:
amt = int((self.document.line_scroll_fraction / 100.) * 15)
amt = int((self.document.line_scroll_fraction / 100) * 15)
self.scroll_by(y=amt)
elif key == 'Up':
if self.document.in_paged_mode:
@ -1344,19 +1346,19 @@ class DocumentView(QWebView): # {{{
if (not self.document.line_scrolling_stops_on_pagebreaks and self.document.at_top):
self.manager.previous_document()
else:
amt = int((self.document.line_scroll_fraction / 100.) * 15)
amt = int((self.document.line_scroll_fraction / 100) * 15)
self.scroll_by(y=-amt)
elif key == 'Left':
if self.document.in_paged_mode:
self.paged_col_scroll(forward=False)
else:
amt = int((self.document.line_scroll_fraction / 100.) * 15)
amt = int((self.document.line_scroll_fraction / 100) * 15)
self.scroll_by(x=-amt)
elif key == 'Right':
if self.document.in_paged_mode:
self.paged_col_scroll()
else:
amt = int((self.document.line_scroll_fraction / 100.) * 15)
amt = int((self.document.line_scroll_fraction / 100) * 15)
self.scroll_by(x=amt)
elif key == 'Back':
if self.manager is not None:

View File

@ -1,8 +1,8 @@
#!/usr/bin/env python2
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import absolute_import, division, print_function, unicode_literals
import os
from PyQt5.Qt import QNetworkReply, QNetworkAccessManager, QUrl, QNetworkRequest, QTimer, pyqtSignal, QByteArray
@ -12,6 +12,7 @@ from calibre.constants import FAKE_HOST, FAKE_PROTOCOL, DEBUG
from calibre.ebooks.oeb.base import OEB_DOCS
from calibre.ebooks.oeb.display.webview import cleanup_html, load_as_html
from calibre.utils.short_uuid import uuid4
from polyglot.builtins import unicode_type
def guess_type(x):
@ -101,7 +102,7 @@ class NetworkAccessManager(QNetworkAccessManager):
def __init__(self, parent=None):
QNetworkAccessManager.__init__(self, parent)
self.mathjax_prefix = str(uuid4())
self.mathjax_prefix = unicode_type(uuid4())
self.mathjax_base = '%s://%s/%s/' % (FAKE_PROTOCOL, FAKE_HOST, self.mathjax_prefix)
self.root = self.orig_root = os.path.dirname(P('viewer/blank.html', allow_user_override=False))
self.mime_map, self.single_pages, self.codec_map = {}, set(), {}

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
@ -113,5 +114,3 @@ class SlideFlip(QWidget):
fget=lambda self: self._current_width,
fset=set_current_width
)

View File

@ -1,6 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'

View File

@ -1,8 +1,8 @@
#!/usr/bin/env python2
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2015, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import absolute_import, division, print_function, unicode_literals
from __future__ import print_function
import functools
import os
import sys
@ -421,7 +421,7 @@ class EbookViewer(MainWindow):
def lookup(self, word):
from polyglot.urllib import quote
word = word.replace(u'\u00ad', '')
word = word.replace('\u00ad', '')
word = quote(word.encode('utf-8'))
lang = canonicalize_lang(self.view.current_language) or get_lang() or 'en'
try:

View File

@ -1,6 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
@ -9,7 +9,6 @@ __docformat__ = 'restructuredtext en'
import os, traceback, re
from contextlib import closing
from PyQt5.Qt import (QWizard, QWizardPage, QIcon, Qt, QAbstractListModel,
QItemSelectionModel, pyqtSignal, QItemSelection, QDir)
from calibre import __appname__
@ -573,7 +572,7 @@ class StanzaPage(QWizardPage, StanzaUI):
try:
s.bind(('0.0.0.0', p))
t = unicode_type(self.instructions.text())
t = re.sub(r':\d+', ':'+str(p), t)
t = re.sub(r':\d+', ':'+unicode_type(p), t)
self.instructions.setText(t)
return p
except:
@ -686,10 +685,10 @@ class LibraryPage(QWizardPage, LibraryUI):
for item in items:
self.language.addItem(item[1], (item[0]))
self.language.blockSignals(False)
prefs['language'] = str(self.language.itemData(self.language.currentIndex()) or '')
prefs['language'] = unicode_type(self.language.itemData(self.language.currentIndex()) or '')
def change_language(self, idx):
prefs['language'] = str(self.language.itemData(self.language.currentIndex()) or '')
prefs['language'] = unicode_type(self.language.itemData(self.language.currentIndex()) or '')
from polyglot.builtins import builtins
builtins.__dict__['_'] = lambda x: x
from calibre.utils.localization import set_translators
@ -766,7 +765,7 @@ class LibraryPage(QWizardPage, LibraryUI):
if not lp:
fname = _('Calibre Library')
try:
base = os.path.expanduser(u'~')
base = os.path.expanduser('~')
except ValueError:
base = QDir.homePath().replace('/', os.sep)
@ -778,7 +777,7 @@ class LibraryPage(QWizardPage, LibraryUI):
except:
traceback.print_exc()
try:
lp = os.path.expanduser(u'~')
lp = os.path.expanduser('~')
except ValueError:
lp = QDir.homePath().replace('/', os.sep)
self.location.setText(lp)

View File

@ -1,6 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'

View File

@ -1,6 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
@ -136,7 +136,7 @@ class CustomColumns(object):
x = [y.strip() for y in x if y.strip()]
x = [y.decode(preferred_encoding, 'replace') if not isinstance(y,
unicode_type) else y for y in x]
return [u' '.join(y.split()) for y in x]
return [' '.join(y.split()) for y in x]
else:
return x if x is None or isinstance(x, unicode_type) else \
x.decode(preferred_encoding, 'replace')

View File

@ -1,8 +1,11 @@
from __future__ import absolute_import, division, print_function, unicode_literals
'''
Created on 25 May 2010
@author: charles
'''
import traceback
from collections import OrderedDict

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
@ -63,19 +64,19 @@ class DBPrefs(dict):
self.__setitem__(key, val)
def get_namespaced(self, namespace, key, default=None):
key = u'namespaced:%s:%s'%(namespace, key)
key = 'namespaced:%s:%s'%(namespace, key)
try:
return dict.__getitem__(self, key)
except KeyError:
return default
def set_namespaced(self, namespace, key, val):
if u':' in key:
if ':' in key:
raise KeyError('Colons are not allowed in keys')
if u':' in namespace:
if ':' in namespace:
raise KeyError('Colons are not allowed in'
' the namespace')
key = u'namespaced:%s:%s'%(namespace, key)
key = 'namespaced:%s:%s'%(namespace, key)
self[key] = val
def write_serialized(self, library_path):

View File

@ -12,11 +12,10 @@ import errno, os, sys, numbers, hashlib, json
from functools import partial
import dukpy
from polyglot.builtins import reraise
from calibre.constants import iswindows
from calibre.utils.filenames import atomic_rename
from polyglot.builtins import error_message, getcwd
from polyglot.builtins import error_message, getcwd, reraise, unicode_type
Context_, undefined = dukpy.Context, dukpy.undefined
@ -112,7 +111,7 @@ def load_file(base_dirs, builtin_modules, name):
raise
raise EnvironmentError('No module named: %s found in the base directories: %s' % (name, os.pathsep.join(base_dirs)))
except Exception as e:
return [False, str(e)]
return [False, unicode_type(e)]
def readfile(path, enc='utf-8'):
@ -156,7 +155,7 @@ class Function(object):
def __repr__(self):
# For some reason x._Formals is undefined in duktape
x = self.func
return str('[Function: %s(...) from file: %s]' % (x.name, x.fileName))
return unicode_type('[Function: %s(...) from file: %s]' % (x.name, x.fileName))
def __call__(self, *args, **kwargs):
try: