1
0
mirror of https://github.com/gryf/ebook-converter.git synced 2026-04-21 13:41:30 +02:00

Removed osx code

This commit is contained in:
2020-07-18 18:02:59 +02:00
parent 45b6bb5b2c
commit f1837397a1
8 changed files with 137 additions and 148 deletions
-3
View File
@@ -17,14 +17,11 @@ Various run time constants.
_plat = sys.platform.lower()
isosx = 'darwin' in _plat
isnewosx = isosx and getattr(sys, 'new_app_bundle', False)
isfreebsd = 'freebsd' in _plat
isnetbsd = 'netbsd' in _plat
isdragonflybsd = 'dragonfly' in _plat
ishaiku = 'haiku1' in _plat
isfrozen = hasattr(sys, 'frozen')
isunix = True
isportable = os.getenv('CALIBRE_PORTABLE_BUILD') is not None
isxp = isoldvista = False
is64bit = sys.maxsize > (1 << 32)
+5 -10
View File
@@ -2,16 +2,10 @@ import importlib
import sys
import zipfile
from ebook_converter.constants_old import numeric_version, isosx
from ebook_converter.constants_old import numeric_version
from ebook_converter.ptempfile import PersistentTemporaryFile
platform = 'linux'
if isosx:
platform = 'osx'
class PluginNotFound(ValueError):
pass
@@ -482,7 +476,8 @@ class CatalogPlugin(Plugin):
# TODO(gryf): remove this entire abomination in favor of map and lazy
# importing if needed.
from ebook_converter.customize.builtins import plugins as builtin_plugins
from ebook_converter.customize.builtins import plugins as \
builtin_plugins
if not type(self) in builtin_plugins:
raise ValueError(f'Plugin type "{self.__str__}" not found')
@@ -526,8 +521,8 @@ class InterfaceActionBase(Plugin):
ac = self.actual_plugin_
if ac is None:
mod, cls = self.actual_plugin.split(':')
ac = getattr(importlib.import_module(mod), cls)(gui,
self.site_customization)
ac = getattr(importlib.import_module(mod),
cls)(gui, self.site_customization)
self.actual_plugin_ = ac
return ac
+13 -13
View File
@@ -3,16 +3,11 @@ from struct import pack
from io import BytesIO
from ebook_converter.ebooks.oeb import base
from ebook_converter.constants_old import isosx
from ebook_converter.ebooks.mobi.utils import (utf8_text, to_base)
from ebook_converter.utils.localization import lang_as_iso639_1
from ebook_converter.ebooks.metadata import authors_to_sort_string
__license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
EXTH_CODES = {
'creator': 100,
'publisher': 101,
@@ -67,7 +62,7 @@ def build_exth(metadata, prefer_author_sort=False, is_periodical=False,
elif term == 'rights':
try:
rights = utf8_text(str(metadata.rights[0]))
except:
except Exception:
rights = b'Unknown'
exth.write(pack(b'>II', EXTH_CODES['rights'], len(rights) + 8))
exth.write(rights)
@@ -145,7 +140,8 @@ def build_exth(metadata, prefer_author_sort=False, is_periodical=False,
exth.write(datestr)
nrecs += 1
if is_periodical:
exth.write(pack(b'>II', EXTH_CODES['lastupdatetime'], len(datestr) + 8))
exth.write(pack(b'>II', EXTH_CODES['lastupdatetime'],
len(datestr) + 8))
exth.write(datestr)
nrecs += 1
@@ -174,8 +170,11 @@ def build_exth(metadata, prefer_author_sort=False, is_periodical=False,
if thumbnail_offset is not None:
exth.write(pack(b'>III', EXTH_CODES['thumboffset'], 12,
thumbnail_offset))
thumbnail_uri_str = ('kindle:embed:%s' %(to_base(thumbnail_offset, base=32, min_num_digits=4))).encode('utf-8')
exth.write(pack(b'>II', EXTH_CODES['kf8_thumbnail_uri'], len(thumbnail_uri_str) + 8))
thumbnail_uri_str = ('kindle:embed:%s' %
to_base(thumbnail_offset, base=32,
min_num_digits=4)).encode('utf-8')
exth.write(pack(b'>II', EXTH_CODES['kf8_thumbnail_uri'],
len(thumbnail_uri_str) + 8))
exth.write(thumbnail_uri_str)
nrecs += 2
@@ -186,8 +185,7 @@ def build_exth(metadata, prefer_author_sort=False, is_periodical=False,
start_offset = [start_offset]
for so in start_offset:
if so is not None:
exth.write(pack(b'>III', EXTH_CODES['startreading'], 12,
so))
exth.write(pack(b'>III', EXTH_CODES['startreading'], 12, so))
nrecs += 1
if kf8_header_index is not None:
@@ -207,13 +205,15 @@ def build_exth(metadata, prefer_author_sort=False, is_periodical=False,
if primary_writing_mode:
pwm = primary_writing_mode.encode('utf-8')
exth.write(pack(b'>II', EXTH_CODES['primary_writing_mode'], len(pwm) + 8))
exth.write(pack(b'>II', EXTH_CODES['primary_writing_mode'],
len(pwm) + 8))
exth.write(pwm)
nrecs += 1
if page_progression_direction in {'rtl', 'ltr', 'default'}:
ppd = page_progression_direction.encode('ascii')
exth.write(pack(b'>II', EXTH_CODES['page_progression_direction'], len(ppd) + 8))
exth.write(pack(b'>II', EXTH_CODES['page_progression_direction'],
len(ppd) + 8))
exth.write(ppd)
nrecs += 1
+28 -31
View File
@@ -1,13 +1,13 @@
__license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
"""
Provides platform independent temporary files that persist even after
being closed.
"""
import tempfile, os, atexit
import atexit
import os
import tempfile
from ebook_converter.constants_old import __version__, __appname__, \
filesystem_encoding, isosx
filesystem_encoding
def cleanup(path):
@@ -15,7 +15,7 @@ def cleanup(path):
import os as oss
if oss.path.exists(path):
oss.remove(path)
except:
except Exception:
pass
@@ -26,7 +26,7 @@ def remove_dir(x):
try:
import shutil
shutil.rmtree(x, ignore_errors=True)
except:
except Exception:
pass
@@ -36,7 +36,7 @@ def determined_remove_dir(x):
import shutil
shutil.rmtree(x)
return
except:
except Exception:
import os # noqa
if os.path.exists(x):
# In case some other program has one of the temp files open.
@@ -47,7 +47,7 @@ def determined_remove_dir(x):
try:
import shutil
shutil.rmtree(x, ignore_errors=True)
except:
except Exception:
pass
@@ -67,13 +67,15 @@ def osx_cache_dir():
import ctypes
libc = ctypes.CDLL(None)
buf = ctypes.create_string_buffer(512)
l = libc.confstr(65538, ctypes.byref(buf), len(buf)) # _CS_DARWIN_USER_CACHE_DIR = 65538
if 0 < l < len(buf):
# _CS_DARWIN_USER_CACHE_DIR = 65538
buflen = libc.confstr(65538, ctypes.byref(buf), len(buf))
if 0 < buflen < len(buf):
try:
q = buf.value.decode('utf-8').rstrip('\0')
except ValueError:
pass
if q and os.path.isdir(q) and os.access(q, os.R_OK | os.W_OK | os.X_OK):
if q and os.path.isdir(q) and os.access(q, os.R_OK | os.W_OK |
os.X_OK):
_osx_cache_dir = q
return q
@@ -98,20 +100,12 @@ def base_dir():
else:
base = os.environ.get('CALIBRE_TEMP_DIR', None)
prefix = app_prefix('tmp_')
if base is None:
if isosx:
# Use the cache dir rather than the temp dir for temp files as Apple
# thinks deleting unused temp files is a good idea. See note under
# _CS_DARWIN_USER_TEMP_DIR here
# https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/confstr.3.html
base = osx_cache_dir()
_base_dir = tempfile.mkdtemp(prefix=prefix, dir=base)
atexit.register(remove_dir, _base_dir)
try:
tempfile.gettempdir()
except:
except Exception:
# Widows temp vars set to a path not encodable in mbcs
# Use our temp dir
tempfile.tempdir = _base_dir
@@ -144,10 +138,10 @@ def _make_dir(suffix, prefix, base):
class PersistentTemporaryFile(object):
"""
A file-like object that is a temporary file that is available even after being closed on
all platforms. It is automatically deleted on normal program termination.
A file-like object that is a temporary file that is available even after
being closed on all platforms. It is automatically deleted on normal
program termination.
"""
_file = None
@@ -177,15 +171,15 @@ class PersistentTemporaryFile(object):
def __del__(self):
try:
self.close()
except:
except Exception:
pass
def PersistentTemporaryDirectory(suffix='', prefix='', dir=None):
'''
"""
Return the path to a newly created temporary directory that will
be automatically deleted on application exit.
'''
"""
if dir is None:
dir = base_dir()
tdir = _make_dir(suffix, prefix, dir)
@@ -195,10 +189,9 @@ def PersistentTemporaryDirectory(suffix='', prefix='', dir=None):
class TemporaryDirectory(object):
'''
"""
A temporary directory to be used in a with statement.
'''
"""
def __init__(self, suffix='', prefix='', dir=None, keep=False):
self.suffix = suffix
@@ -227,7 +220,10 @@ class TemporaryFile(object):
suffix = ''
if dir is None:
dir = base_dir()
self.prefix, self.suffix, self.dir, self.mode = prefix, suffix, dir, mode
self.mode = mode
self.dir = dir
self.suffix = suffix
self.prefix = prefix
self._file = None
def __enter__(self):
@@ -253,7 +249,8 @@ class SpooledTemporaryFile(tempfile.SpooledTemporaryFile):
dir = base_dir()
self._name = None
tempfile.SpooledTemporaryFile.__init__(self, max_size=max_size,
suffix=suffix, prefix=prefix, dir=dir, mode=mode)
suffix=suffix, prefix=prefix,
dir=dir, mode=mode)
@property
def name(self):
+4 -5
View File
@@ -30,8 +30,6 @@ if not _run_once:
#
# Convert command line arguments to unicode
enc = constants_old.preferred_encoding
if constants_old.isosx:
enc = 'utf-8'
for i in range(1, len(sys.argv)):
if not isinstance(sys.argv[i], str):
sys.argv[i] = sys.argv[i].decode(enc, 'replace')
@@ -62,13 +60,14 @@ if not _run_once:
import string
string
try:
locale.setlocale(locale.LC_ALL, '') # set the locale to the user's default locale
except:
# set the locale to the user's default locale
locale.setlocale(locale.LC_ALL, '')
except Exception:
dl = locale.getdefaultlocale()
try:
if dl:
locale.setlocale(locale.LC_ALL, dl[0])
except:
except Exception:
pass
def connect_lambda(bound_signal, self, func, **kw):
+49 -33
View File
@@ -3,7 +3,7 @@ import datetime
import time
import functools
from ebook_converter.constants_old import isosx, plugins, preferred_encoding
from ebook_converter.constants_old import preferred_encoding
from ebook_converter.utils.iso8601 import utc_tz, local_tz, UNDEFINED_DATE
from ebook_converter.utils.localization import lcdata
@@ -24,9 +24,10 @@ try:
import locale
raw = locale.nl_langinfo(locale.D_FMT)
parse_date_day_first = first_index(raw, ('%d', '%a', '%A')) < first_index(raw, ('%m', '%b', '%B'))
parse_date_day_first = (first_index(raw, ('%d', '%a', '%A')) <
first_index(raw, ('%m', '%b', '%B')))
del raw, first_index
except:
except Exception:
parse_date_day_first = False
DEFAULT_DATE = datetime.datetime(2000, 1, 1, tzinfo=utc_tz)
@@ -61,9 +62,9 @@ def iso_pat():
def parse_date(date_string, assume_utc=False, as_utc=True, default=None):
'''
Parse a date/time string into a timezone aware datetime object. The timezone
is always either UTC or the local timezone.
"""
Parse a date/time string into a timezone aware datetime object. The
timezone is always either UTC or the local timezone.
:param assume_utc: If True and date_string does not specify a timezone,
assume UTC, otherwise assume local timezone.
@@ -72,7 +73,7 @@ def parse_date(date_string, assume_utc=False, as_utc=True, default=None):
:param default: Missing fields are filled in from default. If None, the
current month and year are used.
'''
"""
from dateutil.parser import parse
if not date_string:
return UNDEFINED_DATE
@@ -81,7 +82,8 @@ def parse_date(date_string, assume_utc=False, as_utc=True, default=None):
if default is None:
func = (datetime.datetime.utcnow if assume_utc
else datetime.datetime.now)
default = func().replace(day=15, hour=0, minute=0, second=0, microsecond=0,
default = func().replace(day=15, hour=0, minute=0, second=0,
microsecond=0,
tzinfo=_utc_tz if assume_utc else _local_tz)
if iso_pat().match(date_string) is not None:
dt = parse(date_string, default=default)
@@ -110,7 +112,8 @@ def parse_only_date(raw, assume_utc=True, as_utc=True):
f = utcnow if assume_utc else now
default = f().replace(hour=0, minute=0, second=0, microsecond=0,
day=15)
return fix_only_date(parse_date(raw, default=default, assume_utc=assume_utc, as_utc=as_utc))
return fix_only_date(parse_date(raw, default=default,
assume_utc=assume_utc, as_utc=as_utc))
def strptime(val, fmt, assume_utc=False, as_utc=True):
@@ -127,7 +130,8 @@ def dt_factory(time_t, assume_utc=False, as_utc=True):
return dt.astimezone(_utc_tz if as_utc else _local_tz)
safeyear = lambda x: min(max(x, datetime.MINYEAR), datetime.MAXYEAR)
def _safeyear(year):
return min(max(year, datetime.MINYEAR), datetime.MAXYEAR)
def qt_to_dt(qdate_or_qdatetime, as_utc=True):
@@ -137,17 +141,23 @@ def qt_to_dt(qdate_or_qdatetime, as_utc=True):
o = o.toUTC()
d, t = o.date(), o.time()
try:
ans = datetime.datetime(safeyear(d.year()), d.month(), d.day(), t.hour(), t.minute(), t.second(), t.msec()*1000, utc_tz)
ans = datetime.datetime(_safeyear(d.year()), d.month(), d.day(),
t.hour(), t.minute(), t.second(),
t.msec()*1000, utc_tz)
except ValueError:
ans = datetime.datetime(safeyear(d.year()), d.month(), 1, t.hour(), t.minute(), t.second(), t.msec()*1000, utc_tz)
ans = datetime.datetime(_safeyear(d.year()), d.month(), 1,
t.hour(), t.minute(), t.second(),
t.msec()*1000, utc_tz)
if not as_utc:
ans = ans.astimezone(local_tz)
return ans
try:
dt = datetime.datetime(safeyear(o.year()), o.month(), o.day()).replace(tzinfo=_local_tz)
dt = datetime.datetime(_safeyear(o.year()), o.month(),
o.day()).replace(tzinfo=_local_tz)
except ValueError:
dt = datetime.datetime(safeyear(o.year()), o.month(), 1).replace(tzinfo=_local_tz)
dt = datetime.datetime(_safeyear(o.year()), o.month(),
1).replace(tzinfo=_local_tz)
return dt.astimezone(_utc_tz if as_utc else _local_tz)
@@ -249,7 +259,8 @@ def utcnow():
def utcfromtimestamp(stamp):
try:
return datetime.datetime.utcfromtimestamp(stamp).replace(tzinfo=_utc_tz)
return (datetime.datetime.utcfromtimestamp(stamp)
.replace(tzinfo=_utc_tz))
except ValueError:
# Raised if stamp is out of range for the platforms gmtime function
# For example, this happens with negative values on windows
@@ -269,25 +280,25 @@ def timestampfromdt(dt, assume_utc=True):
def fd_format_hour(dt, ampm, hr):
l = len(hr)
length = len(hr)
h = dt.hour
if ampm:
h = h % 12
if l == 1:
if length == 1:
return '%d' % h
return '%02d' % h
def fd_format_minute(dt, ampm, min):
l = len(min)
if l == 1:
length = len(min)
if length == 1:
return '%d' % dt.minute
return '%02d' % dt.minute
def fd_format_second(dt, ampm, sec):
l = len(sec)
if l == 1:
length = len(sec)
if length == 1:
return '%d' % dt.second
return '%02d' % dt.second
@@ -300,21 +311,21 @@ def fd_format_ampm(dt, ampm, ap):
def fd_format_day(dt, ampm, dy):
l = len(dy)
if l == 1:
length = len(dy)
if length == 1:
return '%d' % dt.day
if l == 2:
if length == 2:
return '%02d' % dt.day
return lcdata['abday' if l == 3 else 'day'][(dt.weekday() + 1) % 7]
return lcdata['abday' if length == 3 else 'day'][(dt.weekday() + 1) % 7]
def fd_format_month(dt, ampm, mo):
l = len(mo)
if l == 1:
length = len(mo)
if length == 1:
return '%d' % dt.month
if l == 2:
if length == 2:
return '%02d' % dt.month
return lcdata['abmon' if l == 3 else 'mon'][dt.month - 1]
return lcdata['abmon' if length == 3 else 'mon'][dt.month - 1]
def fd_format_year(dt, ampm, yr):
@@ -343,7 +354,10 @@ def fd_repl_func(dt, ampm, mo):
def format_date(dt, format, assume_utc=False, as_utc=False):
''' Return a date formatted as a string using a subset of Qt's formatting codes '''
"""
Return a date formatted as a string using a subset of Qt's formatting
codes
"""
if not format:
format = 'dd MMM yyyy'
@@ -440,9 +454,11 @@ def clean_date_for_sort(dt, fmt=None):
'min': UNDEFINED_DATE.minute, 'sec': UNDEFINED_DATE.second}
repl_func = functools.partial(cd_repl_func, tt, dt)
re.sub('(s{1,2})|(m{1,2})|(h{1,2})|(d{1,4}|M{1,4}|(?:yyyy|yy))', repl_func, fmt)
return dt.replace(year=tt['year'], month=tt['mon'], day=tt['day'], hour=tt['hour'],
minute=tt['min'], second=tt['sec'], microsecond=0)
re.sub('(s{1,2})|(m{1,2})|(h{1,2})|(d{1,4}|M{1,4}|(?:yyyy|yy))',
repl_func, fmt)
return dt.replace(year=tt['year'], month=tt['mon'], day=tt['day'],
hour=tt['hour'], minute=tt['min'], second=tt['sec'],
microsecond=0)
# }}}
+1 -11
View File
@@ -3,8 +3,7 @@ from collections import defaultdict
from threading import Thread
from ebook_converter import walk
from ebook_converter.constants_old import isosx
from ebook_converter.constants_old import plugins, DEBUG
from ebook_converter.constants_old import DEBUG
from ebook_converter.constants_old import filesystem_encoding
from ebook_converter.utils.fonts.metadata import FontMetadata, UnsupportedFont
@@ -90,15 +89,6 @@ def fc_list():
def font_dirs():
if isosx:
return [
'/Library/Fonts',
'/System/Library/Fonts',
'/usr/share/fonts',
'/var/root/Library/Fonts',
os.path.expanduser('~/.fonts'),
os.path.expanduser('~/Library/Fonts'),
]
return fc_list()
# }}}
-5
View File
@@ -16,7 +16,6 @@ del err
def collator():
__import__('pdb').set_trace()
global _collator, _locale
if _collator is None:
if _locale is None:
@@ -34,7 +33,6 @@ def collator():
def primary_collator():
__import__('pdb').set_trace()
'Ignores case differences and accented characters'
global _primary_collator
if _primary_collator is None:
@@ -44,7 +42,6 @@ def primary_collator():
def sort_collator():
__import__('pdb').set_trace()
'Ignores case differences and recognizes numbers in strings (if the tweak is set)'
global _sort_collator
if _sort_collator is None:
@@ -55,7 +52,6 @@ def sort_collator():
def numeric_collator():
__import__('pdb').set_trace()
'Uses natural sorting for numbers inside strings so something2 will sort before something10'
global _numeric_collator
if _numeric_collator is None:
@@ -66,7 +62,6 @@ def numeric_collator():
def case_sensitive_collator():
__import__('pdb').set_trace()
'Always sorts upper case letter before lower case'
global _case_sensitive_collator
if _case_sensitive_collator is None: