b@418: # -*- coding: utf-8 -*- b@418: b@418: #This file is part of PLCOpenEditor, a library implementing an IEC 61131-3 editor b@418: #based on the plcopen standard. b@418: # b@418: #Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD b@418: # b@418: #See COPYING file for copyrights details. b@418: # b@418: #This library is free software; you can redistribute it and/or b@418: #modify it under the terms of the GNU General Public b@418: #License as published by the Free Software Foundation; either b@418: #version 2.1 of the License, or (at your option) any later version. b@418: # b@418: #This library is distributed in the hope that it will be useful, b@418: #but WITHOUT ANY WARRANTY; without even the implied warranty of b@418: #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU b@418: #General Public License for more details. b@418: # b@418: #You should have received a copy of the GNU General Public b@418: #License along with this library; if not, write to the Free Software b@418: #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA b@418: laurent@436: import os b@418: import wx, wx.grid b@418: b@419: from types import TupleType b@419: b@418: from plcopen.structures import LOCATIONDATATYPES, TestIdentifier, IEC_KEYWORDS laurent@436: from PLCControler import LOCATION_PLUGIN, LOCATION_MODULE, LOCATION_GROUP, LOCATION_VAR_INPUT, LOCATION_VAR_OUTPUT, LOCATION_VAR_MEMORY laurent@436: laurent@436: CWD = os.path.split(os.path.realpath(__file__))[0] laurent@431: laurent@431: # Compatibility function for wx versions < 2.6 laurent@431: def AppendMenu(parent, help, id, kind, text): laurent@431: if wx.VERSION >= (2, 6, 0): laurent@431: parent.Append(help=help, id=id, kind=kind, text=text) laurent@431: else: laurent@431: parent.Append(helpString=help, id=id, kind=kind, item=text) laurent@431: laurent@431: [TITLE, TOOLBAR, FILEMENU, EDITMENU, DISPLAYMENU, TYPESTREE, laurent@431: INSTANCESTREE, LIBRARYTREE, SCALING laurent@431: ] = range(9) b@418: b@418: #------------------------------------------------------------------------------- b@418: # Variables Editor Panel b@418: #------------------------------------------------------------------------------- b@418: b@418: def GetVariableTableColnames(location): b@418: _ = lambda x : x b@418: if location: laurent@483: return ["#", _("Name"), _("Class"), _("Type"), _("Location"), _("Initial Value"), _("Option"), _("Documentation")] laurent@483: return ["#", _("Name"), _("Class"), _("Type"), _("Initial Value"), _("Option"), _("Documentation")] laurent@483: laurent@484: def GetOptions(constant=True, retain=True, non_retain=True): b@418: _ = lambda x : x laurent@484: options = [""] laurent@484: if constant: laurent@484: options.append(_("Constant")) laurent@484: if retain: laurent@484: options.append(_("Retain")) laurent@484: if non_retain: laurent@484: options.append(_("Non-Retain")) laurent@484: return options laurent@483: OPTIONS_DICT = dict([(_(option), option) for option in GetOptions()]) b@418: b@418: def GetFilterChoiceTransfer(): b@418: _ = lambda x : x b@418: return {_("All"): _("All"), _("Interface"): _("Interface"), b@418: _(" Input"): _("Input"), _(" Output"): _("Output"), _(" InOut"): _("InOut"), b@418: _(" External"): _("External"), _("Variables"): _("Variables"), _(" Local"): _("Local"), b@418: _(" Temp"): _("Temp"), _("Global"): _("Global")}#, _("Access") : _("Access")} b@418: VARIABLE_CLASSES_DICT = dict([(_(_class), _class) for _class in GetFilterChoiceTransfer().itervalues()]) b@418: laurent@484: CheckOptionForClass = {"Local": lambda x: x, laurent@484: "Temp": lambda x: "", laurent@484: "Input": lambda x: {"Retain": "Retain", "Non-Retain": "Non-Retain"}.get(x, ""), laurent@484: "InOut": lambda x: "", laurent@484: "Output": lambda x: {"Retain": "Retain", "Non-Retain": "Non-Retain"}.get(x, ""), laurent@484: "Global": lambda x: {"Constant": "Constant", "Retain": "Retain"}.get(x, ""), laurent@484: "External": lambda x: {"Constant": "Constant"}.get(x, "") laurent@484: } laurent@484: b@418: class VariableTable(wx.grid.PyGridTableBase): b@418: b@418: """ b@418: A custom wx.grid.Grid Table using user supplied data b@418: """ b@418: def __init__(self, parent, data, colnames): b@418: # The base class must be initialized *first* b@418: wx.grid.PyGridTableBase.__init__(self) b@418: self.data = data b@418: self.old_value = None b@418: self.colnames = colnames b@418: self.Errors = {} b@418: self.Parent = parent b@418: # XXX b@418: # we need to store the row length and collength to b@418: # see if the table has changed size b@418: self._rows = self.GetNumberRows() b@418: self._cols = self.GetNumberCols() b@418: b@418: def GetNumberCols(self): b@418: return len(self.colnames) b@418: b@418: def GetNumberRows(self): b@418: return len(self.data) b@418: b@418: def GetColLabelValue(self, col, translate=True): b@418: if col < len(self.colnames): b@418: if translate: b@418: return _(self.colnames[col]) b@418: return self.colnames[col] b@418: b@418: def GetRowLabelValues(self, row, translate=True): b@418: return row b@418: b@418: def GetValue(self, row, col): b@418: if row < self.GetNumberRows(): b@418: if col == 0: b@418: return self.data[row]["Number"] b@418: colname = self.GetColLabelValue(col, False) b@418: value = str(self.data[row].get(colname, "")) laurent@483: if colname in ["Class", "Option"]: b@418: return _(value) b@418: return value b@418: b@418: def SetValue(self, row, col, value): b@418: if col < len(self.colnames): b@418: colname = self.GetColLabelValue(col, False) b@418: if colname == "Name": b@418: self.old_value = self.data[row][colname] b@418: elif colname == "Class": b@418: value = VARIABLE_CLASSES_DICT[value] laurent@484: self.SetValueByName(row, "Option", CheckOptionForClass[value](self.GetValueByName(row, "Option"))) laurent@484: if value == "External": laurent@484: self.SetValueByName(row, "Initial Value", "") laurent@483: elif colname == "Option": laurent@483: value = OPTIONS_DICT[value] b@418: self.data[row][colname] = value b@418: b@418: def GetValueByName(self, row, colname): b@418: if row < self.GetNumberRows(): b@418: return self.data[row].get(colname) b@418: b@418: def SetValueByName(self, row, colname, value): b@418: if row < self.GetNumberRows(): b@418: self.data[row][colname] = value b@418: b@418: def GetOldValue(self): b@418: return self.old_value b@418: b@418: def ResetView(self, grid): b@418: """ b@418: (wx.grid.Grid) -> Reset the grid view. Call this to b@418: update the grid if rows and columns have been added or deleted b@418: """ b@418: grid.BeginBatch() b@418: for current, new, delmsg, addmsg in [ b@418: (self._rows, self.GetNumberRows(), wx.grid.GRIDTABLE_NOTIFY_ROWS_DELETED, wx.grid.GRIDTABLE_NOTIFY_ROWS_APPENDED), b@418: (self._cols, self.GetNumberCols(), wx.grid.GRIDTABLE_NOTIFY_COLS_DELETED, wx.grid.GRIDTABLE_NOTIFY_COLS_APPENDED), b@418: ]: b@418: if new < current: b@418: msg = wx.grid.GridTableMessage(self,delmsg,new,current-new) b@418: grid.ProcessTableMessage(msg) b@418: elif new > current: b@418: msg = wx.grid.GridTableMessage(self,addmsg,new-current) b@418: grid.ProcessTableMessage(msg) b@418: self.UpdateValues(grid) b@418: grid.EndBatch() b@418: b@418: self._rows = self.GetNumberRows() b@418: self._cols = self.GetNumberCols() b@418: # update the column rendering scheme b@418: self._updateColAttrs(grid) b@418: b@418: # update the scrollbars and the displayed part of the grid b@418: grid.AdjustScrollbars() b@418: grid.ForceRefresh() b@418: b@418: def UpdateValues(self, grid): b@418: """Update all displayed values""" b@418: # This sends an event to the grid table to update all of the values b@418: msg = wx.grid.GridTableMessage(self, wx.grid.GRIDTABLE_REQUEST_VIEW_GET_VALUES) b@418: grid.ProcessTableMessage(msg) b@418: b@418: def _updateColAttrs(self, grid): b@418: """ b@418: wx.grid.Grid -> update the column attributes to add the b@418: appropriate renderer given the column name. b@418: b@418: Otherwise default to the default renderer. b@418: """ b@418: for row in range(self.GetNumberRows()): laurent@484: var_class = self.GetValueByName(row, "Class") b@418: for col in range(self.GetNumberCols()): b@418: editor = None b@418: renderer = None b@418: colname = self.GetColLabelValue(col, False) laurent@483: if colname == "Option": laurent@484: options = GetOptions(constant = var_class in ["Local", "External", "Global"], laurent@484: retain = self.Parent.ElementType != "function" and var_class in ["Local", "Input", "Output", "Global"], laurent@484: non_retain = self.Parent.ElementType != "function" and var_class in ["Local", "Input", "Output"]) laurent@484: if len(options) > 1: laurent@484: editor = wx.grid.GridCellChoiceEditor() laurent@484: editor.SetParameters(",".join(map(_, options))) laurent@484: else: laurent@484: grid.SetReadOnly(row, col, True) laurent@483: elif col != 0 and self.GetValueByName(row, "Edit"): b@418: grid.SetReadOnly(row, col, False) b@418: if colname == "Name": laurent@484: if self.Parent.PouIsUsed and var_class in ["Input", "Output", "InOut"]: b@418: grid.SetReadOnly(row, col, True) b@418: else: b@418: editor = wx.grid.GridCellTextEditor() b@418: renderer = wx.grid.GridCellStringRenderer() b@418: elif colname == "Initial Value": laurent@484: if var_class != "External": laurent@484: editor = wx.grid.GridCellTextEditor() laurent@484: renderer = wx.grid.GridCellStringRenderer() laurent@484: else: laurent@484: grid.SetReadOnly(row, col, True) b@418: elif colname == "Location": laurent@484: if var_class in ["Local", "Global"]: laurent@436: editor = LocationCellEditor(self, self.Parent.Controler) b@418: renderer = wx.grid.GridCellStringRenderer() b@418: else: b@418: grid.SetReadOnly(row, col, True) b@418: elif colname == "Class": laurent@484: if len(self.Parent.ClassList) == 1 or self.Parent.PouIsUsed and var_class in ["Input", "Output", "InOut"]: b@418: grid.SetReadOnly(row, col, True) b@418: else: b@418: editor = wx.grid.GridCellChoiceEditor() b@418: excluded = [] b@418: if self.Parent.PouIsUsed: b@418: excluded.extend(["Input","Output","InOut"]) b@418: if self.Parent.IsFunctionBlockType(self.data[row]["Type"]): b@418: excluded.extend(["Local","Temp"]) b@418: editor.SetParameters(",".join([_(choice) for choice in self.Parent.ClassList if choice not in excluded])) laurent@483: elif colname != "Documentation": b@418: grid.SetReadOnly(row, col, True) b@418: b@418: grid.SetCellEditor(row, col, editor) b@418: grid.SetCellRenderer(row, col, renderer) b@418: b@418: if row in self.Errors and self.Errors[row][0] == colname.lower(): b@418: grid.SetCellBackgroundColour(row, col, wx.Colour(255, 255, 0)) b@418: grid.SetCellTextColour(row, col, wx.RED) b@418: grid.MakeCellVisible(row, col) b@418: else: b@418: grid.SetCellTextColour(row, col, wx.BLACK) b@418: grid.SetCellBackgroundColour(row, col, wx.WHITE) b@418: b@418: def SetData(self, data): b@418: self.data = data b@418: b@418: def GetData(self): b@418: return self.data b@418: b@418: def GetCurrentIndex(self): b@418: return self.CurrentIndex b@418: b@418: def SetCurrentIndex(self, index): b@418: self.CurrentIndex = index b@418: b@418: def AppendRow(self, row_content): b@418: self.data.append(row_content) b@418: b@418: def RemoveRow(self, row_index): b@418: self.data.pop(row_index) b@418: b@418: def GetRow(self, row_index): b@418: return self.data[row_index] b@418: b@418: def Empty(self): b@418: self.data = [] b@418: self.editors = [] b@418: b@418: def AddError(self, infos): b@418: self.Errors[infos[0]] = infos[1:] b@418: b@418: def ClearErrors(self): b@418: self.Errors = {} b@418: b@418: class VariableDropTarget(wx.TextDropTarget): b@419: ''' b@419: This allows dragging a variable location from somewhere to the Location b@419: column of a variable row. b@419: b@419: The drag source should be a TextDataObject containing a Python tuple like: b@419: ('%ID0.0.0', 'location', 'REAL') b@419: b@419: c_ext/CFileEditor.py has an example of this (you can drag a C extension b@419: variable to the Location column of the variable panel). b@419: ''' b@418: def __init__(self, parent): b@418: wx.TextDropTarget.__init__(self) b@418: self.ParentWindow = parent b@418: b@418: def OnDropText(self, x, y, data): b@418: x, y = self.ParentWindow.VariablesGrid.CalcUnscrolledPosition(x, y) b@418: col = self.ParentWindow.VariablesGrid.XToCol(x) b@418: row = self.ParentWindow.VariablesGrid.YToRow(y - self.ParentWindow.VariablesGrid.GetColLabelSize()) b@418: if col != wx.NOT_FOUND and row != wx.NOT_FOUND: b@418: if self.ParentWindow.Table.GetColLabelValue(col, False) != "Location": b@418: return b@418: message = None b@418: if not self.ParentWindow.Table.GetValueByName(row, "Edit"): b@427: message = _("Can't give a location to a function block instance") b@418: elif self.ParentWindow.Table.GetValueByName(row, "Class") not in ["Local", "Global"]: b@427: message = _("Can only give a location to local or global variables") b@418: else: b@418: try: b@418: values = eval(data) b@418: except: b@418: message = _("Invalid value \"%s\" for location")%data b@418: values = None b@418: if not isinstance(values, TupleType): b@418: message = _("Invalid value \"%s\" for location")%data b@418: values = None b@418: if values is not None and values[1] == "location": b@418: location = values[0] b@418: variable_type = self.ParentWindow.Table.GetValueByName(row, "Type") b@418: base_type = self.ParentWindow.Controler.GetBaseType(variable_type) b@418: message = None b@418: if location.startswith("%"): b@418: if base_type != values[2]: b@418: message = _("Incompatible data types between \"%s\" and \"%s\"")%(values[2], variable_type) b@418: else: b@418: self.ParentWindow.Table.SetValue(row, col, location) b@418: self.ParentWindow.Table.ResetView(self.ParentWindow.VariablesGrid) b@418: self.ParentWindow.SaveValues() b@418: else: b@418: if location[0].isdigit() and base_type != "BOOL": b@418: message = _("Incompatible size of data between \"%s\" and \"BOOL\"")%location b@418: elif location[0] not in LOCATIONDATATYPES: b@418: message = _("Unrecognized data size \"%s\"")%location[0] b@418: elif base_type not in LOCATIONDATATYPES[location[0]]: b@418: message = _("Incompatible size of data between \"%s\" and \"%s\"")%(location, variable_type) b@418: else: b@418: dialog = wx.SingleChoiceDialog(self.ParentWindow, _("Select a variable class:"), _("Variable class"), ["Input", "Output", "Memory"], wx.OK|wx.CANCEL) b@418: if dialog.ShowModal() == wx.ID_OK: b@418: selected = dialog.GetSelection() b@418: if selected == 0: b@418: location = "%I" + location b@418: elif selected == 1: b@418: location = "%Q" + location b@418: else: b@418: location = "%M" + location b@418: self.ParentWindow.Table.SetValue(row, col, location) b@418: self.ParentWindow.Table.ResetView(self.ParentWindow.VariablesGrid) b@418: self.ParentWindow.SaveValues() b@418: dialog.Destroy() b@418: if message is not None: b@418: wx.CallAfter(self.ShowMessage, message) b@418: b@418: def ShowMessage(self, message): b@418: message = wx.MessageDialog(self.ParentWindow, message, _("Error"), wx.OK|wx.ICON_ERROR) b@418: message.ShowModal() b@418: message.Destroy() b@418: b@418: [ID_VARIABLEEDITORPANEL, ID_VARIABLEEDITORPANELVARIABLESGRID, b@418: ID_VARIABLEEDITORCONTROLPANEL, ID_VARIABLEEDITORPANELRETURNTYPE, b@418: ID_VARIABLEEDITORPANELCLASSFILTER, ID_VARIABLEEDITORPANELADDBUTTON, b@418: ID_VARIABLEEDITORPANELDELETEBUTTON, ID_VARIABLEEDITORPANELUPBUTTON, b@418: ID_VARIABLEEDITORPANELDOWNBUTTON, ID_VARIABLEEDITORPANELSTATICTEXT1, b@418: ID_VARIABLEEDITORPANELSTATICTEXT2, ID_VARIABLEEDITORPANELSTATICTEXT3, b@418: ] = [wx.NewId() for _init_ctrls in range(12)] b@418: b@418: class VariablePanel(wx.Panel): b@418: b@418: if wx.VERSION < (2, 6, 0): b@418: def Bind(self, event, function, id = None): b@418: if id is not None: b@418: event(self, id, function) b@418: else: b@418: event(self, function) b@418: b@418: def _init_coll_MainSizer_Items(self, parent): b@418: parent.AddWindow(self.VariablesGrid, 0, border=0, flag=wx.GROW) b@418: parent.AddWindow(self.ControlPanel, 0, border=5, flag=wx.GROW|wx.ALL) b@418: b@418: def _init_coll_MainSizer_Growables(self, parent): b@418: parent.AddGrowableCol(0) b@418: parent.AddGrowableRow(0) b@418: b@418: def _init_coll_ControlPanelSizer_Items(self, parent): b@418: parent.AddSizer(self.ChoicePanelSizer, 0, border=0, flag=wx.GROW) b@418: parent.AddSizer(self.ButtonPanelSizer, 0, border=0, flag=wx.ALIGN_CENTER) b@418: b@418: def _init_coll_ControlPanelSizer_Growables(self, parent): b@418: parent.AddGrowableCol(0) b@418: parent.AddGrowableRow(0) b@418: parent.AddGrowableRow(1) b@418: b@418: def _init_coll_ChoicePanelSizer_Items(self, parent): b@418: parent.AddWindow(self.staticText1, 0, border=0, flag=wx.ALIGN_BOTTOM) b@418: parent.AddWindow(self.ReturnType, 0, border=0, flag=0) b@418: parent.AddWindow(self.staticText2, 0, border=0, flag=wx.ALIGN_BOTTOM) b@418: parent.AddWindow(self.ClassFilter, 0, border=0, flag=0) b@418: b@418: def _init_coll_ButtonPanelSizer_Items(self, parent): b@418: parent.AddWindow(self.UpButton, 0, border=0, flag=0) b@418: parent.AddWindow(self.AddButton, 0, border=0, flag=0) b@418: parent.AddWindow(self.DownButton, 0, border=0, flag=0) b@418: parent.AddWindow(self.DeleteButton, 0, border=0, flag=0) b@418: b@418: def _init_coll_ButtonPanelSizer_Growables(self, parent): b@418: parent.AddGrowableCol(0) b@418: parent.AddGrowableCol(1) b@418: parent.AddGrowableCol(2) b@418: parent.AddGrowableCol(3) b@418: parent.AddGrowableRow(0) b@418: b@418: def _init_sizers(self): b@418: self.MainSizer = wx.FlexGridSizer(cols=2, hgap=10, rows=1, vgap=0) b@418: self.ControlPanelSizer = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=5) b@418: self.ChoicePanelSizer = wx.GridSizer(cols=1, hgap=5, rows=4, vgap=5) b@418: self.ButtonPanelSizer = wx.FlexGridSizer(cols=2, hgap=5, rows=2, vgap=5) b@418: b@418: self._init_coll_MainSizer_Items(self.MainSizer) b@418: self._init_coll_MainSizer_Growables(self.MainSizer) b@418: self._init_coll_ControlPanelSizer_Items(self.ControlPanelSizer) b@418: self._init_coll_ControlPanelSizer_Growables(self.ControlPanelSizer) b@418: self._init_coll_ChoicePanelSizer_Items(self.ChoicePanelSizer) b@418: self._init_coll_ButtonPanelSizer_Items(self.ButtonPanelSizer) b@418: self._init_coll_ButtonPanelSizer_Growables(self.ButtonPanelSizer) b@418: b@418: self.SetSizer(self.MainSizer) b@418: self.ControlPanel.SetSizer(self.ControlPanelSizer) b@418: b@418: def _init_ctrls(self, prnt): b@418: wx.Panel.__init__(self, id=ID_VARIABLEEDITORPANEL, b@418: name='VariableEditorPanel', parent=prnt, pos=wx.Point(0, 0), b@418: size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL) b@418: b@418: self.VariablesGrid = wx.grid.Grid(id=ID_VARIABLEEDITORPANELVARIABLESGRID, b@418: name='VariablesGrid', parent=self, pos=wx.Point(0, 0), b@418: size=wx.Size(0, 0), style=wx.VSCROLL) b@418: self.VariablesGrid.SetFont(wx.Font(12, 77, wx.NORMAL, wx.NORMAL, False, b@418: 'Sans')) b@418: self.VariablesGrid.SetLabelFont(wx.Font(10, 77, wx.NORMAL, wx.NORMAL, b@418: False, 'Sans')) b@418: self.VariablesGrid.SetSelectionBackground(wx.WHITE) b@418: self.VariablesGrid.SetSelectionForeground(wx.BLACK) b@418: if wx.VERSION >= (2, 6, 0): b@418: self.VariablesGrid.Bind(wx.grid.EVT_GRID_CELL_CHANGE, self.OnVariablesGridCellChange) b@418: self.VariablesGrid.Bind(wx.grid.EVT_GRID_SELECT_CELL, self.OnVariablesGridSelectCell) b@418: self.VariablesGrid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.OnVariablesGridCellLeftClick) b@418: self.VariablesGrid.Bind(wx.grid.EVT_GRID_EDITOR_SHOWN, self.OnVariablesGridEditorShown) b@418: #self.VariablesGrid.Bind(wx.EVT_KEY_DOWN, self.OnChar) b@418: else: b@418: wx.grid.EVT_GRID_CELL_CHANGE(self.VariablesGrid, self.OnVariablesGridCellChange) b@418: wx.grid.EVT_GRID_SELECT_CELL(self.VariablesGrid, self.OnVariablesGridSelectCell) b@418: wx.grid.EVT_GRID_CELL_LEFT_CLICK(self.VariablesGrid, self.OnVariablesGridCellLeftClick) b@418: wx.grid.EVT_GRID_EDITOR_SHOWN(self.VariablesGrid, self.OnVariablesGridEditorShown) b@418: #wx.EVT_KEY_DOWN(self.VariablesGrid, self.OnChar) b@418: self.VariablesGrid.SetDropTarget(VariableDropTarget(self)) b@418: b@418: self.ControlPanel = wx.ScrolledWindow(id=ID_VARIABLEEDITORCONTROLPANEL, b@418: name='ControlPanel', parent=self, pos=wx.Point(0, 0), b@418: size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL) b@418: self.ControlPanel.SetScrollRate(0, 10) b@418: b@418: self.staticText1 = wx.StaticText(id=ID_VARIABLEEDITORPANELSTATICTEXT1, b@418: label=_('Return Type:'), name='staticText1', parent=self.ControlPanel, b@418: pos=wx.Point(0, 0), size=wx.Size(145, 17), style=0) b@418: b@418: self.ReturnType = wx.ComboBox(id=ID_VARIABLEEDITORPANELRETURNTYPE, b@418: name='ReturnType', parent=self.ControlPanel, pos=wx.Point(0, 0), b@418: size=wx.Size(145, 28), style=wx.CB_READONLY) b@418: self.Bind(wx.EVT_COMBOBOX, self.OnReturnTypeChanged, id=ID_VARIABLEEDITORPANELRETURNTYPE) b@418: b@418: self.staticText2 = wx.StaticText(id=ID_VARIABLEEDITORPANELSTATICTEXT2, b@418: label=_('Class Filter:'), name='staticText2', parent=self.ControlPanel, b@418: pos=wx.Point(0, 0), size=wx.Size(145, 17), style=0) b@418: b@418: self.ClassFilter = wx.ComboBox(id=ID_VARIABLEEDITORPANELCLASSFILTER, b@418: name='ClassFilter', parent=self.ControlPanel, pos=wx.Point(0, 0), b@418: size=wx.Size(145, 28), style=wx.CB_READONLY) b@418: self.Bind(wx.EVT_COMBOBOX, self.OnClassFilter, id=ID_VARIABLEEDITORPANELCLASSFILTER) b@418: b@418: self.AddButton = wx.Button(id=ID_VARIABLEEDITORPANELADDBUTTON, label=_('Add'), b@418: name='AddButton', parent=self.ControlPanel, pos=wx.Point(0, 0), b@418: size=wx.DefaultSize, style=0) b@418: self.Bind(wx.EVT_BUTTON, self.OnAddButton, id=ID_VARIABLEEDITORPANELADDBUTTON) b@418: b@418: self.DeleteButton = wx.Button(id=ID_VARIABLEEDITORPANELDELETEBUTTON, label=_('Delete'), b@418: name='DeleteButton', parent=self.ControlPanel, pos=wx.Point(0, 0), b@418: size=wx.DefaultSize, style=0) b@418: self.Bind(wx.EVT_BUTTON, self.OnDeleteButton, id=ID_VARIABLEEDITORPANELDELETEBUTTON) b@418: b@418: self.UpButton = wx.Button(id=ID_VARIABLEEDITORPANELUPBUTTON, label='^', b@418: name='UpButton', parent=self.ControlPanel, pos=wx.Point(0, 0), b@418: size=wx.Size(32, 32), style=0) b@418: self.Bind(wx.EVT_BUTTON, self.OnUpButton, id=ID_VARIABLEEDITORPANELUPBUTTON) b@418: b@418: self.DownButton = wx.Button(id=ID_VARIABLEEDITORPANELDOWNBUTTON, label='v', b@418: name='DownButton', parent=self.ControlPanel, pos=wx.Point(0, 0), b@418: size=wx.Size(32, 32), style=0) b@418: self.Bind(wx.EVT_BUTTON, self.OnDownButton, id=ID_VARIABLEEDITORPANELDOWNBUTTON) b@418: b@418: self._init_sizers() b@418: b@418: def __init__(self, parent, window, controler, element_type): b@418: self._init_ctrls(parent) b@418: self.ParentWindow = window b@418: self.Controler = controler b@418: self.ElementType = element_type b@418: b@418: self.Filter = "All" b@418: self.FilterChoices = [] b@418: self.FilterChoiceTransfer = GetFilterChoiceTransfer() b@418: b@424: self.DefaultValue = { "Name" : "", "Class" : "", "Type" : "INT", "Location" : "", laurent@483: "Initial Value" : "", "Option" : "", b@424: "Documentation" : "", "Edit" : True b@424: } b@424: b@418: if element_type in ["config", "resource"]: b@418: self.DefaultTypes = {"All" : "Global"} b@418: else: b@418: self.DefaultTypes = {"All" : "Local", "Interface" : "Input", "Variables" : "Local"} b@424: b@424: if element_type in ["config", "resource"] \ b@424: or element_type in ["program", "transition", "action"]: b@424: # this is an element that can have located variables b@418: self.Table = VariableTable(self, [], GetVariableTableColnames(True)) b@424: b@424: if element_type in ["config", "resource"]: b@424: self.FilterChoices = ["All", "Global"]#,"Access"] b@418: else: b@424: self.FilterChoices = ["All", b@424: "Interface", " Input", " Output", " InOut", " External", b@424: "Variables", " Local", " Temp"]#,"Access"] b@424: b@424: # these condense the ColAlignements list b@424: l = wx.ALIGN_LEFT b@424: c = wx.ALIGN_CENTER b@424: laurent@483: # Num Name Class Type Loc Init Option Doc laurent@483: self.ColSizes = [40, 80, 70, 80, 80, 80, 100, 80] laurent@483: self.ColAlignements = [c, l, l, l, l, l, l, l] b@424: b@424: else: b@424: # this is an element that cannot have located variables b@418: self.Table = VariableTable(self, [], GetVariableTableColnames(False)) b@424: b@418: if element_type == "function": b@424: self.FilterChoices = ["All", b@424: "Interface", " Input", " Output", " InOut", laurent@484: "Variables", " Local"] b@418: else: b@424: self.FilterChoices = ["All", b@424: "Interface", " Input", " Output", " InOut", " External", b@424: "Variables", " Local", " Temp"] b@424: b@424: # these condense the ColAlignements list b@424: l = wx.ALIGN_LEFT b@424: c = wx.ALIGN_CENTER b@424: laurent@483: # Num Name Class Type Init Option Doc laurent@483: self.ColSizes = [40, 80, 70, 80, 80, 100, 160] laurent@483: self.ColAlignements = [c, l, l, l, l, l, l] b@424: b@418: for choice in self.FilterChoices: b@418: self.ClassFilter.Append(_(choice)) b@424: b@418: reverse_transfer = {} b@418: for filter, choice in self.FilterChoiceTransfer.items(): b@418: reverse_transfer[choice] = filter b@418: self.ClassFilter.SetStringSelection(_(reverse_transfer[self.Filter])) b@418: self.RefreshTypeList() b@418: b@418: if element_type == "function": b@418: for base_type in self.Controler.GetBaseTypes(): b@418: self.ReturnType.Append(base_type) b@418: self.ReturnType.Enable(True) b@418: else: b@418: self.ReturnType.Enable(False) b@418: self.staticText1.Hide() b@418: self.ReturnType.Hide() b@418: b@418: self.VariablesGrid.SetTable(self.Table) b@418: self.VariablesGrid.SetRowLabelSize(0) b@418: for col in range(self.Table.GetNumberCols()): b@418: attr = wx.grid.GridCellAttr() b@418: attr.SetAlignment(self.ColAlignements[col], wx.ALIGN_CENTRE) b@418: self.VariablesGrid.SetColAttr(col, attr) b@418: self.VariablesGrid.SetColMinimalWidth(col, self.ColSizes[col]) b@418: self.VariablesGrid.AutoSizeColumn(col, False) b@418: b@418: def SetTagName(self, tagname): b@418: self.TagName = tagname b@418: b@418: def IsFunctionBlockType(self, name): laurent@431: bodytype = self.Controler.GetEditedElementBodyType(self.TagName) laurent@431: pouname, poutype = self.Controler.GetEditedElementType(self.TagName) b@418: if poutype != "function" and bodytype in ["ST", "IL"]: b@418: return False b@418: else: laurent@431: return name in self.Controler.GetFunctionBlockTypes(self.TagName) b@418: b@418: def RefreshView(self): laurent@431: self.PouNames = self.Controler.GetProjectPouNames() b@418: b@418: words = self.TagName.split("::") b@418: if self.ElementType == "config": b@418: self.PouIsUsed = False b@418: returnType = None laurent@431: self.Values = self.Controler.GetConfigurationGlobalVars(words[1]) b@418: elif self.ElementType == "resource": b@418: self.PouIsUsed = False b@418: returnType = None laurent@431: self.Values = self.Controler.GetConfigurationResourceGlobalVars(words[1], words[2]) laurent@431: else: laurent@431: self.PouIsUsed = self.Controler.PouIsUsed(words[1]) laurent@431: returnType = self.Controler.GetEditedElementInterfaceReturnType(self.TagName) laurent@431: self.Values = self.Controler.GetEditedElementInterfaceVars(self.TagName) b@418: b@418: if returnType and self.ReturnType.IsEnabled(): b@418: self.ReturnType.SetStringSelection(returnType) b@418: b@418: self.RefreshValues() b@418: self.RefreshButtons() b@418: b@418: def OnReturnTypeChanged(self, event): b@418: words = self.TagName.split("::") b@418: self.Controler.SetPouInterfaceReturnType(words[1], self.ReturnType.GetStringSelection()) b@418: self.Controler.BufferProject() b@418: self.ParentWindow.RefreshEditor(variablepanel = False) laurent@494: self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, INSTANCESTREE, LIBRARYTREE) b@418: event.Skip() b@418: b@418: def OnClassFilter(self, event): b@418: self.Filter = self.FilterChoiceTransfer[self.ClassFilter.GetStringSelection()] b@418: self.RefreshTypeList() b@418: self.RefreshValues() b@418: self.RefreshButtons() b@418: event.Skip() b@418: b@418: def RefreshTypeList(self): b@418: if self.Filter == "All": b@418: self.ClassList = [self.FilterChoiceTransfer[choice] for choice in self.FilterChoices if self.FilterChoiceTransfer[choice] not in ["All","Interface","Variables"]] b@418: elif self.Filter == "Interface": b@418: self.ClassList = ["Input","Output","InOut","External"] b@418: elif self.Filter == "Variables": b@418: self.ClassList = ["Local","Temp"] b@418: else: b@418: self.ClassList = [self.Filter] b@418: b@418: def RefreshButtons(self): b@418: if getattr(self, "Table", None): b@418: table_length = len(self.Table.data) b@418: row_class = None b@418: row_edit = True b@418: if table_length > 0: b@418: row = self.VariablesGrid.GetGridCursorRow() b@418: row_edit = self.Table.GetValueByName(row, "Edit") b@418: if self.PouIsUsed: b@418: row_class = self.Table.GetValueByName(row, "Class") b@418: self.AddButton.Enable(not self.PouIsUsed or self.Filter not in ["Interface", "Input", "Output", "InOut"]) b@418: self.DeleteButton.Enable(table_length > 0 and row_edit and row_class not in ["Input", "Output", "InOut"]) b@418: self.UpButton.Enable(table_length > 0 and self.Filter == "All" and row_class not in ["Input", "Output", "InOut"]) b@418: self.DownButton.Enable(table_length > 0 and self.Filter == "All" and row_class not in ["Input", "Output", "InOut"]) b@418: b@418: def OnAddButton(self, event): b@418: new_row = self.DefaultValue.copy() b@418: if self.Filter in self.DefaultTypes: b@418: new_row["Class"] = self.DefaultTypes[self.Filter] b@418: else: b@418: new_row["Class"] = self.Filter b@418: if self.Filter == "All" and len(self.Values) > 0: b@418: row_index = self.VariablesGrid.GetGridCursorRow() + 1 b@418: self.Values.insert(row_index, new_row) b@418: else: b@418: row_index = -1 b@418: self.Values.append(new_row) b@418: self.SaveValues() b@418: self.RefreshValues(row_index) b@418: self.RefreshButtons() b@418: event.Skip() b@418: b@418: def OnDeleteButton(self, event): b@418: row = self.Table.GetRow(self.VariablesGrid.GetGridCursorRow()) b@418: self.Values.remove(row) b@418: self.SaveValues() b@418: self.RefreshValues() b@418: self.RefreshButtons() b@418: event.Skip() b@418: b@418: def OnUpButton(self, event): b@418: self.MoveValue(self.VariablesGrid.GetGridCursorRow(), -1) b@418: self.RefreshButtons() b@418: event.Skip() b@418: b@418: def OnDownButton(self, event): b@418: self.MoveValue(self.VariablesGrid.GetGridCursorRow(), 1) b@418: self.RefreshButtons() b@418: event.Skip() b@418: b@418: def OnVariablesGridCellChange(self, event): b@418: row, col = event.GetRow(), event.GetCol() laurent@431: colname = self.Table.GetColLabelValue(col, False) b@418: value = self.Table.GetValue(row, col) b@422: b@418: if colname == "Name" and value != "": b@418: if not TestIdentifier(value): b@418: message = wx.MessageDialog(self, _("\"%s\" is not a valid identifier!")%value, _("Error"), wx.OK|wx.ICON_ERROR) b@418: message.ShowModal() b@418: message.Destroy() b@418: event.Veto() b@418: elif value.upper() in IEC_KEYWORDS: b@418: message = wx.MessageDialog(self, _("\"%s\" is a keyword. It can't be used!")%value, _("Error"), wx.OK|wx.ICON_ERROR) b@418: message.ShowModal() b@418: message.Destroy() b@418: event.Veto() b@418: elif value.upper() in self.PouNames: laurent@446: message = wx.MessageDialog(self, _("A POU named \"%s\" already exists!")%value, _("Error"), wx.OK|wx.ICON_ERROR) b@418: message.ShowModal() b@418: message.Destroy() b@418: event.Veto() b@418: elif value.upper() in [var["Name"].upper() for var in self.Values if var != self.Table.data[row]]: b@418: message = wx.MessageDialog(self, _("A variable with \"%s\" as name already exists in this pou!")%value, _("Error"), wx.OK|wx.ICON_ERROR) b@418: message.ShowModal() b@418: message.Destroy() b@418: event.Veto() b@418: else: b@418: self.SaveValues(False) b@418: old_value = self.Table.GetOldValue() b@418: if old_value != "": b@418: self.Controler.UpdateEditedElementUsedVariable(self.TagName, old_value, value) b@418: self.Controler.BufferProject() laurent@431: self.ParentWindow.RefreshEditor(variablepanel = False) laurent@483: self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, INSTANCESTREE, LIBRARYTREE) b@418: event.Skip() b@418: else: b@418: self.SaveValues() b@418: if colname == "Class": b@418: self.Table.ResetView(self.VariablesGrid) laurent@483: self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU) b@418: event.Skip() b@418: b@418: def OnVariablesGridEditorShown(self, event): b@418: row, col = event.GetRow(), event.GetCol() b@422: b@422: label_value = self.Table.GetColLabelValue(col) b@422: if label_value == "Type": b@422: type_menu = wx.Menu(title='') # the root menu b@422: b@422: # build a submenu containing standard IEC types b@418: base_menu = wx.Menu(title='') b@418: for base_type in self.Controler.GetBaseTypes(): b@418: new_id = wx.NewId() b@418: AppendMenu(base_menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=base_type) b@418: self.Bind(wx.EVT_MENU, self.GetVariableTypeFunction(base_type), id=new_id) b@422: b@418: type_menu.AppendMenu(wx.NewId(), _("Base Types"), base_menu) b@422: b@422: # build a submenu containing user-defined types b@418: datatype_menu = wx.Menu(title='') laurent@484: laurent@484: # TODO : remove complextypes argument when matiec can manage complex types in pou interface laurent@491: datatypes = self.Controler.GetDataTypes(basetypes = False) b@422: for datatype in datatypes: b@418: new_id = wx.NewId() b@418: AppendMenu(datatype_menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=datatype) b@418: self.Bind(wx.EVT_MENU, self.GetVariableTypeFunction(datatype), id=new_id) b@422: b@418: type_menu.AppendMenu(wx.NewId(), _("User Data Types"), datatype_menu) b@422: b@422: # build a submenu containing function block types laurent@431: bodytype = self.Controler.GetEditedElementBodyType(self.TagName) laurent@431: pouname, poutype = self.Controler.GetEditedElementType(self.TagName) b@422: classtype = self.Table.GetValueByName(row, "Class") b@422: b@422: if classtype in ["Input", "Output", "InOut", "External", "Global"] or \ b@422: poutype != "function" and bodytype in ["ST", "IL"]: b@422: functionblock_menu = wx.Menu(title='') laurent@431: fbtypes = self.Controler.GetFunctionBlockTypes(self.TagName) b@422: for functionblock_type in fbtypes: b@418: new_id = wx.NewId() b@418: AppendMenu(functionblock_menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=functionblock_type) b@418: self.Bind(wx.EVT_MENU, self.GetVariableTypeFunction(functionblock_type), id=new_id) b@422: b@418: type_menu.AppendMenu(wx.NewId(), _("Function Block Types"), functionblock_menu) b@422: b@418: rect = self.VariablesGrid.BlockToDeviceRect((row, col), (row, col)) b@422: corner_x = rect.x + rect.width b@422: corner_y = rect.y + self.VariablesGrid.GetColLabelSize() b@422: b@422: # pop up this new menu b@422: self.VariablesGrid.PopupMenuXY(type_menu, corner_x, corner_y) b@418: event.Veto() b@418: else: b@418: event.Skip() b@418: b@418: def GetVariableTypeFunction(self, base_type): b@418: def VariableTypeFunction(event): b@418: row = self.VariablesGrid.GetGridCursorRow() b@418: self.Table.SetValueByName(row, "Type", base_type) b@418: self.Table.ResetView(self.VariablesGrid) b@418: self.SaveValues(False) b@418: self.ParentWindow.RefreshEditor(variablepanel = False) b@418: self.Controler.BufferProject() laurent@494: self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, INSTANCESTREE, LIBRARYTREE) b@418: return VariableTypeFunction b@418: b@418: def OnVariablesGridCellLeftClick(self, event): b@418: row = event.GetRow() b@418: if event.GetCol() == 0 and self.Table.GetValueByName(row, "Edit"): b@418: row = event.GetRow() b@418: var_name = self.Table.GetValueByName(row, "Name") b@418: var_class = self.Table.GetValueByName(row, "Class") b@418: var_type = self.Table.GetValueByName(row, "Type") b@418: data = wx.TextDataObject(str((var_name, var_class, var_type, self.TagName))) b@418: dragSource = wx.DropSource(self.VariablesGrid) b@418: dragSource.SetData(data) b@418: dragSource.DoDragDrop() b@418: event.Skip() b@418: b@418: def OnVariablesGridSelectCell(self, event): b@418: wx.CallAfter(self.RefreshButtons) b@418: event.Skip() b@418: b@418: def OnChar(self, event): b@418: keycode = event.GetKeyCode() b@418: if keycode == wx.WXK_DELETE: b@418: row = self.Table.GetRow(self.VariablesGrid.GetGridCursorRow()) b@418: self.Values.remove(row) b@418: self.SaveValues() b@418: self.RefreshValues() b@418: self.RefreshButtons() b@418: event.Skip() b@418: b@418: def MoveValue(self, value_index, move): b@418: new_index = max(0, min(value_index + move, len(self.Values) - 1)) b@418: if new_index != value_index: b@418: self.Values.insert(new_index, self.Values.pop(value_index)) b@418: self.SaveValues() b@418: self.RefreshValues() b@418: self.VariablesGrid.SetGridCursor(new_index, self.VariablesGrid.GetGridCursorCol()) b@418: b@418: def RefreshValues(self, select=0): b@418: if len(self.Table.data) > 0: b@418: self.VariablesGrid.SetGridCursor(0, 1) b@418: data = [] b@418: for num, variable in enumerate(self.Values): b@418: if variable["Class"] in self.ClassList: b@418: variable["Number"] = num + 1 b@418: data.append(variable) b@418: self.Table.SetData(data) b@418: if len(self.Table.data) > 0: b@418: if select == -1: b@418: select = len(self.Table.data) - 1 b@418: self.VariablesGrid.SetGridCursor(select, 1) b@418: self.VariablesGrid.MakeCellVisible(select, 1) b@418: self.Table.ResetView(self.VariablesGrid) b@418: b@418: def SaveValues(self, buffer = True): b@418: words = self.TagName.split("::") b@418: if self.ElementType == "config": b@418: self.Controler.SetConfigurationGlobalVars(words[1], self.Values) b@418: elif self.ElementType == "resource": b@418: self.Controler.SetConfigurationResourceGlobalVars(words[1], words[2], self.Values) b@418: else: b@418: if self.ReturnType.IsEnabled(): b@418: self.Controler.SetPouInterfaceReturnType(words[1], self.ReturnType.GetStringSelection()) b@418: self.Controler.SetPouInterfaceVars(words[1], self.Values) b@418: if buffer: b@418: self.Controler.BufferProject() laurent@494: self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, INSTANCESTREE, LIBRARYTREE) b@418: b@418: def AddVariableError(self, infos): b@418: if isinstance(infos[0], TupleType): b@418: for i in xrange(*infos[0]): b@418: self.Table.AddError((i,) + infos[1:]) b@418: else: b@418: self.Table.AddError(infos) b@418: self.Table.ResetView(self.VariablesGrid) b@418: b@418: def ClearErrors(self): b@418: self.Table.ClearErrors() b@418: self.Table.ResetView(self.VariablesGrid) b@422: b@422: class LocationCellControl(wx.PyControl): laurent@436: laurent@436: def _init_coll_MainSizer_Items(self, parent): laurent@436: parent.AddWindow(self.Location, 0, border=0, flag=wx.GROW) laurent@436: parent.AddWindow(self.BrowseButton, 0, border=0, flag=wx.GROW) laurent@436: laurent@436: def _init_coll_MainSizer_Growables(self, parent): laurent@436: parent.AddGrowableCol(0) laurent@436: parent.AddGrowableRow(0) laurent@436: laurent@436: def _init_sizers(self): laurent@436: self.MainSizer = wx.FlexGridSizer(cols=2, hgap=0, rows=1, vgap=0) laurent@436: laurent@436: self._init_coll_MainSizer_Items(self.MainSizer) laurent@436: self._init_coll_MainSizer_Growables(self.MainSizer) laurent@436: laurent@436: self.SetSizer(self.MainSizer) laurent@436: laurent@436: def _init_ctrls(self, prnt): laurent@436: wx.Control.__init__(self, id=-1, laurent@436: name='LocationCellControl', parent=prnt, laurent@436: size=wx.DefaultSize, style=0) laurent@436: laurent@436: # create location text control laurent@436: self.Location = wx.TextCtrl(id=-1, name='Location', parent=self, laurent@443: pos=wx.Point(0, 0), size=wx.Size(0, 0), style=wx.TE_PROCESS_ENTER) laurent@443: self.Location.Bind(wx.EVT_KEY_DOWN, self.OnLocationChar) laurent@436: laurent@436: # create browse button laurent@436: self.BrowseButton = wx.Button(id=-1, label='...', laurent@436: name='staticText1', parent=self, pos=wx.Point(0, 0), laurent@436: size=wx.Size(30, 0), style=0) laurent@436: self.BrowseButton.Bind(wx.EVT_BUTTON, self.OnBrowseButtonClick) laurent@436: laurent@436: self.Bind(wx.EVT_SIZE, self.OnSize) laurent@436: laurent@436: self._init_sizers() laurent@436: b@422: ''' b@422: Custom cell editor control with a text box and a button that launches b@422: the BrowseVariableLocationsDialog. b@422: ''' laurent@436: def __init__(self, parent, locations): laurent@436: self._init_ctrls(parent) laurent@436: self.Locations = locations laurent@436: self.VarType = None laurent@436: laurent@436: def SetVarType(self, vartype): laurent@436: self.VarType = vartype laurent@436: laurent@436: def SetValue(self, value): laurent@436: self.Location.SetValue(value) laurent@436: laurent@436: def GetValue(self): laurent@436: return self.Location.GetValue() b@422: b@422: def OnSize(self, event): laurent@431: self.Layout() b@422: laurent@436: def OnBrowseButtonClick(self, event): b@422: # pop up the location browser dialog laurent@436: dialog = BrowseLocationsDialog(self, self.VarType, self.Locations) laurent@436: if dialog.ShowModal() == wx.ID_OK: laurent@436: infos = dialog.GetValues() b@422: b@422: # set the location laurent@436: self.Location.SetValue(infos["location"]) laurent@436: laurent@436: dialog.Destroy() laurent@436: laurent@436: self.Location.SetFocus() b@422: laurent@443: def OnLocationChar(self, event): laurent@443: keycode = event.GetKeyCode() laurent@443: if keycode == wx.WXK_RETURN or keycode == wx.WXK_TAB: laurent@443: self.Parent.Parent.ProcessEvent(event) laurent@443: self.Parent.Parent.SetFocus() laurent@443: else: laurent@443: event.Skip() laurent@443: b@422: def SetInsertionPoint(self, i): laurent@436: self.Location.SetInsertionPoint(i) laurent@436: b@422: def SetFocus(self): laurent@436: self.Location.SetFocus() b@422: b@422: class LocationCellEditor(wx.grid.PyGridCellEditor): b@422: ''' b@422: Grid cell editor that uses LocationCellControl to display a browse button. b@422: ''' laurent@436: def __init__(self, table, controler): b@422: wx.grid.PyGridCellEditor.__init__(self) laurent@436: self.Table = table laurent@436: self.Controler = controler laurent@443: laurent@443: def __del__(self): laurent@443: self.CellControl = None laurent@443: b@422: def Create(self, parent, id, evt_handler): laurent@436: locations = self.Controler.GetVariableLocationTree() laurent@436: if len(locations) > 0: laurent@436: self.CellControl = LocationCellControl(parent, locations) laurent@436: else: laurent@436: self.CellControl = wx.TextCtrl(parent, -1) laurent@436: self.SetControl(self.CellControl) b@422: if evt_handler: laurent@436: self.CellControl.PushEventHandler(evt_handler) b@422: b@422: def BeginEdit(self, row, col, grid): laurent@436: self.CellControl.SetValue(self.Table.GetValueByName(row, 'Location')) laurent@436: if isinstance(self.CellControl, LocationCellControl): laurent@436: self.CellControl.SetVarType(self.Controler.GetBaseType(self.Table.GetValueByName(row, 'Type'))) laurent@436: self.CellControl.SetFocus() b@422: b@422: def EndEdit(self, row, col, grid): laurent@436: loc = self.CellControl.GetValue() laurent@436: old_loc = self.Table.GetValueByName(row, 'Location') b@422: if loc != old_loc: laurent@436: self.Table.SetValueByName(row, 'Location', loc) b@422: return True laurent@436: return False b@422: b@422: def SetSize(self, rect): laurent@436: self.CellControl.SetDimensions(rect.x + 1, rect.y, laurent@431: rect.width, rect.height, b@422: wx.SIZE_ALLOW_MINUS_ONE) b@422: b@422: def Clone(self): laurent@436: return LocationCellEditor(self.Table, self.Locations) laurent@436: laurent@436: def GetDirChoiceOptions(): laurent@436: _ = lambda x : x laurent@436: return [(_("All"), [LOCATION_VAR_INPUT, LOCATION_VAR_OUTPUT, LOCATION_VAR_MEMORY]), laurent@436: (_("Input"), [LOCATION_VAR_INPUT]), laurent@436: (_("Output"), [LOCATION_VAR_OUTPUT]), laurent@436: (_("Memory"), [LOCATION_VAR_MEMORY])] laurent@436: DIRCHOICE_OPTIONS_FILTER = dict([(_(option), filter) for option, filter in GetDirChoiceOptions()]) laurent@436: laurent@436: # turn LOCATIONDATATYPES inside-out laurent@436: LOCATION_SIZES = {} laurent@436: for size, types in LOCATIONDATATYPES.iteritems(): laurent@436: for type in types: laurent@436: LOCATION_SIZES[type] = size laurent@436: laurent@436: [ID_BROWSELOCATIONSDIALOG, ID_BROWSELOCATIONSDIALOGLOCATIONSTREE, laurent@436: ID_BROWSELOCATIONSDIALOGDIRCHOICE, ID_BROWSELOCATIONSDIALOGSTATICTEXT1, laurent@436: ID_BROWSELOCATIONSDIALOGSTATICTEXT2, laurent@436: ] = [wx.NewId() for _init_ctrls in range(5)] laurent@436: laurent@436: class BrowseLocationsDialog(wx.Dialog): laurent@436: laurent@436: if wx.VERSION < (2, 6, 0): laurent@436: def Bind(self, event, function, id = None): laurent@436: if id is not None: laurent@436: event(self, id, function) laurent@436: else: laurent@436: event(self, function) laurent@436: laurent@436: def _init_coll_MainSizer_Items(self, parent): laurent@436: parent.AddWindow(self.staticText1, 0, border=20, flag=wx.TOP|wx.LEFT|wx.RIGHT|wx.GROW) laurent@436: parent.AddWindow(self.LocationsTree, 0, border=20, flag=wx.LEFT|wx.RIGHT|wx.GROW) laurent@436: parent.AddSizer(self.ButtonGridSizer, 0, border=20, flag=wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.GROW) laurent@436: laurent@436: def _init_coll_MainSizer_Growables(self, parent): laurent@436: parent.AddGrowableCol(0) laurent@436: parent.AddGrowableRow(1) laurent@436: laurent@436: def _init_coll_ButtonGridSizer_Items(self, parent): laurent@436: parent.AddWindow(self.staticText2, 0, border=0, flag=wx.ALIGN_CENTER_VERTICAL) laurent@436: parent.AddWindow(self.DirChoice, 0, border=0, flag=wx.ALIGN_CENTER_VERTICAL) laurent@436: parent.AddSizer(self.ButtonSizer, 0, border=0, flag=wx.ALIGN_RIGHT) laurent@436: laurent@436: def _init_coll_ButtonGridSizer_Growables(self, parent): laurent@436: parent.AddGrowableCol(2) laurent@436: parent.AddGrowableRow(0) laurent@436: laurent@436: def _init_sizers(self): laurent@436: self.MainSizer = wx.FlexGridSizer(cols=1, hgap=0, rows=3, vgap=10) laurent@436: self.ButtonGridSizer = wx.FlexGridSizer(cols=3, hgap=5, rows=1, vgap=0) laurent@436: laurent@436: self._init_coll_MainSizer_Items(self.MainSizer) laurent@436: self._init_coll_MainSizer_Growables(self.MainSizer) laurent@436: self._init_coll_ButtonGridSizer_Items(self.ButtonGridSizer) laurent@436: self._init_coll_ButtonGridSizer_Growables(self.ButtonGridSizer) laurent@436: laurent@436: self.SetSizer(self.MainSizer) laurent@436: laurent@436: def _init_ctrls(self, prnt): laurent@436: wx.Dialog.__init__(self, id=ID_BROWSELOCATIONSDIALOG, laurent@436: name='BrowseLocationsDialog', parent=prnt, laurent@436: size=wx.Size(600, 400), style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER, laurent@436: title=_('Browse Locations')) laurent@436: laurent@436: self.staticText1 = wx.StaticText(id=ID_BROWSELOCATIONSDIALOGSTATICTEXT1, laurent@436: label=_('Locations available:'), name='staticText1', parent=self, laurent@436: pos=wx.Point(0, 0), size=wx.DefaultSize, style=0) laurent@436: laurent@436: if wx.Platform == '__WXMSW__': laurent@436: treestyle = wx.TR_HAS_BUTTONS|wx.TR_SINGLE|wx.SUNKEN_BORDER laurent@436: else: laurent@436: treestyle = wx.TR_HAS_BUTTONS|wx.TR_HIDE_ROOT|wx.TR_SINGLE|wx.SUNKEN_BORDER laurent@436: self.LocationsTree = wx.TreeCtrl(id=ID_BROWSELOCATIONSDIALOGLOCATIONSTREE, laurent@436: name='LocationsTree', parent=self, pos=wx.Point(0, 0), laurent@436: size=wx.Size(0, 0), style=treestyle) laurent@436: self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnLocationsTreeItemActivated, laurent@436: id=ID_BROWSELOCATIONSDIALOGLOCATIONSTREE) laurent@436: laurent@436: self.staticText2 = wx.StaticText(id=ID_BROWSELOCATIONSDIALOGSTATICTEXT2, laurent@436: label=_('Direction:'), name='staticText2', parent=self, laurent@436: pos=wx.Point(0, 0), size=wx.DefaultSize, style=0) laurent@436: laurent@436: self.DirChoice = wx.ComboBox(id=ID_BROWSELOCATIONSDIALOGDIRCHOICE, laurent@436: name='DirChoice', parent=self, pos=wx.Point(0, 0), laurent@436: size=wx.DefaultSize, style=wx.CB_READONLY) laurent@436: self.Bind(wx.EVT_COMBOBOX, self.OnDirChoice, id=ID_BROWSELOCATIONSDIALOGDIRCHOICE) laurent@436: laurent@436: self.ButtonSizer = self.CreateButtonSizer(wx.OK|wx.CANCEL|wx.CENTRE) laurent@436: if wx.VERSION >= (2, 5, 0): laurent@436: self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.ButtonSizer.GetAffirmativeButton().GetId()) laurent@436: else: laurent@436: self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.ButtonSizer.GetChildren()[0].GetSizer().GetChildren()[0].GetWindow().GetId()) laurent@436: laurent@436: self._init_sizers() laurent@436: laurent@436: def __init__(self, parent, var_type, locations): laurent@436: self._init_ctrls(parent) laurent@436: self.VarType = var_type laurent@436: self.Locations = locations laurent@436: laurent@436: # Define Tree item icon list laurent@436: self.TreeImageList = wx.ImageList(16, 16) laurent@436: self.TreeImageDict = {} laurent@436: laurent@436: # Icons for items laurent@436: for imgname, itemtype in [ laurent@436: ("CONFIGURATION", LOCATION_PLUGIN), laurent@436: ("RESOURCE", LOCATION_MODULE), laurent@436: ("PROGRAM", LOCATION_GROUP), laurent@436: ("VAR_INPUT", LOCATION_VAR_INPUT), laurent@436: ("VAR_OUTPUT", LOCATION_VAR_OUTPUT), laurent@436: ("VAR_LOCAL", LOCATION_VAR_MEMORY)]: laurent@436: self.TreeImageDict[itemtype]=self.TreeImageList.Add(wx.Bitmap(os.path.join(CWD, 'Images', '%s.png'%imgname))) laurent@436: laurent@436: # Assign icon list to TreeCtrls laurent@436: self.LocationsTree.SetImageList(self.TreeImageList) laurent@436: laurent@436: # Set a options for the choice laurent@436: for option, filter in GetDirChoiceOptions(): laurent@436: self.DirChoice.Append(_(option)) laurent@436: self.DirChoice.SetStringSelection(_("All")) laurent@436: self.RefreshFilter() laurent@436: laurent@436: self.RefreshLocationsTree() laurent@436: laurent@436: def RefreshFilter(self): laurent@436: self.Filter = DIRCHOICE_OPTIONS_FILTER[self.DirChoice.GetStringSelection()] laurent@436: laurent@436: def RefreshLocationsTree(self): laurent@436: root = self.LocationsTree.GetRootItem() laurent@436: if not root.IsOk(): laurent@436: if wx.Platform == '__WXMSW__': laurent@436: root = self.LocationsTree.AddRoot(_('Plugins')) laurent@436: else: laurent@436: root = self.LocationsTree.AddRoot("") laurent@436: self.GenerateLocationsTreeBranch(root, self.Locations) laurent@436: self.LocationsTree.Expand(root) laurent@436: laurent@436: def GenerateLocationsTreeBranch(self, root, locations): laurent@436: to_delete = [] laurent@436: if wx.VERSION >= (2, 6, 0): laurent@436: item, root_cookie = self.LocationsTree.GetFirstChild(root) laurent@436: else: laurent@436: item, root_cookie = self.LocationsTree.GetFirstChild(root, 0) laurent@436: for loc_infos in locations: laurent@436: infos = loc_infos.copy() laurent@436: if infos["type"] in [LOCATION_PLUGIN, LOCATION_MODULE, LOCATION_GROUP] or\ laurent@436: infos["type"] in self.Filter and (infos["IEC_type"] == self.VarType or laurent@436: infos["IEC_type"] is None and LOCATION_SIZES[self.VarType] == infos["size"]): laurent@436: children = [child for child in infos.pop("children")] laurent@436: if not item.IsOk(): laurent@436: item = self.LocationsTree.AppendItem(root, infos["name"]) laurent@436: if wx.Platform != '__WXMSW__': laurent@436: item, root_cookie = self.LocationsTree.GetNextChild(root, root_cookie) b@422: else: laurent@436: self.LocationsTree.SetItemText(item, infos["name"]) laurent@436: self.LocationsTree.SetPyData(item, infos) laurent@436: self.LocationsTree.SetItemImage(item, self.TreeImageDict[infos["type"]]) laurent@436: self.GenerateLocationsTreeBranch(item, children) laurent@436: item, root_cookie = self.LocationsTree.GetNextChild(root, root_cookie) laurent@436: while item.IsOk(): laurent@436: to_delete.append(item) laurent@436: item, root_cookie = self.LocationsTree.GetNextChild(root, root_cookie) laurent@436: for item in to_delete: laurent@436: self.LocationsTree.Delete(item) laurent@436: laurent@436: def OnLocationsTreeItemActivated(self, event): laurent@436: infos = self.LocationsTree.GetPyData(event.GetItem()) laurent@436: if infos["type"] not in [LOCATION_PLUGIN, LOCATION_MODULE, LOCATION_GROUP]: laurent@436: wx.CallAfter(self.EndModal, wx.ID_OK) laurent@436: event.Skip() laurent@436: laurent@436: def OnDirChoice(self, event): laurent@436: self.RefreshFilter() laurent@436: self.RefreshLocationsTree() laurent@436: laurent@436: def GetValues(self): laurent@436: selected = self.LocationsTree.GetSelection() laurent@436: return self.LocationsTree.GetPyData(selected) laurent@436: laurent@436: def OnOK(self, event): laurent@436: selected = self.LocationsTree.GetSelection() laurent@436: var_infos = None laurent@436: if selected.IsOk(): laurent@436: var_infos = self.LocationsTree.GetPyData(selected) laurent@436: if var_infos is None or var_infos["type"] in [LOCATION_PLUGIN, LOCATION_MODULE, LOCATION_GROUP]: laurent@436: message = wx.MessageDialog(self, _("A location must be selected!"), _("Error"), wx.OK|wx.ICON_ERROR) laurent@436: message.ShowModal() laurent@436: message.Destroy() laurent@436: else: laurent@436: self.EndModal(wx.ID_OK) laurent@436: