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

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. from lxml.etree import XPath, ElementBase
  5. from lxml.html import fromstring, tostring, XHTML_NAMESPACE
  6. from lxml.html import _forms_xpath, _options_xpath, _nons, _transform_result
  7. from lxml.html import defs
  8. import copy
  9.  
  10. try:
  11.     basestring = __builtins__['basestring']
  12. except (KeyError, NameError):
  13.     basestring = str
  14.  
  15. __all__ = [
  16.     'FormNotFound',
  17.     'fill_form',
  18.     'fill_form_html',
  19.     'insert_errors',
  20.     'insert_errors_html',
  21.     'DefaultErrorCreator']
  22.  
  23. class FormNotFound(LookupError):
  24.     pass
  25.  
  26. _form_name_xpath = XPath('descendant-or-self::form[name=$name]|descendant-or-self::x:form[name=$name]', namespaces = {
  27.     'x': XHTML_NAMESPACE })
  28. _input_xpath = []([]([ 'descendant-or-self::' + _tag for _tag in ('input', 'select', 'textarea', 'x:input', 'x:select', 'x:textarea') ]), namespaces = {
  29.     'x': XHTML_NAMESPACE })
  30. _label_for_xpath = XPath('//label[@for=$for_id]|//x:label[@for=$for_id]', namespaces = {
  31.     'x': XHTML_NAMESPACE })
  32. _name_xpath = XPath('descendant-or-self::*[@name=$name]')
  33.  
  34. def fill_form(el, values, form_id = None, form_index = None):
  35.     el = _find_form(el, form_id = form_id, form_index = form_index)
  36.     _fill_form(el, values)
  37.  
  38.  
  39. def fill_form_html(html, values, form_id = None, form_index = None):
  40.     result_type = type(html)
  41.     if isinstance(html, basestring):
  42.         doc = fromstring(html)
  43.     else:
  44.         doc = copy.deepcopy(html)
  45.     fill_form(doc, values, form_id = form_id, form_index = form_index)
  46.     return _transform_result(result_type, doc)
  47.  
  48.  
  49. def _fill_form(el, values):
  50.     counts = { }
  51.     if hasattr(values, 'mixed'):
  52.         values = values.mixed()
  53.     
  54.     inputs = _input_xpath(el)
  55.     for input in inputs:
  56.         name = input.get('name')
  57.         if not name:
  58.             continue
  59.         
  60.         if _takes_multiple(input):
  61.             value = values.get(name, [])
  62.             if not isinstance(value, (list, tuple)):
  63.                 value = [
  64.                     value]
  65.             
  66.             _fill_multiple(input, value)
  67.             continue
  68.         if name not in values:
  69.             continue
  70.             continue
  71.         index = counts.get(name, 0)
  72.         counts[name] = index + 1
  73.         value = values[name]
  74.         if isinstance(value, (list, tuple)):
  75.             
  76.             try:
  77.                 value = value[index]
  78.             except IndexError:
  79.                 continue
  80.             except:
  81.                 None<EXCEPTION MATCH>IndexError
  82.             
  83.  
  84.         None<EXCEPTION MATCH>IndexError
  85.         if index > 0:
  86.             continue
  87.         
  88.         _fill_single(input, value)
  89.     
  90.  
  91.  
  92. def _takes_multiple(input):
  93.     if _nons(input.tag) == 'select' and input.get('multiple'):
  94.         return True
  95.     type = input.get('type', '').lower()
  96.     if type in ('radio', 'checkbox'):
  97.         return True
  98.     return False
  99.  
  100.  
  101. def _fill_multiple(input, value):
  102.     type = input.get('type', '').lower()
  103.     if type == 'checkbox':
  104.         v = input.get('value')
  105.         if v is None:
  106.             if not value:
  107.                 result = False
  108.             else:
  109.                 result = value[0]
  110.                 if isinstance(value, basestring):
  111.                     result = result == 'on'
  112.                 
  113.             _check(input, result)
  114.         else:
  115.             _check(input, v in value)
  116.     elif type == 'radio':
  117.         v = input.get('value')
  118.         _check(input, v in value)
  119.     else:
  120.         for option in _options_xpath(input):
  121.             v = option.get('value')
  122.             if v is None:
  123.                 v = option.text_content()
  124.             
  125.             _select(option, v in value)
  126.         
  127.  
  128.  
  129. def _check(el, check):
  130.     if check:
  131.         el.set('checked', '')
  132.     elif 'checked' in el.attrib:
  133.         del el.attrib['checked']
  134.     
  135.  
  136.  
  137. def _select(el, select):
  138.     if select:
  139.         el.set('selected', '')
  140.     elif 'selected' in el.attrib:
  141.         del el.attrib['selected']
  142.     
  143.  
  144.  
  145. def _fill_single(input, value):
  146.     if _nons(input.tag) == 'textarea':
  147.         input.clear()
  148.         input.text = value
  149.     else:
  150.         input.set('value', value)
  151.  
  152.  
  153. def _find_form(el, form_id = None, form_index = None):
  154.     if form_id is None and form_index is None:
  155.         forms = _forms_xpath(el)
  156.         for form in forms:
  157.             return form
  158.         
  159.         raise FormNotFound('No forms in page')
  160.     form_index is None
  161.     if form_id is not None:
  162.         form = el.get_element_by_id(form_id)
  163.         if form is not None:
  164.             return form
  165.         forms = _form_name_xpath(el, name = form_id)
  166.         if forms:
  167.             return forms[0]
  168.         raise FormNotFound('No form with the name or id of %r (forms: %s)' % (id, ', '.join(_find_form_ids(el))))
  169.     form_id is not None
  170.     if form_index is not None:
  171.         forms = _forms_xpath(el)
  172.         
  173.         try:
  174.             return forms[form_index]
  175.         except IndexError:
  176.             raise FormNotFound('There is no form with the index %r (%i forms found)' % (form_index, len(forms)))
  177.         except:
  178.             None<EXCEPTION MATCH>IndexError
  179.         
  180.  
  181.     None<EXCEPTION MATCH>IndexError
  182.  
  183.  
  184. def _find_form_ids(el):
  185.     forms = _forms_xpath(el)
  186.     if not forms:
  187.         yield '(no forms)'
  188.         return None
  189.     for index, form in enumerate(forms):
  190.         if form.get('id'):
  191.             if form.get('name'):
  192.                 yield '%s or %s' % (form.get('id'), form.get('name'))
  193.                 forms
  194.             else:
  195.                 yield form.get('id')
  196.                 forms
  197.         form.get('name')
  198.         if form.get('name'):
  199.             yield form.get('name')
  200.             forms
  201.             continue
  202.         yield '(unnamed form %s)' % index
  203.     
  204.  
  205.  
  206. class DefaultErrorCreator(object):
  207.     insert_before = True
  208.     block_inside = True
  209.     error_container_tag = 'div'
  210.     error_message_class = 'error-message'
  211.     error_block_class = 'error-block'
  212.     default_message = 'Invalid'
  213.     
  214.     def __init__(self, **kw):
  215.         for name, value in kw.items():
  216.             if not hasattr(self, name):
  217.                 raise TypeError('Unexpected keyword argument: %s' % name)
  218.             hasattr(self, name)
  219.             setattr(self, name, value)
  220.         
  221.  
  222.     
  223.     def __call__(self, el, is_block, message):
  224.         error_el = el.makeelement(self.error_container_tag)
  225.         if self.error_message_class:
  226.             error_el.set('class', self.error_message_class)
  227.         
  228.         if is_block and self.error_block_class:
  229.             error_el.set('class', error_el.get('class', '') + ' ' + self.error_block_class)
  230.         
  231.         if message is None or message == '':
  232.             message = self.default_message
  233.         
  234.         if isinstance(message, ElementBase):
  235.             error_el.append(message)
  236.         elif not message:
  237.             pass
  238.         error_el.text = self.default_message
  239.         if is_block and self.block_inside:
  240.             if self.insert_before:
  241.                 error_el.tail = el.text
  242.                 el.text = None
  243.                 el.insert(0, error_el)
  244.             else:
  245.                 el.append(error_el)
  246.         else:
  247.             parent = el.getparent()
  248.             pos = parent.index(el)
  249.             if self.insert_before:
  250.                 parent.insert(pos, error_el)
  251.             else:
  252.                 error_el.tail = el.tail
  253.                 el.tail = None
  254.                 parent.insert(pos + 1, error_el)
  255.  
  256.  
  257. default_error_creator = DefaultErrorCreator()
  258.  
  259. def insert_errors(el, errors, form_id = None, form_index = None, error_class = 'error', error_creator = default_error_creator):
  260.     el = _find_form(el, form_id = form_id, form_index = form_index)
  261.     for name, error in errors.items():
  262.         if error is None:
  263.             continue
  264.         
  265.         for error_el, message in _find_elements_for_name(el, name, error):
  266.             _insert_error(error_el, message, error_class, error_creator)
  267.         
  268.     
  269.  
  270.  
  271. def insert_errors_html(html, values, **kw):
  272.     result_type = type(html)
  273.     if isinstance(html, basestring):
  274.         doc = fromstring(html)
  275.     else:
  276.         doc = copy.deepcopy(html)
  277.     insert_errors(doc, values, **kw)
  278.     return _transform_result(result_type, doc)
  279.  
  280.  
  281. def _insert_error(el, error, error_class, error_creator):
  282.     if _nons(el.tag) in defs.empty_tags or _nons(el.tag) == 'textarea':
  283.         is_block = False
  284.     else:
  285.         is_block = True
  286.     if _nons(el.tag) != 'form' and error_class:
  287.         _add_class(el, error_class)
  288.     
  289.     if el.get('id'):
  290.         labels = _label_for_xpath(el, for_id = el.get('id'))
  291.         if labels:
  292.             for label in labels:
  293.                 _add_class(label, error_class)
  294.             
  295.         
  296.     
  297.     error_creator(el, is_block, error)
  298.  
  299.  
  300. def _add_class(el, class_name):
  301.     if el.get('class'):
  302.         el.set('class', el.get('class') + ' ' + class_name)
  303.     else:
  304.         el.set('class', class_name)
  305.  
  306.  
  307. def _find_elements_for_name(form, name, error):
  308.     if name is None:
  309.         yield (form, error)
  310.         return None
  311.     if name.startswith('#'):
  312.         el = form.get_element_by_id(name[1:])
  313.         return None
  314.     els = _name_xpath(form, name = name)
  315.     if not els:
  316.         return None
  317.     if not isinstance(error, (list, tuple)):
  318.         yield (els[0], error)
  319.         els
  320.         return None
  321.     for el, err in zip(els, error):
  322.         yield (el, err)
  323.         name.startswith('#') if err is None else els
  324.     
  325.  
  326.