Get rid of the PyQt4 string from everywhere

This commit is contained in:
Kovid Goyal 2014-04-11 18:55:49 +05:30
parent 62f72877e9
commit 5068f62f0f
10 changed files with 15 additions and 726 deletions

View File

@ -7,7 +7,7 @@ __license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
from PyQt4.Qt import QWidget, QHBoxLayout, QLabel, QLineEdit from PyQt5.Qt import QWidget, QHBoxLayout, QLabel, QLineEdit
from calibre.utils.config import JSONConfig from calibre.utils.config import JSONConfig

View File

@ -13,7 +13,7 @@ if False:
# You do not need this code in your plugins # You do not need this code in your plugins
get_icons = get_resources = None get_icons = get_resources = None
from PyQt4.Qt import QDialog, QVBoxLayout, QPushButton, QMessageBox, QLabel from PyQt5.Qt import QDialog, QVBoxLayout, QPushButton, QMessageBox, QLabel
from calibre_plugins.interface_demo.config import prefs from calibre_plugins.interface_demo.config import prefs
@ -136,7 +136,8 @@ class DemoDialog(QDialog):
mi = self.db.get_metadata(book_id, index_is_id=True, mi = self.db.get_metadata(book_id, index_is_id=True,
get_cover=True, cover_as_data=True) get_cover=True, cover_as_data=True)
fmts = self.db.formats(book_id, index_is_id=True) fmts = self.db.formats(book_id, index_is_id=True)
if not fmts: continue if not fmts:
continue
for fmt in fmts.split(','): for fmt in fmts.split(','):
fmt = fmt.lower() fmt = fmt.lower()
# Get a python file object for the format. This will be either # Get a python file object for the format. This will be either

View File

@ -1,277 +0,0 @@
#!/usr/bin/env python
from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net'
__docformat__ = 'restructuredtext en'
'''
Create linux binary.
'''
from setup import Command, __version__, __appname__
class LinuxFreeze(Command):
description = 'Create frozen linux binary'
def run(self, opts):
import glob, sys, tarfile, os, textwrap, shutil, platform
from contextlib import closing
from cx_Freeze import Executable, setup
from calibre.linux import entry_points
from calibre import walk
is64bit = platform.architecture()[0] == '64bit'
arch = 'x86_64' if is64bit else 'i686'
ffi = '/usr/lib/gcc/x86_64-pc-linux-gnu/4.4.2/libffi.so.4' if is64bit else '/usr/lib/gcc/i686-pc-linux-gnu/4.4.1/libffi.so.4'
stdcpp = '/usr/lib/gcc/%s-pc-linux-gnu/%s/libstdc++.so.6'%(arch, '4.4.2'
if is64bit else '4.4.1')
QTDIR = '/usr/lib/qt4'
QTDLLS = ('QtCore', 'QtGui', 'QtNetwork', 'QtSvg', 'QtXml',
'QtWebKit', 'QtDBus', 'QtXmlPatterns')
binary_excludes = ['libGLcore*', 'libGL*', 'libnvidia*']
os.system('sudo cp /usr/bin/calibre-mount-helper /tmp/calibre-mount-helper')
os.system('sudo chown kovid:users /tmp/calibre-mount-helper')
binary_includes = [
'/usr/bin/pdftohtml',
'/usr/lib/libwmflite-0.2.so.7',
'/usr/lib/liblcms.so.1',
'/usr/lib/liblcms2.so.2',
'/usr/lib/libstlport.so.5.1',
'/tmp/calibre-mount-helper',
'/usr/lib/libchm.so.0',
'/usr/lib/libsqlite3.so.0',
'/usr/lib/libmng.so.1',
'/usr/lib/libpodofo.so.0.8.2',
'/lib/libz.so.1',
'/lib/libuuid.so.1',
'/usr/lib/libtiff.so.5',
'/lib/libbz2.so.1',
'/usr/lib/libpoppler.so.6',
'/usr/lib/libxml2.so.2',
'/usr/lib/libopenjpeg.so.2',
'/usr/lib/libxslt.so.1',
'/usr/lib/libjpeg.so.7',
'/usr/lib/libxslt.so.1',
'/usr/lib/libgthread-2.0.so.0',
stdcpp,
ffi,
'/usr/lib/libpng14.so.14',
'/usr/lib/libexslt.so.0',
'/usr/lib/libMagickWand.so.3',
'/usr/lib/libMagickCore.so.3',
'/usr/lib/libgcrypt.so.11',
'/usr/lib/libgpg-error.so.0',
'/usr/lib/libphonon.so.4',
'/usr/lib/libssl.so.0.9.8',
'/usr/lib/libcrypto.so.0.9.8',
'/lib/libreadline.so.6',
]
binary_includes += [os.path.join(QTDIR, 'lib%s.so.4'%x) for x in QTDLLS]
CALIBRESRC = self.d(self.SRC)
CALIBREPLUGINS = os.path.join(CALIBRESRC, 'src', 'calibre', 'plugins')
FREEZE_DIR = os.path.join(CALIBRESRC, 'build', 'cx_freeze')
DIST_DIR = os.path.join(CALIBRESRC, 'dist')
os.chdir(CALIBRESRC)
self.info('Freezing calibre located at', CALIBRESRC)
entry_points = entry_points['console_scripts'] + entry_points['gui_scripts']
entry_points = ['calibre_postinstall=calibre.linux:main'] + entry_points
executables = {}
for ep in entry_points:
executables[ep.split('=')[0].strip()] = (ep.split('=')[1].split(':')[0].strip(),
ep.split(':')[-1].strip())
if os.path.exists(FREEZE_DIR):
shutil.rmtree(FREEZE_DIR)
os.makedirs(FREEZE_DIR)
if not os.path.exists(DIST_DIR):
os.makedirs(DIST_DIR)
includes = [x[0] for x in executables.values()]
includes += ['email.iterators', 'email.generator', 'sqlite3.dump']
excludes = ['matplotlib', "Tkconstants", "Tkinter", "tcl", "_imagingtk",
"ImageTk", "FixTk", 'wx', 'PyQt4.QtAssistant', 'PyQt4.QtOpenGL.so',
'PyQt4.QtScript.so', 'PyQt4.QtSql.so', 'PyQt4.QtTest.so', 'qt',
'glib', 'gobject']
packages = ['calibre', 'encodings', 'cherrypy', 'cssutils', 'xdg',
'dateutil', 'dns', 'email', 'dbus']
includes += ['calibre.gui2.convert.'+x.split('/')[-1].rpartition('.')[0] for x in \
glob.glob('src/calibre/gui2/convert/*.py')]
includes += ['calibre.gui2.catalog.'+x.split('/')[-1].rpartition('.')[0] for x in \
glob.glob('src/calibre/gui2/catalog/*.py')]
includes += ['calibre.gui2.actions.'+x.split('/')[-1].rpartition('.')[0] for x in \
glob.glob('src/calibre/gui2/actions/*.py')]
includes += ['calibre.gui2.preferences.'+x.split('/')[-1].rpartition('.')[0] for x in \
glob.glob('src/calibre/gui2/preferences/*.py')]
LOADER = '/tmp/loader.py'
open(LOADER, 'wb').write('# This script is never actually used.\nimport sys')
INIT_SCRIPT = '/tmp/init.py'
open(INIT_SCRIPT, 'wb').write(textwrap.dedent('''
## Load calibre module specified in the environment variable CALIBRE_CX_EXE
## Also restrict sys.path to the executables' directory and add the
## executables directory to LD_LIBRARY_PATH
import encodings
import os
import sys
import warnings
import zipimport
import locale
import codecs
enc = locale.getdefaultlocale()[1]
if not enc:
enc = locale.nl_langinfo(locale.CODESET)
enc = codecs.lookup(enc if enc else 'UTF-8').name
sys.setdefaultencoding(enc)
paths = os.environ.get('LD_LIBRARY_PATH', '').split(os.pathsep)
if DIR_NAME not in paths or not sys.getfilesystemencoding():
paths.insert(0, DIR_NAME)
os.environ['LD_LIBRARY_PATH'] = os.pathsep.join(paths)
os.environ['PYTHONIOENCODING'] = enc
os.execv(sys.executable, sys.argv)
sys.path = sys.path[:3]
sys.frozen = True
sys.frozen_path = DIR_NAME
sys.extensions_location = os.path.join(DIR_NAME, 'plugins')
sys.resources_location = os.path.join(DIR_NAME, 'resources')
dfv = os.environ.get('CALIBRE_DEVELOP_FROM', None)
if dfv and os.path.exists(dfv):
sys.path.insert(0, os.path.abspath(dfv))
executables = %(executables)s
exe = os.environ.get('CALIBRE_CX_EXE', False)
ret = 1
if not exe:
print >>sys.stderr, 'Invalid invocation of calibre loader. CALIBRE_CX_EXE not set'
elif exe not in executables:
print >>sys.stderr, 'Invalid invocation of calibre loader. CALIBRE_CX_EXE=%%s is unknown'%%exe
else:
sys.argv[0] = exe
module, func = executables[exe]
module = __import__(module, fromlist=[1])
func = getattr(module, func)
ret = func()
module = sys.modules.get("threading")
if module is not None:
module._shutdown()
sys.exit(ret)
''')%dict(executables=repr(executables)))
sys.argv = ['freeze', 'build_exe']
setup(
name = __appname__,
version = __version__,
executables = [Executable(script=LOADER, targetName='loader', compress=False)],
options = { 'build_exe' :
{
'build_exe' : os.path.join(CALIBRESRC, 'build/cx_freeze'),
'optimize' : 2,
'excludes' : excludes,
'includes' : includes,
'packages' : packages,
'init_script' : INIT_SCRIPT,
'copy_dependent_files' : True,
'create_shared_zip' : False,
}
}
)
def copy_binary(src, dest_dir):
dest = os.path.join(dest_dir, os.path.basename(src))
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
shutil.copyfile(os.path.realpath(src), dest)
shutil.copymode(os.path.realpath(src), dest)
for f in binary_includes:
copy_binary(f, FREEZE_DIR)
for pat in binary_excludes:
matches = glob.glob(os.path.join(FREEZE_DIR, pat))
for f in matches:
os.remove(f)
self.info('Adding ImageMagick...')
im = glob.glob('/usr/lib/ImageMagick-*')[0]
dest = os.path.join(FREEZE_DIR, 'ImageMagick')
shutil.copytree(im, dest)
for x in os.walk(dest):
for f in x[-1]:
if f.endswith('.a'):
os.remove(os.path.join(x[0], f))
self.info('Adding calibre plugins...')
os.makedirs(os.path.join(FREEZE_DIR, 'plugins'))
for f in glob.glob(os.path.join(CALIBREPLUGINS, '*.so')):
copy_binary(f, os.path.join(FREEZE_DIR, 'plugins'))
self.info('Adding calibre resources...')
shutil.copytree('resources', os.path.join(FREEZE_DIR, 'resources'))
self.info('Adding Qt plugins...')
plugdir = os.path.join(QTDIR, 'plugins')
for dirpath, dirnames, filenames in os.walk(plugdir):
for f in filenames:
if not f.endswith('.so') or 'designer' in dirpath or 'codecs' in dirpath or 'sqldrivers' in dirpath:
continue
f = os.path.join(dirpath, f)
dest_dir = dirpath.replace(plugdir, os.path.join(FREEZE_DIR, 'qtplugins'))
copy_binary(f, dest_dir)
self.info('Creating launchers')
for exe in executables:
path = os.path.join(FREEZE_DIR, exe)
open(path, 'wb').write(textwrap.dedent('''\
#!/bin/sh
export CALIBRE_CX_EXE=%s
path=`readlink -e $0`
base=`dirname $path`
loader=$base/loader
export LD_LIBRARY_PATH=$base:$LD_LIBRARY_PATH
export MAGICK_CONFIGURE_PATH=$base/ImageMagick/config
export MAGICK_CODER_MODULE_PATH=$base/ImageMagick/modules-Q16/coders
export MAGICK_CODER_FILTER_PATH=$base/ImageMagick/modules-Q16/filter
export QT_PLUGIN_PATH=$base/qtplugins:$QT_PLUGIN_PATH
$loader "$@"
''')%exe)
os.chmod(path, 0755)
exes = list(executables.keys())
exes.remove('calibre_postinstall')
open(os.path.join(FREEZE_DIR, 'manifest'), 'wb').write('\n'.join(exes))
self.info('Creating archive...')
dist = open(os.path.join(DIST_DIR, 'calibre-%s-%s.tar.bz2'%(__version__,
arch)), 'wb')
with closing(tarfile.open(fileobj=dist, mode='w:bz2',
format=tarfile.PAX_FORMAT)) as tf:
for f in walk(FREEZE_DIR):
name = f.replace(FREEZE_DIR, '')[1:]
if name:
tf.add(f, name)
dist.flush()
dist.seek(0, 2)
self.info('Archive %s created: %.2f MB'%(dist.name,
dist.tell()/(1024.**2)))

View File

@ -12,7 +12,7 @@ import sys, os, shutil, platform, subprocess, stat, py_compile, glob, \
from setup import Command, modules, basenames, functions, __version__, \ from setup import Command, modules, basenames, functions, __version__, \
__appname__ __appname__
SITE_PACKAGES = ['PIL', 'dateutil', 'dns', 'PyQt4', 'mechanize', SITE_PACKAGES = ['PIL', 'dateutil', 'dns', 'PyQt5', 'mechanize',
'sip.so', 'BeautifulSoup.py', 'cssutils', 'encutils', 'lxml', 'sip.so', 'BeautifulSoup.py', 'cssutils', 'encutils', 'lxml',
'sipconfig.py', 'xdg', 'dbus', '_dbus_bindings.so', 'sipconfig.py', 'xdg', 'dbus', '_dbus_bindings.so',
'_dbus_glib_bindings.so', 'netifaces.so', '_psutil_posix.so', '_dbus_glib_bindings.so', 'netifaces.so', '_psutil_posix.so',
@ -363,7 +363,7 @@ class LinuxFreeze(Command):
def set_qt_plugin_path(): def set_qt_plugin_path():
import uuid import uuid
uuid.uuid4() # Workaround for libuuid/PyQt conflict uuid.uuid4() # Workaround for libuuid/PyQt conflict
from PyQt4.Qt import QCoreApplication from PyQt5.Qt import QCoreApplication
paths = list(map(unicode, QCoreApplication.libraryPaths())) paths = list(map(unicode, QCoreApplication.libraryPaths()))
paths.insert(0, sys.frozen_path + '/lib/qt_plugins') paths.insert(0, sys.frozen_path + '/lib/qt_plugins')
QCoreApplication.setLibraryPaths(paths) QCoreApplication.setLibraryPaths(paths)

View File

@ -1,424 +0,0 @@
#!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
''' Create an OSX installer '''
import sys, re, os, shutil, subprocess, stat, glob, zipfile, plistlib
from setup import __version__ as VERSION, __appname__ as APPNAME, SRC, Command, \
scripts, basenames, functions as main_functions, modules as main_modules
try:
from setuptools import setup
setup
except:
class setup:
pass
try:
from py2app.build_app import py2app
from modulegraph.find_modules import find_modules
py2app
except ImportError:
py2app = object
PYTHON = '/Library/Frameworks/Python.framework/Versions/Current/bin/python'
info = warn = None
class OSX32_Freeze(Command):
description = 'Freeze OSX calibre installation'
def run(self, opts):
global info, warn
info, warn = self.info, self.warn
main()
class BuildAPP(py2app):
QT_PREFIX = '/Volumes/sw/qt'
LOADER_TEMPLATE = \
r'''#!/usr/bin/env python
import os, sys, glob
path = os.path.abspath(os.path.realpath(__file__))
dirpath = os.path.dirname(path)
name = os.path.basename(path)
base_dir = os.path.dirname(os.path.dirname(dirpath))
resources_dir = os.path.join(base_dir, 'Resources')
frameworks_dir = os.path.join(base_dir, 'Frameworks')
extensions_dir = os.path.join(frameworks_dir, 'plugins')
r_dir = os.path.join(resources_dir, 'resources')
base_name = os.path.splitext(name)[0]
python = os.path.join(base_dir, 'MacOS', 'python')
qt_plugins = os.path.join(os.path.realpath(base_dir), 'MacOS')
loader_path = os.path.join(dirpath, base_name+'.py')
loader = open(loader_path, 'w')
site_packages = glob.glob(resources_dir+'/lib/python*/site-packages.zip')[0]
devf = os.environ.get('CALIBRE_DEVELOP_FROM', None)
do_devf = devf and os.path.exists(devf)
if do_devf:
devf = os.path.abspath(devf)
print >>loader, 'import sys'
print >>loader, 'sys.argv[0] =', repr(os.path.basename(path))
print >>loader, 'if', repr(dirpath), 'in sys.path: sys.path.remove(', repr(dirpath), ')'
print >>loader, 'sys.path.append(', repr(site_packages), ')'
if do_devf:
print >>loader, 'sys.path.insert(0, '+repr(devf)+')'
print >>loader, 'sys.frozen = "macosx_app"'
print >>loader, 'sys.frameworks_dir =', repr(frameworks_dir)
print >>loader, 'sys.extensions_location =', repr(extensions_dir)
print >>loader, 'sys.resources_location =', repr(r_dir)
print >>loader, 'import os'
print >>loader, 'from %(module)s import %(function)s'
print >>loader, '%(function)s()'
loader.close()
os.chmod(loader_path, 0700)
os.environ['PYTHONHOME'] = resources_dir
os.environ['FONTCONFIG_PATH'] = os.path.join(resources_dir, 'fonts')
os.environ['MAGICK_HOME'] = os.path.join(frameworks_dir, 'ImageMagick')
os.environ['DYLD_LIBRARY_PATH'] = os.path.join(frameworks_dir, 'ImageMagick', 'lib')
os.environ['QT_PLUGIN_PATH'] = qt_plugins
args = [path, loader_path] + sys.argv[1:]
os.execv(python, args)
'''
def get_modulefinder(self):
if self.debug_modulegraph:
debug = 4
else:
debug = 0
return find_modules(
scripts=scripts['console'] + scripts['gui'],
includes=list(self.includes) + main_modules['console'],
packages=self.packages,
excludes=self.excludes,
debug=debug)
@classmethod
def makedmg(cls, d, volname,
destdir='dist',
internet_enable=True,
format='UDBZ'):
''' Copy a directory d into a dmg named volname '''
if not os.path.exists(destdir):
os.makedirs(destdir)
dmg = os.path.join(destdir, volname+'.dmg')
if os.path.exists(dmg):
os.unlink(dmg)
subprocess.check_call(['/usr/bin/hdiutil', 'create', '-srcfolder', os.path.abspath(d),
'-volname', volname, '-format', format, dmg])
if internet_enable:
subprocess.check_call(['/usr/bin/hdiutil', 'internet-enable', '-yes', dmg])
return dmg
@classmethod
def qt_dependencies(cls, path):
pipe = subprocess.Popen('/usr/bin/otool -L '+path, shell=True, stdout=subprocess.PIPE).stdout
deps = []
for l in pipe.readlines():
match = re.search(r'(.*)\(', l)
if not match:
continue
lib = match.group(1).strip()
if lib.startswith(BuildAPP.QT_PREFIX):
deps.append(lib)
return deps
@classmethod
def fix_qt_dependencies(cls, path, deps):
fp = '@executable_path/../Frameworks/'
info('Fixing qt dependencies for:', os.path.basename(path))
for dep in deps:
match = re.search(r'(Qt\w+?)\.framework', dep)
if not match:
match = re.search(r'(phonon)\.framework', dep)
if not match:
warn(dep)
raise Exception('Unknown Qt dependency')
module = match.group(1)
newpath = fp + '%s.framework/Versions/Current/%s'%(module, module)
cmd = ' '.join(['/usr/bin/install_name_tool', '-change', dep, newpath, path])
subprocess.check_call(cmd, shell=True)
def add_qt_plugins(self):
macos_dir = os.path.join(self.dist_dir, APPNAME + '.app', 'Contents', 'MacOS')
for root, dirs, files in os.walk(BuildAPP.QT_PREFIX+'/plugins'):
for name in files:
if name.endswith('.dylib'):
path = os.path.join(root, name)
dir = os.path.basename(root)
dest_dir = os.path.join(macos_dir, dir)
if not os.path.exists(dest_dir):
os.mkdir(dest_dir)
target = os.path.join(dest_dir, name)
shutil.copyfile(path, target)
shutil.copymode(path, target)
deps = BuildAPP.qt_dependencies(target)
BuildAPP.fix_qt_dependencies(target, deps)
#deps = BuildAPP.qt_dependencies(path)
def fix_python_dependencies(self, files):
for f in files:
subprocess.check_call(['/usr/bin/install_name_tool', '-change', '/Library/Frameworks/Python.framework/Versions/2.6/Python', '@executable_path/../Frameworks/Python.framework/Versions/2.6/Python', f])
def fix_misc_dependencies(self, files):
for path in files:
frameworks_dir = os.path.join(self.dist_dir, APPNAME + '.app', 'Contents', 'Frameworks')
pipe = subprocess.Popen('/usr/bin/otool -L '+path, shell=True, stdout=subprocess.PIPE).stdout
for l in pipe.readlines():
match = re.search(r'\s+(.*?)\s+\(', l)
if match:
dep = match.group(1)
name = os.path.basename(dep)
if not name:
name = dep
bundle = os.path.join(frameworks_dir, name)
if os.path.exists(bundle):
subprocess.check_call(['/usr/bin/install_name_tool', '-change', dep,
'@executable_path/../Frameworks/'+name, path])
def add_plugins(self):
self.add_qt_plugins()
frameworks_dir = os.path.join(self.dist_dir, APPNAME + '.app', 'Contents', 'Frameworks')
plugins_dir = os.path.join(frameworks_dir, 'plugins')
if not os.path.exists(plugins_dir):
os.mkdir(plugins_dir)
maps = {}
for f in glob.glob('src/calibre/plugins/*'):
tgt = plugins_dir
if f.endswith('.dylib'):
tgt = frameworks_dir
maps[f] = os.path.join(tgt, os.path.basename(f))
deps = []
for src, dst in maps.items():
shutil.copyfile(src, dst)
self.fix_qt_dependencies(dst, self.qt_dependencies(dst))
deps.append(dst)
self.fix_python_dependencies(deps)
self.fix_misc_dependencies(deps)
def fix_image_magick_deps(self, root):
modules = []
frameworks_dir = os.path.dirname(root)
for x in os.walk(root):
for f in x[-1]:
if f.endswith('.so'):
modules.append(os.path.join(x[0], f))
for x in os.walk(os.path.join(frameworks_dir, 'plugins')):
for f in x[-1]:
if f.endswith('.so'):
modules.append(os.path.join(x[0], f))
deps = {}
for x in ('Core.1', 'Wand.1'):
modules.append(os.path.join(root, 'lib', 'libMagick%s.dylib'%x))
x = modules[-1]
deps[os.path.join('/Users/kovid/ImageMagick/lib',
os.path.basename(x))] = '@executable_path/../Frameworks/ImageMagick/lib/'+os.path.basename(x)
subprocess.check_call(['install_name_tool', '-id',
'@executable_path/../Frameworks/ImageMagick/lib/'+os.path.basename(x),
x])
for x in ('/usr/local/lib/libfreetype.6.dylib',
'/Volumes/sw/lib/libwmflite-0.2.7.dylib'):
deps[x] = '@executable_path/../Frameworks/'+ os.path.basename(x)
for x in modules:
print 'Fixing deps in', x
for f, t in deps.items():
subprocess.check_call(['install_name_tool', '-change', f, t, x])
def run(self):
py2app.run(self)
resource_dir = os.path.join(self.dist_dir,
APPNAME + '.app', 'Contents', 'Resources')
frameworks_dir = os.path.join(os.path.dirname(resource_dir), 'Frameworks')
all_scripts = scripts['console'] + scripts['gui']
all_names = basenames['console'] + basenames['gui']
all_modules = main_modules['console'] + main_modules['gui']
all_functions = main_functions['console'] + main_functions['gui']
info('\nAdding resources')
dest = os.path.join(resource_dir, 'resources')
if os.path.exists(dest):
shutil.rmtree(dest)
shutil.copytree(os.path.join(os.path.dirname(SRC), 'resources'), dest)
info('\nAdding PoDoFo')
pdf = glob.glob(os.path.expanduser('/Volumes/sw/podofo/libpodofo*.dylib'))[0]
shutil.copyfile(pdf, os.path.join(frameworks_dir, os.path.basename(pdf)))
info('\nAdding poppler')
popps = []
for x in ('bin/pdftohtml', 'lib/libpoppler.5.dylib'):
dest = os.path.join(frameworks_dir, os.path.basename(x))
popps.append(dest)
shutil.copy2(os.path.join('/Volumes/sw', x), dest)
subprocess.check_call(['install_name_tool', '-change',
'/usr/local/lib/libfontconfig.1.dylib',
'@executable_path/../Frameworks/libfontconfig.1.dylib',
os.path.join(frameworks_dir, 'pdftohtml')])
x ='libpng12.0.dylib'
shutil.copy2('/usr/local/lib/'+x, frameworks_dir)
subprocess.check_call(['install_name_tool', '-id',
'@executable_path/../Frameworks/'+x, os.path.join(frameworks_dir, x)])
self.fix_misc_dependencies(popps)
subprocess.check_call(['install_name_tool', '-change',
'/usr/local/lib/libfontconfig.1.dylib',
'@executable_path/../Frameworks/libfontconfig.1.dylib', popps[1]])
subprocess.check_call(['install_name_tool', '-id',
'@executable_path/../Frameworks/'+os.path.basename(popps[1]), popps[1]])
loader_path = os.path.join(resource_dir, 'loaders')
if not os.path.exists(loader_path):
os.mkdir(loader_path)
for name, module, function in zip(all_names, all_modules, all_functions):
path = os.path.join(loader_path, name)
info('Creating loader:', path)
f = open(path, 'w')
f.write(BuildAPP.LOADER_TEMPLATE % dict(module=module,
function=function))
f.close()
os.chmod(path, stat.S_IXUSR|stat.S_IXGRP|stat.S_IXOTH|stat.S_IREAD\
|stat.S_IWUSR|stat.S_IROTH|stat.S_IRGRP)
info('Adding fontconfig')
for f in glob.glob(os.path.expanduser('~/fontconfig-bundled/*')):
dest = os.path.join(frameworks_dir, os.path.basename(f))
if os.path.exists(dest):
os.remove(dest)
shutil.copyfile(f, dest)
dst = os.path.join(resource_dir, 'fonts')
if os.path.exists(dst):
shutil.rmtree(dst)
shutil.copytree('/usr/local/etc/fonts', dst, symlinks=False)
self.add_plugins()
info('Adding IPython')
dst = os.path.join(resource_dir, 'lib', 'python2.6', 'IPython')
if os.path.exists(dst): shutil.rmtree(dst)
shutil.copytree(os.path.expanduser('~/build/ipython/IPython'), dst)
info('Adding ImageMagick')
libwmf = '/Volumes/sw/lib/libwmflite-0.2.7.dylib'
dest = os.path.join(frameworks_dir, os.path.basename(libwmf))
shutil.copy2(libwmf, frameworks_dir)
nid = '@executable_path/../Frameworks/'+os.path.basename(dest)
subprocess.check_call(['install_name_tool', '-id', nid, dest])
dest = os.path.join(frameworks_dir, 'ImageMagick')
if os.path.exists(dest):
shutil.rmtree(dest)
shutil.copytree(os.path.expanduser('~/ImageMagick'), dest, True)
shutil.rmtree(os.path.join(dest, 'include'))
shutil.rmtree(os.path.join(dest, 'share', 'doc'))
shutil.rmtree(os.path.join(dest, 'share', 'man'))
shutil.copyfile('/usr/local/lib/libpng12.0.dylib', os.path.join(dest, 'lib', 'libpng12.0.dylib'))
self.fix_image_magick_deps(dest)
info('Installing prescipt')
sf = [os.path.basename(s) for s in all_names]
launcher_path = os.path.join(resource_dir, '__boot__.py')
f = open(launcher_path, 'r')
src = f.read()
f.close()
src = src.replace('import Image', 'from PIL import Image')
src = re.sub('(_run\s*\(.*?.py.*?\))', '%s'%(
'''
sys.frameworks_dir = os.path.join(os.path.dirname(os.environ['RESOURCEPATH']), 'Frameworks')
sys.resources_location = os.path.join(os.environ['RESOURCEPATH'], 'resources')
sys.extensions_location = os.path.join(sys.frameworks_dir, 'plugins')
devf = os.environ.get('CALIBRE_DEVELOP_FROM', None)
do_devf = devf and os.path.exists(devf)
if do_devf:
devf = os.path.abspath(devf)
sys.path.insert(0, devf)
''') + r'\n\1', src)
f = open(launcher_path, 'w')
print >>f, 'import sys, os'
f.write(src)
f.close()
info('\nAdding main scripts to site-packages')
f = zipfile.ZipFile(os.path.join(self.dist_dir, APPNAME+'.app', 'Contents', 'Resources', 'lib', 'python'+sys.version[:3], 'site-packages.zip'), 'a', zipfile.ZIP_DEFLATED)
for script in scripts['gui']+scripts['console']:
f.write(script, script.partition('/')[-1])
f.close()
info('\nCreating console.app')
contents_dir = os.path.dirname(resource_dir)
cc_dir = os.path.join(contents_dir, 'console.app', 'Contents')
os.makedirs(cc_dir)
for x in os.listdir(contents_dir):
if x == 'console.app':
continue
if x == 'Info.plist':
plist = plistlib.readPlist(os.path.join(contents_dir, x))
plist['LSUIElement'] = '1'
plistlib.writePlist(plist, os.path.join(cc_dir, x))
else:
os.symlink(os.path.join('../..', x),
os.path.join(cc_dir, x))
info('\nBuilding disk image')
BuildAPP.makedmg(os.path.join(self.dist_dir, APPNAME+'.app'), APPNAME+'-'+VERSION)
def main():
sys.argv[1:2] = ['py2app']
d = os.path.dirname
icon = os.path.abspath('icons/library.icns')
if not os.access(icon, os.R_OK):
raise Exception('No icon at '+icon)
setup(
name = APPNAME,
app = [scripts['gui'][0]],
cmdclass = { 'py2app' : BuildAPP },
options = { 'py2app' :
{
'optimize' : 2,
'dist_dir' : 'build/py2app',
'argv_emulation' : True,
'iconfile' : icon,
'frameworks': ['libusb.dylib'],
'includes' : ['sip', 'pkg_resources', 'PyQt4.QtXml',
'PyQt4.QtSvg', 'PyQt4.QtWebKit', 'commands',
'mechanize', 'ClientForm', 'usbobserver',
'genshi', 'calibre.web.feeds.recipes.*',
'calibre.gui2.convert.*',
'PyQt4.QtNetwork',
'keyword', 'codeop', 'pydoc', 'readline',
'BeautifulSoup',
'dateutil', 'email.iterators',
'email.generator', 'sqlite3.dump',
'calibre.ebooks.metadata.amazon',
],
'packages' : ['PIL', 'Authorization', 'lxml', 'dns'],
'excludes' : ['IPython', 'PyQt4.uic.port_v3.proxy_base'],
'plist' : { 'CFBundleGetInfoString' : '''calibre, an E-book management application.'''
''' Visit http://calibre-ebook.com for details.''',
'CFBundleIdentifier':'net.kovidgoyal.calibre',
'CFBundleShortVersionString':VERSION,
'CFBundleVersion':APPNAME + ' ' + VERSION,
'LSMinimumSystemVersion':'10.4.3',
'NSHumanReadableCopyright':'Copyright 2008, Kovid Goyal',
'LSEnvironment':{
'FC_CONFIG_DIR':'@executable_path/../Resources/fonts',
'MAGICK_HOME':'@executable_path/../Frameworks/ImageMagick',
'DYLD_LIBRARY_PATH':'@executable_path/../Frameworks/ImageMagick/lib',
}
},
},
},
setup_requires = ['py2app'],
)
return 0

View File

@ -216,7 +216,7 @@ class Win32Freeze(Command, WixMixIn):
if os.path.isdir(folder): if os.path.isdir(folder):
self.fix_pyd_bootstraps_in(folder) self.fix_pyd_bootstraps_in(folder)
for pat in (r'PyQt4\uic\port_v3', ): for pat in (r'PyQt5\uic\port_v3', ):
x = glob.glob(self.j(self.lib_dir, 'site-packages', pat))[0] x = glob.glob(self.j(self.lib_dir, 'site-packages', pat))[0]
shutil.rmtree(x) shutil.rmtree(x)

View File

@ -17,16 +17,7 @@ def all_py_files():
if n.endswith('.py'): if n.endswith('.py'):
yield os.path.join(dirpath, n) yield os.path.join(dirpath, n)
def port_imports():
for path in all_py_files():
with open(path, 'r+b') as f:
raw = f.read()
nraw = raw.replace(b'from PyQt4.', b'from PyQt5.')
if nraw != raw:
f.seek(0), f.truncate()
f.write(nraw)
if __name__ == '__main__': if __name__ == '__main__':
port_imports() pass

View File

@ -22,7 +22,7 @@ from calibre.constants import (iswindows, isosx, islinux, isfrozen,
from calibre.startup import winutil, winutilerror from calibre.startup import winutil, winutilerror
if False and islinux and not getattr(sys, 'frozen', False): if False and islinux and not getattr(sys, 'frozen', False):
# Imported before PyQt4 to workaround PyQt4 util-linux conflict discovered on gentoo # Imported before PyQt to workaround PyQt util-linux conflict discovered on gentoo
# See http://bugs.gentoo.org/show_bug.cgi?id=317557 # See http://bugs.gentoo.org/show_bug.cgi?id=317557
# Importing uuid is slow so get rid of this at some point, maybe in a few # Importing uuid is slow so get rid of this at some point, maybe in a few
# years when even Debian has caught up # years when even Debian has caught up

View File

@ -10,8 +10,7 @@ __license__ = 'GPL v3'
from PyQt5.Qt import (QDialog, QVBoxLayout, QLabel, QDialogButtonBox, from PyQt5.Qt import (QDialog, QVBoxLayout, QLabel, QDialogButtonBox,
QListWidget, QAbstractItemView) QListWidget, QAbstractItemView, QSizePolicy)
from PyQt4 import QtGui
class ChoosePluginToolbarsDialog(QDialog): class ChoosePluginToolbarsDialog(QDialog):
@ -32,8 +31,7 @@ class ChoosePluginToolbarsDialog(QDialog):
self._locations_list = QListWidget(self) self._locations_list = QListWidget(self)
self._locations_list.setSelectionMode(QAbstractItemView.MultiSelection) self._locations_list.setSelectionMode(QAbstractItemView.MultiSelection)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum)
QtGui.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0) sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0) sizePolicy.setVerticalStretch(0)
self._locations_list.setSizePolicy(sizePolicy) self._locations_list.setSizePolicy(sizePolicy)

View File

@ -780,7 +780,7 @@ class PythonHighlighter(QSyntaxHighlighter): # {{{
r"|\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b"), r"|\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b"),
"number")) "number"))
PythonHighlighter.Rules.append((QRegExp( PythonHighlighter.Rules.append((QRegExp(
r"\bPyQt4\b|\bQt?[A-Z][a-z]\w+\b"), "pyqt")) r"\bPyQt5\b|\bQt?[A-Z][a-z]\w+\b"), "pyqt"))
PythonHighlighter.Rules.append((QRegExp(r"\b@\w+\b"), "decorator")) PythonHighlighter.Rules.append((QRegExp(r"\b@\w+\b"), "decorator"))
stringRe = QRegExp(r"""(?:'[^']*'|"[^"]*")""") stringRe = QRegExp(r"""(?:'[^']*'|"[^"]*")""")
stringRe.setMinimal(True) stringRe.setMinimal(True)