home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_1376 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  19.9 KB  |  403 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. __license__ = 'GPL v3'
  5. __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
  6. import sys
  7. import os
  8. import cPickle
  9. import textwrap
  10. import stat
  11. from subprocess import check_call
  12. from calibre import __appname__, prints, guess_type
  13. from calibre.constants import islinux, isfreebsd
  14. from calibre.customize.ui import all_input_formats
  15. from calibre.ptempfile import TemporaryDirectory
  16. from calibre import CurrentDir
  17. entry_points = {
  18.     'console_scripts': [
  19.         'ebook-device       = calibre.devices.prs500.cli.main:main',
  20.         'ebook-meta         = calibre.ebooks.metadata.cli:main',
  21.         'ebook-convert      = calibre.ebooks.conversion.cli:main',
  22.         'markdown-calibre   = calibre.ebooks.markdown.markdown:main',
  23.         'web2disk           = calibre.web.fetch.simple:main',
  24.         'calibre-server     = calibre.library.server.main:main',
  25.         'lrf2lrs            = calibre.ebooks.lrf.lrfparser:main',
  26.         'lrs2lrf            = calibre.ebooks.lrf.lrs.convert_from:main',
  27.         'librarything       = calibre.ebooks.metadata.library_thing:main',
  28.         'calibre-debug      = calibre.debug:main',
  29.         'calibredb          = calibre.library.cli:main',
  30.         'calibre-parallel   = calibre.utils.ipc.worker:main',
  31.         'calibre-customize  = calibre.customize.ui:main',
  32.         'calibre-complete   = calibre.utils.complete:main',
  33.         'pdfmanipulate      = calibre.ebooks.pdf.manipulate.cli:main',
  34.         'fetch-ebook-metadata = calibre.ebooks.metadata.fetch:main',
  35.         'epub-fix           = calibre.ebooks.epub.fix.main:main',
  36.         'calibre-smtp = calibre.utils.smtp:main'],
  37.     'gui_scripts': [
  38.         __appname__ + ' = calibre.gui2.main:main',
  39.         'lrfviewer    = calibre.gui2.lrf_renderer.main:main',
  40.         'ebook-viewer = calibre.gui2.viewer.main:main'] }
  41. UNINSTALL = "#!{python}\neuid = {euid}\n\nimport os, subprocess, shutil\n\nif os.geteuid() != euid:\n    print 'WARNING: uninstaller must be run as', euid, 'to remove all files'\n\nfor x in {manifest!r}:\n    if not os.path.exists(x): continue\n    print 'Removing', x\n    try:\n        if os.path.isdir(x):\n            shutil.rmtree(x)\n        else:\n            os.unlink(x)\n    except Exception, e:\n        print 'Failed to delete', x\n        print '\t', e\n\nicr = {icon_resources!r}\nfor context, name, size in icr:\n    cmd = ['xdg-icon-resource', 'uninstall', '--context', context, '--size', size, name]\n    if (context, name) != icr[-1]:\n        cmd.insert(2, '--noupdate')\n    ret = subprocess.call(cmd)\n    if ret != 0:\n        print 'WARNING: Failed to remove icon', name\n\nmr = {menu_resources!r}\nfor f in mr:\n    cmd = ['xdg-desktop-menu', 'uninstall', f]\n    ret = subprocess.call(cmd)\n    if ret != 0:\n        print 'WARNING: Failed to remove menu item', f\n\nos.remove(os.path.abspath(__file__))\n"
  42.  
  43. class PostInstall:
  44.     
  45.     def task_failed(self, msg):
  46.         self.warn(msg, 'with error:')
  47.         import traceback
  48.         tb = '\n\t'.join(traceback.format_exc().splitlines())
  49.         self.info('\t' + tb)
  50.         print 
  51.  
  52.     
  53.     def warning(self, *args, **kwargs):
  54.         print '\n' + '____________________', 'WARNING', '____________________'
  55.         prints(*args, **kwargs)
  56.         print '_' * 50
  57.         self.warnings.append((args, kwargs))
  58.         sys.stdout.flush()
  59.  
  60.     
  61.     def __init__(self, opts, info = prints, warn = None, manifest = None):
  62.         self.opts = opts
  63.         self.info = info
  64.         self.warn = warn
  65.         self.warnings = []
  66.         if self.warn is None:
  67.             self.warn = self.warning
  68.         
  69.         if not self.opts.staging_bindir:
  70.             self.opts.staging_bindir = os.path.join(self.opts.staging_root, 'bin')
  71.         
  72.         if not self.opts.staging_sharedir:
  73.             self.opts.staging_sharedir = os.path.join(self.opts.staging_root, 'share', 'calibre')
  74.         
  75.         self.opts.staging_etc = None if self.opts.staging_root == '/usr' else os.path.join(self.opts.staging_root, 'etc')
  76.         scripts = cPickle.loads(P('scripts.pickle', data = True))
  77.         if getattr(sys, 'frozen_path', False):
  78.             self.info('Creating symlinks...')
  79.             for exe in scripts.keys():
  80.                 dest = os.path.join(self.opts.staging_bindir, exe)
  81.                 if os.path.lexists(dest):
  82.                     os.unlink(dest)
  83.                 
  84.                 tgt = os.path.join(getattr(sys, 'frozen_path'), exe)
  85.                 self.info('\tSymlinking %s to %s' % (tgt, dest))
  86.                 os.symlink(tgt, dest)
  87.             
  88.         
  89.         self.manifest = manifest
  90.         self.icon_resources = []
  91.         self.menu_resources = []
  92.         self.mime_resources = []
  93.         if islinux:
  94.             self.setup_completion()
  95.         
  96.         self.install_man_pages()
  97.         if islinux:
  98.             self.setup_desktop_integration()
  99.         
  100.         self.create_uninstaller()
  101.         config_dir = config_dir
  102.         import calibre.utils.config
  103.         if os.path.exists(config_dir):
  104.             os.chdir(config_dir)
  105.             if islinux:
  106.                 for f in os.listdir('.'):
  107.                     if os.stat(f).st_uid == 0:
  108.                         None if os.path.isdir(f) else os.unlink(f)
  109.                         continue
  110.                 
  111.                 if os.stat(config_dir).st_uid == 0:
  112.                     os.rmdir(config_dir)
  113.                 
  114.             
  115.         
  116.         if warn is None and self.warnings:
  117.             self.info('There were %d warnings' % len(self.warnings))
  118.             for args, kwargs in self.warnings:
  119.                 self.info('*', *args, **kwargs)
  120.                 print 
  121.             
  122.         
  123.  
  124.     
  125.     def create_uninstaller(self):
  126.         dest = os.path.join(self.opts.staging_bindir, 'calibre-uninstall')
  127.         raw = UNINSTALL.format(python = os.path.abspath(sys.executable), euid = os.geteuid(), manifest = self.manifest, icon_resources = self.icon_resources, menu_resources = self.menu_resources)
  128.         
  129.         try:
  130.             
  131.             try:
  132.                 f = _[1]
  133.                 f.write(raw)
  134.             finally:
  135.                 pass
  136.  
  137.             os.chmod(dest, stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH)
  138.             if os.geteuid() == 0:
  139.                 os.chown(dest, 0, 0)
  140.         except:
  141.             if self.opts.fatal_errors:
  142.                 raise 
  143.             self.opts.fatal_errors
  144.             self.task_failed('Creating uninstaller failed')
  145.  
  146.  
  147.     
  148.     def setup_completion(self):
  149.         
  150.         try:
  151.             self.info('Setting up bash completion...')
  152.             metaop = option_parser
  153.             meta_filetypes = filetypes
  154.             import calibre.ebooks.metadata.cli
  155.             lrf2lrsop = option_parser
  156.             import calibre.ebooks.lrf.lrfparser
  157.             lrfviewerop = option_parser
  158.             import calibre.gui2.lrf_renderer.main
  159.             viewer_op = option_parser
  160.             import calibre.gui2.viewer.main
  161.             fem_op = option_parser
  162.             import calibre.ebooks.metadata.fetch
  163.             guiop = option_parser
  164.             import calibre.gui2.main
  165.             smtp_op = option_parser
  166.             import calibre.utils.smtp
  167.             fix_op = option_parser
  168.             import calibre.ebooks.epub.fix.main
  169.             any_formats = [
  170.                 'epub',
  171.                 'htm',
  172.                 'html',
  173.                 'xhtml',
  174.                 'xhtm',
  175.                 'rar',
  176.                 'zip',
  177.                 'txt',
  178.                 'lit',
  179.                 'rtf',
  180.                 'pdf',
  181.                 'prc',
  182.                 'mobi',
  183.                 'fb2',
  184.                 'odt',
  185.                 'lrf']
  186.             bc = os.path.join(os.path.dirname(self.opts.staging_sharedir), 'bash-completion')
  187.             if os.path.exists(bc):
  188.                 f = os.path.join(bc, 'calibre')
  189.             else:
  190.                 f = os.path.join(self.opts.staging_etc, 'bash_completion.d/calibre')
  191.             if not os.path.exists(os.path.dirname(f)):
  192.                 os.makedirs(os.path.dirname(f))
  193.             
  194.             self.manifest.append(f)
  195.             self.info('Installing bash completion to', f)
  196.             
  197.             try:
  198.                 f = _[1]
  199.                 f.write('# calibre Bash Shell Completion\n')
  200.                 f.write(opts_and_exts('calibre', guiop, any_formats))
  201.                 f.write(opts_and_exts('lrf2lrs', lrf2lrsop, [
  202.                     'lrf']))
  203.                 f.write(opts_and_exts('ebook-meta', metaop, list(meta_filetypes())))
  204.                 f.write(opts_and_exts('lrfviewer', lrfviewerop, [
  205.                     'lrf']))
  206.                 f.write(opts_and_exts('ebook-viewer', viewer_op, any_formats))
  207.                 f.write(opts_and_words('fetch-ebook-metadata', fem_op, []))
  208.                 f.write(opts_and_words('calibre-smtp', smtp_op, []))
  209.                 f.write(opts_and_exts('epub-fix', fix_op, [
  210.                     'epub']))
  211.                 f.write(textwrap.dedent('\n                _ebook_device_ls()\n                {\n                local pattern search listing prefix\n                pattern="$1"\n                search="$1"\n                if [[ -n "{$pattern}" ]]; then\n                    if [[ "${pattern:(-1)}" == "/" ]]; then\n                    pattern=""\n                    else\n                    pattern="$(basename ${pattern} 2> /dev/null)"\n                    search="$(dirname ${search} 2> /dev/null)"\n                    fi\n                fi\n\n                if [[  "x${search}" == "x" || "x${search}" == "x." ]]; then\n                    search="/"\n                fi\n\n                listing="$(ebook-device ls ${search} 2>/dev/null)"\n\n                prefix="${search}"\n                if [[ "x${prefix:(-1)}" != "x/" ]]; then\n                    prefix="${prefix}/"\n                fi\n\n                echo $(compgen -P "${prefix}" -W "${listing}" "${pattern}")\n                }\n\n                _ebook_device()\n                {\n                local cur prev\n                cur="${COMP_WORDS[COMP_CWORD]}"\n                prev="${COMP_WORDS[COMP_CWORD-1]}"\n                COMPREPLY=()\n                case "${prev}" in\n                    ls|rm|mkdir|touch|cat )\n                        COMPREPLY=( $(_ebook_device_ls "${cur}") )\n                        return 0\n                        ;;\n                    cp )\n                        if [[ ${cur} == prs500:* ]]; then\n                        COMPREPLY=( $(_ebook_device_ls "${cur:7}") )\n                        return 0\n                        else\n                        _filedir\n                        return 0\n                        fi\n                        ;;\n                    prs500 )\n                        COMPREPLY=( $(compgen -W "cp ls rm mkdir touch cat info books df" "${cur}") )\n                        return 0\n                        ;;\n                    * )\n                        if [[ ${cur} == prs500:* ]]; then\n                        COMPREPLY=( $(_ebook_device_ls "${cur:7}") )\n                        return 0\n                        else\n                        if [[ ${prev} == prs500:* ]]; then\n                            _filedir\n                            return 0\n                        else\n                            COMPREPLY=( $(compgen -W "prs500:" "${cur}") )\n                            return 0\n                        fi\n                        return 0\n                        fi\n                    ;;\n                esac\n                }\n                complete -o nospace  -F _ebook_device ebook-device\n\n                complete -o nospace -C calibre-complete ebook-convert\n                '))
  212.             finally:
  213.                 pass
  214.  
  215.         except TypeError:
  216.             err = None
  217.             if 'resolve_entities' in str(err):
  218.                 print 'You need python-lxml >= 2.0.5 for calibre'
  219.                 sys.exit(1)
  220.             
  221.             raise 
  222.         except:
  223.             if self.opts.fatal_errors:
  224.                 raise 
  225.             self.opts.fatal_errors
  226.             self.task_failed('Setting up completion failed')
  227.  
  228.  
  229.     
  230.     def install_man_pages(self):
  231.         
  232.         try:
  233.             create_man_page = create_man_page
  234.             import calibre.utils.help2man
  235.             if isfreebsd:
  236.                 manpath = os.path.join(self.opts.staging_root, 'man/man1')
  237.             else:
  238.                 manpath = os.path.join(self.opts.staging_sharedir, 'man/man1')
  239.             if not os.path.exists(manpath):
  240.                 os.makedirs(manpath)
  241.             
  242.             self.info('Installing MAN pages...')
  243.             for src in entry_points['console_scripts']:
  244.                 (prog, right) = src.split('=')
  245.                 prog = prog.strip()
  246.                 module = __import__(right.split(':')[0].strip(), fromlist = [
  247.                     'a'])
  248.                 parser = getattr(module, 'option_parser', None)
  249.                 if parser is None:
  250.                     continue
  251.                 
  252.                 parser = parser()
  253.                 raw = create_man_page(prog, parser)
  254.                 if isfreebsd:
  255.                     manfile = os.path.join(manpath, prog + '.1')
  256.                 else:
  257.                     manfile = os.path.join(manpath, prog + '.1' + __appname__ + '.bz2')
  258.                 self.info('\tInstalling MAN page for', prog)
  259.                 open(manfile, 'wb').write(raw)
  260.                 self.manifest.append(manfile)
  261.         except:
  262.             if self.opts.fatal_errors:
  263.                 raise 
  264.             self.opts.fatal_errors
  265.             self.task_failed('Installing MAN pages failed')
  266.  
  267.  
  268.     
  269.     def setup_desktop_integration(self):
  270.         
  271.         try:
  272.             self.info('Setting up desktop integration...')
  273.             
  274.             try:
  275.                 tdir = _[1]
  276.                 CurrentDir(tdir).__enter__()
  277.                 
  278.                 try:
  279.                     render_img('mimetypes/lrf.svg', 'calibre-lrf.png')
  280.                     check_call('xdg-icon-resource install --noupdate --context mimetypes --size 128 calibre-lrf.png application-lrf', shell = True)
  281.                     self.icon_resources.append(('mimetypes', 'application-lrf', '128'))
  282.                     check_call('xdg-icon-resource install --noupdate --context mimetypes --size 128 calibre-lrf.png text-lrs', shell = True)
  283.                     self.icon_resources.append(('mimetypes', 'application-lrs', '128'))
  284.                     render_img('lt.png', 'calibre-gui.png')
  285.                     check_call('xdg-icon-resource install --noupdate --size 128 calibre-gui.png calibre-gui', shell = True)
  286.                     self.icon_resources.append(('apps', 'calibre-gui', '128'))
  287.                     render_img('viewer.svg', 'calibre-viewer.png')
  288.                     check_call('xdg-icon-resource install --size 128 calibre-viewer.png calibre-viewer', shell = True)
  289.                     self.icon_resources.append(('apps', 'calibre-viewer', '128'))
  290.                     mimetypes = set([])
  291.                     for x in all_input_formats():
  292.                         mt = guess_type('dummy.' + x)[0]
  293.                         if mt and 'chemical' not in mt:
  294.                             mimetypes.add(mt)
  295.                             continue
  296.                         CurrentDir(tdir).__exit__
  297.                     
  298.                     
  299.                     def write_mimetypes(f):
  300.                         f.write('MimeType=%s;\n' % ';'.join(mimetypes))
  301.  
  302.                     f = open('calibre-lrfviewer.desktop', 'wb')
  303.                     f.write(VIEWER)
  304.                     f.close()
  305.                     f = open('calibre-ebook-viewer.desktop', 'wb')
  306.                     f.write(EVIEWER)
  307.                     write_mimetypes(f)
  308.                     f.close()
  309.                     f = open('calibre-gui.desktop', 'wb')
  310.                     f.write(GUI)
  311.                     write_mimetypes(f)
  312.                     f.close()
  313.                     des = ('calibre-gui.desktop', 'calibre-lrfviewer.desktop', 'calibre-ebook-viewer.desktop')
  314.                     for x in des:
  315.                         cmd = [
  316.                             'xdg-desktop-menu',
  317.                             'install',
  318.                             './' + x]
  319.                         check_call(' '.join(cmd), shell = True)
  320.                         self.menu_resources.append(x)
  321.                     
  322.                     f = open('calibre-mimetypes', 'wb')
  323.                     f.write(MIME)
  324.                     f.close()
  325.                     self.mime_resources.append('calibre-mimetypes')
  326.                     check_call('xdg-mime install ./calibre-mimetypes', shell = True)
  327.                 finally:
  328.                     pass
  329.  
  330.             finally:
  331.                 pass
  332.  
  333.         except Exception:
  334.             if self.opts.fatal_errors:
  335.                 raise 
  336.             self.opts.fatal_errors
  337.             self.task_failed('Setting up desktop integration failed')
  338.  
  339.  
  340.  
  341.  
  342. def option_parser():
  343.     OptionParser = OptionParser
  344.     import calibre.utils.config
  345.     parser = OptionParser()
  346.     parser.add_option('--make-errors-fatal', action = 'store_true', default = False, dest = 'fatal_errors', help = 'If set die on errors.')
  347.     parser.add_option('--root', dest = 'staging_root', default = '/usr', help = 'Prefix under which to install files')
  348.     parser.add_option('--bindir', default = None, dest = 'staging_bindir', help = 'Location where calibre launcher scripts were installed. Typically /usr/bin')
  349.     parser.add_option('--sharedir', default = None, dest = 'staging_sharedir', help = 'Location where calibre resources were installed, typically /usr/share/calibre')
  350.     return parser
  351.  
  352.  
  353. def options(option_parser):
  354.     parser = option_parser()
  355.     options = parser.option_list
  356.     for group in parser.option_groups:
  357.         options += group.option_list
  358.     
  359.     opts = []
  360.     for opt in options:
  361.         opts.extend(opt._short_opts)
  362.         opts.extend(opt._long_opts)
  363.     
  364.     return opts
  365.  
  366.  
  367. def opts_and_words(name, op, words):
  368.     opts = '|'.join(options(op))
  369.     words = []([ w.replace("'", "\\'") for w in words ])
  370.     fname = name.replace('-', '_')
  371.     return ('_' + fname + '()' + '\n{\n    local cur opts\n    local IFS=$\'|\\t\'\n    COMPREPLY=()\n    cur="${COMP_WORDS[COMP_CWORD]}"\n    opts="%s"\n    words="%s"\n\n    case "${cur}" in\n      -* )\n         COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )\n         COMPREPLY=( $( echo ${COMPREPLY[@]} | sed \'s/ /\\\\ /g\' | tr \'\\n\' \'\\t\' ) )\n         return 0\n         ;;\n      *  )\n         COMPREPLY=( $(compgen -W "${words}" -- ${cur}) )\n         COMPREPLY=( $( echo ${COMPREPLY[@]} | sed \'s/ /\\\\ /g\' | tr \'\\n\' \'\\t\' ) )\n         return 0\n         ;;\n    esac\n\n}\ncomplete -F _' % (opts, words) + fname + ' ' + name + '\n\n').encode('utf-8')
  372.  
  373.  
  374. def opts_and_exts(name, op, exts):
  375.     opts = ' '.join(options(op))
  376.     []([ i.upper() for i in exts ])
  377.     exts = '|'.join(exts)
  378.     fname = name.replace('-', '_')
  379.     return '_' + fname + '()' + '\n{\n    local cur prev opts\n    COMPREPLY=()\n    cur="${COMP_WORDS[COMP_CWORD]}"\n    prev="${COMP_WORDS[COMP_CWORD-1]}"\n    opts="%s"\n    pics="@(jpg|jpeg|png|gif|bmp|JPG|JPEG|PNG|GIF|BMP)"\n\n    case "${prev}" in\n      --cover )\n           _filedir "${pics}"\n           return 0\n           ;;\n    esac\n\n    case "${cur}" in\n      --cover )\n         _filedir "${pics}"\n         return 0\n         ;;\n      -* )\n         COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )\n         return 0\n         ;;\n      *  )\n        _filedir \'@(%s)\'\n        return 0\n        ;;\n    esac\n\n}\ncomplete -o filenames -F _' % (opts, exts) + fname + ' ' + name + '\n\n'
  380.  
  381. VIEWER = '[Desktop Entry]\nVersion=1.0\nType=Application\nName=LRF Viewer\nGenericName=Viewer for LRF files\nComment=Viewer for LRF files (SONY ebook format files)\nTryExec=lrfviewer\nExec=lrfviewer %F\nIcon=calibre-viewer\nMimeType=application/x-sony-bbeb;\nCategories=Graphics;Viewer;\n'
  382. EVIEWER = '[Desktop Entry]\nVersion=1.0\nType=Application\nName=E-book Viewer\nGenericName=Viewer for E-books\nComment=Viewer for E-books in all the major formats\nTryExec=ebook-viewer\nExec=ebook-viewer %F\nIcon=calibre-viewer\nCategories=Graphics;Viewer;\n'
  383. GUI = '[Desktop Entry]\nVersion=1.0\nType=Application\nName=calibre\nGenericName=E-book library management\nComment=E-book library management: Convert, view, share, catalogue all your e-books\nTryExec=calibre\nExec=calibre\nIcon=calibre-gui\nCategories=Office;\n'
  384. MIME = '<?xml version="1.0"?>\n<mime-info xmlns=\'http://www.freedesktop.org/standards/shared-mime-info\'>\n    <mime-type type="application/x-sony-bbeb">\n        <comment>SONY E-book compiled format</comment>\n        <glob pattern="*.lrf"/>\n    </mime-type>\n    <mime-type type="application/epub+zip">\n        <comment>EPUB ebook format</comment>\n        <glob pattern="*.epub"/>\n    </mime-type>\n    <mime-type type="text/lrs">\n        <comment>SONY E-book source format</comment>\n        <glob pattern="*.lrs"/>\n    </mime-type>\n</mime-info>\n'
  385.  
  386. def render_img(image, dest, width = 128, height = 128):
  387.     QImage = QImage
  388.     Qt = Qt
  389.     import PyQt4.Qt
  390.     img = QImage(I(image)).scaled(width, height, Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
  391.     img.save(dest)
  392.  
  393.  
  394. def main():
  395.     p = option_parser()
  396.     (opts, args) = p.parse_args()
  397.     PostInstall(opts)
  398.     return 0
  399.  
  400. if __name__ == '__main__':
  401.     sys.exit(main())
  402.  
  403.