# HG changeset patch # User b.taylor@willowglen.ca # Date 1251916792 21600 # Node ID a06221a0930b7947ab2bce78524cfd62255b0cca # Parent 218142afdb537591685af074ed6cae59d3b00e4b split the variable editor panel into its own file diff -r 218142afdb53 -r a06221a0930b PLCOpenEditor.py --- a/PLCOpenEditor.py Wed Sep 02 12:38:06 2009 -0600 +++ b/PLCOpenEditor.py Wed Sep 02 12:39:52 2009 -0600 @@ -108,7 +108,7 @@ from RessourceEditor import * from DataTypeEditor import * from PLCControler import * -from plcopen.structures import LOCATIONDATATYPES +from VariablePanel import VariablePanel # Define PLCOpenEditor controls id [ID_PLCOPENEDITOR, ID_PLCOPENEDITORTREENOTEBOOK, @@ -3847,773 +3847,6 @@ panel.ClearErrors() #------------------------------------------------------------------------------- -# Variables Editor Panel -#------------------------------------------------------------------------------- - -def GetVariableTableColnames(location): - _ = lambda x : x - if location: - return ["#", _("Name"), _("Class"), _("Type"), _("Location"), _("Initial Value"), _("Retain"), _("Constant")] - return ["#", _("Name"), _("Class"), _("Type"), _("Initial Value"), _("Retain"), _("Constant")] - -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 = wx.grid.GridCellTextEditor() - 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): - - 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 affect a location to a function block instance") - elif self.ParentWindow.Table.GetValueByName(row, "Class") not in ["Local", "Global"]: - message = _("Can affect a location only 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() - - if element_type in ["config", "resource"]: - self.DefaultTypes = {"All" : "Global"} - self.DefaultValue = {"Name" : "", "Class" : "", "Type" : "INT", "Location" : "", "Initial Value" : "", "Retain" : "No", "Constant" : "No", "Edit" : True} - else: - self.DefaultTypes = {"All" : "Local", "Interface" : "Input", "Variables" : "Local"} - self.DefaultValue = {"Name" : "", "Class" : "", "Type" : "INT", "Location" : "", "Initial Value" : "", "Retain" : "No", "Constant" : "No", "Edit" : True} - if element_type in ["config", "resource"] or element_type in ["program", "transition", "action"]: - self.Table = VariableTable(self, [], GetVariableTableColnames(True)) - if element_type not in ["config", "resource"]: - self.FilterChoices = ["All", "Interface", " Input", " Output", " InOut", " External", "Variables", " Local", " Temp"]#,"Access"] - else: - self.FilterChoices = ["All", "Global"]#,"Access"] - self.ColSizes = [40, 80, 70, 80, 80, 80, 60, 70] - self.ColAlignements = [wx.ALIGN_CENTER, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_CENTER, wx.ALIGN_CENTER] - else: - 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"] - self.ColSizes = [40, 120, 70, 80, 120, 60, 70] - self.ColAlignements = [wx.ALIGN_CENTER, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_CENTER, wx.ALIGN_CENTER] - 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, self.ParentWindow.Debug) - pouname, poutype = self.Controler.GetEditedElementType(self.TagName, self.ParentWindow.Debug) - if poutype != "function" and bodytype in ["ST", "IL"]: - return False - else: - return name in self.Controler.GetFunctionBlockTypes(self.TagName, self.ParentWindow.Debug) - - def RefreshView(self): - self.PouNames = self.Controler.GetProjectPouNames(self.ParentWindow.Debug) - - words = self.TagName.split("::") - if self.ElementType == "config": - self.PouIsUsed = False - returnType = None - self.Values = self.Controler.GetConfigurationGlobalVars(words[1], self.ParentWindow.Debug) - elif self.ElementType == "resource": - self.PouIsUsed = False - returnType = None - self.Values = self.Controler.GetConfigurationResourceGlobalVars(words[1], words[2], self.ParentWindow.Debug) - else: - self.PouIsUsed = self.Controler.PouIsUsed(words[1], self.ParentWindow.Debug) - returnType = self.Controler.GetEditedElementInterfaceReturnType(self.TagName, self.ParentWindow.Debug) - self.Values = self.Controler.GetEditedElementInterfaceVars(self.TagName, self.ParentWindow.Debug) - - 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.RefreshTitle() - self.ParentWindow.RefreshEditMenu() - self.ParentWindow.RefreshInstancesTree() - self.ParentWindow.RefreshLibraryTree() - 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) - 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.RefreshTitle() - self.ParentWindow.RefreshEditMenu() - self.ParentWindow.RefreshInstancesTree() - self.ParentWindow.RefreshLibraryTree() - 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() - classtype = self.Table.GetValueByName(row, "Class") - if self.Table.GetColLabelValue(col) == "Type": - type_menu = wx.Menu(title='') - 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) - datatype_menu = wx.Menu(title='') - for datatype in self.Controler.GetDataTypes(basetypes = False, debug = self.ParentWindow.Debug): - 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) - functionblock_menu = wx.Menu(title='') - bodytype = self.Controler.GetEditedElementBodyType(self.TagName, self.ParentWindow.Debug) - pouname, poutype = self.Controler.GetEditedElementType(self.TagName, self.ParentWindow.Debug) - if classtype in ["Input","Output","InOut","External","Global"] or poutype != "function" and bodytype in ["ST", "IL"]: - for functionblock_type in self.Controler.GetFunctionBlockTypes(self.TagName, self.ParentWindow.Debug): - 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)) - self.VariablesGrid.PopupMenuXY(type_menu, rect.x + rect.width, rect.y + self.VariablesGrid.GetColLabelSize()) - 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.RefreshTitle() - self.ParentWindow.RefreshEditMenu() - self.ParentWindow.RefreshInstancesTree() - self.ParentWindow.RefreshLibraryTree() - 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.RefreshTitle() - self.ParentWindow.RefreshEditMenu() - self.ParentWindow.RefreshInstancesTree() - self.ParentWindow.RefreshLibraryTree() - - 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) - -#------------------------------------------------------------------------------- # Debug Variables Panel #------------------------------------------------------------------------------- diff -r 218142afdb53 -r a06221a0930b VariablePanel.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/VariablePanel.py Wed Sep 02 12:39:52 2009 -0600 @@ -0,0 +1,794 @@ +# -*- 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 PLCOpenEditor import AppendMenu +from plcopen.structures import LOCATIONDATATYPES, TestIdentifier, IEC_KEYWORDS + +#------------------------------------------------------------------------------- +# Variables Editor Panel +#------------------------------------------------------------------------------- + +def GetVariableTableColnames(location): + _ = lambda x : x + if location: + return ["#", _("Name"), _("Class"), _("Type"), _("Location"), _("Initial Value"), _("Retain"), _("Constant")] + return ["#", _("Name"), _("Class"), _("Type"), _("Initial Value"), _("Retain"), _("Constant")] + +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 = wx.grid.GridCellTextEditor() + 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): + + 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 affect a location to a function block instance") + elif self.ParentWindow.Table.GetValueByName(row, "Class") not in ["Local", "Global"]: + message = _("Can affect a location only 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() + + if element_type in ["config", "resource"]: + self.DefaultTypes = {"All" : "Global"} + self.DefaultValue = {"Name" : "", "Class" : "", "Type" : "INT", "Location" : "", "Initial Value" : "", "Retain" : "No", "Constant" : "No", "Edit" : True} + else: + self.DefaultTypes = {"All" : "Local", "Interface" : "Input", "Variables" : "Local"} + self.DefaultValue = {"Name" : "", "Class" : "", "Type" : "INT", "Location" : "", "Initial Value" : "", "Retain" : "No", "Constant" : "No", "Edit" : True} + if element_type in ["config", "resource"] or element_type in ["program", "transition", "action"]: + self.Table = VariableTable(self, [], GetVariableTableColnames(True)) + if element_type not in ["config", "resource"]: + self.FilterChoices = ["All", "Interface", " Input", " Output", " InOut", " External", "Variables", " Local", " Temp"]#,"Access"] + else: + self.FilterChoices = ["All", "Global"]#,"Access"] + self.ColSizes = [40, 80, 70, 80, 80, 80, 60, 70] + self.ColAlignements = [wx.ALIGN_CENTER, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_CENTER, wx.ALIGN_CENTER] + else: + 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"] + self.ColSizes = [40, 120, 70, 80, 120, 60, 70] + self.ColAlignements = [wx.ALIGN_CENTER, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_CENTER, wx.ALIGN_CENTER] + 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, self.ParentWindow.Debug) + pouname, poutype = self.Controler.GetEditedElementType(self.TagName, self.ParentWindow.Debug) + if poutype != "function" and bodytype in ["ST", "IL"]: + return False + else: + return name in self.Controler.GetFunctionBlockTypes(self.TagName, self.ParentWindow.Debug) + + def RefreshView(self): + self.PouNames = self.Controler.GetProjectPouNames(self.ParentWindow.Debug) + + words = self.TagName.split("::") + if self.ElementType == "config": + self.PouIsUsed = False + returnType = None + self.Values = self.Controler.GetConfigurationGlobalVars(words[1], self.ParentWindow.Debug) + elif self.ElementType == "resource": + self.PouIsUsed = False + returnType = None + self.Values = self.Controler.GetConfigurationResourceGlobalVars(words[1], words[2], self.ParentWindow.Debug) + else: + self.PouIsUsed = self.Controler.PouIsUsed(words[1], self.ParentWindow.Debug) + returnType = self.Controler.GetEditedElementInterfaceReturnType(self.TagName, self.ParentWindow.Debug) + self.Values = self.Controler.GetEditedElementInterfaceVars(self.TagName, self.ParentWindow.Debug) + + 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.RefreshTitle() + self.ParentWindow.RefreshEditMenu() + self.ParentWindow.RefreshInstancesTree() + self.ParentWindow.RefreshLibraryTree() + 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) + 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.RefreshTitle() + self.ParentWindow.RefreshEditMenu() + self.ParentWindow.RefreshInstancesTree() + self.ParentWindow.RefreshLibraryTree() + 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() + classtype = self.Table.GetValueByName(row, "Class") + if self.Table.GetColLabelValue(col) == "Type": + type_menu = wx.Menu(title='') + 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) + datatype_menu = wx.Menu(title='') + for datatype in self.Controler.GetDataTypes(basetypes = False, debug = self.ParentWindow.Debug): + 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) + functionblock_menu = wx.Menu(title='') + bodytype = self.Controler.GetEditedElementBodyType(self.TagName, self.ParentWindow.Debug) + pouname, poutype = self.Controler.GetEditedElementType(self.TagName, self.ParentWindow.Debug) + if classtype in ["Input","Output","InOut","External","Global"] or poutype != "function" and bodytype in ["ST", "IL"]: + for functionblock_type in self.Controler.GetFunctionBlockTypes(self.TagName, self.ParentWindow.Debug): + 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)) + self.VariablesGrid.PopupMenuXY(type_menu, rect.x + rect.width, rect.y + self.VariablesGrid.GetColLabelSize()) + 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.RefreshTitle() + self.ParentWindow.RefreshEditMenu() + self.ParentWindow.RefreshInstancesTree() + self.ParentWindow.RefreshLibraryTree() + 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.RefreshTitle() + self.ParentWindow.RefreshEditMenu() + self.ParentWindow.RefreshInstancesTree() + self.ParentWindow.RefreshLibraryTree() + + 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)