Laurent@814: #!/usr/bin/env python
Laurent@814: # -*- coding: utf-8 -*-
Laurent@814: 
andrej@1571: # This file is part of Beremiz, a Integrated Development Environment for
andrej@1571: # programming IEC 61131-3 automates supporting plcopen standard and CanFestival.
Laurent@814: #
andrej@1571: # Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD
Laurent@814: #
andrej@1571: # See COPYING file for copyrights details.
Laurent@814: #
andrej@1571: # This program is free software; you can redistribute it and/or
andrej@1571: # modify it under the terms of the GNU General Public License
andrej@1571: # as published by the Free Software Foundation; either version 2
andrej@1571: # of the License, or (at your option) any later version.
Laurent@814: #
andrej@1571: # This program is distributed in the hope that it will be useful,
andrej@1571: # but WITHOUT ANY WARRANTY; without even the implied warranty of
andrej@1571: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
andrej@1571: # GNU General Public License for more details.
Laurent@814: #
andrej@1571: # You should have received a copy of the GNU General Public License
andrej@1571: # along with this program; if not, write to the Free Software
andrej@1571: # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
Laurent@814: 
Laurent@814: import os
Laurent@814: import re
Laurent@814: from types import TupleType, StringType, UnicodeType
Laurent@814: 
Laurent@814: import wx
Laurent@814: import wx.grid
Laurent@814: import wx.lib.buttons
Laurent@814: 
Edouard@1412: from plcopen.structures import LOCATIONDATATYPES, TestIdentifier, IEC_KEYWORDS, DefaultType
Laurent@814: from graphics.GraphicCommons import REFRESH_HIGHLIGHT_PERIOD, ERROR_HIGHLIGHT
Laurent@814: from dialogs.ArrayTypeDialog import ArrayTypeDialog
Laurent@814: from CustomGrid import CustomGrid
Laurent@814: from CustomTable import CustomTable
Laurent@814: from LocationCellEditor import LocationCellEditor
Laurent@814: from util.BitmapLibrary import GetBitmap
Laurent@1347: from PLCControler import _VariableInfos
Laurent@814: 
Laurent@814: #-------------------------------------------------------------------------------
Laurent@814: #                                 Helpers
Laurent@814: #-------------------------------------------------------------------------------
Laurent@814: 
Edouard@1412: [TITLE, EDITORTOOLBAR, FILEMENU, EDITMENU, DISPLAYMENU, PROJECTTREE,
Laurent@814:  POUINSTANCEVARIABLESPANEL, LIBRARYTREE, SCALING, PAGETITLES
Edouard@1184: ] = range(10)
Laurent@814: 
Laurent@814: def GetVariableTableColnames(location):
Laurent@814:     _ = lambda x : x
Laurent@814:     if location:
Laurent@814:     	return ["#", _("Name"), _("Class"), _("Type"), _("Location"), _("Initial Value"), _("Option"), _("Documentation")]
Laurent@814:     return ["#", _("Name"), _("Class"), _("Type"), _("Initial Value"), _("Option"), _("Documentation")]
Laurent@814: 
Laurent@814: def GetOptions(constant=True, retain=True, non_retain=True):
Laurent@814:     _ = lambda x : x
Laurent@814:     options = [""]
Laurent@814:     if constant:
Laurent@814:         options.append(_("Constant"))
Laurent@814:     if retain:
Laurent@814:         options.append(_("Retain"))
Laurent@814:     if non_retain:
Laurent@814:         options.append(_("Non-Retain"))
Laurent@814:     return options
Laurent@814: OPTIONS_DICT = dict([(_(option), option) for option in GetOptions()])
Laurent@814: 
Laurent@814: def GetFilterChoiceTransfer():
Laurent@814:     _ = lambda x : x
Edouard@1412:     return {_("All"): _("All"), _("Interface"): _("Interface"),
Edouard@1412:             _("   Input"): _("Input"), _("   Output"): _("Output"), _("   InOut"): _("InOut"),
Laurent@814:             _("   External"): _("External"), _("Variables"): _("Variables"), _("   Local"): _("Local"),
Laurent@814:             _("   Temp"): _("Temp"), _("Global"): _("Global")}#, _("Access") : _("Access")}
Laurent@814: VARIABLE_CHOICES_DICT = dict([(_(_class), _class) for _class in GetFilterChoiceTransfer().iterkeys()])
Laurent@814: VARIABLE_CLASSES_DICT = dict([(_(_class), _class) for _class in GetFilterChoiceTransfer().itervalues()])
Laurent@814: 
Laurent@814: CheckOptionForClass = {"Local": lambda x: x,
Laurent@814:                        "Temp": lambda x: "",
Laurent@814:                        "Input": lambda x: {"Retain": "Retain", "Non-Retain": "Non-Retain"}.get(x, ""),
Laurent@814:                        "InOut": lambda x: "",
Laurent@814:                        "Output": lambda x: {"Retain": "Retain", "Non-Retain": "Non-Retain"}.get(x, ""),
Laurent@814:                        "Global": lambda x: {"Constant": "Constant", "Retain": "Retain"}.get(x, ""),
Laurent@814:                        "External": lambda x: {"Constant": "Constant"}.get(x, "")
Laurent@814:                       }
Laurent@814: 
Laurent@814: LOCATION_MODEL = re.compile("((?:%[IQM](?:\*|(?:[XBWLD]?[0-9]+(?:\.[0-9]+)*)))?)$")
Laurent@1122: VARIABLE_NAME_SUFFIX_MODEL = re.compile("([0-9]*)$")
Laurent@814: 
Laurent@814: #-------------------------------------------------------------------------------
Laurent@814: #                            Variables Panel Table
Laurent@814: #-------------------------------------------------------------------------------
Laurent@814: 
Laurent@814: class VariableTable(CustomTable):
Edouard@1412: 
Laurent@814:     """
Laurent@814:     A custom wx.grid.Grid Table using user supplied data
Laurent@814:     """
Laurent@814:     def __init__(self, parent, data, colnames):
Laurent@814:         # The base class must be initialized *first*
Laurent@814:         CustomTable.__init__(self, parent, data, colnames)
Laurent@814:         self.old_value = None
Edouard@1412: 
Laurent@1347:     def GetValueByName(self, row, colname):
Laurent@1347:         if row < self.GetNumberRows():
Laurent@1347:             return getattr(self.data[row], colname)
Laurent@1347: 
Laurent@1347:     def SetValueByName(self, row, colname, value):
Laurent@1347:         if row < self.GetNumberRows():
Laurent@1347:             setattr(self.data[row], colname, value)
Edouard@1412: 
Laurent@814:     def GetValue(self, row, col):
Laurent@814:         if row < self.GetNumberRows():
Laurent@814:             if col == 0:
Laurent@1347:                 return self.data[row].Number
Laurent@814:             colname = self.GetColLabelValue(col, False)
Laurent@1347:             if colname == "Initial Value":
Laurent@1347:                 colname = "InitialValue"
Laurent@1347:             value = getattr(self.data[row], colname, "")
Laurent@814:             if colname == "Type" and isinstance(value, TupleType):
Laurent@814:                 if value[0] == "array":
Laurent@814:                     return "ARRAY [%s] OF %s" % (",".join(map(lambda x : "..".join(x), value[2])), value[1])
Laurent@814:             if not isinstance(value, (StringType, UnicodeType)):
Laurent@814:                 value = str(value)
Laurent@814:             if colname in ["Class", "Option"]:
Laurent@814:                 return _(value)
Laurent@814:             return value
Edouard@1412: 
Laurent@814:     def SetValue(self, row, col, value):
Laurent@814:         if col < len(self.colnames):
Laurent@814:             colname = self.GetColLabelValue(col, False)
Laurent@814:             if colname == "Name":
Laurent@1347:                 self.old_value = getattr(self.data[row], colname)
Laurent@814:             elif colname == "Class":
Laurent@814:                 value = VARIABLE_CLASSES_DICT[value]
Laurent@814:                 self.SetValueByName(row, "Option", CheckOptionForClass[value](self.GetValueByName(row, "Option")))
Laurent@814:                 if value == "External":
Laurent@1347:                     self.SetValueByName(row, "InitialValue", "")
Laurent@814:             elif colname == "Option":
Laurent@814:                 value = OPTIONS_DICT[value]
Laurent@1347:             elif colname == "Initial Value":
Laurent@1347:                 colname = "InitialValue"
Laurent@1347:             setattr(self.data[row], colname, value)
Laurent@814: 
Laurent@814:     def GetOldValue(self):
Laurent@814:         return self.old_value
Laurent@814: 
surkovsv93@1522:     def _GetRowEdit(self, row):
surkovsv93@1522:         row_edit = self.GetValueByName(row, "Edit")
surkovsv93@1522:         var_type = self.Parent.GetTagName()
surkovsv93@1522:         bodytype = self.Parent.Controler.GetEditedElementBodyType(var_type)
surkovsv93@1522:         if bodytype in ["ST", "IL"]:
surkovsv93@1522:             row_edit = True;
surkovsv93@1522:         return row_edit
surkovsv93@1522: 
Laurent@814:     def _updateColAttrs(self, grid):
Laurent@814:         """
Laurent@814:         wx.grid.Grid -> update the column attributes to add the
Laurent@814:         appropriate renderer given the column name.
Laurent@814: 
Laurent@814:         Otherwise default to the default renderer.
Laurent@814:         """
Laurent@814:         for row in range(self.GetNumberRows()):
Laurent@814:             var_class = self.GetValueByName(row, "Class")
Laurent@814:             var_type = self.GetValueByName(row, "Type")
Laurent@814:             row_highlights = self.Highlights.get(row, {})
Laurent@814:             for col in range(self.GetNumberCols()):
Laurent@814:                 editor = None
Laurent@814:                 renderer = None
Laurent@814:                 colname = self.GetColLabelValue(col, False)
Laurent@814:                 if self.Parent.Debug:
Laurent@814:                     grid.SetReadOnly(row, col, True)
Laurent@814:                 else:
Laurent@814:                     if colname == "Option":
Laurent@814:                         options = GetOptions(constant = var_class in ["Local", "External", "Global"],
Laurent@814:                                              retain = self.Parent.ElementType != "function" and var_class in ["Local", "Input", "Output", "Global"],
Laurent@814:                                              non_retain = self.Parent.ElementType != "function" and var_class in ["Local", "Input", "Output"])
Laurent@814:                         if len(options) > 1:
Laurent@814:                             editor = wx.grid.GridCellChoiceEditor()
Laurent@814:                             editor.SetParameters(",".join(map(_, options)))
Laurent@814:                         else:
Laurent@814:                             grid.SetReadOnly(row, col, True)
surkovsv93@1522:                     elif col != 0 and self._GetRowEdit(row):
Laurent@814:                         grid.SetReadOnly(row, col, False)
Laurent@814:                         if colname == "Name":
Laurent@1128:                             editor = wx.grid.GridCellTextEditor()
Laurent@1128:                             renderer = wx.grid.GridCellStringRenderer()
Laurent@814:                         elif colname == "Initial Value":
Laurent@814:                             if var_class not in ["External", "InOut"]:
Laurent@814:                                 if self.Parent.Controler.IsEnumeratedType(var_type):
Laurent@814:                                     editor = wx.grid.GridCellChoiceEditor()
Laurent@1308:                                     editor.SetParameters(",".join([""] + self.Parent.Controler.GetEnumeratedDataValues(var_type)))
Laurent@814:                                 else:
Laurent@814:                                     editor = wx.grid.GridCellTextEditor()
Laurent@814:                                 renderer = wx.grid.GridCellStringRenderer()
Laurent@814:                             else:
Laurent@814:                                 grid.SetReadOnly(row, col, True)
Laurent@814:                         elif colname == "Location":
Laurent@814:                             if var_class in ["Local", "Global"] and self.Parent.Controler.IsLocatableType(var_type):
Laurent@814:                                 editor = LocationCellEditor(self, self.Parent.Controler)
Laurent@814:                                 renderer = wx.grid.GridCellStringRenderer()
Laurent@814:                             else:
Laurent@814:                                 grid.SetReadOnly(row, col, True)
Laurent@814:                         elif colname == "Class":
Laurent@1128:                             if len(self.Parent.ClassList) == 1:
Laurent@814:                                 grid.SetReadOnly(row, col, True)
Laurent@814:                             else:
Laurent@814:                                 editor = wx.grid.GridCellChoiceEditor()
Laurent@814:                                 excluded = []
Laurent@814:                                 if self.Parent.IsFunctionBlockType(var_type):
Laurent@814:                                     excluded.extend(["Local","Temp"])
Laurent@814:                                 editor.SetParameters(",".join([_(choice) for choice in self.Parent.ClassList if choice not in excluded]))
Laurent@814:                     elif colname != "Documentation":
Laurent@814:                         grid.SetReadOnly(row, col, True)
Edouard@1412: 
Laurent@814:                 grid.SetCellEditor(row, col, editor)
Laurent@814:                 grid.SetCellRenderer(row, col, renderer)
Edouard@1412: 
laurent@831:                 if colname == "Location" and LOCATION_MODEL.match(self.GetValueByName(row, colname)) is None:
Laurent@814:                     highlight_colours = ERROR_HIGHLIGHT
Laurent@814:                 else:
Laurent@814:                     highlight_colours = row_highlights.get(colname.lower(), [(wx.WHITE, wx.BLACK)])[-1]
Laurent@814:                 grid.SetCellBackgroundColour(row, col, highlight_colours[0])
Laurent@814:                 grid.SetCellTextColour(row, col, highlight_colours[1])
Laurent@814:             self.ResizeRow(grid, row)
Laurent@814: 
Laurent@814: #-------------------------------------------------------------------------------
Laurent@814: #                         Variable Panel Drop Target
Edouard@1412: #-------------------------------------------------------------------------------
Laurent@814: 
Laurent@814: class VariableDropTarget(wx.TextDropTarget):
Laurent@814:     '''
Laurent@814:     This allows dragging a variable location from somewhere to the Location
Laurent@814:     column of a variable row.
Edouard@1412: 
Laurent@814:     The drag source should be a TextDataObject containing a Python tuple like:
Laurent@814:         ('%ID0.0.0', 'location', 'REAL')
Edouard@1412: 
Laurent@814:     c_ext/CFileEditor.py has an example of this (you can drag a C extension
Laurent@814:     variable to the Location column of the variable panel).
Laurent@814:     '''
Laurent@814:     def __init__(self, parent):
Laurent@814:         wx.TextDropTarget.__init__(self)
Laurent@814:         self.ParentWindow = parent
Edouard@1412: 
Laurent@814:     def OnDropText(self, x, y, data):
Laurent@814:         self.ParentWindow.ParentWindow.Select()
Laurent@814:         x, y = self.ParentWindow.VariablesGrid.CalcUnscrolledPosition(x, y)
Laurent@814:         col = self.ParentWindow.VariablesGrid.XToCol(x)
andrej@1577:         row = self.ParentWindow.VariablesGrid.YToRow(y)
Laurent@814:         message = None
Laurent@814:         element_type = self.ParentWindow.ElementType
Laurent@814:         try:
Edouard@1412:             values = eval(data)
Laurent@814:         except:
Laurent@814:             message = _("Invalid value \"%s\" for variable grid element")%data
Laurent@814:             values = None
Laurent@814:         if not isinstance(values, TupleType):
Laurent@814:             message = _("Invalid value \"%s\" for variable grid element")%data
Laurent@814:             values = None
Laurent@814:         if values is not None:
Laurent@814:             if col != wx.NOT_FOUND and row != wx.NOT_FOUND:
Laurent@814:                 colname = self.ParentWindow.Table.GetColLabelValue(col, False)
Laurent@814:                 if colname == "Location" and values[1] == "location":
Laurent@814:                     if not self.ParentWindow.Table.GetValueByName(row, "Edit"):
Laurent@814:                         message = _("Can't give a location to a function block instance")
Laurent@814:                     elif self.ParentWindow.Table.GetValueByName(row, "Class") not in ["Local", "Global"]:
Laurent@814:                         message = _("Can only give a location to local or global variables")
Laurent@814:                     else:
Laurent@814:                         location = values[0]
Laurent@814:                         variable_type = self.ParentWindow.Table.GetValueByName(row, "Type")
Laurent@814:                         base_type = self.ParentWindow.Controler.GetBaseType(variable_type)
Edouard@1412: 
laurent@830:                         if values[2] is not None:
laurent@830:                             base_location_type = self.ParentWindow.Controler.GetBaseType(values[2])
laurent@830:                             if values[2] != variable_type and base_type != base_location_type:
andrej@1581:                                 message = _("Incompatible data types between \"{a1}\" and \"{a2}\"").\
andrej@1581:                                           format(a1 = values[2], a2 = variable_type)
Edouard@1412: 
laurent@830:                         if message is None:
laurent@830:                             if not location.startswith("%"):
laurent@830:                                 if location[0].isdigit() and base_type != "BOOL":
laurent@830:                                     message = _("Incompatible size of data between \"%s\" and \"BOOL\"")%location
laurent@830:                                 elif location[0] not in LOCATIONDATATYPES:
laurent@830:                                     message = _("Unrecognized data size \"%s\"")%location[0]
laurent@830:                                 elif base_type not in LOCATIONDATATYPES[location[0]]:
andrej@1581:                                     message = _("Incompatible size of data between \"{a1}\" and \"{a2}\"").\
andrej@1581:                                               format(a1 = location, a2 = variable_type)
Laurent@814:                                 else:
Edouard@1412:                                     dialog = wx.SingleChoiceDialog(self.ParentWindow.ParentWindow.ParentWindow,
Edouard@1412:                                           _("Select a variable class:"), _("Variable class"),
andrej@1578:                                           [_("Input"), _("Output"), _("Memory")],
laurent@830:                                           wx.DEFAULT_DIALOG_STYLE|wx.OK|wx.CANCEL)
laurent@830:                                     if dialog.ShowModal() == wx.ID_OK:
laurent@830:                                         selected = dialog.GetSelection()
laurent@830:                                     else:
laurent@830:                                         selected = None
laurent@830:                                     dialog.Destroy()
laurent@830:                                     if selected is None:
laurent@830:                                         return
laurent@830:                                     if selected == 0:
laurent@830:                                         location = "%I" + location
laurent@830:                                     elif selected == 1:
laurent@830:                                         location = "%Q" + location
laurent@830:                                     else:
laurent@830:                                         location = "%M" + location
Edouard@1412: 
laurent@830:                             if message is None:
Laurent@814:                                 self.ParentWindow.Table.SetValue(row, col, location)
Laurent@814:                                 self.ParentWindow.Table.ResetView(self.ParentWindow.VariablesGrid)
Laurent@814:                                 self.ParentWindow.SaveValues()
Laurent@814:                 elif colname == "Initial Value" and values[1] == "Constant":
Laurent@814:                     if not self.ParentWindow.Table.GetValueByName(row, "Edit"):
Laurent@814:                         message = _("Can't set an initial value to a function block instance")
Laurent@814:                     else:
Laurent@814:                         self.ParentWindow.Table.SetValue(row, col, values[0])
Laurent@814:                         self.ParentWindow.Table.ResetView(self.ParentWindow.VariablesGrid)
Laurent@814:                         self.ParentWindow.SaveValues()
Edouard@1412:             elif (element_type not in ["config", "resource", "function"] and values[1] == "Global" and
Laurent@1140:                   self.ParentWindow.Filter in ["All", "Interface", "External"] or
Edouard@1416:                   element_type != "function" and values[1] in ["location", "NamedConstant"]):
Edouard@1416:                 if values[1] in  ["location","NamedConstant"]:
Laurent@814:                     var_name = values[3]
Laurent@814:                 else:
Laurent@814:                     var_name = values[0]
Laurent@814:                 tagname = self.ParentWindow.GetTagName()
Edouard@1417:                 dlg = wx.TextEntryDialog(
Edouard@1417:                     self.ParentWindow.ParentWindow.ParentWindow,
Edouard@1417:                     _("Confirm or change variable name"),
andrej@1578:                     _('Variable Drop'), var_name)
Edouard@1417:                 dlg.SetValue(var_name)
Edouard@1417:                 var_name = dlg.GetValue() if dlg.ShowModal() == wx.ID_OK else None
Edouard@1417:                 dlg.Destroy()
Edouard@1417:                 if var_name is None:
Edouard@1417:                     return
Edouard@1417:                 elif var_name.upper() in [name.upper()
Laurent@1171:                         for name in self.ParentWindow.Controler.\
Laurent@1171:                             GetProjectPouNames(self.ParentWindow.Debug)]:
Laurent@814:                     message = _("\"%s\" pou already exists!")%var_name
Edouard@1412:                 elif not var_name.upper() in [name.upper()
Laurent@1171:                         for name in self.ParentWindow.Controler.\
Laurent@1171:                             GetEditedElementVariables(tagname, self.ParentWindow.Debug)]:
Laurent@814:                     var_infos = self.ParentWindow.DefaultValue.copy()
Laurent@1347:                     var_infos.Name = var_name
Laurent@1347:                     var_infos.Type = values[2]
Edouard@1416:                     var_infos.Documentation = values[4]
Laurent@814:                     if values[1] == "location":
Laurent@1171:                         location = values[0]
Laurent@1171:                         if not location.startswith("%"):
Edouard@1412:                             dialog = wx.SingleChoiceDialog(self.ParentWindow.ParentWindow.ParentWindow,
Edouard@1412:                                   _("Select a variable class:"), _("Variable class"),
andrej@1578:                                   [_("Input"), _("Output"), _("Memory")],
Laurent@1171:                                   wx.DEFAULT_DIALOG_STYLE|wx.OK|wx.CANCEL)
Laurent@1171:                             if dialog.ShowModal() == wx.ID_OK:
Laurent@1171:                                 selected = dialog.GetSelection()
Laurent@1171:                             else:
Laurent@1171:                                 selected = None
Laurent@1171:                             dialog.Destroy()
Laurent@1171:                             if selected is None:
Laurent@1171:                                 return
Laurent@1171:                             if selected == 0:
Laurent@1171:                                 location = "%I" + location
Laurent@1171:                             elif selected == 1:
Laurent@1171:                                 location = "%Q" + location
Laurent@1171:                             else:
Laurent@1171:                                 location = "%M" + location
Laurent@1171:                         if element_type == "functionBlock":
Laurent@1171:                             configs = self.ParentWindow.Controler.GetProjectConfigNames(
Laurent@1171:                                                                 self.ParentWindow.Debug)
Laurent@1171:                             if len(configs) == 0:
Laurent@1171:                                 return
Edouard@1412:                             if not var_name.upper() in [name.upper()
Laurent@1171:                                 for name in self.ParentWindow.Controler.\
Laurent@1171:                                     GetConfigurationVariableNames(configs[0])]:
Laurent@1171:                                 self.ParentWindow.Controler.AddConfigurationGlobalVar(
Laurent@1171:                                     configs[0], values[2], var_name, location, "")
Laurent@1347:                             var_infos.Class = "External"
Laurent@1083:                         else:
Laurent@1171:                             if element_type == "program":
Laurent@1347:                                 var_infos.Class = "Local"
Laurent@1171:                             else:
Laurent@1347:                                 var_infos.Class = "Global"
Laurent@1347:                             var_infos.Location = location
Edouard@1416:                     elif values[1] == "NamedConstant":
Edouard@1416:                         if element_type in ["functionBlock","program"]:
Edouard@1416:                             var_infos.Class = "Local"
Edouard@1416:                             var_infos.InitialValue = values[0]
Edouard@1416:                         else :
Edouard@1416:                             return
Laurent@814:                     else:
Laurent@1347:                         var_infos.Class = "External"
Laurent@1347:                     var_infos.Number = len(self.ParentWindow.Values)
Laurent@814:                     self.ParentWindow.Values.append(var_infos)
Laurent@814:                     self.ParentWindow.SaveValues()
Laurent@814:                     self.ParentWindow.RefreshValues()
Edouard@1417:                 else:
Edouard@1417:                     message = _("\"%s\" element for this pou already exists!")%var_name
Edouard@1412: 
Laurent@814:         if message is not None:
Laurent@814:             wx.CallAfter(self.ShowMessage, message)
Edouard@1412: 
Laurent@814:     def ShowMessage(self, message):
Laurent@814:         message = wx.MessageDialog(self.ParentWindow, message, _("Error"), wx.OK|wx.ICON_ERROR)
Laurent@814:         message.ShowModal()
Laurent@814:         message.Destroy()
Laurent@814: 
Laurent@814: #-------------------------------------------------------------------------------
Laurent@814: #                               Variable Panel
Edouard@1412: #-------------------------------------------------------------------------------
Laurent@814: 
Laurent@814: class VariablePanel(wx.Panel):
Edouard@1412: 
Laurent@814:     def __init__(self, parent, window, controler, element_type, debug=False):
Laurent@814:         wx.Panel.__init__(self, parent, style=wx.TAB_TRAVERSAL)
Edouard@1412: 
Laurent@814:         self.MainSizer = wx.FlexGridSizer(cols=1, hgap=10, rows=2, vgap=0)
Laurent@814:         self.MainSizer.AddGrowableCol(0)
Laurent@814:         self.MainSizer.AddGrowableRow(1)
Edouard@1412: 
Laurent@814:         controls_sizer = wx.FlexGridSizer(cols=10, hgap=5, rows=1, vgap=5)
Laurent@814:         controls_sizer.AddGrowableCol(5)
Laurent@814:         controls_sizer.AddGrowableRow(0)
Laurent@814:         self.MainSizer.AddSizer(controls_sizer, border=5, flag=wx.GROW|wx.ALL)
Edouard@1412: 
Laurent@814:         self.ReturnTypeLabel = wx.StaticText(self, label=_('Return Type:'))
Laurent@814:         controls_sizer.AddWindow(self.ReturnTypeLabel, flag=wx.ALIGN_CENTER_VERTICAL)
Edouard@1412: 
Laurent@814:         self.ReturnType = wx.ComboBox(self,
Laurent@814:               size=wx.Size(145, -1), style=wx.CB_READONLY)
Laurent@814:         self.Bind(wx.EVT_COMBOBOX, self.OnReturnTypeChanged, self.ReturnType)
Laurent@814:         controls_sizer.AddWindow(self.ReturnType)
Edouard@1412: 
Laurent@814:         self.DescriptionLabel = wx.StaticText(self, label=_('Description:'))
Laurent@814:         controls_sizer.AddWindow(self.DescriptionLabel, flag=wx.ALIGN_CENTER_VERTICAL)
Edouard@1412: 
Laurent@814:         self.Description = wx.TextCtrl(self,
Laurent@814:               size=wx.Size(250, -1), style=wx.TE_PROCESS_ENTER)
Laurent@814:         self.Bind(wx.EVT_TEXT_ENTER, self.OnDescriptionChanged, self.Description)
Laurent@814:         self.Description.Bind(wx.EVT_KILL_FOCUS, self.OnDescriptionChanged)
Edouard@1412:         controls_sizer.AddWindow(self.Description)
Edouard@1412: 
Laurent@814:         class_filter_label = wx.StaticText(self, label=_('Class Filter:'))
Laurent@814:         controls_sizer.AddWindow(class_filter_label, flag=wx.ALIGN_CENTER_VERTICAL)
Edouard@1412: 
Edouard@1412:         self.ClassFilter = wx.ComboBox(self,
Laurent@814:               size=wx.Size(145, -1), style=wx.CB_READONLY)
Laurent@814:         self.Bind(wx.EVT_COMBOBOX, self.OnClassFilter, self.ClassFilter)
Laurent@814:         controls_sizer.AddWindow(self.ClassFilter)
Edouard@1412: 
Laurent@814:         for name, bitmap, help in [
Laurent@814:                 ("AddButton", "add_element", _("Add variable")),
Laurent@814:                 ("DeleteButton", "remove_element", _("Remove variable")),
Laurent@814:                 ("UpButton", "up", _("Move variable up")),
Laurent@814:                 ("DownButton", "down", _("Move variable down"))]:
Edouard@1412:             button = wx.lib.buttons.GenBitmapButton(self, bitmap=GetBitmap(bitmap),
Laurent@814:                   size=wx.Size(28, 28), style=wx.NO_BORDER)
Laurent@814:             button.SetToolTipString(help)
Laurent@814:             setattr(self, name, button)
Laurent@814:             controls_sizer.AddWindow(button)
Edouard@1412: 
andrej@1675:         self.VariablesGrid = CustomGrid(self, style=wx.VSCROLL | wx.HSCROLL)
Laurent@814:         self.VariablesGrid.SetDropTarget(VariableDropTarget(self))
Edouard@1412:         self.VariablesGrid.Bind(wx.grid.EVT_GRID_CELL_CHANGE,
Laurent@814:               self.OnVariablesGridCellChange)
Edouard@1412:         self.VariablesGrid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK,
Laurent@814:               self.OnVariablesGridCellLeftClick)
Edouard@1412:         self.VariablesGrid.Bind(wx.grid.EVT_GRID_EDITOR_SHOWN,
Laurent@814:               self.OnVariablesGridEditorShown)
Laurent@814:         self.MainSizer.AddWindow(self.VariablesGrid, flag=wx.GROW)
Edouard@1412: 
Laurent@814:         self.SetSizer(self.MainSizer)
Edouard@1412: 
Laurent@814:         self.ParentWindow = window
Laurent@814:         self.Controler = controler
Laurent@814:         self.ElementType = element_type
Laurent@814:         self.Debug = debug
Edouard@1412: 
Laurent@814:         self.RefreshHighlightsTimer = wx.Timer(self, -1)
Edouard@1412:         self.Bind(wx.EVT_TIMER, self.OnRefreshHighlightsTimer,
Laurent@814:               self.RefreshHighlightsTimer)
Edouard@1412: 
Laurent@814:         self.Filter = "All"
Laurent@814:         self.FilterChoices = []
Laurent@814:         self.FilterChoiceTransfer = GetFilterChoiceTransfer()
Edouard@1412: 
Edouard@1412:         self.DefaultValue = _VariableInfos("", "", "", "", "", True, "", DefaultType, ([], []), 0)
Edouard@1412: 
Laurent@814:         if element_type in ["config", "resource"]:
Laurent@814:             self.DefaultTypes = {"All" : "Global"}
Laurent@814:         else:
Laurent@814:             self.DefaultTypes = {"All" : "Local", "Interface" : "Input", "Variables" : "Local"}
Laurent@814: 
Laurent@814:         if element_type in ["config", "resource"] \
Laurent@814:         or element_type in ["program", "transition", "action"]:
Laurent@814:             # this is an element that can have located variables
Laurent@814:             self.Table = VariableTable(self, [], GetVariableTableColnames(True))
Laurent@814: 
Laurent@814:             if element_type in ["config", "resource"]:
Laurent@814:                 self.FilterChoices = ["All", "Global"]#,"Access"]
Laurent@814:             else:
Laurent@814:                 self.FilterChoices = ["All",
Laurent@814:                                         "Interface", "   Input", "   Output", "   InOut", "   External",
Laurent@814:                                         "Variables", "   Local", "   Temp"]#,"Access"]
Laurent@814: 
Laurent@814:             # these condense the ColAlignements list
Laurent@814:             l = wx.ALIGN_LEFT
Edouard@1412:             c = wx.ALIGN_CENTER
Laurent@814: 
Laurent@814:             #                      Num  Name    Class   Type    Loc     Init    Option   Doc
surkovsv93@1654:             self.ColSizes       = [40,  80,     100,    80,     110,     120,    100,     160]
Laurent@814:             self.ColAlignements = [c,   l,      l,      l,      l,      l,      l,       l]
surkovsv93@1654:             self.ColFixedSizeFlag=[True,False,  True,   False,  True,   True,   True,    False]
Laurent@814: 
Laurent@814:         else:
Laurent@814:             # this is an element that cannot have located variables
Laurent@814:             self.Table = VariableTable(self, [], GetVariableTableColnames(False))
Laurent@814: 
Laurent@814:             if element_type == "function":
Laurent@814:                 self.FilterChoices = ["All",
Laurent@814:                                         "Interface", "   Input", "   Output", "   InOut",
Laurent@814:                                         "Variables", "   Local"]
Laurent@814:             else:
Laurent@814:                 self.FilterChoices = ["All",
Laurent@814:                                         "Interface", "   Input", "   Output", "   InOut", "   External",
Laurent@814:                                         "Variables", "   Local", "   Temp"]
Laurent@814: 
Laurent@814:             # these condense the ColAlignements list
Laurent@814:             l = wx.ALIGN_LEFT
Edouard@1412:             c = wx.ALIGN_CENTER
Laurent@814: 
Laurent@814:             #                      Num  Name    Class   Type    Init    Option   Doc
surkovsv93@1654:             self.ColSizes       = [40,  80,     100,    80,     120,    100,     160]
Laurent@814:             self.ColAlignements = [c,   l,      l,      l,      l,      l,       l]
surkovsv93@1654:             self.ColFixedSizeFlag=[True,False,  True,   False,  True,   True,    False]
Edouard@1412: 
andrej@1675:         self.PanelWidthMin = sum(self.ColSizes)
andrej@1675:         
Laurent@1342:         self.ElementType = element_type
Laurent@1342:         self.BodyType = None
Edouard@1412: 
Laurent@814:         for choice in self.FilterChoices:
Laurent@814:             self.ClassFilter.Append(_(choice))
Laurent@814: 
Laurent@814:         reverse_transfer = {}
Laurent@814:         for filter, choice in self.FilterChoiceTransfer.items():
Laurent@814:             reverse_transfer[choice] = filter
Laurent@814:         self.ClassFilter.SetStringSelection(_(reverse_transfer[self.Filter]))
Laurent@814:         self.RefreshTypeList()
Laurent@814: 
Laurent@814:         self.VariablesGrid.SetTable(self.Table)
Laurent@814:         self.VariablesGrid.SetButtons({"Add": self.AddButton,
Laurent@814:                                        "Delete": self.DeleteButton,
Laurent@814:                                        "Up": self.UpButton,
Laurent@814:                                        "Down": self.DownButton})
Laurent@814:         self.VariablesGrid.SetEditable(not self.Debug)
Edouard@1412: 
Laurent@814:         def _AddVariable(new_row):
Laurent@1128:             if new_row > 0:
Laurent@1128:                 row_content = self.Values[new_row - 1].copy()
Edouard@1412: 
Laurent@1347:                 result = VARIABLE_NAME_SUFFIX_MODEL.search(row_content.Name)
Laurent@1128:                 if result is not None:
Laurent@1347:                     name = row_content.Name[:result.start(1)]
Laurent@1128:                     suffix = result.group(1)
Laurent@1128:                     if suffix != "":
Laurent@1128:                         start_idx = int(suffix)
Laurent@1122:                     else:
Laurent@1122:                         start_idx = 0
Laurent@814:                 else:
Laurent@1347:                     name = row_content.Name
Laurent@1128:                     start_idx = 0
Laurent@1175:             else:
Edouard@1184:                 row_content = None
Edouard@1184:                 start_idx = 0
Edouard@1184:                 name = "LocalVar"
Edouard@1412: 
Edouard@1412:             if row_content is not None and row_content.Edit:
Laurent@1175:                 row_content = self.Values[new_row - 1].copy()
Laurent@1128:             else:
Laurent@1128:                 row_content = self.DefaultValue.copy()
Laurent@1128:                 if self.Filter in self.DefaultTypes:
Laurent@1347:                     row_content.Class = self.DefaultTypes[self.Filter]
Laurent@814:                 else:
Laurent@1347:                     row_content.Class = self.Filter
Edouard@1412: 
Laurent@1347:             row_content.Name = self.Controler.GenerateNewName(
Laurent@1175:                     self.TagName, None, name + "%d", start_idx)
Edouard@1412: 
Laurent@1128:             if self.Filter == "All" and len(self.Values) > 0:
Laurent@1128:                 self.Values.insert(new_row, row_content)
Laurent@1128:             else:
Laurent@1128:                 self.Values.append(row_content)
Laurent@1128:                 new_row = self.Table.GetNumberRows()
Laurent@1128:             self.SaveValues()
Edouard@1422:             if self.ElementType == "resource":
Edouard@1422:                 self.ParentWindow.RefreshView(variablepanel = False)
Laurent@1128:             self.RefreshValues()
Laurent@1128:             return new_row
Laurent@814:         setattr(self.VariablesGrid, "_AddRow", _AddVariable)
Edouard@1412: 
Laurent@814:         def _DeleteVariable(row):
andrej@1510:             if _GetRowEdit(row):
Laurent@814:                 self.Values.remove(self.Table.GetRow(row))
Laurent@814:                 self.SaveValues()
Laurent@1361:                 if self.ElementType == "resource":
Laurent@1361:                     self.ParentWindow.RefreshView(variablepanel = False)
Laurent@814:                 self.RefreshValues()
Laurent@814:         setattr(self.VariablesGrid, "_DeleteRow", _DeleteVariable)
Edouard@1412: 
Laurent@814:         def _MoveVariable(row, move):
Laurent@1128:             if self.Filter == "All":
Laurent@814:                 new_row = max(0, min(row + move, len(self.Values) - 1))
Laurent@814:                 if new_row != row:
Laurent@814:                     self.Values.insert(new_row, self.Values.pop(row))
Laurent@814:                     self.SaveValues()
Laurent@814:                     self.RefreshValues()
Laurent@814:                 return new_row
Laurent@814:             return row
Laurent@814:         setattr(self.VariablesGrid, "_MoveRow", _MoveVariable)
Edouard@1412: 
andrej@1510:         def _GetRowEdit(row):
andrej@1510:             row_edit = False
andrej@1510:             if self:
andrej@1510:                 row_edit = self.Table.GetValueByName(row, "Edit")
andrej@1510:                 bodytype = self.Controler.GetEditedElementBodyType(self.TagName)
andrej@1510:                 row_edit = row_edit or (bodytype in ["ST", "IL"])
andrej@1510:             return row_edit
andrej@1510: 
Laurent@814:         def _RefreshButtons():
Laurent@814:             if self:
Laurent@814:                 table_length = len(self.Table.data)
Laurent@814:                 row_class = None
Laurent@814:                 row_edit = True
Laurent@814:                 row = 0
Laurent@814:                 if table_length > 0:
Laurent@814:                     row = self.VariablesGrid.GetGridCursorRow()
andrej@1510:                     row_edit = _GetRowEdit(row)
Laurent@1128:                 self.AddButton.Enable(not self.Debug)
Laurent@1128:                 self.DeleteButton.Enable(not self.Debug and (table_length > 0 and row_edit))
Laurent@1128:                 self.UpButton.Enable(not self.Debug and (table_length > 0 and row > 0 and self.Filter == "All"))
Laurent@1128:                 self.DownButton.Enable(not self.Debug and (table_length > 0 and row < table_length - 1 and self.Filter == "All"))
Laurent@814:         setattr(self.VariablesGrid, "RefreshButtons", _RefreshButtons)
Edouard@1412: 
andrej@1675:         panel_width = window.Parent.ScreenRect.Width - 35
andrej@1675:         if panel_width > self.PanelWidthMin:
andrej@1675:             stretch_cols_width = panel_width
andrej@1675:             stretch_cols_sum = 0            
andrej@1675:             for col in range(len(self.ColFixedSizeFlag)):
andrej@1675:                 if self.ColFixedSizeFlag[col]:
andrej@1675:                     stretch_cols_width -= self.ColSizes[col]
andrej@1675:                 else:
andrej@1675:                     stretch_cols_sum += self.ColSizes[col]
andrej@1675: 
Laurent@814:         self.VariablesGrid.SetRowLabelSize(0)
Laurent@814:         for col in range(self.Table.GetNumberCols()):
Laurent@814:             attr = wx.grid.GridCellAttr()
Laurent@814:             attr.SetAlignment(self.ColAlignements[col], wx.ALIGN_CENTRE)
Laurent@814:             self.VariablesGrid.SetColAttr(col, attr)
Laurent@814:             self.VariablesGrid.SetColMinimalWidth(col, self.ColSizes[col])
andrej@1675:             if (panel_width > self.PanelWidthMin) and not self.ColFixedSizeFlag[col]:
surkovsv93@1654:                 self.VariablesGrid.SetColSize(col, int((float(self.ColSizes[col])/stretch_cols_sum)*stretch_cols_width))
surkovsv93@1654:             else:
surkovsv93@1654:                 self.VariablesGrid.SetColSize(col, self.ColSizes[col])
Edouard@1412: 
Laurent@814:     def __del__(self):
Laurent@814:         self.RefreshHighlightsTimer.Stop()
Edouard@1412: 
Laurent@814:     def SetTagName(self, tagname):
Laurent@814:         self.TagName = tagname
Laurent@1342:         self.BodyType = self.Controler.GetEditedElementBodyType(self.TagName)
Edouard@1412: 
Laurent@814:     def GetTagName(self):
Laurent@814:         return self.TagName
Edouard@1412: 
Laurent@814:     def IsFunctionBlockType(self, name):
Edouard@1412:         if (isinstance(name, TupleType) or
Laurent@1380:             self.ElementType != "function" and self.BodyType in ["ST", "IL"]):
Laurent@814:             return False
Laurent@814:         else:
Laurent@1325:             return self.Controler.GetBlockType(name, debug=self.Debug) is not None
Edouard@1412: 
Laurent@814:     def RefreshView(self):
Laurent@814:         self.PouNames = self.Controler.GetProjectPouNames(self.Debug)
Laurent@814:         returnType = None
Laurent@814:         description = None
Edouard@1412: 
Laurent@814:         words = self.TagName.split("::")
Laurent@814:         if self.ElementType == "config":
Laurent@814:             self.Values = self.Controler.GetConfigurationGlobalVars(words[1], self.Debug)
Laurent@814:         elif self.ElementType == "resource":
Laurent@814:             self.Values = self.Controler.GetConfigurationResourceGlobalVars(words[1], words[2], self.Debug)
Laurent@814:         else:
Laurent@814:             if self.ElementType == "function":
Laurent@814:                 self.ReturnType.Clear()
Laurent@853:                 for data_type in self.Controler.GetDataTypes(self.TagName, debug=self.Debug):
Laurent@853:                     self.ReturnType.Append(data_type)
Laurent@1347:                 returnType = self.Controler.GetEditedElementInterfaceReturnType(self.TagName, debug=self.Debug)
Laurent@814:             description = self.Controler.GetPouDescription(words[1])
Laurent@1347:             self.Values = self.Controler.GetEditedElementInterfaceVars(self.TagName, debug=self.Debug)
Edouard@1412: 
Laurent@814:         if returnType is not None:
Laurent@814:             self.ReturnType.SetStringSelection(returnType)
Laurent@814:             self.ReturnType.Enable(not self.Debug)
Laurent@814:             self.ReturnTypeLabel.Show()
Laurent@814:             self.ReturnType.Show()
Laurent@814:         else:
Laurent@814:             self.ReturnType.Enable(False)
Laurent@814:             self.ReturnTypeLabel.Hide()
Laurent@814:             self.ReturnType.Hide()
Edouard@1412: 
Laurent@814:         if description is not None:
Laurent@814:             self.Description.SetValue(description)
Laurent@814:             self.Description.Enable(not self.Debug)
Laurent@814:             self.DescriptionLabel.Show()
Laurent@814:             self.Description.Show()
Laurent@814:         else:
Laurent@814:             self.Description.Enable(False)
Laurent@814:             self.DescriptionLabel.Hide()
Laurent@814:             self.Description.Hide()
Edouard@1412: 
Laurent@814:         self.RefreshValues()
Laurent@814:         self.VariablesGrid.RefreshButtons()
Laurent@814:         self.MainSizer.Layout()
Edouard@1412: 
Laurent@814:     def OnReturnTypeChanged(self, event):
Laurent@814:         words = self.TagName.split("::")
Laurent@814:         self.Controler.SetPouInterfaceReturnType(words[1], self.ReturnType.GetStringSelection())
Laurent@814:         self.Controler.BufferProject()
Laurent@814:         self.ParentWindow.RefreshView(variablepanel = False)
Laurent@814:         self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, POUINSTANCEVARIABLESPANEL, LIBRARYTREE)
Laurent@814:         event.Skip()
Edouard@1412: 
Laurent@814:     def OnDescriptionChanged(self, event):
Laurent@814:         words = self.TagName.split("::")
Laurent@814:         old_description = self.Controler.GetPouDescription(words[1])
Laurent@814:         new_description = self.Description.GetValue()
Laurent@814:         if new_description != old_description:
Laurent@814:             self.Controler.SetPouDescription(words[1], new_description)
Laurent@1009:             self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, PAGETITLES, POUINSTANCEVARIABLESPANEL, LIBRARYTREE)
Laurent@814:         event.Skip()
Edouard@1412: 
Laurent@814:     def OnClassFilter(self, event):
Laurent@814:         self.Filter = self.FilterChoiceTransfer[VARIABLE_CHOICES_DICT[self.ClassFilter.GetStringSelection()]]
Laurent@814:         self.RefreshTypeList()
Laurent@814:         self.RefreshValues()
Laurent@814:         self.VariablesGrid.RefreshButtons()
Laurent@814:         event.Skip()
Laurent@814: 
Laurent@814:     def RefreshTypeList(self):
Laurent@814:         if self.Filter == "All":
Laurent@814:             self.ClassList = [self.FilterChoiceTransfer[choice] for choice in self.FilterChoices if self.FilterChoiceTransfer[choice] not in ["All","Interface","Variables"]]
Laurent@814:         elif self.Filter == "Interface":
Laurent@814:             self.ClassList = ["Input","Output","InOut","External"]
Laurent@814:         elif self.Filter == "Variables":
Laurent@814:             self.ClassList = ["Local","Temp"]
Laurent@814:         else:
Laurent@814:             self.ClassList = [self.Filter]
Laurent@814: 
andrej@1658:     def ShowErrorMessage(self, message):
andrej@1658:         dialog = wx.MessageDialog(self, message, _("Error"), wx.OK|wx.ICON_ERROR)
andrej@1658:         dialog.ShowModal()
andrej@1658:         dialog.Destroy()
andrej@1658:             
Laurent@814:     def OnVariablesGridCellChange(self, event):
Laurent@814:         row, col = event.GetRow(), event.GetCol()
Laurent@814:         colname = self.Table.GetColLabelValue(col, False)
Laurent@814:         value = self.Table.GetValue(row, col)
Laurent@814:         message = None
Edouard@1412: 
Laurent@814:         if colname == "Name" and value != "":
Laurent@814:             if not TestIdentifier(value):
Laurent@814:                 message = _("\"%s\" is not a valid identifier!") % value
Laurent@814:             elif value.upper() in IEC_KEYWORDS:
Laurent@814:                 message = _("\"%s\" is a keyword. It can't be used!") % value
Laurent@814:             elif value.upper() in self.PouNames:
Laurent@814:                 message = _("A POU named \"%s\" already exists!") % value
Laurent@1347:             elif value.upper() in [var.Name.upper() for var in self.Values if var != self.Table.data[row]]:
Laurent@814:                 message = _("A variable with \"%s\" as name already exists in this pou!") % value
Laurent@814:             else:
Laurent@814:                 self.SaveValues(False)
Laurent@814:                 old_value = self.Table.GetOldValue()
Laurent@814:                 if old_value != "":
Laurent@814:                     self.Controler.UpdateEditedElementUsedVariable(self.TagName, old_value, value)
Laurent@814:                 self.Controler.BufferProject()
Edouard@1184:                 wx.CallAfter(self.ParentWindow.RefreshView, False)
Laurent@1016:                 self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, PAGETITLES, POUINSTANCEVARIABLESPANEL, LIBRARYTREE)
Laurent@814:         else:
Laurent@814:             self.SaveValues()
Laurent@814:             if colname == "Class":
surkovsv93@1668:                 self.ClearLocation(row, col, value)
surkovsv93@1668:                 wx.CallAfter(self.ParentWindow.RefreshView)
Laurent@814:             elif colname == "Location":
Laurent@814:                 wx.CallAfter(self.ParentWindow.RefreshView)
Edouard@1412: 
Laurent@814:         if message is not None:
andrej@1658:             wx.CallAfter(self.ShowErrorMessage, message)
andrej@1658:             event.Veto()            
Laurent@814:         else:
Laurent@814:             event.Skip()
Edouard@1412: 
surkovsv93@1668:     def ClearLocation(self, row, col, value):
surkovsv93@1668:         if self.Values[row].Location != '':
surkovsv93@1668:             if self.Table.GetColLabelValue(col, False) == 'Class' and value not in ["Local", "Global"] or \
andrej@1676:                self.Table.GetColLabelValue(col, False) == 'Type' and not self.Controler.IsLocatableType(value):
surkovsv93@1668:                 self.Values[row].Location = ''
andrej@1676:                 self.RefreshValues()
andrej@1676:                 self.SaveValues()
surkovsv93@1668: 
Edouard@1414:     def BuildStdIECTypesMenu(self,type_menu):
Laurent@814:             # build a submenu containing standard IEC types
Laurent@814:             base_menu = wx.Menu(title='')
Laurent@814:             for base_type in self.Controler.GetBaseTypes():
Laurent@814:                 new_id = wx.NewId()
Edouard@1414:                 base_menu.Append(help='', id=new_id, kind=wx.ITEM_NORMAL, text=base_type)
Laurent@814:                 self.Bind(wx.EVT_MENU, self.GetVariableTypeFunction(base_type), id=new_id)
Laurent@814: 
Laurent@814:             type_menu.AppendMenu(wx.NewId(), _("Base Types"), base_menu)
Laurent@814: 
Edouard@1414:     def BuildUserTypesMenu(self,type_menu):
Laurent@814:             # build a submenu containing user-defined types
Laurent@814:             datatype_menu = wx.Menu(title='')
Laurent@863:             datatypes = self.Controler.GetDataTypes(basetypes = False, confnodetypes = False)
Laurent@814:             for datatype in datatypes:
Laurent@814:                 new_id = wx.NewId()
Edouard@1414:                 datatype_menu.Append(help='', id=new_id, kind=wx.ITEM_NORMAL, text=datatype)
Laurent@814:                 self.Bind(wx.EVT_MENU, self.GetVariableTypeFunction(datatype), id=new_id)
Laurent@814: 
Laurent@814:             type_menu.AppendMenu(wx.NewId(), _("User Data Types"), datatype_menu)
Edouard@1412: 
Edouard@1414:     def BuildLibsTypesMenu(self, type_menu):
Edouard@1414:         for category in self.Controler.GetConfNodeDataTypes():
Edouard@1414:             if len(category["list"]) > 0:
Edouard@1414:                 # build a submenu containing confnode types
Edouard@1414:                 confnode_datatype_menu = wx.Menu(title='')
Edouard@1414:                 for datatype in category["list"]:
Edouard@1414:                     new_id = wx.NewId()
Edouard@1414:                     confnode_datatype_menu.Append(help='', id=new_id, kind=wx.ITEM_NORMAL, text=datatype)
Edouard@1414:                     self.Bind(wx.EVT_MENU, self.GetVariableTypeFunction(datatype), id=new_id)
Edouard@1414: 
Edouard@1414:                 type_menu.AppendMenu(wx.NewId(), category["name"], confnode_datatype_menu)
Edouard@1414: 
Edouard@1414:     def BuildProjectTypesMenu(self, type_menu, classtype):
Edouard@1414:         # build a submenu containing function block types
Edouard@1414:         bodytype = self.Controler.GetEditedElementBodyType(self.TagName)
Edouard@1414:         pouname, poutype = self.Controler.GetEditedElementType(self.TagName)
Edouard@1414:         if classtype in ["Input", "Output", "InOut", "External", "Global"] or \
Edouard@1414:         poutype != "function" and bodytype in ["ST", "IL"]:
Edouard@1414:             functionblock_menu = wx.Menu(title='')
Edouard@1414:             fbtypes = self.Controler.GetFunctionBlockTypes(self.TagName)
Edouard@1414:             for functionblock_type in fbtypes:
Edouard@1414:                 new_id = wx.NewId()
Edouard@1414:                 functionblock_menu.Append(help='', id=new_id, kind=wx.ITEM_NORMAL, text=functionblock_type)
Edouard@1414:                 self.Bind(wx.EVT_MENU, self.GetVariableTypeFunction(functionblock_type), id=new_id)
Edouard@1414: 
Edouard@1414:             type_menu.AppendMenu(wx.NewId(), _("Function Block Types"), functionblock_menu)
Edouard@1414: 
Edouard@1414:     def BuildArrayTypesMenu(self, type_menu):
Edouard@1414:         new_id = wx.NewId()
Edouard@1414:         type_menu.Append(help='', id=new_id, kind=wx.ITEM_NORMAL, text=_("Array"))
Edouard@1414:         self.Bind(wx.EVT_MENU, self.VariableArrayTypeFunction, id=new_id)
Edouard@1414: 
Edouard@1414:     def OnVariablesGridEditorShown(self, event):
Edouard@1414:         row, col = event.GetRow(), event.GetCol()
Edouard@1414: 
Edouard@1414:         label_value = self.Table.GetColLabelValue(col, False)
Edouard@1414:         if label_value == "Type":
surkovsv93@1668:             old_value = self.Values[row].Type
Laurent@814:             classtype = self.Table.GetValueByName(row, "Class")
Edouard@1414:             type_menu = wx.Menu(title='')   # the root menu
Edouard@1414: 
Edouard@1414:             self.BuildStdIECTypesMenu(type_menu)
Edouard@1414: 
Edouard@1414:             self.BuildUserTypesMenu(type_menu)
Edouard@1414: 
Edouard@1414:             self.BuildLibsTypesMenu(type_menu)
Edouard@1414: 
Edouard@1414:             self.BuildProjectTypesMenu(type_menu,classtype)
Edouard@1414: 
Edouard@1414:             self.BuildArrayTypesMenu(type_menu)
Laurent@814: 
Laurent@814:             rect = self.VariablesGrid.BlockToDeviceRect((row, col), (row, col))
Laurent@814:             corner_x = rect.x + rect.width
Laurent@814:             corner_y = rect.y + self.VariablesGrid.GetColLabelSize()
Laurent@814: 
Laurent@814:             # pop up this new menu
Laurent@814:             self.VariablesGrid.PopupMenuXY(type_menu, corner_x, corner_y)
Laurent@814:             type_menu.Destroy()
Laurent@814:             event.Veto()
surkovsv93@1668:             value = self.Values[row].Type
surkovsv93@1668:             if old_value != value:
surkovsv93@1668:                 self.ClearLocation(row, col, value)
Laurent@814:         else:
Laurent@814:             event.Skip()
Edouard@1412: 
Laurent@814:     def GetVariableTypeFunction(self, base_type):
Laurent@814:         def VariableTypeFunction(event):
Laurent@814:             row = self.VariablesGrid.GetGridCursorRow()
Laurent@814:             self.Table.SetValueByName(row, "Type", base_type)
Laurent@814:             self.Table.ResetView(self.VariablesGrid)
Laurent@814:             self.SaveValues(False)
Laurent@814:             self.ParentWindow.RefreshView(variablepanel = False)
Laurent@814:             self.Controler.BufferProject()
Laurent@1009:             self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, PAGETITLES, POUINSTANCEVARIABLESPANEL, LIBRARYTREE)
Laurent@814:         return VariableTypeFunction
Edouard@1412: 
Laurent@814:     def VariableArrayTypeFunction(self, event):
Laurent@814:         row = self.VariablesGrid.GetGridCursorRow()
Edouard@1412:         dialog = ArrayTypeDialog(self,
Edouard@1412:                                  self.Controler.GetDataTypes(self.TagName),
Laurent@814:                                  self.Table.GetValueByName(row, "Type"))
Laurent@814:         if dialog.ShowModal() == wx.ID_OK:
Laurent@814:             self.Table.SetValueByName(row, "Type", dialog.GetValue())
Laurent@814:             self.Table.ResetView(self.VariablesGrid)
Laurent@814:             self.SaveValues(False)
Laurent@814:             self.ParentWindow.RefreshView(variablepanel = False)
Laurent@814:             self.Controler.BufferProject()
Laurent@1009:             self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, PAGETITLES, POUINSTANCEVARIABLESPANEL, LIBRARYTREE)
Laurent@814:         dialog.Destroy()
Edouard@1412: 
Laurent@814:     def OnVariablesGridCellLeftClick(self, event):
Laurent@814:         row = event.GetRow()
Laurent@814:         if not self.Debug and (event.GetCol() == 0 and self.Table.GetValueByName(row, "Edit")):
Laurent@814:             var_name = self.Table.GetValueByName(row, "Name")
Laurent@814:             var_class = self.Table.GetValueByName(row, "Class")
Laurent@814:             var_type = self.Table.GetValueByName(row, "Type")
Laurent@814:             data = wx.TextDataObject(str((var_name, var_class, var_type, self.TagName)))
Laurent@814:             dragSource = wx.DropSource(self.VariablesGrid)
Laurent@814:             dragSource.SetData(data)
Laurent@814:             dragSource.DoDragDrop()
Laurent@814:         event.Skip()
Edouard@1412: 
Laurent@814:     def RefreshValues(self):
Laurent@814:         data = []
Laurent@814:         for num, variable in enumerate(self.Values):
Laurent@1347:             if variable.Class in self.ClassList:
Laurent@1347:                 variable.Number = num + 1
Laurent@814:                 data.append(variable)
Laurent@814:         self.Table.SetData(data)
Laurent@814:         self.Table.ResetView(self.VariablesGrid)
Edouard@1412: 
Laurent@814:     def SaveValues(self, buffer = True):
Laurent@814:         words = self.TagName.split("::")
Laurent@814:         if self.ElementType == "config":
Laurent@814:             self.Controler.SetConfigurationGlobalVars(words[1], self.Values)
Laurent@814:         elif self.ElementType == "resource":
Laurent@814:             self.Controler.SetConfigurationResourceGlobalVars(words[1], words[2], self.Values)
Laurent@814:         else:
Laurent@814:             if self.ReturnType.IsEnabled():
Laurent@814:                 self.Controler.SetPouInterfaceReturnType(words[1], self.ReturnType.GetStringSelection())
Laurent@814:             self.Controler.SetPouInterfaceVars(words[1], self.Values)
Laurent@814:         if buffer:
Laurent@814:             self.Controler.BufferProject()
Edouard@1412:             self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, PAGETITLES, POUINSTANCEVARIABLESPANEL, LIBRARYTREE)
Laurent@814: 
Laurent@814: #-------------------------------------------------------------------------------
Laurent@814: #                        Highlights showing functions
Laurent@814: #-------------------------------------------------------------------------------
Laurent@814: 
Laurent@814:     def OnRefreshHighlightsTimer(self, event):
Laurent@814:         self.Table.ResetView(self.VariablesGrid)
Laurent@814:         event.Skip()
Laurent@814: 
Laurent@814:     def AddVariableHighlight(self, infos, highlight_type):
Laurent@814:         if isinstance(infos[0], TupleType):
Laurent@814:             for i in xrange(*infos[0]):
Laurent@814:                 self.Table.AddHighlight((i,) + infos[1:], highlight_type)
Laurent@814:             cell_visible = infos[0][0]
Laurent@814:         else:
Laurent@814:             self.Table.AddHighlight(infos, highlight_type)
Laurent@814:             cell_visible = infos[0]
Laurent@814:         colnames = [colname.lower() for colname in self.Table.colnames]
Laurent@814:         self.VariablesGrid.MakeCellVisible(cell_visible, colnames.index(infos[1]))
Laurent@814:         self.RefreshHighlightsTimer.Start(int(REFRESH_HIGHLIGHT_PERIOD * 1000), oneShot=True)
Laurent@814: 
Laurent@814:     def RemoveVariableHighlight(self, infos, highlight_type):
Laurent@814:         if isinstance(infos[0], TupleType):
Laurent@814:             for i in xrange(*infos[0]):
Laurent@814:                 self.Table.RemoveHighlight((i,) + infos[1:], highlight_type)
Laurent@814:         else:
Laurent@814:             self.Table.RemoveHighlight(infos, highlight_type)
Laurent@814:         self.RefreshHighlightsTimer.Start(int(REFRESH_HIGHLIGHT_PERIOD * 1000), oneShot=True)
Laurent@814: 
Laurent@814:     def ClearHighlights(self, highlight_type=None):
Laurent@814:         self.Table.ClearHighlights(highlight_type)
Laurent@814:         self.Table.ResetView(self.VariablesGrid)