--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/VariablePanel.py Tue Sep 22 09:56:02 2009 +0200
@@ -0,0 +1,1178 @@
+# -*- coding: utf-8 -*-
+
+#This file is part of PLCOpenEditor, a library implementing an IEC 61131-3 editor
+#based on the plcopen standard.
+#
+#Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD
+#
+#See COPYING file for copyrights details.
+#
+#This library is free software; you can redistribute it and/or
+#modify it under the terms of the GNU General Public
+#License as published by the Free Software Foundation; either
+#version 2.1 of the License, or (at your option) any later version.
+#
+#This library is distributed in the hope that it will be useful,
+#but WITHOUT ANY WARRANTY; without even the implied warranty of
+#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+#General Public License for more details.
+#
+#You should have received a copy of the GNU General Public
+#License along with this library; if not, write to the Free Software
+#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+import wx, wx.grid
+
+from types import TupleType
+
+from plcopen.structures import LOCATIONDATATYPES, TestIdentifier, IEC_KEYWORDS
+
+# Compatibility function for wx versions < 2.6
+def AppendMenu(parent, help, id, kind, text):
+ if wx.VERSION >= (2, 6, 0):
+ parent.Append(help=help, id=id, kind=kind, text=text)
+ else:
+ parent.Append(helpString=help, id=id, kind=kind, item=text)
+
+[TITLE, TOOLBAR, FILEMENU, EDITMENU, DISPLAYMENU, TYPESTREE,
+ INSTANCESTREE, LIBRARYTREE, SCALING
+] = range(9)
+
+#-------------------------------------------------------------------------------
+# Variables Editor Panel
+#-------------------------------------------------------------------------------
+
+def GetVariableTableColnames(location):
+ _ = lambda x : x
+ if location:
+ return ["#", _("Name"), _("Class"), _("Type"), _("Location"), _("Initial Value"), _("Retain"), _("Constant"), _("Documentation")]
+ return ["#", _("Name"), _("Class"), _("Type"), _("Initial Value"), _("Retain"), _("Constant"), _("Documentation")]
+
+def GetAlternativeOptions():
+ _ = lambda x : x
+ return [_("Yes"), _("No")]
+ALTERNATIVE_OPTIONS_DICT = dict([(_(option), option) for option in GetAlternativeOptions()])
+
+def GetFilterChoiceTransfer():
+ _ = lambda x : x
+ return {_("All"): _("All"), _("Interface"): _("Interface"),
+ _(" Input"): _("Input"), _(" Output"): _("Output"), _(" InOut"): _("InOut"),
+ _(" External"): _("External"), _("Variables"): _("Variables"), _(" Local"): _("Local"),
+ _(" Temp"): _("Temp"), _("Global"): _("Global")}#, _("Access") : _("Access")}
+VARIABLE_CLASSES_DICT = dict([(_(_class), _class) for _class in GetFilterChoiceTransfer().itervalues()])
+
+class VariableTable(wx.grid.PyGridTableBase):
+
+ """
+ A custom wx.grid.Grid Table using user supplied data
+ """
+ def __init__(self, parent, data, colnames):
+ # The base class must be initialized *first*
+ wx.grid.PyGridTableBase.__init__(self)
+ self.data = data
+ self.old_value = None
+ self.colnames = colnames
+ self.Errors = {}
+ self.Parent = parent
+ # XXX
+ # we need to store the row length and collength to
+ # see if the table has changed size
+ self._rows = self.GetNumberRows()
+ self._cols = self.GetNumberCols()
+
+ def GetNumberCols(self):
+ return len(self.colnames)
+
+ def GetNumberRows(self):
+ return len(self.data)
+
+ def GetColLabelValue(self, col, translate=True):
+ if col < len(self.colnames):
+ if translate:
+ return _(self.colnames[col])
+ return self.colnames[col]
+
+ def GetRowLabelValues(self, row, translate=True):
+ return row
+
+ def GetValue(self, row, col):
+ if row < self.GetNumberRows():
+ if col == 0:
+ return self.data[row]["Number"]
+ colname = self.GetColLabelValue(col, False)
+ value = str(self.data[row].get(colname, ""))
+ if colname in ["Class", "Retain", "Constant"]:
+ return _(value)
+ return value
+
+ def SetValue(self, row, col, value):
+ if col < len(self.colnames):
+ colname = self.GetColLabelValue(col, False)
+ if colname == "Name":
+ self.old_value = self.data[row][colname]
+ elif colname == "Class":
+ value = VARIABLE_CLASSES_DICT[value]
+ elif colname in ["Retain", "Constant"]:
+ value = ALTERNATIVE_OPTIONS_DICT[value]
+ self.data[row][colname] = value
+
+ def GetValueByName(self, row, colname):
+ if row < self.GetNumberRows():
+ return self.data[row].get(colname)
+
+ def SetValueByName(self, row, colname, value):
+ if row < self.GetNumberRows():
+ self.data[row][colname] = value
+
+ def GetOldValue(self):
+ return self.old_value
+
+ def ResetView(self, grid):
+ """
+ (wx.grid.Grid) -> Reset the grid view. Call this to
+ update the grid if rows and columns have been added or deleted
+ """
+ grid.BeginBatch()
+ for current, new, delmsg, addmsg in [
+ (self._rows, self.GetNumberRows(), wx.grid.GRIDTABLE_NOTIFY_ROWS_DELETED, wx.grid.GRIDTABLE_NOTIFY_ROWS_APPENDED),
+ (self._cols, self.GetNumberCols(), wx.grid.GRIDTABLE_NOTIFY_COLS_DELETED, wx.grid.GRIDTABLE_NOTIFY_COLS_APPENDED),
+ ]:
+ if new < current:
+ msg = wx.grid.GridTableMessage(self,delmsg,new,current-new)
+ grid.ProcessTableMessage(msg)
+ elif new > current:
+ msg = wx.grid.GridTableMessage(self,addmsg,new-current)
+ grid.ProcessTableMessage(msg)
+ self.UpdateValues(grid)
+ grid.EndBatch()
+
+ self._rows = self.GetNumberRows()
+ self._cols = self.GetNumberCols()
+ # update the column rendering scheme
+ self._updateColAttrs(grid)
+
+ # update the scrollbars and the displayed part of the grid
+ grid.AdjustScrollbars()
+ grid.ForceRefresh()
+
+ def UpdateValues(self, grid):
+ """Update all displayed values"""
+ # This sends an event to the grid table to update all of the values
+ msg = wx.grid.GridTableMessage(self, wx.grid.GRIDTABLE_REQUEST_VIEW_GET_VALUES)
+ grid.ProcessTableMessage(msg)
+
+ def _updateColAttrs(self, grid):
+ """
+ wx.grid.Grid -> update the column attributes to add the
+ appropriate renderer given the column name.
+
+ Otherwise default to the default renderer.
+ """
+
+ for row in range(self.GetNumberRows()):
+ for col in range(self.GetNumberCols()):
+ editor = None
+ renderer = None
+ colname = self.GetColLabelValue(col, False)
+ if col != 0 and self.GetValueByName(row, "Edit"):
+ grid.SetReadOnly(row, col, False)
+ if colname == "Name":
+ if self.Parent.PouIsUsed and self.GetValueByName(row, "Class") in ["Input", "Output", "InOut"]:
+ grid.SetReadOnly(row, col, True)
+ else:
+ editor = wx.grid.GridCellTextEditor()
+ renderer = wx.grid.GridCellStringRenderer()
+ elif colname == "Initial Value":
+ editor = wx.grid.GridCellTextEditor()
+ renderer = wx.grid.GridCellStringRenderer()
+ elif colname == "Location":
+ if self.GetValueByName(row, "Class") in ["Local", "Global"]:
+ editor = LocationCellEditor(self.Parent)
+ renderer = wx.grid.GridCellStringRenderer()
+ else:
+ grid.SetReadOnly(row, col, True)
+ elif colname == "Class":
+ if len(self.Parent.ClassList) == 1 or self.Parent.PouIsUsed and self.GetValueByName(row, "Class") in ["Input", "Output", "InOut"]:
+ grid.SetReadOnly(row, col, True)
+ else:
+ editor = wx.grid.GridCellChoiceEditor()
+ excluded = []
+ if self.Parent.PouIsUsed:
+ excluded.extend(["Input","Output","InOut"])
+ if self.Parent.IsFunctionBlockType(self.data[row]["Type"]):
+ excluded.extend(["Local","Temp"])
+ editor.SetParameters(",".join([_(choice) for choice in self.Parent.ClassList if choice not in excluded]))
+ elif colname in ["Retain", "Constant"]:
+ editor = wx.grid.GridCellChoiceEditor()
+ editor.SetParameters(",".join(map(_, self.Parent.OptionList)))
+ elif colname == "Type":
+ editor = wx.grid.GridCellTextEditor()
+ else:
+ grid.SetReadOnly(row, col, True)
+
+ grid.SetCellEditor(row, col, editor)
+ grid.SetCellRenderer(row, col, renderer)
+
+ if row in self.Errors and self.Errors[row][0] == colname.lower():
+ grid.SetCellBackgroundColour(row, col, wx.Colour(255, 255, 0))
+ grid.SetCellTextColour(row, col, wx.RED)
+ grid.MakeCellVisible(row, col)
+ else:
+ grid.SetCellTextColour(row, col, wx.BLACK)
+ grid.SetCellBackgroundColour(row, col, wx.WHITE)
+
+ def SetData(self, data):
+ self.data = data
+
+ def GetData(self):
+ return self.data
+
+ def GetCurrentIndex(self):
+ return self.CurrentIndex
+
+ def SetCurrentIndex(self, index):
+ self.CurrentIndex = index
+
+ def AppendRow(self, row_content):
+ self.data.append(row_content)
+
+ def RemoveRow(self, row_index):
+ self.data.pop(row_index)
+
+ def GetRow(self, row_index):
+ return self.data[row_index]
+
+ def Empty(self):
+ self.data = []
+ self.editors = []
+
+ def AddError(self, infos):
+ self.Errors[infos[0]] = infos[1:]
+
+ def ClearErrors(self):
+ self.Errors = {}
+
+class VariableDropTarget(wx.TextDropTarget):
+ '''
+ This allows dragging a variable location from somewhere to the Location
+ column of a variable row.
+
+ The drag source should be a TextDataObject containing a Python tuple like:
+ ('%ID0.0.0', 'location', 'REAL')
+
+ c_ext/CFileEditor.py has an example of this (you can drag a C extension
+ variable to the Location column of the variable panel).
+ '''
+ def __init__(self, parent):
+ wx.TextDropTarget.__init__(self)
+ self.ParentWindow = parent
+
+ def OnDropText(self, x, y, data):
+ x, y = self.ParentWindow.VariablesGrid.CalcUnscrolledPosition(x, y)
+ col = self.ParentWindow.VariablesGrid.XToCol(x)
+ row = self.ParentWindow.VariablesGrid.YToRow(y - self.ParentWindow.VariablesGrid.GetColLabelSize())
+ if col != wx.NOT_FOUND and row != wx.NOT_FOUND:
+ if self.ParentWindow.Table.GetColLabelValue(col, False) != "Location":
+ return
+ message = None
+ if not self.ParentWindow.Table.GetValueByName(row, "Edit"):
+ message = _("Can't give a location to a function block instance")
+ elif self.ParentWindow.Table.GetValueByName(row, "Class") not in ["Local", "Global"]:
+ message = _("Can only give a location to local or global variables")
+ else:
+ try:
+ values = eval(data)
+ except:
+ message = _("Invalid value \"%s\" for location")%data
+ values = None
+ if not isinstance(values, TupleType):
+ message = _("Invalid value \"%s\" for location")%data
+ values = None
+ if values is not None and values[1] == "location":
+ location = values[0]
+ variable_type = self.ParentWindow.Table.GetValueByName(row, "Type")
+ base_type = self.ParentWindow.Controler.GetBaseType(variable_type)
+ message = None
+ if location.startswith("%"):
+ if base_type != values[2]:
+ message = _("Incompatible data types between \"%s\" and \"%s\"")%(values[2], variable_type)
+ else:
+ self.ParentWindow.Table.SetValue(row, col, location)
+ self.ParentWindow.Table.ResetView(self.ParentWindow.VariablesGrid)
+ self.ParentWindow.SaveValues()
+ else:
+ if location[0].isdigit() and base_type != "BOOL":
+ message = _("Incompatible size of data between \"%s\" and \"BOOL\"")%location
+ elif location[0] not in LOCATIONDATATYPES:
+ message = _("Unrecognized data size \"%s\"")%location[0]
+ elif base_type not in LOCATIONDATATYPES[location[0]]:
+ message = _("Incompatible size of data between \"%s\" and \"%s\"")%(location, variable_type)
+ else:
+ dialog = wx.SingleChoiceDialog(self.ParentWindow, _("Select a variable class:"), _("Variable class"), ["Input", "Output", "Memory"], wx.OK|wx.CANCEL)
+ if dialog.ShowModal() == wx.ID_OK:
+ selected = dialog.GetSelection()
+ if selected == 0:
+ location = "%I" + location
+ elif selected == 1:
+ location = "%Q" + location
+ else:
+ location = "%M" + location
+ self.ParentWindow.Table.SetValue(row, col, location)
+ self.ParentWindow.Table.ResetView(self.ParentWindow.VariablesGrid)
+ self.ParentWindow.SaveValues()
+ dialog.Destroy()
+ if message is not None:
+ wx.CallAfter(self.ShowMessage, message)
+
+ def ShowMessage(self, message):
+ message = wx.MessageDialog(self.ParentWindow, message, _("Error"), wx.OK|wx.ICON_ERROR)
+ message.ShowModal()
+ message.Destroy()
+
+[ID_VARIABLEEDITORPANEL, ID_VARIABLEEDITORPANELVARIABLESGRID,
+ ID_VARIABLEEDITORCONTROLPANEL, ID_VARIABLEEDITORPANELRETURNTYPE,
+ ID_VARIABLEEDITORPANELCLASSFILTER, ID_VARIABLEEDITORPANELADDBUTTON,
+ ID_VARIABLEEDITORPANELDELETEBUTTON, ID_VARIABLEEDITORPANELUPBUTTON,
+ ID_VARIABLEEDITORPANELDOWNBUTTON, ID_VARIABLEEDITORPANELSTATICTEXT1,
+ ID_VARIABLEEDITORPANELSTATICTEXT2, ID_VARIABLEEDITORPANELSTATICTEXT3,
+] = [wx.NewId() for _init_ctrls in range(12)]
+
+class VariablePanel(wx.Panel):
+
+ if wx.VERSION < (2, 6, 0):
+ def Bind(self, event, function, id = None):
+ if id is not None:
+ event(self, id, function)
+ else:
+ event(self, function)
+
+ def _init_coll_MainSizer_Items(self, parent):
+ parent.AddWindow(self.VariablesGrid, 0, border=0, flag=wx.GROW)
+ parent.AddWindow(self.ControlPanel, 0, border=5, flag=wx.GROW|wx.ALL)
+
+ def _init_coll_MainSizer_Growables(self, parent):
+ parent.AddGrowableCol(0)
+ parent.AddGrowableRow(0)
+
+ def _init_coll_ControlPanelSizer_Items(self, parent):
+ parent.AddSizer(self.ChoicePanelSizer, 0, border=0, flag=wx.GROW)
+ parent.AddSizer(self.ButtonPanelSizer, 0, border=0, flag=wx.ALIGN_CENTER)
+
+ def _init_coll_ControlPanelSizer_Growables(self, parent):
+ parent.AddGrowableCol(0)
+ parent.AddGrowableRow(0)
+ parent.AddGrowableRow(1)
+
+ def _init_coll_ChoicePanelSizer_Items(self, parent):
+ parent.AddWindow(self.staticText1, 0, border=0, flag=wx.ALIGN_BOTTOM)
+ parent.AddWindow(self.ReturnType, 0, border=0, flag=0)
+ parent.AddWindow(self.staticText2, 0, border=0, flag=wx.ALIGN_BOTTOM)
+ parent.AddWindow(self.ClassFilter, 0, border=0, flag=0)
+
+ def _init_coll_ButtonPanelSizer_Items(self, parent):
+ parent.AddWindow(self.UpButton, 0, border=0, flag=0)
+ parent.AddWindow(self.AddButton, 0, border=0, flag=0)
+ parent.AddWindow(self.DownButton, 0, border=0, flag=0)
+ parent.AddWindow(self.DeleteButton, 0, border=0, flag=0)
+
+ def _init_coll_ButtonPanelSizer_Growables(self, parent):
+ parent.AddGrowableCol(0)
+ parent.AddGrowableCol(1)
+ parent.AddGrowableCol(2)
+ parent.AddGrowableCol(3)
+ parent.AddGrowableRow(0)
+
+ def _init_sizers(self):
+ self.MainSizer = wx.FlexGridSizer(cols=2, hgap=10, rows=1, vgap=0)
+ self.ControlPanelSizer = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=5)
+ self.ChoicePanelSizer = wx.GridSizer(cols=1, hgap=5, rows=4, vgap=5)
+ self.ButtonPanelSizer = wx.FlexGridSizer(cols=2, hgap=5, rows=2, vgap=5)
+
+ self._init_coll_MainSizer_Items(self.MainSizer)
+ self._init_coll_MainSizer_Growables(self.MainSizer)
+ self._init_coll_ControlPanelSizer_Items(self.ControlPanelSizer)
+ self._init_coll_ControlPanelSizer_Growables(self.ControlPanelSizer)
+ self._init_coll_ChoicePanelSizer_Items(self.ChoicePanelSizer)
+ self._init_coll_ButtonPanelSizer_Items(self.ButtonPanelSizer)
+ self._init_coll_ButtonPanelSizer_Growables(self.ButtonPanelSizer)
+
+ self.SetSizer(self.MainSizer)
+ self.ControlPanel.SetSizer(self.ControlPanelSizer)
+
+ def _init_ctrls(self, prnt):
+ wx.Panel.__init__(self, id=ID_VARIABLEEDITORPANEL,
+ name='VariableEditorPanel', parent=prnt, pos=wx.Point(0, 0),
+ size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL)
+
+ self.VariablesGrid = wx.grid.Grid(id=ID_VARIABLEEDITORPANELVARIABLESGRID,
+ name='VariablesGrid', parent=self, pos=wx.Point(0, 0),
+ size=wx.Size(0, 0), style=wx.VSCROLL)
+ self.VariablesGrid.SetFont(wx.Font(12, 77, wx.NORMAL, wx.NORMAL, False,
+ 'Sans'))
+ self.VariablesGrid.SetLabelFont(wx.Font(10, 77, wx.NORMAL, wx.NORMAL,
+ False, 'Sans'))
+ self.VariablesGrid.SetSelectionBackground(wx.WHITE)
+ self.VariablesGrid.SetSelectionForeground(wx.BLACK)
+ if wx.VERSION >= (2, 6, 0):
+ self.VariablesGrid.Bind(wx.grid.EVT_GRID_CELL_CHANGE, self.OnVariablesGridCellChange)
+ self.VariablesGrid.Bind(wx.grid.EVT_GRID_SELECT_CELL, self.OnVariablesGridSelectCell)
+ self.VariablesGrid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.OnVariablesGridCellLeftClick)
+ self.VariablesGrid.Bind(wx.grid.EVT_GRID_EDITOR_SHOWN, self.OnVariablesGridEditorShown)
+ #self.VariablesGrid.Bind(wx.EVT_KEY_DOWN, self.OnChar)
+ else:
+ wx.grid.EVT_GRID_CELL_CHANGE(self.VariablesGrid, self.OnVariablesGridCellChange)
+ wx.grid.EVT_GRID_SELECT_CELL(self.VariablesGrid, self.OnVariablesGridSelectCell)
+ wx.grid.EVT_GRID_CELL_LEFT_CLICK(self.VariablesGrid, self.OnVariablesGridCellLeftClick)
+ wx.grid.EVT_GRID_EDITOR_SHOWN(self.VariablesGrid, self.OnVariablesGridEditorShown)
+ #wx.EVT_KEY_DOWN(self.VariablesGrid, self.OnChar)
+ self.VariablesGrid.SetDropTarget(VariableDropTarget(self))
+
+ self.ControlPanel = wx.ScrolledWindow(id=ID_VARIABLEEDITORCONTROLPANEL,
+ name='ControlPanel', parent=self, pos=wx.Point(0, 0),
+ size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL)
+ self.ControlPanel.SetScrollRate(0, 10)
+
+ self.staticText1 = wx.StaticText(id=ID_VARIABLEEDITORPANELSTATICTEXT1,
+ label=_('Return Type:'), name='staticText1', parent=self.ControlPanel,
+ pos=wx.Point(0, 0), size=wx.Size(145, 17), style=0)
+
+ self.ReturnType = wx.ComboBox(id=ID_VARIABLEEDITORPANELRETURNTYPE,
+ name='ReturnType', parent=self.ControlPanel, pos=wx.Point(0, 0),
+ size=wx.Size(145, 28), style=wx.CB_READONLY)
+ self.Bind(wx.EVT_COMBOBOX, self.OnReturnTypeChanged, id=ID_VARIABLEEDITORPANELRETURNTYPE)
+
+ self.staticText2 = wx.StaticText(id=ID_VARIABLEEDITORPANELSTATICTEXT2,
+ label=_('Class Filter:'), name='staticText2', parent=self.ControlPanel,
+ pos=wx.Point(0, 0), size=wx.Size(145, 17), style=0)
+
+ self.ClassFilter = wx.ComboBox(id=ID_VARIABLEEDITORPANELCLASSFILTER,
+ name='ClassFilter', parent=self.ControlPanel, pos=wx.Point(0, 0),
+ size=wx.Size(145, 28), style=wx.CB_READONLY)
+ self.Bind(wx.EVT_COMBOBOX, self.OnClassFilter, id=ID_VARIABLEEDITORPANELCLASSFILTER)
+
+ self.AddButton = wx.Button(id=ID_VARIABLEEDITORPANELADDBUTTON, label=_('Add'),
+ name='AddButton', parent=self.ControlPanel, pos=wx.Point(0, 0),
+ size=wx.DefaultSize, style=0)
+ self.Bind(wx.EVT_BUTTON, self.OnAddButton, id=ID_VARIABLEEDITORPANELADDBUTTON)
+
+ self.DeleteButton = wx.Button(id=ID_VARIABLEEDITORPANELDELETEBUTTON, label=_('Delete'),
+ name='DeleteButton', parent=self.ControlPanel, pos=wx.Point(0, 0),
+ size=wx.DefaultSize, style=0)
+ self.Bind(wx.EVT_BUTTON, self.OnDeleteButton, id=ID_VARIABLEEDITORPANELDELETEBUTTON)
+
+ self.UpButton = wx.Button(id=ID_VARIABLEEDITORPANELUPBUTTON, label='^',
+ name='UpButton', parent=self.ControlPanel, pos=wx.Point(0, 0),
+ size=wx.Size(32, 32), style=0)
+ self.Bind(wx.EVT_BUTTON, self.OnUpButton, id=ID_VARIABLEEDITORPANELUPBUTTON)
+
+ self.DownButton = wx.Button(id=ID_VARIABLEEDITORPANELDOWNBUTTON, label='v',
+ name='DownButton', parent=self.ControlPanel, pos=wx.Point(0, 0),
+ size=wx.Size(32, 32), style=0)
+ self.Bind(wx.EVT_BUTTON, self.OnDownButton, id=ID_VARIABLEEDITORPANELDOWNBUTTON)
+
+ self._init_sizers()
+
+ def __init__(self, parent, window, controler, element_type):
+ self._init_ctrls(parent)
+ self.ParentWindow = window
+ self.Controler = controler
+ self.ElementType = element_type
+
+ self.Filter = "All"
+ self.FilterChoices = []
+ self.FilterChoiceTransfer = GetFilterChoiceTransfer()
+
+ self.DefaultValue = { "Name" : "", "Class" : "", "Type" : "INT", "Location" : "",
+ "Initial Value" : "", "Retain" : "No", "Constant" : "No",
+ "Documentation" : "", "Edit" : True
+ }
+
+ if element_type in ["config", "resource"]:
+ self.DefaultTypes = {"All" : "Global"}
+ else:
+ self.DefaultTypes = {"All" : "Local", "Interface" : "Input", "Variables" : "Local"}
+
+ if element_type in ["config", "resource"] \
+ or element_type in ["program", "transition", "action"]:
+ # this is an element that can have located variables
+ self.Table = VariableTable(self, [], GetVariableTableColnames(True))
+
+ if element_type in ["config", "resource"]:
+ self.FilterChoices = ["All", "Global"]#,"Access"]
+ else:
+ self.FilterChoices = ["All",
+ "Interface", " Input", " Output", " InOut", " External",
+ "Variables", " Local", " Temp"]#,"Access"]
+
+ # these condense the ColAlignements list
+ l = wx.ALIGN_LEFT
+ c = wx.ALIGN_CENTER
+
+ # Num Name Class Type Loc Init Retain Const Doc
+ self.ColSizes = [40, 80, 70, 80, 80, 80, 60, 70, 80]
+ self.ColAlignements = [c, l, l, l, l, l, c, c, l]
+
+ else:
+ # this is an element that cannot have located variables
+ self.Table = VariableTable(self, [], GetVariableTableColnames(False))
+
+ if element_type == "function":
+ self.FilterChoices = ["All",
+ "Interface", " Input", " Output", " InOut",
+ "Variables", " Local", " Temp"]
+ else:
+ self.FilterChoices = ["All",
+ "Interface", " Input", " Output", " InOut", " External",
+ "Variables", " Local", " Temp"]
+
+ # these condense the ColAlignements list
+ l = wx.ALIGN_LEFT
+ c = wx.ALIGN_CENTER
+
+ # Num Name Class Type Init Retain Const Doc
+ self.ColSizes = [40, 80, 70, 80, 80, 60, 70, 160]
+ self.ColAlignements = [c, l, l, l, l, c, c, l]
+
+ for choice in self.FilterChoices:
+ self.ClassFilter.Append(_(choice))
+
+ reverse_transfer = {}
+ for filter, choice in self.FilterChoiceTransfer.items():
+ reverse_transfer[choice] = filter
+ self.ClassFilter.SetStringSelection(_(reverse_transfer[self.Filter]))
+ self.RefreshTypeList()
+
+ self.OptionList = GetAlternativeOptions()
+
+ if element_type == "function":
+ for base_type in self.Controler.GetBaseTypes():
+ self.ReturnType.Append(base_type)
+ self.ReturnType.Enable(True)
+ else:
+ self.ReturnType.Enable(False)
+ self.staticText1.Hide()
+ self.ReturnType.Hide()
+
+ self.VariablesGrid.SetTable(self.Table)
+ self.VariablesGrid.SetRowLabelSize(0)
+ for col in range(self.Table.GetNumberCols()):
+ attr = wx.grid.GridCellAttr()
+ attr.SetAlignment(self.ColAlignements[col], wx.ALIGN_CENTRE)
+ self.VariablesGrid.SetColAttr(col, attr)
+ self.VariablesGrid.SetColMinimalWidth(col, self.ColSizes[col])
+ self.VariablesGrid.AutoSizeColumn(col, False)
+
+ def SetTagName(self, tagname):
+ self.TagName = tagname
+
+ def IsFunctionBlockType(self, name):
+ bodytype = self.Controler.GetEditedElementBodyType(self.TagName)
+ pouname, poutype = self.Controler.GetEditedElementType(self.TagName)
+ if poutype != "function" and bodytype in ["ST", "IL"]:
+ return False
+ else:
+ return name in self.Controler.GetFunctionBlockTypes(self.TagName)
+
+ def RefreshView(self):
+ self.PouNames = self.Controler.GetProjectPouNames()
+
+ words = self.TagName.split("::")
+ if self.ElementType == "config":
+ self.PouIsUsed = False
+ returnType = None
+ self.Values = self.Controler.GetConfigurationGlobalVars(words[1])
+ elif self.ElementType == "resource":
+ self.PouIsUsed = False
+ returnType = None
+ self.Values = self.Controler.GetConfigurationResourceGlobalVars(words[1], words[2])
+ else:
+ self.PouIsUsed = self.Controler.PouIsUsed(words[1])
+ returnType = self.Controler.GetEditedElementInterfaceReturnType(self.TagName)
+ self.Values = self.Controler.GetEditedElementInterfaceVars(self.TagName)
+
+ if returnType and self.ReturnType.IsEnabled():
+ self.ReturnType.SetStringSelection(returnType)
+
+ self.RefreshValues()
+ self.RefreshButtons()
+
+ def OnReturnTypeChanged(self, event):
+ words = self.TagName.split("::")
+ self.Controler.SetPouInterfaceReturnType(words[1], self.ReturnType.GetStringSelection())
+ self.Controler.BufferProject()
+ self.ParentWindow.RefreshEditor(variablepanel = False)
+ self.ParentWindow._Refresh(TITLE, EDITMENU, INSTANCETREE, LIBRARYTREE)
+ event.Skip()
+
+ def OnClassFilter(self, event):
+ self.Filter = self.FilterChoiceTransfer[self.ClassFilter.GetStringSelection()]
+ self.RefreshTypeList()
+ self.RefreshValues()
+ self.RefreshButtons()
+ event.Skip()
+
+ def RefreshTypeList(self):
+ if self.Filter == "All":
+ self.ClassList = [self.FilterChoiceTransfer[choice] for choice in self.FilterChoices if self.FilterChoiceTransfer[choice] not in ["All","Interface","Variables"]]
+ elif self.Filter == "Interface":
+ self.ClassList = ["Input","Output","InOut","External"]
+ elif self.Filter == "Variables":
+ self.ClassList = ["Local","Temp"]
+ else:
+ self.ClassList = [self.Filter]
+
+ def RefreshButtons(self):
+ if getattr(self, "Table", None):
+ table_length = len(self.Table.data)
+ row_class = None
+ row_edit = True
+ if table_length > 0:
+ row = self.VariablesGrid.GetGridCursorRow()
+ row_edit = self.Table.GetValueByName(row, "Edit")
+ if self.PouIsUsed:
+ row_class = self.Table.GetValueByName(row, "Class")
+ self.AddButton.Enable(not self.PouIsUsed or self.Filter not in ["Interface", "Input", "Output", "InOut"])
+ self.DeleteButton.Enable(table_length > 0 and row_edit and row_class not in ["Input", "Output", "InOut"])
+ self.UpButton.Enable(table_length > 0 and self.Filter == "All" and row_class not in ["Input", "Output", "InOut"])
+ self.DownButton.Enable(table_length > 0 and self.Filter == "All" and row_class not in ["Input", "Output", "InOut"])
+
+ def OnAddButton(self, event):
+ new_row = self.DefaultValue.copy()
+ if self.Filter in self.DefaultTypes:
+ new_row["Class"] = self.DefaultTypes[self.Filter]
+ else:
+ new_row["Class"] = self.Filter
+ if self.Filter == "All" and len(self.Values) > 0:
+ row_index = self.VariablesGrid.GetGridCursorRow() + 1
+ self.Values.insert(row_index, new_row)
+ else:
+ row_index = -1
+ self.Values.append(new_row)
+ self.SaveValues()
+ self.RefreshValues(row_index)
+ self.RefreshButtons()
+ event.Skip()
+
+ def OnDeleteButton(self, event):
+ row = self.Table.GetRow(self.VariablesGrid.GetGridCursorRow())
+ self.Values.remove(row)
+ self.SaveValues()
+ self.RefreshValues()
+ self.RefreshButtons()
+ event.Skip()
+
+ def OnUpButton(self, event):
+ self.MoveValue(self.VariablesGrid.GetGridCursorRow(), -1)
+ self.RefreshButtons()
+ event.Skip()
+
+ def OnDownButton(self, event):
+ self.MoveValue(self.VariablesGrid.GetGridCursorRow(), 1)
+ self.RefreshButtons()
+ event.Skip()
+
+ def OnVariablesGridCellChange(self, event):
+ row, col = event.GetRow(), event.GetCol()
+ colname = self.Table.GetColLabelValue(col, False)
+ value = self.Table.GetValue(row, col)
+
+ if colname == "Name" and value != "":
+ if not TestIdentifier(value):
+ message = wx.MessageDialog(self, _("\"%s\" is not a valid identifier!")%value, _("Error"), wx.OK|wx.ICON_ERROR)
+ message.ShowModal()
+ message.Destroy()
+ event.Veto()
+ elif value.upper() in IEC_KEYWORDS:
+ message = wx.MessageDialog(self, _("\"%s\" is a keyword. It can't be used!")%value, _("Error"), wx.OK|wx.ICON_ERROR)
+ message.ShowModal()
+ message.Destroy()
+ event.Veto()
+ elif value.upper() in self.PouNames:
+ message = wx.MessageDialog(self, _("A pou with \"%s\" as name exists!")%value, _("Error"), wx.OK|wx.ICON_ERROR)
+ message.ShowModal()
+ message.Destroy()
+ event.Veto()
+ elif value.upper() in [var["Name"].upper() for var in self.Values if var != self.Table.data[row]]:
+ message = wx.MessageDialog(self, _("A variable with \"%s\" as name already exists in this pou!")%value, _("Error"), wx.OK|wx.ICON_ERROR)
+ message.ShowModal()
+ message.Destroy()
+ event.Veto()
+ else:
+ self.SaveValues(False)
+ old_value = self.Table.GetOldValue()
+ if old_value != "":
+ self.Controler.UpdateEditedElementUsedVariable(self.TagName, old_value, value)
+ self.Controler.BufferProject()
+ self.ParentWindow.RefreshEditor(variablepanel = False)
+ self.ParentWindow._Refresh(TITLE, EDITMENU, INSTANCETREE, LIBRARYTREE)
+ event.Skip()
+ else:
+ self.SaveValues()
+ if colname == "Class":
+ self.Table.ResetView(self.VariablesGrid)
+ event.Skip()
+
+ def OnVariablesGridEditorShown(self, event):
+ row, col = event.GetRow(), event.GetCol()
+
+ label_value = self.Table.GetColLabelValue(col)
+ if label_value == "Type":
+ type_menu = wx.Menu(title='') # the root menu
+
+ # build a submenu containing standard IEC types
+ base_menu = wx.Menu(title='')
+ for base_type in self.Controler.GetBaseTypes():
+ new_id = wx.NewId()
+ AppendMenu(base_menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=base_type)
+ self.Bind(wx.EVT_MENU, self.GetVariableTypeFunction(base_type), id=new_id)
+
+ type_menu.AppendMenu(wx.NewId(), _("Base Types"), base_menu)
+
+ # build a submenu containing user-defined types
+ datatype_menu = wx.Menu(title='')
+ datatypes = self.Controler.GetDataTypes(basetypes = False)
+ for datatype in datatypes:
+ new_id = wx.NewId()
+ AppendMenu(datatype_menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=datatype)
+ self.Bind(wx.EVT_MENU, self.GetVariableTypeFunction(datatype), id=new_id)
+
+ type_menu.AppendMenu(wx.NewId(), _("User Data Types"), datatype_menu)
+
+ # build a submenu containing function block types
+ bodytype = self.Controler.GetEditedElementBodyType(self.TagName)
+ pouname, poutype = self.Controler.GetEditedElementType(self.TagName)
+ classtype = self.Table.GetValueByName(row, "Class")
+
+ if classtype in ["Input", "Output", "InOut", "External", "Global"] or \
+ poutype != "function" and bodytype in ["ST", "IL"]:
+ functionblock_menu = wx.Menu(title='')
+ fbtypes = self.Controler.GetFunctionBlockTypes(self.TagName)
+ for functionblock_type in fbtypes:
+ new_id = wx.NewId()
+ AppendMenu(functionblock_menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=functionblock_type)
+ self.Bind(wx.EVT_MENU, self.GetVariableTypeFunction(functionblock_type), id=new_id)
+
+ type_menu.AppendMenu(wx.NewId(), _("Function Block Types"), functionblock_menu)
+
+ rect = self.VariablesGrid.BlockToDeviceRect((row, col), (row, col))
+ corner_x = rect.x + rect.width
+ corner_y = rect.y + self.VariablesGrid.GetColLabelSize()
+
+ # pop up this new menu
+ self.VariablesGrid.PopupMenuXY(type_menu, corner_x, corner_y)
+ event.Veto()
+ else:
+ event.Skip()
+
+ def GetVariableTypeFunction(self, base_type):
+ def VariableTypeFunction(event):
+ row = self.VariablesGrid.GetGridCursorRow()
+ self.Table.SetValueByName(row, "Type", base_type)
+ self.Table.ResetView(self.VariablesGrid)
+ self.SaveValues(False)
+ self.ParentWindow.RefreshEditor(variablepanel = False)
+ self.Controler.BufferProject()
+ self.ParentWindow._Refresh(TITLE, EDITMENU, INSTANCESTREE, LIBRARYTREE)
+ event.Skip()
+ return VariableTypeFunction
+
+ def OnVariablesGridCellLeftClick(self, event):
+ row = event.GetRow()
+ if event.GetCol() == 0 and self.Table.GetValueByName(row, "Edit"):
+ row = event.GetRow()
+ var_name = self.Table.GetValueByName(row, "Name")
+ var_class = self.Table.GetValueByName(row, "Class")
+ var_type = self.Table.GetValueByName(row, "Type")
+ data = wx.TextDataObject(str((var_name, var_class, var_type, self.TagName)))
+ dragSource = wx.DropSource(self.VariablesGrid)
+ dragSource.SetData(data)
+ dragSource.DoDragDrop()
+ event.Skip()
+
+ def OnVariablesGridSelectCell(self, event):
+ wx.CallAfter(self.RefreshButtons)
+ event.Skip()
+
+ def OnChar(self, event):
+ keycode = event.GetKeyCode()
+ if keycode == wx.WXK_DELETE:
+ row = self.Table.GetRow(self.VariablesGrid.GetGridCursorRow())
+ self.Values.remove(row)
+ self.SaveValues()
+ self.RefreshValues()
+ self.RefreshButtons()
+ event.Skip()
+
+ def MoveValue(self, value_index, move):
+ new_index = max(0, min(value_index + move, len(self.Values) - 1))
+ if new_index != value_index:
+ self.Values.insert(new_index, self.Values.pop(value_index))
+ self.SaveValues()
+ self.RefreshValues()
+ self.VariablesGrid.SetGridCursor(new_index, self.VariablesGrid.GetGridCursorCol())
+
+ def RefreshValues(self, select=0):
+ if len(self.Table.data) > 0:
+ self.VariablesGrid.SetGridCursor(0, 1)
+ data = []
+ for num, variable in enumerate(self.Values):
+ if variable["Class"] in self.ClassList:
+ variable["Number"] = num + 1
+ data.append(variable)
+ self.Table.SetData(data)
+ if len(self.Table.data) > 0:
+ if select == -1:
+ select = len(self.Table.data) - 1
+ self.VariablesGrid.SetGridCursor(select, 1)
+ self.VariablesGrid.MakeCellVisible(select, 1)
+ self.Table.ResetView(self.VariablesGrid)
+
+ def SaveValues(self, buffer = True):
+ words = self.TagName.split("::")
+ if self.ElementType == "config":
+ self.Controler.SetConfigurationGlobalVars(words[1], self.Values)
+ elif self.ElementType == "resource":
+ self.Controler.SetConfigurationResourceGlobalVars(words[1], words[2], self.Values)
+ else:
+ if self.ReturnType.IsEnabled():
+ self.Controler.SetPouInterfaceReturnType(words[1], self.ReturnType.GetStringSelection())
+ self.Controler.SetPouInterfaceVars(words[1], self.Values)
+ if buffer:
+ self.Controler.BufferProject()
+ self.ParentWindow._Refresh(TITLE, EDITMENU, INSTANCESTREE, LIBRARYTREE)
+
+ def AddVariableError(self, infos):
+ if isinstance(infos[0], TupleType):
+ for i in xrange(*infos[0]):
+ self.Table.AddError((i,) + infos[1:])
+ else:
+ self.Table.AddError(infos)
+ self.Table.ResetView(self.VariablesGrid)
+
+ def ClearErrors(self):
+ self.Table.ClearErrors()
+ self.Table.ResetView(self.VariablesGrid)
+
+class LocationCellControl(wx.PyControl):
+ '''
+ Custom cell editor control with a text box and a button that launches
+ the BrowseVariableLocationsDialog.
+ '''
+ def __init__(self, parent, var_panel):
+ wx.Control.__init__(self, parent, -1)
+ self.ParentWindow = parent
+ self.VarPanel = var_panel
+ self.Row = -1
+
+ self.Bind(wx.EVT_SIZE, self.OnSize)
+
+ # create text control
+ self.txt = wx.TextCtrl(self, -1, '', size=wx.Size(0, 0))
+
+ # create browse button
+ self.btn = wx.Button(self, -1, label='...', size=wx.Size(30, 0))
+ self.btn.Bind(wx.EVT_BUTTON, self.OnBtnBrowseClick)
+
+ self.Sizer = wx.FlexGridSizer(cols=2, hgap=0, rows=1, vgap=0)
+ self.Sizer.AddWindow(self.txt, 0, border=0, flag=wx.ALL|wx.GROW)
+ self.Sizer.AddWindow(self.btn, 0, border=0, flag=wx.ALL|wx.GROW)
+ self.Sizer.AddGrowableCol(0)
+ self.Sizer.AddGrowableRow(0)
+
+ self.SetSizer(self.Sizer)
+
+ def SetRow(self, row):
+ '''set the grid row that we're working on'''
+ self.Row = row
+
+ def OnSize(self, event):
+ '''resize the button and text control to fit'''
+ #overall_width = self.GetSize()[0]
+ #btn_width, btn_height = self.btn.GetSize()
+ #new_txt_width = overall_width - btn_width
+
+ #self.txt.SetSize(wx.Size(new_txt_width, -1))
+ #self.btn.SetDimensions(new_txt_width, -1, btn_width, btn_height)
+ self.Layout()
+
+ def OnBtnBrowseClick(self, event):
+ # pop up the location browser dialog
+ dia = BrowseVariableLocationsDialog(self.ParentWindow, self.VarPanel)
+ dia.ShowModal()
+
+ if dia.Selection:
+ loc, iec_type, doc = dia.Selection
+
+ # set the location
+ self.SetText(loc)
+
+ # set the variable type and documentation
+ # NOTE: this update won't be displayed until editing is complete
+ # (when EndEdit is called).
+ # we can't call VarPanel.RefreshValues() here because it causes
+ # an exception.
+ self.VarPanel.Table.SetValueByName(self.Row, 'Type', iec_type)
+ self.VarPanel.Table.SetValueByName(self.Row, 'Documentation', doc)
+
+ self.txt.SetFocus()
+
+ def SetText(self, text):
+ self.txt.SetValue(text)
+
+ def SetInsertionPoint(self, i):
+ self.txt.SetInsertionPoint(i)
+
+ def GetText(self):
+ return self.txt.GetValue()
+
+ def SetFocus(self):
+ self.txt.SetFocus()
+
+class LocationCellEditor(wx.grid.PyGridCellEditor):
+ '''
+ Grid cell editor that uses LocationCellControl to display a browse button.
+ '''
+ def __init__(self, var_panel):
+ wx.grid.PyGridCellEditor.__init__(self)
+ self.VarPanel = var_panel
+
+ def Create(self, parent, id, evt_handler):
+ self.text_browse = LocationCellControl(parent, self.VarPanel)
+ self.SetControl(self.text_browse)
+ if evt_handler:
+ self.text_browse.PushEventHandler(evt_handler)
+
+ def BeginEdit(self, row, col, grid):
+ loc = self.VarPanel.Table.GetValueByName(row, 'Location')
+ self.text_browse.SetText(loc)
+ self.text_browse.SetRow(row)
+ self.text_browse.SetFocus()
+
+ def EndEdit(self, row, col, grid):
+ loc = self.text_browse.GetText()
+ old_loc = self.VarPanel.Table.GetValueByName(row, 'Location')
+
+ if loc != old_loc:
+ self.VarPanel.Table.SetValueByName(row, 'Location', loc)
+
+ # NOTE: this is a really lame hack to force this row's
+ # 'Type' cell to redraw (since it may have changed).
+ # There's got to be a better way than this.
+ self.VarPanel.VariablesGrid.AutoSizeRow(row)
+ return True
+
+ def SetSize(self, rect):
+ self.text_browse.SetDimensions(rect.x + 1, rect.y,
+ rect.width, rect.height,
+ wx.SIZE_ALLOW_MINUS_ONE)
+
+ def Clone(self):
+ return LocationCellEditor(self.VarPanel)
+
+class BrowseVariableLocationsDialog(wx.Dialog):
+ # turn LOCATIONDATATYPES inside-out
+ LOCATION_SIZES = {}
+ for size, types in LOCATIONDATATYPES.iteritems():
+ for type in types:
+ LOCATION_SIZES[type] = size
+
+ class PluginData:
+ '''contains a plugin's VariableLocationTree'''
+ def __init__(self, plugin):
+ self.subtree = plugin.GetVariableLocationTree()
+
+ class SubtreeData:
+ '''contains a subtree of a plugin's VariableLocationTree'''
+ def __init__(self, subtree):
+ self.subtree = subtree
+
+ class VariableData:
+ '''contains all the information about a valid variable location'''
+ def __init__(self, type, dir, loc):
+ self.type = type
+
+ loc_suffix = '.'.join([str(x) for x in loc])
+
+ size = BrowseVariableLocationsDialog.LOCATION_SIZES[type]
+ self.loc = size + loc_suffix
+
+ # if a direction was given, use it
+ # (if not we'll prompt the user to select one)
+ if dir:
+ self.loc = '%' + dir + self.loc
+
+ def __init__(self, parent, var_panel):
+ self.VarPanel = var_panel
+ self.Selection = None
+
+ # create the dialog
+ wx.Dialog.__init__(self, parent=parent, title=_('Browse Variables'),
+ style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER,
+ size=(-1, 400))
+
+ # create the root sizer
+ sizer = wx.BoxSizer(wx.VERTICAL)
+ self.SetSizer(sizer)
+
+ # create the tree control
+ self.tree = wx.TreeCtrl(self, style=wx.TR_DEFAULT_STYLE|wx.TR_HIDE_ROOT)
+ sizer.Add(self.tree, 1, wx.EXPAND|wx.ALL, border=20)
+
+ # create the Direction sizer and field
+ dsizer = wx.BoxSizer(wx.HORIZONTAL)
+ sizer.Add(dsizer, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, border=20)
+
+ # direction label
+ ltext = wx.StaticText(self, -1, _('Direction:'))
+ dsizer.Add(ltext, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, border=20)
+
+ # direction choice
+ self.DirChoice = wx.Choice(id=-1, parent=self, choices=[_('Input'), _('Output'), _('Memory')])
+ dsizer.Add(self.DirChoice, flag=wx.EXPAND)
+ # set a default for the choice
+ self.SetSelectedDirection('I')
+
+ # create the button sizer
+ btsizer = wx.BoxSizer(wx.HORIZONTAL)
+ sizer.Add(btsizer, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.ALIGN_RIGHT, border=20)
+
+ # add plugins to the tree
+ root = self.tree.AddRoot(_('Plugins'))
+ ctrl = self.VarPanel.Controler
+ self.AddChildPluginsToTree(ctrl, root)
+
+ # -- buttons --
+
+ # ok button
+ self.OkButton = wx.Button(self, wx.ID_OK, _('Use Location'))
+ self.OkButton.SetDefault()
+ btsizer.Add(self.OkButton, flag=wx.RIGHT, border=5)
+
+ # cancel button
+ b = wx.Button(self, wx.ID_CANCEL, _('Cancel'))
+ btsizer.Add(b)
+
+ # -- event handlers --
+
+ # accept the location on doubleclick or clicking the Use Location button
+ self.Bind(wx.EVT_BUTTON, self.OnOk, self.OkButton)
+ self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnOk, self.tree)
+
+ # disable the Add button when we're not on a valid variable
+ self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChange, self.tree)
+
+ # handle the Expand event. this lets us create the tree as it's expanded
+ # (trying to create it all at once is slow since plugin variable location
+ # trees can be big)
+ wx.EVT_TREE_ITEM_EXPANDING(self.tree, self.tree.GetId(), self.OnExpand)
+
+ def OnExpand(self, event):
+ item = event.GetItem()
+ if not item.IsOk():
+ item = self.tree.GetSelection()
+
+ data = self.tree.GetPyData(item)
+ self.ExpandTree(item, data.subtree)
+
+ def AddChildPluginsToTree(self, plugin, root):
+ for p in plugin.IECSortedChilds():
+ plug_name = p.BaseParams.getName()
+ new_item = self.tree.AppendItem(root, plug_name)
+
+ # make it look like the tree item has children (since it doesn't yet)
+ self.tree.SetItemHasChildren(new_item)
+
+ # attach the plugin data to the tree item
+ self.tree.SetPyData(new_item, BrowseVariableLocationsDialog.PluginData(p))
+
+ # add child plugins recursively
+ self.AddChildPluginsToTree(p, new_item)
+
+ def ExpandTree(self, root, subtree):
+ items = subtree.items()
+ items.sort()
+
+ for node_name, data in items:
+ if isinstance(data, dict):
+ # this is a new subtree
+
+ new_item = self.tree.AppendItem(root, node_name)
+ self.tree.SetItemHasChildren(new_item)
+
+ # attach the new subtree's data to the tree item
+ new_data = BrowseVariableLocationsDialog.SubtreeData(data)
+ self.tree.SetPyData(new_item, new_data)
+ else:
+ # this is a new leaf.
+
+ # data is a tuple containing (IEC type, I/Q/M/None, IEC path tuple)
+ type, dir, loc = data
+
+ node_name = '%s (%s)' % (node_name, type)
+ new_item = self.tree.AppendItem(root, node_name)
+
+ vd = BrowseVariableLocationsDialog.VariableData(type, dir, loc)
+ self.tree.SetPyData(new_item, vd)
+
+ def OnSelChange(self, event):
+ '''updates the text field and the "Use Location" button.'''
+ item = self.tree.GetSelection()
+ data = self.tree.GetPyData(item)
+
+ if isinstance(data, BrowseVariableLocationsDialog.VariableData):
+ self.OkButton.Enable()
+
+ location = data.loc
+ if location[0] == '%':
+ # location has a fixed direction
+ self.SetSelectedDirection(location[1])
+ self.DirChoice.Disable()
+ else:
+ # this location can have any direction (user selects)
+ self.DirChoice.Enable()
+ else:
+ self.OkButton.Disable()
+ self.DirChoice.Disable()
+
+ def GetSelectedDirection(self):
+ selected = self.DirChoice.GetSelection()
+ if selected == 0:
+ return 'I'
+ elif selected == 1:
+ return 'Q'
+ else:
+ return 'M'
+
+ def SetSelectedDirection(self, dir_letter):
+ if dir_letter == 'I':
+ self.DirChoice.SetSelection(0)
+ elif dir_letter == 'Q':
+ self.DirChoice.SetSelection(1)
+ else:
+ self.DirChoice.SetSelection(2)
+
+ def OnOk(self, event):
+ item = self.tree.GetSelection()
+ data = self.tree.GetPyData(item)
+
+ if not isinstance(data, BrowseVariableLocationsDialog.VariableData):
+ return
+
+ location = data.loc
+
+ if location[0] != '%':
+ # no direction was given, grab the one from the wxChoice
+ dir = self.GetSelectedDirection()
+ location = '%' + dir + location
+
+ # walk up the tree, building documentation for the variable
+ documentation = self.tree.GetItemText(item)
+ parent = self.tree.GetItemParent(item)
+ root = self.tree.GetRootItem()
+ while parent != root:
+ text = self.tree.GetItemText(parent)
+ documentation = text + ":" + documentation
+ parent = self.tree.GetItemParent(parent)
+
+ self.Selection = (location, data.type, documentation)
+ self.Destroy()