view src/tools/ @ 800:e0770d977d58

xmlui: added boolean type management in XMLUIResult2DataFormResult
author Goffi <>
date Tue, 04 Feb 2014 18:04:32 +0100
parents 8f5479f8709a
children 9007bb133009
line wrap: on
line source

# -*- coding: utf-8 -*-

# SAT: a jabber client
# Copyright (C) 2009, 2010, 2011, 2012, 2013  Jérôme Poisson (

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <>.

from sat.core.i18n import _
from logging import debug, info, error, warning
from xml.dom import minidom, NotFoundErr
from wokkel import data_form
from twisted.words.xish import domish
from sat.core import exceptions

"""This library help manage XML used in SàT (parameters, registration, etc) """

SAT_PARAM_SEPARATOR = "_XMLUI_PARAM_" # used to have unique elements names

def dataForm2XMLUI(form, submit_id, session_id=None):
    """Take a data form (xep-0004, Wokkel's implementation) and convert it to a SàT xml"""

    form_ui = XMLUI("form", "vertical", submit_id=submit_id, session_id=session_id)

    if form.instructions:
        form_ui.addText('\n'.join(form.instructions), 'instructions')

    labels = [field for field in form.fieldList if field.label]
    if labels:
        # if there is no label, we don't need to use pairs

    for field in form.fieldList:
        if field.fieldType == 'fixed':
            __field_type = 'text'
        elif field.fieldType == 'text-single':
            __field_type = "string"
        elif field.fieldType == 'text-private':
            __field_type = "password"
        elif field.fieldType == 'boolean':
            __field_type = "bool"
            if field.value is None:
                field.value = "false"
        elif field.fieldType == 'list-single':
            __field_type = "list"
            error(u"FIXME FIXME FIXME: Type [%s] is not managed yet by SàT" % field.fieldType)
            __field_type = "string"

        if labels:
            if field.label:

        form_ui.addElement(__field_type, field.var, field.value, [option.value for option in field.options])
    return form_ui

def dataFormResult2AdvancedList(form_ui, form_xml):
    """Take a raw data form (not parsed by XEP-0004) and convert it to an advanced list
    raw data form is used because Wokkel doesn't manage result items parsing yet
    @param form_ui: the XMLUI where the AdvancedList will be added
    @param form_xml: domish.Element of the data form
    @return: AdvancedList element
    headers = []
    items = []
        reported_elt = form_xml.elements('jabber:x:data', 'reported').next()
    except StopIteration:
        raise exceptions.DataError("Couldn't find expected <reported> tag")

    for elt in reported_elt.elements():
        if != "field":
            raise exceptions.DataError("Unexpected tag")
        name = elt["var"]
        label = elt.attributes.get('label','')
        type_ = elt.attributes.get('type','') # TODO
        headers.append(Header(name, label))

    if not headers:
        raise exceptions.DataError("No reported fields (see XEP-0004 §3.4)")

    item_elts = form_xml.elements('jabber:x:data', 'item')

    for item_elt in item_elts:
        fields = []
        for elt in item_elt.elements():
            if != 'field':
                warning("Unexpected tag (%s)" %
            name = elt['var']
            child_elt = elt.firstChildElement()
            if != "value":
                raise exceptions.DataError('Was expecting <value> tag')
            value = unicode(child_elt)
            fields.append(Field(name, value))
        items.append(Item(' | '.join((field.value for field in fields if field)), fields))

    return form_ui.addAdvancedList(None, headers, items)

def dataFormResult2XMLUI(form_xml, session_id=None):
    """Take a raw data form (not parsed by XEP-0004) and convert it to a SàT XMLUI
    raw data form is used because Wokkel doesn't manage result items parsing yet
    @param form_xml: domish.Element of the data form
    @return: XMLUI interface

    form_ui = XMLUI("window", "vertical", session_id=session_id)
    dataFormResult2AdvancedList(form_ui, form_xml)
    return form_ui

def XMLUIResult2DataFormResult(xmlui_data):
    """ Extract form data from a XMLUI return
    @xmlui_data: data returned by frontends for XMLUI form
    @return: dict of data usable by Wokkel's dataform
    return {key[len(SAT_FORM_PREFIX):]: value for key, value in xmlui_data.iteritems() if key.startswith(SAT_FORM_PREFIX)}

def XMLUIResultToElt(xmlui_data):
    """ Construct result domish.Element from XMLUI result
    @xmlui_data: data returned by frontends for XMLUI form
    form = data_form.Form('result')
    return form.toElement()

def tupleList2dataForm(values):
    """convert a list of tuples (name,value) to a wokkel submit data form"""
    form = data_form.Form('submit')
    for value in values:
        field = data_form.Field(var=value[0], value=value[1])

    return form

def paramsXml2xmlUI(xml):
    """Convert the xml for parameter to a SàT XML User Interface"""
    params_doc = minidom.parseString(xml.encode('utf-8'))
    top = params_doc.documentElement
    if top.nodeName != 'params':
        error(_('INTERNAL ERROR: parameters xml not valid'))
    param_ui = XMLUI("param", "tabs")
    for category in top.getElementsByTagName("category"):
        category_name = category.getAttribute('name')
        label = category.getAttribute('label')
        if not category_name:
            error(_('INTERNAL ERROR: params categories must have a name'))
        param_ui.addCategory(category_name, 'pairs', label=label)
        for param in category.getElementsByTagName("param"):
            param_name = param.getAttribute('name')
            label = param.getAttribute('label')
            if not param_name:
                error(_('INTERNAL ERROR: params must have a name'))
            type_ = param.getAttribute('type')
            value = param.getAttribute('value') or None
            options = getOptions(param)
            callback_id = param.getAttribute('callback_id') or None
            if type_ == "button":
                param_ui.addLabel(label or param_name)
            param_ui.addElement(name="%s%s%s" % (category_name, SAT_PARAM_SEPARATOR, param_name), type_=type_, value=value, options=options, callback_id=callback_id)

    return param_ui.toXml()

def getOptions(param):
    """Retrieve the options for list element. Allow listing the <option/>
    tags directly in <param/> or in an intermediate <options/> tag."""
    elems = param.getElementsByTagName("options")
    if len(elems) == 0:
        elems = param.getElementsByTagName("option")
        elems = elems.item(0).getElementsByTagName("option")
    if len(elems) == 0:
        return []
    return [elem.getAttribute("value") for elem in elems]

class Header(object):
    """AdvandeList's header"""

    def __init__(self, field_name, label, description=None, type_=None):
        @param field_name: name of the field referenced
        @param label: label to be displayed in columns
        @param description: long descriptive text
        @param type_: TODO

        self.field_name = field_name
        self.label = label
        self.description = description
        self.type = type_
        if type_ is not None:
            raise NotImplementedError # TODO:

class Item(object):
    """Item used in AdvancedList"""

    def __init__(self, text=None, fields=None):
        @param text: Optional textual representation, when fields are not showed individually
        @param fields: list of Field instances²
        self.text = text
        self.fields = fields if fields is not None else []

class Field(object):
    """Field used in AdvancedList (in items)"""

    def __init__(self, name, value):
        @param name: name of the field, used to identify the field in headers
        @param value: actual content of the field
        """ = name
        self.value = value

class XMLUI(object):
    """This class is used to create a user interface (form/window/parameters/etc) using SàT XML"""

    def __init__(self, panel_type, layout="vertical", title=None, submit_id=None, session_id=None):
        """Init SàT XML Panel
        @param panel_type: one of
            - window (new window)
            - form (formulaire, depend of the frontend, usually a panel with cancel/submit buttons)
            - param (parameters, presentatio depend of the frontend)
        @param layout: disposition of elements, one of:
            - vertical: elements are disposed up to bottom
            - horizontal: elements are disposed left to right
            - pairs: elements come on two aligned columns
              (usually one for a label, the next for the element)
            - tabs: elemens are in categories with tabs (notebook)
        @param title: title or default if None
        @param submit_id: callback id to call for panel_type we can submit (form, param)
        if panel_type not in ['window', 'form', 'param']:
            raise exceptions.DataError(_("Unknown panel type [%s]") % panel_type)
        if panel_type == 'form' and submit_id is None:
            raise exceptions.DataError(_("form XMLUI need a submit_id"))
        self.type_ = panel_type
        impl = minidom.getDOMImplementation()

        self.doc = impl.createDocument(None, "sat_xmlui", None)
        top_element = self.doc.documentElement
        top_element.setAttribute("type", panel_type)
        if title:
            top_element.setAttribute("title", title)
        self.submit_id = submit_id
        self.session_id = session_id
        self.parentTabsLayout = None  # used only we have 'tabs' layout
        self.currentCategory = None  # used only we have 'tabs' layout
        self.currentLayout = None

    def __del__(self):

    def submit_id(self):
        top_element = self.doc.documentElement
        value = top_element.getAttribute("submit")
        return value or None

    def submit_id(self, value):
        top_element = self.doc.documentElement
        if value is None:
            except NotFoundErr:
        elif value: # submit_id can be the empty string to bypass form restriction
            top_element.setAttribute("submit", value)

    def session_id(self):
        top_element = self.doc.documentElement
        value = top_element.getAttribute("session_id")
        return value or None

    def session_id(self, value):
        top_element = self.doc.documentElement
        if value is None:
            except NotFoundErr:
        elif value:
            top_element.setAttribute("session_id", value)
            raise exceptions.DataError("session_id can't be empty")

    def _createLayout(self, layout, parent=None):
        """Create a layout element
        @param type: layout type (cf init doc)
        @parent: parent element or None
        if not layout in ['vertical', 'horizontal', 'pairs', 'tabs']:
            error(_("Unknown layout type [%s]") % layout)
            assert False
        layout_elt = self.doc.createElement('layout')
        layout_elt.setAttribute('type', layout)
        if parent is not None:
        return layout_elt

    def _createElem(self, type_, name=None, parent=None):
        """Create an element
        @param type_: one of
            - empty: empty element (usefull to skip something in a layout, e.g. skip first element in a PAIRS layout)
            - text: text to be displayed in an multi-line area, e.g. instructions
        @param name: name of the element or None
        @param parent: parent element or None
        @return: created element
        elem = self.doc.createElement('elem')
        if name:
            elem.setAttribute('name', name)
        elem.setAttribute('type', type_)
        if parent is not None:
        return elem

    def changeLayout(self, layout):
        """Change the current layout"""
        self.currentLayout = self._createLayout(layout, self.currentCategory if self.currentCategory else self.doc.documentElement)
        if layout == "tabs":
            self.parentTabsLayout = self.currentLayout

    def addEmpty(self, name=None):
        """Add a multi-lines text"""
        return self._createElem('empty', name, self.currentLayout)

    def addText(self, text, name=None):
        """Add a multi-lines text"""
        elem = self._createElem('text', name, self.currentLayout)
        text = self.doc.createTextNode(text)
        return elem

    def addLabel(self, text, name=None):
        """Add a single line text, mainly useful as label before element"""
        elem = self._createElem('label', name, self.currentLayout)
        elem.setAttribute('value', text)
        return elem

    def addString(self, name=None, value=None):
        """Add a string box"""
        elem = self._createElem('string', name, self.currentLayout)
        if value:
            elem.setAttribute('value', value)
        return elem

    def addPassword(self, name=None, value=None):
        """Add a password box"""
        elem = self._createElem('password', name, self.currentLayout)
        if value:
            elem.setAttribute('value', value)
        return elem

    def addTextBox(self, name=None, value=None):
        """Add a string box"""
        elem = self._createElem('textbox', name, self.currentLayout)
        if value:
            elem.setAttribute('value', value)
        return elem

    def addBool(self, name=None, value="true"):
        """Add a string box"""
        if value=="0":
        elif value=="1":
        assert value in ["true", "false"]
        elem = self._createElem('bool', name, self.currentLayout)
        elem.setAttribute('value', value)
        return elem

    def addList(self, options, name=None, value=None, style=None):
        """Add a list of choices"""
        if style is None:
            style = set()
        styles = set(style)
        assert options
        assert styles.issubset(['multi'])
        elem = self._createElem('list', name, self.currentLayout)
        self.addOptions(options, elem)
        if value:
            elem.setAttribute('value', value)
        for style in styles:
            elem.setAttribute(style, 'yes')
        return elem

    def addAdvancedList(self, name=None, headers=None, items=None):
        """Create an advanced list
        @param headers: optional headers informations
        @param items: list of Item instances
        @return: created element
        elem = self._createElem('advanced_list', name, self.currentLayout)
        self.addHeaders(headers, elem)
        if items:
            self.addItems(items, elem)
        return elem

    def addButton(self, callback_id, name, value, fields_back=[]):
        """Add a button
        @param callback: callback which will be called if button is pressed
        @param name: name
        @param value: label of the button
        @fields_back: list of names of field to give back when pushing the button
        elem = self._createElem('button', name, self.currentLayout)
        elem.setAttribute('callback', callback_id)
        elem.setAttribute('value', value)
        for field in fields_back:
            fback_el = self.doc.createElement('field_back')
            fback_el.setAttribute('name', field)
        return elem

    def addElement(self, type_, name=None, value=None, options=None, callback_id=None, headers=None, available=None):
        """Convenience method to add element, the params correspond to the ones in addSomething methods"""
        if type_ == 'empty':
            return self.addEmpty(name)
        elif type_ == 'text':
            assert value is not None
            return self.addText(value, name)
        elif type_ == 'label':
            return self.addLabel(value)
        elif type_ == 'string':
            return self.addString(name, value)
        elif type_ == 'password':
            return self.addPassword(name, value)
        elif type_ == 'textbox':
            return self.addTextBox(name, value)
        elif type_ == 'bool':
            if not value:
                value = "true"
            return self.addBool(name, value)
        elif type_ == 'list':
            return self.addList(options, name, value)
        elif type_ == 'advancedlist':
            return self.addAdvancedList(name, headers, available)
        elif type_ == 'button':
            assert(callback_id and value)
            return self.addButton(callback_id, name, value)

    # List

    def addOptions(self, options, parent):
        """Add options to a multi-values element (e.g. list)
        @param parent: multi-values element"""
        for option in options:
            opt = self.doc.createElement('option')
            if isinstance(option, basestring):
                value, label = option, option
            elif isinstance(option, tuple):
                value, label = option
            opt.setAttribute('value', value)
            opt.setAttribute('label', label)

    # Advanced list

    def addHeaders(self, headers, parent):
        headers_elt = self.doc.createElement('headers')
        for header in headers:
            field_elt = self.doc.createElement('field')
            field_elt.setAttribute('field_name', header.field_name)
            field_elt.setAttribute('label', header.label)
            if header.description:
                field_elt.setAttribute('description', header.description)
            if header.type:
                field_elt.setAttribute('type', header.type)

    def addItems(self, items, parent):
        """Add items to an AdvancedList
        @param items: list of Item instances
        @param parent: parent element (should be addAdvancedList)

        items_elt = self.doc.createElement('items')
        for item in items:
            item_elt = self.doc.createElement('item')
            if item.text is not None:
                text_elt = self.doc.createElement('text')

            for field in item.fields:
                field_elt = self.doc.createElement('field')
                field_elt.setAttribute('value', field.value)



    # Tabs

    def addCategory(self, name, layout, label=None):
        """Add a category to current layout (must be a tabs layout)"""
        assert(layout != 'tabs')
        if not self.parentTabsLayout:
            error(_("Trying to add a category without parent tabs layout"))
        if self.parentTabsLayout.getAttribute('type') != 'tabs':
            error(_("parent layout of a category is not tabs"))

        if not label:
            label = name
        self.currentCategory = cat = self.doc.createElement('category')
        cat.setAttribute('name', name)
        cat.setAttribute('label', label)

    def toXml(self):
        """return the XML representation of the panel"""
        return self.doc.toxml()

class ElementParser(object):
    """callable class to parse XML string into Element
    Found at
    (c) Karl Anderson"""

    def __call__(self, string):
        self.result = None

        def onStart(elem):
            self.result = elem

        def onEnd():

        def onElement(elem):

        parser = domish.elementStream()
        parser.DocumentStartEvent = onStart
        parser.ElementEvent = onElement
        parser.DocumentEndEvent = onEnd
        tmp = domish.Element((None, "s"))
        tmp.addRawXml(string.replace('\n', ' ').replace('\t', ' '))
        return self.result.firstChildElement()