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

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. __license__ = 'GPL v3'
  5. __copyright__ = '2008, Kovid Goyal <kovid@kovidgoyal.net>'
  6. __docformat__ = 'restructuredtext en'
  7. import sys
  8. import os
  9. import re
  10. import logging
  11. import time
  12. import mimetypes
  13. import __builtin__
  14. import warnings
  15. import multiprocessing
  16. from urllib import getproxies
  17.  
  18. __builtin__.__dict__['dynamic_property'] = lambda func: func(None)
  19. from htmlentitydefs import name2codepoint
  20. from math import floor
  21. from functools import partial
  22. warnings.simplefilter('ignore', DeprecationWarning)
  23. from calibre.constants import iswindows, isosx, islinux, isfreebsd, isfrozen, terminal_controller, preferred_encoding, __appname__, __version__, __author__, win32event, win32api, winerror, fcntl, filesystem_encoding, plugins, config_dir
  24. from calibre.startup import winutil, winutilerror
  25. import mechanize
  26. if False:
  27.     (winutil, winutilerror, __appname__, islinux, __version__)
  28.     (fcntl, win32event, isfrozen, __author__, terminal_controller)
  29.     (winerror, win32api, isfreebsd)
  30.  
  31. mimetypes.add_type('application/epub+zip', '.epub')
  32. mimetypes.add_type('text/x-sony-bbeb+xml', '.lrs')
  33. mimetypes.add_type('application/xhtml+xml', '.xhtml')
  34. mimetypes.add_type('image/svg+xml', '.svg')
  35. mimetypes.add_type('text/fb2+xml', '.fb2')
  36. mimetypes.add_type('application/x-sony-bbeb', '.lrf')
  37. mimetypes.add_type('application/x-sony-bbeb', '.lrx')
  38. mimetypes.add_type('application/x-dtbncx+xml', '.ncx')
  39. mimetypes.add_type('application/adobe-page-template+xml', '.xpgt')
  40. mimetypes.add_type('application/x-font-opentype', '.otf')
  41. mimetypes.add_type('application/x-font-truetype', '.ttf')
  42. mimetypes.add_type('application/oebps-package+xml', '.opf')
  43. mimetypes.add_type('application/vnd.palm', '.pdb')
  44. mimetypes.add_type('application/x-mobipocket-ebook', '.mobi')
  45. mimetypes.add_type('application/x-mobipocket-ebook', '.prc')
  46. mimetypes.add_type('application/x-mobipocket-ebook', '.azw')
  47. mimetypes.add_type('application/x-cbz', '.cbz')
  48. mimetypes.add_type('application/x-cbr', '.cbr')
  49. mimetypes.add_type('application/x-koboreader-ebook', '.kobo')
  50. mimetypes.add_type('image/wmf', '.wmf')
  51. guess_type = mimetypes.guess_type
  52. import cssutils
  53. cssutils.log.setLevel(logging.WARN)
  54.  
  55. def to_unicode(raw, encoding = 'utf-8', errors = 'strict'):
  56.     if isinstance(raw, unicode):
  57.         return raw
  58.     return raw.decode(encoding, errors)
  59.  
  60.  
  61. def patheq(p1, p2):
  62.     p = os.path
  63.     
  64.     d = lambda x: p.normcase(p.normpath(p.realpath(p.normpath(x))))
  65.     if not p1 or not p2:
  66.         return False
  67.     return d(p1) == d(p2)
  68.  
  69.  
  70. def unicode_path(path, abs = False):
  71.     if not isinstance(path, unicode):
  72.         path = path.decode(sys.getfilesystemencoding())
  73.     
  74.     if abs:
  75.         path = os.path.abspath(path)
  76.     
  77.     return path
  78.  
  79.  
  80. def osx_version():
  81.     if isosx:
  82.         import platform
  83.         src = platform.mac_ver()[0]
  84.         m = re.match('(\\d+)\\.(\\d+)\\.(\\d+)', src)
  85.         if m:
  86.             return (int(m.group(1)), int(m.group(2)), int(m.group(3)))
  87.     
  88.  
  89. _filename_sanitize = re.compile('[\\xae\\0\\\\|\\?\\*<":>\\+/]')
  90.  
  91. def sanitize_file_name(name, substitute = '_', as_unicode = False):
  92.     if isinstance(name, unicode):
  93.         name = name.encode(filesystem_encoding, 'ignore')
  94.     
  95.     one = _filename_sanitize.sub(substitute, name)
  96.     one = re.sub('\\s', ' ', one).strip()
  97.     one = re.sub('^\\.+$', '_', one)
  98.     if as_unicode:
  99.         one = one.decode(filesystem_encoding)
  100.     
  101.     one = one.replace('..', substitute)
  102.     if one.endswith('.'):
  103.         one = one[:-1] + '_'
  104.     
  105.     return one
  106.  
  107.  
  108. def prints(*args, **kwargs):
  109.     file = kwargs.get('file', sys.stdout)
  110.     sep = kwargs.get('sep', ' ')
  111.     end = kwargs.get('end', '\n')
  112.     enc = preferred_encoding
  113.     safe_encode = kwargs.get('safe_encode', False)
  114.     if 'CALIBRE_WORKER' in os.environ:
  115.         enc = 'utf-8'
  116.     
  117.     for i, arg in enumerate(args):
  118.         if isinstance(arg, unicode):
  119.             
  120.             try:
  121.                 arg = arg.encode(enc)
  122.             except UnicodeEncodeError:
  123.                 
  124.                 try:
  125.                     arg = arg.encode('utf-8')
  126.                 if not safe_encode:
  127.                     raise 
  128.                 safe_encode
  129.                 arg = repr(arg)
  130.  
  131.             except:
  132.                 None<EXCEPTION MATCH>UnicodeEncodeError
  133.             
  134.  
  135.         None<EXCEPTION MATCH>UnicodeEncodeError
  136.         if not isinstance(arg, str):
  137.             
  138.             try:
  139.                 arg = str(arg)
  140.             except ValueError:
  141.                 arg = unicode(arg)
  142.  
  143.             if isinstance(arg, unicode):
  144.                 
  145.                 try:
  146.                     arg = arg.encode(enc)
  147.                 except UnicodeEncodeError:
  148.                     
  149.                     try:
  150.                         arg = arg.encode('utf-8')
  151.                     if not safe_encode:
  152.                         raise 
  153.                     safe_encode
  154.                     arg = repr(arg)
  155.  
  156.                 except:
  157.                     None<EXCEPTION MATCH>UnicodeEncodeError
  158.                 
  159.  
  160.             None<EXCEPTION MATCH>UnicodeEncodeError
  161.         
  162.         
  163.         try:
  164.             file.write(arg)
  165.         except:
  166.             file.write(repr(arg))
  167.  
  168.         if i != len(args) - 1:
  169.             file.write(sep)
  170.             continue
  171.     
  172.     file.write(end)
  173.  
  174.  
  175. class CommandLineError(Exception):
  176.     pass
  177.  
  178.  
  179. def setup_cli_handlers(logger, level):
  180.     if os.environ.get('CALIBRE_WORKER', None) is not None and logger.handlers:
  181.         return None
  182.     logger.setLevel(level)
  183.     if level == logging.WARNING:
  184.         handler = logging.StreamHandler(sys.stdout)
  185.         handler.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
  186.         handler.setLevel(logging.WARNING)
  187.     elif level == logging.INFO:
  188.         handler = logging.StreamHandler(sys.stdout)
  189.         handler.setFormatter(logging.Formatter())
  190.         handler.setLevel(logging.INFO)
  191.     elif level == logging.DEBUG:
  192.         handler = logging.StreamHandler(sys.stderr)
  193.         handler.setLevel(logging.DEBUG)
  194.         handler.setFormatter(logging.Formatter('[%(levelname)s] %(filename)s:%(lineno)s: %(message)s'))
  195.     
  196.     logger.addHandler(handler)
  197.  
  198.  
  199. def load_library(name, cdll):
  200.     if iswindows:
  201.         return cdll.LoadLibrary(name)
  202.     if isosx:
  203.         name += '.dylib'
  204.         if hasattr(sys, 'frameworks_dir'):
  205.             return cdll.LoadLibrary(os.path.join(getattr(sys, 'frameworks_dir'), name))
  206.         return cdll.LoadLibrary(name)
  207.     return cdll.LoadLibrary(name + '.so')
  208.  
  209.  
  210. def filename_to_utf8(name):
  211.     if isinstance(name, unicode):
  212.         return name.encode('utf8')
  213.     codec = isinstance(name, unicode) if iswindows else 'utf8'
  214.     return name.decode(codec, 'replace').encode('utf8')
  215.  
  216.  
  217. def extract(path, dir):
  218.     ext = os.path.splitext(path)[1][1:].lower()
  219.     extractor = None
  220.     if ext in ('zip', 'cbz', 'epub', 'oebzip'):
  221.         zipextract = extract
  222.         import calibre.libunzip
  223.         extractor = zipextract
  224.     elif ext in ('cbr', 'rar'):
  225.         rarextract = extract
  226.         import calibre.libunrar
  227.         extractor = rarextract
  228.     
  229.     if extractor is None:
  230.         raise Exception('Unknown archive type')
  231.     extractor is None
  232.     extractor(path, dir)
  233.  
  234.  
  235. def get_proxies(debug = True):
  236.     proxies = getproxies()
  237.     for key, proxy in list(proxies.items()):
  238.         if not proxy or '..' in proxy:
  239.             del proxies[key]
  240.             continue
  241.         
  242.         if proxy.startswith(key + '://'):
  243.             proxy = proxy[len(key) + 3:]
  244.         
  245.         if proxy.endswith('/'):
  246.             proxy = proxy[:-1]
  247.         
  248.         if len(proxy) > 4:
  249.             proxies[key] = proxy
  250.             continue
  251.         prints('Removing invalid', key, 'proxy:', proxy)
  252.         del proxies[key]
  253.     
  254.     if proxies and debug:
  255.         prints('Using proxies:', proxies)
  256.     
  257.     return proxies
  258.  
  259.  
  260. def get_parsed_proxy(typ = 'http', debug = True):
  261.     proxies = get_proxies(debug)
  262.     proxy = proxies.get(typ, None)
  263.     if proxy:
  264.         pattern = re.compile('(?:ptype://)?(?:(?P<user>\\w+):(?P<pass>.*)@)?(?P<host>[\\w\\-\\.]+)(?::(?P<port>\\d+))?'.replace('ptype', typ))
  265.         match = pattern.match(proxies[typ])
  266.         if match:
  267.             
  268.             try:
  269.                 ans = {
  270.                     'host': match.group('host'),
  271.                     'port': match.group('port'),
  272.                     'user': match.group('user'),
  273.                     'pass': match.group('pass') }
  274.                 if ans['port']:
  275.                     ans['port'] = int(ans['port'])
  276.             except:
  277.                 if debug:
  278.                     traceback.print_exc()
  279.                 
  280.  
  281.             if debug:
  282.                 prints('Using http proxy', str(ans))
  283.             
  284.             return ans
  285.         match
  286.     
  287.  
  288.  
  289. def browser(honor_time = True, max_time = 2, mobile_browser = False):
  290.     opener = mechanize.Browser()
  291.     opener.set_handle_refresh(True, max_time = max_time, honor_time = honor_time)
  292.     opener.set_handle_robots(False)
  293.     opener.addheaders = [
  294.         (None, 'User-agent' if mobile_browser else 'Mozilla/5.0 (X11; U; i686 Linux; en_US; rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4')]
  295.     http_proxy = get_proxies().get('http', None)
  296.     if http_proxy:
  297.         opener.set_proxies({
  298.             'http': http_proxy })
  299.     
  300.     return opener
  301.  
  302.  
  303. def fit_image(width, height, pwidth, pheight):
  304.     if not height > pheight:
  305.         pass
  306.     scaled = width > pwidth
  307.     if height > pheight:
  308.         corrf = pheight / float(height)
  309.         width = floor(corrf * width)
  310.         height = pheight
  311.     
  312.     if width > pwidth:
  313.         corrf = pwidth / float(width)
  314.         width = pwidth
  315.         height = floor(corrf * height)
  316.     
  317.     if height > pheight:
  318.         corrf = pheight / float(height)
  319.         width = floor(corrf * width)
  320.         height = pheight
  321.     
  322.     return (scaled, int(width), int(height))
  323.  
  324.  
  325. class CurrentDir(object):
  326.     
  327.     def __init__(self, path):
  328.         self.path = path
  329.         self.cwd = None
  330.  
  331.     
  332.     def __enter__(self, *args):
  333.         self.cwd = os.getcwd()
  334.         os.chdir(self.path)
  335.         return self.cwd
  336.  
  337.     
  338.     def __exit__(self, *args):
  339.         os.chdir(self.cwd)
  340.  
  341.  
  342.  
  343. class StreamReadWrapper(object):
  344.     
  345.     def __init__(self, stream):
  346.         for x in ('read', 'seek', 'tell'):
  347.             setattr(self, x, getattr(stream, x))
  348.         
  349.  
  350.     
  351.     def __exit__(self, *args):
  352.         for x in ('read', 'seek', 'tell'):
  353.             setattr(self, x, None)
  354.         
  355.  
  356.     
  357.     def __enter__(self):
  358.         return self
  359.  
  360.  
  361.  
  362. def detect_ncpus():
  363.     ans = -1
  364.     
  365.     try:
  366.         ans = multiprocessing.cpu_count()
  367.     except:
  368.         QThread = QThread
  369.         import PyQt4.Qt
  370.         ans = QThread.idealThreadCount()
  371.  
  372.     if ans < 1:
  373.         ans = 1
  374.     
  375.     return ans
  376.  
  377. relpath = os.path.relpath
  378. _spat = re.compile('^the\\s+|^a\\s+|^an\\s+', re.IGNORECASE)
  379.  
  380. def english_sort(x, y):
  381.     return cmp(_spat.sub('', x), _spat.sub('', y))
  382.  
  383.  
  384. def walk(dir):
  385.     for record in os.walk(dir):
  386.         for f in record[-1]:
  387.             yield os.path.join(record[0], f)
  388.         
  389.     
  390.  
  391.  
  392. def strftime(fmt, t = None):
  393.     if t is None:
  394.         t = time.localtime()
  395.     
  396.     if hasattr(t, 'timetuple'):
  397.         t = t.timetuple()
  398.     
  399.     early_year = t[0] < 1900
  400.     if early_year:
  401.         replacement = None if t[0] % 4 == 0 else 1901
  402.         fmt = fmt.replace('%Y', '_early year hack##')
  403.         t = list(t)
  404.         orig_year = t[0]
  405.         t[0] = replacement
  406.     
  407.     ans = None
  408.     if iswindows:
  409.         if isinstance(fmt, unicode):
  410.             fmt = fmt.encode('mbcs')
  411.         
  412.         ans = plugins['winutil'][0].strftime(fmt, t)
  413.     
  414.     ans = time.strftime(fmt, t).decode(preferred_encoding, 'replace')
  415.     if early_year:
  416.         ans = ans.replace('_early year hack##', str(orig_year))
  417.     
  418.     return ans
  419.  
  420.  
  421. def my_unichr(num):
  422.     
  423.     try:
  424.         return unichr(num)
  425.     except ValueError:
  426.         return u'?'
  427.  
  428.  
  429.  
  430. def entity_to_unicode(match, exceptions = [], encoding = 'cp1252', result_exceptions = { }):
  431.     
  432.     def check(ch):
  433.         return result_exceptions.get(ch, ch)
  434.  
  435.     ent = match.group(1)
  436.     if ent in exceptions:
  437.         return '&' + ent + ';'
  438.     if ent == 'apos':
  439.         return check("'")
  440.     if ent.startswith('#'):
  441.         
  442.         try:
  443.             if ent[1] in ('x', 'X'):
  444.                 num = int(ent[2:], 16)
  445.             else:
  446.                 num = int(ent[1:])
  447.         except:
  448.             (None,) if ent == 'hellips' else ent in exceptions
  449.             return '&' + ent + ';'
  450.  
  451.         if encoding is None or num > 255:
  452.             return check(my_unichr(num))
  453.         
  454.         try:
  455.             return check(chr(num).decode(encoding))
  456.         except UnicodeDecodeError:
  457.             num > 255
  458.             num > 255
  459.             (None,) if ent == 'hellips' else ent in exceptions
  460.             return check(my_unichr(num))
  461.         
  462.  
  463.     num > 255<EXCEPTION MATCH>UnicodeDecodeError
  464.     
  465.     try:
  466.         return check(my_unichr(name2codepoint[ent]))
  467.     except KeyError:
  468.         num > 255
  469.         num > 255
  470.         num > 255
  471.         return '&' + ent + ';'
  472.         (None,) if ent == 'hellips' else ent in exceptions
  473.  
  474.  
  475. _ent_pat = re.compile('&(\\S+?);')
  476. xml_entity_to_unicode = partial(entity_to_unicode, result_exceptions = {
  477.     '"': '"',
  478.     "'": ''',
  479.     '<': '<',
  480.     '>': '>',
  481.     '&': '&' })
  482.  
  483. def replace_entities(raw):
  484.     return _ent_pat.sub(entity_to_unicode, raw)
  485.  
  486.  
  487. def prepare_string_for_xml(raw, attribute = False):
  488.     raw = _ent_pat.sub(entity_to_unicode, raw)
  489.     raw = raw.replace('&', '&').replace('<', '<').replace('>', '>')
  490.     if attribute:
  491.         raw = raw.replace('"', '"').replace("'", ''')
  492.     
  493.     return raw
  494.  
  495.  
  496. def isbytestring(obj):
  497.     return isinstance(obj, (str, bytes))
  498.  
  499.  
  500. def human_readable(size):
  501.     (divisor, suffix) = (1, 'B')
  502.     for i, candidate in enumerate(('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB')):
  503.         if size < 1024 ** (i + 1):
  504.             divisor = 1024 ** i
  505.             suffix = candidate
  506.             break
  507.             continue
  508.     
  509.     size = str(float(size) / divisor)
  510.     if size.find('.') > -1:
  511.         size = size[:size.find('.') + 2]
  512.     
  513.     if size.endswith('.0'):
  514.         size = size[:-2]
  515.     
  516.     return size + ' ' + suffix
  517.  
  518. if isosx:
  519.     import glob
  520.     import shutil
  521.     fdir = os.path.expanduser('~/.fonts')
  522.     
  523.     try:
  524.         if not os.path.exists(fdir):
  525.             os.makedirs(fdir)
  526.         
  527.         if not os.path.exists(os.path.join(fdir, 'LiberationSans_Regular.ttf')):
  528.             base = P('fonts/liberation/*.ttf')
  529.             for f in glob.glob(base):
  530.                 shutil.copy2(f, fdir)
  531.             
  532.     import traceback
  533.     traceback.print_exc()
  534.  
  535.  
  536.  
  537. def ipython(user_ns = None):
  538.     old_argv = sys.argv
  539.     sys.argv = [
  540.         'ipython']
  541.     if user_ns is None:
  542.         user_ns = locals()
  543.     
  544.     ipydir = None(os.path.join, config_dir if iswindows else '.' + 'ipython')
  545.     os.environ['IPYTHONDIR'] = ipydir
  546.     if not os.path.exists(ipydir):
  547.         os.makedirs(ipydir)
  548.     
  549.     for x in ('', '.ini'):
  550.         rc = os.path.join(ipydir, 'ipythonrc' + x)
  551.         if not os.path.exists(rc):
  552.             open(rc, 'wb').write(' ')
  553.             continue
  554.     
  555.     UC = '\nimport IPython.ipapi\nip = IPython.ipapi.get()\n\n# You probably want to uncomment this if you did %upgrade -nolegacy\nimport ipy_defaults\n\nimport os, re, sys\n\ndef main():\n    # Handy tab-completers for %cd, %run, import etc.\n    # Try commenting this out if you have completion problems/slowness\n    import ipy_stock_completers\n\n    # uncomment if you want to get ipython -p sh behaviour\n    # without having to use command line switches\n\n    import ipy_profile_sh\n\n\n    # Configure your favourite editor?\n    # Good idea e.g. for %edit os.path.isfile\n\n    import ipy_editors\n\n    # Choose one of these:\n\n    #ipy_editors.scite()\n    #ipy_editors.scite(\'c:/opt/scite/scite.exe\')\n    #ipy_editors.komodo()\n    #ipy_editors.idle()\n    # ... or many others, try \'ipy_editors??\' after import to see them\n\n    # Or roll your own:\n    #ipy_editors.install_editor("c:/opt/jed +$line $file")\n\n    ipy_editors.kate()\n\n    o = ip.options\n    # An example on how to set options\n    #o.autocall = 1\n    o.system_verbose = 0\n    o.confirm_exit = 0\n\nmain()\n    '
  556.     uc = os.path.join(ipydir, 'ipy_user_conf.py')
  557.     if not os.path.exists(uc):
  558.         open(uc, 'wb').write(UC)
  559.     
  560.     IPShellEmbed = IPShellEmbed
  561.     import IPython.Shell
  562.     ipshell = IPShellEmbed(user_ns = user_ns)
  563.     ipshell()
  564.     sys.argv = old_argv
  565.  
  566.