VariablePanel.py
author laurent
Thu, 21 Apr 2011 15:15:57 +0200
changeset 536 288324dddfb8
parent 520 7ca6c3e076f7
child 544 ad4dd01c3c35
permissions -rw-r--r--
Adding '0' and '1' as possible value to force boolean variables
# -*- coding: utf-8 -*-

#This file is part of PLCOpenEditor, a library implementing an IEC 61131-3 editor
#based on the plcopen standard. 
#
#Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD
#
#See COPYING file for copyrights details.
#
#This library 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.1 of the License, or (at your option) any later version.
#
#This library 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 library; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import os
import wx, wx.grid

from types import TupleType

from plcopen.structures import LOCATIONDATATYPES, TestIdentifier, IEC_KEYWORDS
from PLCControler import LOCATION_PLUGIN, LOCATION_MODULE, LOCATION_GROUP, LOCATION_VAR_INPUT, LOCATION_VAR_OUTPUT, LOCATION_VAR_MEMORY
from dialogs import ArrayTypeDialog

CWD = os.path.split(os.path.realpath(__file__))[0]

# Compatibility function for wx versions < 2.6
def AppendMenu(parent, help, id, kind, text):
    if wx.VERSION >= (2, 6, 0):
        parent.Append(help=help, id=id, kind=kind, text=text)
    else:
        parent.Append(helpString=help, id=id, kind=kind, item=text)

[TITLE, TOOLBAR, FILEMENU, EDITMENU, DISPLAYMENU, TYPESTREE, 
 INSTANCESTREE, LIBRARYTREE, SCALING
] = range(9)

#-------------------------------------------------------------------------------
#                            Variables Editor Panel
#-------------------------------------------------------------------------------

def GetVariableTableColnames(location):
    _ = lambda x : x
    if location:
    	return ["#", _("Name"), _("Class"), _("Type"), _("Location"), _("Initial Value"), _("Option"), _("Documentation")]
    return ["#", _("Name"), _("Class"), _("Type"), _("Initial Value"), _("Option"), _("Documentation")]

def GetOptions(constant=True, retain=True, non_retain=True):
    _ = lambda x : x
    options = [""]
    if constant:
        options.append(_("Constant"))
    if retain:
        options.append(_("Retain"))
    if non_retain:
        options.append(_("Non-Retain"))
    return options
OPTIONS_DICT = dict([(_(option), option) for option in GetOptions()])

def GetFilterChoiceTransfer():
    _ = lambda x : x
    return {_("All"): _("All"), _("Interface"): _("Interface"), 
            _("   Input"): _("Input"), _("   Output"): _("Output"), _("   InOut"): _("InOut"), 
            _("   External"): _("External"), _("Variables"): _("Variables"), _("   Local"): _("Local"),
            _("   Temp"): _("Temp"), _("Global"): _("Global")}#, _("Access") : _("Access")}
VARIABLE_CHOICES_DICT = dict([(_(_class), _class) for _class in GetFilterChoiceTransfer().iterkeys()])
VARIABLE_CLASSES_DICT = dict([(_(_class), _class) for _class in GetFilterChoiceTransfer().itervalues()])

CheckOptionForClass = {"Local": lambda x: x,
                       "Temp": lambda x: "",
                       "Input": lambda x: {"Retain": "Retain", "Non-Retain": "Non-Retain"}.get(x, ""),
                       "InOut": lambda x: "",
                       "Output": lambda x: {"Retain": "Retain", "Non-Retain": "Non-Retain"}.get(x, ""),
                       "Global": lambda x: {"Constant": "Constant", "Retain": "Retain"}.get(x, ""),
                       "External": lambda x: {"Constant": "Constant"}.get(x, "")
                      }

class VariableTable(wx.grid.PyGridTableBase):
    
    """
    A custom wx.grid.Grid Table using user supplied data
    """
    def __init__(self, parent, data, colnames):
        # The base class must be initialized *first*
        wx.grid.PyGridTableBase.__init__(self)
        self.data = data
        self.old_value = None
        self.colnames = colnames
        self.Errors = {}
        self.Parent = parent
        # XXX
        # we need to store the row length and collength to
        # see if the table has changed size
        self._rows = self.GetNumberRows()
        self._cols = self.GetNumberCols()
    
    def GetNumberCols(self):
        return len(self.colnames)
        
    def GetNumberRows(self):
        return len(self.data)

    def GetColLabelValue(self, col, translate=True):
        if col < len(self.colnames):
            if translate:
                return _(self.colnames[col])
            return self.colnames[col]

    def GetRowLabelValues(self, row, translate=True):
        return row

    def GetValue(self, row, col):
        if row < self.GetNumberRows():
            if col == 0:
                return self.data[row]["Number"]
            colname = self.GetColLabelValue(col, False)
            value = self.data[row].get(colname, "")
            if colname == "Type" and isinstance(value, TupleType):
                if value[0] == "array":
                    return "ARRAY [%s] OF %s" % (",".join(map(lambda x : "..".join(x), value[2])), value[1])
            value = str(value)
            if colname in ["Class", "Option"]:
                return _(value)
            return value
    
    def SetValue(self, row, col, value):
        if col < len(self.colnames):
            colname = self.GetColLabelValue(col, False)
            if colname == "Name":
                self.old_value = self.data[row][colname]
            elif colname == "Class":
                value = VARIABLE_CLASSES_DICT[value]
                self.SetValueByName(row, "Option", CheckOptionForClass[value](self.GetValueByName(row, "Option")))
                if value == "External":
                    self.SetValueByName(row, "Initial Value", "")
            elif colname == "Option":
                value = OPTIONS_DICT[value]
            self.data[row][colname] = value
    
    def GetValueByName(self, row, colname):
        if row < self.GetNumberRows():
            return self.data[row].get(colname)

    def SetValueByName(self, row, colname, value):
        if row < self.GetNumberRows():
            self.data[row][colname] = value

    def GetOldValue(self):
        return self.old_value
    
    def ResetView(self, grid):
        """
        (wx.grid.Grid) -> Reset the grid view.   Call this to
        update the grid if rows and columns have been added or deleted
        """
        grid.BeginBatch()
        for current, new, delmsg, addmsg in [
            (self._rows, self.GetNumberRows(), wx.grid.GRIDTABLE_NOTIFY_ROWS_DELETED, wx.grid.GRIDTABLE_NOTIFY_ROWS_APPENDED),
            (self._cols, self.GetNumberCols(), wx.grid.GRIDTABLE_NOTIFY_COLS_DELETED, wx.grid.GRIDTABLE_NOTIFY_COLS_APPENDED),
        ]:
            if new < current:
                msg = wx.grid.GridTableMessage(self,delmsg,new,current-new)
                grid.ProcessTableMessage(msg)
            elif new > current:
                msg = wx.grid.GridTableMessage(self,addmsg,new-current)
                grid.ProcessTableMessage(msg)
                self.UpdateValues(grid)
        grid.EndBatch()

        self._rows = self.GetNumberRows()
        self._cols = self.GetNumberCols()
        # update the column rendering scheme
        self._updateColAttrs(grid)

        # update the scrollbars and the displayed part of the grid
        grid.AdjustScrollbars()
        grid.ForceRefresh()

    def UpdateValues(self, grid):
        """Update all displayed values"""
        # This sends an event to the grid table to update all of the values
        msg = wx.grid.GridTableMessage(self, wx.grid.GRIDTABLE_REQUEST_VIEW_GET_VALUES)
        grid.ProcessTableMessage(msg)

    def _updateColAttrs(self, grid):
        """
        wx.grid.Grid -> update the column attributes to add the
        appropriate renderer given the column name.

        Otherwise default to the default renderer.
        """
        for row in range(self.GetNumberRows()):
            var_class = self.GetValueByName(row, "Class")
            for col in range(self.GetNumberCols()):
                editor = None
                renderer = None
                colname = self.GetColLabelValue(col, False)
                if colname == "Option":
                    options = GetOptions(constant = var_class in ["Local", "External", "Global"],
                                         retain = self.Parent.ElementType != "function" and var_class in ["Local", "Input", "Output", "Global"],
                                         non_retain = self.Parent.ElementType != "function" and var_class in ["Local", "Input", "Output"])
                    if len(options) > 1:
                        editor = wx.grid.GridCellChoiceEditor()
                        editor.SetParameters(",".join(map(_, options)))
                    else:
                        grid.SetReadOnly(row, col, True)
                elif col != 0 and self.GetValueByName(row, "Edit"):
                    grid.SetReadOnly(row, col, False)
                    if colname == "Name":
                        if self.Parent.PouIsUsed and var_class in ["Input", "Output", "InOut"]:
                            grid.SetReadOnly(row, col, True)
                        else:
                            editor = wx.grid.GridCellTextEditor()
                            renderer = wx.grid.GridCellStringRenderer()
                    elif colname == "Initial Value":
                        if var_class != "External":
                            editor = wx.grid.GridCellTextEditor()
                            renderer = wx.grid.GridCellStringRenderer()
                        else:
                            grid.SetReadOnly(row, col, True)
                    elif colname == "Location":
                        if var_class in ["Local", "Global"]:
                            editor = LocationCellEditor(self, self.Parent.Controler)
                            renderer = wx.grid.GridCellStringRenderer()
                        else:
                            grid.SetReadOnly(row, col, True)
                    elif colname == "Class":
                        if len(self.Parent.ClassList) == 1 or self.Parent.PouIsUsed and var_class in ["Input", "Output", "InOut"]:
                            grid.SetReadOnly(row, col, True)
                        else:
                            editor = wx.grid.GridCellChoiceEditor()
                            excluded = []
                            if self.Parent.PouIsUsed:
                                excluded.extend(["Input","Output","InOut"])
                            if self.Parent.IsFunctionBlockType(self.data[row]["Type"]):
                                excluded.extend(["Local","Temp"])
                            editor.SetParameters(",".join([_(choice) for choice in self.Parent.ClassList if choice not in excluded]))
                elif colname != "Documentation":
                    grid.SetReadOnly(row, col, True)
                
                grid.SetCellEditor(row, col, editor)
                grid.SetCellRenderer(row, col, renderer)
                
                if row in self.Errors and self.Errors[row][0] == colname.lower():
                    grid.SetCellBackgroundColour(row, col, wx.Colour(255, 255, 0))
                    grid.SetCellTextColour(row, col, wx.RED)
                    grid.MakeCellVisible(row, col)
                else:
                    grid.SetCellTextColour(row, col, wx.BLACK)
                    grid.SetCellBackgroundColour(row, col, wx.WHITE)
            if wx.Platform == '__WXMSW__':
                grid.SetRowMinimalHeight(row, 20)
            else:
                grid.SetRowMinimalHeight(row, 28)
            grid.AutoSizeRow(row, False)
    
    def SetData(self, data):
        self.data = data
    
    def GetData(self):
        return self.data
    
    def GetCurrentIndex(self):
        return self.CurrentIndex
    
    def SetCurrentIndex(self, index):
        self.CurrentIndex = index
    
    def AppendRow(self, row_content):
        self.data.append(row_content)

    def RemoveRow(self, row_index):
        self.data.pop(row_index)

    def GetRow(self, row_index):
        return self.data[row_index]

    def Empty(self):
        self.data = []
        self.editors = []

    def AddError(self, infos):
        self.Errors[infos[0]] = infos[1:]

    def ClearErrors(self):
        self.Errors = {}

class VariableDropTarget(wx.TextDropTarget):
    '''
    This allows dragging a variable location from somewhere to the Location
    column of a variable row.
    
    The drag source should be a TextDataObject containing a Python tuple like:
        ('%ID0.0.0', 'location', 'REAL')
    
    c_ext/CFileEditor.py has an example of this (you can drag a C extension
    variable to the Location column of the variable panel).
    '''
    def __init__(self, parent):
        wx.TextDropTarget.__init__(self)
        self.ParentWindow = parent
    
    def OnDropText(self, x, y, data):
        x, y = self.ParentWindow.VariablesGrid.CalcUnscrolledPosition(x, y)
        col = self.ParentWindow.VariablesGrid.XToCol(x)
        row = self.ParentWindow.VariablesGrid.YToRow(y - self.ParentWindow.VariablesGrid.GetColLabelSize())
        if col != wx.NOT_FOUND and row != wx.NOT_FOUND:
            if self.ParentWindow.Table.GetColLabelValue(col, False) != "Location":
                return
            message = None
            if not self.ParentWindow.Table.GetValueByName(row, "Edit"):
                message = _("Can't give a location to a function block instance")
            elif self.ParentWindow.Table.GetValueByName(row, "Class") not in ["Local", "Global"]:
                message = _("Can only give a location to local or global variables")
            else:
                try:
                    values = eval(data)    
                except:
                    message = _("Invalid value \"%s\" for location")%data
                    values = None
                if not isinstance(values, TupleType):
                    message = _("Invalid value \"%s\" for location")%data
                    values = None
                if values is not None and values[1] == "location":
                    location = values[0]
                    variable_type = self.ParentWindow.Table.GetValueByName(row, "Type")
                    base_type = self.ParentWindow.Controler.GetBaseType(variable_type)
                    message = None
                    if location.startswith("%"):
                        if base_type != values[2]:
                            message = _("Incompatible data types between \"%s\" and \"%s\"")%(values[2], variable_type)
                        else:
                            self.ParentWindow.Table.SetValue(row, col, location)
                            self.ParentWindow.Table.ResetView(self.ParentWindow.VariablesGrid)
                            self.ParentWindow.SaveValues()
                    else:
                        if location[0].isdigit() and base_type != "BOOL":
                            message = _("Incompatible size of data between \"%s\" and \"BOOL\"")%location
                        elif location[0] not in LOCATIONDATATYPES:
                            message = _("Unrecognized data size \"%s\"")%location[0]
                        elif base_type not in LOCATIONDATATYPES[location[0]]:
                            message = _("Incompatible size of data between \"%s\" and \"%s\"")%(location, variable_type)
                        else:
                            dialog = wx.SingleChoiceDialog(self.ParentWindow, _("Select a variable class:"), _("Variable class"), ["Input", "Output", "Memory"], wx.OK|wx.CANCEL)
                            if dialog.ShowModal() == wx.ID_OK:
                                selected = dialog.GetSelection()
                                if selected == 0:
                                    location = "%I" + location
                                elif selected == 1:
                                    location = "%Q" + location
                                else:
                                    location = "%M" + location
                                self.ParentWindow.Table.SetValue(row, col, location)
                                self.ParentWindow.Table.ResetView(self.ParentWindow.VariablesGrid)
                                self.ParentWindow.SaveValues()
                            dialog.Destroy()
            if message is not None:
                wx.CallAfter(self.ShowMessage, message)
            
    def ShowMessage(self, message):
        message = wx.MessageDialog(self.ParentWindow, message, _("Error"), wx.OK|wx.ICON_ERROR)
        message.ShowModal()
        message.Destroy()

[ID_VARIABLEEDITORPANEL, ID_VARIABLEEDITORPANELVARIABLESGRID, 
 ID_VARIABLEEDITORCONTROLPANEL, ID_VARIABLEEDITORPANELRETURNTYPE, 
 ID_VARIABLEEDITORPANELCLASSFILTER, ID_VARIABLEEDITORPANELADDBUTTON, 
 ID_VARIABLEEDITORPANELDELETEBUTTON, ID_VARIABLEEDITORPANELUPBUTTON, 
 ID_VARIABLEEDITORPANELDOWNBUTTON, ID_VARIABLEEDITORPANELSTATICTEXT1, 
 ID_VARIABLEEDITORPANELSTATICTEXT2, ID_VARIABLEEDITORPANELSTATICTEXT3,
] = [wx.NewId() for _init_ctrls in range(12)]

class VariablePanel(wx.Panel):
    
    if wx.VERSION < (2, 6, 0):
        def Bind(self, event, function, id = None):
            if id is not None:
                event(self, id, function)
            else:
                event(self, function)
    
    def _init_coll_MainSizer_Items(self, parent):
        parent.AddWindow(self.VariablesGrid, 0, border=0, flag=wx.GROW)
        parent.AddWindow(self.ControlPanel, 0, border=5, flag=wx.GROW|wx.ALL)
    
    def _init_coll_MainSizer_Growables(self, parent):
        parent.AddGrowableCol(0)
        parent.AddGrowableRow(0)
    
    def _init_coll_ControlPanelSizer_Items(self, parent):
        parent.AddSizer(self.ChoicePanelSizer, 0, border=0, flag=wx.GROW)
        parent.AddSizer(self.ButtonPanelSizer, 0, border=0, flag=wx.ALIGN_CENTER)

    def _init_coll_ControlPanelSizer_Growables(self, parent):
        parent.AddGrowableCol(0)
        parent.AddGrowableRow(0)
        parent.AddGrowableRow(1)

    def _init_coll_ChoicePanelSizer_Items(self, parent):
        parent.AddWindow(self.staticText1, 0, border=0, flag=wx.ALIGN_BOTTOM)
        parent.AddWindow(self.ReturnType, 0, border=0, flag=0)
        parent.AddWindow(self.staticText2, 0, border=0, flag=wx.ALIGN_BOTTOM)
        parent.AddWindow(self.ClassFilter, 0, border=0, flag=0)

    def _init_coll_ButtonPanelSizer_Items(self, parent):
        parent.AddWindow(self.UpButton, 0, border=0, flag=0)
        parent.AddWindow(self.AddButton, 0, border=0, flag=0)
        parent.AddWindow(self.DownButton, 0, border=0, flag=0)
        parent.AddWindow(self.DeleteButton, 0, border=0, flag=0)
        
    def _init_coll_ButtonPanelSizer_Growables(self, parent):
        parent.AddGrowableCol(0)
        parent.AddGrowableCol(1)
        parent.AddGrowableCol(2)
        parent.AddGrowableCol(3)
        parent.AddGrowableRow(0)

    def _init_sizers(self):
        self.MainSizer = wx.FlexGridSizer(cols=2, hgap=10, rows=1, vgap=0)
        self.ControlPanelSizer = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=5)
        self.ChoicePanelSizer = wx.GridSizer(cols=1, hgap=5, rows=4, vgap=5)
        self.ButtonPanelSizer = wx.FlexGridSizer(cols=2, hgap=5, rows=2, vgap=5)
        
        self._init_coll_MainSizer_Items(self.MainSizer)
        self._init_coll_MainSizer_Growables(self.MainSizer)
        self._init_coll_ControlPanelSizer_Items(self.ControlPanelSizer)
        self._init_coll_ControlPanelSizer_Growables(self.ControlPanelSizer)
        self._init_coll_ChoicePanelSizer_Items(self.ChoicePanelSizer)
        self._init_coll_ButtonPanelSizer_Items(self.ButtonPanelSizer)
        self._init_coll_ButtonPanelSizer_Growables(self.ButtonPanelSizer)
        
        self.SetSizer(self.MainSizer)
        self.ControlPanel.SetSizer(self.ControlPanelSizer)

    def _init_ctrls(self, prnt):
        wx.Panel.__init__(self, id=ID_VARIABLEEDITORPANEL,
              name='VariableEditorPanel', parent=prnt, pos=wx.Point(0, 0),
              size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL)

        self.VariablesGrid = wx.grid.Grid(id=ID_VARIABLEEDITORPANELVARIABLESGRID,
              name='VariablesGrid', parent=self, pos=wx.Point(0, 0), 
              size=wx.Size(0, 0), style=wx.VSCROLL)
        self.VariablesGrid.SetFont(wx.Font(12, 77, wx.NORMAL, wx.NORMAL, False,
              'Sans'))
        self.VariablesGrid.SetLabelFont(wx.Font(10, 77, wx.NORMAL, wx.NORMAL,
              False, 'Sans'))
        self.VariablesGrid.SetSelectionBackground(wx.WHITE)
        self.VariablesGrid.SetSelectionForeground(wx.BLACK)
        if wx.VERSION >= (2, 6, 0):
            self.VariablesGrid.Bind(wx.grid.EVT_GRID_CELL_CHANGE, self.OnVariablesGridCellChange)
            self.VariablesGrid.Bind(wx.grid.EVT_GRID_SELECT_CELL, self.OnVariablesGridSelectCell)
            self.VariablesGrid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.OnVariablesGridCellLeftClick)
            self.VariablesGrid.Bind(wx.grid.EVT_GRID_EDITOR_SHOWN, self.OnVariablesGridEditorShown)
            #self.VariablesGrid.Bind(wx.EVT_KEY_DOWN, self.OnChar)
        else:
            wx.grid.EVT_GRID_CELL_CHANGE(self.VariablesGrid, self.OnVariablesGridCellChange)
            wx.grid.EVT_GRID_SELECT_CELL(self.VariablesGrid, self.OnVariablesGridSelectCell)
            wx.grid.EVT_GRID_CELL_LEFT_CLICK(self.VariablesGrid, self.OnVariablesGridCellLeftClick)
            wx.grid.EVT_GRID_EDITOR_SHOWN(self.VariablesGrid, self.OnVariablesGridEditorShown)
            #wx.EVT_KEY_DOWN(self.VariablesGrid, self.OnChar)
        self.VariablesGrid.SetDropTarget(VariableDropTarget(self))
        
        self.ControlPanel = wx.ScrolledWindow(id=ID_VARIABLEEDITORCONTROLPANEL,
              name='ControlPanel', parent=self, pos=wx.Point(0, 0),
              size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL)
        self.ControlPanel.SetScrollRate(0, 10)
        
        self.staticText1 = wx.StaticText(id=ID_VARIABLEEDITORPANELSTATICTEXT1,
              label=_('Return Type:'), name='staticText1', parent=self.ControlPanel,
              pos=wx.Point(0, 0), size=wx.Size(145, 17), style=0)

        self.ReturnType = wx.ComboBox(id=ID_VARIABLEEDITORPANELRETURNTYPE,
              name='ReturnType', parent=self.ControlPanel, pos=wx.Point(0, 0),
              size=wx.Size(145, 28), style=wx.CB_READONLY)
        self.Bind(wx.EVT_COMBOBOX, self.OnReturnTypeChanged, id=ID_VARIABLEEDITORPANELRETURNTYPE)

        self.staticText2 = wx.StaticText(id=ID_VARIABLEEDITORPANELSTATICTEXT2,
              label=_('Class Filter:'), name='staticText2', parent=self.ControlPanel,
              pos=wx.Point(0, 0), size=wx.Size(145, 17), style=0)

        self.ClassFilter = wx.ComboBox(id=ID_VARIABLEEDITORPANELCLASSFILTER,
              name='ClassFilter', parent=self.ControlPanel, pos=wx.Point(0, 0),
              size=wx.Size(145, 28), style=wx.CB_READONLY)
        self.Bind(wx.EVT_COMBOBOX, self.OnClassFilter, id=ID_VARIABLEEDITORPANELCLASSFILTER)

        self.AddButton = wx.Button(id=ID_VARIABLEEDITORPANELADDBUTTON, label=_('Add'),
              name='AddButton', parent=self.ControlPanel, pos=wx.Point(0, 0),
              size=wx.DefaultSize, style=0)
        self.Bind(wx.EVT_BUTTON, self.OnAddButton, id=ID_VARIABLEEDITORPANELADDBUTTON)

        self.DeleteButton = wx.Button(id=ID_VARIABLEEDITORPANELDELETEBUTTON, label=_('Delete'),
              name='DeleteButton', parent=self.ControlPanel, pos=wx.Point(0, 0),
              size=wx.DefaultSize, style=0)
        self.Bind(wx.EVT_BUTTON, self.OnDeleteButton, id=ID_VARIABLEEDITORPANELDELETEBUTTON)

        self.UpButton = wx.Button(id=ID_VARIABLEEDITORPANELUPBUTTON, label='^',
              name='UpButton', parent=self.ControlPanel, pos=wx.Point(0, 0),
              size=wx.Size(32, 32), style=0)
        self.Bind(wx.EVT_BUTTON, self.OnUpButton, id=ID_VARIABLEEDITORPANELUPBUTTON)

        self.DownButton = wx.Button(id=ID_VARIABLEEDITORPANELDOWNBUTTON, label='v',
              name='DownButton', parent=self.ControlPanel, pos=wx.Point(0, 0),
              size=wx.Size(32, 32), style=0)
        self.Bind(wx.EVT_BUTTON, self.OnDownButton, id=ID_VARIABLEEDITORPANELDOWNBUTTON)

        self._init_sizers()

    def __init__(self, parent, window, controler, element_type):
        self._init_ctrls(parent)
        self.ParentWindow = window
        self.Controler = controler
        self.ElementType = element_type
        
        self.Filter = "All"
        self.FilterChoices = []
        self.FilterChoiceTransfer = GetFilterChoiceTransfer()
        
        self.DefaultValue = {   "Name" : "", "Class" : "", "Type" : "INT", "Location" : "",
                                "Initial Value" : "", "Option" : "",
                                "Documentation" : "", "Edit" : True
                            }

        if element_type in ["config", "resource"]:
            self.DefaultTypes = {"All" : "Global"}
        else:
            self.DefaultTypes = {"All" : "Local", "Interface" : "Input", "Variables" : "Local"}

        if element_type in ["config", "resource"] \
        or element_type in ["program", "transition", "action"]:
            # this is an element that can have located variables
            self.Table = VariableTable(self, [], GetVariableTableColnames(True))

            if element_type in ["config", "resource"]:
                self.FilterChoices = ["All", "Global"]#,"Access"]
            else:
                self.FilterChoices = ["All",
                                        "Interface", "   Input", "   Output", "   InOut", "   External",
                                        "Variables", "   Local", "   Temp"]#,"Access"]

            # these condense the ColAlignements list
            l = wx.ALIGN_LEFT
            c = wx.ALIGN_CENTER 

            #                      Num  Name    Class   Type    Loc     Init    Option   Doc
            self.ColSizes       = [40,  80,     70,     80,     80,     80,     100,     80]
            self.ColAlignements = [c,   l,      l,      l,      l,      l,      l,       l]

        else:
            # this is an element that cannot have located variables
            self.Table = VariableTable(self, [], GetVariableTableColnames(False))

            if element_type == "function":
                self.FilterChoices = ["All",
                                        "Interface", "   Input", "   Output", "   InOut",
                                        "Variables", "   Local"]
            else:
                self.FilterChoices = ["All",
                                        "Interface", "   Input", "   Output", "   InOut", "   External",
                                        "Variables", "   Local", "   Temp"]

            # these condense the ColAlignements list
            l = wx.ALIGN_LEFT
            c = wx.ALIGN_CENTER 

            #                      Num  Name    Class   Type    Init    Option   Doc
            self.ColSizes       = [40,  80,     70,     80,     80,     100,     160]
            self.ColAlignements = [c,   l,      l,      l,      l,      l,       l]

        for choice in self.FilterChoices:
            self.ClassFilter.Append(_(choice))

        reverse_transfer = {}
        for filter, choice in self.FilterChoiceTransfer.items():
            reverse_transfer[choice] = filter
        self.ClassFilter.SetStringSelection(_(reverse_transfer[self.Filter]))
        self.RefreshTypeList()

        if element_type == "function":
            for base_type in self.Controler.GetBaseTypes():
                self.ReturnType.Append(base_type)
            self.ReturnType.Enable(True)
        else:
            self.ReturnType.Enable(False)
            self.staticText1.Hide()
            self.ReturnType.Hide()
            
        self.VariablesGrid.SetTable(self.Table)
        self.VariablesGrid.SetRowLabelSize(0)
        for col in range(self.Table.GetNumberCols()):
            attr = wx.grid.GridCellAttr()
            attr.SetAlignment(self.ColAlignements[col], wx.ALIGN_CENTRE)
            self.VariablesGrid.SetColAttr(col, attr)
            self.VariablesGrid.SetColMinimalWidth(col, self.ColSizes[col])
            self.VariablesGrid.AutoSizeColumn(col, False)
    
    def SetTagName(self, tagname):
        self.TagName = tagname
    
    def IsFunctionBlockType(self, name):
        bodytype = self.Controler.GetEditedElementBodyType(self.TagName)
        pouname, poutype = self.Controler.GetEditedElementType(self.TagName)
        if poutype != "function" and bodytype in ["ST", "IL"]:
            return False
        else:
            return name in self.Controler.GetFunctionBlockTypes(self.TagName)
    
    def RefreshView(self):
        self.PouNames = self.Controler.GetProjectPouNames()
        
        words = self.TagName.split("::")
        if self.ElementType == "config":
            self.PouIsUsed = False
            returnType = None
            self.Values = self.Controler.GetConfigurationGlobalVars(words[1])
        elif self.ElementType == "resource":
            self.PouIsUsed = False
            returnType = None
            self.Values = self.Controler.GetConfigurationResourceGlobalVars(words[1], words[2])
        else:
            self.PouIsUsed = self.Controler.PouIsUsed(words[1])
            returnType = self.Controler.GetEditedElementInterfaceReturnType(self.TagName)
            self.Values = self.Controler.GetEditedElementInterfaceVars(self.TagName)
        
        if returnType and self.ReturnType.IsEnabled():
            self.ReturnType.SetStringSelection(returnType)
        
        self.RefreshValues()
        self.RefreshButtons()
    
    def OnReturnTypeChanged(self, event):
        words = self.TagName.split("::")
        self.Controler.SetPouInterfaceReturnType(words[1], self.ReturnType.GetStringSelection())
        self.Controler.BufferProject()
        self.ParentWindow.RefreshEditor(variablepanel = False)
        self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, INSTANCESTREE, LIBRARYTREE)
        event.Skip()
    
    def OnClassFilter(self, event):
        self.Filter = self.FilterChoiceTransfer[VARIABLE_CHOICES_DICT[self.ClassFilter.GetStringSelection()]]
        self.RefreshTypeList()
        self.RefreshValues()
        self.RefreshButtons()
        event.Skip()

    def RefreshTypeList(self):
        if self.Filter == "All":
            self.ClassList = [self.FilterChoiceTransfer[choice] for choice in self.FilterChoices if self.FilterChoiceTransfer[choice] not in ["All","Interface","Variables"]]
        elif self.Filter == "Interface":
            self.ClassList = ["Input","Output","InOut","External"]
        elif self.Filter == "Variables":
            self.ClassList = ["Local","Temp"]
        else:
            self.ClassList = [self.Filter]

    def RefreshButtons(self):
        if getattr(self, "Table", None):
            table_length = len(self.Table.data)
            row_class = None
            row_edit = True
            row = 0
            if table_length > 0:
                row = self.VariablesGrid.GetGridCursorRow()
                row_edit = self.Table.GetValueByName(row, "Edit")
                if self.PouIsUsed:
                    row_class = self.Table.GetValueByName(row, "Class")
            self.AddButton.Enable(not self.PouIsUsed or self.Filter not in ["Interface", "Input", "Output", "InOut"])
            self.DeleteButton.Enable(table_length > 0 and row_edit and row_class not in ["Input", "Output", "InOut"])
            self.UpButton.Enable(table_length > 0 and row > 0 and self.Filter == "All" and row_class not in ["Input", "Output", "InOut"])
            self.DownButton.Enable(table_length > 0 and row < table_length - 1 and self.Filter == "All" and row_class not in ["Input", "Output", "InOut"])

    def OnAddButton(self, event):
        new_row = self.DefaultValue.copy()
        if self.Filter in self.DefaultTypes:
            new_row["Class"] = self.DefaultTypes[self.Filter]
        else:
            new_row["Class"] = self.Filter
        if self.Filter == "All" and len(self.Values) > 0:
            row_index = self.VariablesGrid.GetGridCursorRow() + 1
            self.Values.insert(row_index, new_row)
        else:
            row_index = -1
            self.Values.append(new_row)
        self.SaveValues()
        self.RefreshValues(row_index)
        self.RefreshButtons()
        event.Skip()

    def OnDeleteButton(self, event):
        row = self.Table.GetRow(self.VariablesGrid.GetGridCursorRow())
        self.Values.remove(row)
        self.SaveValues()
        self.RefreshValues()
        self.RefreshButtons()
        event.Skip()

    def OnUpButton(self, event):
        self.MoveValue(self.VariablesGrid.GetGridCursorRow(), -1)
        self.RefreshButtons()
        event.Skip()

    def OnDownButton(self, event):
        self.MoveValue(self.VariablesGrid.GetGridCursorRow(), 1)
        self.RefreshButtons()
        event.Skip()

    def OnVariablesGridCellChange(self, event):
        row, col = event.GetRow(), event.GetCol()
        colname = self.Table.GetColLabelValue(col, False)
        value = self.Table.GetValue(row, col)

        if colname == "Name" and value != "":
            if not TestIdentifier(value):
                message = wx.MessageDialog(self, _("\"%s\" is not a valid identifier!")%value, _("Error"), wx.OK|wx.ICON_ERROR)
                message.ShowModal()
                message.Destroy()
                event.Veto()
            elif value.upper() in IEC_KEYWORDS:
                message = wx.MessageDialog(self, _("\"%s\" is a keyword. It can't be used!")%value, _("Error"), wx.OK|wx.ICON_ERROR)
                message.ShowModal()
                message.Destroy()
                event.Veto()
            elif value.upper() in self.PouNames:
                message = wx.MessageDialog(self, _("A POU named \"%s\" already exists!")%value, _("Error"), wx.OK|wx.ICON_ERROR)
                message.ShowModal()
                message.Destroy()
                event.Veto()
            elif value.upper() in [var["Name"].upper() for var in self.Values if var != self.Table.data[row]]:
                message = wx.MessageDialog(self, _("A variable with \"%s\" as name already exists in this pou!")%value, _("Error"), wx.OK|wx.ICON_ERROR)
                message.ShowModal()
                message.Destroy()
                event.Veto()
            else:
                self.SaveValues(False)
                old_value = self.Table.GetOldValue()
                if old_value != "":
                    self.Controler.UpdateEditedElementUsedVariable(self.TagName, old_value, value)
                self.Controler.BufferProject()
                self.ParentWindow.RefreshEditor(variablepanel = False)
                self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, INSTANCESTREE, LIBRARYTREE)
                event.Skip()
        else:
            self.SaveValues()
            if colname == "Class":
                self.ParentWindow.RefreshEditor(variablepanel = False)
            event.Skip()
    
    def OnVariablesGridEditorShown(self, event):
        row, col = event.GetRow(), event.GetCol() 

        label_value = self.Table.GetColLabelValue(col)
        if label_value == "Type":
            type_menu = wx.Menu(title='')   # the root menu

            # build a submenu containing standard IEC types
            base_menu = wx.Menu(title='')
            for base_type in self.Controler.GetBaseTypes():
                new_id = wx.NewId()
                AppendMenu(base_menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=base_type)
                self.Bind(wx.EVT_MENU, self.GetVariableTypeFunction(base_type), id=new_id)

            type_menu.AppendMenu(wx.NewId(), _("Base Types"), base_menu)

            # build a submenu containing user-defined types
            datatype_menu = wx.Menu(title='')
            
            # TODO : remove complextypes argument when matiec can manage complex types in pou interface
            datatypes = self.Controler.GetDataTypes(basetypes = False)
            for datatype in datatypes:
                new_id = wx.NewId()
                AppendMenu(datatype_menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=datatype)
                self.Bind(wx.EVT_MENU, self.GetVariableTypeFunction(datatype), id=new_id)

            type_menu.AppendMenu(wx.NewId(), _("User Data Types"), datatype_menu)

            # build a submenu containing function block types
            bodytype = self.Controler.GetEditedElementBodyType(self.TagName)
            pouname, poutype = self.Controler.GetEditedElementType(self.TagName)
            classtype = self.Table.GetValueByName(row, "Class")
            
            #new_id = wx.NewId()
            #AppendMenu(type_menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=_("Array"))
            #self.Bind(wx.EVT_MENU, self.VariableArrayTypeFunction, id=new_id)
            
            if classtype in ["Input", "Output", "InOut", "External", "Global"] or \
            poutype != "function" and bodytype in ["ST", "IL"]:
                functionblock_menu = wx.Menu(title='')
                fbtypes = self.Controler.GetFunctionBlockTypes(self.TagName)
                for functionblock_type in fbtypes:
                    new_id = wx.NewId()
                    AppendMenu(functionblock_menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=functionblock_type)
                    self.Bind(wx.EVT_MENU, self.GetVariableTypeFunction(functionblock_type), id=new_id)

                type_menu.AppendMenu(wx.NewId(), _("Function Block Types"), functionblock_menu)

            rect = self.VariablesGrid.BlockToDeviceRect((row, col), (row, col))
            corner_x = rect.x + rect.width
            corner_y = rect.y + self.VariablesGrid.GetColLabelSize()

            # pop up this new menu
            self.VariablesGrid.PopupMenuXY(type_menu, corner_x, corner_y)
            event.Veto()
        else:
            event.Skip()
    
    def GetVariableTypeFunction(self, base_type):
        def VariableTypeFunction(event):
            row = self.VariablesGrid.GetGridCursorRow()
            self.Table.SetValueByName(row, "Type", base_type)
            self.Table.ResetView(self.VariablesGrid)
            self.SaveValues(False)
            self.ParentWindow.RefreshEditor(variablepanel = False)
            self.Controler.BufferProject()
            self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, INSTANCESTREE, LIBRARYTREE)
        return VariableTypeFunction
    
    def VariableArrayTypeFunction(self, event):
        row = self.VariablesGrid.GetGridCursorRow()
        dialog = ArrayTypeDialog(self, 
                                 self.Controler.GetDataTypes(self.TagName), 
                                 self.Table.GetValueByName(row, "Type"))
        if dialog.ShowModal() == wx.ID_OK:
            self.Table.SetValueByName(row, "Type", dialog.GetValue())
            self.Table.ResetView(self.VariablesGrid)
            self.SaveValues(False)
            self.ParentWindow.RefreshEditor(variablepanel = False)
            self.Controler.BufferProject()
            self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, INSTANCESTREE, LIBRARYTREE)
        dialog.Destroy()
    
    def OnVariablesGridCellLeftClick(self, event):
        row = event.GetRow()
        if event.GetCol() == 0 and self.Table.GetValueByName(row, "Edit"):
            row = event.GetRow()
            var_name = self.Table.GetValueByName(row, "Name")
            var_class = self.Table.GetValueByName(row, "Class")
            var_type = self.Table.GetValueByName(row, "Type")
            data = wx.TextDataObject(str((var_name, var_class, var_type, self.TagName)))
            dragSource = wx.DropSource(self.VariablesGrid)
            dragSource.SetData(data)
            dragSource.DoDragDrop()
        event.Skip()
    
    def OnVariablesGridSelectCell(self, event):
        wx.CallAfter(self.RefreshButtons)
        event.Skip()

    def OnChar(self, event):
        keycode = event.GetKeyCode()
        if keycode == wx.WXK_DELETE:
            row = self.Table.GetRow(self.VariablesGrid.GetGridCursorRow())
            self.Values.remove(row)
            self.SaveValues()
            self.RefreshValues()
            self.RefreshButtons()
        event.Skip()

    def MoveValue(self, value_index, move):
        new_index = max(0, min(value_index + move, len(self.Values) - 1))
        if new_index != value_index:
            self.Values.insert(new_index, self.Values.pop(value_index))
            self.SaveValues()
            self.RefreshValues()
            self.VariablesGrid.SetGridCursor(new_index, self.VariablesGrid.GetGridCursorCol())
        
    def RefreshValues(self, select=0):
        if len(self.Table.data) > 0:
            self.VariablesGrid.SetGridCursor(0, 1)
        data = []
        for num, variable in enumerate(self.Values):
            if variable["Class"] in self.ClassList:
                variable["Number"] = num + 1
                data.append(variable)
        self.Table.SetData(data)
        if len(self.Table.data) > 0:
            if select == -1:
                select = len(self.Table.data) - 1
            self.VariablesGrid.SetGridCursor(select, 1)
            self.VariablesGrid.MakeCellVisible(select, 1)
        self.Table.ResetView(self.VariablesGrid)

    def SaveValues(self, buffer = True):
        words = self.TagName.split("::")
        if self.ElementType == "config":
            self.Controler.SetConfigurationGlobalVars(words[1], self.Values)
        elif self.ElementType == "resource":
            self.Controler.SetConfigurationResourceGlobalVars(words[1], words[2], self.Values)
        else:
            if self.ReturnType.IsEnabled():
                self.Controler.SetPouInterfaceReturnType(words[1], self.ReturnType.GetStringSelection())
            self.Controler.SetPouInterfaceVars(words[1], self.Values)
        if buffer:
            self.Controler.BufferProject()
            self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, INSTANCESTREE, LIBRARYTREE)            

    def AddVariableError(self, infos):
        if isinstance(infos[0], TupleType):
            for i in xrange(*infos[0]):
                self.Table.AddError((i,) + infos[1:])
        else:
            self.Table.AddError(infos)
        self.Table.ResetView(self.VariablesGrid)

    def ClearErrors(self):
        self.Table.ClearErrors()
        self.Table.ResetView(self.VariablesGrid)

class LocationCellControl(wx.PyControl):
    
    def _init_coll_MainSizer_Items(self, parent):
        parent.AddWindow(self.Location, 0, border=0, flag=wx.GROW)
        parent.AddWindow(self.BrowseButton, 0, border=0, flag=wx.GROW)
        
    def _init_coll_MainSizer_Growables(self, parent):
        parent.AddGrowableCol(0)
        parent.AddGrowableRow(0)
    
    def _init_sizers(self):
        self.MainSizer = wx.FlexGridSizer(cols=2, hgap=0, rows=1, vgap=0)
        
        self._init_coll_MainSizer_Items(self.MainSizer)
        self._init_coll_MainSizer_Growables(self.MainSizer)
        
        self.SetSizer(self.MainSizer)
    
    def _init_ctrls(self, prnt):
        wx.Control.__init__(self, id=-1, 
              name='LocationCellControl', parent=prnt,  
              size=wx.DefaultSize, style=0)
        
        # create location text control
        self.Location = wx.TextCtrl(id=-1, name='Location', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(0, 0), style=wx.TE_PROCESS_ENTER)
        self.Location.Bind(wx.EVT_KEY_DOWN, self.OnLocationChar)
        
        # create browse button
        self.BrowseButton = wx.Button(id=-1, label='...', 
              name='staticText1', parent=self, pos=wx.Point(0, 0), 
              size=wx.Size(30, 0), style=0)
        self.BrowseButton.Bind(wx.EVT_BUTTON, self.OnBrowseButtonClick)

        self.Bind(wx.EVT_SIZE, self.OnSize)
        
        self._init_sizers()

    '''
    Custom cell editor control with a text box and a button that launches
    the BrowseVariableLocationsDialog.
    '''
    def __init__(self, parent, locations):
        self._init_ctrls(parent)
        self.Locations = locations
        self.VarType = None

    def SetVarType(self, vartype):
        self.VarType = vartype

    def SetValue(self, value):
        self.Location.SetValue(value)
    
    def GetValue(self):
        return self.Location.GetValue()

    def OnSize(self, event):
        self.Layout()

    def OnBrowseButtonClick(self, event):
        # pop up the location browser dialog
        dialog = BrowseLocationsDialog(self, self.VarType, self.Locations)
        if dialog.ShowModal() == wx.ID_OK:
            infos = dialog.GetValues()

            # set the location
            self.Location.SetValue(infos["location"])

        dialog.Destroy()

        self.Location.SetFocus()

    def OnLocationChar(self, event):
        keycode = event.GetKeyCode()
        if keycode == wx.WXK_RETURN or keycode == wx.WXK_TAB:
            self.Parent.Parent.ProcessEvent(event)
            self.Parent.Parent.SetFocus()
        else:
            event.Skip()

    def SetInsertionPoint(self, i):
        self.Location.SetInsertionPoint(i)
    
    def SetFocus(self):
        self.Location.SetFocus()

class LocationCellEditor(wx.grid.PyGridCellEditor):
    '''
    Grid cell editor that uses LocationCellControl to display a browse button.
    '''
    def __init__(self, table, controler):
        wx.grid.PyGridCellEditor.__init__(self)
        self.Table = table
        self.Controler = controler

    def __del__(self):
        self.CellControl = None
    
    def Create(self, parent, id, evt_handler):
        locations = self.Controler.GetVariableLocationTree()
        if len(locations) > 0:
            self.CellControl = LocationCellControl(parent, locations)
        else:
            self.CellControl = wx.TextCtrl(parent, -1)
        self.SetControl(self.CellControl)
        if evt_handler:
            self.CellControl.PushEventHandler(evt_handler)

    def BeginEdit(self, row, col, grid):
        self.CellControl.SetValue(self.Table.GetValueByName(row, 'Location'))
        if isinstance(self.CellControl, LocationCellControl):
            self.CellControl.SetVarType(self.Controler.GetBaseType(self.Table.GetValueByName(row, 'Type')))
        self.CellControl.SetFocus()

    def EndEdit(self, row, col, grid):
        loc = self.CellControl.GetValue()
        old_loc = self.Table.GetValueByName(row, 'Location')
        if loc != old_loc:
            self.Table.SetValueByName(row, 'Location', loc)
            return True
        return False

    def SetSize(self, rect):
        self.CellControl.SetDimensions(rect.x + 1, rect.y,
                                        rect.width, rect.height,
                                        wx.SIZE_ALLOW_MINUS_ONE)

    def Clone(self):
        return LocationCellEditor(self.Table, self.Locations)

def GetDirChoiceOptions():
    _ = lambda x : x
    return [(_("All"), [LOCATION_VAR_INPUT, LOCATION_VAR_OUTPUT, LOCATION_VAR_MEMORY]), 
            (_("Input"), [LOCATION_VAR_INPUT]), 
            (_("Output"), [LOCATION_VAR_OUTPUT]), 
            (_("Memory"), [LOCATION_VAR_MEMORY])]
DIRCHOICE_OPTIONS_FILTER = dict([(_(option), filter) for option, filter in GetDirChoiceOptions()])

# turn LOCATIONDATATYPES inside-out
LOCATION_SIZES = {}
for size, types in LOCATIONDATATYPES.iteritems():
    for type in types:
        LOCATION_SIZES[type] = size

[ID_BROWSELOCATIONSDIALOG, ID_BROWSELOCATIONSDIALOGLOCATIONSTREE, 
 ID_BROWSELOCATIONSDIALOGDIRCHOICE, ID_BROWSELOCATIONSDIALOGSTATICTEXT1, 
 ID_BROWSELOCATIONSDIALOGSTATICTEXT2, 
] = [wx.NewId() for _init_ctrls in range(5)]

class BrowseLocationsDialog(wx.Dialog):
    
    if wx.VERSION < (2, 6, 0):
        def Bind(self, event, function, id = None):
            if id is not None:
                event(self, id, function)
            else:
                event(self, function)
    
    def _init_coll_MainSizer_Items(self, parent):
        parent.AddWindow(self.staticText1, 0, border=20, flag=wx.TOP|wx.LEFT|wx.RIGHT|wx.GROW)
        parent.AddWindow(self.LocationsTree, 0, border=20, flag=wx.LEFT|wx.RIGHT|wx.GROW)
        parent.AddSizer(self.ButtonGridSizer, 0, border=20, flag=wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.GROW)
        
    def _init_coll_MainSizer_Growables(self, parent):
        parent.AddGrowableCol(0)
        parent.AddGrowableRow(1)
    
    def _init_coll_ButtonGridSizer_Items(self, parent):
        parent.AddWindow(self.staticText2, 0, border=0, flag=wx.ALIGN_CENTER_VERTICAL)
        parent.AddWindow(self.DirChoice, 0, border=0, flag=wx.ALIGN_CENTER_VERTICAL)
        parent.AddSizer(self.ButtonSizer, 0, border=0, flag=wx.ALIGN_RIGHT)
        
    def _init_coll_ButtonGridSizer_Growables(self, parent):
        parent.AddGrowableCol(2)
        parent.AddGrowableRow(0)
    
    def _init_sizers(self):
        self.MainSizer = wx.FlexGridSizer(cols=1, hgap=0, rows=3, vgap=10)
        self.ButtonGridSizer = wx.FlexGridSizer(cols=3, hgap=5, rows=1, vgap=0)
        
        self._init_coll_MainSizer_Items(self.MainSizer)
        self._init_coll_MainSizer_Growables(self.MainSizer)
        self._init_coll_ButtonGridSizer_Items(self.ButtonGridSizer)
        self._init_coll_ButtonGridSizer_Growables(self.ButtonGridSizer)
        
        self.SetSizer(self.MainSizer)
    
    def _init_ctrls(self, prnt):
        wx.Dialog.__init__(self, id=ID_BROWSELOCATIONSDIALOG, 
              name='BrowseLocationsDialog', parent=prnt,  
              size=wx.Size(600, 400), style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER,
              title=_('Browse Locations'))
    
        self.staticText1 = wx.StaticText(id=ID_BROWSELOCATIONSDIALOGSTATICTEXT1,
              label=_('Locations available:'), name='staticText1', parent=self,
              pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
        
        if wx.Platform == '__WXMSW__':
            treestyle = wx.TR_HAS_BUTTONS|wx.TR_SINGLE|wx.SUNKEN_BORDER
        else:
            treestyle = wx.TR_HAS_BUTTONS|wx.TR_HIDE_ROOT|wx.TR_SINGLE|wx.SUNKEN_BORDER
        self.LocationsTree = wx.TreeCtrl(id=ID_BROWSELOCATIONSDIALOGLOCATIONSTREE,
              name='LocationsTree', parent=self, pos=wx.Point(0, 0),
              size=wx.Size(0, 0), style=treestyle)
        self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnLocationsTreeItemActivated, 
                  id=ID_BROWSELOCATIONSDIALOGLOCATIONSTREE)
        
        self.staticText2 = wx.StaticText(id=ID_BROWSELOCATIONSDIALOGSTATICTEXT2,
              label=_('Direction:'), name='staticText2', parent=self,
              pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
        
        self.DirChoice = wx.ComboBox(id=ID_BROWSELOCATIONSDIALOGDIRCHOICE,
              name='DirChoice', parent=self, pos=wx.Point(0, 0),
              size=wx.DefaultSize, style=wx.CB_READONLY)
        self.Bind(wx.EVT_COMBOBOX, self.OnDirChoice, id=ID_BROWSELOCATIONSDIALOGDIRCHOICE)
        
        self.ButtonSizer = self.CreateButtonSizer(wx.OK|wx.CANCEL|wx.CENTRE)
        if wx.VERSION >= (2, 5, 0):
            self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.ButtonSizer.GetAffirmativeButton().GetId())
        else:
            self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.ButtonSizer.GetChildren()[0].GetSizer().GetChildren()[0].GetWindow().GetId())
        
        self._init_sizers()
    
    def __init__(self, parent, var_type, locations):
        self._init_ctrls(parent)
        self.VarType = var_type
        self.Locations = locations
        
        # Define Tree item icon list
        self.TreeImageList = wx.ImageList(16, 16)
        self.TreeImageDict = {}
        
        # Icons for items
        for imgname, itemtype in [
            ("CONFIGURATION", LOCATION_PLUGIN), 
            ("RESOURCE",      LOCATION_MODULE), 
            ("PROGRAM",       LOCATION_GROUP), 
            ("VAR_INPUT",     LOCATION_VAR_INPUT), 
            ("VAR_OUTPUT",    LOCATION_VAR_OUTPUT), 
            ("VAR_LOCAL",     LOCATION_VAR_MEMORY)]:
            self.TreeImageDict[itemtype]=self.TreeImageList.Add(wx.Bitmap(os.path.join(CWD, 'Images', '%s.png'%imgname)))
        
        # Assign icon list to TreeCtrls
        self.LocationsTree.SetImageList(self.TreeImageList)
        
        # Set a options for the choice
        for option, filter in GetDirChoiceOptions():
            self.DirChoice.Append(_(option))
        self.DirChoice.SetStringSelection(_("All"))
        self.RefreshFilter()
        
        self.RefreshLocationsTree()
    
    def RefreshFilter(self):
        self.Filter = DIRCHOICE_OPTIONS_FILTER[self.DirChoice.GetStringSelection()]
    
    def RefreshLocationsTree(self):
        root = self.LocationsTree.GetRootItem()
        if not root.IsOk():
            if wx.Platform == '__WXMSW__':
                root = self.LocationsTree.AddRoot(_('Plugins'))
            else:
                root = self.LocationsTree.AddRoot("")
        self.GenerateLocationsTreeBranch(root, self.Locations)
        self.LocationsTree.Expand(root)
    
    def GenerateLocationsTreeBranch(self, root, locations):
        to_delete = []
        if wx.VERSION >= (2, 6, 0):
            item, root_cookie = self.LocationsTree.GetFirstChild(root)
        else:
            item, root_cookie = self.LocationsTree.GetFirstChild(root, 0)
        for loc_infos in locations:
            infos = loc_infos.copy()
            if infos["type"] in [LOCATION_PLUGIN, LOCATION_MODULE, LOCATION_GROUP] or\
               infos["type"] in self.Filter and (infos["IEC_type"] == self.VarType or
               infos["IEC_type"] is None and LOCATION_SIZES[self.VarType] == infos["size"]):
                children = [child for child in infos.pop("children")]
                if not item.IsOk():
                    item = self.LocationsTree.AppendItem(root, infos["name"])
                    if wx.Platform != '__WXMSW__':
                        item, root_cookie = self.LocationsTree.GetNextChild(root, root_cookie)
                else:
                    self.LocationsTree.SetItemText(item, infos["name"])
                self.LocationsTree.SetPyData(item, infos)
                self.LocationsTree.SetItemImage(item, self.TreeImageDict[infos["type"]])
                self.GenerateLocationsTreeBranch(item, children)
                item, root_cookie = self.LocationsTree.GetNextChild(root, root_cookie)
        while item.IsOk():
            to_delete.append(item)
            item, root_cookie = self.LocationsTree.GetNextChild(root, root_cookie)
        for item in to_delete:
            self.LocationsTree.Delete(item)
    
    def OnLocationsTreeItemActivated(self, event):
        infos = self.LocationsTree.GetPyData(event.GetItem())
        if infos["type"] not in [LOCATION_PLUGIN, LOCATION_MODULE, LOCATION_GROUP]:
            wx.CallAfter(self.EndModal, wx.ID_OK)
        event.Skip()
    
    def OnDirChoice(self, event):
        self.RefreshFilter()
        self.RefreshLocationsTree()
        
    def GetValues(self):
        selected = self.LocationsTree.GetSelection()
        return self.LocationsTree.GetPyData(selected)
        
    def OnOK(self, event):
        selected = self.LocationsTree.GetSelection()
        var_infos = None
        if selected.IsOk():
            var_infos = self.LocationsTree.GetPyData(selected)
        if var_infos is None or var_infos["type"] in [LOCATION_PLUGIN, LOCATION_MODULE, LOCATION_GROUP]:
            message = wx.MessageDialog(self, _("A location must be selected!"), _("Error"), wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        else:
            self.EndModal(wx.ID_OK)