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