# -*- coding: iso-8859-1 -*-
#
#-------------------------------------------------------------------------------
#                    Code_Saturne version 1.3
#                    ------------------------
#
#
#     This file is part of the Code_Saturne User Interface, element of the
#     Code_Saturne CFD tool.
#
#     Copyright (C) 1998-2007 EDF S.A., France
#
#     contact: saturne-support@edf.fr
#
#     The Code_Saturne User Interface 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 2 of
#     the License, or (at your option) any later version.
#
#     The Code_Saturne User Interface 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 the Code_Saturne Kernel; if not, write to the
#     Free Software Foundation, Inc.,
#     51 Franklin St, Fifth Floor,
#     Boston, MA  02110-1301  USA
#
#-------------------------------------------------------------------------------


"""
This module defines the 'Additional user's scalars' page.

This module defines the following classes:
- MultiSelect
- DefineUserScalarsModel
- DefineUserScalarsView
- PageText
"""


#-------------------------------------------------------------------------------
# Library modules import
#-------------------------------------------------------------------------------


import string
import Tix
import unittest
from Tkconstants import *


#-------------------------------------------------------------------------------
# Application modules import
#-------------------------------------------------------------------------------


from Base.Common import *
import Base.Toolbox as Tool
import Base.Dialog as Dialog
import Base.TkPage as TkPage
from Base.XMLvariables import Variables
from Base.XMLvariables import Model
from Base.XMLmodel import XMLmodel
from DefineBoundaryRegions import DefBCModel


#-------------------------------------------------------------------------------
# Multi-selection string
#-------------------------------------------------------------------------------


MULTISEL = "*****"


#-------------------------------------------------------------------------------
# Hlist multi-selection class
#-------------------------------------------------------------------------------


class MultiSelect:
    """
    This class is design in order to manage the storage of the selected items in
    the Hlist.
    """
    def __init__(self, case, Hlist, nodeScalar):
        """
        Constructor
        """
        self.case       = case
        self.Hlist      = Hlist
        self.nodeScalar = nodeScalar


    def _initList(self):
        """
        For each mouse selection we reinitialize all lists.
        """
        self.labelL = []
        self.initL = []
        self.variL = []
        self.miniL = []
        self.maxiL = []

        self.mdl = DefineUserScalarsModel(self.case)

    def scalarInfo(self, entry):
        """
        Return info from the argument entry.
        """
        # Here we must call the tk function directly without passing in
        # Tix.py, because of a bug in tix8.1 in the Hlist.item_cget function
        #
        t = PageText()
        h = self.Hlist
        label = h.tk.call(h, 'item', 'cget', entry, 0, '-text')
        init  = h.tk.call(h, 'item', 'cget', entry, 1, '-text')
        vari  = h.tk.call(h, 'item', 'cget', entry, 2, '-text')

        if vari == "--": vari = t.NO_VARIANCE

        return label, float(init), vari


    def setItems(self, entriesL):
        """
        Store values when a new selection is done.
        """
        self._initList()

        for entry in entriesL:
            label, init, vari = self.scalarInfo(entry)
            self.labelL.append(label)
            self.initL.append(init)
            self.variL.append(vari)

            list = self.mdl.getUserScalarsNodeList()
            for scalar in list:
                if self.mdl.mgetLabelScalar(scalar) == label:
                    mini, maxi = self.mdl.mgetMinMaxValue(scalar)
                    self.miniL.append(mini)
                    self.maxiL.append(maxi)


    def getItems(self):
        """
        Return all the lists.
        """
        return self.labelL, self.initL, self.variL, self.miniL, self.maxiL


    def widgetText(self):
        """
        Find the right texts for the widget layout.
        """
        label, init, vari = self.labelL[0], self.initL[0], self.variL[0]
        mini, maxi       = self.miniL[0], self.maxiL[0]

        for i in self.labelL:
            if label != i: 
                label = MULTISEL

        for i in self.initL:
            if init != i: 
                init = MULTISEL

        for i in self.variL:
            if vari != i: 
                vari = MULTISEL

        for i in self.miniL:
            if not i: i = 0
            if mini != i: 
                mini = MULTISEL

        for i in self.maxiL:
            if not i: i = 1.0e+12
            if maxi != i: 
                maxi = MULTISEL

        if init != MULTISEL: init = "%g" % (init)
        if mini != MULTISEL: mini = "%g" % (mini)
        if maxi != MULTISEL: maxi = "%g" % (maxi)

        return label, init, vari, mini, maxi


#-------------------------------------------------------------------------------
# Define User Scalars model class
#-------------------------------------------------------------------------------


class DefineUserScalarsModel(Variables, Model):
    """
    """
    def __init__(self, case):
        """
        Constructor
        """
        self.case = case

        # TODO: the InitZoneView class !
        zone_label = "1"
        self.zone = zone_label

        self.node_th_sca    = self.case.xmlGetNode('thermal_scalar')
        self.node_user_sca  = self.case.xmlGetNode('additional_scalars')
        self.node_bc        = self.case.xmlGetNode('boundary_conditions')

        self.dicoCoeff = {}

    def defaultValues(self):
        """Return the default values"""
        pass


    def getScalarList(self):
        """Return the User scalar label list (thermal scalar included)"""
        list = []
        model = self.node_th_sca['model']
        if model != 'off':
            list.append(self.node_th_sca.xmlGetNodeList('scalar', name=model)['label'])
        for n in self.node_user_sca.xmlGetNodeList('scalar', type='user'):
            list.append(n['label'])
        return list


    def getUserScalarList(self):
        """Return the User scalar label list (without thermal scalar)"""
        list = []
        for n in self.node_user_sca.xmlGetNodeList('scalar', type='user'):
            list.append(n['label'])
        return list


    def setNewUserScalar(self, scalar_label):
        """Input a new additional_scalar with label scalar_label""" 
        Variables(self.case).setNewUserScalar(self.node_user_sca, scalar_label)


    def deleteUserScalar(self, scalar_label):
        """Delete an additional_scalar node with label scalar_label""" 
        for n in self.node_user_sca.xmlGetNodeList('scalar', type='user'):
            if n['label'] == scalar_label:
                n.xmlRemoveNode()


    def setScalarInitialValue(self, scalar_label, zone, initial_value):
        """
        Put initial value for an additional_scalar with label scalar_label
        and zone zone
        """
        for n in self.node_user_sca.xmlGetNodeList('scalar', type='user'):
            if n['label'] == scalar_label:
                n.xmlInitChildNode('initial_value', zone=zone)
                n.xmlSetData('initial_value', initial_value)


    def getScalarInitialValue(self, scalar_label, zone):
        """
        Get initial value from an additional_scalar with label scalar_label
        and zone zone
        """
        for n in self.node_user_sca.xmlGetNodeList('scalar', type='user'):
            if n['label'] == scalar_label:
                n_init = n.xmlGetChildNode('initial_value', zone=zone)
                if n_init: 
                    val = n.xmlGetDouble('initial_value')
        return val


    def setScalarMinValue(self, scalar_label, min_value):
        """Put minimal value for an additional_scalar with label scalar_label"""
        for n in self.node_user_sca.xmlGetNodeList('scalar', type='user'):
            if n['label'] == scalar_label:
##                n_min = n.xmlInitChildNode('min_value')
##                n_min.xmlSetData(min_value)
                n.xmlSetData('min_value', min_value)


    def getScalarMinValue(self, scalar_label):
        """Get minimal value from an additional_scalar with label scalar_label"""
        for n in self.node_user_sca.xmlGetNodeList('scalar', type='user'):
            if n['label'] == scalar_label:
                n_min = n.xmlGetChildNode('min_value')
                if n_min: 
                    min_val = n.xmlGetDouble('min_value')
        return min_val


    def setScalarMaxValue(self, scalar_label, max_value):
        """Put maximal value for an additional_scalar with label scalar_label"""
        for n in self.node_user_sca.xmlGetNodeList('scalar', type='user'):
            if n['label'] == scalar_label:
                n.xmlSetData('max_value', max_value)


    def getScalarMaxValue(self, scalar_label):
        """Get maximal value from an additional_scalar with label scalar_label"""
        for n in self.node_user_sca.xmlGetNodeList('scalar', type='user'):
            if n['label'] == scalar_label:
                n_max = n.xmlGetChildNode('max_value')
                if n_max: 
                    max_val = n.xmlGetDouble('max_value')
        return max_val


    def setScalarVariance(self, scalar_label, variance_label):
        """Put variance of an additional_scalar with label scalar_label"""
        for n in self.node_user_sca.xmlGetNodeList('scalar', type='user'):
            if n['label'] == scalar_label:
                n.xmlSetData('variance',variance_label)


    def getScalarVariance(self, scalar_label):
        """Get variance of an additional_scalar with label scalar_label"""
        for n in self.node_user_sca.xmlGetNodeList('scalar', type='user'):
            if n['label'] == scalar_label:
                n_var = n.xmlGetChildNode('variance')
                if n_var: 
                    var = n.xmlGetString('variance')
        return var


    def setScalarDiffusivity(self, scalar_label, diffusivity_label, initial_value):
        """
        Put initial value of property "diffusivity" for an additional_scalar 
        with label scalar_label
        """
        for n in self.node_user_sca.xmlGetNodeList('scalar', type='user'):
            if n['label'] == scalar_label:
                n_dif = n.xmlInitChildNode('property', label=diffusivity_label)
                n_dif.xmlSetData('initial_value',initial_value)


    def getScalarDiffusivityLabel(self, scalar_label):
        """
        Get label of diffusivity's property for an additional_scalar 
        with label scalar_label
        """
        lab_diff = ''
        for n in self.node_user_sca.xmlGetNodeList('scalar', type='user'):
            if n['label'] == scalar_label:
                n_diff = n.xmlGetChildNode('property')
                if n_diff:
                    lab_diff = n_diff['label']
        return lab_diff


    def setScalarDiffusivityLabel(self, scalar_label, diffusivity_label):
        """
        Put label of diffusivity's property for an additional_scalar 
        with label scalar_label
        """
        for n in self.node_user_sca.xmlGetNodeList('scalar', type='user'):
            if n['label'] == scalar_label:
                n_dif = n.xmlInitChildNode('property')
                n_dif['label'] = diffusivity_label


    def getScalarDiffusivityInitialValue(self, scalar_label):
        """
        Get initial value of diffusivity's property for an additional_scalar 
        with label scalar_label
        """
        for n in self.node_user_sca.xmlGetNodeList('scalar', type='user'):
            if n['label'] == scalar_label:
                n_diff = n.xmlGetChildNode('property')
                if n_diff:
                    diffu = n.xmlGetDouble('initial_value')
        return diffu


    def setScalarDiffusivityInitialValue(self, scalar_label, initial_value):
        """
        Set initial value of diffusivity's property for an additional_scalar 
        with label scalar_label
        """
        for n in self.node_user_sca.xmlGetNodeList('scalar', type='user'):
            if n['label'] == scalar_label:
                n_diff = n.xmlInitChildNode('property')
                n_diff.xmlSetData('initial_value', initial_value)
                
    def getScalarDiffusivityChoice(self, scalar_label):
        """
        Get choice of diffusivity's property for an additional_scalar 
        with label scalar_label
        """
        for n in self.node_user_sca.xmlGetNodeList('scalar', type='user'):
            if n['label'] == scalar_label:
                n_diff = n.xmlGetChildNode('property')
                if n_diff:
                    choice = n_diff['choice']
        return choice


    def setScalarDiffusivityChoice(self, scalar_label, choice):
        """
        Set choice of diffusivity's property for an additional_scalar 
        with label scalar_label
        """
        for n in self.node_user_sca.xmlGetNodeList('scalar', type='user'):
            if n['label'] == scalar_label:
                n_diff = n.xmlGetChildNode('property')
                if n_diff :
                    n_diff['choice'] = choice
                else:
                    n.xmlInitChildNode('property', choice=choice)


    def getUserScalarsNodeList(self):
        """
        Get list of scalar'nodes
        """
        return self.node_user_sca.xmlGetChildNodeList('scalar')


    def mgetLabelScalar(self, node):
        """
        Input the new label in scalar's node
        """
        return node['label']


    def mgetMinMaxValue(self, node):
        """
        Get min and max scalar'nodes
        """
        mini = node.xmlGetChildDouble('min_value')
        maxi = node.xmlGetChildDouble('max_value')
        return mini, maxi


    def mgetLabInitVariScalar(self, scalar):
        """
        Get label, initial value and variancy of the scalar
        """
        label = scalar['label']
        init = scalar.xmlGetChildDouble('initial_value', zone=self.zone)
        vari = scalar.xmlGetChildString('variance')

        if not vari :
            node_diff = scalar.xmlGetNode('property', 'label')
            self.dicoCoeff[label] = node_diff['label']

        return label, init, vari


    def mgetNewScalar(self, node, tag, name):
        """
        Add new scalar in node 'self.node_user_sca' or 'self.node_bc' in XML doc.
        """
        # for new scalar       
        newChild = Variables(self.case).setNewUserScalar(node, name)

        # for boundary conditions
        for node in self.node_bc.xmlGetChildNodeList('inlet'):
            DefBCModel(self.case).setCondScalar(node, 'dirichlet', '0.0')
        for node in self.node_bc.xmlGetChildNodeList('outlet'):
            DefBCModel(self.case).setCondScalar(node, 'neumann', '0.0')

        return newChild


    def addDiffusivityProperty(self, node, coeff):
        """
        """
        n = Variables(self.case).setNewFluidProperty(node, 'diffusion_coefficient', coeff)
        n.xmlSetData('initial_value', self.getMolecularViscosity())


    def getMolecularViscosity(self):
        """
        """
        coeff = 1.0
        node0 = self.case.xmlInitNode('physical_properties')
        node1 = node0.xmlGetNode('fluid_properties')
        if node1:
            node2 = node1.xmlGetNode('property', name='molecular_viscosity')
            if node2:
                coeff = node2.xmlGetChildDouble('initial_value')

        return coeff


    def mReplaceScalar(self, node, init, vari, mini, maxi, nameCoeff):
        """
        Replace the old values by new ones into the XML doc 
        """
        t = PageText()

        node.xmlInitChildNode('initial_value', zone=self.zone)
        node.xmlSetData('initial_value', init)
        if vari != t.NO_VARIANCE:
            node.xmlSetData('variance', vari)
            node.xmlRemoveChild('property')
            node.xmlRemoveChild('min_value')
            node.xmlRemoveChild('max_value')
        else:
            node.xmlRemoveChild('variance')
            node.xmlSetData('min_value', mini)
            node.xmlSetData('max_value', maxi)
            if nameCoeff:
                self.addDiffusivityProperty(node, nameCoeff)


    def mputNewLabelintoBoundCondScalar(self, old_label, new_label):
        """
        Replace the old label by new ones into boundary conditions 
        for scaar in the XML doc 
        """
        for nature in ('inlet','outlet','wall'):
            for node in self.node_bc.xmlGetChildNodeList(nature):
                for n in node.xmlGetChildNodeList('scalar', type='user'):
                    if n['label'] == old_label: n['label'] = new_label 


    def mSetScalar(self, label, nameCoeff, init, vari, mini, maxi):
        """
        Add the new values to the XML doc 
        """
        newChild = self.mgetNewScalar(self.node_user_sca, 'label', label)
        self.mReplaceScalar(newChild, init, vari, mini, maxi, nameCoeff)

        for node in self.node_bc.xmlGetChildNodeList('inlet'):
            DefBCModel(self.case).setCondScalar(node, 'dirichlet', '0.0')
        for node in self.node_bc.xmlGetChildNodeList('outlet'):
            DefBCModel(self.case).setCondScalar(node, 'neumann', '0.0')


    def msetLabelScalar(self, node, label):
        """
        Inpur the new label in scalar's node
        """
        node['label'] = label


    def mverifVariance(self, label):
        """
        """
        vari = 0
        for node in self.node_user_sca.xmlGetNodeList('scalar', 'label'):
            if node['label'] == label:
                if node.xmlGetString('variance'): vari = 1

        return vari


    def msetNewLabelintoVariance(self, old_label, new_label):
        """
        Put the new label if scalr with new label has one variancy
        """
        label_dico = ""
        for node in self.node_user_sca.xmlGetNodeList('scalar'):
            if node.xmlGetString('variance') == old_label:
                node.xmlSetData('variance', new_label)
                label_dico = node['label']

        return label_dico


    def mputDeleteIntoScalarVariance(self, label):
        """
        Put "delete" in node variance of scalar named label
        It will be destroyed after
        """
        lab_vari=""
        list = self.node_user_sca.xmlGetNodeList('scalar')
        for node in list:
            variance = node.xmlGetString('variance')
            if variance == label:
                node['type'] = 'todelete'
                lab_vari = node['label']
                #self.mputDeleteIntoScalar(node['label'])

        return lab_vari


    def mputDeleteIntoScalar(self, label):
        """
        Put "delete" in node scalar named label
        It will be destroyed after
        """
        # Normally there is only one node in nodeList and in nodeListBC
        #
        list = self.node_user_sca.xmlGetNodeList('scalar', label=label)
        for node in list:
            node['type'] = 'todelete'


    def mDeleteBoundaryScalar(self, label):
        """
        Put "delete" in node scalar named label
        It will be destroyed after
        """
        for nature in ('inlet','outlet','wall'):
            for node in self.node_bc.xmlGetChildNodeList(nature):
                for n in node.xmlGetChildNodeList('scalar', type='user'):
                    if n['label'] == label: n.xmlRemoveNode()



    def mcancelNode(self):
        """
        Cancel node in xml file
        """
        nodeList1 = self.node_user_sca.xmlGetNodeList('scalar', type='todelete')
        for node in nodeList1:
            node.xmlRemoveNode()


#-------------------------------------------------------------------------------
# Main class
#-------------------------------------------------------------------------------


class DefineUserScalarsView(TkPage.Page):
    """
    Class to open Define User Scalars Page.
    """

    def _dependsPages(self, name):
        """
        Construction of the list of dependencies Pages.
        """
#        self.case[name]['depends'] = ['scalar/prosca',
#                                      'bounda/scalar']
        self.case[name]['depends'] = ['scalar/prosca']


    def _pageControl(self):
        """
        Default value settings.
        """

        # Class attribute 'self.currentEntry' represents the selected entries
        # in the Hlist with information allready displayed in the widgets.
        # In the other side, 'self.selectedEntry' contents the last selected entries
        # from the Hlist to be displayed (but not yet). If 'self.currentEntry' and
        # 'self.selectedEntry' are different so the 'self.selectedEntry' becomes
        # the 'self.currentEntry'.
        #
        self.selectedEntry = None
        self.currentEntry  = None
        self.entriesNumber = 0
        self.dicolabel     = {}

        self.mdl = DefineUserScalarsModel(self.case)


    def _make_style(self):
        """
        Define beautiful style in order to display columns in the Hlist.
        """
        self.style={}

        self.style['header'] = Tix.DisplayStyle(Tix.TEXT,
                                                refwindow=self.lf1,
                                                anchor=CENTER,
                                                padx=5, pady=2,
                                                font=fB)
        self.style['style'+'b'] = Tix.DisplayStyle(Tix.TEXT,
                                                   refwindow=self.lf1,
                                                   padx=5,
                                                   selectforeground='#fefefe',
                                                   font=fB)
        self.style['styleV'+'b'] = Tix.DisplayStyle(Tix.TEXT,
                                                    refwindow=self.lf1,
                                                    padx=5,
                                                    fg='brown',
                                                    font=fB)
        self.style['style'] = Tix.DisplayStyle(Tix.TEXT,
                                               refwindow=self.lf1,
                                               padx=5, anchor=CENTER,
                                               selectforeground='#fefefe',
                                               font=fN)
        self.style['styleV'] = Tix.DisplayStyle(Tix.TEXT,
                                                refwindow=self.lf1,
                                                padx=5, anchor=CENTER,
                                                fg='brown',
                                                font=fN)


    def _tkControlVariables(self):
        """
        Tkinter variables declaration.
        Note: 'self.init', 'self.mini' and 'self.maxi' are StringVar() and
        not a DoubleVar() because of the 'MULTISEL' contents possibility.
        """
        self.label = Tix.StringVar()
        self.init = Tix.StringVar()
        self.vari = Tix.StringVar()
        self.mini = Tix.StringVar()
        self.maxi = Tix.StringVar()


    def getLabel(self, event=None):
        """
        Return the label of the scalar. If there is no user label, we propose one.
        Space is forbidden in the scalar label.
        """
        t = PageText()
        if self.mdl.dicoCoeff:
            i = 1
            while (("Dv"+str(i)) in self.mdl.dicoCoeff.values()) \
                or (("scalar"+str(i)) in self.mdl.dicoCoeff.keys()): 
                i = i + 1
            num = str(i)
        else: 
            num = str(1)

        if not self.label.get(): self.label.set("scalar" + num)

        diffCoeff = "Dscal" + num

        if len(self.label.get()) > 8:
            self.stbar.set(t.MSG_LABEL)

        self.label.set(string.join(string.split(self.label.get()), '_')[:8])
        self.mdl.dicoCoeff[self.label.get()] = diffCoeff

        return self.label.get(), diffCoeff


    def getVari(self, event=None):
        """
        Return the variance value from the ComboBox.
        """
        t = PageText()
        self.e4.config(state=NORMAL)
        self.e5.config(state=NORMAL)
        self.l4.config(state=NORMAL)
        self.l5.config(state=NORMAL)

        if self.vari.get() == "":
            self.vari.set(t.NO_VARIANCE)

        elif self.vari.get() != t.NO_VARIANCE:
            self.mini.set('0.0')
            self.maxi.set(SPGRAND)
            self.e4.config(state=DISABLED)
            self.e5.config(state=DISABLED)
            self.l4.config(state=DISABLED)
            self.l5.config(state=DISABLED)

        return self.vari.get()


    def isFloat(self, entry, var):
        """
        Verify if the 'entry' contents a float. If not, signal an error
        and return None.
        """
        try:
            double = float(var.get())
        except:
            self.check2.error(entry)
            double = None

        return double


    def string2float(self, entry, var):
        """
        If the StringVar() 'var' associated to the 'entry', is not a 'MULTISEL',
        convert it to a float.
        """
        self.check2.begin(entry)

        # Several selections in Hlist
        #
        if self.currentEntry and len(self.currentEntry) > 1:
            if var.get() != MULTISEL:
                double = self.isFloat(entry, var)
            else:
                double = MULTISEL

        # Only one selection in Hlist
        #
        else:
            double = self.isFloat(entry, var)

        return double


    def getInit(self, event=None):
        """
        Return the initialization value, which can be
        1) a float, if all selections have the same initialization value,
        2) a 'MULTISEL' string if all selections have not the same initialization value,
        3) 'None' if there is an error.
        """
        if not self.init.get(): self.init.set('0.0')
        return self.string2float(self.e2, self.init)


    def getMini(self, event=None):
        """
        Return the min value, which can be
        1) a float, if all selections have the same min value,
        2) a 'MULTISEL' string if all selections have not the same min value,
        3) 'None' if there is an error.
        """
        if not self.mini.get(): self.mini.set(SMGRAND)
        return self.string2float(self.e4, self.mini)


    def getMaxi(self, event=None):
        """
        Return the min value, which can be
        1) a float, if all selections have the same max value,
        2) a 'MULTISEL' string if all selections have not the same max value,
        3) 'None' if there is an error.
        """
        if not self.maxi.get(): self.maxi.set(SPGRAND)
        return self.string2float(self.e5, self.maxi)




    def insertHlist(self, label, init, vari):
        """
        Create the item Hlist associated with the new boundary definition
        and update the listBox
        """
        self.stbar.busy()
        t = PageText()

        self.entriesNumber = self.entriesNumber + 1
        scal_num = 'item' + str(self.entriesNumber)
        self.dicolabel[label] = scal_num


        if vari == t.NO_VARIANCE: vari = "--"

        # If the scalar is a variance, it is displayed with a specific color.
        #
        if vari != "--":
            self.h.hlist.add(scal_num, itemtype=Tix.TEXT, text=label,
                             style=self.style['styleV'+'b'])
            self.h.hlist.item_create(scal_num, 1, itemtype=Tix.TEXT,
                                     text="%g"%(init),
                                     style=self.style['styleV'])
            self.h.hlist.item_create(scal_num, 2, itemtype=Tix.TEXT,
                                     text=vari,
                                     style=self.style['styleV'])
        else:
            self.h.hlist.add(scal_num, itemtype=Tix.TEXT, text=label,
                             style=self.style['style'+'b'])
            self.h.hlist.item_create(scal_num, 1, itemtype=Tix.TEXT,
                                     text="%g"%(init),
                                     style=self.style['style'])
            self.h.hlist.item_create(scal_num, 2, itemtype=Tix.TEXT,
                                     text=vari,
                                     style=self.style['style'])

        self.e3.insert(END, label)
        self.stbar.idle()


    def replaceHlist(self, item, label, init, vari):
        """
        Update the 'item' into the Hlist.
        """
        self.stbar.busy()
        t = PageText()

        self.dicolabel[label] = item

        if vari == t.NO_VARIANCE: vari = "--"

        # If the scalar is a variance, it is displayed with a specific color.
        #
        if vari != "--":
            self.h.hlist.item_configure(item, 0, itemtype=Tix.TEXT, text=label,
                                        style=self.style['styleV'+'b'])
            self.h.hlist.item_configure(item, 1, itemtype=Tix.TEXT,
                                        text="%g"%(init),
                                        style=self.style['styleV'])
            self.h.hlist.item_configure(item, 2, itemtype=Tix.TEXT,
                                        text=vari,
                                        style=self.style['styleV'])
        else:
            self.h.hlist.item_configure(item, 0, itemtype=Tix.TEXT, text=label,
                                        style=self.style['style'+'b'])
            self.h.hlist.item_configure(item, 1, itemtype=Tix.TEXT,
                                        text="%g"%(init),
                                        style=self.style['style'])
            self.h.hlist.item_configure(item, 2, itemtype=Tix.TEXT,
                                        text=vari,
                                        style=self.style['style'])
        self.stbar.idle()


    def eraseEntries(self, event=None):
        """
        Delete all caracters in the entries.
        """
        t = PageText()
        self.e1.config(state=NORMAL)
        self.e1.delete(0, END)
        self.e2.delete(0, END)
        self.vari.set(t.NO_VARIANCE)
        self.e4.delete(0, END)
        self.e5.delete(0, END)


    def checkInitMinMax(self, name, init, mini, maxi):
        """
        Verify the coherence between init, mini and maxi
        """
        OK = 1

        if mini > maxi:
            t = PageText()
            Dialog.ShowInfo(self.master, title=t.INFO, text=t.MSG_CLIPPING+name)

        elif init < mini or init > maxi:
            t = PageText()
            Dialog.ShowInfo(self.master, title=t.WARNING, text=t.MSG_INIT+name)
            OK = 0

        return OK



    def createHlist(self,event=None):
        """
        Upload contents of the definition widget
        when the "Create" button is pushed.
        """
        self.stbar.busy()
        t = PageText()

        # Get back data from entries
        #
        label, nameCoeff = self.getLabel()
        vari = self.getVari()
        init = self.getInit()
        if init != None: mini = self.getMini()	
        if init != None and mini != None: maxi = self.getMaxi()	

        # Verify if everything is OK
        #
        if not self.mdl.mverifVariance(vari) :

            if label not in self.e3.slistbox.listbox.get(0,END) and \
                   label != MULTISEL and init != None and \
                   mini != None and maxi != None:

                if self.checkInitMinMax(label, init, mini, maxi):

                # Update the Hlist and the XML doc with the new data
                #
                    self.insertHlist(label, init, vari)
                    self.mdl.mSetScalar(label, nameCoeff, init, vari, mini, maxi)
        else:
            self.stbar.set(t.MSG_VARIANCE)

        self.eraseEntries()
        self.currentEntry = None
        self.selectHlist()
        self.stbar.idle()


    def setEditedValueHlist(self, node, entry, old_label, old_init, 
                            old_vari,  old_mini, old_maxi):
        """
        Checking consistency of values and interpreting
        complexe entry for reference if necessary.
        """
        t = PageText()

        # Get back data from entries
        #
        new_label, diffCoeff = self.getLabel()
        new_vari = self.getVari()
        new_init = self.getInit()
        if new_init != None: new_mini = self.getMini()	
        if new_init != None and new_mini != None: new_maxi = self.getMaxi()

        # Verify if everything is OK
        #
        if not self.mdl.mverifVariance(new_vari) :

            if (new_label == old_label or new_label not in self.e3.slistbox.listbox.get(0,END) ) and \
               new_vari != old_label and new_init != None and \
               new_mini != None and new_maxi != None:

                if new_init == MULTISEL: new_init = old_init
                if new_mini == MULTISEL: new_mini = old_mini
                if new_maxi == MULTISEL: new_maxi = old_maxi
                if new_label == MULTISEL: new_label = old_label
                if new_vari == MULTISEL: new_vari = old_vari

                if self.checkInitMinMax(old_label, new_init, new_mini, new_maxi): 

                # Update the Hlist and the XML doc with the new data
                #
                    del self.dicolabel[old_label]
                    self.replaceHlist(entry, new_label, new_init, new_vari)
                    self.mdl.mReplaceScalar(node, new_init, new_vari, new_mini, new_maxi, diffCoeff)

                # What to do if the label has changed?
                #
                    if new_label != MULTISEL and new_label != old_label:

                    # Input the new label of the scalar in 'self.node_user_sca'
                    #
                        self.mdl.msetLabelScalar(node, new_label)

                    # If the scalar with the new label has a variance
                    #
                        label_dico = self.mdl.msetNewLabelintoVariance(old_label, new_label)
                        if label_dico:
                            item = self.dicolabel[label_dico]
                            self.h.hlist.item_configure(item, 2, itemtype=Tix.TEXT,
                                                    text=new_label,
                                                    style=self.style['styleV'])
                    # Update the listbox
                    #
                        list = self.e3.slistbox.listbox.get(0,END)
                        for index in range(len(list)):
                            if list[index] == old_label:
                                self.e3.slistbox.listbox.delete(index)
                                self.e3.insert(index, new_label)

                    # Input the new label of the scalar in 'self.node_bc'
                    #
                        self.mdl.mputNewLabelintoBoundCondScalar(old_label, new_label)

        else:
            self.stbar.set(t.MSG_VARIANCE)

        self.stbar.idle()


    def editHlist(self, event=None):
        """
        Modify previous selected entries. A new node is created with
        the new specifications and the previous ChildNodes are cloned
        in order to taking into account the user's boundary conditions
        if they exist.
        """
        if not self.currentEntry: return

        self.stbar.busy()

        label, init, vari, mini, maxi = self.select.getItems()

        # Search of the nodes to modify
        #
        for i in range(len(self.currentEntry)):
            entry = self.currentEntry[i]
            list = self.mdl.getUserScalarsNodeList()
            for node in list:
                # Modify the node's properties one by one
                #
                #labl, init, vari = self.mdl.mgetLabInitVariScalar(node)
                #if node['label'] == label[i]:
                if self.mdl.mgetLabelScalar(node) == label[i]:
                    self.setEditedValueHlist(node, entry,
                                             label[i], init[i],
                                             vari[i], mini[i], maxi[i])

        self.selectHlist()
        self.stbar.idle()


    def cancelScalar(self, label):
        """
        Just delete the current selected entries from the Hlist and
        of course from the XML file.
        """
        # If the scalar has a variance, it will be destroyed too
        #
        lab_vari = self.mdl.mputDeleteIntoScalarVariance(label)
        if lab_vari: self.cancelScalar(lab_vari)

        # Normaly there is only one node in nodeList and in nodeListBC
        #
        self.mdl.mputDeleteIntoScalar(label)

        self.mdl.mDeleteBoundaryScalar(label)

        # Delete the scalar from the listbox
        #
        list = self.e3.slistbox.listbox.get(0,END)
        for index in range(len(list)):
            if list[index] == label:
                self.e3.slistbox.listbox.delete(index)

        # Delete boundary region from the Hlist
        #
        self.h.hlist.delete_entry(self.dicolabel[label])

        self.entriesNumber = self.entriesNumber + 1
        del self.dicolabel[label]
        del self.mdl.dicoCoeff[label]


    def cancelHlist(self, event=None):
        """
        Just delete the current selected entries from the Hlist and
        of course from the XML file.
        """
        if not self.currentEntry: return

        self.stbar.busy()

        for entry in self.currentEntry:
            try:
                label, init, vari = self.select.scalarInfo(entry)
                self.cancelScalar(label)
            except :pass

        self.mdl.mcancelNode()

        self.eraseEntries()
        self.currentEntry = None
        self.selectHlist()
        self.stbar.idle()


    def selectHlist(self, entry=None):
        """
        Browsecmd:
        Every single Clik on the Button1 of the mouse send TWO signal to the GUI
        the first one when man push the button, and the second one when the
        button gets back.

        Command:
        Every double-Click and Return send only ONE signal to the GUI.
        """
        self.selectedEntry = self.h.hlist.info_selection()

        if not self.selectedEntry:
            self.l1.config(state=NORMAL)
            self.l3.config(state=NORMAL)
            self.e1.config(state=NORMAL)
            self.e3.config(state=NORMAL)

            self.e4.config(state=NORMAL)
            self.e5.config(state=NORMAL)
            self.l4.config(state=NORMAL)
            self.l5.config(state=NORMAL)

        elif self.currentEntry != self.selectedEntry:

            self.currentEntry = self.selectedEntry
            self.select.setItems(self.currentEntry)

            label, init, vari, mini, maxi = self.select.widgetText()

            self.e1.delete(0,END)
            self.e1.insert(0,label)
            self.e1.icursor(END)

            self.e2.delete(0,END)
            self.e2.insert(0,init)
            self.e2.icursor(END)

            self.vari.set(vari)

            self.e4.delete(0,END)
            self.e4.insert(0,mini)
            self.e4.icursor(END)

            self.e5.delete(0,END)
            self.e5.insert(0,maxi)
            self.e5.icursor(END)

            if len(self.currentEntry) > 1:
                self.l1.config(state=DISABLED)
                self.l3.config(state=DISABLED)
                self.e1.config(state=DISABLED)
                self.e3.config(state=DISABLED)
            else:
                self.l1.config(state=NORMAL)
                self.l3.config(state=NORMAL)
                self.e1.config(state=NORMAL)
                self.e3.config(state=NORMAL)
                self.label.set(label)


    def reloadHlist(self):
        """
        Destroy the contents of the Hlist, and reload the scalar data
        from the XMLdoc.
        """
        t = PageText()
        self.entriesNumber = 0
        self.dicolabel = {}

        self.e3.slistbox.listbox.delete(0,END)
        self.e3.insert(0, t.NO_VARIANCE)

        self.h.hlist.delete_all()

        list = self.mdl.getUserScalarsNodeList()
        for scalar in list:
            label, init, vari = self.mdl.mgetLabInitVariScalar(scalar)
            if vari in ("", "no variance", "no_variance"):
                vari = t.NO_VARIANCE
            self.insertHlist(label, init, vari)


    def selectHlistAll(self):
        """
        Fonction for the Popup Menu.
        Select everything in the Hlist.
        """
        self.reloadHlist()
        try:
            first = 'item' + repr(1)
            last  = 'item' + repr(self.entriesNumber)
            self.h.hlist.selection_set(first, last)
            self.currentEntry = None
            self.selectHlist()
        except:
            pass


    def cancelSelection(self):
        """
        Fonction for the Popup Menu.
        Blank the selection.
        """
        self.h.hlist.selection_clear()
        self.eraseEntries()
        self.currentEntry = None
        self.selectHlist()


    def _createWidgets(self):
        """
        Page layout
        """

        t = PageText()

        self.lf1 = Tix.LabelFrame(self.myPage, bd=2, label=t.TITLE, relief=FLAT)
        self.lf1.label.config(font=fT)
        self.lf1.pack(side=TOP, fill=X, padx=10, pady=10)

        # Put a simple hierarchy into the Hlist (two levels).
        #
        self.h = Tix.ScrolledHList(self.lf1.frame, options=
                                   'hlist.columns 4 hlist.header 1' )
        self.h.config(scrollbar="auto +x +y")
        self.h.hlist.config(selectmode='extended',
                            browsecmd=self.selectHlist,
                            bg=wm['hlistbackground'])
        self.h.hsb.config(width=10, bd=1)
        self.h.vsb.config(width=10, bd=1)
        self.h.pack(padx=10, pady=10, side=TOP)

        self.balloon.bind_widget(self.h.hlist, statusmsg=t.MSG_HLIST)

        # Create the headers
        #
        self._make_style()

        self.h.hlist.header_create(0, itemtype=Tix.TEXT, text=t.NAME,
                                   style=self.style['header'])
        self.h.hlist.header_create(1, itemtype=Tix.TEXT, text=t.INITIAL,
                                   style=self.style['header'])
        self.h.hlist.header_create(2, itemtype=Tix.TEXT, text=t.VARIANCE,
                                   style=self.style['header'])

        # Notice that we use 4 columns in the Hlist widget. This way when the user
        # expands the windows wide, the right side of the header doesn't look
        # chopped off. The following line ensures that the 4 column header is
        # not shown unless the Hlist window is wider than its contents.
        #
        self.h.hlist.column_width(col=3, width=0)

        # Let configure the appearance of the Hlist subwidget 
        #
        self.h.hlist.config(separator='.', width=39, height=11, drawbranch=0, indent=10)

        # width of the columns
        #
        self.h.hlist.column_width(col=0, chars=13)
        self.h.hlist.column_width(col=1, chars=13)
        self.h.hlist.column_width(col=2, chars=13)

        # Create the mouse selection instance
        #
        self.select = MultiSelect(self.case, self.h.hlist, self.mdl.node_user_sca)

        # Popup Menu of Tree
        #
        pm = Tix.PopupMenu(self.h.hlist, title=t.POPUP, state=NORMAL)
        pm.bind_widget(self.h.hlist)
        pm.menu.add_separator()
        pm.menu.add_command(label=t.SELECT_ALL, command=self.selectHlistAll)
        pm.menu.add_command(label=t.UNSELECT, command=self.cancelSelection)
        pm.menu.m1 = Tix.Menu(pm.menu)
##        pm.menu.add_separator()
##        pm.menu.m2 = Tix.Menu(pm.menu)
##        pm.menu.add_cascade(label=t.OPTION, menu=pm.menu.m2)
##        pm.menu.m2.add_command(label=t.BGCOLOR)

        # Separator
        #
        s = Tix.Frame(self.lf1.frame, height=2, bd=2, relief=SUNKEN)
        s.pack(side=TOP, fill=X)

        f1 = Tix.Frame(self.lf1.frame, relief=FLAT)
        f1.pack(side=TOP, fill=X)

        self.l1 = Tix.Label(f1, text=t.NAME)
        self.l2 = Tix.Label(f1, text=t.INITIAL)
        self.l3 = Tix.Label(f1, text=t.VARIANCE)
        self.l4 = Tix.Label(f1, text=t.MIN)
        self.l5 = Tix.Label(f1, text=t.MAX)

        self.l1.grid(row=0, column=0, padx=3, pady=2, sticky=E)
        self.l2.grid(row=1, column=0, padx=3, pady=2, sticky=E)
        self.l3.grid(row=2, column=0, padx=3, pady=2, sticky=E)
        self.l4.grid(row=3, column=0, padx=3, pady=2, sticky=E)
        self.l5.grid(row=4, column=0, padx=3, pady=2, sticky=E)
        self.balloon.bind_widget(self.l4, balloonmsg=t.KEYWORD+'SCAMIN')
        self.balloon.bind_widget(self.l5, balloonmsg=t.KEYWORD+'SCAMAX')

        self.e3 = Tix.ComboBox(f1, editable=0, bd=2, listwidth=50, 
                               selectmode="", variable=self.vari)
        self.e3.entry.config(width=15, bg=wm['textbackground'])
        self.e3.slistbox.config(height=100, scrollbar="auto")
        self.e3.slistbox.vsb.config(width=10, bd=1)
        self.e3.slistbox.hsb.config(width=10, bd=1)
##      self.e3.event_add("<<Event>>", "<Leave>", "<FocusOut>")
##      self.e3.bind("<<Event>>", self.getVari)

        self.e1 = Tix.Entry(f1, bd=2, width=15, textvariable=self.label)
        self.e2 = Tix.Entry(f1, bd=2, width=15, textvariable=self.init)
        self.e4 = Tix.Entry(f1, bd=2, width=10, textvariable=self.mini)
        self.e5 = Tix.Entry(f1, bd=2, width=10, textvariable=self.maxi)

        self.e1.grid(row=0, column=1, padx=5, pady=2,  sticky=W)
        self.e2.grid(row=1, column=1, padx=5, pady=2,  sticky=W)
        self.e3.grid(row=2, column=1,         pady=2,  sticky=W)
        self.e4.grid(row=3, column=1, padx=5, pady=2,  sticky=W)
        self.e5.grid(row=4, column=1, padx=5, pady=10, sticky=W)
        self.balloon.bind_widget(self.e4, balloonmsg=t.KEYWORD+'SCAMIN')
        self.balloon.bind_widget(self.e5, balloonmsg=t.KEYWORD+'SCAMAX')

        box1 = Tix.ButtonBox(f1, orientation=VERTICAL, relief=FLAT)
        box1.add('create', text=t.CREATE, command=self.createHlist)
        box1.add('modify', text=t.MODIFY, command=self.editHlist)
        box1.add('erase',  text=t.ERASE,  command=self.cancelHlist)
        box1.grid(row=0, column=2, rowspan=4, padx=15, pady=0, sticky=W)

        self.e3.config(bg=wm['textbackground'], command=self.getVari)


    def _initializeWidgets(self):
        """
        Get XML previous value.
        """
        t = PageText()
        self.reloadHlist()
        self.cancelSelection()
        self.vari.set(t.NO_VARIANCE)

        # on rajoute le scalaire thermique dans la liste des variances
        label = XMLmodel(self.case).getThermalScalarLabel()
        if label: self.e3.insert(0, label)


#-------------------------------------------------------------------------------
# Text and messages for this page
#-------------------------------------------------------------------------------


class PageText:
    """
    Storage of all texts and messages for this page.
    """
    def __init__(self):
        
        # 1) Texts
        #
        if Tool.GuiParam.lang == 'fr':
            self.CREATE           = "Créer"
            self.DEFINITION       = "DÉFINITION\nINITIALISATION"
            self.ERASE            = "Effacer"
            self.INITIAL          = "Valeur\ninitiale"
            self.MAX              = "Valeur\nmaximale"
            self.MIN              = "Valeur\nminimale"
            self.MODIFY           = "Modifier"
            self.NAME             = "Nom"
            self.NO_VARIANCE      = "pas de variance"
            self.POPUP            = "Menu popup"
            self.SELECT_ALL       = "Tout sélectionner"
            self.TITLE            = "Définition des scalaires et Initialisation"
            self.UNSELECT         = "Désélectionner"
            self.VARIANCE         = "Variance"
            self.INFO             = "Information"
            self.WARNING          = "Attention"
            self.KEYWORD          = "Mot clé Code_Saturne : "
        else:
            self.CREATE           = "Create"
            self.DEFINITION       = "DEFINITION\nINITIALIZATION"
            self.ERASE            = "Erase"
            self.INITIAL          = "Initial\nvalue"
            self.MAX              = "Maximal\nvalue"
            self.MIN              = "Minimal\nvalue"
            self.MODIFY           = "Modify"
            self.NAME             = "Name"
            self.NO_VARIANCE      = "no variance"
            self.POPUP            = "Menu popup"
            self.SELECT_ALL       = "Select all"
            self.TITLE            = "User Scalar Definition and Initialization"
            self.UNSELECT         = "Unselect"
            self.VARIANCE         = "Variance"
            self.INFO             = "Information"
            self.WARNING          = "Warning"
            self.KEYWORD          = "Code_Saturne key word: "

        # 2) Messages
        #
        if Tool.GuiParam.lang == 'fr':
            self.MSG_HLIST    = "Cliquer le bouton droit pour " \
                                "le menu contextuel."
            self.MSG_CLIPPING = "La valeur minimale est supérieure à la valeur "\
                                "maximale. Il n'y aura donc pas de clipping "\
                                "pour le scalaire :\n\n"
            self.MSG_INIT     = "La valeur initial doit être comprise entre les "\
                                "valeurs minimale et maximale du scalaire :\n\n"
            self.MSG_LABEL    = "Le nom du scalaire est coupé à 8 caractères"
            self.MSG_VARIANCE = "Un scalaire ne peut pas être la variance d'une variance"
        else:
            self.MSG_HLIST    = "Click right button for popup menu."
            self.MSG_CLIPPING = "The minimal value is greater than the maximal "\
                                "value. Therefore there will be no clipping for the "\
                                "scalar named:\n\n"
            self.MSG_INIT     = "The initial value must be set between the "\
                                "minimal and the maximal value of the scalar "\
                                "named:\n\n"
            self.MSG_LABEL    = "Only 8 characters are kept for Scalar name"
            self.MSG_VARIANCE = "Scalar can't be variance of another variance"


#-------------------------------------------------------------------------------
# DefineUsersScalars test case
#-------------------------------------------------------------------------------


class UserScalarTestCase(unittest.TestCase):
    def setUp(self):
        """This method is executed before all "check" methods."""
        from Base.XMLengine import Case, XMLDocument
        from Base.XMLinitialize import XMLinit
        Tool.GuiParam.lang = 'en'
        self.case = Case(None)
        XMLinit(self.case)
        self.doc = XMLDocument()


    def tearDown(self):
        """This method is executed after all "check" methods."""
        del self.case


    def checkDefineUserScalarsModelInstantiation(self):
        """Check whether the DefineUserScalarsModel class could be instantiated."""
        model = None
        model = DefineUserScalarsModel(self.case)

        assert model != None, 'Could not instantiate DefineUserScalarsModel'

    def checkSetNewUserScalar(self):
        """Check whether the DefineUserScalarsModel class could be set new scalar."""
        model = DefineUserScalarsModel(self.case)
        model.setNewUserScalar('toto')
        truc = model.node_user_sca.toString()
        doc = '<additional_scalars>'\
                    '<scalar label="toto" type="user"/>'\
              '</additional_scalars>'
        assert doc == truc, 'Could not set a new scalar'

    def checkGetScalarList(self):
        """Check whether the DefineUserScalarsModel class could be get list."""
        model = DefineUserScalarsModel(self.case)
        model.setNewUserScalar('toto')
        model.setNewUserScalar('titi')
        model.setNewUserScalar('tutu')
        list = model.getScalarList()
        assert list == ['toto', 'titi', 'tutu'], 'Could not get list'

    def checkGetUserScalarList(self):
        """Check whether the DefineUserScalarsModel class could be get user list."""
        model = DefineUserScalarsModel(self.case)
        model.setNewUserScalar('toto')
        model.setNewUserScalar('titi')
        model.setNewUserScalar('tutu')
        list = model.getUserScalarList()
        assert list == ['toto', 'titi', 'tutu'], 'Could not get user scalar list'

    def checkDeleteUserScalar(self):
        """Check whether the DefineUserScalarsModel class could be delete one scalar from user list."""
        model = DefineUserScalarsModel(self.case)
        model.setNewUserScalar('toto')
        model.setNewUserScalar('titi')
        model.setNewUserScalar('tutu')
        model.deleteUserScalar('titi')
        list = model.getUserScalarList()
        assert list == ['toto', 'tutu'], 'Could not delete user scalar list'

    def checkSetScalarInitialValue(self):
        """Check whether the DefineUserScalarsModel class could be set initial value."""
        model = DefineUserScalarsModel(self.case)
        model.setNewUserScalar('toto')
        model.setScalarInitialValue('toto', '1', 0.05)
        truc = model.node_user_sca.toString()
        doc = '<additional_scalars>'\
                '<scalar label="toto" type="user">'\
                    '<initial_value zone="1">0.05</initial_value>'\
                '</scalar>'\
              '</additional_scalars>'
        assert doc == truc, 'Could not set initial value to user scalar'

    def checkGetScalarInitialValue(self):
        """Check whether the DefineUserScalarsModel class could be get initial value."""
        model = DefineUserScalarsModel(self.case)
        model.setNewUserScalar('toto')
        model.setScalarInitialValue('toto', '1', '0.05')
        value = model.getScalarInitialValue('toto','1')
        assert value == 0.05,'Could not get initial value to user scalar'

    def checkSetScalarMinMaxValue(self):
        """Check whether the DefineUserScalarsModel class could be set min and max value."""
        model = DefineUserScalarsModel(self.case)
        model.setNewUserScalar('toto')
        model.setNewUserScalar('titi')
        model.setScalarInitialValue('toto', '1', 0.05)
        model.setScalarMinValue('toto',0.01)
        model.setScalarMaxValue('toto',100.)
        truc = model.node_user_sca.toString()
        doc = '<additional_scalars>'\
                '<scalar label="toto" type="user">'\
                    '<initial_value zone="1">0.05</initial_value>'\
                    '<min_value>0.01</min_value>'\
                    '<max_value>100</max_value>'\
                '</scalar>'\
                '<scalar label="titi" type="user"/>'\
              '</additional_scalars>'
        assert doc == truc,'Could not set min ansd max value to user scalar'

    def checkGetScalarMinMaxValue(self):
        """Check whether the DefineUserScalarsModel class could be get min and max value."""
        model = DefineUserScalarsModel(self.case)
        model.setNewUserScalar('toto')
        model.setNewUserScalar('titi')
        model.setScalarInitialValue('toto', '1', 0.05)
        model.setScalarMinValue('toto',0.01)
        model.setScalarMaxValue('toto',100.)
        truc = model.node_user_sca.toString()
        doc = '<additional_scalars>'\
                '<scalar label="toto" type="user">'\
                    '<initial_value zone="1">0.05</initial_value>'\
                    '<min_value>0.01</min_value>'\
                    '<max_value>100</max_value>'\
                '</scalar>'\
                '<scalar label="titi" type="user"/>'\
              '</additional_scalars>'
        min = model.getScalarMinValue('toto')
        max = model.getScalarMaxValue('toto')
        
        assert min == 0.01,'Could not get min value to user scalar'
        assert max == 100.,'Could not get max value to user scalar'

    def checkSetScalarVariance(self):
        """Check whether the DefineUserScalarsModel class could be set variance."""
        model = DefineUserScalarsModel(self.case)
        model.setNewUserScalar('toto')
        model.setNewUserScalar('titi')
        model.setScalarVariance('toto', 'titi')
        truc = model.node_user_sca.toString()
        doc = '<additional_scalars>'\
                '<scalar label="toto" type="user">'\
                    '<variance>titi</variance>'\
                '</scalar>'\
                '<scalar label="titi" type="user"/>'\
              '</additional_scalars>'
        assert doc == truc,'Could not set variance to user scalar'

    def checkGetScalarVariance(self):
        """Check whether the DefineUserScalarsModel class could be get variance."""
        model = DefineUserScalarsModel(self.case)
        model.setNewUserScalar('toto')
        model.setNewUserScalar('titi')
        model.setScalarVariance('toto', 'titi')
        vari = model.getScalarVariance('toto')
        assert vari == 'titi','Could not get variance to user scalar'

    def checkSetandGetScalarDiffusivityLabel(self):
        """Check whether the DefineUserScalarsModel class could be get label of diffusivity."""
        model = DefineUserScalarsModel(self.case)
        model.setNewUserScalar('toto')
        model.setNewUserScalar('titi')
        model.setScalarDiffusivity('toto', 'diffu_toto', 0.005)
        label = model.getScalarDiffusivityLabel('toto')
        assert label == 'diffu_toto',"Could not set label of user scalar's property"

    def checkSetandGetScalarDiffusivityInitialValue(self):
        """Check whether the DefineUserScalarsModel class could be set diffusivity'initial value."""
        model = DefineUserScalarsModel(self.case)
        model.setNewUserScalar('toto')
        model.setNewUserScalar('titi')
        model.setScalarDiffusivity('toto', 'diffu_toto', 0.005)
        model.setScalarDiffusivityInitialValue('toto', 0.045)
        truc = model.node_user_sca.toString()
        doc ='<additional_scalars>'\
                '<scalar label="toto" type="user">'\
                    '<property label="diffu_toto">'\
                        '<initial_value>0.045</initial_value>'\
                    '</property>'\
                '</scalar>'\
                '<scalar label="titi" type="user"/>'\
             '</additional_scalars>'
        assert doc == truc,"Could not set initial value of user scalar's property"
        
        val = model.getScalarDiffusivityInitialValue('toto')
        assert val == 0.045,"Could not get initial value of user scalar's property"


    def checkSetandGetScalarDiffusivityChoice(self):
        """Check whether the DefineUserScalarsModel class could be set diffusivity's choice."""
        model = DefineUserScalarsModel(self.case)
        model.setNewUserScalar('toto')
        model.setNewUserScalar('titi')
        model.setScalarDiffusivity('toto', 'diffu_toto', 0.005)
        model.setScalarDiffusivityChoice('toto', 'constant')
        truc = model.node_user_sca.toString()
        doc = '<additional_scalars>'\
                '<scalar label="toto" type="user">'\
                    '<property choice="constant" label="diffu_toto">'\
                        '<initial_value>0.005</initial_value>'\
                    '</property>'\
                '</scalar>'\
                '<scalar label="titi" type="user"/>'\
              '</additional_scalars>'
        assert doc==truc,"Could not set choice of user scalar's property"
              
        ch = model.getScalarDiffusivityChoice('toto')
        assert ch == "constant","Could not get choice of user scalar's property"


def suite():
    """unittest function"""
    testSuite = unittest.makeSuite(UserScalarTestCase, "check")
    return testSuite


def runTest():
    """unittest function"""
    print "XMLengineTestCase to be completed..."
    runner = unittest.TextTestRunner()
    runner.run(suite())


#-------------------------------------------------------------------------------
# End DefineUsersScalars
#-------------------------------------------------------------------------------


syntax highlighted by Code2HTML, v. 0.9.1