home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / hplip / base / utils.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  47.6 KB  |  1,632 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. from __future__ import generators
  5. import sys
  6. import os
  7. import fnmatch
  8. import tempfile
  9. import socket
  10. import struct
  11. import select
  12. import time
  13. import fcntl
  14. import errno
  15. import stat
  16. import string
  17. import commands
  18. import cStringIO
  19. import re
  20. import xml.parsers.expat as expat
  21. import getpass
  22. import locale
  23.  
  24. try:
  25.     import platform
  26.     platform_avail = True
  27. except ImportError:
  28.     platform_avail = False
  29.  
  30. from g import *
  31. from codes import *
  32. import pexpect
  33.  
  34. def lock(f):
  35.     log.debug('Locking: %s' % f.name)
  36.     
  37.     try:
  38.         fcntl.flock(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
  39.         return True
  40.     except (IOError, OSError):
  41.         log.debug('Failed to unlock %s.' % f.name)
  42.         return False
  43.  
  44.  
  45.  
  46. def unlock(f):
  47.     if f is not None:
  48.         log.debug('Unlocking: %s' % f.name)
  49.         
  50.         try:
  51.             fcntl.flock(f.fileno(), fcntl.LOCK_UN)
  52.             os.remove(f.name)
  53.         except (IOError, OSError):
  54.             pass
  55.         except:
  56.             None<EXCEPTION MATCH>(IOError, OSError)
  57.         
  58.  
  59.     None<EXCEPTION MATCH>(IOError, OSError)
  60.  
  61.  
  62. def lock_app(application, suppress_error = False):
  63.     dir = prop.user_dir
  64.     if os.geteuid() == 0:
  65.         dir = '/var'
  66.     elif not os.path.exists(dir):
  67.         os.makedirs(dir)
  68.     
  69.     lock_file = os.path.join(dir, '.'.join([
  70.         application,
  71.         'lock']))
  72.     
  73.     try:
  74.         lock_file_f = open(lock_file, 'w')
  75.     except IOError:
  76.         if not suppress_error:
  77.             log.error('Unable to open %s lock file.' % lock_file)
  78.         
  79.         return (False, None)
  80.  
  81.     if not lock(lock_file_f):
  82.         if not suppress_error:
  83.             log.error('Unable to lock %s. Is %s already running?' % (lock_file, application))
  84.         
  85.         return (False, None)
  86.     return (True, lock_file_f)
  87.  
  88. xml_basename_pat = re.compile('HPLIP-(\\d*)_(\\d*)_(\\d*).xml', re.IGNORECASE)
  89.  
  90. def Translator(frm = '', to = '', delete = '', keep = None):
  91.     allchars = string.maketrans('', '')
  92.     if len(to) == 1:
  93.         to = to * len(frm)
  94.     
  95.     trans = string.maketrans(frm, to)
  96.     if keep is not None:
  97.         delete = allchars.translate(allchars, keep.translate(allchars, delete))
  98.     
  99.     
  100.     def callable(s):
  101.         return s.translate(trans, delete)
  102.  
  103.     return callable
  104.  
  105.  
  106. def to_bool_str(s, default = '0'):
  107.     ''' Convert an arbitrary 0/1/T/F/Y/N string to a normalized string 0/1.'''
  108.     return default
  109.  
  110.  
  111. def to_bool(s, default = False):
  112.     ''' Convert an arbitrary 0/1/T/F/Y/N string to a boolean True/False value.'''
  113.     if isinstance(s, str) and s:
  114.         if s[0].lower() in ('1', 't', 'y'):
  115.             return True
  116.         if s[0].lower() in ('0', 'f', 'n'):
  117.             return False
  118.     elif isinstance(s, bool):
  119.         return s
  120.     s[0].lower() in ('1', 't', 'y')
  121.     return default
  122.  
  123.  
  124. def walkFiles(root, recurse = True, abs_paths = False, return_folders = False, pattern = '*', path = None):
  125.     if path is None:
  126.         path = root
  127.     
  128.     
  129.     try:
  130.         names = os.listdir(root)
  131.     except os.error:
  132.         raise StopIteration
  133.  
  134.     if not pattern:
  135.         pass
  136.     pattern = '*'
  137.     pat_list = pattern.split(';')
  138.     for name in names:
  139.         fullname = os.path.normpath(os.path.join(root, name))
  140.         for pat in pat_list:
  141.             if fnmatch.fnmatch(name, pat):
  142.                 if return_folders or not os.path.isdir(fullname):
  143.                     pass
  144.                 None if abs_paths else None<EXCEPTION MATCH>ValueError
  145.                 continue
  146.         
  147.         if recurse and os.path.isdir(fullname):
  148.             for f in walkFiles(fullname, recurse, abs_paths, return_folders, pattern, path):
  149.                 yield f
  150.             
  151.     
  152.  
  153.  
  154. def is_path_writable(path):
  155.     return False
  156.  
  157.  
  158. class TextFormatter:
  159.     LEFT = 0
  160.     CENTER = 1
  161.     RIGHT = 2
  162.     
  163.     def __init__(self, colspeclist):
  164.         self.columns = []
  165.         for colspec in colspeclist:
  166.             self.columns.append(Column(**colspec))
  167.         
  168.  
  169.     
  170.     def compose(self, textlist, add_newline = False):
  171.         numlines = 0
  172.         textlist = list(textlist)
  173.         if len(textlist) != len(self.columns):
  174.             log.error('Formatter: Number of text items does not match columns')
  175.             return None
  176.         for text, column in map(None, textlist, self.columns):
  177.             column.wrap(text)
  178.             numlines = max(numlines, len(column.lines))
  179.         
  180.         complines = [
  181.             ''] * numlines
  182.         for ln in range(numlines):
  183.             for column in self.columns:
  184.                 complines[ln] = complines[ln] + column.getline(ln)
  185.             
  186.         
  187.         if add_newline:
  188.             return '\n'.join(complines) + '\n'
  189.         return '\n'.join(complines)
  190.  
  191.  
  192.  
  193. class Column:
  194.     
  195.     def __init__(self, width = 78, alignment = TextFormatter.LEFT, margin = 0):
  196.         self.width = width
  197.         self.alignment = alignment
  198.         self.margin = margin
  199.         self.lines = []
  200.  
  201.     
  202.     def align(self, line):
  203.         if self.alignment == TextFormatter.CENTER:
  204.             return line.center(self.width)
  205.         if self.alignment == TextFormatter.RIGHT:
  206.             return line.rjust(self.width)
  207.         return line.ljust(self.width)
  208.  
  209.     
  210.     def wrap(self, text):
  211.         self.lines = []
  212.         words = []
  213.         for word in text.split():
  214.             if word <= self.width:
  215.                 words.append(word)
  216.                 continue
  217.             for i in range(0, len(word), self.width):
  218.                 words.append(word[i:i + self.width])
  219.             
  220.         
  221.         if not len(words):
  222.             return None
  223.         current = words.pop(0)
  224.         for word in words:
  225.             increment = 1 + len(word)
  226.             if len(current) + increment > self.width:
  227.                 self.lines.append(self.align(current))
  228.                 current = word
  229.                 continue
  230.             len(words)
  231.             current = current + ' ' + word
  232.         
  233.         self.lines.append(self.align(current))
  234.  
  235.     
  236.     def getline(self, index):
  237.         if index < len(self.lines):
  238.             return ' ' * self.margin + self.lines[index]
  239.         return ' ' * (self.margin + self.width)
  240.  
  241.  
  242.  
  243. class Stack:
  244.     
  245.     def __init__(self):
  246.         self.stack = []
  247.  
  248.     
  249.     def pop(self):
  250.         return self.stack.pop()
  251.  
  252.     
  253.     def push(self, value):
  254.         self.stack.append(value)
  255.  
  256.     
  257.     def as_list(self):
  258.         return self.stack
  259.  
  260.     
  261.     def clear(self):
  262.         self.stack = []
  263.  
  264.     
  265.     def __len__(self):
  266.         return len(self.stack)
  267.  
  268.  
  269.  
  270. class Queue(Stack):
  271.     
  272.     def __init__(self):
  273.         Stack.__init__(self)
  274.  
  275.     
  276.     def get(self):
  277.         return self.stack.pop(0)
  278.  
  279.     
  280.     def put(self, value):
  281.         Stack.push(self, value)
  282.  
  283.  
  284.  
  285. class RingBuffer:
  286.     
  287.     def __init__(self, size_max = 50):
  288.         self.max = size_max
  289.         self.data = []
  290.  
  291.     
  292.     def append(self, x):
  293.         '''append an element at the end of the buffer'''
  294.         self.data.append(x)
  295.         if len(self.data) == self.max:
  296.             self.cur = 0
  297.             self.__class__ = RingBufferFull
  298.         
  299.  
  300.     
  301.     def replace(self, x):
  302.         '''replace the last element instead off appending'''
  303.         self.data[-1] = x
  304.  
  305.     
  306.     def get(self):
  307.         ''' return a list of elements from the oldest to the newest'''
  308.         return self.data
  309.  
  310.  
  311.  
  312. class RingBufferFull:
  313.     
  314.     def __init__(self, n):
  315.         pass
  316.  
  317.     
  318.     def append(self, x):
  319.         self.data[self.cur] = x
  320.         self.cur = (self.cur + 1) % self.max
  321.  
  322.     
  323.     def replace(self, x):
  324.         self.cur = (self.cur - 1) % self.max
  325.         self.data[self.cur] = x
  326.         self.cur = (self.cur + 1) % self.max
  327.  
  328.     
  329.     def get(self):
  330.         return self.data[self.cur:] + self.data[:self.cur]
  331.  
  332.  
  333.  
  334. def sort_dict_by_value(d):
  335.     ''' Returns the keys of dictionary d sorted by their values '''
  336.     items = d.items()
  337.     backitems = [ [
  338.         v[1],
  339.         v[0]] for v in items ]
  340.     backitems.sort()
  341.     return [ backitems[i][1] for i in range(0, len(backitems)) ]
  342.  
  343.  
  344. def commafy(val):
  345.     return unicode(locale.format('%d', val, grouping = True))
  346.  
  347.  
  348. def format_bytes(s, show_bytes = False):
  349.     if s < 1024:
  350.         return ''.join([
  351.             commafy(s),
  352.             ' B'])
  353.     if s < s:
  354.         pass
  355.     elif s < 1048576:
  356.         if show_bytes:
  357.             return ''.join([
  358.                 unicode(round(s / 1024, 1)),
  359.                 u' KB (',
  360.                 commafy(s),
  361.                 ')'])
  362.         return ''.join([
  363.             unicode(round(s / 1024, 1)),
  364.             u' KB'])
  365.     elif s < s:
  366.         pass
  367.     elif s < 1073741824:
  368.         if show_bytes:
  369.             return ''.join([
  370.                 unicode(round(s / 1.04858e+06, 1)),
  371.                 u' MB (',
  372.                 commafy(s),
  373.                 ')'])
  374.         return ''.join([
  375.             unicode(round(s / 1.04858e+06, 1)),
  376.             u' MB'])
  377.     elif show_bytes:
  378.         return ''.join([
  379.             unicode(round(s / 1.07374e+09, 1)),
  380.             u' GB (',
  381.             commafy(s),
  382.             ')'])
  383.     s < 1024
  384.     return ''.join([
  385.         unicode(round(s / 1.07374e+09, 1)),
  386.         u' GB'])
  387.  
  388.  
  389. try:
  390.     make_temp_file = tempfile.mkstemp
  391. except AttributeError:
  392.     
  393.     def make_temp_file(suffix = '', prefix = '', dir = '', text = False):
  394.         path = tempfile.mktemp(suffix)
  395.         fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_EXCL, 448)
  396.         return (os.fdopen(fd, 'w+b'), path)
  397.  
  398.  
  399.  
  400. def which(command, return_full_path = False):
  401.     path = os.getenv('PATH').split(':')
  402.     path.append('/sbin')
  403.     path.append('/usr/sbin')
  404.     path.append('/usr/local/sbin')
  405.     found_path = ''
  406.     for p in path:
  407.         
  408.         try:
  409.             files = os.listdir(p)
  410.         except OSError:
  411.             continue
  412.             continue
  413.  
  414.         if command in files:
  415.             found_path = p
  416.             break
  417.             continue
  418.     
  419.     if return_full_path:
  420.         if found_path:
  421.             return os.path.join(found_path, command)
  422.         return ''
  423.     return_full_path
  424.     return found_path
  425.  
  426.  
  427. class UserSettings(object):
  428.     
  429.     def __init__(self):
  430.         self.load()
  431.  
  432.     
  433.     def loadDefaults(self):
  434.         self.cmd_print = ''
  435.         path = which('hp-print')
  436.         if len(path) > 0:
  437.             self.cmd_print = 'hp-print -p%PRINTER%'
  438.         else:
  439.             path = which('kprinter')
  440.             if len(path) > 0:
  441.                 self.cmd_print = 'kprinter -P%PRINTER% --system cups'
  442.             else:
  443.                 path = which('gtklp')
  444.                 if len(path) > 0:
  445.                     self.cmd_print = 'gtklp -P%PRINTER%'
  446.                 else:
  447.                     path = which('xpp')
  448.                     if len(path) > 0:
  449.                         self.cmd_print = 'xpp -P%PRINTER%'
  450.                     
  451.         self.cmd_scan = ''
  452.         path = which('xsane')
  453.         if len(path) > 0:
  454.             self.cmd_scan = 'xsane -V %SANE_URI%'
  455.         else:
  456.             path = which('kooka')
  457.             if len(path) > 0:
  458.                 self.cmd_scan = 'kooka'
  459.             else:
  460.                 path = which('xscanimage')
  461.                 if len(path) > 0:
  462.                     self.cmd_scan = 'xscanimage'
  463.                 
  464.         path = which('hp-unload')
  465.         if len(path):
  466.             self.cmd_pcard = 'hp-unload -d %DEVICE_URI%'
  467.         else:
  468.             self.cmd_pcard = 'python %HOME%/unload.py -d %DEVICE_URI%'
  469.         path = which('hp-makecopies')
  470.         if len(path):
  471.             self.cmd_copy = 'hp-makecopies -d %DEVICE_URI%'
  472.         else:
  473.             self.cmd_copy = 'python %HOME%/makecopies.py -d %DEVICE_URI%'
  474.         path = which('hp-sendfax')
  475.         if len(path):
  476.             self.cmd_fax = 'hp-sendfax -d %FAX_URI%'
  477.         else:
  478.             self.cmd_fax = 'python %HOME%/sendfax.py -d %FAX_URI%'
  479.         path = which('hp-fab')
  480.         if len(path):
  481.             self.cmd_fab = 'hp-fab'
  482.         else:
  483.             self.cmd_fab = 'python %HOME%/fab.py'
  484.  
  485.     
  486.     def load(self):
  487.         self.loadDefaults()
  488.         log.debug('Loading user settings...')
  489.         self.auto_refresh = to_bool(user_conf.get('refresh', 'enable', '0'))
  490.         
  491.         try:
  492.             self.auto_refresh_rate = int(user_conf.get('refresh', 'rate', '30'))
  493.         except ValueError:
  494.             self.auto_refresh_rate = 30
  495.  
  496.         
  497.         try:
  498.             self.auto_refresh_type = int(user_conf.get('refresh', 'type', '0'))
  499.         except ValueError:
  500.             self.auto_refresh_type = 0
  501.  
  502.         self.cmd_print = user_conf.get('commands', 'prnt', self.cmd_print)
  503.         self.cmd_scan = user_conf.get('commands', 'scan', self.cmd_scan)
  504.         self.cmd_pcard = user_conf.get('commands', 'pcard', self.cmd_pcard)
  505.         self.cmd_copy = user_conf.get('commands', 'cpy', self.cmd_copy)
  506.         self.cmd_fax = user_conf.get('commands', 'fax', self.cmd_fax)
  507.         self.cmd_fab = user_conf.get('commands', 'fab', self.cmd_fab)
  508.         self.debug()
  509.  
  510.     
  511.     def debug(self):
  512.         log.debug('Print command: %s' % self.cmd_print)
  513.         log.debug('PCard command: %s' % self.cmd_pcard)
  514.         log.debug('Fax command: %s' % self.cmd_fax)
  515.         log.debug('FAB command: %s' % self.cmd_fab)
  516.         log.debug('Copy command: %s ' % self.cmd_copy)
  517.         log.debug('Scan command: %s' % self.cmd_scan)
  518.         log.debug('Auto refresh: %s' % self.auto_refresh)
  519.         log.debug('Auto refresh rate: %s' % self.auto_refresh_rate)
  520.         log.debug('Auto refresh type: %s' % self.auto_refresh_type)
  521.  
  522.     
  523.     def save(self):
  524.         log.debug('Saving user settings...')
  525.         user_conf.set('commands', 'prnt', self.cmd_print)
  526.         user_conf.set('commands', 'pcard', self.cmd_pcard)
  527.         user_conf.set('commands', 'fax', self.cmd_fax)
  528.         user_conf.set('commands', 'scan', self.cmd_scan)
  529.         user_conf.set('commands', 'cpy', self.cmd_copy)
  530.         user_conf.set('refresh', 'enable', self.auto_refresh)
  531.         user_conf.set('refresh', 'rate', self.auto_refresh_rate)
  532.         user_conf.set('refresh', 'type', self.auto_refresh_type)
  533.         self.debug()
  534.  
  535.  
  536.  
  537. def no_qt_message_gtk():
  538.     
  539.     try:
  540.         import gtk
  541.         w = gtk.Window()
  542.         dialog = gtk.MessageDialog(w, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, 'PyQt not installed. GUI not available. Please check that the PyQt package is installed. Exiting.')
  543.         dialog.run()
  544.         dialog.destroy()
  545.     except ImportError:
  546.         log.error('PyQt not installed. GUI not available. Please check that the PyQt package is installed. Exiting.')
  547.  
  548.  
  549.  
  550. def canEnterGUIMode():
  551.     if not prop.gui_build:
  552.         log.warn('GUI mode disabled in build.')
  553.         return False
  554.     if not os.getenv('DISPLAY'):
  555.         log.warn('No display found.')
  556.         return False
  557.     if not checkPyQtImport():
  558.         log.warn('Qt/PyQt 3 initialization failed.')
  559.         return False
  560.     return True
  561.  
  562.  
  563. def canEnterGUIMode4():
  564.     if not prop.gui_build:
  565.         log.warn('GUI mode disabled in build.')
  566.         return False
  567.     if not os.getenv('DISPLAY'):
  568.         log.warn('No display found.')
  569.         return False
  570.     if not checkPyQtImport4():
  571.         log.warn('Qt/PyQt 4 initialization failed.')
  572.         return False
  573.     return True
  574.  
  575.  
  576. def checkPyQtImport():
  577.     
  578.     try:
  579.         import qt
  580.     except ImportError:
  581.         if os.getenv('DISPLAY') and os.getenv('STARTED_FROM_MENU'):
  582.             no_qt_message_gtk()
  583.         
  584.         log.error('PyQt not installed. GUI not available. Exiting.')
  585.         return False
  586.  
  587.     qtMajor = int(qt.qVersion().split('.')[0])
  588.     if qtMajor < MINIMUM_QT_MAJOR_VER:
  589.         log.error('Incorrect version of Qt installed. Ver. 3.0.0 or greater required.')
  590.         return False
  591.     
  592.     try:
  593.         pyqtVersion = qt.PYQT_VERSION_STR
  594.     except AttributeError:
  595.         qtMajor < MINIMUM_QT_MAJOR_VER
  596.         qtMajor < MINIMUM_QT_MAJOR_VER
  597.         pyqtVersion = qt.PYQT_VERSION
  598.     except:
  599.         qtMajor < MINIMUM_QT_MAJOR_VER
  600.  
  601.     while pyqtVersion.count('.') < 2:
  602.         pyqtVersion += '.0'
  603.         continue
  604.         qtMajor < MINIMUM_QT_MAJOR_VER
  605.     (maj_ver, min_ver, pat_ver) = pyqtVersion.split('.')
  606.     return True
  607.  
  608.  
  609. def checkPyQtImport4():
  610.     
  611.     try:
  612.         import PyQt4
  613.     except ImportError:
  614.         return False
  615.  
  616.     return True
  617.  
  618.  
  619. try:
  620.     from string import Template
  621. except ImportError:
  622.     
  623.     class _multimap:
  624.         '''Helper class for combining multiple mappings.
  625.  
  626.         Used by .{safe_,}substitute() to combine the mapping and keyword
  627.         arguments.
  628.         '''
  629.         
  630.         def __init__(self, primary, secondary):
  631.             self._primary = primary
  632.             self._secondary = secondary
  633.  
  634.         
  635.         def __getitem__(self, key):
  636.             
  637.             try:
  638.                 return self._primary[key]
  639.             except KeyError:
  640.                 return self._secondary[key]
  641.  
  642.  
  643.  
  644.     
  645.     class _TemplateMetaclass(type):
  646.         pattern = '\n        %(delim)s(?:\n          (?P<escaped>%(delim)s) |   # Escape sequence of two delimiters\n          (?P<named>%(id)s)      |   # delimiter and a Python identifier\n          {(?P<braced>%(id)s)}   |   # delimiter and a braced identifier\n          (?P<invalid>)              # Other ill-formed delimiter exprs\n        )\n        '
  647.         
  648.         def __init__(cls, name, bases, dct):
  649.             super(_TemplateMetaclass, cls).__init__(name, bases, dct)
  650.             if 'pattern' in dct:
  651.                 pattern = cls.pattern
  652.             else:
  653.                 pattern = _TemplateMetaclass.pattern % {
  654.                     'delim': re.escape(cls.delimiter),
  655.                     'id': cls.idpattern }
  656.             cls.pattern = re.compile(pattern, re.IGNORECASE | re.VERBOSE)
  657.  
  658.  
  659.     
  660.     class Template:
  661.         '''A string class for supporting $-substitutions.'''
  662.         __metaclass__ = _TemplateMetaclass
  663.         delimiter = '$'
  664.         idpattern = '[_a-z][_a-z0-9]*'
  665.         
  666.         def __init__(self, template):
  667.             self.template = template
  668.  
  669.         
  670.         def _invalid(self, mo):
  671.             i = mo.start('invalid')
  672.             lines = self.template[:i].splitlines(True)
  673.             if not lines:
  674.                 colno = 1
  675.                 lineno = 1
  676.             else:
  677.                 colno = i - len(''.join(lines[:-1]))
  678.                 lineno = len(lines)
  679.             raise ValueError('Invalid placeholder in string: line %d, col %d' % (lineno, colno))
  680.  
  681.         
  682.         def substitute(self, *args, **kws):
  683.             if len(args) > 1:
  684.                 raise TypeError('Too many positional arguments')
  685.             len(args) > 1
  686.             if not args:
  687.                 mapping = kws
  688.             elif kws:
  689.                 mapping = _multimap(kws, args[0])
  690.             else:
  691.                 mapping = args[0]
  692.             
  693.             def convert(mo):
  694.                 if not mo.group('named'):
  695.                     pass
  696.                 named = mo.group('braced')
  697.                 if named is not None:
  698.                     val = mapping[named]
  699.                     return '%s' % val
  700.                 if mo.group('escaped') is not None:
  701.                     return self.delimiter
  702.                 raise ValueError('Unrecognized named group in pattern', self.pattern)
  703.  
  704.             return self.pattern.sub(convert, self.template)
  705.  
  706.         
  707.         def safe_substitute(self, *args, **kws):
  708.             if len(args) > 1:
  709.                 raise TypeError('Too many positional arguments')
  710.             len(args) > 1
  711.             if not args:
  712.                 mapping = kws
  713.             elif kws:
  714.                 mapping = _multimap(kws, args[0])
  715.             else:
  716.                 mapping = args[0]
  717.             
  718.             def convert(mo):
  719.                 named = mo.group('named')
  720.                 if named is not None:
  721.                     
  722.                     try:
  723.                         return '%s' % mapping[named]
  724.                     except KeyError:
  725.                         return self.delimiter + named
  726.                     
  727.  
  728.                 None<EXCEPTION MATCH>KeyError
  729.                 braced = mo.group('braced')
  730.                 if braced is not None:
  731.                     
  732.                     try:
  733.                         return '%s' % mapping[braced]
  734.                     except KeyError:
  735.                         return self.delimiter + '{' + braced + '}'
  736.                     
  737.  
  738.                 None<EXCEPTION MATCH>KeyError
  739.                 if mo.group('escaped') is not None:
  740.                     return self.delimiter
  741.                 if mo.group('invalid') is not None:
  742.                     return self.delimiter
  743.                 raise ValueError('Unrecognized named group in pattern', self.pattern)
  744.  
  745.             return self.pattern.sub(convert, self.template)
  746.  
  747.  
  748.  
  749.  
  750. def cat(s):
  751.     globals = sys._getframe(1).f_globals.copy()
  752.     if 'self' in globals:
  753.         del globals['self']
  754.     
  755.     locals = sys._getframe(1).f_locals.copy()
  756.     if 'self' in locals:
  757.         del locals['self']
  758.     
  759.     return Template(s).substitute(sys._getframe(1).f_globals, **locals)
  760.  
  761. identity = string.maketrans('', '')
  762. unprintable = identity.translate(identity, string.printable)
  763.  
  764. def printable(s):
  765.     return s.translate(identity, unprintable)
  766.  
  767.  
  768. def any(S, f = (lambda x: x)):
  769.     for x in S:
  770.         if f(x):
  771.             return True
  772.     
  773.     return False
  774.  
  775.  
  776. def all(S, f = (lambda x: x)):
  777.     for x in S:
  778.         if not f(x):
  779.             return False
  780.     
  781.     return True
  782.  
  783. BROWSERS = [
  784.     'firefox',
  785.     'mozilla',
  786.     'konqueror',
  787.     'galeon',
  788.     'skipstone']
  789. BROWSER_OPTS = {
  790.     'firefox': '-new-window',
  791.     'mozilla': '',
  792.     'konqueror': '',
  793.     'galeon': '-w',
  794.     'skipstone': '' }
  795.  
  796. def find_browser():
  797.     if platform_avail and platform.system() == 'Darwin':
  798.         return 'open'
  799.     for b in BROWSERS:
  800.         if which(b):
  801.             return b
  802.     else:
  803.         return None
  804.     return which(b)
  805.  
  806.  
  807. def openURL(url):
  808.     if platform_avail and platform.system() == 'Darwin':
  809.         cmd = 'open "%s"' % url
  810.         log.debug(cmd)
  811.         os.system(cmd)
  812.     else:
  813.         for b in BROWSERS:
  814.             bb = which(b)
  815.             if bb:
  816.                 bb = os.path.join(bb, b)
  817.                 cmd = '%s %s "%s" &' % (bb, BROWSER_OPTS[b], url)
  818.                 log.debug(cmd)
  819.                 os.system(cmd)
  820.                 break
  821.                 continue
  822.         
  823.  
  824.  
  825. def uniqueList(input):
  826.     temp = []
  827.     _[1]
  828.     return temp
  829.  
  830.  
  831. def list_move_up(l, m, cmp = None):
  832.     for i in range(1, len(l)):
  833.         if f(i):
  834.             l[i - 1] = l[i]
  835.             l[i] = l[i - 1]
  836.             continue
  837.         None if cmp is None else (None, None, None)
  838.     
  839.  
  840.  
  841. def list_move_down(l, m, cmp = None):
  842.     for i in range(len(l) - 2, -1, -1):
  843.         if f(i):
  844.             l[i] = l[i + 1]
  845.             l[i + 1] = l[i]
  846.             continue
  847.         None if cmp is None else (None, None, None)
  848.     
  849.  
  850.  
  851. class XMLToDictParser:
  852.     
  853.     def __init__(self):
  854.         self.stack = []
  855.         self.data = { }
  856.         self.last_start = ''
  857.  
  858.     
  859.     def startElement(self, name, attrs):
  860.         self.stack.append(str(name).lower())
  861.         self.last_start = str(name).lower()
  862.         if len(attrs):
  863.             for a in attrs:
  864.                 self.stack.append(str(a).lower())
  865.                 self.addData(attrs[a])
  866.                 self.stack.pop()
  867.             
  868.         
  869.  
  870.     
  871.     def endElement(self, name):
  872.         if name.lower() == self.last_start:
  873.             self.addData('')
  874.         
  875.         self.stack.pop()
  876.  
  877.     
  878.     def charData(self, data):
  879.         data = str(data).strip()
  880.         if data and self.stack:
  881.             self.addData(data)
  882.         
  883.  
  884.     
  885.     def addData(self, data):
  886.         self.last_start = ''
  887.         
  888.         try:
  889.             data = int(data)
  890.         except ValueError:
  891.             data = str(data)
  892.  
  893.         stack_str = '-'.join(self.stack)
  894.         stack_str_0 = '-'.join([
  895.             stack_str,
  896.             '0'])
  897.         
  898.         try:
  899.             self.data[stack_str]
  900.         except KeyError:
  901.             
  902.             try:
  903.                 self.data[stack_str_0]
  904.             except KeyError:
  905.                 self.data[stack_str] = data
  906.  
  907.             j = 2
  908.             while True:
  909.                 
  910.                 try:
  911.                     self.data['-'.join([
  912.                         stack_str,
  913.                         str(j)])]
  914.                 except KeyError:
  915.                     self.data['-'.join([
  916.                         stack_str,
  917.                         str(j)])] = data
  918.                     break
  919.  
  920.                 j += 1
  921.  
  922.         self.data[stack_str_0] = self.data[stack_str]
  923.         self.data['-'.join([
  924.             stack_str,
  925.             '1'])] = data
  926.         del self.data[stack_str]
  927.  
  928.     
  929.     def parseXML(self, text):
  930.         parser = expat.ParserCreate()
  931.         parser.StartElementHandler = self.startElement
  932.         parser.EndElementHandler = self.endElement
  933.         parser.CharacterDataHandler = self.charData
  934.         parser.Parse(text, True)
  935.         return self.data
  936.  
  937.  
  938.  
  939. def dquote(s):
  940.     return ''.join([
  941.         '"',
  942.         s,
  943.         '"'])
  944.  
  945. if sys.hexversion < 33686512:
  946.     
  947.     def xlstrip(s, chars = ' '):
  948.         i = 0
  949.         for c, i in zip(s, range(len(s))):
  950.             if c not in chars:
  951.                 break
  952.                 continue
  953.         
  954.         return s[i:]
  955.  
  956.     
  957.     def xrstrip(s, chars = ' '):
  958.         return xreverse(xlstrip(xreverse(s), chars))
  959.  
  960.     
  961.     def xreverse(s):
  962.         l = list(s)
  963.         l.reverse()
  964.         return ''.join(l)
  965.  
  966.     
  967.     def xstrip(s, chars = ' '):
  968.         return xreverse(xlstrip(xreverse(xlstrip(s, chars)), chars))
  969.  
  970. else:
  971.     xlstrip = string.lstrip
  972.     xrstrip = string.rstrip
  973.     xstrip = string.strip
  974.  
  975. def getBitness():
  976.     if platform_avail:
  977.         return int(platform.architecture()[0][:-3])
  978.     return struct.calcsize('P') << 3
  979.  
  980.  
  981. def getProcessor():
  982.     if platform_avail:
  983.         return platform.machine().replace(' ', '_').lower()
  984.     return 'i686'
  985.  
  986. BIG_ENDIAN = 0
  987. LITTLE_ENDIAN = 1
  988.  
  989. def getEndian():
  990.     if sys.byteorder == 'big':
  991.         return BIG_ENDIAN
  992.     return LITTLE_ENDIAN
  993.  
  994.  
  995. def get_password():
  996.     return getpass.getpass('Enter password: ')
  997.  
  998.  
  999. def run(cmd, log_output = True, password_func = get_password, timeout = 1):
  1000.     output = cStringIO.StringIO()
  1001.     
  1002.     try:
  1003.         child = pexpect.spawn(cmd, timeout = timeout)
  1004.     except pexpect.ExceptionPexpect:
  1005.         return (-1, '')
  1006.  
  1007.     
  1008.     try:
  1009.         while True:
  1010.             update_spinner()
  1011.             i = child.expect([
  1012.                 '[pP]assword:',
  1013.                 pexpect.EOF,
  1014.                 pexpect.TIMEOUT])
  1015.             if child.before:
  1016.                 output.write(child.before)
  1017.                 if log_output:
  1018.                     log.debug(child.before)
  1019.                 
  1020.             
  1021.             if i == 0:
  1022.                 if password_func is not None:
  1023.                     child.sendline(password_func())
  1024.                 else:
  1025.                     child.sendline(get_password())
  1026.             password_func is not None
  1027.             if i == 1:
  1028.                 break
  1029.                 continue
  1030.             if i == 2:
  1031.                 continue
  1032.                 continue
  1033.     except Exception:
  1034.         e = None
  1035.         log.error('Exception: %s' % e)
  1036.  
  1037.     cleanup_spinner()
  1038.     child.close()
  1039.     return (child.exitstatus, output.getvalue())
  1040.  
  1041.  
  1042. def expand_range(ns):
  1043.     '''Credit: Jean Brouwers, comp.lang.python 16-7-2004
  1044.        Convert a string representation of a set of ranges into a
  1045.        list of ints, e.g.
  1046.        u"1-4, 7, 9-12" --> [1,2,3,4,7,9,10,11,12]
  1047.     '''
  1048.     fs = []
  1049.     for n in ns.split(u','):
  1050.         n = n.strip()
  1051.         r = n.split('-')
  1052.         if len(r) == 2:
  1053.             h = r[0].rstrip(u'0123456789')
  1054.             r[0] = r[0][len(h):]
  1055.             if not r[0] and r[1]:
  1056.                 raise ValueError, 'empty range: ' + n
  1057.             r[1]
  1058.             r = [ int(i, 10) for i in r ]
  1059.             if r[0] > r[1]:
  1060.                 raise ValueError, 'bad range: ' + n
  1061.             r[0] > r[1]
  1062.             for i in range(r[0], r[1] + 1):
  1063.                 fs.append(h % i)
  1064.             
  1065.         []
  1066.         fs.append(n)
  1067.     
  1068.     fs = []([ (n, i) for i, n in enumerate(fs) ]).keys()
  1069.     fs = _[4]
  1070.     fs.sort()
  1071.     return fs
  1072.  
  1073.  
  1074. def collapse_range(x):
  1075.     ''' Convert a list of integers into a string
  1076.         range representation:
  1077.         [1,2,3,4,7,9,10,11,12] --> u"1-4,7,9-12"
  1078.     '''
  1079.     if not x:
  1080.         return ''
  1081.     s = [
  1082.         str(x[0])]
  1083.     c = x[0]
  1084.     r = False
  1085.     for i in x[1:]:
  1086.         if i == c + 1:
  1087.             r = True
  1088.         elif r:
  1089.             s.append(u'-%s,%s' % (c, i))
  1090.             r = False
  1091.         else:
  1092.             s.append(u',%s' % i)
  1093.         c = i
  1094.     
  1095.     if r:
  1096.         s.append(u'-%s' % i)
  1097.     
  1098.     return ''.join(s)
  1099.  
  1100.  
  1101. def createSequencedFilename(basename, ext, dir = None, digits = 3):
  1102.     if dir is None:
  1103.         dir = os.getcwd()
  1104.     
  1105.     m = 0
  1106.     for f in walkFiles(dir, recurse = False, abs_paths = False, return_folders = False, pattern = '*', path = None):
  1107.         (r, e) = os.path.splitext(f)
  1108.         if r.startswith(basename) and ext == e:
  1109.             
  1110.             try:
  1111.                 i = int(r[len(basename):])
  1112.             except ValueError:
  1113.                 continue
  1114.  
  1115.             m = max(m, i)
  1116.             continue
  1117.     
  1118.     return os.path.join(dir, '%s%0*d%s' % (basename, digits, m + 1, ext))
  1119.  
  1120.  
  1121. def validate_language(lang, default = 'en_US'):
  1122.     if lang is None:
  1123.         (loc, encoder) = locale.getdefaultlocale()
  1124.     else:
  1125.         lang = lang.lower().strip()
  1126.         for loc, ll in supported_locales.items():
  1127.             if lang in ll:
  1128.                 break
  1129.                 continue
  1130.         else:
  1131.             loc = 'en_US'
  1132.     return loc
  1133.  
  1134.  
  1135. def gen_random_uuid():
  1136.     
  1137.     try:
  1138.         import uuid
  1139.         return str(uuid.uuid4())
  1140.     except ImportError:
  1141.         uuidgen = which('uuidgen')
  1142.         if uuidgen:
  1143.             uuidgen = os.path.join(uuidgen, 'uuidgen')
  1144.             return commands.getoutput(uuidgen)
  1145.         return ''
  1146.     except:
  1147.         uuidgen
  1148.  
  1149.  
  1150.  
  1151. class RestTableFormatter(object):
  1152.     
  1153.     def __init__(self, header = None):
  1154.         self.header = header
  1155.         self.rows = []
  1156.  
  1157.     
  1158.     def add(self, row_data):
  1159.         self.rows.append(row_data)
  1160.  
  1161.     
  1162.     def output(self, w):
  1163.         if self.rows:
  1164.             num_cols = len(self.rows[0])
  1165.             for r in self.rows:
  1166.                 if len(r) != num_cols:
  1167.                     log.error('Invalid number of items in row: %s' % r)
  1168.                     return None
  1169.             
  1170.             if len(self.header) != num_cols:
  1171.                 log.error('Invalid number of items in header.')
  1172.             
  1173.             col_widths = []
  1174.             for x, c in enumerate(self.header):
  1175.                 max_width = len(c)
  1176.                 for r in self.rows:
  1177.                     max_width = max(max_width, len(r[x]))
  1178.                 
  1179.                 col_widths.append(max_width + 2)
  1180.             
  1181.             x = '+'
  1182.             for c in col_widths:
  1183.                 x = ''.join([
  1184.                     x,
  1185.                     '-' * (c + 2),
  1186.                     '+'])
  1187.             
  1188.             x = ''.join([
  1189.                 x,
  1190.                 '\n'])
  1191.             w.write(x)
  1192.             if self.header:
  1193.                 x = '|'
  1194.                 for i, c in enumerate(col_widths):
  1195.                     x = ''.join([
  1196.                         x,
  1197.                         ' ',
  1198.                         self.header[i],
  1199.                         ' ' * (c + 1 - len(self.header[i])),
  1200.                         '|'])
  1201.                 
  1202.                 x = ''.join([
  1203.                     x,
  1204.                     '\n'])
  1205.                 w.write(x)
  1206.                 x = '+'
  1207.                 for c in col_widths:
  1208.                     x = ''.join([
  1209.                         x,
  1210.                         '=' * (c + 2),
  1211.                         '+'])
  1212.                 
  1213.                 x = ''.join([
  1214.                     x,
  1215.                     '\n'])
  1216.                 w.write(x)
  1217.             
  1218.             for j, r in enumerate(self.rows):
  1219.                 x = '|'
  1220.                 for i, c in enumerate(col_widths):
  1221.                     x = ''.join([
  1222.                         x,
  1223.                         ' ',
  1224.                         self.rows[j][i],
  1225.                         ' ' * (c + 1 - len(self.rows[j][i])),
  1226.                         '|'])
  1227.                 
  1228.                 x = ''.join([
  1229.                     x,
  1230.                     '\n'])
  1231.                 w.write(x)
  1232.                 x = '+'
  1233.                 for c in col_widths:
  1234.                     x = ''.join([
  1235.                         x,
  1236.                         '-' * (c + 2),
  1237.                         '+'])
  1238.                 
  1239.                 x = ''.join([
  1240.                     x,
  1241.                     '\n'])
  1242.                 w.write(x)
  1243.             
  1244.         else:
  1245.             log.error('No data rows')
  1246.  
  1247.  
  1248.  
  1249. def mixin(cls):
  1250.     import inspect
  1251.     locals = inspect.stack()[1][0].f_locals
  1252.     if '__module__' not in locals:
  1253.         raise TypeError('Must call mixin() from within class def.')
  1254.     '__module__' not in locals
  1255.     dict = cls.__dict__.copy()
  1256.     dict.pop('__doc__', None)
  1257.     dict.pop('__module__', None)
  1258.     locals.update(dict)
  1259.  
  1260. USAGE_OPTIONS = ('[OPTIONS]', '', 'heading', False)
  1261. USAGE_LOGGING1 = ('Set the logging level:', '-l<level> or --logging=<level>', 'option', False)
  1262. USAGE_LOGGING2 = ('', '<level>: none, info\\*, error, warn, debug (\\*default)', 'option', False)
  1263. USAGE_LOGGING3 = ('Run in debug mode:', '-g (same as option: -ldebug)', 'option', False)
  1264. USAGE_LOGGING_PLAIN = ('Output plain text only:', '-t', 'option', False)
  1265. USAGE_ARGS = ('[PRINTER|DEVICE-URI]', '', 'heading', False)
  1266. USAGE_ARGS2 = ('[PRINTER]', '', 'heading', False)
  1267. USAGE_DEVICE = ('To specify a device-URI:', '-d<device-uri> or --device=<device-uri>', 'option', False)
  1268. USAGE_PRINTER = ('To specify a CUPS printer:', '-p<printer> or --printer=<printer>', 'option', False)
  1269. USAGE_BUS1 = ('Bus to probe (if device not specified):', '-b<bus> or --bus=<bus>', 'option', False)
  1270. USAGE_BUS2 = ('', '<bus>: cups\\*, usb\\*, net, bt, fw, par\\* (\\*defaults) (Note: bt and fw not supported in this release.)', 'option', False)
  1271. USAGE_HELP = ('This help information:', '-h or --help', 'option', True)
  1272. USAGE_SPACE = ('', '', 'space', False)
  1273. USAGE_EXAMPLES = ('Examples:', '', 'heading', False)
  1274. USAGE_NOTES = ('Notes:', '', 'heading', False)
  1275. USAGE_STD_NOTES1 = ('If device or printer is not specified, the local device bus is probed and the program enters interactive mode.', '', 'note', False)
  1276. USAGE_STD_NOTES2 = ('If -p\\* is specified, the default CUPS printer will be used.', '', 'note', False)
  1277. USAGE_SEEALSO = ('See Also:', '', 'heading', False)
  1278. USAGE_LANGUAGE = ('Set the language:', '-q <lang> or --lang=<lang>. Use -q? or --lang=? to see a list of available language codes.', 'option', False)
  1279. USAGE_LANGUAGE2 = ('Set the language:', '--lang=<lang>. Use --lang=? to see a list of available language codes.', 'option', False)
  1280. USAGE_MODE = ('[MODE]', '', 'header', False)
  1281. USAGE_NON_INTERACTIVE_MODE = ('Run in non-interactive mode:', '-n or --non-interactive', 'option', False)
  1282. USAGE_GUI_MODE = ('Run in graphical UI mode:', '-u or --gui (Default)', 'option', False)
  1283. USAGE_INTERACTIVE_MODE = ('Run in interactive mode:', '-i or --interactive', 'option', False)
  1284. if sys_conf.get('configure', 'ui-toolkit', 'qt3') == 'qt3':
  1285.     USAGE_USE_QT3 = ('Use Qt3:', '--qt3 (Default)', 'option', False)
  1286.     USAGE_USE_QT4 = ('Use Qt4:', '--qt4', 'option', False)
  1287. else:
  1288.     USAGE_USE_QT3 = ('Use Qt3:', '--qt3', 'option', False)
  1289.     USAGE_USE_QT4 = ('Use Qt4:', '--qt4 (Default)', 'option', False)
  1290.  
  1291. def ttysize():
  1292.     ln1 = commands.getoutput('stty -a').splitlines()[0]
  1293.     vals = {
  1294.         'rows': None,
  1295.         'columns': None }
  1296.     for ph in ln1.split(';'):
  1297.         x = ph.split()
  1298.         if len(x) == 2:
  1299.             vals[x[0]] = x[1]
  1300.             vals[x[1]] = x[0]
  1301.             continue
  1302.     
  1303.     
  1304.     try:
  1305.         rows = int(vals['rows'])
  1306.         cols = int(vals['columns'])
  1307.     except TypeError:
  1308.         (rows, cols) = (25, 80)
  1309.  
  1310.     return (rows, cols)
  1311.  
  1312.  
  1313. def usage_formatter(override = 0):
  1314.     (rows, cols) = ttysize()
  1315.     if override:
  1316.         col1 = override
  1317.         col2 = cols - col1 - 8
  1318.     else:
  1319.         col1 = int(cols / 3) - 8
  1320.         col2 = cols - col1 - 8
  1321.     return TextFormatter(({
  1322.         'width': col1,
  1323.         'margin': 2 }, {
  1324.         'width': col2,
  1325.         'margin': 2 }))
  1326.  
  1327.  
  1328. def format_text(text_list, typ = 'text', title = '', crumb = '', version = ''):
  1329.     '''
  1330.     Format usage text in multiple formats:
  1331.         text: for --help in the console
  1332.         rest: for conversion with rst2web for the website
  1333.         man: for manpages
  1334.     '''
  1335.     if typ == 'text':
  1336.         formatter = usage_formatter()
  1337.         for line in text_list:
  1338.             (text1, text2, format, trailing_space) = line
  1339.             text1 = text1.replace('\\', '')
  1340.             text2 = text2.replace('\\', '')
  1341.             if format == 'summary':
  1342.                 log.info(log.bold(text1))
  1343.                 log.info('')
  1344.                 continue
  1345.             if format in ('para', 'name', 'seealso'):
  1346.                 log.info(text1)
  1347.                 if trailing_space:
  1348.                     log.info('')
  1349.                 
  1350.             trailing_space
  1351.             if format in ('heading', 'header'):
  1352.                 log.info(log.bold(text1))
  1353.                 continue
  1354.             if format in ('option', 'example'):
  1355.                 log.info(formatter.compose((text1, text2), trailing_space))
  1356.                 continue
  1357.             if format == 'note':
  1358.                 if text1.startswith(' '):
  1359.                     log.info('\t' + text1.lstrip())
  1360.                 else:
  1361.                     log.info(text1)
  1362.             text1.startswith(' ')
  1363.             if format == 'space':
  1364.                 log.info('')
  1365.                 continue
  1366.         
  1367.         log.info('')
  1368.     elif typ == 'rest':
  1369.         (opt_colwidth1, opt_colwidth2) = (0, 0)
  1370.         (exmpl_colwidth1, exmpl_colwidth2) = (0, 0)
  1371.         (note_colwidth1, note_colwidth2) = (0, 0)
  1372.         for line in text_list:
  1373.             (text1, text2, format, trailing_space) = line
  1374.             if format == 'option':
  1375.                 opt_colwidth1 = max(len(text1), opt_colwidth1)
  1376.                 opt_colwidth2 = max(len(text2), opt_colwidth2)
  1377.                 continue
  1378.             if format == 'example':
  1379.                 exmpl_colwidth1 = max(len(text1), exmpl_colwidth1)
  1380.                 exmpl_colwidth2 = max(len(text2), exmpl_colwidth2)
  1381.                 continue
  1382.             if format == 'note':
  1383.                 note_colwidth1 = max(len(text1), note_colwidth1)
  1384.                 note_colwidth2 = max(len(text2), note_colwidth2)
  1385.                 continue
  1386.         
  1387.         opt_colwidth1 += 4
  1388.         opt_colwidth2 += 4
  1389.         exmpl_colwidth1 += 4
  1390.         exmpl_colwidth2 += 4
  1391.         note_colwidth1 += 4
  1392.         note_colwidth2 += 4
  1393.         opt_tablewidth = opt_colwidth1 + opt_colwidth2
  1394.         exmpl_tablewidth = exmpl_colwidth1 + exmpl_colwidth2
  1395.         note_tablewidth = note_colwidth1 + note_colwidth2
  1396.         log.info('restindex\npage-title: %s\ncrumb: %s\nformat: rest\nfile-extension: html\nencoding: utf8\n/restindex\n' % (title, crumb))
  1397.         t = '%s: %s (ver. %s)' % (crumb, title, version)
  1398.         log.info(t)
  1399.         log.info('=' * len(t))
  1400.         log.info('')
  1401.         links = []
  1402.         needs_header = False
  1403.         for line in text_list:
  1404.             (text1, text2, format, trailing_space) = line
  1405.             if format == 'seealso':
  1406.                 links.append(text1)
  1407.                 text1 = '`%s`_' % text1
  1408.             
  1409.             len1 = len(text1)
  1410.             len2 = len(text2)
  1411.             if format == 'summary':
  1412.                 log.info(''.join([
  1413.                     '**',
  1414.                     text1,
  1415.                     '**']))
  1416.                 log.info('')
  1417.                 continue
  1418.             if format in ('para', 'name'):
  1419.                 log.info('')
  1420.                 log.info(text1)
  1421.                 log.info('')
  1422.                 continue
  1423.             if format in ('heading', 'header'):
  1424.                 log.info('')
  1425.                 log.info('**' + text1 + '**')
  1426.                 log.info('')
  1427.                 needs_header = True
  1428.                 continue
  1429.             if format == 'option':
  1430.                 if needs_header:
  1431.                     log.info('.. class:: borderless')
  1432.                     log.info('')
  1433.                     log.info(''.join([
  1434.                         '+',
  1435.                         '-' * opt_colwidth1,
  1436.                         '+',
  1437.                         '-' * opt_colwidth2,
  1438.                         '+']))
  1439.                     needs_header = False
  1440.                 
  1441.                 if text1 and '`_' not in text1:
  1442.                     log.info(''.join([
  1443.                         '| *',
  1444.                         text1,
  1445.                         '*',
  1446.                         ' ' * (opt_colwidth1 - len1 - 3),
  1447.                         '|',
  1448.                         text2,
  1449.                         ' ' * (opt_colwidth2 - len2),
  1450.                         '|']))
  1451.                 elif text1:
  1452.                     log.info(''.join([
  1453.                         '|',
  1454.                         text1,
  1455.                         ' ' * (opt_colwidth1 - len1),
  1456.                         '|',
  1457.                         text2,
  1458.                         ' ' * (opt_colwidth2 - len2),
  1459.                         '|']))
  1460.                 else:
  1461.                     log.info(''.join([
  1462.                         '|',
  1463.                         ' ' * opt_colwidth1,
  1464.                         '|',
  1465.                         text2,
  1466.                         ' ' * (opt_colwidth2 - len2),
  1467.                         '|']))
  1468.                 log.info(''.join([
  1469.                     '+',
  1470.                     '-' * opt_colwidth1,
  1471.                     '+',
  1472.                     '-' * opt_colwidth2,
  1473.                     '+']))
  1474.                 continue
  1475.             if format == 'example':
  1476.                 if needs_header:
  1477.                     log.info('.. class:: borderless')
  1478.                     log.info('')
  1479.                     log.info(''.join([
  1480.                         '+',
  1481.                         '-' * exmpl_colwidth1,
  1482.                         '+',
  1483.                         '-' * exmpl_colwidth2,
  1484.                         '+']))
  1485.                     needs_header = False
  1486.                 
  1487.                 if text1 and '`_' not in text1:
  1488.                     log.info(''.join([
  1489.                         '| *',
  1490.                         text1,
  1491.                         '*',
  1492.                         ' ' * (exmpl_colwidth1 - len1 - 3),
  1493.                         '|',
  1494.                         text2,
  1495.                         ' ' * (exmpl_colwidth2 - len2),
  1496.                         '|']))
  1497.                 elif text1:
  1498.                     log.info(''.join([
  1499.                         '|',
  1500.                         text1,
  1501.                         ' ' * (exmpl_colwidth1 - len1),
  1502.                         '|',
  1503.                         text2,
  1504.                         ' ' * (exmpl_colwidth2 - len2),
  1505.                         '|']))
  1506.                 else:
  1507.                     log.info(''.join([
  1508.                         '|',
  1509.                         ' ' * exmpl_colwidth1,
  1510.                         '|',
  1511.                         text2,
  1512.                         ' ' * (exmpl_colwidth2 - len2),
  1513.                         '|']))
  1514.                 log.info(''.join([
  1515.                     '+',
  1516.                     '-' * exmpl_colwidth1,
  1517.                     '+',
  1518.                     '-' * exmpl_colwidth2,
  1519.                     '+']))
  1520.                 continue
  1521.             if format == 'seealso':
  1522.                 if text1 and '`_' not in text1:
  1523.                     log.info(text1)
  1524.                 
  1525.             '`_' not in text1
  1526.             if format == 'note':
  1527.                 if needs_header:
  1528.                     log.info('.. class:: borderless')
  1529.                     log.info('')
  1530.                     log.info(''.join([
  1531.                         '+',
  1532.                         '-' * note_colwidth1,
  1533.                         '+',
  1534.                         '-' * note_colwidth2,
  1535.                         '+']))
  1536.                     needs_header = False
  1537.                 
  1538.                 if text1.startswith(' '):
  1539.                     log.info(''.join([
  1540.                         '|',
  1541.                         ' ' * (note_tablewidth + 1),
  1542.                         '|']))
  1543.                 
  1544.                 log.info(''.join([
  1545.                     '|',
  1546.                     text1,
  1547.                     ' ' * ((note_tablewidth - len1) + 1),
  1548.                     '|']))
  1549.                 log.info(''.join([
  1550.                     '+',
  1551.                     '-' * note_colwidth1,
  1552.                     '+',
  1553.                     '-' * note_colwidth2,
  1554.                     '+']))
  1555.                 continue
  1556.             if format == 'space':
  1557.                 log.info('')
  1558.                 continue
  1559.         
  1560.         for l in links:
  1561.             log.info('\n.. _`%s`: %s.html\n' % (l, l.replace('hp-', '')))
  1562.         
  1563.         log.info('')
  1564.     elif typ == 'man':
  1565.         log.info('.TH "%s" 1 "%s" Linux "User Manuals"' % (crumb, version))
  1566.         log.info('.SH NAME\n%s \\- %s' % (crumb, title))
  1567.         for line in text_list:
  1568.             (text1, text2, format, trailing_space) = line
  1569.             text1 = text1.replace('\\*', '*')
  1570.             text2 = text2.replace('\\*', '*')
  1571.             len1 = len(text1)
  1572.             len2 = len(text2)
  1573.             if format == 'summary':
  1574.                 log.info('.SH SYNOPSIS')
  1575.                 log.info('.B %s' % text1.replace('Usage:', ''))
  1576.                 continue
  1577.             if format == 'name':
  1578.                 log.info('.SH DESCRIPTION\n%s' % text1)
  1579.                 continue
  1580.             if format in ('option', 'example', 'note'):
  1581.                 if text1:
  1582.                     log.info('.IP "%s"\n%s' % (text1, text2))
  1583.                 else:
  1584.                     log.info(text2)
  1585.             text1
  1586.             if format in ('header', 'heading'):
  1587.                 log.info('.SH %s' % text1.upper().replace(':', '').replace('[', '').replace(']', ''))
  1588.                 continue
  1589.             if format in 'seealso, para':
  1590.                 log.info(text1)
  1591.                 continue
  1592.         
  1593.         log.info('.SH AUTHOR')
  1594.         log.info('HPLIP (Hewlett-Packard Linux Imaging and Printing) is an')
  1595.         log.info('HP developed solution for printing, scanning, and faxing with')
  1596.         log.info('HP inkjet and laser based printers in Linux.')
  1597.         log.info('.SH REPORTING BUGS')
  1598.         log.info('The HPLIP Launchpad.net site')
  1599.         log.info('.B https://launchpad.net/hplip')
  1600.         log.info('is available to get help, report')
  1601.         log.info('bugs, make suggestions, discuss the HPLIP project or otherwise')
  1602.         log.info('contact the HPLIP Team.')
  1603.         log.info('.SH COPYRIGHT')
  1604.         log.info('Copyright (c) 2001-8 Hewlett-Packard Development Company, L.P.')
  1605.         log.info('.LP')
  1606.         log.info('This software comes with ABSOLUTELY NO WARRANTY.')
  1607.         log.info('This is free software, and you are welcome to distribute it')
  1608.         log.info('under certain conditions. See COPYING file for more details.')
  1609.         log.info('')
  1610.     
  1611.  
  1612.  
  1613. def log_title(program_name, version, show_ver = True):
  1614.     log.info('')
  1615.     if show_ver:
  1616.         log.info(log.bold('HP Linux Imaging and Printing System (ver. %s)' % prop.version))
  1617.     else:
  1618.         log.info(log.bold('HP Linux Imaging and Printing System'))
  1619.     log.info(log.bold('%s ver. %s' % (program_name, version)))
  1620.     log.info('')
  1621.     log.info('Copyright (c) 2001-8 Hewlett-Packard Development Company, LP')
  1622.     log.info('This software comes with ABSOLUTELY NO WARRANTY.')
  1623.     log.info('This is free software, and you are welcome to distribute it')
  1624.     log.info('under certain conditions. See COPYING file for more details.')
  1625.     log.info('')
  1626.  
  1627.  
  1628. def ireplace(old, search, replace):
  1629.     regex = '(?i)' + re.escape(search)
  1630.     return re.sub(regex, replace, old)
  1631.  
  1632.