view frontends/wix/xmlui.py @ 103:6be927a465ed

XMLUI refactoring, step 1
author Goffi <goffi@goffi.org>
date Wed, 23 Jun 2010 00:23:26 +0800
parents frontends/wix/form.py@2503de7fb4c7
children 5458ac1380cc
line wrap: on
line source

#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
wix: a SAT frontend
Copyright (C) 2009, 2010  Jérôme Poisson (goffi@goffi.org)

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""



import wx
import pdb
from xml.dom import minidom
from logging import debug, info, warning, error
from tools.jid  import JID


class XMLUI(wx.Frame):
    """Create an user interface from a SàT xml"""

    def __init__(self, host, xml_data='', title="Form", options=[], misc={}):
        style = wx.DEFAULT_FRAME_STYLE & ~wx.CLOSE_BOX if 'NO_CANCEL' in options else wx.DEFAULT_FRAME_STYLE #FIXME: gof: Q&D tmp hack
        super(XMLUI, self).__init__(None, title=title, style=style)

        self.host = host
        self.options = options
        self.misc = misc
        self.ctl_list = []  # usefull to access ctrl

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(self.sizer)
        self.SetAutoLayout(True)
        
        #events
        if not 'NO_CANCEL' in self.options:
            self.Bind(wx.EVT_CLOSE, self.onClose, self)
        
        self.MakeModal()

        self.constructUI(xml_data)

        self.Show()

    def __parse_elems(self, childs, parent, sizer):
        """Parse elements inside a <layout> tags, and add them to the sizer"""
        for elem in childs:
            if elem.nodeName != "elem":
                message=_("Unmanaged tag")
                error(message)
                raise Exception(message)
            _proportion = 0
            name = elem.getAttribute("name")
            type = elem.getAttribute("type")
            value = elem.getAttribute("value") if elem.hasAttribute('value') else u''
            if type=="empty":
                ctrl = wx.Window(parent, -1)
            elif type=="text":
                try:
                    value = elem.childNodes[0].wholeText
                except KeyError:
                    warning (_("text node has no child !"))
                ctrl = wx.StaticText(parent, -1, value)
            elif type=="label":
                ctrl = wx.StaticText(parent, -1, value+": ")
            elif type=="string":
                ctrl = wx.TextCtrl(parent, -1, value)
                self.ctl_list.append({'name':name, 'type':type, 'control':ctrl})
                _proportion = 1
            elif type=="password":
                ctrl = wx.TextCtrl(parent, -1, value, style=wx.TE_PASSWORD)
                self.ctl_list.append({'name':name, 'type':type, 'control':ctrl})
                _proportion = 1
            elif type=="list":
                ctrl = wx.ListBox(parent, -1, choices=[option.getAttribute("value") for option in elem.getElementsByTagName("option")], style=wx.LB_SINGLE)
                self.ctl_list.append({'name':name, 'type':type, 'control':ctrl})
                _proportion = 1
            else:
                error(_("FIXME FIXME FIXME: type [%s] is not implemented") % type)  #FIXME !
                raise NotImplementedError
            sizer.Add(ctrl, _proportion, flag=wx.EXPAND)



    def constructUI(self, xml_data):
        panel=wx.Panel(self)
        panel.sizer = wx.BoxSizer(wx.VERTICAL)

        cat_dom = minidom.parseString(xml_data.encode('utf-8'))
        top= cat_dom.documentElement
        self.type = top.getAttribute("type")
        if top.nodeName != "sat_xmlui" or not self.type in ['form', 'param', 'window']:
            message = _("XML UI received is invalid")
            error(message)
            raise Exception(message)

        for node in cat_dom.documentElement.childNodes:
            if node.nodeName == "layout":
                layout_panel = wx.Panel(panel, -1)
                if node.getAttribute('type') == "vertical":
                    current_sizer = wx.BoxSizer(wx.VERTICAL)
                elif node.getAttribute('type') == "pairs":
                    current_sizer = wx.FlexGridSizer(cols=2)
                    current_sizer.AddGrowableCol(1) #The growable column need most of time to be the right one in pairs
                else:
                    warning(_("Unknown layout, using default one"))
                    current_sizer = wx.BoxSizer(wx.VERTICAL)
                layout_panel.SetSizer(current_sizer)
                self.__parse_elems(node.childNodes, layout_panel, current_sizer)
                panel.sizer.Add(layout_panel, flag=wx.EXPAND)
            else:
                message=_("Unknown tag")
                error(message)
                raise Exception(message) #TODO: raise a custom exception here

        if self.type == 'form':
            dialogButtons = wx.StdDialogButtonSizer()
            submitButton = wx.Button(panel,wx.ID_OK, label=_("Submit"))
            dialogButtons.AddButton(submitButton)
            panel.Bind(wx.EVT_BUTTON, self.onFormSubmitted, submitButton)
            if not 'NO_CANCEL' in self.options:
                cancelButton = wx.Button(panel,wx.ID_CANCEL)
                dialogButtons.AddButton(cancelButton)
                panel.Bind(wx.EVT_BUTTON, self.onFormCancelled, cancelButton)
            dialogButtons.Realize()
            panel.sizer.Add(dialogButtons, flag=wx.ALIGN_CENTER_HORIZONTAL)

        panel.SetSizer(panel.sizer)
        panel.SetAutoLayout(True)
        panel.sizer.Fit(self)
        self.sizer.Add(panel, 1, flag=wx.EXPAND)
        cat_dom.unlink()

    def onFormSubmitted(self, event):
        """Called when submit button is clicked"""
        debug(_("Submitting form"))
        data = []
        for ctrl in self.ctl_list:
            if isinstance(ctrl['control'], wx.ListBox):
                data.append((ctrl['name'], ctrl['control'].GetStringSelection()))
            else:
                data.append((ctrl["name"], ctrl["control"].GetValue()))
        if self.misc.has_key('action_back'): #FIXME FIXME FIXME: WTF ! Must be cleaned
            id = self.misc['action_back']("SUBMIT",self.misc['target'], data)
            self.host.current_action_ids.add(id)
        elif self.misc.has_key('callback'):
            self.misc['callback'](data)
        else:
            warning (_("The form data is not sent back, the type is not managed properly"))
        self.MakeModal(False)
        self.Destroy()
        
    def onFormCancelled(self, event):
        """Called when cancel button is clicked"""
        debug(_("Cancelling form"))
        self.MakeModal(False)
        self.Close()
   
    def onClose(self, event):
        """Close event: we have to send the form."""
        debug(_("close"))
        self.MakeModal(False)
        event.Skip()