Laurent@814: #!/usr/bin/env python Laurent@814: # -*- coding: utf-8 -*- Laurent@814: Laurent@814: #This file is part of PLCOpenEditor, a library implementing an IEC 61131-3 editor Laurent@814: #based on the plcopen standard. Laurent@814: # Laurent@814: #Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD Laurent@814: # Laurent@814: #See COPYING file for copyrights details. Laurent@814: # Laurent@814: #This library is free software; you can redistribute it and/or Laurent@814: #modify it under the terms of the GNU General Public Laurent@814: #License as published by the Free Software Foundation; either Laurent@814: #version 2.1 of the License, or (at your option) any later version. Laurent@814: # Laurent@814: #This library is distributed in the hope that it will be useful, Laurent@814: #but WITHOUT ANY WARRANTY; without even the implied warranty of Laurent@814: #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Laurent@814: #General Public License for more details. Laurent@814: # Laurent@814: #You should have received a copy of the GNU General Public Laurent@814: #License along with this library; if not, write to the Free Software Laurent@814: #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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: Laurent@814: from plcopen.structures import LOCATIONDATATYPES, TestIdentifier, IEC_KEYWORDS 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@814: Laurent@814: #------------------------------------------------------------------------------- Laurent@814: # Helpers Laurent@814: #------------------------------------------------------------------------------- Laurent@814: Laurent@814: def AppendMenu(parent, help, id, kind, text): Laurent@814: if wx.VERSION >= (2, 6, 0): Laurent@814: parent.Append(help=help, id=id, kind=kind, text=text) Laurent@814: else: Laurent@814: parent.Append(helpString=help, id=id, kind=kind, item=text) Laurent@814: Laurent@814: [TITLE, EDITORTOOLBAR, FILEMENU, EDITMENU, DISPLAYMENU, PROJECTTREE, Laurent@814: POUINSTANCEVARIABLESPANEL, LIBRARYTREE, SCALING, PAGETITLES Laurent@814: ] = 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 Laurent@814: return {_("All"): _("All"), _("Interface"): _("Interface"), Laurent@814: _(" 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@814: Laurent@814: #------------------------------------------------------------------------------- Laurent@814: # Variables Panel Table Laurent@814: #------------------------------------------------------------------------------- Laurent@814: Laurent@814: class VariableTable(CustomTable): Laurent@814: 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 Laurent@814: Laurent@814: def GetValue(self, row, col): Laurent@814: if row < self.GetNumberRows(): Laurent@814: if col == 0: Laurent@814: return self.data[row]["Number"] Laurent@814: colname = self.GetColLabelValue(col, False) Laurent@814: value = self.data[row].get(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 Laurent@814: 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@814: self.old_value = 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@814: self.SetValueByName(row, "Initial Value", "") Laurent@814: elif colname == "Option": Laurent@814: value = OPTIONS_DICT[value] Laurent@814: self.data[row][colname] = value Laurent@814: Laurent@814: def GetOldValue(self): Laurent@814: return self.old_value Laurent@814: 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) Laurent@814: elif col != 0 and self.GetValueByName(row, "Edit"): Laurent@814: grid.SetReadOnly(row, col, False) Laurent@814: if colname == "Name": Laurent@814: if self.Parent.PouIsUsed and var_class in ["Input", "Output", "InOut"]: Laurent@814: grid.SetReadOnly(row, col, True) Laurent@814: else: Laurent@814: editor = wx.grid.GridCellTextEditor() Laurent@814: 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@814: 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@814: if len(self.Parent.ClassList) == 1 or self.Parent.PouIsUsed and var_class in ["Input", "Output", "InOut"]: Laurent@814: grid.SetReadOnly(row, col, True) Laurent@814: else: Laurent@814: editor = wx.grid.GridCellChoiceEditor() Laurent@814: excluded = [] Laurent@814: if self.Parent.PouIsUsed: Laurent@814: excluded.extend(["Input","Output","InOut"]) 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) Laurent@814: Laurent@814: grid.SetCellEditor(row, col, editor) Laurent@814: grid.SetCellRenderer(row, col, renderer) Laurent@814: 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 Laurent@814: #------------------------------------------------------------------------------- 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. Laurent@814: Laurent@814: The drag source should be a TextDataObject containing a Python tuple like: Laurent@814: ('%ID0.0.0', 'location', 'REAL') Laurent@814: 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 Laurent@814: 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) Laurent@814: row = self.ParentWindow.VariablesGrid.YToRow(y - self.ParentWindow.VariablesGrid.GetColLabelSize()) Laurent@814: message = None Laurent@814: element_type = self.ParentWindow.ElementType Laurent@814: try: Laurent@814: 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) laurent@830: 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: Laurent@814: message = _("Incompatible data types between \"%s\" and \"%s\"")%(values[2], variable_type) laurent@830: 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]]: laurent@830: message = _("Incompatible size of data between \"%s\" and \"%s\"")%(location, variable_type) Laurent@814: else: laurent@830: dialog = wx.SingleChoiceDialog(self.ParentWindow.ParentWindow.ParentWindow, laurent@830: _("Select a variable class:"), _("Variable class"), laurent@830: ["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 laurent@830: 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() Laurent@814: elif (element_type not in ["config", "resource"] and values[1] == "Global" and self.ParentWindow.Filter in ["All", "Interface", "External"] or Laurent@814: element_type in ["config", "resource"] and values[1] == "location"): Laurent@814: if values[1] == "location": Laurent@814: var_name = values[3] Laurent@814: else: Laurent@814: var_name = values[0] Laurent@814: tagname = self.ParentWindow.GetTagName() Laurent@814: if var_name.upper() in [name.upper() for name in self.ParentWindow.Controler.GetProjectPouNames(self.ParentWindow.Debug)]: Laurent@814: message = _("\"%s\" pou already exists!")%var_name Laurent@814: elif not var_name.upper() in [name.upper() for name in self.ParentWindow.Controler.GetEditedElementVariables(tagname, self.ParentWindow.Debug)]: Laurent@814: var_infos = self.ParentWindow.DefaultValue.copy() Laurent@814: var_infos["Name"] = var_name Laurent@814: var_infos["Type"] = values[2] Laurent@814: if values[1] == "location": Laurent@814: var_infos["Class"] = "Global" Laurent@814: var_infos["Location"] = values[0] Laurent@814: else: Laurent@814: var_infos["Class"] = "External" Laurent@814: 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() Laurent@814: Laurent@814: if message is not None: Laurent@814: wx.CallAfter(self.ShowMessage, message) Laurent@814: 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 Laurent@814: #------------------------------------------------------------------------------- Laurent@814: Laurent@814: class VariablePanel(wx.Panel): Laurent@814: Laurent@814: def __init__(self, parent, window, controler, element_type, debug=False): Laurent@814: wx.Panel.__init__(self, parent, style=wx.TAB_TRAVERSAL) Laurent@814: 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) Laurent@814: 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) Laurent@814: Laurent@814: self.ReturnTypeLabel = wx.StaticText(self, label=_('Return Type:')) Laurent@814: controls_sizer.AddWindow(self.ReturnTypeLabel, flag=wx.ALIGN_CENTER_VERTICAL) Laurent@814: 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) Laurent@814: Laurent@814: self.DescriptionLabel = wx.StaticText(self, label=_('Description:')) Laurent@814: controls_sizer.AddWindow(self.DescriptionLabel, flag=wx.ALIGN_CENTER_VERTICAL) Laurent@814: 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) Laurent@814: controls_sizer.AddWindow(self.Description) Laurent@814: Laurent@814: class_filter_label = wx.StaticText(self, label=_('Class Filter:')) Laurent@814: controls_sizer.AddWindow(class_filter_label, flag=wx.ALIGN_CENTER_VERTICAL) Laurent@814: Laurent@814: 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) Laurent@814: 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"))]: Laurent@814: 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) Laurent@814: Laurent@814: self.VariablesGrid = CustomGrid(self, style=wx.VSCROLL) Laurent@814: self.VariablesGrid.SetDropTarget(VariableDropTarget(self)) Laurent@814: self.VariablesGrid.Bind(wx.grid.EVT_GRID_CELL_CHANGE, Laurent@814: self.OnVariablesGridCellChange) Laurent@814: self.VariablesGrid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, Laurent@814: self.OnVariablesGridCellLeftClick) Laurent@814: self.VariablesGrid.Bind(wx.grid.EVT_GRID_EDITOR_SHOWN, Laurent@814: self.OnVariablesGridEditorShown) Laurent@814: self.MainSizer.AddWindow(self.VariablesGrid, flag=wx.GROW) Laurent@814: Laurent@814: self.SetSizer(self.MainSizer) Laurent@814: Laurent@814: self.ParentWindow = window Laurent@814: self.Controler = controler Laurent@814: self.ElementType = element_type Laurent@814: self.Debug = debug Laurent@814: Laurent@814: self.RefreshHighlightsTimer = wx.Timer(self, -1) Laurent@814: self.Bind(wx.EVT_TIMER, self.OnRefreshHighlightsTimer, Laurent@814: self.RefreshHighlightsTimer) Laurent@814: Laurent@814: self.Filter = "All" Laurent@814: self.FilterChoices = [] Laurent@814: self.FilterChoiceTransfer = GetFilterChoiceTransfer() Laurent@814: Laurent@814: self.DefaultValue = { Laurent@814: "Name" : "", Laurent@814: "Class" : "", Laurent@814: "Type" : "INT", Laurent@814: "Location" : "", Laurent@814: "Initial Value" : "", Laurent@814: "Option" : "", Laurent@814: "Documentation" : "", Laurent@814: "Edit" : True Laurent@814: } Laurent@814: 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 Laurent@814: c = wx.ALIGN_CENTER Laurent@814: Laurent@814: # Num Name Class Type Loc Init Option Doc Laurent@814: self.ColSizes = [40, 80, 70, 80, 80, 80, 100, 80] Laurent@814: self.ColAlignements = [c, l, l, l, l, l, l, l] 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 Laurent@814: c = wx.ALIGN_CENTER Laurent@814: Laurent@814: # Num Name Class Type Init Option Doc Laurent@814: self.ColSizes = [40, 80, 70, 80, 80, 100, 160] Laurent@814: self.ColAlignements = [c, l, l, l, l, l, l] Laurent@814: 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) Laurent@814: Laurent@814: def _AddVariable(new_row): Laurent@814: if not self.PouIsUsed or self.Filter not in ["Interface", "Input", "Output", "InOut"]: Laurent@814: row_content = self.DefaultValue.copy() Laurent@814: if self.Filter in self.DefaultTypes: Laurent@814: row_content["Class"] = self.DefaultTypes[self.Filter] Laurent@814: else: Laurent@814: row_content["Class"] = self.Filter Laurent@814: if self.Filter == "All" and len(self.Values) > 0: Laurent@814: self.Values.insert(new_row, row_content) Laurent@814: else: Laurent@814: self.Values.append(row_content) Laurent@814: new_row = self.Table.GetNumberRows() Laurent@814: self.SaveValues() Laurent@814: self.RefreshValues() Laurent@814: return new_row Laurent@814: return self.VariablesGrid.GetGridCursorRow() Laurent@814: setattr(self.VariablesGrid, "_AddRow", _AddVariable) Laurent@814: Laurent@814: def _DeleteVariable(row): Laurent@814: if (self.Table.GetValueByName(row, "Edit") and Laurent@814: (not self.PouIsUsed or self.Table.GetValueByName(row, "Class") not in ["Input", "Output", "InOut"])): Laurent@814: self.Values.remove(self.Table.GetRow(row)) Laurent@814: self.SaveValues() Laurent@814: self.RefreshValues() Laurent@814: setattr(self.VariablesGrid, "_DeleteRow", _DeleteVariable) Laurent@814: Laurent@814: def _MoveVariable(row, move): Laurent@814: if (self.Filter == "All" and Laurent@814: (not self.PouIsUsed or self.Table.GetValueByName(row, "Class") not in ["Input", "Output", "InOut"])): 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) Laurent@814: 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() Laurent@814: row_edit = self.Table.GetValueByName(row, "Edit") Laurent@814: if self.PouIsUsed: Laurent@814: row_class = self.Table.GetValueByName(row, "Class") Laurent@814: self.AddButton.Enable(not self.Debug and (not self.PouIsUsed or self.Filter not in ["Interface", "Input", "Output", "InOut"])) Laurent@814: self.DeleteButton.Enable(not self.Debug and (table_length > 0 and row_edit and row_class not in ["Input", "Output", "InOut"])) Laurent@814: self.UpButton.Enable(not self.Debug and (table_length > 0 and row > 0 and self.Filter == "All" and row_class not in ["Input", "Output", "InOut"])) Laurent@814: self.DownButton.Enable(not self.Debug and (table_length > 0 and row < table_length - 1 and self.Filter == "All" and row_class not in ["Input", "Output", "InOut"])) Laurent@814: setattr(self.VariablesGrid, "RefreshButtons", _RefreshButtons) Laurent@814: 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]) Laurent@814: self.VariablesGrid.AutoSizeColumn(col, False) Laurent@814: Laurent@814: def __del__(self): Laurent@814: self.RefreshHighlightsTimer.Stop() Laurent@814: Laurent@814: def SetTagName(self, tagname): Laurent@814: self.TagName = tagname Laurent@814: Laurent@814: def GetTagName(self): Laurent@814: return self.TagName Laurent@814: Laurent@814: def IsFunctionBlockType(self, name): Laurent@814: bodytype = self.Controler.GetEditedElementBodyType(self.TagName) Laurent@814: pouname, poutype = self.Controler.GetEditedElementType(self.TagName) Laurent@814: if poutype != "function" and bodytype in ["ST", "IL"]: Laurent@814: return False Laurent@814: else: Laurent@814: return name in self.Controler.GetFunctionBlockTypes(self.TagName) Laurent@814: Laurent@814: def RefreshView(self): Laurent@814: self.PouNames = self.Controler.GetProjectPouNames(self.Debug) Laurent@814: returnType = None Laurent@814: description = None Laurent@814: Laurent@814: words = self.TagName.split("::") Laurent@814: if self.ElementType == "config": Laurent@814: self.PouIsUsed = False Laurent@814: self.Values = self.Controler.GetConfigurationGlobalVars(words[1], self.Debug) Laurent@814: elif self.ElementType == "resource": Laurent@814: self.PouIsUsed = False 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@814: returnType = self.Controler.GetEditedElementInterfaceReturnType(self.TagName) Laurent@814: description = self.Controler.GetPouDescription(words[1]) Laurent@814: self.PouIsUsed = self.Controler.PouIsUsed(words[1]) Laurent@814: self.Values = self.Controler.GetEditedElementInterfaceVars(self.TagName, self.Debug) Laurent@814: 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() Laurent@814: 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() Laurent@814: Laurent@814: self.RefreshValues() Laurent@814: self.VariablesGrid.RefreshButtons() Laurent@814: self.MainSizer.Layout() Laurent@814: 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() Laurent@814: 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@814: self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, POUINSTANCEVARIABLESPANEL, LIBRARYTREE) Laurent@814: event.Skip() Laurent@814: 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: 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 Laurent@814: 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@814: 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() Laurent@814: self.ParentWindow.RefreshView(variablepanel = False) Laurent@814: self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, POUINSTANCEVARIABLESPANEL, LIBRARYTREE) Laurent@814: event.Skip() Laurent@814: else: Laurent@814: self.SaveValues() Laurent@814: if colname == "Class": Laurent@814: self.ParentWindow.RefreshView(variablepanel = False) Laurent@814: elif colname == "Location": Laurent@814: wx.CallAfter(self.ParentWindow.RefreshView) Laurent@814: Laurent@814: if message is not None: Laurent@814: dialog = wx.MessageDialog(self, message, _("Error"), wx.OK|wx.ICON_ERROR) Laurent@814: dialog.ShowModal() Laurent@814: dialog.Destroy() Laurent@814: event.Veto() Laurent@814: else: Laurent@814: event.Skip() Laurent@814: Laurent@814: def OnVariablesGridEditorShown(self, event): Laurent@814: row, col = event.GetRow(), event.GetCol() Laurent@814: Laurent@814: label_value = self.Table.GetColLabelValue(col, False) Laurent@814: if label_value == "Type": Laurent@814: type_menu = wx.Menu(title='') # the root menu Laurent@814: 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() Laurent@814: AppendMenu(base_menu, 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: Laurent@814: # build a submenu containing user-defined types Laurent@814: datatype_menu = wx.Menu(title='') Laurent@814: datatypes = self.Controler.GetDataTypes(basetypes = False) Laurent@814: for datatype in datatypes: Laurent@814: new_id = wx.NewId() Laurent@814: AppendMenu(datatype_menu, 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) Laurent@814: Laurent@814: for category in self.Controler.GetConfNodeDataTypes(): Laurent@814: Laurent@814: if len(category["list"]) > 0: Laurent@814: # build a submenu containing confnode types Laurent@814: confnode_datatype_menu = wx.Menu(title='') Laurent@814: for datatype in category["list"]: Laurent@814: new_id = wx.NewId() Laurent@814: AppendMenu(confnode_datatype_menu, 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(), category["name"], confnode_datatype_menu) Laurent@814: Laurent@814: # build a submenu containing function block types Laurent@814: bodytype = self.Controler.GetEditedElementBodyType(self.TagName) Laurent@814: pouname, poutype = self.Controler.GetEditedElementType(self.TagName) Laurent@814: classtype = self.Table.GetValueByName(row, "Class") Laurent@814: Laurent@814: new_id = wx.NewId() Laurent@814: AppendMenu(type_menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=_("Array")) Laurent@814: self.Bind(wx.EVT_MENU, self.VariableArrayTypeFunction, id=new_id) Laurent@814: Laurent@814: if classtype in ["Input", "Output", "InOut", "External", "Global"] or \ Laurent@814: poutype != "function" and bodytype in ["ST", "IL"]: Laurent@814: functionblock_menu = wx.Menu(title='') Laurent@814: fbtypes = self.Controler.GetFunctionBlockTypes(self.TagName) Laurent@814: for functionblock_type in fbtypes: Laurent@814: new_id = wx.NewId() Laurent@814: AppendMenu(functionblock_menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=functionblock_type) Laurent@814: self.Bind(wx.EVT_MENU, self.GetVariableTypeFunction(functionblock_type), id=new_id) Laurent@814: Laurent@814: type_menu.AppendMenu(wx.NewId(), _("Function Block Types"), functionblock_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() Laurent@814: else: Laurent@814: event.Skip() Laurent@814: 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@814: self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, POUINSTANCEVARIABLESPANEL, LIBRARYTREE) Laurent@814: return VariableTypeFunction Laurent@814: Laurent@814: def VariableArrayTypeFunction(self, event): Laurent@814: row = self.VariablesGrid.GetGridCursorRow() Laurent@814: dialog = ArrayTypeDialog(self, Laurent@814: 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@814: self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, POUINSTANCEVARIABLESPANEL, LIBRARYTREE) Laurent@814: dialog.Destroy() Laurent@814: 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: row = event.GetRow() 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() Laurent@814: Laurent@814: def RefreshValues(self): Laurent@814: data = [] Laurent@814: for num, variable in enumerate(self.Values): Laurent@814: if variable["Class"] in self.ClassList: Laurent@814: variable["Number"] = num + 1 Laurent@814: data.append(variable) Laurent@814: self.Table.SetData(data) Laurent@814: self.Table.ResetView(self.VariablesGrid) Laurent@814: 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() Laurent@814: self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, 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)