# HG changeset patch
# User b.taylor@willowglen.ca
# Date 1250780611 21600
# Node ID 127d524a5f1df36b3b9278f3cac85bcb1a7e764f
# Parent d432eae889edc684099f3dfa52cc9334da42221f# Parent e0a6a5952d13665b681028eaf640e8bdbe708d05
merged with lolitech, my change is obsolete.
diff -r e0a6a5952d13 -r 127d524a5f1d .cvsignore
--- a/.cvsignore Mon Jul 06 11:24:37 2009 -0600
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,6 +0,0 @@
-*.pyc
-*.st
-.settings
-.pydevproject
-.project
-.externalToolBuilders
diff -r e0a6a5952d13 -r 127d524a5f1d .hgignore
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/.hgignore Thu Aug 20 09:03:31 2009 -0600
@@ -0,0 +1,1 @@
+.project
diff -r e0a6a5952d13 -r 127d524a5f1d .project
--- a/.project Mon Jul 06 11:24:37 2009 -0600
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,17 +0,0 @@
-
-
- plcopeneditor
-
-
-
-
-
- org.python.pydev.PyDevBuilder
-
-
-
-
-
- org.python.pydev.pythonNature
-
-
diff -r e0a6a5952d13 -r 127d524a5f1d DataTypeEditor.py
--- a/DataTypeEditor.py Mon Jul 06 11:24:37 2009 -0600
+++ b/DataTypeEditor.py Thu Aug 20 09:03:31 2009 -0600
@@ -41,6 +41,10 @@
# Structure Elements Table
#-------------------------------------------------------------------------------
+def GetElementsTableColnames():
+ _ = lambda x : x
+ return ["#", _("Name"), _("Type"), _("Initial Value")]
+
class ElementsTable(wx.grid.PyGridTableBase):
"""
@@ -66,23 +70,25 @@
def GetNumberRows(self):
return len(self.data)
- def GetColLabelValue(self, col):
+ 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):
+ def GetRowLabelValues(self, row, translate=True):
return row
def GetValue(self, row, col):
if row < self.GetNumberRows():
if col == 0:
return row + 1
- name = str(self.data[row].get(self.GetColLabelValue(col), ""))
+ name = str(self.data[row].get(self.GetColLabelValue(col, False), ""))
return name
def SetValue(self, row, col, value):
if col < len(self.colnames):
- colname = self.GetColLabelValue(col)
+ colname = self.GetColLabelValue(col, False)
if colname == "Name":
self.old_value = self.data[row][colname]
self.data[row][colname] = value
@@ -140,13 +146,11 @@
Otherwise default to the default renderer.
"""
- typelist = None
- accesslist = None
for row in range(self.GetNumberRows()):
for col in range(self.GetNumberCols()):
editor = None
renderer = None
- colname = self.GetColLabelValue(col)
+ colname = self.GetColLabelValue(col, False)
if col != 0:
grid.SetReadOnly(row, col, False)
if colname == "Name":
@@ -163,7 +167,7 @@
grid.SetCellEditor(row, col, editor)
grid.SetCellRenderer(row, col, renderer)
- if row in self.Errors and self.Errors[row][0] == colname.lower():
+ if self.Errors.has_key(row) 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)
@@ -204,7 +208,7 @@
self.Errors = {}
#-------------------------------------------------------------------------------
-# Configuration Editor class
+# Datatype Editor class
#-------------------------------------------------------------------------------
[ID_DATATYPEEDITOR, ID_DATATYPEEDITORSTATICBOX,
@@ -227,6 +231,11 @@
ID_DATATYPEEDITORSTATICTEXT11,
] = [wx.NewId() for _init_ctrls in range(35)]
+def GetDatatypeTypes():
+ _ = lambda x : x
+ return [_("Directly"), _("Subrange"), _("Enumerated"), _("Array"), _("Structure")]
+DATATYPE_TYPES_DICT = dict([(_(datatype), datatype) for datatype in GetDatatypeTypes()])
+
class DataTypeEditor(wx.Panel):
def _init_coll_MainSizer_Items(self, parent):
@@ -238,8 +247,8 @@
parent.AddGrowableRow(1)
def _init_coll_TopSizer_Items(self, parent):
- parent.AddWindow(self.staticText1, 0, border=5, flag=wx.GROW|wx.LEFT)
- parent.AddWindow(self.DerivationType, 0, border=0, flag=wx.GROW)
+ parent.AddWindow(self.staticText1, 0, border=5, flag=wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT)
+ parent.AddWindow(self.DerivationType, 0, border=5, flag=wx.GROW|wx.RIGHT)
def _init_coll_TypeInfosSizer_Items(self, parent):
parent.AddWindow(self.DirectlyPanel, 1, border=0, flag=wx.ALL)
@@ -249,31 +258,34 @@
parent.AddWindow(self.StructurePanel, 1, border=0, flag=wx.GROW|wx.ALL)
def _init_coll_DirectlyPanelSizer_Items(self, parent):
- parent.AddWindow(self.staticText2, 1, border=5, flag=wx.GROW|wx.ALL)
+ parent.AddWindow(self.staticText2, 1, border=5, flag=wx.ALIGN_CENTER_VERTICAL|wx.ALL)
parent.AddWindow(self.DirectlyBaseType, 1, border=5, flag=wx.GROW|wx.ALL)
- parent.AddWindow(self.staticText3, 1, border=5, flag=wx.GROW|wx.ALL)
+ parent.AddWindow(self.staticText3, 1, border=5, flag=wx.ALIGN_CENTER_VERTICAL|wx.ALL)
parent.AddWindow(self.DirectlyInitialValue, 1, border=5, flag=wx.GROW|wx.ALL)
def _init_coll_SubrangePanelSizer_Items(self, parent):
- parent.AddWindow(self.staticText4, 1, border=5, flag=wx.GROW|wx.ALL)
+ parent.AddWindow(self.staticText4, 1, border=5, flag=wx.ALIGN_CENTER_VERTICAL|wx.ALL)
parent.AddWindow(self.SubrangeBaseType, 1, border=5, flag=wx.GROW|wx.ALL)
- parent.AddWindow(self.staticText5, 1, border=5, flag=wx.GROW|wx.ALL)
+ parent.AddWindow(self.staticText5, 1, border=5, flag=wx.ALIGN_CENTER_VERTICAL|wx.ALL)
parent.AddWindow(self.SubrangeInitialValue, 1, border=5, flag=wx.GROW|wx.ALL)
- parent.AddWindow(self.staticText6, 1, border=5, flag=wx.GROW|wx.ALL)
+ parent.AddWindow(self.staticText6, 1, border=5, flag=wx.ALIGN_CENTER_VERTICAL|wx.ALL)
parent.AddWindow(self.SubrangeMinimum, 1, border=5, flag=wx.GROW|wx.ALL)
parent.AddWindow(wx.Size(0, 0), 1, border=5, flag=wx.GROW|wx.ALL)
parent.AddWindow(wx.Size(0, 0), 1, border=5, flag=wx.GROW|wx.ALL)
- parent.AddWindow(self.staticText7, 1, border=5, flag=wx.GROW|wx.ALL)
+ parent.AddWindow(self.staticText7, 1, border=5, flag=wx.ALIGN_CENTER_VERTICAL|wx.ALL)
parent.AddWindow(self.SubrangeMaximum, 1, border=5, flag=wx.GROW|wx.ALL)
def _init_coll_EnumeratedPanelSizer_Items(self, parent):
- parent.AddWindow(self.EnumeratedValues, 2, border=5, flag=wx.GROW|wx.ALL)
- parent.AddWindow(self.staticText8, 1, border=5, flag=wx.GROW|wx.ALL)
+ parent.AddWindow(self.EnumeratedValues, 1, border=5, flag=wx.GROW|wx.ALL)
+ parent.AddSizer(self.EnumeratedPanelRightSizer, 1, border=0, flag=0)
+
+ def _init_coll_EnumeratedPanelRightSizer_Items(self, parent):
+ parent.AddWindow(self.staticText8, 1, border=5, flag=wx.ALIGN_CENTER_VERTICAL|wx.ALL)
parent.AddWindow(self.EnumeratedInitialValue, 1, border=5, flag=wx.ALL)
def _init_coll_ArrayPanelSizer_Items(self, parent):
parent.AddSizer(self.ArrayPanelLeftSizer, 0, border=0, flag=wx.GROW)
- parent.AddSizer(self.ArrayPanelRightSizer, 0, border=0, flag=wx.GROW)
+ parent.AddSizer(self.ArrayPanelRightSizer, 0, border=0, flag=0)
parent.AddWindow(self.ArrayDimensions, 0, border=5, flag=wx.GROW|wx.ALL)
def _init_coll_ArrayPanelSizer_Growables(self, parent):
@@ -282,15 +294,15 @@
parent.AddGrowableRow(1)
def _init_coll_ArrayPanelLeftSizer_Items(self, parent):
- parent.AddWindow(self.staticText9, 1, border=5, flag=wx.GROW|wx.ALL)
+ parent.AddWindow(self.staticText9, 1, border=5, flag=wx.ALIGN_CENTER_VERTICAL|wx.ALL)
parent.AddWindow(self.ArrayBaseType, 1, border=5, flag=wx.GROW|wx.ALL)
def _init_coll_ArrayPanelRightSizer_Items(self, parent):
- parent.AddWindow(self.staticText10, 1, border=5, flag=wx.GROW|wx.ALL)
+ parent.AddWindow(self.staticText10, 1, border=5, flag=wx.ALIGN_CENTER_VERTICAL|wx.ALL)
parent.AddWindow(self.ArrayInitialValue, 1, border=5, flag=wx.GROW|wx.ALL)
def _init_coll_StructurePanelSizer_Items(self, parent):
- parent.AddWindow(self.staticText11, 0, border=5, flag=wx.GROW|wx.ALL)
+ parent.AddWindow(self.staticText11, 0, border=5, flag=wx.ALL)
parent.AddWindow(self.StructureElementsGrid, 0, border=0, flag=wx.GROW)
parent.AddSizer(self.StructurePanelButtonSizer, 0, border=0, flag=wx.ALIGN_RIGHT)
@@ -299,22 +311,23 @@
parent.AddGrowableRow(1)
def _init_coll_StructurePanelButtonSizer_Items(self, parent):
- parent.AddWindow(self.StructureAddButton, 1, border=5, flag=wx.GROW|wx.ALL)
- parent.AddWindow(self.StructureDeleteButton, 1, border=5, flag=wx.GROW|wx.ALL)
- parent.AddWindow(self.StructureUpButton, 1, border=5, flag=wx.GROW|wx.ALL)
- parent.AddWindow(self.StructureDownButton, 1, border=5, flag=wx.GROW|wx.ALL)
+ parent.AddWindow(self.StructureAddButton, 0, border=5, flag=wx.ALL)
+ parent.AddWindow(self.StructureDeleteButton, 0, border=5, flag=wx.ALL)
+ parent.AddWindow(self.StructureUpButton, 0, border=5, flag=wx.ALL)
+ parent.AddWindow(self.StructureDownButton, 0, border=5, flag=wx.ALL)
def _init_sizers(self):
self.MainSizer = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=10)
self.TopSizer = wx.BoxSizer(wx.HORIZONTAL)
self.TypeInfosSizer = wx.StaticBoxSizer(self.staticbox, wx.HORIZONTAL)
self.DirectlyPanelSizer = wx.BoxSizer(wx.HORIZONTAL)
- self.SubrangePanelSizer = wx.GridSizer(cols=4, hgap=0, rows=3, vgap=0)
+ self.SubrangePanelSizer = wx.GridSizer(cols=4, hgap=5, rows=3, vgap=0)
self.EnumeratedPanelSizer = wx.BoxSizer(wx.HORIZONTAL)
- self.ArrayPanelSizer = wx.FlexGridSizer(cols=2, hgap=0, rows=2, vgap=0)
+ self.EnumeratedPanelRightSizer = wx.BoxSizer(wx.HORIZONTAL)
+ self.ArrayPanelSizer = wx.FlexGridSizer(cols=2, hgap=5, rows=2, vgap=0)
self.ArrayPanelLeftSizer = wx.BoxSizer(wx.HORIZONTAL)
self.ArrayPanelRightSizer = wx.BoxSizer(wx.HORIZONTAL)
- self.StructurePanelSizer = wx.FlexGridSizer(cols=1, hgap=0, rows=3, vgap=0)
+ self.StructurePanelSizer = wx.FlexGridSizer(cols=1, hgap=5, rows=3, vgap=0)
self.StructurePanelButtonSizer = wx.BoxSizer(wx.HORIZONTAL)
self._init_coll_MainSizer_Items(self.MainSizer)
self._init_coll_MainSizer_Growables(self.MainSizer)
@@ -323,6 +336,7 @@
self._init_coll_DirectlyPanelSizer_Items(self.DirectlyPanelSizer)
self._init_coll_SubrangePanelSizer_Items(self.SubrangePanelSizer)
self._init_coll_EnumeratedPanelSizer_Items(self.EnumeratedPanelSizer)
+ self._init_coll_EnumeratedPanelRightSizer_Items(self.EnumeratedPanelRightSizer)
self._init_coll_ArrayPanelSizer_Items(self.ArrayPanelSizer)
self._init_coll_ArrayPanelSizer_Growables(self.ArrayPanelSizer)
self._init_coll_ArrayPanelLeftSizer_Items(self.ArrayPanelLeftSizer)
@@ -343,12 +357,12 @@
size=wx.Size(0, 0), style=wx.SUNKEN_BORDER)
self.staticbox = wx.StaticBox(id=ID_DATATYPEEDITORSTATICBOX,
- label='Type infos:', name='staticBox1', parent=self,
- pos=wx.Point(0, 0), size=wx.Size(10, 0), style=0)
+ label=_('Type infos:'), name='staticBox1', parent=self,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.staticText1 = wx.StaticText(id=ID_DATATYPEEDITORSTATICTEXT1,
- label='Derivation Type:', name='staticText1', parent=self,
- pos=wx.Point(0, 0), size=wx.Size(150, 17), style=0)
+ label=_('Derivation Type:'), name='staticText1', parent=self,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.DerivationType = wx.ComboBox(id=ID_DATATYPEEDITORDERIVATIONTYPE,
name='DerivationType', parent=self, pos=wx.Point(0, 0),
@@ -362,8 +376,8 @@
size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL)
self.staticText2 = wx.StaticText(id=ID_DATATYPEEDITORSTATICTEXT2,
- label='Base Type:', name='staticText2', parent=self.DirectlyPanel,
- pos=wx.Point(0, 0), size=wx.Size(150, 17), style=0)
+ label=_('Base Type:'), name='staticText2', parent=self.DirectlyPanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.DirectlyBaseType = wx.ComboBox(id=ID_DATATYPEEDITORDIRECTLYBASETYPE,
name='DirectlyBaseType', parent=self.DirectlyPanel, pos=wx.Point(0, 0),
@@ -371,8 +385,8 @@
self.Bind(wx.EVT_COMBOBOX, self.OnInfosChanged, id=ID_DATATYPEEDITORDIRECTLYBASETYPE)
self.staticText3 = wx.StaticText(id=ID_DATATYPEEDITORSTATICTEXT3,
- label='Initial Value:', name='staticText3', parent=self.DirectlyPanel,
- pos=wx.Point(0, 0), size=wx.Size(150, 17), style=0)
+ label=_('Initial Value:'), name='staticText3', parent=self.DirectlyPanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.DirectlyInitialValue = wx.TextCtrl(id=ID_DATATYPEEDITORDIRECTLYINITIALVALUE,
name='DirectlyInitialValue', parent=self.DirectlyPanel, pos=wx.Point(0, 0),
@@ -386,8 +400,8 @@
size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL)
self.staticText4 = wx.StaticText(id=ID_DATATYPEEDITORSTATICTEXT4,
- label='Base Type:', name='staticText4', parent=self.SubrangePanel,
- pos=wx.Point(0, 0), size=wx.Size(150, 17), style=0)
+ label=_('Base Type:'), name='staticText4', parent=self.SubrangePanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.SubrangeBaseType = wx.ComboBox(id=ID_DATATYPEEDITORSUBRANGEBASETYPE,
name='SubrangeBaseType', parent=self.SubrangePanel, pos=wx.Point(0, 0),
@@ -395,8 +409,8 @@
self.Bind(wx.EVT_COMBOBOX, self.OnSubrangeBaseTypeChanged, id=ID_DATATYPEEDITORSUBRANGEBASETYPE)
self.staticText5 = wx.StaticText(id=ID_DATATYPEEDITORSTATICTEXT5,
- label='Initial Value:', name='staticText5', parent=self.SubrangePanel,
- pos=wx.Point(0, 0), size=wx.Size(150, 17), style=0)
+ label=_('Initial Value:'), name='staticText5', parent=self.SubrangePanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.SubrangeInitialValue = wx.SpinCtrl(id=ID_DATATYPEEDITORSUBRANGEINITIALVALUE,
name='SubrangeInitialValue', parent=self.SubrangePanel, pos=wx.Point(0, 0),
@@ -404,8 +418,8 @@
self.Bind(wx.EVT_SPINCTRL, self.OnInfosChanged, id=ID_DATATYPEEDITORSUBRANGEINITIALVALUE)
self.staticText6 = wx.StaticText(id=ID_DATATYPEEDITORSTATICTEXT6,
- label='Minimum:', name='staticText6', parent=self.SubrangePanel,
- pos=wx.Point(0, 0), size=wx.Size(150, 17), style=0)
+ label=_('Minimum:'), name='staticText6', parent=self.SubrangePanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.SubrangeMinimum = wx.SpinCtrl(id=ID_DATATYPEEDITORSUBRANGEMINIMUM,
name='SubrangeMinimum', parent=self.SubrangePanel, pos=wx.Point(0, 0),
@@ -413,8 +427,8 @@
self.Bind(wx.EVT_SPINCTRL, self.OnSubrangeMinimumChanged, id=ID_DATATYPEEDITORSUBRANGEMINIMUM)
self.staticText7 = wx.StaticText(id=ID_DATATYPEEDITORSTATICTEXT7,
- label='Maximum:', name='staticText7', parent=self.SubrangePanel,
- pos=wx.Point(0, 0), size=wx.Size(150, 17), style=0)
+ label=_('Maximum:'), name='staticText7', parent=self.SubrangePanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.SubrangeMaximum = wx.SpinCtrl(id=ID_DATATYPEEDITORSUBRANGEMAXIMUM,
name='SubrangeMaximum', parent=self.SubrangePanel, pos=wx.Point(0, 0),
@@ -428,17 +442,26 @@
size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL)
self.EnumeratedValues = wx.gizmos.EditableListBox(id=ID_DATATYPEEDITORENUMERATEDVALUES,
- name='EnumeratedValues', parent=self.EnumeratedPanel, label="Values:", pos=wx.Point(0, 0),
+ name='EnumeratedValues', parent=self.EnumeratedPanel, label=_("Values:"), pos=wx.Point(0, 0),
size=wx.Size(0, 0), style=wx.gizmos.EL_ALLOW_NEW | wx.gizmos.EL_ALLOW_EDIT | wx.gizmos.EL_ALLOW_DELETE)
self.EnumeratedValues.GetListCtrl().Bind(wx.EVT_LIST_END_LABEL_EDIT, self.OnEnumeratedValueEndEdit)
- self.EnumeratedValues.GetNewButton().Bind(wx.EVT_BUTTON, self.OnEnumeratedValuesChanged)
- self.EnumeratedValues.GetDelButton().Bind(wx.EVT_BUTTON, self.OnEnumeratedValuesChanged)
- self.EnumeratedValues.GetUpButton().Bind(wx.EVT_BUTTON, self.OnEnumeratedValuesChanged)
- self.EnumeratedValues.GetDownButton().Bind(wx.EVT_BUTTON, self.OnEnumeratedValuesChanged)
+ self.EnumeratedValues.GetEditButton().SetToolTipString(_("Edit item"))
+ new_button = self.EnumeratedValues.GetNewButton()
+ new_button.SetToolTipString(_("New item"))
+ new_button.Bind(wx.EVT_BUTTON, self.OnEnumeratedValuesChanged)
+ del_button = self.EnumeratedValues.GetDelButton()
+ del_button.SetToolTipString(_("Delete item"))
+ del_button.Bind(wx.EVT_BUTTON, self.OnEnumeratedValuesChanged)
+ up_button = self.EnumeratedValues.GetUpButton()
+ up_button.SetToolTipString(_("Move up"))
+ up_button.Bind(wx.EVT_BUTTON, self.OnEnumeratedValuesChanged)
+ down_button = self.EnumeratedValues.GetDownButton()
+ down_button.SetToolTipString(_("Move down"))
+ down_button.Bind(wx.EVT_BUTTON, self.OnEnumeratedValuesChanged)
self.staticText8 = wx.StaticText(id=ID_DATATYPEEDITORSTATICTEXT8,
- label='Initial Value:', name='staticText8', parent=self.EnumeratedPanel,
- pos=wx.Point(0, 0), size=wx.Size(150, 17), style=0)
+ label=_('Initial Value:'), name='staticText8', parent=self.EnumeratedPanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.EnumeratedInitialValue = wx.ComboBox(id=ID_DATATYPEEDITORENUMERATEDINITIALVALUE,
name='EnumeratedInitialValue', parent=self.EnumeratedPanel, pos=wx.Point(0, 0),
@@ -452,8 +475,8 @@
size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL)
self.staticText9 = wx.StaticText(id=ID_DATATYPEEDITORSTATICTEXT9,
- label='Base Type:', name='staticText9', parent=self.ArrayPanel,
- pos=wx.Point(0, 0), size=wx.Size(150, 17), style=0)
+ label=_('Base Type:'), name='staticText9', parent=self.ArrayPanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.ArrayBaseType = wx.ComboBox(id=ID_DATATYPEEDITORARRAYBASETYPE,
name='SubrangeBaseType', parent=self.ArrayPanel, pos=wx.Point(0, 0),
@@ -461,17 +484,26 @@
self.Bind(wx.EVT_COMBOBOX, self.OnInfosChanged, id=ID_DATATYPEEDITORARRAYBASETYPE)
self.ArrayDimensions = wx.gizmos.EditableListBox(id=ID_DATATYPEEDITORARRAYDIMENSIONS,
- name='ArrayDimensions', parent=self.ArrayPanel, label="Dimensions:", pos=wx.Point(0, 0),
+ name='ArrayDimensions', parent=self.ArrayPanel, label=_("Dimensions:"), pos=wx.Point(0, 0),
size=wx.Size(0, 24), style=wx.gizmos.EL_ALLOW_NEW | wx.gizmos.EL_ALLOW_EDIT | wx.gizmos.EL_ALLOW_DELETE)
self.ArrayDimensions.GetListCtrl().Bind(wx.EVT_LIST_END_LABEL_EDIT, self.OnDimensionsChanged)
- self.ArrayDimensions.GetNewButton().Bind(wx.EVT_BUTTON, self.OnDimensionsChanged)
- self.ArrayDimensions.GetDelButton().Bind(wx.EVT_BUTTON, self.OnDimensionsChanged)
- self.ArrayDimensions.GetUpButton().Bind(wx.EVT_BUTTON, self.OnDimensionsChanged)
- self.ArrayDimensions.GetDownButton().Bind(wx.EVT_BUTTON, self.OnDimensionsChanged)
+ self.ArrayDimensions.GetEditButton().SetToolTipString(_("Edit item"))
+ new_button = self.ArrayDimensions.GetNewButton()
+ new_button.SetToolTipString(_("New item"))
+ new_button.Bind(wx.EVT_BUTTON, self.OnDimensionsChanged)
+ del_button = self.ArrayDimensions.GetDelButton()
+ del_button.SetToolTipString(_("Delete item"))
+ del_button.Bind(wx.EVT_BUTTON, self.OnDimensionsChanged)
+ up_button = self.ArrayDimensions.GetUpButton()
+ up_button.SetToolTipString(_("Move up"))
+ up_button.Bind(wx.EVT_BUTTON, self.OnDimensionsChanged)
+ down_button = self.ArrayDimensions.GetDownButton()
+ down_button.SetToolTipString(_("Move down"))
+ down_button.Bind(wx.EVT_BUTTON, self.OnDimensionsChanged)
self.staticText10 = wx.StaticText(id=ID_DATATYPEEDITORSTATICTEXT10,
- label='Initial Value:', name='staticText10', parent=self.ArrayPanel,
- pos=wx.Point(0, 0), size=wx.Size(150, 17), style=0)
+ label=_('Initial Value:'), name='staticText10', parent=self.ArrayPanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.ArrayInitialValue = wx.TextCtrl(id=ID_DATATYPEEDITORARRAYINITIALVALUE,
name='ArrayInitialValue', parent=self.ArrayPanel, pos=wx.Point(0, 0),
@@ -485,8 +517,8 @@
size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL)
self.staticText11 = wx.StaticText(id=ID_DATATYPEEDITORSTATICTEXT11,
- label='Elements :', name='staticText11', parent=self.StructurePanel,
- pos=wx.Point(0, 0), size=wx.Size(150, 17), style=0)
+ label=_('Elements :'), name='staticText11', parent=self.StructurePanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.StructureElementsGrid = wx.grid.Grid(id=ID_DATATYPEEDITORSTRUCTUREELEMENTSGRID,
name='StructureElementsGrid', parent=self.StructurePanel, pos=wx.Point(0, 0),
@@ -504,14 +536,14 @@
wx.grid.EVT_GRID_CELL_CHANGE(self.StructureElementsGrid, self.OnStructureElementsGridCellChange)
wx.grid.EVT_GRID_EDITOR_SHOWN(self.StructureElementsGrid, self.OnStructureElementsGridEditorShown)
- self.StructureAddButton = wx.Button(id=ID_DATATYPEEDITORSTRUCTUREADDBUTTON, label='Add',
+ self.StructureAddButton = wx.Button(id=ID_DATATYPEEDITORSTRUCTUREADDBUTTON, label=_('Add'),
name='StructureAddButton', parent=self.StructurePanel, pos=wx.Point(0, 0),
- size=wx.Size(72, 32), style=0)
+ size=wx.DefaultSize, style=0)
self.Bind(wx.EVT_BUTTON, self.OnStructureAddButton, id=ID_DATATYPEEDITORSTRUCTUREADDBUTTON)
- self.StructureDeleteButton = wx.Button(id=ID_DATATYPEEDITORSTRUCTUREDELETEBUTTON, label='Delete',
+ self.StructureDeleteButton = wx.Button(id=ID_DATATYPEEDITORSTRUCTUREDELETEBUTTON, label=_('Delete'),
name='StructureDeleteButton', parent=self.StructurePanel, pos=wx.Point(0, 0),
- size=wx.Size(72, 32), style=0)
+ size=wx.DefaultSize, style=0)
self.Bind(wx.EVT_BUTTON, self.OnStructureDeleteButton, id=ID_DATATYPEEDITORSTRUCTUREDELETEBUTTON)
self.StructureUpButton = wx.Button(id=ID_DATATYPEEDITORSTRUCTUREUPBUTTON, label='^',
@@ -530,7 +562,7 @@
self._init_ctrls(parent)
self.StructureElementDefaultValue = {"Name" : "", "Type" : "INT", "Initial Value" : ""}
- self.StructureElementsTable = ElementsTable(self, [], ["#", "Name", "Type", "Initial Value"])
+ self.StructureElementsTable = ElementsTable(self, [], GetElementsTableColnames())
self.StructureColSizes = [40, 150, 100, 250]
self.StructureColAlignements = [wx.ALIGN_CENTER, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT]
@@ -540,13 +572,11 @@
attr = wx.grid.GridCellAttr()
attr.SetAlignment(self.StructureColAlignements[col], wx.ALIGN_CENTRE)
self.StructureElementsGrid.SetColAttr(col, attr)
- self.StructureElementsGrid.SetColSize(col, self.StructureColSizes[col])
-
- self.DerivationType.Append("Directly")
- self.DerivationType.Append("Subrange")
- self.DerivationType.Append("Enumerated")
- self.DerivationType.Append("Array")
- self.DerivationType.Append("Structure")
+ self.StructureElementsGrid.SetColMinimalWidth(col, self.StructureColSizes[col])
+ self.StructureElementsGrid.AutoSizeColumn(col, False)
+
+ for datatype in GetDatatypeTypes():
+ self.DerivationType.Append(_(datatype))
self.SubrangePanel.Hide()
self.EnumeratedPanel.Hide()
self.ArrayPanel.Hide()
@@ -590,15 +620,16 @@
self.RefreshBoundsRange()
type_infos = self.Controler.GetDataTypeInfos(self.TagName)
if type_infos is not None:
- self.DerivationType.SetStringSelection(type_infos["type"])
+ datatype = type_infos["type"]
+ self.DerivationType.SetStringSelection(_(datatype))
if type_infos["type"] == "Directly":
self.DirectlyBaseType.SetStringSelection(type_infos["base_type"])
self.DirectlyInitialValue.SetValue(type_infos["initial"])
elif type_infos["type"] == "Subrange":
self.SubrangeBaseType.SetStringSelection(type_infos["base_type"])
self.RefreshBoundsRange()
- self.SubrangeMinimum.SetValue(type_infos["min"])
- self.SubrangeMaximum.SetValue(type_infos["max"])
+ self.SubrangeMinimum.SetValue(int(type_infos["min"]))
+ self.SubrangeMaximum.SetValue(int(type_infos["max"]))
self.RefreshSubrangeInitialValueRange()
if type_infos["initial"] != "":
self.SubrangeInitialValue.SetValue(int(type_infos["initial"]))
@@ -610,7 +641,7 @@
self.EnumeratedInitialValue.SetStringSelection(type_infos["initial"])
elif type_infos["type"] == "Array":
self.ArrayBaseType.SetStringSelection(type_infos["base_type"])
- self.ArrayDimensions.SetStrings(map(lambda x : "..".join(map(str, x)), type_infos["dimensions"]))
+ self.ArrayDimensions.SetStrings(map(lambda x : "..".join(x), type_infos["dimensions"]))
self.ArrayInitialValue.SetValue(type_infos["initial"])
elif type_infos["type"] == "Structure":
self.StructureElementsTable.SetData(type_infos["elements"])
@@ -663,12 +694,12 @@
index = event.GetIndex()
if index >= len(values) or values[index].upper() != text.upper():
if text.upper() in [value.upper() for value in values]:
- message = wx.MessageDialog(self, "\"%s\" value already defined!"%text, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" value already defined!")%text, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
event.Veto()
elif text.upper() in IEC_KEYWORDS:
- message = wx.MessageDialog(self, "\"%s\" is a keyword. It can't be used!"%text, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is a keyword. It can't be used!")%text, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
else:
@@ -723,12 +754,12 @@
value = self.StructureElementsTable.GetValue(row, col)
if colname == "Name":
if not TestIdentifier(value):
- message = wx.MessageDialog(self, "\"%s\" is not a valid identifier!"%value, "Error", wx.OK|wx.ICON_ERROR)
+ 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 = 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()
@@ -738,7 +769,7 @@
## message.Destroy()
## event.Veto()
elif value.upper() in [var["Name"].upper() for idx, var in enumerate(self.StructureElementsTable.GetData()) if idx != row]:
- message = wx.MessageDialog(self, "A element with \"%s\" as name exists in this structure!"%value, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("A element with \"%s\" as name exists in this structure!")%value, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
event.Veto()
@@ -764,13 +795,13 @@
new_id = wx.NewId()
AppendMenu(base_menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=base_type)
self.Bind(wx.EVT_MENU, self.GetElementTypeFunction(base_type), id=new_id)
- type_menu.AppendMenu(wx.NewId(), "Base Types", base_menu)
+ type_menu.AppendMenu(wx.NewId(), _("Base Types"), base_menu)
datatype_menu = wx.Menu(title='')
for datatype in self.Controler.GetDataTypes(self.TagName, False, 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.GetElementTypeFunction(datatype), id=new_id)
- type_menu.AppendMenu(wx.NewId(), "User Data Types", datatype_menu)
+ 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)
@@ -779,7 +810,7 @@
## 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)
+## type_menu.AppendMenu(wx.NewId(), _("Function Block Types"), functionblock_menu)
rect = self.StructureElementsGrid.BlockToDeviceRect((row, col), (row, col))
self.StructureElementsGrid.PopupMenuXY(type_menu, rect.x + rect.width, rect.y + self.StructureElementsGrid.GetColLabelSize())
event.Veto()
@@ -796,7 +827,7 @@
return ElementTypeFunction
def RefreshDisplayedInfos(self):
- selected = self.DerivationType.GetStringSelection()
+ selected = DATATYPE_TYPES_DICT[self.DerivationType.GetStringSelection()]
if selected != self.CurrentPanel:
if self.CurrentPanel == "Directly":
self.DirectlyPanel.Hide()
@@ -842,15 +873,15 @@
self.SubrangeInitialValue.SetRange(self.SubrangeMinimum.GetValue(), self.SubrangeMaximum.GetValue())
def RefreshTypeInfos(self):
- selected = self.DerivationType.GetStringSelection()
+ selected = DATATYPE_TYPES_DICT[self.DerivationType.GetStringSelection()]
infos = {"type" : selected}
if selected == "Directly":
infos["base_type"] = self.DirectlyBaseType.GetStringSelection()
infos["initial"] = self.DirectlyInitialValue.GetValue()
elif selected == "Subrange":
infos["base_type"] = self.SubrangeBaseType.GetStringSelection()
- infos["min"] = self.SubrangeMinimum.GetValue()
- infos["max"] = self.SubrangeMaximum.GetValue()
+ infos["min"] = str(self.SubrangeMinimum.GetValue())
+ infos["max"] = str(self.SubrangeMaximum.GetValue())
initial_value = self.SubrangeInitialValue.GetValue()
if initial_value == infos["min"]:
infos["initial"] = ""
@@ -865,19 +896,19 @@
for dimensions in self.ArrayDimensions.GetStrings():
result = DIMENSION_MODEL.match(dimensions)
if result is None:
- message = wx.MessageDialog(self, "\"%s\" value isn't a valid array dimension!"%dimensions, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" value isn't a valid array dimension!")%dimensions, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
self.RefreshView()
return
bounds = result.groups()
if bounds[0] >= bounds[1]:
- message = wx.MessageDialog(self, "\"%s\" value isn't a valid array dimension!\nRight value must be greater than left value."%dimensions, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" value isn't a valid array dimension!\nRight value must be greater than left value.")%dimensions, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
self.RefreshView()
return
- infos["dimensions"].append(map(int, bounds))
+ infos["dimensions"].append(bounds)
infos["initial"] = self.ArrayInitialValue.GetValue()
elif selected == "Structure":
infos["elements"] = self.StructureElementsTable.GetData()
diff -r e0a6a5952d13 -r 127d524a5f1d Dialogs.py
--- a/Dialogs.py Mon Jul 06 11:24:37 2009 -0600
+++ b/Dialogs.py Thu Aug 20 09:03:31 2009 -0600
@@ -77,21 +77,24 @@
parent.AddGrowableRow(2)
def _init_coll_RightUpGridSizer_Items(self, parent):
- parent.AddWindow(self.staticText2, 0, border=4, flag=wx.GROW|wx.TOP)
+ parent.AddWindow(self.staticText2, 0, border=4, flag=wx.ALIGN_CENTER_VERTICAL|wx.TOP)
parent.AddWindow(self.BlockName, 0, border=0, flag=wx.GROW)
- parent.AddWindow(self.staticText3, 0, border=4, flag=wx.GROW|wx.TOP)
+ parent.AddWindow(self.staticText3, 0, border=4, flag=wx.ALIGN_CENTER_VERTICAL|wx.TOP)
parent.AddWindow(self.Inputs, 0, border=0, flag=wx.GROW)
- parent.AddWindow(self.staticText4, 0, border=4, flag=wx.GROW|wx.TOP)
+ parent.AddWindow(self.staticText4, 0, border=4, flag=wx.ALIGN_CENTER_VERTICAL|wx.TOP)
parent.AddWindow(self.ExecutionOrder, 0, border=0, flag=wx.GROW)
- parent.AddWindow(self.staticText5, 0, border=4, flag=wx.GROW|wx.TOP)
+ parent.AddWindow(self.staticText5, 0, border=4, flag=wx.ALIGN_CENTER_VERTICAL|wx.TOP)
parent.AddWindow(self.ExecutionControl, 0, border=0, flag=wx.GROW)
-
+
+ def _init_coll_RightUpGridSizer_Growables(self, parent):
+ parent.AddGrowableCol(1)
+
def _init_sizers(self):
self.flexGridSizer1 = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=10)
self.MainSizer = wx.BoxSizer(wx.HORIZONTAL)
self.LeftBoxSizer = wx.StaticBoxSizer(self.staticbox1, wx.VERTICAL)
self.RightGridSizer = wx.FlexGridSizer(cols=1, hgap=0, rows=3, vgap=5)
- self.RightUpGridSizer = wx.GridSizer(cols=2, hgap=5, rows=4, vgap=5)
+ self.RightUpGridSizer = wx.FlexGridSizer(cols=2, hgap=5, rows=4, vgap=5)
self._init_coll_flexGridSizer1_Items(self.flexGridSizer1)
self._init_coll_flexGridSizer1_Growables(self.flexGridSizer1)
@@ -100,6 +103,7 @@
self._init_coll_RightGridSizer_Items(self.RightGridSizer)
self._init_coll_RightGridSizer_Growables(self.RightGridSizer)
self._init_coll_RightUpGridSizer_Items(self.RightUpGridSizer)
+ self._init_coll_RightUpGridSizer_Growables(self.RightUpGridSizer)
self.SetSizer(self.flexGridSizer1)
@@ -107,32 +111,32 @@
wx.Dialog.__init__(self, id=ID_BLOCKPROPERTIESDIALOG,
name='BlockPropertiesDialog', parent=prnt, pos=wx.Point(376, 223),
size=wx.Size(600, 400), style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER,
- title='Block Properties')
+ title=_('Block Properties'))
self.SetClientSize(wx.Size(600, 400))
self.staticbox1 = wx.StaticBox(id=ID_BLOCKPROPERTIESDIALOGSTATICTEXT1,
- label='Type:', name='staticBox1', parent=self,
+ label=_('Type:'), name='staticBox1', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 0), style=0)
self.staticText2 = wx.StaticText(id=ID_BLOCKPROPERTIESDIALOGSTATICTEXT2,
- label='Name:', name='staticText2', parent=self,
- pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
+ label=_('Name:'), name='staticText2', parent=self,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.staticText3 = wx.StaticText(id=ID_BLOCKPROPERTIESDIALOGSTATICTEXT2,
- label='Inputs:', name='staticText4', parent=self,
- pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
+ label=_('Inputs:'), name='staticText4', parent=self,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.staticText4 = wx.StaticText(id=ID_BLOCKPROPERTIESDIALOGSTATICTEXT4,
- label='Execution Order:', name='staticText4', parent=self,
- pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
+ label=_('Execution Order:'), name='staticText4', parent=self,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.staticText5 = wx.StaticText(id=ID_BLOCKPROPERTIESDIALOGSTATICTEXT5,
- label='Execution Control:', name='staticText5', parent=self,
- pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
+ label=_('Execution Control:'), name='staticText5', parent=self,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.staticText6 = wx.StaticText(id=ID_BLOCKPROPERTIESDIALOGSTATICTEXT6,
- label='Preview:', name='staticText6', parent=self,
- pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
+ label=_('Preview:'), name='staticText6', parent=self,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
if wx.Platform == '__WXMSW__':
treestyle = wx.TR_HAS_BUTTONS|wx.TR_SINGLE|wx.SUNKEN_BORDER
@@ -234,27 +238,27 @@
block_name = self.BlockName.GetValue()
name_enabled = self.BlockName.IsEnabled()
if not selected.IsOk() or self.TypeTree.GetItemParent(selected) == self.TypeTree.GetRootItem() or selected == self.TypeTree.GetRootItem():
- message = wx.MessageDialog(self, "Form isn't complete. Valid block type must be selected!", "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("Form isn't complete. Valid block type must be selected!"), _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif name_enabled and block_name == "":
- message = wx.MessageDialog(self, "Form isn't complete. Name must be filled!", "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("Form isn't complete. Name must be filled!"), _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif name_enabled and not TestIdentifier(block_name):
- message = wx.MessageDialog(self, "\"%s\" is not a valid identifier!"%block_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is not a valid identifier!")%block_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif name_enabled and block_name.upper() in IEC_KEYWORDS:
- message = wx.MessageDialog(self, "\"%s\" is a keyword. It can't be used!"%block_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is a keyword. It can't be used!")%block_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif name_enabled and block_name.upper() in self.PouNames:
- message = wx.MessageDialog(self, "\"%s\" pou already exists!"%block_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" pou already exists!")%block_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif name_enabled and block_name.upper() in self.PouElementNames:
- message = wx.MessageDialog(self, "\"%s\" element for this pou already exists!"%block_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" element for this pou already exists!")%block_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
else:
@@ -262,12 +266,13 @@
def SetBlockList(self, blocktypes):
if wx.Platform == '__WXMSW__':
- root = self.TypeTree.AddRoot("Block Types")
+ root = self.TypeTree.AddRoot(_("Block Types"))
else:
root = self.TypeTree.AddRoot("")
self.TypeTree.SetPyData(root, {"type" : CATEGORY})
for category in blocktypes:
- category_item = self.TypeTree.AppendItem(root, category["name"])
+ category_name = category["name"]
+ category_item = self.TypeTree.AppendItem(root, _(category_name))
self.TypeTree.SetPyData(category_item, {"type" : CATEGORY})
for blocktype in category["list"]:
blocktype_item = self.TypeTree.AppendItem(category_item, blocktype["name"])
@@ -330,7 +335,8 @@
self.Inputs.SetValue(len(blocktype["inputs"]))
self.Inputs.Enable(blocktype["extensible"])
self.BlockName.Enable(blocktype["type"] != "function")
- self.TypeDesc.SetValue(blocktype["comment"])
+ comment = blocktype["comment"]
+ self.TypeDesc.SetValue(_(comment) + blocktype.get("usage", ""))
wx.CallAfter(self.RefreshPreview)
else:
self.BlockName.Enable(False)
@@ -416,6 +422,11 @@
ID_VARIABLEPROPERTIESDIALOGSTATICTEXT4, ID_VARIABLEPROPERTIESDIALOGSTATICTEXT5
] = [wx.NewId() for _init_ctrls in range(12)]
+VARIABLE_CLASSES_DICT = {INPUT : _("Input"),
+ INOUT : _("InOut"),
+ OUTPUT : _("Output")}
+VARIABLE_CLASSES_DICT_REVERSE = dict([(value, key) for key, value in VARIABLE_CLASSES_DICT.iteritems()])
+
class VariablePropertiesDialog(wx.Dialog):
if wx.VERSION < (2, 6, 0):
@@ -490,27 +501,27 @@
wx.Dialog.__init__(self, id=ID_VARIABLEPROPERTIESDIALOG,
name='VariablePropertiesDialog', parent=prnt, pos=wx.Point(376, 223),
size=wx.Size(400, 380), style=wx.DEFAULT_DIALOG_STYLE,
- title='Variable Properties')
+ title=_('Variable Properties'))
self.SetClientSize(wx.Size(400, 380))
self.staticText1 = wx.StaticText(id=ID_VARIABLEPROPERTIESDIALOGSTATICTEXT1,
- label='Class:', name='staticText1', parent=self,
+ label=_('Class:'), name='staticText1', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.staticText2 = wx.StaticText(id=ID_VARIABLEPROPERTIESDIALOGSTATICTEXT2,
- label='Expression:', name='staticText2', parent=self,
+ label=_('Expression:'), name='staticText2', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.staticText3 = wx.StaticText(id=ID_VARIABLEPROPERTIESDIALOGSTATICTEXT3,
- label='Execution Order:', name='staticText3', parent=self,
+ label=_('Execution Order:'), name='staticText3', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.staticText4 = wx.StaticText(id=ID_VARIABLEPROPERTIESDIALOGSTATICTEXT4,
- label='Name:', name='staticText4', parent=self,
+ label=_('Name:'), name='staticText4', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.staticText5 = wx.StaticText(id=ID_VARIABLEPROPERTIESDIALOGSTATICTEXT5,
- label='Preview:', name='staticText5', parent=self,
+ label=_('Preview:'), name='staticText5', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.Class = wx.ComboBox(id=ID_VARIABLEPROPERTIESDIALOGCLASS,
@@ -561,28 +572,30 @@
self.Variable = None
self.VarList = []
self.MinVariableSize = None
+
+ for choice in VARIABLE_CLASSES_DICT.itervalues():
+ self.Class.Append(choice)
+ self.Class.SetStringSelection(VARIABLE_CLASSES_DICT[INPUT])
+
self.RefreshNameList()
-
- for choice in ["Input", "Output", "InOut"]:
- self.Class.Append(choice)
- self.Class.SetStringSelection("Input")
def SetPreviewFont(self, font):
self.Preview.SetFont(font)
def RefreshNameList(self):
selected = self.VariableName.GetStringSelection()
+ var_class = VARIABLE_CLASSES_DICT_REVERSE[self.Class.GetStringSelection()]
self.VariableName.Clear()
self.VariableName.Append("")
for name, var_type, value_type in self.VarList:
- if var_type != "Input" or self.Class.GetStringSelection() == "Input":
+ if var_type != "Input" or var_class == INPUT:
self.VariableName.Append(name)
if selected != "" and self.VariableName.FindString(selected) != wx.NOT_FOUND:
self.VariableName.SetStringSelection(selected)
self.Expression.Enable(False)
else:
self.VariableName.SetStringSelection("")
- self.Expression.Enable(self.Class.GetStringSelection() == "Input")
+ self.Expression.Enable(var_class == INPUT)
self.VariableName.Enable(self.VariableName.GetCount() > 0)
def SetMinVariableSize(self, size):
@@ -596,12 +609,7 @@
value_type = values.get("type", None)
value_name = values.get("name", None)
if value_type:
- if value_type == INPUT:
- self.Class.SetStringSelection("Input")
- if value_type == OUTPUT:
- self.Class.SetStringSelection("Output")
- if value_type == INOUT:
- self.Class.SetStringSelection("InOut")
+ self.Class.SetStringSelection(VARIABLE_CLASSES_DICT[value_type])
self.RefreshNameList()
if value_name:
if self.VariableName.FindString(value_name) != wx.NOT_FOUND:
@@ -616,13 +624,7 @@
def GetValues(self):
values = {}
- classtype = self.Class.GetStringSelection()
- if classtype == "Input":
- values["type"] = INPUT
- elif classtype == "Output":
- values["type"] = OUTPUT
- elif classtype == "InOut":
- values["type"] = INOUT
+ values["type"] = VARIABLE_CLASSES_DICT_REVERSE[self.Class.GetStringSelection()]
expression = self.Expression.GetValue()
if self.Expression.IsEnabled() and expression != "":
values["name"] = expression
@@ -643,11 +645,11 @@
else:
value = self.VariableName.GetStringSelection()
if value == "":
- message = wx.MessageDialog(self, "At least a variable or an expression must be selected!", "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("At least a variable or an expression must be selected!"), _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
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 = wx.MessageDialog(self, _("\"%s\" is a keyword. It can't be used!")%value, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
else:
@@ -661,7 +663,7 @@
def OnNameChanged(self, event):
if self.VariableName.GetStringSelection() != "":
self.Expression.Enable(False)
- elif self.Class.GetStringSelection() == "Input":
+ elif VARIABLE_CLASSES_DICT_REVERSE[self.Class.GetStringSelection()] == INPUT:
self.Expression.Enable(True)
self.RefreshPreview()
event.Skip()
@@ -691,13 +693,8 @@
for var_name, var_type, value_type in self.VarList:
if var_name == name:
type = value_type
- classtype = self.Class.GetStringSelection()
- if classtype == "Input":
- self.Variable = FBD_Variable(self.Preview, INPUT, name, type, executionOrder = self.ExecutionOrder.GetValue())
- elif classtype == "Output":
- self.Variable = FBD_Variable(self.Preview, OUTPUT, name, type, executionOrder = self.ExecutionOrder.GetValue())
- elif classtype == "InOut":
- self.Variable = FBD_Variable(self.Preview, INOUT, name, type, executionOrder = self.ExecutionOrder.GetValue())
+ classtype = VARIABLE_CLASSES_DICT_REVERSE[self.Class.GetStringSelection()]
+ self.Variable = FBD_Variable(self.Preview, classtype, name, type, executionOrder = self.ExecutionOrder.GetValue())
width, height = self.MinVariableSize
min_width, min_height = self.Variable.GetMinSize()
width, height = max(min_width, width), max(min_height, height)
@@ -784,29 +781,29 @@
wx.Dialog.__init__(self, id=ID_CONNECTIONPROPERTIESDIALOG,
name='ConnectionPropertiesDialog', parent=prnt, pos=wx.Point(376, 223),
size=wx.Size(350, 220), style=wx.DEFAULT_DIALOG_STYLE,
- title='Connection Properties')
+ title=_('Connection Properties'))
self.SetClientSize(wx.Size(350, 220))
self.staticText1 = wx.StaticText(id=ID_CONNECTIONPROPERTIESDIALOGSTATICTEXT1,
- label='Type:', name='staticText1', parent=self,
+ label=_('Type:'), name='staticText1', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.staticText2 = wx.StaticText(id=ID_CONNECTIONPROPERTIESDIALOGSTATICTEXT2,
- label='Name:', name='staticText2', parent=self,
+ label=_('Name:'), name='staticText2', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.staticText3 = wx.StaticText(id=ID_CONNECTIONPROPERTIESDIALOGSTATICTEXT3,
- label='Preview:', name='staticText3', parent=self,
+ label=_('Preview:'), name='staticText3', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.radioButton1 = wx.RadioButton(id=ID_CONNECTIONPROPERTIESDIALOGRADIOBUTTON1,
- label='Connector', name='radioButton1', parent=self,
+ label=_('Connector'), name='radioButton1', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 24), style=wx.RB_GROUP)
self.Bind(wx.EVT_RADIOBUTTON, self.OnTypeChanged, id=ID_CONNECTIONPROPERTIESDIALOGRADIOBUTTON1)
self.radioButton1.SetValue(True)
self.radioButton2 = wx.RadioButton(id=ID_CONNECTIONPROPERTIESDIALOGRADIOBUTTON2,
- label='Continuation', name='radioButton2', parent=self,
+ label=_('Continuation'), name='radioButton2', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 24), style=0)
self.Bind(wx.EVT_RADIOBUTTON, self.OnTypeChanged, id=ID_CONNECTIONPROPERTIESDIALOGRADIOBUTTON2)
self.radioButton2.SetValue(False)
@@ -882,23 +879,23 @@
def OnOK(self, event):
connection_name = self.ConnectionName.GetValue()
if connection_name == "":
- message = wx.MessageDialog(self, "Form isn't complete. Name must be filled!", "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("Form isn't complete. Name must be filled!"), _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif not TestIdentifier(connection_name):
- message = wx.MessageDialog(self, "\"%s\" is not a valid identifier!"%connection_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is not a valid identifier!")%connection_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif connection_name.upper() in IEC_KEYWORDS:
- message = wx.MessageDialog(self, "\"%s\" is a keyword. It can't be used!"%connection_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is a keyword. It can't be used!")%connection_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif connection_name.upper() in self.PouNames:
- message = wx.MessageDialog(self, "\"%s\" pou already exists!"%connection_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" pou already exists!")%connection_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif connection_name.upper() in self.PouElementNames:
- message = wx.MessageDialog(self, "\"%s\" element for this pou already exists!"%connection_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" element for this pou already exists!")%connection_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
else:
@@ -1022,45 +1019,45 @@
self.SetClientSize(wx.Size(350, 260 + extra_size))
self.staticText1 = wx.StaticText(id=ID_LDELEMENTDIALOGSTATICTEXT1,
- label='Modifier:', name='staticText1', parent=self,
+ label=_('Modifier:'), name='staticText1', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.staticText2 = wx.StaticText(id=ID_LDELEMENTDIALOGSTATICTEXT2,
- label='Name:', name='staticText2', parent=self,
+ label=_('Name:'), name='staticText2', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.staticText3 = wx.StaticText(id=ID_LDELEMENTDIALOGSTATICTEXT3,
- label='Preview:', name='staticText3', parent=self,
+ label=_('Preview:'), name='staticText3', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.radioButton1 = wx.RadioButton(id=ID_LDELEMENTDIALOGRADIOBUTTON1,
- label="Normal", name='radioButton1', parent=self,
+ label=_("Normal"), name='radioButton1', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 24), style=wx.RB_GROUP)
self.Bind(wx.EVT_RADIOBUTTON, self.OnTypeChanged, id=ID_LDELEMENTDIALOGRADIOBUTTON1)
self.radioButton1.SetValue(True)
self.radioButton2 = wx.RadioButton(id=ID_LDELEMENTDIALOGRADIOBUTTON2,
- label="Negated", name='radioButton2', parent=self,
+ label=_("Negated"), name='radioButton2', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 24), style=0)
self.Bind(wx.EVT_RADIOBUTTON, self.OnTypeChanged, id=ID_LDELEMENTDIALOGRADIOBUTTON2)
self.radioButton3 = wx.RadioButton(id=ID_LDELEMENTDIALOGRADIOBUTTON3,
- label="Set", name='radioButton3', parent=self,
+ label=_("Set"), name='radioButton3', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 24), style=0)
self.Bind(wx.EVT_RADIOBUTTON, self.OnTypeChanged, id=ID_LDELEMENTDIALOGRADIOBUTTON3)
self.radioButton4 = wx.RadioButton(id=ID_LDELEMENTDIALOGRADIOBUTTON4,
- label="Reset", name='radioButton4', parent=self,
+ label=_("Reset"), name='radioButton4', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 24), style=0)
self.Bind(wx.EVT_RADIOBUTTON, self.OnTypeChanged, id=ID_LDELEMENTDIALOGRADIOBUTTON4)
self.radioButton5 = wx.RadioButton(id=ID_LDELEMENTDIALOGRADIOBUTTON5,
- label="Rising Edge", name='radioButton5', parent=self,
+ label=_("Rising Edge"), name='radioButton5', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 24), style=0)
self.Bind(wx.EVT_RADIOBUTTON, self.OnTypeChanged, id=ID_LDELEMENTDIALOGRADIOBUTTON5)
self.radioButton6 = wx.RadioButton(id=ID_LDELEMENTDIALOGRADIOBUTTON6,
- label="Falling Edge", name='radioButton6', parent=self,
+ label=_("Falling Edge"), name='radioButton6', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 24), style=0)
self.Bind(wx.EVT_RADIOBUTTON, self.OnTypeChanged, id=ID_LDELEMENTDIALOGRADIOBUTTON6)
@@ -1093,12 +1090,12 @@
def __init__(self, parent, controler, type):
self.Type = type
if type == "contact":
- self._init_ctrls(parent, controler, "Edit Contact Values")
+ self._init_ctrls(parent, controler, _("Edit Contact Values"))
self.Element = LD_Contact(self.Preview, CONTACT_NORMAL, "")
self.radioButton3.Hide()
self.radioButton4.Hide()
elif type == "coil":
- self._init_ctrls(parent, controler, "Edit Coil Values", 50)
+ self._init_ctrls(parent, controler, _("Edit Coil Values"), 50)
self.Element = LD_Coil(self.Preview, COIL_NORMAL, "")
@@ -1271,29 +1268,29 @@
wx.Dialog.__init__(self, id=ID_LDPOWERRAILDIALOG,
name='PowerRailDialog', parent=prnt, pos=wx.Point(376, 223),
size=wx.Size(350, 260), style=wx.DEFAULT_DIALOG_STYLE,
- title='Power Rail Properties')
+ title=_('Power Rail Properties'))
self.SetClientSize(wx.Size(350, 260))
self.staticText1 = wx.StaticText(id=ID_LDPOWERRAILDIALOGSTATICTEXT1,
- label='Type:', name='staticText1', parent=self,
+ label=_('Type:'), name='staticText1', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.staticText2 = wx.StaticText(id=ID_LDPOWERRAILDIALOGSTATICTEXT2,
- label='Pin number:', name='staticText2', parent=self,
+ label=_('Pin number:'), name='staticText2', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.staticText3 = wx.StaticText(id=ID_LDPOWERRAILDIALOGSTATICTEXT3,
- label='Preview:', name='staticText3', parent=self,
+ label=_('Preview:'), name='staticText3', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.radioButton1 = wx.RadioButton(id=ID_LDPOWERRAILDIALOGRADIOBUTTON1,
- label='Left PowerRail', name='radioButton1', parent=self,
+ label=_('Left PowerRail'), name='radioButton1', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 24), style=wx.RB_GROUP)
self.Bind(wx.EVT_RADIOBUTTON, self.OnTypeChanged, id=ID_LDPOWERRAILDIALOGRADIOBUTTON1)
self.radioButton1.SetValue(True)
self.radioButton2 = wx.RadioButton(id=ID_LDPOWERRAILDIALOGRADIOBUTTON2,
- label='Right PowerRail', name='radioButton2', parent=self,
+ label=_('Right PowerRail'), name='radioButton2', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 24), style=0)
self.Bind(wx.EVT_RADIOBUTTON, self.OnTypeChanged, id=ID_LDPOWERRAILDIALOGRADIOBUTTON2)
@@ -1451,19 +1448,19 @@
wx.Dialog.__init__(self, id=ID_STEPCONTENTDIALOG,
name='StepContentDialog', parent=prnt, pos=wx.Point(376, 223),
size=wx.Size(400, 250), style=wx.DEFAULT_DIALOG_STYLE,
- title='Edit Step')
+ title=_('Edit Step'))
self.SetClientSize(wx.Size(400, 250))
self.staticText1 = wx.StaticText(id=ID_STEPCONTENTDIALOGSTATICTEXT1,
- label='Name:', name='staticText1', parent=self,
+ label=_('Name:'), name='staticText1', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.staticText2 = wx.StaticText(id=ID_STEPCONTENTDIALOGSTATICTEXT2,
- label='Connectors:', name='staticText2', parent=self,
+ label=_('Connectors:'), name='staticText2', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.staticText3 = wx.StaticText(id=ID_STEPCONTENTDIALOGSTATICTEXT3,
- label='Preview:', name='staticText4', parent=self,
+ label=_('Preview:'), name='staticText4', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.StepName = wx.TextCtrl(id=ID_STEPCONTENTDIALOGNAME,
@@ -1472,17 +1469,17 @@
self.Bind(wx.EVT_TEXT, self.OnNameChanged, id=ID_STEPCONTENTDIALOGNAME)
self.checkBox1 = wx.CheckBox(id=ID_STEPCONTENTDIALOGCHECKBOX1,
- label="Input", name='checkBox1', parent=self,
+ label=_("Input"), name='checkBox1', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 24), style=0)
self.Bind(wx.EVT_CHECKBOX, self.OnConnectorsChanged, id=ID_STEPCONTENTDIALOGCHECKBOX1)
self.checkBox2 = wx.CheckBox(id=ID_STEPCONTENTDIALOGCHECKBOX2,
- label="Output", name='checkBox2', parent=self,
+ label=_("Output"), name='checkBox2', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 24), style=0)
self.Bind(wx.EVT_CHECKBOX, self.OnConnectorsChanged, id=ID_STEPCONTENTDIALOGCHECKBOX2)
self.checkBox3 = wx.CheckBox(id=ID_STEPCONTENTDIALOGCHECKBOX3,
- label="Action", name='checkBox3', parent=self,
+ label=_("Action"), name='checkBox3', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 24), style=0)
self.Bind(wx.EVT_CHECKBOX, self.OnConnectorsChanged, id=ID_STEPCONTENTDIALOGCHECKBOX3)
@@ -1525,27 +1522,27 @@
def OnOK(self, event):
step_name = self.StepName.GetValue()
if step_name == "":
- message = wx.MessageDialog(self, "You must type a name!", "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("You must type a name!"), _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif not TestIdentifier(step_name):
- message = wx.MessageDialog(self, "\"%s\" is not a valid identifier!"%step_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is not a valid identifier!")%step_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif step_name.upper() in IEC_KEYWORDS:
- message = wx.MessageDialog(self, "\"%s\" is a keyword. It can't be used!"%step_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is a keyword. It can't be used!")%step_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif step_name.upper() in self.PouNames:
- message = wx.MessageDialog(self, "A pou with \"%s\" as name exists!"%step_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("A pou with \"%s\" as name exists!")%step_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif step_name.upper() in self.Variables:
- message = wx.MessageDialog(self, "A variable with \"%s\" as name exists!"%step_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("A variable with \"%s\" as name already exists in this pou!")%step_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif step_name.upper() in self.StepNames:
- message = wx.MessageDialog(self, "\"%s\" step already exists!"%step_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" step already exists!")%step_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
else:
@@ -1698,23 +1695,23 @@
wx.Dialog.__init__(self, id=ID_TRANSITIONCONTENTDIALOG,
name='ProjectDialog', parent=prnt, pos=wx.Point(376, 223),
size=wx.Size(350, 300), style=wx.DEFAULT_DIALOG_STYLE,
- title='Edit transition')
+ title=_('Edit transition'))
self.SetClientSize(wx.Size(350, 300))
self.staticText1 = wx.StaticText(id=ID_TRANSITIONCONTENTDIALOGSTATICTEXT1,
- label='Type:', name='staticText1', parent=self,
+ label=_('Type:'), name='staticText1', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.staticText2 = wx.StaticText(id=ID_TRANSITIONCONTENTDIALOGSTATICTEXT2,
- label='Preview:', name='staticText2', parent=self,
+ label=_('Preview:'), name='staticText2', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.staticText3 = wx.StaticText(id=ID_TRANSITIONCONTENTDIALOGSTATICTEXT3,
- label='Priority:', name='staticText3', parent=self,
+ label=_('Priority:'), name='staticText3', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.radioButton1 = wx.RadioButton(id=ID_TRANSITIONCONTENTDIALOGRADIOBUTTON1,
- label='Reference', name='radioButton1', parent=self,
+ label=_('Reference'), name='radioButton1', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 24), style=wx.RB_GROUP)
self.Bind(wx.EVT_RADIOBUTTON, self.OnTypeChanged, id=ID_TRANSITIONCONTENTDIALOGRADIOBUTTON1)
self.radioButton1.SetValue(True)
@@ -1725,7 +1722,7 @@
self.Bind(wx.EVT_COMBOBOX, self.OnReferenceChanged, id=ID_TRANSITIONCONTENTDIALOGREFERENCE)
self.radioButton2 = wx.RadioButton(id=ID_TRANSITIONCONTENTDIALOGRADIOBUTTON2,
- label='Inline', name='radioButton2', parent=self,
+ label=_('Inline'), name='radioButton2', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 24), style=0)
self.Bind(wx.EVT_RADIOBUTTON, self.OnTypeChanged, id=ID_TRANSITIONCONTENTDIALOGRADIOBUTTON2)
self.radioButton2.SetValue(False)
@@ -1737,7 +1734,7 @@
self.Inline.Enable(False)
self.radioButton3 = wx.RadioButton(id=ID_TRANSITIONCONTENTDIALOGRADIOBUTTON3,
- label='Connection', name='radioButton3', parent=self,
+ label=_('Connection'), name='radioButton3', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 24), style=0)
self.Bind(wx.EVT_RADIOBUTTON, self.OnTypeChanged, id=ID_TRANSITIONCONTENTDIALOGRADIOBUTTON3)
self.radioButton3.SetValue(False)
@@ -1791,19 +1788,19 @@
def OnOK(self, event):
error = []
if self.radioButton1.GetValue() and self.Reference.GetStringSelection() == "":
- error.append("Reference")
+ error.append(_("Reference"))
if self.radioButton2.GetValue() and self.Inline.GetValue() == "":
- error.append("Inline")
+ error.append(_("Inline"))
if len(error) > 0:
text = ""
for i, item in enumerate(error):
if i == 0:
text += item
elif i == len(error) - 1:
- text += " and %s"%item
+ text += _(" and %s")%item
else:
- text += ", %s"%item
- message = wx.MessageDialog(self, "Form isn't complete. %s must be filled!"%text, "Error", wx.OK|wx.ICON_ERROR)
+ text += _(", %s")%item
+ message = wx.MessageDialog(self, _("Form isn't complete. %s must be filled!")%text, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
else:
@@ -1976,39 +1973,39 @@
wx.Dialog.__init__(self, id=ID_DIVERGENCECREATEDIALOG,
name='DivergencePropertiesDialog', parent=prnt, pos=wx.Point(376, 223),
size=wx.Size(500, 300), style=wx.DEFAULT_DIALOG_STYLE,
- title='Create a new divergence or convergence')
+ title=_('Create a new divergence or convergence'))
self.SetClientSize(wx.Size(500, 300))
self.staticText1 = wx.StaticText(id=ID_DIVERGENCECREATEDIALOGSTATICTEXT1,
- label='Type:', name='staticText1', parent=self,
+ label=_('Type:'), name='staticText1', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.radioButton1 = wx.RadioButton(id=ID_DIVERGENCECREATEDIALOGRADIOBUTTON1,
- label='Selection Divergence', name='radioButton1', parent=self,
+ label=_('Selection Divergence'), name='radioButton1', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 24), style=wx.RB_GROUP)
self.Bind(wx.EVT_RADIOBUTTON, self.OnTypeChanged, id=ID_DIVERGENCECREATEDIALOGRADIOBUTTON1)
self.radioButton1.SetValue(True)
self.radioButton2 = wx.RadioButton(id=ID_DIVERGENCECREATEDIALOGRADIOBUTTON2,
- label='Selection Convergence', name='radioButton2', parent=self,
+ label=_('Selection Convergence'), name='radioButton2', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 24), style=0)
self.Bind(wx.EVT_RADIOBUTTON, self.OnTypeChanged, id=ID_DIVERGENCECREATEDIALOGRADIOBUTTON2)
self.radioButton2.SetValue(False)
self.radioButton3 = wx.RadioButton(id=ID_DIVERGENCECREATEDIALOGRADIOBUTTON3,
- label='Simultaneous Divergence', name='radioButton3', parent=self,
+ label=_('Simultaneous Divergence'), name='radioButton3', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 24), style=0)
self.Bind(wx.EVT_RADIOBUTTON, self.OnTypeChanged, id=ID_DIVERGENCECREATEDIALOGRADIOBUTTON3)
self.radioButton3.SetValue(False)
self.radioButton4 = wx.RadioButton(id=ID_DIVERGENCECREATEDIALOGRADIOBUTTON4,
- label='Simultaneous Convergence', name='radioButton4', parent=self,
+ label=_('Simultaneous Convergence'), name='radioButton4', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 24), style=0)
self.Bind(wx.EVT_RADIOBUTTON, self.OnTypeChanged, id=ID_DIVERGENCECREATEDIALOGRADIOBUTTON4)
self.radioButton4.SetValue(False)
self.staticText2 = wx.StaticText(id=ID_DIVERGENCECREATEDIALOGSTATICTEXT2,
- label='Number of sequences:', name='staticText2', parent=self,
+ label=_('Number of sequences:'), name='staticText2', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.Sequences = wx.SpinCtrl(id=ID_DIVERGENCECREATEDIALOGSEQUENCES,
@@ -2017,7 +2014,7 @@
self.Bind(wx.EVT_SPINCTRL, self.OnSequencesChanged, id=ID_DIVERGENCECREATEDIALOGSEQUENCES)
self.staticText3 = wx.StaticText(id=ID_DIVERGENCECREATEDIALOGSTATICTEXT3,
- label='Preview:', name='staticText3', parent=self,
+ label=_('Preview:'), name='staticText3', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.Preview = wx.Panel(id=ID_DIVERGENCECREATEDIALOGPREVIEW,
@@ -2103,6 +2100,14 @@
# Action Block Dialog
#-------------------------------------------------------------------------------
+def GetActionTableColnames():
+ _ = lambda x: x
+ return [_("Qualifier"), _("Duration"), _("Type"), _("Value"), _("Indicator")]
+
+def GetTypeList():
+ _ = lambda x: x
+ return [_("Action"), _("Variable"), _("Inline")]
+
class ActionTable(wx.grid.PyGridTableBase):
"""
@@ -2126,16 +2131,22 @@
def GetNumberRows(self):
return len(self.data)
- def GetColLabelValue(self, col):
+ def GetColLabelValue(self, col, translate=True):
if col < len(self.colnames):
- return self.colnames[col]
-
- def GetRowLabelValues(self, row):
+ colname = self.colnames[col]
+ if translate:
+ return _(colname)
+ return colname
+
+ def GetRowLabelValues(self, row, translate=True):
return row
def GetValue(self, row, col):
if row < self.GetNumberRows():
- name = str(self.data[row].get(self.GetColLabelValue(col), ""))
+ colname = self.GetColLabelValue(col, False)
+ name = str(self.data[row].get(colname, ""))
+ if colname == "Type":
+ return _(name)
return name
def GetValueByName(self, row, colname):
@@ -2143,7 +2154,10 @@
def SetValue(self, row, col, value):
if col < len(self.colnames):
- self.data[row][self.GetColLabelValue(col)] = value
+ colname = self.GetColLabelValue(col, False)
+ if colname == "Type":
+ value = self.Parent.TranslateType[value]
+ self.data[row][colname] = value
def ResetView(self, grid):
"""
@@ -2187,20 +2201,12 @@
Otherwise default to the default renderer.
"""
- for col in range(self.GetNumberCols()):
- attr = wx.grid.GridCellAttr()
- attr.SetAlignment(self.Parent.ColAlignements[col], wx.ALIGN_CENTRE)
- grid.SetColAttr(col, attr)
- grid.SetColSize(col, self.Parent.ColSizes[col])
-
- typelist = None
- accesslist = None
for row in range(self.GetNumberRows()):
for col in range(self.GetNumberCols()):
editor = None
renderer = None
readonly = False
- colname = self.GetColLabelValue(col)
+ colname = self.GetColLabelValue(col, False)
if colname == "Qualifier":
editor = wx.grid.GridCellChoiceEditor()
editor.SetParameters(self.Parent.QualifierList)
@@ -2319,11 +2325,11 @@
wx.Dialog.__init__(self, id=ID_ACTIONBLOCKDIALOG,
name='ActionBlockDialog', parent=prnt, pos=wx.Point(376, 223),
size=wx.Size(500, 300), style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER,
- title='Edit action block properties')
+ title=_('Edit action block properties'))
self.SetClientSize(wx.Size(500, 300))
self.staticText1 = wx.StaticText(id=ID_ACTIONBLOCKDIALOGSTATICTEXT1,
- label='Actions:', name='staticText1', parent=self,
+ label=_('Actions:'), name='staticText1', parent=self,
pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)
self.ActionsGrid = wx.grid.Grid(id=ID_ACTIONBLOCKDIALOGVARIABLESGRID,
@@ -2337,14 +2343,14 @@
self.ActionsGrid.EnableScrolling(False, True)
self.ActionsGrid.Bind(wx.grid.EVT_GRID_CELL_CHANGE, self.OnActionsGridCellChange)
- self.AddButton = wx.Button(id=ID_ACTIONBLOCKDIALOGADDBUTTON, label='Add',
+ self.AddButton = wx.Button(id=ID_ACTIONBLOCKDIALOGADDBUTTON, label=_('Add'),
name='AddButton', parent=self, pos=wx.Point(0, 0),
- size=wx.Size(72, 32), style=0)
+ size=wx.DefaultSize, style=0)
self.Bind(wx.EVT_BUTTON, self.OnAddButton, id=ID_ACTIONBLOCKDIALOGADDBUTTON)
- self.DeleteButton = wx.Button(id=ID_ACTIONBLOCKDIALOGDELETEBUTTON, label='Delete',
+ self.DeleteButton = wx.Button(id=ID_ACTIONBLOCKDIALOGDELETEBUTTON, label=_('Delete'),
name='DeleteButton', parent=self, pos=wx.Point(0, 0),
- size=wx.Size(72, 32), style=0)
+ size=wx.DefaultSize, style=0)
self.Bind(wx.EVT_BUTTON, self.OnDeleteButton, id=ID_ACTIONBLOCKDIALOGDELETEBUTTON)
self.UpButton = wx.Button(id=ID_ACTIONBLOCKDIALOGUPBUTTON, label='^',
@@ -2369,14 +2375,23 @@
self._init_ctrls(parent)
self.DefaultValue = {"Qualifier" : "N", "Duration" : "", "Type" : "Action", "Value" : "", "Indicator" : ""}
- self.Table = ActionTable(self, [], ["Qualifier","Duration","Type","Value","Indicator"])
- self.TypeList = "Action,Variable,Inline"
+ self.Table = ActionTable(self, [], GetActionTableColnames())
+ typelist = GetTypeList()
+ self.TypeList = ",".join(map(_,typelist))
+ self.TranslateType = dict([(_(value), value) for value in typelist])
self.ColSizes = [60, 90, 80, 110, 80]
self.ColAlignements = [wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT]
self.ActionsGrid.SetTable(self.Table)
self.ActionsGrid.SetRowLabelSize(0)
+ for col in range(self.Table.GetNumberCols()):
+ attr = wx.grid.GridCellAttr()
+ attr.SetAlignment(self.ColAlignements[col], wx.ALIGN_CENTRE)
+ self.ActionsGrid.SetColAttr(col, attr)
+ self.ActionsGrid.SetColMinimalWidth(col, self.ColSizes[col])
+ self.ActionsGrid.AutoSizeColumn(col, False)
+
self.Table.ResetView(self.ActionsGrid)
def OnOK(self, event):
@@ -2490,27 +2505,27 @@
def OnOK(self, event):
step_name = self.GetSizer().GetItem(1).GetWindow().GetValue()
if step_name == "":
- message = wx.MessageDialog(self, "You must type a name!", "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("You must type a name!"), _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif not TestIdentifier(step_name):
- message = wx.MessageDialog(self, "\"%s\" is not a valid identifier!"%step_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is not a valid identifier!")%step_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif step_name.upper() in IEC_KEYWORDS:
- message = wx.MessageDialog(self, "\"%s\" is a keyword. It can't be used!"%step_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is a keyword. It can't be used!")%step_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif step_name.upper() in self.PouNames:
- message = wx.MessageDialog(self, "A pou with \"%s\" as name exists!"%step_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("A pou with \"%s\" as name exists!")%step_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif step_name.upper() in self.Variables:
- message = wx.MessageDialog(self, "A variable with \"%s\" as name exists!"%step_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("A variable with \"%s\" as name already exists in this pou!")%step_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif step_name.upper() in self.StepNames:
- message = wx.MessageDialog(self, "\"%s\" step already exists!"%step_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" step already exists!")%step_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
else:
@@ -2557,19 +2572,19 @@
def OnOK(self, event):
step_name = self.GetSizer().GetItem(1).GetWindow().GetValue()
if step_name == "":
- message = wx.MessageDialog(self, "You must type a name!", "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("You must type a name!"), _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif not TestIdentifier(step_name):
- message = wx.MessageDialog(self, "\"%s\" is not a valid identifier!"%step_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is not a valid identifier!")%step_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif step_name.upper() in IEC_KEYWORDS:
- message = wx.MessageDialog(self, "\"%s\" is a keyword. It can't be used!"%step_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is a keyword. It can't be used!")%step_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif step_name.upper() in self.PouNames:
- message = wx.MessageDialog(self, "A pou with \"%s\" as name exists!"%step_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("A pou with \"%s\" as name exists!")%step_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
else:
@@ -2579,4 +2594,4 @@
self.PouNames = [pou_name.upper() for pou_name in pou_names]
def GetValue(self):
- return self.GetSizer().GetItem(1).GetWindow().GetValue()
\ No newline at end of file
+ return self.GetSizer().GetItem(1).GetWindow().GetValue()
diff -r e0a6a5952d13 -r 127d524a5f1d GraphicViewer.py
--- a/GraphicViewer.py Mon Jul 06 11:24:37 2009 -0600
+++ b/GraphicViewer.py Thu Aug 20 09:03:31 2009 -0600
@@ -59,9 +59,9 @@
def _init_coll_RangeSizer_Items(self, parent):
# generated method, don't edit
- parent.AddWindow(self.staticbox1, 0, border=5, flag=wx.ALL)
+ parent.AddWindow(self.staticbox1, 0, border=5, flag=wx.ALIGN_CENTER_VERTICAL|wx.ALL)
parent.AddWindow(self.CanvasRange, 0, border=5, flag=wx.ALL)
- parent.AddWindow(self.staticText2, 0, border=5, flag=wx.ALL)
+ parent.AddWindow(self.staticText2, 0, border=5, flag=wx.ALIGN_CENTER_VERTICAL|wx.ALL)
parent.AddWindow(self.CanvasPosition, 0, border=5, flag=wx.GROW|wx.ALL)
parent.AddWindow(self.ResetButton, 0, border=5, flag=wx.ALL)
parent.AddWindow(self.CurrentButton, 0, border=5, flag=wx.ALL)
@@ -103,8 +103,8 @@
self.Canvas.SetYSpec('border')
self.staticbox1 = wx.StaticText(id=ID_GRAPHICVIEWERSTATICTEXT1,
- label='Range:', name='staticText1', parent=self,
- pos=wx.Point(0, 0), size=wx.Size(45, 17), style=0)
+ label=_('Range:'), name='staticText1', parent=self,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.CanvasRange = wx.ComboBox(id=ID_GRAPHICVIEWERCANVASRANGE,
name='CanvasRange', parent=self, pos=wx.Point(0, 0),
@@ -114,8 +114,8 @@
self.Bind(wx.EVT_TEXT_ENTER, self.OnRangeChanged, id=ID_GRAPHICVIEWERCANVASRANGE)
self.staticText2 = wx.StaticText(id=ID_GRAPHICVIEWERSTATICTEXT2,
- label='Position:', name='staticText2', parent=self,
- pos=wx.Point(0, 0), size=wx.Size(60, 17), style=0)
+ label=_('Position:'), name='staticText2', parent=self,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.CanvasPosition = wx.ScrollBar(id=ID_GRAPHICVIEWERCANVASPOSITION,
name='Position', parent=self, pos=wx.Point(0, 0),
@@ -178,7 +178,7 @@
self.VariableGraphic = plot.PolyLine(self.Datas[self.CurrentValue:self.CurrentValue + self.CurrentRange],
legend=var_name, colour=colours[0])
- self.GraphicsObject = plot.PlotGraphics([self.VariableGraphic], "%s Graphics" % var_name, "Tick", "Values")
+ self.GraphicsObject = plot.PlotGraphics([self.VariableGraphic], _("%s Graphics") % var_name, _("Tick"), _("Values"))
datas_length = len(self.Datas)
if datas_length > 1:
start = self.Datas[self.CurrentValue][0]
diff -r e0a6a5952d13 -r 127d524a5f1d LDViewer.py
--- a/LDViewer.py Mon Jul 06 11:24:37 2009 -0600
+++ b/LDViewer.py Thu Aug 20 09:03:31 2009 -0600
@@ -193,8 +193,8 @@
else:
self.RungComments.insert(i, None)
- def loadInstance(self, instance, ids):
- Viewer.loadInstance(self, instance, ids)
+ def loadInstance(self, instance, ids, selection):
+ Viewer.loadInstance(self, instance, ids, selection)
if self.GetDrawingMode() != FREEDRAWING_MODE:
if instance["type"] == "leftPowerRail":
element = self.FindElementById(instance["id"])
@@ -210,7 +210,7 @@
if rung not in rungs:
rungs.append(rung)
if len(rungs) > 1:
- raise "ValueError", "Ladder element with id %d is on more than one rung."%instance["id"]
+ raise ValueError, _("Ladder element with id %d is on more than one rung.")%instance["id"]
element = self.FindElementById(instance["id"])
self.Rungs[rungs[0]].SelectElement(element)
for connector in element.GetConnectors():
@@ -225,7 +225,7 @@
if rung not in rungs:
rungs.append(rung)
if len(rungs) > 1:
- raise "ValueError", "Ladder element with id %d is on more than one rung."%instance["id"]
+ raise ValueError, _("Ladder element with id %d is on more than one rung.")%instance["id"]
element = self.FindElementById(instance["id"])
self.Rungs[rungs[0]].SelectElement(element)
for wire, num in element.GetConnectors()["input"].GetWires():
@@ -358,7 +358,7 @@
else:
element.OnLeftUp(event, dc, self.Scaling)
self.SelectedElement.Refresh()
- wx.CallAfter(self.SetCursor, wx.NullCursor)
+ wx.CallAfter(self.SetCurrentCursor, 0)
event.Skip()
def OnViewerRightUp(self, event):
@@ -378,7 +378,7 @@
self.SelectedElement.SetSelected(True)
self.SelectedElement.OnRightUp(event, dc, self.Scaling)
self.SelectedElement.Refresh()
- wx.CallAfter(self.SetCursor, wx.NullCursor)
+ wx.CallAfter(self.SetCurrentCursor, 0)
event.Skip()
def OnViewerLeftDClick(self, event):
@@ -475,7 +475,7 @@
rung = Graphic_Group(self)
# Create comment
id = self.GetNewId()
- comment = Comment(self, "Commentaire", id)
+ comment = Comment(self, _("Comment"), id)
comment.SetPosition(startx, starty)
comment.SetSize(LD_COMMENT_DEFAULTSIZE[0], LD_COMMENT_DEFAULTSIZE[1])
self.AddComment(comment)
@@ -625,7 +625,7 @@
self.RefreshScrollBars()
self.Refresh(False)
else:
- message = wx.MessageDialog(self, "You must select the wire where a contact should be added!", "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("You must select the wire where a contact should be added!"), _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
@@ -847,16 +847,16 @@
self.RefreshScrollBars()
self.Refresh(False)
else:
- message = wx.MessageDialog(self, "The group of block must be coherent!", "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("The group of block must be coherent!"), _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
else:
- message = wx.MessageDialog(self, "You must select the block or group of blocks around which a branch should be added!", "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("You must select the block or group of blocks around which a branch should be added!"), _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
def AddLadderBlock(self):
- message = wx.MessageDialog(self, "This option isn't available yet!", "Warning", wx.OK|wx.ICON_EXCLAMATION)
+ message = wx.MessageDialog(self, _("This option isn't available yet!"), _("Warning"), wx.OK|wx.ICON_EXCLAMATION)
message.ShowModal()
message.Destroy()
diff -r e0a6a5952d13 -r 127d524a5f1d PLCControler.py
--- a/PLCControler.py Mon Jul 06 11:24:37 2009 -0600
+++ b/PLCControler.py Thu Aug 20 09:03:31 2009 -0600
@@ -26,8 +26,8 @@
from types import StringType, UnicodeType
import cPickle
import os,sys,re
+import datetime
from time import localtime
-from datetime import *
from plcopen import plcopen
from plcopen.structures import *
@@ -77,6 +77,16 @@
ScriptDirectory = os.path.split(os.path.realpath(__file__))[0]
+def GetUneditableNames():
+ _ = lambda x:x
+ return [_("User-defined POUs"), _("Functions"), _("Function Blocks"),
+ _("Programs"), _("Data Types"), _("Transitions"), _("Actions"),
+ _("Configurations"), _("Resources"), _("Properties")]
+UNEDITABLE_NAMES = GetUneditableNames()
+[USER_DEFINED_POUS, FUNCTIONS, FUNCTION_BLOCKS, PROGRAMS,
+ DATA_TYPES, TRANSITIONS, ACTIONS, CONFIGURATIONS,
+ RESOURCES, PROPERTIES] = UNEDITABLE_NAMES
+
#-------------------------------------------------------------------------------
# Undo Buffer for PLCOpenEditor
#-------------------------------------------------------------------------------
@@ -211,7 +221,7 @@
def CreateNewProject(self, properties):
# Create the project
self.Project = plcopen.project()
- properties["creationDateTime"] = datetime(*localtime()[:6])
+ properties["creationDateTime"] = datetime.datetime(*localtime()[:6])
self.Project.setfileHeader(properties)
self.Project.setcontentHeader(properties)
self.SetFilePath("")
@@ -280,7 +290,7 @@
self.FilePath = filepath
if filepath == "":
self.LastNewIndex += 1
- self.FileName = "Unnamed%d"%self.LastNewIndex
+ self.FileName = _("Unnamed%d")%self.LastNewIndex
else:
self.FileName = os.path.splitext(os.path.basename(filepath))[0]
@@ -309,13 +319,13 @@
project = self.GetProject(debug)
if project is not None:
infos = {"name": project.getname(), "type": ITEM_PROJECT}
- datatypes = {"name": "Data Types", "type": ITEM_DATATYPES, "values":[]}
+ datatypes = {"name": DATA_TYPES, "type": ITEM_DATATYPES, "values":[]}
for datatype in project.getdataTypes():
datatypes["values"].append({"name": datatype.getname(), "type": ITEM_DATATYPE,
"tagname": self.ComputeDataTypeName(datatype.getname()), "values": []})
- pou_types = {"function": {"name": "Functions", "type": ITEM_FUNCTION, "values":[]},
- "functionBlock": {"name": "Function Blocks", "type": ITEM_FUNCTIONBLOCK, "values":[]},
- "program": {"name": "Programs", "type": ITEM_PROGRAM, "values":[]}}
+ pou_types = {"function": {"name": FUNCTIONS, "type": ITEM_FUNCTION, "values":[]},
+ "functionBlock": {"name": FUNCTION_BLOCKS, "type": ITEM_FUNCTIONBLOCK, "values":[]},
+ "program": {"name": PROGRAMS, "type": ITEM_PROGRAM, "values":[]}}
for pou in project.getpous():
pou_type = pou.getpouType()
pou_infos = {"name": pou.getname(), "type": ITEM_POU,
@@ -327,23 +337,23 @@
transitions.append({"name": transition.getname(), "type": ITEM_TRANSITION,
"tagname": self.ComputePouTransitionName(pou.getname(), transition.getname()),
"values": []})
- pou_values.append({"name": "Transitions", "type": ITEM_TRANSITIONS, "values": transitions})
+ pou_values.append({"name": TRANSITIONS, "type": ITEM_TRANSITIONS, "values": transitions})
actions = []
for action in pou.getactionList():
actions.append({"name": action.getname(), "type": ITEM_ACTION,
"tagname": self.ComputePouActionName(pou.getname(), action.getname()),
"values": []})
- pou_values.append({"name": "Actions", "type": ITEM_ACTIONS, "values": actions})
+ pou_values.append({"name": ACTIONS, "type": ITEM_ACTIONS, "values": actions})
if pou_type in pou_types:
pou_infos["values"] = pou_values
pou_types[pou_type]["values"].append(pou_infos)
- configurations = {"name": "Configurations", "type": ITEM_CONFIGURATIONS, "values": []}
+ configurations = {"name": CONFIGURATIONS, "type": ITEM_CONFIGURATIONS, "values": []}
for config in project.getconfigurations():
config_name = config.getname()
config_infos = {"name": config_name, "type": ITEM_CONFIGURATION,
"tagname": self.ComputeConfigurationName(config.getname()),
"values": []}
- resources = {"name": "Resources", "type": ITEM_RESOURCES, "values": []}
+ resources = {"name": RESOURCES, "type": ITEM_RESOURCES, "values": []}
for resource in config.getresource():
resource_name = resource.getname()
resource_infos = {"name": resource_name, "type": ITEM_RESOURCE,
@@ -352,7 +362,7 @@
resources["values"].append(resource_infos)
config_infos["values"] = [resources]
configurations["values"].append(config_infos)
- infos["values"] = [{"name": "Properties", "type": ITEM_PROPERTIES, "values": []},
+ infos["values"] = [{"name": PROPERTIES, "type": ITEM_PROPERTIES, "values": []},
datatypes, pou_types["function"], pou_types["functionBlock"],
pou_types["program"], configurations]
return infos
@@ -369,11 +379,11 @@
resource_infos = {"name" : resource.getname(), "type": ITEM_RESOURCE, "values": []}
for task in resource.gettask():
for pou in task.getpouInstance():
- instance_infos = self.GetPouTopology(pou.getname(), pou.gettype(), debug=debug)
+ instance_infos = self.GetPouTopology(pou.getname(), pou.gettypeName(), debug=debug)
if instance_infos is not None:
resource_infos["values"].append(instance_infos)
for pou in resource.getpouInstance():
- instance_infos = self.GetPouTopology(pou.getname(), pou.gettype(), debug=debug)
+ instance_infos = self.GetPouTopology(pou.getname(), pou.gettypeName(), debug=debug)
if instance_infos is not None:
resource_infos["values"].append(instance_infos)
for varlist in resource.getglobalVars():
@@ -1165,7 +1175,7 @@
blocktypes = [category for category in BlockTypes + self.PluginTypes]
project = self.GetProject(debug)
if project is not None:
- blocktypes.append({"name" : "User-defined POUs", "list": project.GetCustomBlockTypes(name, type == "function" or words[0] == "T")})
+ blocktypes.append({"name" : USER_DEFINED_POUS, "list": project.GetCustomBlockTypes(name, type == "function" or words[0] == "T")})
return blocktypes
# Return Function Block types checking for recursion
@@ -1580,6 +1590,148 @@
return self.GetProjectPouVariables(words[1], debug)
return []
+ def GetEditedElementCopy(self, tagname, debug = False):
+ element = self.GetEditedElement(tagname, debug)
+ if element is not None:
+ name = element.__class__.__name__
+ return element.generateXMLText(name.split("_")[-1], 0)
+ return ""
+
+ def GetEditedElementInstancesCopy(self, tagname, blocks_id = None, wires = None, debug = False):
+ element = self.GetEditedElement(tagname, debug)
+ text = ""
+ if element is not None:
+ wires = dict([(wire, True) for wire in wires if wire[0] in blocks_id and wire[1] in blocks_id])
+ for id in blocks_id:
+ instance = element.getinstance(id)
+ if instance is not None:
+ instance_copy = self.Copy(instance)
+ instance_copy.filterConnections(wires)
+ name = instance_copy.__class__.__name__
+ text += instance_copy.generateXMLText(name.split("_")[-1], 0)
+ return text
+
+ def GenerateNewName(self, tagname, name, format, exclude={}, debug=False):
+ names = exclude.copy()
+ names.update(dict([(varname.upper(), True) for varname in self.GetEditedElementVariables(tagname, debug)]))
+ element = self.GetEditedElement(tagname, debug)
+ if element is not None:
+ for instance in element.getinstances():
+ if isinstance(instance, (plcopen.sfcObjects_step, plcopen.commonObjects_connector, plcopen.commonObjects_continuation)):
+ names[instance.getname()] = True
+ i = 1
+ while names.get(name.upper(), False):
+ name = (format%i)
+ i += 1
+ return name
+
+ CheckPasteCompatibility = {"SFC": lambda name: True,
+ "LD": lambda name: not name.startswith("sfcObjects"),
+ "FBD": lambda name: name.startswith("fbdObjects") or name.startswith("commonObjects")}
+
+ def PasteEditedElementInstances(self, tagname, text, new_pos, middle=False, debug=False):
+ element = self.GetEditedElement(tagname, debug)
+ element_name, element_type = self.GetEditedElementType(tagname, debug)
+ if element is not None:
+ bodytype = element.getbodyType()
+
+ # Get edited element type scaling
+ scaling = None
+ project = self.GetProject(debug)
+ if project is not None:
+ properties = project.getcontentHeader()
+ scaling = properties["scaling"][bodytype]
+
+ # Get ids already by all the instances in edited element
+ used_id = dict([(instance.getlocalId(), True) for instance in element.getinstances()])
+ new_id = {}
+
+ text = "%s"%text
+
+ try:
+ tree = minidom.parseString(text)
+ except:
+ return _("Invalid plcopen element(s)!!!")
+ instances = []
+ exclude = {}
+ for root in tree.childNodes:
+ if root.nodeType == tree.ELEMENT_NODE and root.nodeName == "paste":
+ for child in root.childNodes:
+ if child.nodeType == tree.ELEMENT_NODE:
+ classname = plcopen.ElementNameToClass[child.nodeName]
+ if not self.CheckPasteCompatibility[bodytype](classname):
+ return _("\"%s\" element can't be paste here!!!")%child.nodeName
+ classobj = getattr(plcopen, classname, None)
+ if classobj is not None:
+ instance = classobj()
+ instance.loadXMLTree(child)
+ if child.nodeName == "block":
+ blockname = instance.getinstanceName()
+ if blockname is not None:
+ blocktype = instance.gettypeName()
+ if element_type == "function":
+ return _("FunctionBlock \"%s\" can't be paste in a Function!!!")%blocktype
+ blockname = self.GenerateNewName(tagname, blockname, "Block%d", debug=debug)
+ exclude[blockname] = True
+ instance.setinstanceName(blockname)
+ self.AddEditedElementPouVar(tagname, blocktype, blockname)
+ elif child.nodeName == "step":
+ stepname = self.GenerateNewName(tagname, instance.getname(), "Step%d", exclude, debug)
+ exclude[stepname] = True
+ instance.setname(stepname)
+ localid = instance.getlocalId()
+ if not used_id.has_key(localid):
+ new_id[localid] = True
+ instances.append((child.nodeName, instance))
+
+ if len(instances) == 0:
+ return _("Invalid plcopen element(s)!!!")
+
+ idx = 1
+ translate_id = {}
+ bbox = plcopen.rect()
+ for name, instance in instances:
+ localId = instance.getlocalId()
+ bbox.union(instance.getBoundingBox())
+ if used_id.has_key(localId):
+ while used_id.has_key(idx) or new_id.has_key(idx):
+ idx += 1
+ new_id[idx] = True
+ instance.setlocalId(idx)
+ translate_id[localId] = idx
+
+ x, y, width, height = bbox.bounding_box()
+ if middle:
+ new_pos[0] -= width / 2
+ new_pos[1] -= height / 2
+ else:
+ new_pos = map(lambda x: x + 30, new_pos)
+ if scaling[0] != 0 and scaling[1] != 0:
+ min_pos = map(lambda x: 30 / x, scaling)
+ minx = round(min_pos[0])
+ if int(min_pos[0]) == round(min_pos[0]):
+ minx += 1
+ miny = round(min_pos[1])
+ if int(min_pos[1]) == round(min_pos[1]):
+ miny += 1
+ minx *= scaling[0]
+ miny *= scaling[1]
+ new_pos = (max(minx, round(new_pos[0] / scaling[0]) * scaling[0]),
+ max(miny, round(new_pos[1] / scaling[1]) * scaling[1]))
+ else:
+ new_pos = (max(30, new_pos[0]), max(30, new_pos[1]))
+ diff = (new_pos[0] - x, new_pos[1] - y)
+
+ connections = {}
+ for name, instance in instances:
+ connections.update(instance.updateConnectionsId(translate_id))
+ if getattr(instance, "setexecutionOrderId", None) is not None:
+ instance.setexecutionOrderId(0)
+ instance.translate(*diff)
+ element.addinstance(name, instance)
+
+ return new_id, connections
+
# Return the current pou editing informations
def GetEditedElementInstanceInfos(self, tagname, id = None, exclude = [], debug = False):
infos = {}
@@ -1592,282 +1744,10 @@
else:
instance = element.getrandomInstance(exclude)
if instance is not None:
- if id is not None:
- infos["id"] = id
- else:
- infos["id"] = instance.getlocalId()
- infos["x"] = instance.getx()
- infos["y"] = instance.gety()
- infos["height"] = instance.getheight()
- infos["width"] = instance.getwidth()
- if isinstance(instance, plcopen.fbdObjects_block):
- infos["name"] = instance.getinstanceName()
- infos["type"] = instance.gettypeName()
- executionOrder = instance.getexecutionOrderId()
- if executionOrder is not None:
- infos["executionOrder"] = executionOrder
- else:
- infos["executionOrder"] = 0
- infos["connectors"] = {"inputs":[],"outputs":[]}
- for variable in instance.inputVariables.getvariable():
- connector = {}
- connector["name"] = variable.getformalParameter()
- connector["position"] = variable.connectionPointIn.getrelPositionXY()
- connector["negated"] = variable.getnegated()
- connector["edge"] = variable.getedge()
- connector["links"] = []
- connections = variable.connectionPointIn.getconnections()
- if connections:
- for link in connections:
- dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
- connector["links"].append(dic)
- infos["connectors"]["inputs"].append(connector)
- for variable in instance.outputVariables.getvariable():
- connector = {}
- connector["name"] = variable.getformalParameter()
- connector["position"] = variable.connectionPointOut.getrelPositionXY()
- connector["negated"] = variable.getnegated()
- connector["edge"] = variable.getedge()
- infos["connectors"]["outputs"].append(connector)
- elif isinstance(instance, plcopen.fbdObjects_inVariable):
- infos["name"] = instance.getexpression()
- infos["value_type"] = self.GetEditedElementVarValueType(tagname, infos["name"], debug)
- infos["type"] = "input"
- executionOrder = instance.getexecutionOrderId()
- if executionOrder is not None:
- infos["executionOrder"] = executionOrder
- else:
- infos["executionOrder"] = 0
- infos["connector"] = {}
- infos["connector"]["position"] = instance.connectionPointOut.getrelPositionXY()
- infos["connector"]["negated"] = instance.getnegated()
- infos["connector"]["edge"] = instance.getedge()
- elif isinstance(instance, plcopen.fbdObjects_outVariable):
- infos["name"] = instance.getexpression()
- infos["value_type"] = self.GetEditedElementVarValueType(tagname, infos["name"], debug)
- infos["type"] = "output"
- executionOrder = instance.getexecutionOrderId()
- if executionOrder is not None:
- infos["executionOrder"] = executionOrder
- else:
- infos["executionOrder"] = 0
- infos["connector"] = {}
- infos["connector"]["position"] = instance.connectionPointIn.getrelPositionXY()
- infos["connector"]["negated"] = instance.getnegated()
- infos["connector"]["edge"] = instance.getedge()
- infos["connector"]["links"] = []
- connections = instance.connectionPointIn.getconnections()
- if connections:
- for link in connections:
- dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
- infos["connector"]["links"].append(dic)
- elif isinstance(instance, plcopen.fbdObjects_inOutVariable):
- infos["name"] = instance.getexpression()
- infos["value_type"] = self.GetEditedElementVarValueType(tagname, infos["name"], debug)
- infos["type"] = "inout"
- executionOrder = instance.getexecutionOrderId()
- if executionOrder is not None:
- infos["executionOrder"] = executionOrder
- else:
- infos["executionOrder"] = 0
- infos["connectors"] = {"input":{},"output":{}}
- infos["connectors"]["output"]["position"] = instance.connectionPointOut.getrelPositionXY()
- infos["connectors"]["output"]["negated"] = instance.getnegatedOut()
- infos["connectors"]["output"]["edge"] = instance.getedgeOut()
- infos["connectors"]["input"]["position"] = instance.connectionPointIn.getrelPositionXY()
- infos["connectors"]["input"]["negated"] = instance.getnegatedIn()
- infos["connectors"]["input"]["edge"] = instance.getedgeIn()
- infos["connectors"]["input"]["links"] = []
- connections = instance.connectionPointIn.getconnections()
- if connections:
- for link in connections:
- dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
- infos["connectors"]["input"]["links"].append(dic)
- elif isinstance(instance, plcopen.commonObjects_continuation):
- infos["name"] = instance.getname()
- infos["type"] = "continuation"
- infos["connector"] = {}
- infos["connector"]["position"] = instance.connectionPointOut.getrelPositionXY()
- elif isinstance(instance, plcopen.commonObjects_connector):
- infos["name"] = instance.getname()
- infos["type"] = "connection"
- infos["connector"] = {}
- infos["connector"]["position"] = instance.connectionPointIn.getrelPositionXY()
- infos["connector"]["links"] = []
- connections = instance.connectionPointIn.getconnections()
- if connections:
- for link in connections:
- dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
- infos["connector"]["links"].append(dic)
- elif isinstance(instance, plcopen.commonObjects_comment):
- infos["type"] = "comment"
- infos["content"] = instance.getcontentText()
- elif isinstance(instance, plcopen.ldObjects_leftPowerRail):
- infos["type"] = "leftPowerRail"
- infos["connectors"] = []
- for connection in instance.getconnectionPointOut():
- connector = {}
- connector["position"] = connection.getrelPositionXY()
- infos["connectors"].append(connector)
- elif isinstance(instance, plcopen.ldObjects_rightPowerRail):
- infos["type"] = "rightPowerRail"
- infos["connectors"] = []
- for connection in instance.getconnectionPointIn():
- connector = {}
- connector["position"] = connection.getrelPositionXY()
- connector["links"] = []
- connections = connection.getconnections()
- if connections:
- for link in connection.getconnections():
- dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
- connector["links"].append(dic)
- infos["connectors"].append(connector)
- elif isinstance(instance, plcopen.ldObjects_contact):
- infos["name"] = instance.getvariable()
- infos["type"] = "contact"
- executionOrder = instance.getexecutionOrderId()
- if executionOrder is not None:
- infos["executionOrder"] = executionOrder
- else:
- infos["executionOrder"] = 0
- infos["negated"] = instance.getnegated()
- infos["edge"] = instance.getedge()
- infos["connectors"] = {"input":{},"output":{}}
- infos["connectors"]["input"]["position"] = instance.connectionPointIn.getrelPositionXY()
- infos["connectors"]["input"]["links"] = []
- connections = instance.connectionPointIn.getconnections()
- if connections:
- for link in connections:
- dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
- infos["connectors"]["input"]["links"].append(dic)
- infos["connectors"]["output"]["position"] = instance.connectionPointOut.getrelPositionXY()
- elif isinstance(instance, plcopen.ldObjects_coil):
- infos["name"] = instance.getvariable()
- infos["type"] = "coil"
- executionOrder = instance.getexecutionOrderId()
- if executionOrder is not None:
- infos["executionOrder"] = executionOrder
- else:
- infos["executionOrder"] = 0
- infos["negated"] = instance.getnegated()
- infos["edge"] = instance.getedge()
- infos["storage"] = instance.getstorage()
- infos["connectors"] = {"input":{},"output":{}}
- infos["connectors"]["input"]["position"] = instance.connectionPointIn.getrelPositionXY()
- infos["connectors"]["input"]["links"] = []
- connections = instance.connectionPointIn.getconnections()
- if connections:
- for link in connections:
- dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
- infos["connectors"]["input"]["links"].append(dic)
- infos["connectors"]["output"]["position"] = instance.connectionPointOut.getrelPositionXY()
- elif isinstance(instance, plcopen.sfcObjects_step):
- infos["name"] = instance.getname()
- infos["type"] = "step"
- infos["initial"] = instance.getinitialStep()
- infos["connectors"] = {}
- if instance.connectionPointIn:
- infos["connectors"]["input"] = {}
- infos["connectors"]["input"]["position"] = instance.connectionPointIn.getrelPositionXY()
- infos["connectors"]["input"]["links"] = []
- connections = instance.connectionPointIn.getconnections()
- if connections:
- for link in connections:
- dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
- infos["connectors"]["input"]["links"].append(dic)
- if instance.connectionPointOut:
- infos["connectors"]["output"] = {"position" : instance.connectionPointOut.getrelPositionXY()}
- if instance.connectionPointOutAction:
- infos["connectors"]["action"] = {"position" : instance.connectionPointOutAction.getrelPositionXY()}
- elif isinstance(instance, plcopen.sfcObjects_transition):
- infos["type"] = "transition"
- condition = instance.getconditionContent()
- priority = instance.getpriority()
- if priority == None:
- infos["priority"] = 0
- else:
- infos["priority"] = priority
- infos["condition_type"] = condition["type"]
- infos["connectors"] = {"input":{},"output":{}}
- infos["connectors"]["input"]["position"] = instance.connectionPointIn.getrelPositionXY()
- infos["connectors"]["input"]["links"] = []
- connections = instance.connectionPointIn.getconnections()
- if connections:
- for link in connections:
- dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
- infos["connectors"]["input"]["links"].append(dic)
- infos["connectors"]["output"]["position"] = instance.connectionPointOut.getrelPositionXY()
- if infos["condition_type"] == "connection":
- infos["connectors"]["connection"] = {}
- infos["connectors"]["connection"]["links"] = []
- connections = instance.getconnections()
- if connections:
- for link in connections:
- dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
- infos["connectors"]["connection"]["links"].append(dic)
- infos["condition"] = None
- else:
- infos["condition"] = condition["value"]
- elif isinstance(instance, (plcopen.sfcObjects_selectionDivergence, plcopen.sfcObjects_simultaneousDivergence)):
- if isinstance(instance, plcopen.sfcObjects_selectionDivergence):
- infos["type"] = "selectionDivergence"
- else:
- infos["type"] = "simultaneousDivergence"
- infos["connectors"] = {"inputs":[],"outputs":[]}
- connector = {}
- connector["position"] = instance.connectionPointIn.getrelPositionXY()
- connector["links"] = []
- connections = instance.connectionPointIn.getconnections()
- if connections:
- for link in connections:
- dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
- connector["links"].append(dic)
- infos["connectors"]["inputs"].append(connector)
- for sequence in instance.getconnectionPointOut():
- connector = {}
- connector["position"] = sequence.getrelPositionXY()
- infos["connectors"]["outputs"].append(connector)
- elif isinstance(instance, (plcopen.sfcObjects_selectionConvergence, plcopen.sfcObjects_simultaneousConvergence)):
- if isinstance(instance, plcopen.sfcObjects_selectionConvergence):
- infos["type"] = "selectionConvergence"
- else:
- infos["type"] = "simultaneousConvergence"
- infos["connectors"] = {"inputs":[],"outputs":[]}
- for sequence in instance.getconnectionPointIn():
- connector = {}
- connector["position"] = sequence.getrelPositionXY()
- connector["links"] = []
- connections = sequence.getconnections()
- if connections:
- for link in connections:
- dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
- connector["links"].append(dic)
- infos["connectors"]["inputs"].append(connector)
- connector = {}
- connector["position"] = instance.connectionPointOut.getrelPositionXY()
- infos["connectors"]["outputs"].append(connector)
- elif isinstance(instance, plcopen.sfcObjects_jumpStep):
- infos["type"] = "jump"
- infos["target"] = instance.gettargetName()
- infos["connector"] = {}
- infos["connector"]["position"] = instance.connectionPointIn.getrelPositionXY()
- infos["connector"]["links"] = []
- connections = instance.connectionPointIn.getconnections()
- if connections:
- for link in connections:
- dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
- infos["connector"]["links"].append(dic)
- elif isinstance(instance, plcopen.commonObjects_actionBlock):
- infos["type"] = "actionBlock"
- infos["actions"] = instance.getactions()
- infos["connector"] = {}
- infos["connector"]["position"] = instance.connectionPointIn.getrelPositionXY()
- infos["connector"]["links"] = []
- connections = instance.connectionPointIn.getconnections()
- if connections:
- for link in connections:
- dic = {"refLocalId":link.getrefLocalId(),"points":link.getpoints(),"formalParameter":link.getformalParameter()}
- infos["connector"]["links"].append(dic)
+ infos = instance.getinfos()
+ if infos["type"] in ["input", "output", "inout"]:
+ var_type = self.GetEditedElementVarValueType(tagname, infos["specific_values"]["name"], debug)
+ infos["specific_values"]["value_type"] = var_type
return infos
return None
@@ -2067,39 +1947,29 @@
elif param == "y":
variable.sety(value)
elif param == "connectors":
- if isinstance(variable, plcopen.fbdObjects_inVariable):
- if value["output"].IsNegated():
- variable.setnegated(True)
- if value["output"].GetEdge() != "none":
- variable.setedge(value["output"].GetEdge())
- position = value["output"].GetRelPosition()
+ if len(value["outputs"]) > 0:
+ output = value["outputs"][0]
+ if len(value["inputs"]) > 0:
+ variable.setnegatedOut(output.IsNegated())
+ variable.setedgeOut(output.GetEdge())
+ else:
+ variable.setnegated(output.IsNegated())
+ variable.setedge(output.GetEdge())
+ position = output.GetRelPosition()
variable.addconnectionPointOut()
variable.connectionPointOut.setrelPositionXY(position.x, position.y)
- elif isinstance(variable, plcopen.fbdObjects_outVariable):
- if value["input"].IsNegated():
- variable.setnegated(True)
- if value["input"].GetEdge() != "none":
- variable.setedge(value["input"].GetEdge())
- position = value["input"].GetRelPosition()
+ if len(value["inputs"]) > 0:
+ input = value["inputs"][0]
+ if len(value["outputs"]) > 0:
+ variable.setnegatedIn(input.IsNegated())
+ variable.setedgeIn(input.GetEdge())
+ else:
+ variable.setnegated(input.IsNegated())
+ variable.setedge(input.GetEdge())
+ position = input.GetRelPosition()
variable.addconnectionPointIn()
variable.connectionPointIn.setrelPositionXY(position.x, position.y)
- self.SetConnectionWires(variable.connectionPointIn, value["input"])
- elif isinstance(variable, plcopen.fbdObjects_inOutVariable):
- if value["input"].IsNegated():
- variable.setnegatedIn(True)
- if value["input"].GetEdge() != "none":
- variable.setedgeIn(value["input"].GetEdge())
- if value["output"].IsNegated():
- variable.setnegatedOut(True)
- if value["output"].GetEdge() != "none":
- variable.setedgeOut(value["output"].GetEdge())
- position = value["output"].GetRelPosition()
- variable.addconnectionPointOut()
- variable.connectionPointOut.setrelPositionXY(position.x, position.y)
- position = value["input"].GetRelPosition()
- variable.addconnectionPointIn()
- variable.connectionPointIn.setrelPositionXY(position.x, position.y)
- self.SetConnectionWires(variable.connectionPointIn, value["input"])
+ self.SetConnectionWires(variable.connectionPointIn, input)
def AddEditedElementConnection(self, tagname, id, type):
element = self.GetEditedElement(tagname)
@@ -2193,14 +2063,14 @@
elif param == "connectors":
if isinstance(powerrail, plcopen.ldObjects_leftPowerRail):
powerrail.setconnectionPointOut([])
- for connector in value:
+ for connector in value["outputs"]:
position = connector.GetRelPosition()
connection = plcopen.leftPowerRail_connectionPointOut()
connection.setrelPositionXY(position.x, position.y)
powerrail.connectionPointOut.append(connection)
elif isinstance(powerrail, plcopen.ldObjects_rightPowerRail):
powerrail.setconnectionPointIn([])
- for connector in value:
+ for connector in value["inputs"]:
position = connector.GetRelPosition()
connection = plcopen.connectionPointIn()
connection.setrelPositionXY(position.x, position.y)
@@ -2245,12 +2115,12 @@
elif param == "y":
contact.sety(value)
elif param == "connectors":
- input_connector = value["input"]
+ input_connector = value["inputs"][0]
position = input_connector.GetRelPosition()
contact.addconnectionPointIn()
contact.connectionPointIn.setrelPositionXY(position.x, position.y)
self.SetConnectionWires(contact.connectionPointIn, input_connector)
- output_connector = value["output"]
+ output_connector = value["outputs"][0]
position = output_connector.GetRelPosition()
contact.addconnectionPointOut()
contact.connectionPointOut.setrelPositionXY(position.x, position.y)
@@ -2305,12 +2175,12 @@
elif param == "y":
coil.sety(value)
elif param == "connectors":
- input_connector = value["input"]
+ input_connector = value["inputs"][0]
position = input_connector.GetRelPosition()
coil.addconnectionPointIn()
coil.connectionPointIn.setrelPositionXY(position.x, position.y)
self.SetConnectionWires(coil.connectionPointIn, input_connector)
- output_connector = value["output"]
+ output_connector = value["outputs"][0]
position = output_connector.GetRelPosition()
coil.addconnectionPointOut()
coil.connectionPointOut.setrelPositionXY(position.x, position.y)
@@ -2342,24 +2212,24 @@
elif param == "y":
step.sety(value)
elif param == "connectors":
- input_connector = value["input"]
- if input_connector:
+ if len(value["inputs"]) > 0:
+ input_connector = value["inputs"][0]
position = input_connector.GetRelPosition()
step.addconnectionPointIn()
step.connectionPointIn.setrelPositionXY(position.x, position.y)
self.SetConnectionWires(step.connectionPointIn, input_connector)
else:
step.deleteconnectionPointIn()
- output_connector = value["output"]
- if output_connector:
+ if len(value["outputs"]) > 0:
+ output_connector = value["outputs"][0]
position = output_connector.GetRelPosition()
step.addconnectionPointOut()
step.connectionPointOut.setrelPositionXY(position.x, position.y)
else:
step.deleteconnectionPointOut()
- action_connector = value["action"]
- if action_connector:
- position = action_connector.GetRelPosition()
+ elif param == "action":
+ if value:
+ position = value.GetRelPosition()
step.addconnectionPointOutAction()
step.connectionPointOutAction.setrelPositionXY(position.x, position.y)
else:
@@ -2395,19 +2265,18 @@
else:
transition.setpriority(None)
elif param == "connectors":
- input_connector = value["input"]
+ input_connector = value["inputs"][0]
position = input_connector.GetRelPosition()
transition.addconnectionPointIn()
transition.connectionPointIn.setrelPositionXY(position.x, position.y)
self.SetConnectionWires(transition.connectionPointIn, input_connector)
- output_connector = value["output"]
+ output_connector = value["outputs"][0]
position = output_connector.GetRelPosition()
transition.addconnectionPointOut()
transition.connectionPointOut.setrelPositionXY(position.x, position.y)
- if infos.get("type", None) == "connection":
- transition.setconditionContent("connection", None)
- connection_connector = value["connection"]
- self.SetConnectionWires(transition, connection_connector)
+ elif infos.get("type", None) == "connection" and param == "connection" and value:
+ transition.setconditionContent("connection", None)
+ self.SetConnectionWires(transition.condition.content["value"], value)
def AddEditedElementDivergence(self, tagname, id, type):
element = self.GetEditedElement(tagname)
@@ -2567,17 +2436,19 @@
new_task.setname(task["Name"])
if task["Single"] != "":
new_task.setsingle(task["Single"])
- result = duration_model.match(task["Interval"]).groups()
- if reduce(lambda x, y: x or y != None, result):
- values = []
- for value in result[:-1]:
- if value != None:
- values.append(int(value))
- else:
- values.append(0)
- if result[-1] is not None:
- values.append(int(float(result[-1]) * 1000))
- new_task.setinterval(time(*values))
+## result = duration_model.match(task["Interval"]).groups()
+## if reduce(lambda x, y: x or y != None, result):
+## values = []
+## for value in result[:-1]:
+## if value != None:
+## values.append(int(value))
+## else:
+## values.append(0)
+## if result[-1] is not None:
+## values.append(int(float(result[-1]) * 1000))
+## new_task.setinterval(datetime.time(*values))
+ if task["Interval"] != "":
+ new_task.setinterval(task["Interval"])
new_task.setpriority(int(task["Priority"]))
if task["Name"] != "":
task_list[task["Name"]] = new_task
@@ -2585,7 +2456,7 @@
for instance in instances:
new_instance = plcopen.pouInstance()
new_instance.setname(instance["Name"])
- new_instance.settype(instance["Type"])
+ new_instance.settypeName(instance["Type"])
if instance["Task"] != "":
task_list[instance["Task"]].appendpouInstance(new_instance)
else:
@@ -2608,19 +2479,20 @@
new_task["Single"] = ""
interval = task.getinterval()
if interval:
- text = ""
- if interval.hour != 0:
- text += "%dh"%interval.hour
- if interval.minute != 0:
- text += "%dm"%interval.minute
- if interval.second != 0:
- text += "%ds"%interval.second
- if interval.microsecond != 0:
- if interval.microsecond % 1000 != 0:
- text += "%.3fms"%(float(interval.microsecond) / 1000)
- else:
- text += "%dms"%(interval.microsecond / 1000)
- new_task["Interval"] = text
+## text = ""
+## if interval.hour != 0:
+## text += "%dh"%interval.hour
+## if interval.minute != 0:
+## text += "%dm"%interval.minute
+## if interval.second != 0:
+## text += "%ds"%interval.second
+## if interval.microsecond != 0:
+## if interval.microsecond % 1000 != 0:
+## text += "%.3fms"%(float(interval.microsecond) / 1000)
+## else:
+## text += "%dms"%(interval.microsecond / 1000)
+## new_task["Interval"] = text
+ new_task["Interval"] = interval
else:
new_task["Interval"] = ""
new_task["Priority"] = str(task.getpriority())
@@ -2628,13 +2500,13 @@
for instance in task.getpouInstance():
new_instance = {}
new_instance["Name"] = instance.getname()
- new_instance["Type"] = instance.gettype()
+ new_instance["Type"] = instance.gettypeName()
new_instance["Task"] = task.getname()
instances_data.append(new_instance)
for instance in instances:
new_instance = {}
new_instance["Name"] = instance.getname()
- new_instance["Type"] = instance.gettype()
+ new_instance["Type"] = instance.gettypeName()
new_instance["Task"] = ""
instances_data.append(new_instance)
return tasks_data, instances_data
@@ -2660,14 +2532,14 @@
self.Buffering = False
self.CurrentElementEditing = None
return None
- return "No PLC project found"
+ return _("No PLC project found")
def SaveXMLFile(self, filepath = None):
if not filepath and self.FilePath == "":
return False
else:
contentheader = self.Project.getcontentHeader()
- contentheader["modificationDateTime"] = datetime(*localtime()[:6])
+ contentheader["modificationDateTime"] = datetime.datetime(*localtime()[:6])
self.Project.setcontentHeader(contentheader)
text = "\n"
diff -r e0a6a5952d13 -r 127d524a5f1d PLCGenerator.py
--- a/PLCGenerator.py Mon Jul 06 11:24:37 2009 -0600
+++ b/PLCGenerator.py Thu Aug 20 09:03:31 2009 -0600
@@ -143,9 +143,9 @@
max_value = basetype_content["value"].range.getupper()
datatype_def += [(basetype_name, (tagname, "base")),
(" (", ()),
- ("%d"%min_value, (tagname, "lower")),
+ ("%s"%min_value, (tagname, "lower")),
("..", ()),
- ("%d"%max_value, (tagname, "upper")),
+ ("%s"%max_value, (tagname, "upper")),
(")",())]
# Data type is an enumerated type
elif basetype_content["name"] == "enum":
@@ -167,9 +167,9 @@
# Array derived directly from an elementary type
else:
basetype_name = base_type["name"]
- dimensions = [[("%d"%dimension.getlower(), (tagname, "range", i, "lower")),
+ dimensions = [[("%s"%dimension.getlower(), (tagname, "range", i, "lower")),
("..", ()),
- ("%d"%dimension.getupper(), (tagname, "range", i, "upper"))]
+ ("%s"%dimension.getupper(), (tagname, "range", i, "upper"))]
for i, dimension in enumerate(basetype_content["value"].getdimension())]
datatype_def += [("ARRAY [", ())]
datatype_def += JoinList([(",", ())], dimensions)
@@ -229,7 +229,7 @@
program = pou_program.GenerateProgram(pou)
self.Program += program
else:
- raise PLCGenException, "Undefined pou type \"%s\""%pou_type
+ raise PLCGenException, _("Undefined pou type \"%s\"")%pou_type
# Generate a POU defined and used in text
def GeneratePouProgramInText(self, text):
@@ -356,16 +356,19 @@
# Interval argument if exists
interval = task.getinterval()
if interval:
- resrce += [("INTERVAL := t#", ())]
- if interval.hour != 0:
- resrce += [("%dh"%interval.hour, (tagname, "task", task_number, "interval", "hour"))]
- if interval.minute != 0:
- resrce += [("%dm"%interval.minute, (tagname, "task", task_number, "interval", "minute"))]
- if interval.second != 0:
- resrce += [("%ds"%interval.second, (tagname, "task", task_number, "interval", "second"))]
- if interval.microsecond != 0:
- resrce += [("%dms"%(interval.microsecond / 1000), (tagname, "task", task_number, "interval", "millisecond"))]
- resrce += [(",", ())]
+ resrce += [("INTERVAL := ", ()),
+ (interval, (tagname, "task", task_number, "interval")),
+ (",", ())]
+## resrce += [("INTERVAL := t#", ())]
+## if interval.hour != 0:
+## resrce += [("%dh"%interval.hour, (tagname, "task", task_number, "interval", "hour"))]
+## if interval.minute != 0:
+## resrce += [("%dm"%interval.minute, (tagname, "task", task_number, "interval", "minute"))]
+## if interval.second != 0:
+## resrce += [("%ds"%interval.second, (tagname, "task", task_number, "interval", "second"))]
+## if interval.microsecond != 0:
+## resrce += [("%dms"%(interval.microsecond / 1000), (tagname, "task", task_number, "interval", "millisecond"))]
+## resrce += [(",", ())]
# Priority argument
resrce += [("PRIORITY := ", ()),
("%d"%task.getpriority(), (tagname, "task", task_number, "priority")),
@@ -380,7 +383,7 @@
(" WITH ", ()),
(task.getname(), (tagname, "instance", instance_number, "task")),
(" : ", ()),
- (instance.gettype(), (tagname, "instance", instance_number, "type")),
+ (instance.gettypeName(), (tagname, "instance", instance_number, "type")),
(";\n", ())]
instance_number += 1
# Generate any program assign to no task
@@ -388,7 +391,7 @@
resrce += [(" PROGRAM ", ()),
(instance.getname(), (tagname, "instance", instance_number, "name")),
(" : ", ()),
- (instance.gettype(), (tagname, "instance", instance_number, "type")),
+ (instance.gettypeName(), (tagname, "instance", instance_number, "type")),
(";\n", ())]
instance_number += 1
resrce += [(" END_RESOURCE\n", ())]
@@ -532,6 +535,8 @@
interface = pou.getinterface()
if interface is not None:
body = pou.getbody()
+ if isinstance(body, ListType):
+ body = body[0]
body_content = body.getcontent()
if self.Type == "FUNCTION":
returntype_content = interface.getreturnType().getcontent()
@@ -596,6 +601,8 @@
def ComputeConnectionTypes(self, pou):
body = pou.getbody()
+ if isinstance(body, ListType):
+ body = body[0]
body_content = body.getcontent()
body_type = body_content["name"]
if body_type in ["FBD", "LD", "SFC"]:
@@ -662,7 +669,7 @@
for element in body.getcontentInstances():
if isinstance(element, plcopen.commonObjects_connector) and element.getname() == name:
if connector is not None:
- raise PLCGenException, "More than one connector found corresponding to \"%s\" continuation in \"%s\" POU"%(name, self.Name)
+ raise PLCGenException, _("More than one connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name)
connector = element
if connector is not None:
undefined = [instance.connectionPointOut, connector.connectionPointIn]
@@ -681,59 +688,64 @@
for connection in related:
self.ConnectionTypes[connection] = var_type
else:
- raise PLCGenException, "No connector found corresponding to \"%s\" continuation in \"%s\" POU"%(name, self.Name)
+ raise PLCGenException, _("No connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name)
elif isinstance(instance, plcopen.fbdObjects_block):
block_infos = self.GetBlockType(instance.gettypeName())
- undefined = {}
- for variable in instance.outputVariables.getvariable():
- output_name = variable.getformalParameter()
- if output_name == "ENO":
- for connection in self.ExtractRelatedConnections(variable.connectionPointOut):
- self.ConnectionTypes[connection] = "BOOL"
- else:
- for oname, otype, oqualifier in block_infos["outputs"]:
- if output_name == oname:
- if otype.startswith("ANY"):
- if not undefined.has_key(otype):
- undefined[otype] = []
- undefined[otype].append(variable.connectionPointOut)
- elif not self.ConnectionTypes.has_key(variable.connectionPointOut):
- for connection in self.ExtractRelatedConnections(variable.connectionPointOut):
- self.ConnectionTypes[connection] = otype
- for variable in instance.inputVariables.getvariable():
- input_name = variable.getformalParameter()
- if input_name == "EN":
- for connection in self.ExtractRelatedConnections(variable.connectionPointIn):
- self.ConnectionTypes[connection] = "BOOL"
- for iname, itype, iqualifier in block_infos["inputs"]:
- if input_name == iname:
- connected = self.GetConnectedConnector(variable.connectionPointIn, body)
- if itype.startswith("ANY"):
- if not undefined.has_key(itype):
- undefined[itype] = []
- undefined[itype].append(variable.connectionPointIn)
- if connected:
- undefined[itype].append(connected)
+ if block_infos is not None:
+ undefined = {}
+ for variable in instance.outputVariables.getvariable():
+ output_name = variable.getformalParameter()
+ if output_name == "ENO":
+ for connection in self.ExtractRelatedConnections(variable.connectionPointOut):
+ self.ConnectionTypes[connection] = "BOOL"
+ else:
+ for oname, otype, oqualifier in block_infos["outputs"]:
+ if output_name == oname:
+ if otype.startswith("ANY"):
+ if not undefined.has_key(otype):
+ undefined[otype] = []
+ undefined[otype].append(variable.connectionPointOut)
+ elif not self.ConnectionTypes.has_key(variable.connectionPointOut):
+ for connection in self.ExtractRelatedConnections(variable.connectionPointOut):
+ self.ConnectionTypes[connection] = otype
+ for variable in instance.inputVariables.getvariable():
+ input_name = variable.getformalParameter()
+ if input_name == "EN":
+ for connection in self.ExtractRelatedConnections(variable.connectionPointIn):
+ self.ConnectionTypes[connection] = "BOOL"
+ for iname, itype, iqualifier in block_infos["inputs"]:
+ if input_name == iname:
+ connected = self.GetConnectedConnector(variable.connectionPointIn, body)
+ if itype.startswith("ANY"):
+ if not undefined.has_key(itype):
+ undefined[itype] = []
+ undefined[itype].append(variable.connectionPointIn)
+ if connected:
+ undefined[itype].append(connected)
+ else:
+ self.ConnectionTypes[variable.connectionPointIn] = itype
+ if connected and not self.ConnectionTypes.has_key(connected):
+ for connection in self.ExtractRelatedConnections(connected):
+ self.ConnectionTypes[connection] = itype
+ for var_type, connections in undefined.items():
+ related = []
+ for connection in connections:
+ if self.ConnectionTypes.has_key(connection):
+ var_type = self.ConnectionTypes[connection]
else:
- self.ConnectionTypes[variable.connectionPointIn] = itype
- if connected and not self.ConnectionTypes.has_key(connected):
- for connection in self.ExtractRelatedConnections(connected):
- self.ConnectionTypes[connection] = itype
- for var_type, connections in undefined.items():
- related = []
- for connection in connections:
- if self.ConnectionTypes.has_key(connection):
- var_type = self.ConnectionTypes[connection]
+ related.extend(self.ExtractRelatedConnections(connection))
+ if var_type.startswith("ANY") and len(related) > 0:
+ self.RelatedConnections.append(related)
else:
- related.extend(self.ExtractRelatedConnections(connection))
- if var_type.startswith("ANY") and len(related) > 0:
- self.RelatedConnections.append(related)
- else:
- for connection in related:
- self.ConnectionTypes[connection] = var_type
-
+ for connection in related:
+ self.ConnectionTypes[connection] = var_type
+ else:
+ raise PLCGenException, _("No informations found for \"%s\" block")%(instance.gettypeName())
+
def ComputeProgram(self, pou):
body = pou.getbody()
+ if isinstance(body, ListType):
+ body = body[0]
body_content = body.getcontent()
body_type = body_content["name"]
if body_type in ["IL","ST"]:
@@ -861,7 +873,7 @@
for instance in body.getcontentInstances():
if isinstance(instance, plcopen.commonObjects_connector) and instance.getname() == name:
if connector is not None:
- raise PLCGenException, "More than one connector found corresponding to \"%s\" continuation in \"%s\" POU"%(name, self.Name)
+ raise PLCGenException, _("More than one connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name)
connector = instance
if connector is not None:
connections = connector.connectionPointIn.getconnections()
@@ -870,7 +882,7 @@
self.ComputedConnectors[name] = expression
paths.append(str(expression))
else:
- raise PLCGenException, "No connector found corresponding to \"%s\" continuation in \"%s\" POU"%(name, self.Name)
+ raise PLCGenException, _("No connector found corresponding to \"%s\" continuation in \"%s\" POU")%(name, self.Name)
elif isinstance(next, plcopen.ldObjects_contact):
contact_info = (self.TagName, "contact", next.getlocalId())
variable = str(self.ExtractModifier(next, [(next.getvariable(), contact_info + ("reference",))], contact_info))
@@ -958,7 +970,10 @@
connections = connectionPointIn.getconnections()
if connections is not None and len(connections) == 1:
instanceLocalId = connections[0].getrefLocalId()
- return pou.body.getcontentInstance(instanceLocalId)
+ body = pou.getbody()
+ if isinstance(body, ListType):
+ body = body[0]
+ return body.getcontentInstance(instanceLocalId)
return None
def ExtractConvergenceInputs(self, convergence, pou):
@@ -967,7 +982,10 @@
connections = connectionPointIn.getconnections()
if len(connections) == 1:
instanceLocalId = connections[0].getrefLocalId()
- instances.append(pou.body.getcontentInstance(instanceLocalId))
+ body = pou.getbody()
+ if isinstance(body, ListType):
+ body = body[0]
+ instances.append(body.getcontentInstance(instanceLocalId))
return instances
def GenerateSFCStep(self, step, pou):
@@ -984,7 +1002,10 @@
connections = step.connectionPointIn.getconnections()
if len(connections) == 1:
instanceLocalId = connections[0].getrefLocalId()
- instance = pou.body.getcontentInstance(instanceLocalId)
+ body = pou.getbody()
+ if isinstance(body, ListType):
+ body = body[0]
+ instance = body.getcontentInstance(instanceLocalId)
if isinstance(instance, plcopen.sfcObjects_transition):
instances.append(instance)
elif isinstance(instance, plcopen.sfcObjects_selectionConvergence):
@@ -1010,7 +1031,10 @@
connections = jump.connectionPointIn.getconnections()
if len(connections) == 1:
instanceLocalId = connections[0].getrefLocalId()
- instance = pou.body.getcontentInstance(instanceLocalId)
+ body = pou.getbody()
+ if isinstance(body, ListType):
+ body = body[0]
+ instance = body.getcontentInstance(instanceLocalId)
if isinstance(instance, plcopen.sfcObjects_transition):
instances.append(instance)
elif isinstance(instance, plcopen.sfcObjects_selectionConvergence):
@@ -1032,7 +1056,10 @@
connections = actionBlock.connectionPointIn.getconnections()
if connections is not None and len(connections) == 1:
stepLocalId = connections[0].getrefLocalId()
- step = pou.body.getcontentInstance(stepLocalId)
+ body = pou.getbody()
+ if isinstance(body, ListType):
+ body = body[0]
+ step = body.getcontentInstance(stepLocalId)
self.GenerateSFCStep(step, pou)
step_name = step.getname()
if step_name in self.SFCNetworks["Steps"].keys():
@@ -1073,7 +1100,10 @@
connections = transition.connectionPointIn.getconnections()
if connections is not None and len(connections) == 1:
instanceLocalId = connections[0].getrefLocalId()
- instance = pou.body.getcontentInstance(instanceLocalId)
+ body = pou.getbody()
+ if isinstance(body, ListType):
+ body = body[0]
+ instance = body.getcontentInstance(instanceLocalId)
if isinstance(instance, plcopen.sfcObjects_step):
steps.append(instance)
elif isinstance(instance, plcopen.sfcObjects_selectionDivergence):
@@ -1119,6 +1149,8 @@
self.TagName = previous_tagname
elif transitionValues["type"] == "connection":
body = pou.getbody()
+ if isinstance(body, ListType):
+ body = body[0]
connections = transition.getconnections()
if connections is not None:
expression = self.ComputeExpression(body, connections)
@@ -1193,7 +1225,7 @@
elif len(transition_infos["from"]) == 1:
self.Program += transition_infos["from"][0]
else:
- raise PLCGenException, "Transition with content \"%s\" not connected to a previous step in \"%s\" POU"%(transition_infos["content"], self.Name)
+ raise PLCGenException, _("Transition with content \"%s\" not connected to a previous step in \"%s\" POU")%(transition_infos["content"], self.Name)
self.Program += [(" TO ", ())]
if len(transition_infos["to"]) > 1:
self.Program += [("(", ())]
@@ -1202,7 +1234,7 @@
elif len(transition_infos["to"]) == 1:
self.Program += transition_infos["to"][0]
else:
- raise PLCGenException, "Transition with content \"%s\" not connected to a next step in \"%s\" POU"%(transition_infos["content"], self.Name)
+ raise PLCGenException, _("Transition with content \"%s\" not connected to a next step in \"%s\" POU")%(transition_infos["content"], self.Name)
self.Program += transition_infos["content"]
self.Program += [("%sEND_TRANSITION\n\n"%self.CurrentIndent, ())]
for [(step_name, step_infos)] in transition_infos["to"]:
@@ -1220,9 +1252,9 @@
(self.ReturnType, (self.TagName, "return"))]
program += [("\n", ())]
if len(self.Interface) == 0:
- raise PLCGenException, "No variable defined in \"%s\" POU"%self.Name
+ raise PLCGenException, _("No variable defined in \"%s\" POU")%self.Name
if len(self.Program) == 0 :
- raise PLCGenException, "No body defined in \"%s\" POU"%self.Name
+ raise PLCGenException, _("No body defined in \"%s\" POU")%self.Name
var_number = 0
for list_type, retain, constant, located, variables in self.Interface:
program += [(" %s"%list_type, ())]
diff -r e0a6a5952d13 -r 127d524a5f1d PLCOpenEditor.py
--- a/PLCOpenEditor.py Mon Jul 06 11:24:37 2009 -0600
+++ b/PLCOpenEditor.py Thu Aug 20 09:03:31 2009 -0600
@@ -31,6 +31,75 @@
else:
USE_AUI = False
+import os, re, platform, sys, time, traceback, getopt
+import cPickle
+
+CWD = os.path.split(os.path.realpath(__file__))[0]
+base_folder = os.path.split(CWD)[0]
+sys.path.append(base_folder)
+from docutils import *
+
+from types import TupleType
+
+__version__ = "$Revision: 1.130 $"
+
+if __name__ == '__main__':
+ # Usage message displayed when help request or when error detected in
+ # command line
+ def usage():
+ print "\nUsage of PLCOpenEditor.py :"
+ print "\n %s [Filepath]\n"%sys.argv[0]
+
+ # Parse options given to PLCOpenEditor in command line
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], "h", ["help"])
+ except getopt.GetoptError:
+ # print help information and exit:
+ usage()
+ sys.exit(2)
+
+ # Extract if help has been requested
+ for o, a in opts:
+ if o in ("-h", "--help"):
+ usage()
+ sys.exit()
+
+ # Extract the optional filename to open
+ fileOpen = None
+ if len(args) > 1:
+ usage()
+ sys.exit()
+ elif len(args) == 1:
+ fileOpen = args[0]
+
+ # Create wxApp (Need to create App before internationalization because of
+ # Windows)
+ app = wx.PySimpleApp()
+
+# Import module for internationalization
+import gettext
+import __builtin__
+
+# Get folder containing translation files
+localedir = os.path.join(CWD,"locale")
+# Get the default language
+langid = wx.LANGUAGE_DEFAULT
+# Define translation domain (name of translation files)
+domain = "PLCOpenEditor"
+
+# Define locale for wx
+loc = __builtin__.__dict__.get('loc', None)
+if loc is None:
+ loc = wx.Locale(langid)
+ __builtin__.__dict__['loc'] = loc
+# Define location for searching translation files
+loc.AddCatalogLookupPathPrefix(localedir)
+# Define locale domain
+loc.AddCatalog(domain)
+
+if __name__ == '__main__':
+ __builtin__.__dict__['_'] = wx.GetTranslation
+
from SFCViewer import *
from LDViewer import *
from Viewer import *
@@ -41,18 +110,7 @@
from PLCControler import *
from plcopen.structures import LOCATIONDATATYPES
-import os, re, platform, sys, time, traceback, getopt
-
-base_folder = os.path.split(sys.path[0])[0]
-sys.path.append(base_folder)
-from docutils import *
-
-from types import TupleType
-
-__version__ = "$Revision$"
-
-CWD = os.path.split(os.path.realpath(__file__))[0]
-
+# Define PLCOpenEditor controls id
[ID_PLCOPENEDITOR, ID_PLCOPENEDITORTREENOTEBOOK,
ID_PLCOPENEDITORTYPESTREE, ID_PLCOPENEDITORINSTANCESTREE,
ID_PLCOPENEDITORMAINSPLITTER, ID_PLCOPENEDITORSECONDSPLITTER,
@@ -64,9 +122,11 @@
ID_PLCOPENEDITORLDTOOLBAR,
] = [wx.NewId() for _init_ctrls in range(17)]
+# Define PLCOpenEditor FileMenu extra items id
[ID_PLCOPENEDITORFILEMENUGENERATE,
] = [wx.NewId() for _init_coll_FileMenu_Items in range(1)]
+# Define PLCOpenEditor EditMenu extra items id
[ID_PLCOPENEDITOREDITMENUENABLEUNDOREDO, ID_PLCOPENEDITOREDITMENUADDDATATYPE,
ID_PLCOPENEDITOREDITMENUADDFUNCTION, ID_PLCOPENEDITOREDITMENUADDFUNCTIONBLOCK,
ID_PLCOPENEDITOREDITMENUADDPROGRAM, ID_PLCOPENEDITOREDITMENUADDCONFIGURATION,
@@ -77,7 +137,7 @@
# ToolBars definitions
#-------------------------------------------------------------------------------
-
+# Define PLCOpenEditor Toolbar items id
[ID_PLCOPENEDITORTOOLBARSELECTION, ID_PLCOPENEDITORTOOLBARCOMMENT,
ID_PLCOPENEDITORTOOLBARVARIABLE, ID_PLCOPENEDITORTOOLBARBLOCK,
ID_PLCOPENEDITORTOOLBARCONNECTION, ID_PLCOPENEDITORTOOLBARWIRE,
@@ -89,96 +149,149 @@
ID_PLCOPENEDITORTOOLBARJUMP,
] = [wx.NewId() for _init_coll_DefaultToolBar_Items in range(17)]
+# Define behaviour of each Toolbar item according to current POU body type
+# Informations meaning are in this order:
+# - Item is toggled
+# - PLCOpenEditor mode where item is displayed (could be more then one)
+# - Item id
+# - Item callback function name
+# - Item icon filename
+# - Item tooltip text
ToolBarItems = {
"FBD" : [(True, FREEDRAWING_MODE|DRIVENDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARCOMMENT, "OnCommentTool",
- "add_comment.png", "Create a new comment"),
+ "add_comment.png", _("Create a new comment")),
(True, FREEDRAWING_MODE|DRIVENDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARVARIABLE, "OnVariableTool",
- "add_variable.png", "Create a new variable"),
+ "add_variable.png", _("Create a new variable")),
(True, FREEDRAWING_MODE|DRIVENDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARBLOCK, "OnBlockTool",
- "add_block.png", "Create a new block"),
+ "add_block.png", _("Create a new block")),
(True, FREEDRAWING_MODE|DRIVENDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARCONNECTION, "OnConnectionTool",
- "add_connection.png", "Create a new connection")],
+ "add_connection.png", _("Create a new connection"))],
"LD" : [(True, FREEDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARCOMMENT, "OnCommentTool",
- "add_comment.png", "Create a new comment"),
+ "add_comment.png", _("Create a new comment")),
(True, FREEDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARPOWERRAIL, "OnPowerRailTool",
- "add_powerrail.png", "Create a new power rail"),
+ "add_powerrail.png", _("Create a new power rail")),
(False, DRIVENDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARRUNG, "OnRungTool",
- "add_rung.png", "Create a new rung"),
+ "add_rung.png", _("Create a new rung")),
(True, FREEDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARCOIL, "OnCoilTool",
- "add_coil.png", "Create a new coil"),
+ "add_coil.png", _("Create a new coil")),
(False, FREEDRAWING_MODE|DRIVENDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARCONTACT, "OnContactTool",
- "add_contact.png", "Create a new contact"),
+ "add_contact.png", _("Create a new contact")),
(False, DRIVENDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARBRANCH, "OnBranchTool",
- "add_branch.png", "Create a new branch"),
+ "add_branch.png", _("Create a new branch")),
(True, FREEDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARVARIABLE, "OnVariableTool",
- "add_variable.png", "Create a new variable"),
+ "add_variable.png", _("Create a new variable")),
(False, FREEDRAWING_MODE|DRIVENDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARBLOCK, "OnBlockTool",
- "add_block.png", "Create a new block"),
+ "add_block.png", _("Create a new block")),
(True, FREEDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARCONNECTION, "OnConnectionTool",
- "add_connection.png", "Create a new connection")],
+ "add_connection.png", _("Create a new connection"))],
"SFC" : [(True, FREEDRAWING_MODE|DRIVENDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARCOMMENT, "OnCommentTool",
- "add_comment.png", "Create a new comment"),
+ "add_comment.png", _("Create a new comment")),
(True, FREEDRAWING_MODE|DRIVENDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARINITIALSTEP, "OnInitialStepTool",
- "add_initial_step.png", "Create a new initial step"),
+ "add_initial_step.png", _("Create a new initial step")),
(False, FREEDRAWING_MODE|DRIVENDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARSTEP, "OnStepTool",
- "add_step.png", "Create a new step"),
+ "add_step.png", _("Create a new step")),
(True, FREEDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARTRANSITION, "OnTransitionTool",
- "add_transition.png", "Create a new transition"),
+ "add_transition.png", _("Create a new transition")),
(False, FREEDRAWING_MODE|DRIVENDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARACTIONBLOCK, "OnActionBlockTool",
- "add_action.png", "Create a new action block"),
+ "add_action.png", _("Create a new action block")),
(False, FREEDRAWING_MODE|DRIVENDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARDIVERGENCE, "OnDivergenceTool",
- "add_divergence.png", "Create a new divergence"),
+ "add_divergence.png", _("Create a new divergence")),
(False, FREEDRAWING_MODE|DRIVENDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARJUMP, "OnJumpTool",
- "add_jump.png", "Create a new jump"),
+ "add_jump.png", _("Create a new jump")),
(True, FREEDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARVARIABLE, "OnVariableTool",
- "add_variable.png", "Create a new variable"),
+ "add_variable.png", _("Create a new variable")),
(True, FREEDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARBLOCK, "OnBlockTool",
- "add_block.png", "Create a new block"),
+ "add_block.png", _("Create a new block")),
(True, FREEDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARCONNECTION, "OnConnectionTool",
- "add_connection.png", "Create a new connection"),
+ "add_connection.png", _("Create a new connection")),
(True, FREEDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARPOWERRAIL, "OnPowerRailTool",
- "add_powerrail.png", "Create a new power rail"),
+ "add_powerrail.png", _("Create a new power rail")),
(True, FREEDRAWING_MODE,
ID_PLCOPENEDITORTOOLBARCONTACT, "OnContactTool",
- "add_contact.png", "Create a new contact")],
+ "add_contact.png", _("Create a new contact"))],
"ST" : [],
"IL" : []
}
+#-------------------------------------------------------------------------------
+# Helper Functions
+#-------------------------------------------------------------------------------
+
+# Compatibility function for wx versions < 2.6
def AppendMenu(parent, help, id, kind, text):
if wx.VERSION >= (2, 6, 0):
parent.Append(help=help, id=id, kind=kind, text=text)
else:
parent.Append(helpString=help, id=id, kind=kind, item=text)
+[TITLE, TOOLBAR, FILEMENU, EDITMENU, DISPLAYMENU, TYPESTREE,
+ INSTANCESTREE, LIBRARYTREE, SCALING
+] = [wx.NewId() for _refresh_elements in range(9)]
+
+def GetShortcutKeyCallbackFunction(viewer_function):
+ def ShortcutKeyFunction(self, event):
+ control = self.FindFocus()
+ if isinstance(control, (Viewer, TextViewer)):
+ getattr(control, viewer_function)()
+ elif isinstance(control, wx.TextCtrl):
+ control.ProcessEvent(event)
+ event.Skip()
+ return ShortcutKeyFunction
+
+def GetParentName(tree, item, parent_type):
+ parent_item = tree.GetItemParent(item)
+ parent_item_type = tree.GetPyData(parent_item)
+ while parent_item_type != parent_type:
+ parent_item = tree.GetItemParent(parent_item)
+ parent_item_type = tree.GetPyData(parent_item)
+ return tree.GetItemText(parent_item)
+
+def GetDeleteElementFunction(remove_function, parent_type=None, check_function=None):
+ def DeleteElementFunction(self, selected):
+ name = self.TypesTree.GetItemText(selected)
+ if check_function is None or not check_function(self.Controler, name, self.Debug):
+ if parent_type is not None:
+ parent_name = GetParentName(self.TypesTree, selected, parent_type)
+ remove_function(self.Controler, parent_name, name)
+ else:
+ remove_function(self.Controler, name)
+ else:
+ self.ShowErrorMessage(_("\"%s\" is used by one or more POUs. It can't be removed!")%name)
+ return DeleteElementFunction
+
+#-------------------------------------------------------------------------------
+# PLCOpenEditor Main Class
+#-------------------------------------------------------------------------------
+
+UNEDITABLE_NAMES_DICT = dict([(_(name), name) for name in UNEDITABLE_NAMES])
+
class PLCOpenEditor(wx.Frame):
- CopyBuffer = None
-
+ # Compatibility function for wx versions < 2.6
if wx.VERSION < (2, 6, 0):
def Bind(self, event, function, id = None):
if id is not None:
@@ -187,50 +300,50 @@
event(self, function)
def _init_coll_MenuBar_Menus(self, parent):
- parent.Append(menu=self.FileMenu, title=u'File')
+ parent.Append(menu=self.FileMenu, title=_(u'File'))
if not self.Debug:
- parent.Append(menu=self.EditMenu, title=u'Edit')
- parent.Append(menu=self.DisplayMenu, title=u'Display')
- parent.Append(menu=self.HelpMenu, title=u'Help')
+ parent.Append(menu=self.EditMenu, title=_(u'Edit'))
+ parent.Append(menu=self.DisplayMenu, title=_(u'Display'))
+ parent.Append(menu=self.HelpMenu, title=_(u'Help'))
def _init_coll_FileMenu_Items(self, parent):
if self.ModeSolo:
AppendMenu(parent, help='', id=wx.ID_NEW,
- kind=wx.ITEM_NORMAL, text=u'New\tCTRL+N')
+ kind=wx.ITEM_NORMAL, text=_(u'New\tCTRL+N'))
AppendMenu(parent, help='', id=wx.ID_OPEN,
- kind=wx.ITEM_NORMAL, text=u'Open\tCTRL+O')
+ kind=wx.ITEM_NORMAL, text=_(u'Open\tCTRL+O'))
AppendMenu(parent, help='', id=wx.ID_CLOSE,
- kind=wx.ITEM_NORMAL, text=u'Close Tab\tCTRL+W')
+ kind=wx.ITEM_NORMAL, text=_(u'Close Tab\tCTRL+W'))
if self.ModeSolo:
AppendMenu(parent, help='', id=wx.ID_CLOSE_ALL,
- kind=wx.ITEM_NORMAL, text=u'Close Project')
+ kind=wx.ITEM_NORMAL, text=_(u'Close Project'))
parent.AppendSeparator()
if not self.Debug:
AppendMenu(parent, help='', id=wx.ID_SAVE,
- kind=wx.ITEM_NORMAL, text=u'Save\tCTRL+S')
+ kind=wx.ITEM_NORMAL, text=_(u'Save\tCTRL+S'))
if self.ModeSolo:
AppendMenu(parent, help='', id=wx.ID_SAVEAS,
- kind=wx.ITEM_NORMAL, text=u'Save As...\tCTRL+SHIFT+S')
+ kind=wx.ITEM_NORMAL, text=_(u'Save As...\tCTRL+SHIFT+S'))
AppendMenu(parent, help='', id=ID_PLCOPENEDITORFILEMENUGENERATE,
- kind=wx.ITEM_NORMAL, text=u'Generate Program\tCTRL+G')
+ kind=wx.ITEM_NORMAL, text=_(u'Generate Program\tCTRL+G'))
parent.AppendSeparator()
AppendMenu(parent, help='', id=wx.ID_PAGE_SETUP,
- kind=wx.ITEM_NORMAL, text=u'Page Setup')
+ kind=wx.ITEM_NORMAL, text=_(u'Page Setup'))
AppendMenu(parent, help='', id=wx.ID_PREVIEW,
- kind=wx.ITEM_NORMAL, text=u'Preview')
+ kind=wx.ITEM_NORMAL, text=_(u'Preview'))
AppendMenu(parent, help='', id=wx.ID_PRINT,
- kind=wx.ITEM_NORMAL, text=u'Print')
+ kind=wx.ITEM_NORMAL, text=_(u'Print'))
if not self.Debug:
parent.AppendSeparator()
AppendMenu(parent, help='', id=wx.ID_PROPERTIES,
- kind=wx.ITEM_NORMAL, text=u'Properties')
+ kind=wx.ITEM_NORMAL, text=_(u'Properties'))
parent.AppendSeparator()
if self.ModeSolo:
AppendMenu(parent, help='', id=wx.ID_EXIT,
- kind=wx.ITEM_NORMAL, text=u'Quit\tCTRL+Q')
+ kind=wx.ITEM_NORMAL, text=_(u'Quit\tCTRL+Q'))
else:
AppendMenu(parent, help='', id=wx.ID_STOP,
- kind=wx.ITEM_NORMAL, text=u'Close\tCTRL+Q')
+ kind=wx.ITEM_NORMAL, text=_(u'Close\tCTRL+Q'))
if self.ModeSolo:
self.Bind(wx.EVT_MENU, self.OnNewProjectMenu, id=wx.ID_NEW)
@@ -256,35 +369,33 @@
def _init_coll_EditMenu_Items(self, parent):
AppendMenu(parent, help='', id=wx.ID_UNDO,
- kind=wx.ITEM_NORMAL, text=u'Undo\tCTRL+Z')
+ kind=wx.ITEM_NORMAL, text=_(u'Undo\tCTRL+Z'))
AppendMenu(parent, help='', id=wx.ID_REDO,
- kind=wx.ITEM_NORMAL, text=u'Redo\tCTRL+Y')
- AppendMenu(parent, help='', id=ID_PLCOPENEDITOREDITMENUENABLEUNDOREDO,
- kind=wx.ITEM_CHECK, text=u'Enable Undo/Redo')
+ kind=wx.ITEM_NORMAL, text=_(u'Redo\tCTRL+Y'))
parent.AppendSeparator()
AppendMenu(parent, help='', id=wx.ID_CUT,
- kind=wx.ITEM_NORMAL, text=u'Cut\tCTRL+X')
+ kind=wx.ITEM_NORMAL, text=_(u'Cut\tCTRL+X'))
AppendMenu(parent, help='', id=wx.ID_COPY,
- kind=wx.ITEM_NORMAL, text=u'Copy\tCTRL+C')
+ kind=wx.ITEM_NORMAL, text=_(u'Copy\tCTRL+C'))
AppendMenu(parent, help='', id=wx.ID_PASTE,
- kind=wx.ITEM_NORMAL, text=u'Paste\tCTRL+V')
+ kind=wx.ITEM_NORMAL, text=_(u'Paste\tCTRL+V'))
parent.AppendSeparator()
addmenu = wx.Menu(title='')
- parent.AppendMenu(wx.ID_ADD, "Add Element", addmenu)
+ parent.AppendMenu(wx.ID_ADD, _("Add Element"), addmenu)
AppendMenu(addmenu, help='', id=ID_PLCOPENEDITOREDITMENUADDDATATYPE,
- kind=wx.ITEM_NORMAL, text=u'Data Type')
+ kind=wx.ITEM_NORMAL, text=_(u'Data Type'))
AppendMenu(addmenu, help='', id=ID_PLCOPENEDITOREDITMENUADDFUNCTION,
- kind=wx.ITEM_NORMAL, text=u'Function')
+ kind=wx.ITEM_NORMAL, text=_(u'Function'))
AppendMenu(addmenu, help='', id=ID_PLCOPENEDITOREDITMENUADDFUNCTIONBLOCK,
- kind=wx.ITEM_NORMAL, text=u'Function Block')
+ kind=wx.ITEM_NORMAL, text=_(u'Function Block'))
AppendMenu(addmenu, help='', id=ID_PLCOPENEDITOREDITMENUADDPROGRAM,
- kind=wx.ITEM_NORMAL, text=u'Program')
+ kind=wx.ITEM_NORMAL, text=_(u'Program'))
AppendMenu(addmenu, help='', id=ID_PLCOPENEDITOREDITMENUADDCONFIGURATION,
- kind=wx.ITEM_NORMAL, text=u'Configuration')
+ kind=wx.ITEM_NORMAL, text=_(u'Configuration'))
AppendMenu(parent, help='', id=wx.ID_SELECTALL,
- kind=wx.ITEM_NORMAL, text=u'Select All\tCTRL+A')
+ kind=wx.ITEM_NORMAL, text=_(u'Select All\tCTRL+A'))
AppendMenu(parent, help='', id=wx.ID_DELETE,
- kind=wx.ITEM_NORMAL, text=u'Delete')
+ kind=wx.ITEM_NORMAL, text=_(u'Delete'))
self.Bind(wx.EVT_MENU, self.OnUndoMenu, id=wx.ID_UNDO)
self.Bind(wx.EVT_MENU, self.OnRedoMenu, id=wx.ID_REDO)
self.Bind(wx.EVT_MENU, self.OnEnableUndoRedoMenu, id=ID_PLCOPENEDITOREDITMENUENABLEUNDOREDO)
@@ -306,13 +417,13 @@
def _init_coll_DisplayMenu_Items(self, parent):
AppendMenu(parent, help='', id=wx.ID_REFRESH,
- kind=wx.ITEM_NORMAL, text=u'Refresh\tF5')
+ kind=wx.ITEM_NORMAL, text=_(u'Refresh\tF5'))
if not self.Debug and not self.ModeSolo:
AppendMenu(parent, help='', id=wx.ID_CLEAR,
- kind=wx.ITEM_NORMAL, text=u'Clear Errors\tCTRL+K')
+ kind=wx.ITEM_NORMAL, text=_(u'Clear Errors\tCTRL+K'))
parent.AppendSeparator()
zoommenu = wx.Menu(title='')
- parent.AppendMenu(wx.ID_ZOOM_FIT, "ZOOM", zoommenu)
+ parent.AppendMenu(wx.ID_ZOOM_FIT, _("Zoom"), zoommenu)
for idx, value in enumerate(ZOOM_FACTORS):
new_id = wx.NewId()
AppendMenu(zoommenu, help='', id=new_id,
@@ -324,14 +435,14 @@
def _init_coll_HelpMenu_Items(self, parent):
AppendMenu(parent, help='', id=wx.ID_HELP,
- kind=wx.ITEM_NORMAL, text=u'PLCOpenEditor\tF1')
+ kind=wx.ITEM_NORMAL, text=_(u'PLCOpenEditor\tF1'))
#AppendMenu(parent, help='', id=wx.ID_HELP_CONTENTS,
# kind=wx.ITEM_NORMAL, text=u'PLCOpen\tF2')
#AppendMenu(parent, help='', id=wx.ID_HELP_CONTEXT,
# kind=wx.ITEM_NORMAL, text=u'IEC 61131-3\tF3')
if self.ModeSolo:
AppendMenu(parent, help='', id=wx.ID_ABOUT,
- kind=wx.ITEM_NORMAL, text=u'About')
+ kind=wx.ITEM_NORMAL, text=_(u'About'))
self.Bind(wx.EVT_MENU, self.OnPLCOpenEditorMenu, id=wx.ID_HELP)
#self.Bind(wx.EVT_MENU, self.OnPLCOpenMenu, id=wx.ID_HELP_CONTENTS)
self.Bind(wx.EVT_MENU, self.OnAboutMenu, id=wx.ID_ABOUT)
@@ -371,7 +482,7 @@
def _init_ctrls(self, prnt):
wx.Frame.__init__(self, id=ID_PLCOPENEDITOR, name=u'PLCOpenEditor',
parent=prnt, pos=wx.DefaultPosition, size=wx.Size(1000, 600),
- style=wx.DEFAULT_FRAME_STYLE, title=u'PLCOpenEditor')
+ style=wx.DEFAULT_FRAME_STYLE, title=_(u'PLCOpenEditor'))
self._init_utils()
self.SetClientSize(wx.Size(1000, 600))
self.SetMenuBar(self.MenuBar)
@@ -383,7 +494,7 @@
self.Panes = {}
self.TreeNoteBook = wx.aui.AuiNotebook(self)
- self.AUIManager.AddPane(self.TreeNoteBook, wx.aui.AuiPaneInfo().Caption("Project").Left().Layer(1).BestSize(wx.Size(200, 500)).CloseButton(False))
+ self.AUIManager.AddPane(self.TreeNoteBook, wx.aui.AuiPaneInfo().Caption(_("Project")).Left().Layer(1).BestSize(wx.Size(200, 500)).CloseButton(False))
else:
self.MainSplitter = wx.SplitterWindow(id=ID_PLCOPENEDITORMAINSPLITTER,
@@ -431,6 +542,10 @@
name='InstancesTree', parent=self.TreeNoteBook,
pos=wx.Point(0, 0), size=wx.Size(0, 0),
style=wx.TR_HAS_BUTTONS|wx.TR_SINGLE|wx.SUNKEN_BORDER)
+
+ self.TabsImageList = wx.ImageList(16, 31)
+ self.TabsImageListIndexes = {}
+
if self.Debug:
if wx.VERSION >= (2, 6, 0):
self.InstancesTree.Bind(wx.EVT_RIGHT_UP, self.OnInstancesTreeRightUp)
@@ -441,8 +556,8 @@
self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnInstancesTreeItemActivated,
id=ID_PLCOPENEDITORINSTANCESTREE)
- self.TreeNoteBook.AddPage(self.InstancesTree, "Instances")
- self.TreeNoteBook.AddPage(self.TypesTree, "Types")
+ self.TreeNoteBook.AddPage(self.InstancesTree, _("Instances"))
+ self.TreeNoteBook.AddPage(self.TypesTree, _("Types"))
if USE_AUI:
self.TabsOpened = wx.aui.AuiNotebook(self)
@@ -455,7 +570,7 @@
self.AUIManager.AddPane(self.TabsOpened, wx.aui.AuiPaneInfo().CentrePane())
self.DebugVariablePanel = DebugVariablePanel(self, self.Controler)
- self.AUIManager.AddPane(self.DebugVariablePanel, wx.aui.AuiPaneInfo().Caption("Variables").Right().Layer(0).BestSize(wx.Size(250, 600)).CloseButton(False))
+ self.AUIManager.AddPane(self.DebugVariablePanel, wx.aui.AuiPaneInfo().Caption(_("Variables")).Right().Layer(0).BestSize(wx.Size(250, 600)).CloseButton(False))
else:
self.SecondSplitter = wx.SplitterWindow(id=ID_PLCOPENEDITORSECONDSPLITTER,
name='SecondSplitter', parent=self.MainSplitter, point=wx.Point(0, 0),
@@ -478,19 +593,19 @@
self.SecondSplitter.SplitVertically(self.TabsOpened, self.DebugVariablePanel, -250)
else:
- self.TreeNoteBook.AddPage(self.TypesTree, "Types")
- self.TreeNoteBook.AddPage(self.InstancesTree, "Instances")
+ self.TreeNoteBook.AddPage(self.TypesTree, _("Types"))
+ self.TreeNoteBook.AddPage(self.InstancesTree, _("Instances"))
if USE_AUI:
ToolBar = wx.ToolBar(self, ID_PLCOPENEDITORTOOLBAR, wx.DefaultPosition, wx.DefaultSize,
wx.TB_FLAT | wx.TB_NODIVIDER | wx.NO_BORDER)
ToolBar.SetToolBitmapSize(wx.Size(25, 25))
ToolBar.AddRadioTool(ID_PLCOPENEDITORTOOLBARSELECTION,
- wx.Bitmap(os.path.join(CWD, 'Images', 'select.png')), wx.NullBitmap, "Select an object")
+ wx.Bitmap(os.path.join(CWD, 'Images', 'select.png')), wx.NullBitmap, _("Select an object"))
ToolBar.Realize()
self.Panes["ToolBar"] = ToolBar
self.AUIManager.AddPane(ToolBar, wx.aui.AuiPaneInfo().
- Name("ToolBar").Caption("Toolbar").
+ Name("ToolBar").Caption(_("Toolbar")).
ToolbarPane().Top().
LeftDockable(False).RightDockable(False))
else:
@@ -498,7 +613,7 @@
ID_PLCOPENEDITORTOOLBAR, 'ToolBar')
self.ToolBar.SetToolBitmapSize(wx.Size(25, 25))
self.ToolBar.AddRadioTool(ID_PLCOPENEDITORTOOLBARSELECTION,
- wx.Bitmap(os.path.join(CWD, 'Images', 'select.png')), wx.NullBitmap, "Select an object")
+ wx.Bitmap(os.path.join(CWD, 'Images', 'select.png')), wx.NullBitmap, _("Select an object"))
self.ToolBar.Realize()
self.Bind(wx.EVT_TOOL, self.OnSelectionTool,
@@ -506,7 +621,7 @@
if USE_AUI:
self.VariablePanelIndexer = VariablePanelIndexer(self, self, self.Controler)
- self.AUIManager.AddPane(self.VariablePanelIndexer, wx.aui.AuiPaneInfo().Caption("Variables").Bottom().Layer(0).BestSize(wx.Size(800, 200)).CloseButton(False))
+ self.AUIManager.AddPane(self.VariablePanelIndexer, wx.aui.AuiPaneInfo().Caption(_("Variables")).Bottom().Layer(0).BestSize(wx.Size(800, 200)).CloseButton(False))
self.TabsOpened = wx.aui.AuiNotebook(self)
self.TabsOpened.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CHANGED,
@@ -520,7 +635,7 @@
self.LibraryPanel = wx.Panel(id=ID_PLCOPENEDITORLIBRARYPANEL,
name='LibraryPanel', parent=self, pos=wx.Point(0,
0), size=wx.Size(0, 0), style=0)
- self.AUIManager.AddPane(self.LibraryPanel, wx.aui.AuiPaneInfo().Caption("Library").Right().Layer(0).BestSize(wx.Size(250, 400)).CloseButton(False))
+ self.AUIManager.AddPane(self.LibraryPanel, wx.aui.AuiPaneInfo().Caption(_("Library")).Right().Layer(0).BestSize(wx.Size(250, 400)).CloseButton(False))
else:
self.SecondSplitter = wx.SplitterWindow(id=ID_PLCOPENEDITORSECONDSPLITTER,
name='SecondSplitter', parent=self.MainSplitter, point=wx.Point(0, 0),
@@ -541,9 +656,7 @@
self.TabsOpened = wx.Notebook(id=ID_PLCOPENEDITORTABSOPENED,
name='TabsOpened', parent=self.ThirdSplitter, pos=wx.Point(0,
0), size=wx.Size(0, 0), style=0)
- self.TabsImageList = wx.ImageList(16, 31)
self.TabsOpened.SetImageList(self.TabsImageList)
- self.TabsImageListIndexes = {}
if wx.VERSION >= (2, 6, 0):
self.TabsOpened.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED,
self.OnPouSelectedChanged, id=ID_PLCOPENEDITORTABSOPENED)
@@ -580,11 +693,19 @@
if USE_AUI:
self.AUIManager.Update()
+ ## Constructor of the PLCOpenEditor class.
+ # @param parent The parent window.
+ # @param controler The controler been used by PLCOpenEditor (default: None).
+ # @param fileOpen The filepath to open if no controler defined (default: None).
+ # @param debug The filepath to open if no controler defined (default: False).
def __init__(self, parent, controler = None, fileOpen = None, debug = False):
+ # Variable indicating that PLCOpenEditor was opened with a defined controler
self.ModeSolo = controler == None
self.Debug = debug
if self.ModeSolo:
+ # If no controler defined, create a new one
self.Controler = PLCControler()
+ # Open the filepath if defined
if fileOpen is not None:
self.Controler.OpenXMLFile(fileOpen)
else:
@@ -592,16 +713,18 @@
self._init_ctrls(parent)
- self.SetIcon(wx.Icon(os.path.join(CWD,"Images","poe.ico"),wx.BITMAP_TYPE_ICO))
-
- self.TypesTreeImageList = wx.ImageList(16, 16)
- self.InstancesTreeImageList = wx.ImageList(16, 16)
- self.TypesTreeImageDict = {}
- self.InstancesTreeImageDict = {}
+ # Define PLCOpenEditor icon
+ self.SetIcon(wx.Icon(os.path.join(CWD,"Images", "poe.ico"),wx.BITMAP_TYPE_ICO))
+
+ # Define Tree item icon list
+ self.TreeImageList = wx.ImageList(16, 16)
+ self.TreeImageDict = {}
+
+ # Icons for languages
for language in LANGUAGES:
- self.TypesTreeImageDict[language]=self.TypesTreeImageList.Add(wx.Bitmap(os.path.join(CWD, 'Images', '%s.png'%language)))
- self.InstancesTreeImageDict[language]=self.InstancesTreeImageList.Add(wx.Bitmap(os.path.join(CWD, 'Images', '%s.png'%language)))
-
+ self.TreeImageDict[language]=self.TreeImageList.Add(wx.Bitmap(os.path.join(CWD, 'Images', '%s.png'%language)))
+
+ # Icons for other items
for imgname, itemtype in [
#editables
("PROJECT", ITEM_PROJECT),
@@ -629,10 +752,11 @@
("CONFIGURATIONS", ITEM_CONFIGURATIONS),
("RESOURCES", ITEM_RESOURCES),
("PROPERTIES", ITEM_PROPERTIES)]:
- self.TypesTreeImageDict[itemtype]=self.TypesTreeImageList.Add(wx.Bitmap(os.path.join(CWD, 'Images', '%s.png'%imgname)))
- self.InstancesTreeImageDict[itemtype]=self.InstancesTreeImageList.Add(wx.Bitmap(os.path.join(CWD, 'Images', '%s.png'%imgname)))
- self.TypesTree.AssignImageList(self.TypesTreeImageList)
- self.InstancesTree.AssignImageList(self.InstancesTreeImageList)
+ self.TreeImageDict[itemtype]=self.TreeImageList.Add(wx.Bitmap(os.path.join(CWD, 'Images', '%s.png'%imgname)))
+
+ # Assign icon list to TreeCtrls
+ self.TypesTree.SetImageList(self.TreeImageList)
+ self.InstancesTree.SetImageList(self.TreeImageList)
self.CurrentToolBar = []
self.CurrentLanguage = ""
@@ -643,6 +767,7 @@
if USE_AUI:
self.AuiTabCtrl = []
+ # Initialize Printing configuring elements
self.PrintData = wx.PrintData()
self.PrintData.SetPaperId(wx.PAPER_A4)
self.PrintData.SetPrintMode(wx.PRINT_MODE_PRINTER)
@@ -650,58 +775,69 @@
self.PageSetupData.SetMarginTopLeft(wx.Point(10, 15))
self.PageSetupData.SetMarginBottomRight(wx.Point(10, 20))
+ # Refresh elements that need to
if not self.ModeSolo or fileOpen is not None:
- self.RefreshTypesTree()
- self.RefreshInstancesTree()
- self.RefreshLibraryTree()
-
- self.RefreshFileMenu()
- self.RefreshEditMenu()
- self.RefreshDisplayMenu()
- self.RefreshTitle()
- self.RefreshToolBar()
-
- def ResetSelectedItem(self):
- self.SelectedItem = None
-
+ self._Refresh(TYPESTREE, INSTANCESTREE, LIBRARYTREE)
+ self._Refresh(TITLE, TOOLBAR, FILEMENU, EDITMENU, DISPLAYMENU)
+
+
+#-------------------------------------------------------------------------------
+# General Functions
+#-------------------------------------------------------------------------------
+
+ ## Call PLCOpenEditor refresh functions.
+ # @param elements List of elements to refresh.
+ def _Refresh(self, *elements):
+ for element in elements:
+ self.RefreshFunctions[element](self)
+
+ ## Callback function when AUINotebook Page closed with CloseButton
+ # @param event AUINotebook Event.
def OnPageClose(self, event):
+ # Get Selected Tab
selected = event.GetSelection()
if selected >= 0:
+ # Remove corresponding VariablePanel
if not self.Debug:
tagname = self.TabsOpened.GetPage(selected).GetTagName()
self.VariablePanelIndexer.RemoveVariablePanel(tagname)
+ # Refresh Tab selection
if self.TabsOpened.GetPageCount() > 0:
new_index = min(selected, self.TabsOpened.GetPageCount() - 1)
self.TabsOpened.SetSelection(new_index)
if not self.Debug:
tagname = self.TabsOpened.GetPage(new_index).GetTagName()
self.VariablePanelIndexer.ChangeVariablePanel(tagname)
- self.RefreshTitle()
- self.RefreshFileMenu()
- self.RefreshEditMenu()
- self.RefreshDisplayMenu()
- self.RefreshToolBar()
+ # Refresh all window elements that have changed
+ self._Refresh(TITLE, TOOLBAR, FILEMENU, EDITMENU, DISPLAYMENU)
wx.CallAfter(self.RefreshTabCtrlEvent)
event.Skip()
- def OnPageDragged(self, event):
- wx.CallAfter(self.RefreshTabCtrlEvent)
- event.Skip()
-
def GetCopyBuffer(self):
- return PLCOpenEditor.CopyBuffer
-
- def SetCopyBuffer(self, element):
- PLCOpenEditor.CopyBuffer = element
+ data = None
+ if wx.TheClipboard.Open():
+ dataobj = wx.TextDataObject()
+ if wx.TheClipboard.GetData(dataobj):
+ data = dataobj.GetText()
+ wx.TheClipboard.Close()
+ return data
+
+ def SetCopyBuffer(self, text):
+ if wx.TheClipboard.Open():
+ data = wx.TextDataObject()
+ data.SetText(text)
+ wx.TheClipboard.SetData(data)
+ wx.TheClipboard.Flush()
+ wx.TheClipboard.Close()
self.RefreshEditMenu()
def GetDrawingMode(self):
return self.DrawingMode
def RefreshTitle(self):
- name = "PLCOpenEditor"
+ name = _("PLCOpenEditor")
if self.Debug:
- name += " (Debug)"
+ name += _(" (Debug)")
if self.Controler.HasOpenedProject() > 0:
self.SetTitle("%s - %s"%(name, self.Controler.GetFilename()))
else:
@@ -721,12 +857,8 @@
new_values["creationDateTime"] = old_values["creationDateTime"]
if new_values != old_values:
self.Controler.SetProjectProperties(None, new_values)
- self.RefreshTitle()
- self.RefreshFileMenu()
- self.RefreshEditMenu()
- self.RefreshDisplayMenu()
- self.RefreshTypesTree()
- self.RefreshScaling()
+ self._Refresh(TITLE, TOOLBAR, FILEMENU, EDITMENU, DISPLAYMENU,
+ TYPESTREE, INSTANCESTREE, SCALING)
dialog.Destroy()
def OnCloseFrame(self, event):
@@ -734,83 +866,106 @@
self.AUIManager.UnInit()
self._onclose()
event.Skip()
- elif not self.Controler.ProjectIsSaved():
- dialog = wx.MessageDialog(self, "There are changes, do you want to save?", "Close Application", wx.YES_NO|wx.CANCEL|wx.ICON_QUESTION)
- answer = dialog.ShowModal()
- dialog.Destroy()
- if answer == wx.ID_YES:
- self.SaveProject()
- event.Skip()
- elif answer == wx.ID_NO:
- self.Controler.Reset()
- self.AUIManager.UnInit()
- event.Skip()
+ elif self.CheckSaveBeforeClosing():
+ event.Skip()
+ else:
+ event.Veto()
+
+#-------------------------------------------------------------------------------
+# Notebook Unified Functions
+#-------------------------------------------------------------------------------
+
+ ## Function that generate bitmap for
+ # for wx.aui.AUINotebook.
+ # @param window Panel to display in tab.
+ # @param text title for the tab ctrl.
+ def GenerateBitmap(self, icon1_name, icon2_name = None):
+ # Find index of bitmap if already created
+ index = self.TabsImageListIndexes.get((icon1_name, icon2_name), None)
+ # Return index or bitmap if found
+ if index is not None:
+ if USE_AUI:
+ return self.TabsImageList.GetBitmap(index)
else:
- event.Veto()
- else:
- event.Skip()
-
-#-------------------------------------------------------------------------------
-# Notebook Unified Functions
-#-------------------------------------------------------------------------------
-
- def GenerateBitmap(self, icon1_name, icon2_name = None):
- if not USE_AUI:
- index = self.TabsImageListIndexes.get((icon1_name, icon2_name), None)
- if index is not None:
return index
if icon2_name is None:
+ # Bitmap with only one icon
tmp_bitmap = wx.Bitmap(os.path.join(CWD, 'Images', '%s.png'%icon1_name))
else:
+ # Bitmap with two icon
icon1 = wx.Bitmap(os.path.join(CWD, 'Images', '%s.png'%icon1_name))
icon2 = wx.Bitmap(os.path.join(CWD, 'Images', '%s.png'%icon2_name))
+ # Calculate bitmap size
width = icon1.GetWidth() + icon2.GetWidth() - 1
height = max(icon1.GetHeight(), icon2.GetHeight())
+ # Create bitmap with both icons
tmp_bitmap = wx.EmptyBitmap(width, height)
dc = wx.MemoryDC()
dc.SelectObject(tmp_bitmap)
dc.Clear()
dc.DrawBitmap(icon1, 0, 0)
dc.DrawBitmap(icon2, icon1.GetWidth() - 1, 0)
+ # Store bitmap in ImageList
+ index = self.TabsImageList.Add(tmp_bitmap)
+ # Save bitmap index in ImageList in dictionary
+ self.TabsImageListIndexes[(icon1_name, icon2_name)] = index
if USE_AUI:
return tmp_bitmap
else:
- index = self.TabsImageList.Add(tmp_bitmap)
- self.TabsImageListIndexes[(icon1_name, icon2_name)] = index
return index
+ ## Function that add a tab in Notebook, calling refresh for tab DClick event
+ # for wx.aui.AUINotebook.
+ # @param window Panel to display in tab.
+ # @param text title for the tab ctrl.
def AddPage(self, window, text):
self.TabsOpened.AddPage(window, text)
self.RefreshTabCtrlEvent()
- def RefreshTabCtrlEvent(self):
- if USE_AUI:
- auitabctrl = []
- for child in self.TabsOpened.GetChildren():
- if isinstance(child, wx.aui.AuiTabCtrl):
- auitabctrl.append(child)
- if child not in self.AuiTabCtrl:
- child.Bind(wx.EVT_LEFT_DCLICK, self.GetTabsOpenedDClickFunction(child))
- self.AuiTabCtrl = auitabctrl
- if self.TabsOpened.GetPageCount() == 0:
- pane = self.AUIManager.GetPane(self.TabsOpened)
- if pane.IsMaximized():
- self.AUIManager.RestorePane(pane)
- self.AUIManager.Update()
-
+ ## Function that fix difference in deleting all tabs between
+ # wx.Notebook and wx.aui.AUINotebook.
def DeleteAllPages(self):
if USE_AUI:
for idx in xrange(self.TabsOpened.GetPageCount()):
self.TabsOpened.DeletePage(0)
else:
self.TabsOpened.DeleteAllPages()
-
+ self.RefreshTabCtrlEvent()
+
+ ## Function that fix difference in setting picture on tab between
+ # wx.Notebook and wx.aui.AUINotebook.
+ # @param idx Tab index.
+ # @param bitmap wx.Bitmap to define on tab.
+ # @return True if operation succeeded
def SetPageBitmap(self, idx, bitmap):
if USE_AUI:
return self.TabsOpened.SetPageBitmap(idx, bitmap)
else:
return self.TabsOpened.SetPageImage(idx, bitmap)
+#-------------------------------------------------------------------------------
+# Dialog Message Functions
+#-------------------------------------------------------------------------------
+
+ ## Function displaying an Error dialog in PLCOpenEditor.
+ # @param message The message to display.
+ def ShowErrorMessage(self, message):
+ dialog = wx.MessageDialog(self, message, _("Error"), wx.OK|wx.ICON_ERROR)
+ dialog.ShowModal()
+ dialog.Destroy()
+
+ ## Function displaying an Error dialog in PLCOpenEditor.
+ # @return False if closing cancelled.
+ def CheckSaveBeforeClosing(self):
+ if not self.Controler.ProjectIsSaved():
+ dialog = wx.MessageDialog(self, _("There are changes, do you want to save?"), _("Close Application"), wx.YES_NO|wx.CANCEL|wx.ICON_QUESTION)
+ answer = dialog.ShowModal()
+ dialog.Destroy()
+ if answer == wx.ID_YES:
+ self.SaveProject()
+ elif answer == wx.ID_CANCEL:
+ return False
+ return True
#-------------------------------------------------------------------------------
# File Menu Functions
@@ -861,42 +1016,27 @@
if dialog.ShowModal() == wx.ID_OK:
properties = dialog.GetValues()
self.Controler.CreateNewProject(properties)
- self.RefreshTitle()
- self.RefreshFileMenu()
- self.RefreshEditMenu()
- self.RefreshTypesTree()
- self.RefreshInstancesTree()
- self.RefreshLibraryTree()
+ self._Refresh(TITLE, FILEMENU, EDITMENU, TYPESTREE, INSTANCESTREE,
+ LIBRARYTREE)
event.Skip()
def OnOpenProjectMenu(self, event):
- if not self.Controler.ProjectIsSaved():
- dialog = wx.MessageDialog(self, "There are changes, do you want to save?", "Close Application", wx.YES_NO|wx.CANCEL|wx.ICON_QUESTION)
- answer = dialog.ShowModal()
- dialog.Destroy()
- if answer == wx.ID_YES:
- self.SaveProject()
- elif answer == wx.ID_CANCEL:
- return
+ if not self.CheckSaveBeforeClosing():
+ return
filepath = self.Controler.GetFilePath()
if filepath != "":
directory = os.path.dirname(filepath)
else:
directory = os.getcwd()
- dialog = wx.FileDialog(self, "Choose a file", directory, "", "PLCOpen files (*.xml)|*.xml|All files|*.*", wx.OPEN)
+ dialog = wx.FileDialog(self, _("Choose a file"), directory, "", _("PLCOpen files (*.xml)|*.xml|All files|*.*"), wx.OPEN)
if dialog.ShowModal() == wx.ID_OK:
filepath = dialog.GetPath()
if os.path.isfile(filepath):
self.DeleteAllPages()
self.VariablePanelIndexer.RemoveAllPanels()
self.Controler.OpenXMLFile(filepath)
- self.RefreshTypesTree()
- self.RefreshInstancesTree()
- self.RefreshLibraryTree()
- self.RefreshTitle()
- self.RefreshFileMenu()
- self.RefreshEditMenu()
- self.RefreshToolBar()
+ self._Refresh(TYPESTREE, INSTANCESTREE, LIBRARYTREE)
+ self._Refresh(TITLE, TOOLBAR, FILEMENU, EDITMENU)
dialog.Destroy()
event.Skip()
@@ -913,29 +1053,18 @@
if not self.Debug:
tagname = self.TabsOpened.GetPage(new_index).GetTagName()
self.VariablePanelIndexer.ChangeVariablePanel(tagname)
- self.RefreshFileMenu()
- self.RefreshEditMenu()
- self.RefreshToolBar()
+ self._Refresh(TOOLBAR, FILEMENU, EDITMENU)
event.Skip()
def OnCloseProjectMenu(self, event):
- if not self.Controler.ProjectIsSaved():
- dialog = wx.MessageDialog(self, "There are changes, do you want to save?", "Close Application", wx.YES_NO|wx.CANCEL|wx.ICON_QUESTION)
- answer = dialog.ShowModal()
- dialog.Destroy()
- if answer == wx.ID_YES:
- self.SaveProject()
- elif answer == wx.ID_CANCEL:
- return
+ if not self.CheckSaveBeforeClosing():
+ return
self.DeleteAllPages()
self.VariablePanelIndexer.RemoveAllPanels()
self.TypesTree.DeleteAllItems()
self.InstancesTree.DeleteAllItems()
self.Controler.Reset()
- self.RefreshTitle()
- self.RefreshFileMenu()
- self.RefreshEditMenu()
- self.RefreshToolBar()
+ self._Refresh(TITLE, TOOLBAR, FILEMENU, EDITMENU)
event.Skip()
def OnSaveProjectMenu(self, event):
@@ -950,23 +1079,23 @@
event.Skip()
def OnGenerateProgramMenu(self, event):
- dialog = wx.FileDialog(self, "Choose a file", os.getcwd(), self.Controler.GetProgramFilePath(), "ST files (*.st)|*.st|All files|*.*", wx.SAVE|wx.CHANGE_DIR)
+ dialog = wx.FileDialog(self, _("Choose a file"), os.getcwd(), self.Controler.GetProgramFilePath(), _("ST files (*.st)|*.st|All files|*.*"), wx.SAVE|wx.CHANGE_DIR)
if dialog.ShowModal() == wx.ID_OK:
filepath = dialog.GetPath()
message_text = ""
- header, icon = "Done", wx.ICON_INFORMATION
+ header, icon = _("Done"), wx.ICON_INFORMATION
if os.path.isdir(os.path.dirname(filepath)):
program, errors, warnings = self.Controler.GenerateProgram(filepath)
- message_text += "".join(["warning: %s\n" for warning in warnings])
+ message_text += "".join([_("warning: %s\n") for warning in warnings])
if len(errors) > 0:
- message_text += "".join(["error: %s\n" for warning in warnings])
- message_text += "Can't generate program to file %s!"%filepath
- header, icon = "Error", wx.ICON_ERROR
+ message_text += "".join([_("error: %s\n") for warning in warnings])
+ message_text += _("Can't generate program to file %s!")%filepath
+ header, icon = _("Error"), wx.ICON_ERROR
else:
- message_text += "Program was successfully generated!"
+ message_text += _("Program was successfully generated!")
else:
- message_text += "%s is not a valid folder!"%os.path.dirname(filepath)
- header, icon = "Error", wx.ICON_ERROR
+ message_text += _("\"%s\" is not a valid folder!")%os.path.dirname(filepath)
+ header, icon = _("Error"), wx.ICON_ERROR
message = wx.MessageDialog(self, message_text, header, wx.OK|icon)
message.ShowModal()
message.Destroy()
@@ -986,19 +1115,15 @@
directory, filename = os.path.split(filepath)
else:
directory, filename = os.getcwd(), "%(projectName)s.xml"%self.Controler.GetProjectProperties(self.Debug)
- dialog = wx.FileDialog(self, "Choose a file", directory, filename, "PLCOpen files (*.xml)|*.xml|All files|*.*", wx.SAVE|wx.OVERWRITE_PROMPT)
+ dialog = wx.FileDialog(self, _("Choose a file"), directory, filename, _("PLCOpen files (*.xml)|*.xml|All files|*.*"), wx.SAVE|wx.OVERWRITE_PROMPT)
if dialog.ShowModal() == wx.ID_OK:
filepath = dialog.GetPath()
if os.path.isdir(os.path.dirname(filepath)):
result = self.Controler.SaveXMLFile(filepath)
if not result:
- message = wx.MessageDialog(self, "Can't save project to file %s!"%filepath, "Error", wx.OK|wx.ICON_ERROR)
- message.ShowModal()
- message.Destroy()
+ self.ShowErrorMessage(_("Can't save project to file %s!")%filepath)
else:
- message = wx.MessageDialog(self, "%s is not a valid folder!"%os.path.dirname(filepath), "Error", wx.OK|wx.ICON_ERROR)
- message.ShowModal()
- message.Destroy()
+ self.ShowErrorMessage(_("\"%s\" is not a valid folder!")%os.path.dirname(filepath))
self.RefreshTitle()
dialog.Destroy()
@@ -1022,7 +1147,7 @@
preview = wx.PrintPreview(printout, printout2, data)
if preview.Ok():
- preview_frame = wx.PreviewFrame(preview, self, "Print preview")
+ preview_frame = wx.PreviewFrame(preview, self, _("Print preview"))
preview_frame.Initialize()
@@ -1041,7 +1166,7 @@
printout = GraphicPrintout(self.TabsOpened.GetPage(selected), page_size, margins)
if not printer.Print(self, printout, True):
- wx.MessageBox("There was a problem printing.\nPerhaps your current printer is not set correctly?", "Printing", wx.OK)
+ self.ShowErrorMessage(_("There was a problem printing.\nPerhaps your current printer is not set correctly?"))
printout.Destroy()
event.Skip()
@@ -1071,7 +1196,7 @@
if self.TabsOpened.GetPageCount() > 0:
self.EditMenu.Enable(wx.ID_CUT, True)
self.EditMenu.Enable(wx.ID_COPY, True)
- if self.CopyBuffer is not None:
+ if self.GetCopyBuffer() is not None:
self.EditMenu.Enable(wx.ID_PASTE, True)
else:
self.EditMenu.Enable(wx.ID_PASTE, False)
@@ -1091,8 +1216,7 @@
self.EditMenu.Enable(wx.ID_ADD, False)
self.EditMenu.Enable(wx.ID_DELETE, False)
- def OnUndoMenu(self, event):
- self.Controler.LoadPrevious()
+ def CloseTabsWithoutModel(self):
idxs = range(self.TabsOpened.GetPageCount())
idxs.reverse()
for idx in idxs:
@@ -1100,70 +1224,32 @@
if self.Controler.GetEditedElement(tagname, self.Debug) is None:
self.VariablePanelIndexer.RemoveVariablePanel(tagname)
self.TabsOpened.DeletePage(idx)
- selected = self.TabsOpened.GetSelection()
- if selected != -1:
- window = self.TabsOpened.GetPage(selected)
- window.RefreshView()
- self.VariablePanelIndexer.RefreshVariablePanel(window.GetTagName())
- self.RefreshTitle()
- self.RefreshEditMenu()
- self.RefreshTypesTree()
- self.RefreshInstancesTree()
- self.RefreshLibraryTree()
- self.RefreshScaling()
+
+ def OnUndoMenu(self, event):
+ self.Controler.LoadPrevious()
+ self.CloseTabsWithoutModel()
+ self.RefreshEditor()
+ self._Refresh(TITLE, EDITMENU, TYPESTREE, INSTANCESTREE, LIBRARYTREE,
+ SCALING)
event.Skip()
def OnRedoMenu(self, event):
self.Controler.LoadNext()
- idxs = range(self.TabsOpened.GetPageCount())
- idxs.reverse()
- for idx in idxs:
- tagname = self.TabsOpened.GetPage(idx).GetTagName()
- if self.Controler.GetEditedElement(tagname, self.Debug) is None:
- self.VariablePanelIndexer.RemoveVariablePanel(tagname)
- self.TabsOpened.DeletePage(idx)
- selected = self.TabsOpened.GetSelection()
- if selected != -1:
- window = self.TabsOpened.GetPage(selected)
- window.RefreshView()
- self.VariablePanelIndexer.RefreshVariablePanel(window.GetTagName())
- self.RefreshTitle()
- self.RefreshEditMenu()
- self.RefreshTypesTree()
- self.RefreshInstancesTree()
- self.RefreshLibraryTree()
- self.RefreshScaling()
- event.Skip()
-
+ self.CloseTabsWithoutModel()
+ self.RefreshEditor()
+ self._Refresh(TITLE, EDITMENU, TYPESTREE, INSTANCESTREE, LIBRARYTREE,
+ SCALING)
+ event.Skip()
+
def OnEnableUndoRedoMenu(self, event):
self.Controler.EnableProjectBuffer(event.IsChecked())
self.RefreshEditMenu()
event.Skip()
- def OnCutMenu(self, event):
- control = self.FindFocus()
- if isinstance(control, (Viewer, TextViewer)):
- control.Cut()
- elif isinstance(control, wx.TextCtrl):
- control.ProcessEvent(event)
- event.Skip()
-
- def OnCopyMenu(self, event):
- control = self.FindFocus()
- if isinstance(control, (Viewer, TextViewer)):
- control.Copy()
- elif isinstance(control, wx.TextCtrl):
- control.ProcessEvent(event)
- event.Skip()
-
- def OnPasteMenu(self, event):
- control = self.FindFocus()
- if isinstance(control, (Viewer, TextViewer)):
- control.Paste()
- elif isinstance(control, wx.TextCtrl):
- control.ProcessEvent(event)
- event.Skip()
-
+ OnCutMenu = GetShortcutKeyCallbackFunction("Cut")
+ OnCopyMenu = GetShortcutKeyCallbackFunction("Copy")
+ OnPasteMenu = GetShortcutKeyCallbackFunction("Paste")
+
def OnSelectAllMenu(self, event):
control = self.FindFocus()
if isinstance(control, (Viewer, TextViewer)):
@@ -1174,70 +1260,27 @@
control.SetMark(0, control.GetLastPosition() + 1)
event.Skip()
+ DeleteFunctions = {
+ ITEM_DATATYPE: GetDeleteElementFunction(PLCControler.ProjectRemoveDataType, check_function=PLCControler.DataTypeIsUsed),
+ ITEM_POU: GetDeleteElementFunction(PLCControler.ProjectRemovePou, check_function=PLCControler.PouIsUsed),
+ ITEM_TRANSITION: GetDeleteElementFunction(PLCControler.ProjectRemovePouTransition, ITEM_POU),
+ ITEM_ACTION: GetDeleteElementFunction(PLCControler.ProjectRemovePouAction, ITEM_POU),
+ ITEM_CONFIGURATION: GetDeleteElementFunction(PLCControler.ProjectRemoveConfiguration),
+ ITEM_RESOURCE: GetDeleteElementFunction(PLCControler.ProjectRemoveConfigurationResource, ITEM_CONFIGURATION)
+ }
+
def OnDeleteMenu(self, event):
window = self.FindFocus()
- if window == self.TypesTree:
+ if window == self.TypesTree or window is None:
selected = self.TypesTree.GetSelection()
if selected.IsOk():
type = self.TypesTree.GetPyData(selected)
- tagname = ""
- if type == ITEM_DATATYPE:
- name = self.TypesTree.GetItemText(selected)
- if not self.Controler.DataTypeIsUsed(name, self.Debug):
- self.Controler.ProjectRemoveDataType(name)
- tagname = self.Controler.ComputeDataTypeName(name)
- else:
- message = wx.MessageDialog(self, "\"%s\" is used by one or more POUs. It can't be removed!"%name, "Error", wx.OK|wx.ICON_ERROR)
- message.ShowModal()
- message.Destroy()
- elif type == ITEM_POU:
- name = self.TypesTree.GetItemText(selected)
- if not self.Controler.PouIsUsed(name, self.Debug):
- self.Controler.ProjectRemovePou(name)
- tagname = self.Controler.ComputePouName(name)
- else:
- message = wx.MessageDialog(self, "\"%s\" is used by one or more POUs. It can't be removed!"%name, "Error", wx.OK|wx.ICON_ERROR)
- message.ShowModal()
- message.Destroy()
- elif type in [ITEM_TRANSITION, ITEM_ACTION]:
- item = self.TypesTree.GetItemParent(selected)
- item_type = self.TypesTree.GetPyData(item)
- while item_type != ITEM_POU:
- item = self.TypesTree.GetItemParent(item)
- item_type = self.TypesTree.GetPyData(item)
- pou_name = self.TypesTree.GetItemText(item)
- if type == ITEM_TRANSITION:
- transition = self.TypesTree.GetItemText(selected)
- self.Controler.ProjectRemovePouTransition(pou_name, transition)
- tagname = self.Controler.ComputePouTransitionName(pou_name, transition)
- elif type == ITEM_ACTION:
- action = self.TypesTree.GetItemText(selected)
- self.Controler.ProjectRemovePouAction(pou_name, action)
- tagname = self.Controler.ComputePouActionName(pou_name, action)
- elif type == ITEM_CONFIGURATION:
- name = self.TypesTree.GetItemText(selected)
- self.Controler.ProjectRemoveConfiguration(name)
- tagname = self.Controler.ComputeConfigurationName(name)
- elif type == ITEM_RESOURCE:
- resource = self.TypesTree.GetItemText(selected)
- item = self.TypesTree.GetItemParent(selected)
- item_type = self.TypesTree.GetPyData(item)
- while item_type != ITEM_CONFIGURATION:
- item = self.TypesTree.GetItemParent(item)
- item_type = self.TypesTree.GetPyData(item)
- config_name = self.TypesTree.GetItemText(item)
- self.Controler.ProjectRemoveConfigurationResource(config_name, resource)
- tagname = self.Controler.ComputeConfigurationResourceName(config_name, selected)
- idx = self.IsOpened(tagname)
- if idx is not None:
- self.VariablePanelIndexer.RemoveVariablePanel(tagname)
- self.TabsOpened.DeletePage(idx)
- self.RefreshTitle()
- self.RefreshEditMenu()
- self.RefreshTypesTree()
- self.RefreshInstancesTree()
- self.RefreshLibraryTree()
- self.RefreshToolBar()
+ function = self.DeleteFunctions.get(type, None)
+ if function is not None:
+ function(self, selected)
+ self.CloseTabsWithoutModel()
+ self._Refresh(TITLE, TOOLBAR, EDITMENU, TYPESTREE,
+ INSTANCESTREE, LIBRARYTREE)
elif isinstance(window, (Viewer, TextViewer)):
event = wx.KeyEvent(wx.EVT_CHAR._getEvtType())
event.m_keyCode = wx.WXK_DELETE
@@ -1277,12 +1320,7 @@
self.DisplayMenu.Enable(wx.ID_ZOOM_FIT, False)
def OnRefreshMenu(self, event):
- selected = self.TabsOpened.GetSelection()
- if selected != -1:
- window = self.TabsOpened.GetPage(selected)
- window.RefreshView()
- if not self.Debug:
- self.VariablePanelIndexer.RefreshVariablePanel(window.GetTagName())
+ self.RefreshEditor(not self.Debug)
event.Skip()
def OnClearErrorsMenu(self, event):
@@ -1305,6 +1343,25 @@
# Project Editor Panels Management Functions
#-------------------------------------------------------------------------------
+ def OnPageDragged(self, event):
+ wx.CallAfter(self.RefreshTabCtrlEvent)
+ event.Skip()
+
+ def RefreshTabCtrlEvent(self):
+ if USE_AUI:
+ auitabctrl = []
+ for child in self.TabsOpened.GetChildren():
+ if isinstance(child, wx.aui.AuiTabCtrl):
+ auitabctrl.append(child)
+ if child not in self.AuiTabCtrl:
+ child.Bind(wx.EVT_LEFT_DCLICK, self.GetTabsOpenedDClickFunction(child))
+ self.AuiTabCtrl = auitabctrl
+ if self.TabsOpened.GetPageCount() == 0:
+ pane = self.AUIManager.GetPane(self.TabsOpened)
+ if pane.IsMaximized():
+ self.AUIManager.RestorePane(pane)
+ self.AUIManager.Update()
+
def OnPouSelectedChanged(self, event):
old_selected = self.TabsOpened.GetSelection()
if old_selected >= 0:
@@ -1322,10 +1379,7 @@
window.RefreshView()
if not self.Debug:
self.VariablePanelIndexer.ChangeVariablePanel(window.GetTagName())
- self.RefreshFileMenu()
- self.RefreshEditMenu()
- self.RefreshDisplayMenu()
- self.RefreshToolBar()
+ self._Refresh(FILEMENU, EDITMENU, DISPLAYMENU, TOOLBAR)
event.Skip()
def RefreshEditor(self, variablepanel = True):
@@ -1402,9 +1456,13 @@
self.GenerateTypesTreeBranch(root, infos)
self.TypesTree.Expand(root)
+ def ResetSelectedItem(self):
+ self.SelectedItem = None
+
def GenerateTypesTreeBranch(self, root, infos, topology=False):
to_delete = []
- self.TypesTree.SetItemText(root, infos["name"])
+ item_name = infos["name"]
+ self.TypesTree.SetItemText(root, _(item_name))
self.TypesTree.SetPyData(root, infos["type"])
if infos.get("tagname", None) in self.Errors:
self.TypesTree.SetItemBackgroundColour(root, wx.Colour(255, 255, 0))
@@ -1413,9 +1471,9 @@
self.TypesTree.SetItemBackgroundColour(root, wx.WHITE)
self.TypesTree.SetItemTextColour(root, wx.BLACK)
if infos["type"] == ITEM_POU:
- self.TypesTree.SetItemImage(root, self.TypesTreeImageDict[self.Controler.GetPouBodyType(infos["name"], self.Debug)])
- else:
- self.TypesTree.SetItemImage(root, self.TypesTreeImageDict[infos["type"]])
+ self.TypesTree.SetItemImage(root, self.TreeImageDict[self.Controler.GetPouBodyType(infos["name"], self.Debug)])
+ else:
+ self.TypesTree.SetItemImage(root, self.TreeImageDict[infos["type"]])
if wx.VERSION >= (2, 6, 0):
item, root_cookie = self.TypesTree.GetFirstChild(root)
@@ -1499,9 +1557,9 @@
new_name = event.GetLabel()
if new_name != "":
if not TestIdentifier(new_name):
- message = "\"%s\" is not a valid identifier!"%new_name
+ message = _("\"%s\" is not a valid identifier!")%new_name
elif new_name.upper() in IEC_KEYWORDS:
- message = "\"%s\" is a keyword. It can't be used!"%new_name
+ message = _("\"%s\" is a keyword. It can't be used!")%new_name
else:
item = event.GetItem()
old_name = self.TypesTree.GetItemText(item)
@@ -1510,7 +1568,7 @@
self.Controler.SetProjectProperties(name = new_name)
elif itemtype == ITEM_DATATYPE:
if new_name.upper() in [name.upper() for name in self.Controler.GetProjectDataTypeNames(self.Debug) if name != old_name]:
- message = "\"%s\" data type already exists!"%new_name
+ message = _("\"%s\" data type already exists!")%new_name
abort = True
if not abort:
self.Controler.ChangeDataTypeName(old_name, new_name)
@@ -1519,10 +1577,10 @@
self.RefreshPageTitles()
elif itemtype == ITEM_POU:
if new_name.upper() in [name.upper() for name in self.Controler.GetProjectPouNames(self.Debug) if name != old_name]:
- message = "\"%s\" pou already exists!"%new_name
+ message = _("\"%s\" pou already exists!")%new_name
abort = True
elif new_name.upper() in [name.upper() for name in self.Controler.GetProjectPouVariables(debug = self.Debug)]:
- messageDialog = wx.MessageDialog(self, "A variable is defined with \"%s\" as name. It can generate a conflict. Do you wish to continue?"%new_name, "Error", wx.YES_NO|wx.ICON_QUESTION)
+ messageDialog = wx.MessageDialog(self, _("A pou has an element with \"%s\" as name. It can generate a conflict. Do you wish to continue?")%new_name, _("Error"), wx.YES_NO|wx.ICON_QUESTION)
if messageDialog.ShowModal() == wx.ID_NO:
abort = True
messageDialog.Destroy()
@@ -1533,32 +1591,22 @@
self.RefreshLibraryTree()
self.RefreshPageTitles()
elif itemtype == ITEM_TRANSITION:
- parent = self.TypesTree.GetItemParent(item)
- parent_type = self.TypesTree.GetPyData(parent)
- while parent_type != ITEM_POU:
- parent = self.TypesTree.GetItemParent(parent)
- parent_type = self.TypesTree.GetPyData(parent)
- pou_name = self.TypesTree.GetItemText(parent)
+ pou_name = GetParentName(self.TypesTree, item, ITEM_POU)
if new_name.upper() in [name.upper() for name in self.Controler.GetProjectPouNames(self.Debug)]:
- message = "A pou with \"%s\" as name exists!"%new_name
+ message = _("A pou with \"%s\" as name exists!")%new_name
elif new_name.upper() in [name.upper() for name in self.Controler.GetProjectPouVariables(pou_name, self.Debug) if name != old_name]:
- message = "A variable with \"%s\" as name already exists in this pou!"%new_name
+ message = _("A variable with \"%s\" as name already exists in this pou!")%new_name
else:
self.Controler.ChangePouTransitionName(pou_name, old_name, new_name)
self.RefreshEditorNames(self.Controler.ComputePouTransitionName(pou_name, old_name),
self.Controler.ComputePouTransitionName(pou_name, new_name))
self.RefreshPageTitles()
elif itemtype == ITEM_ACTION:
- parent = self.TypesTree.GetItemParent(item)
- parent_type = self.TypesTree.GetPyData(parent)
- while parent_type != ITEM_POU:
- parent = self.TypesTree.GetItemParent(parent)
- parent_type = self.TypesTree.GetPyData(parent)
- pou_name = self.TypesTree.GetItemText(parent)
+ pou_name = GetParentName(self.TypesTree, item, ITEM_POU)
if new_name.upper() in [name.upper() for name in self.Controler.GetProjectPouNames(self.Debug)]:
- message = "A pou with \"%s\" as name exists!"%new_name
+ message = _("A pou with \"%s\" as name exists!")%new_name
elif new_name.upper() in [name.upper() for name in self.Controler.GetProjectPouVariables(pou_name, self.Debug) if name != old_name]:
- message = "A variable with \"%s\" as name already exists in this pou!"%new_name
+ message = _("A variable with \"%s\" as name already exists in this pou!")%new_name
else:
self.Controler.ChangePouActionName(pou_name, old_name, new_name)
self.RefreshEditorNames(self.Controler.ComputePouActionName(pou_name, old_name),
@@ -1566,15 +1614,15 @@
self.RefreshPageTitles()
elif itemtype == ITEM_CONFIGURATION:
if new_name.upper() in [name.upper() for name in self.Controler.GetProjectConfigNames(self.Debug) if name != old_name]:
- message = "\"%s\" config already exists!"%new_name
+ message = _("\"%s\" config already exists!")%new_name
abort = True
elif new_name.upper() in [name.upper() for name in self.Controler.GetProjectPouNames(self.Debug)]:
- messageDialog = wx.MessageDialog(self, "A pou is defined with \"%s\" as name. It can generate a conflict. Do you wish to continue?"%new_name, "Error", wx.YES_NO|wx.ICON_QUESTION)
+ messageDialog = wx.MessageDialog(self, _("A pou is defined with \"%s\" as name. It can generate a conflict. Do you wish to continue?")%new_name, _("Error"), wx.YES_NO|wx.ICON_QUESTION)
if messageDialog.ShowModal() == wx.ID_NO:
abort = True
messageDialog.Destroy()
elif new_name.upper() in [name.upper() for name in self.Controler.GetProjectPouVariables(debug = self.Debug)]:
- messageDialog = wx.MessageDialog(self, "A variable is defined with \"%s\" as name. It can generate a conflict. Do you wish to continue?"%new_name, "Error", wx.YES_NO|wx.ICON_QUESTION)
+ messageDialog = wx.MessageDialog(self, _("A pou has an element with \"%s\" as name. It can generate a conflict. Do you wish to continue?")%new_name, _("Error"), wx.YES_NO|wx.ICON_QUESTION)
if messageDialog.ShowModal() == wx.ID_NO:
abort = True
messageDialog.Destroy()
@@ -1584,22 +1632,17 @@
self.Controler.ComputeConfigurationName(new_name))
self.RefreshPageTitles()
elif itemtype == ITEM_RESOURCE:
- parent = self.TypesTree.GetItemParent(item)
- parent_type = self.TypesTree.GetPyData(parent)
- while parent_type != ITEM_CONFIGURATION:
- parent = self.TypesTree.GetItemParent(parent)
- parent_type = self.TypesTree.GetPyData(parent)
- config_name = self.TypesTree.GetItemText(parent)
+ config_name = GetParentName(self.TypesTree, item, ITEM_CONFIGURATION)
if new_name.upper() in [name.upper() for name in self.Controler.GetProjectConfigNames(self.Debug)]:
- message = "\"%s\" config already exists!"%new_name
+ message = _("\"%s\" config already exists!")%new_name
abort = True
elif new_name.upper() in [name.upper() for name in self.Controler.GetProjectPouNames(self.Debug)]:
- messageDialog = wx.MessageDialog(self, "A pou is defined with \"%s\" as name. It can generate a conflict. Do you wish to continue?"%new_name, "Error", wx.YES_NO|wx.ICON_QUESTION)
+ messageDialog = wx.MessageDialog(self, _("A pou is defined with \"%s\" as name. It can generate a conflict. Do you wish to continue?")%new_name, _("Error"), wx.YES_NO|wx.ICON_QUESTION)
if messageDialog.ShowModal() == wx.ID_NO:
abort = True
messageDialog.Destroy()
elif new_name.upper() in [name.upper() for name in self.Controler.GetProjectPouVariables(debug = self.Debug)]:
- messageDialog = wx.MessageDialog(self, "A variable is defined with \"%s\" as name. It can generate a conflict. Do you wish to continue?"%new_name, "Error", wx.YES_NO|wx.ICON_QUESTION)
+ messageDialog = wx.MessageDialog(self, _("A pou has an element with \"%s\" as name. It can generate a conflict. Do you wish to continue?")%new_name, _("Error"), wx.YES_NO|wx.ICON_QUESTION)
if messageDialog.ShowModal() == wx.ID_NO:
abort = True
messageDialog.Destroy()
@@ -1610,25 +1653,21 @@
self.RefreshPageTitles()
if message or abort:
if message:
- messageDialog = wx.MessageDialog(self, message, "Error", wx.OK|wx.ICON_ERROR)
- messageDialog.ShowModal()
- messageDialog.Destroy()
+ self.ShowErrorMessage(message)
item = event.GetItem()
wx.CallAfter(self.TypesTree.EditLabel, item)
event.Veto()
else:
wx.CallAfter(self.RefreshTypesTree)
self.RefreshEditor()
- self.RefreshFileMenu()
- self.RefreshEditMenu()
- self.RefreshTitle()
+ self._Refresh(TITLE, FILEMENU, EDITMENU)
event.Skip()
def OnTypesTreeItemActivated(self, event):
selected = event.GetItem()
name = self.TypesTree.GetItemText(selected)
data = self.TypesTree.GetPyData(selected)
- if name == "Properties":
+ if UNEDITABLE_NAMES_DICT.get(name, name) == "Properties":
self.ShowProperties()
if data == ITEM_DATATYPE:
self.EditProjectElement(data, self.Controler.ComputeDataTypeName(name))
@@ -1637,20 +1676,10 @@
elif data == ITEM_CONFIGURATION:
self.EditProjectElement(data, self.Controler.ComputeConfigurationName(name))
elif data == ITEM_RESOURCE:
- item = self.TypesTree.GetItemParent(selected)
- item_type = self.TypesTree.GetPyData(item)
- while item_type != ITEM_CONFIGURATION:
- item = self.TypesTree.GetItemParent(item)
- item_type = self.TypesTree.GetPyData(item)
- config_name = self.TypesTree.GetItemText(item)
+ config_name = GetParentName(self.TypesTree, selected, ITEM_CONFIGURATION)
self.EditProjectElement(data, self.Controler.ComputeConfigurationResourceName(config_name, name))
elif data in [ITEM_TRANSITION, ITEM_ACTION]:
- item = self.TypesTree.GetItemParent(selected)
- item_type = self.TypesTree.GetPyData(item)
- while item_type != ITEM_POU:
- item = self.TypesTree.GetItemParent(item)
- item_type = self.TypesTree.GetPyData(item)
- pou_name = self.TypesTree.GetItemText(item)
+ pou_name = GetParentName(self.TypesTree, selected, ITEM_POU)
if data == ITEM_TRANSITION:
tagname = self.Controler.ComputePouTransitionName(pou_name, name)
elif data == ITEM_ACTION:
@@ -1668,20 +1697,10 @@
elif data == ITEM_CONFIGURATION:
self.EditProjectElement(data, self.Controler.ComputeConfigurationName(name), True)
elif data == ITEM_RESOURCE:
- item = self.TypesTree.GetItemParent(select_item)
- item_type = self.TypesTree.GetPyData(item)
- while item_type != ITEM_CONFIGURATION:
- item = self.TypesTree.GetItemParent(item)
- item_type = self.TypesTree.GetPyData(item)
- config_name = self.TypesTree.GetItemText(item)
+ config_name = GetParentName(self.TypesTree, select_item, ITEM_CONFIGURATION)
self.EditProjectElement(data, self.Controler.ComputeConfigurationResourceName(config_name, name), True)
elif data in [ITEM_TRANSITION, ITEM_ACTION]:
- item = self.TypesTree.GetItemParent(select_item)
- item_type = self.TypesTree.GetPyData(item)
- while item_type != ITEM_POU:
- item = self.TypesTree.GetItemParent(item)
- item_type = self.TypesTree.GetPyData(item)
- pou_name = self.TypesTree.GetItemText(item)
+ pou_name = GetParentName(self.TypesTree, select_item, ITEM_POU)
if data == ITEM_TRANSITION:
tagname = self.Controler.ComputePouTransitionName(pou_name, name)
elif data == ITEM_ACTION:
@@ -1714,12 +1733,9 @@
if old_selected >= 0:
self.TabsOpened.GetPage(old_selected).ResetBuffer()
self.TabsOpened.SetSelection(openedidx)
- self.TabsOpened.GetPage(openedidx).RefreshView()
self.VariablePanelIndexer.ChangeVariablePanel(tagname)
self.RefreshPageTitles()
- self.RefreshFileMenu()
- self.RefreshEditMenu()
- self.RefreshToolBar()
+ self._Refresh(FILEMENU, EDITMENU, TOOLBAR)
elif not onlyopened:
if elementtype == ITEM_CONFIGURATION:
new_window = ConfigurationEditor(self.TabsOpened, tagname, self, self.Controler)
@@ -1765,9 +1781,7 @@
self.TabsOpened.SetSelection(i)
window.SetFocus()
self.RefreshPageTitles()
- self.RefreshFileMenu()
- self.RefreshEditMenu()
- self.RefreshToolBar()
+ self._Refresh(FILEMENU, EDITMENU, TOOLBAR)
def OnTypesTreeRightUp(self, event):
if wx.Platform == '__WXMSW__':
@@ -1780,78 +1794,72 @@
menu = wx.Menu(title='')
if self.Controler.GetPouBodyType(name, self.Debug) == "SFC":
new_id = wx.NewId()
- AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Add Transition")
+ AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=_("Add Transition"))
self.Bind(wx.EVT_MENU, self.GenerateAddTransitionFunction(name), id=new_id)
new_id = wx.NewId()
- AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Add Action")
+ AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=_("Add Action"))
self.Bind(wx.EVT_MENU, self.GenerateAddActionFunction(name), id=new_id)
menu.AppendSeparator()
new_id = wx.NewId()
- AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Create A New POU From")
+ AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=_("Create a new POU from"))
self.Bind(wx.EVT_MENU, self.OnCreatePouFromMenu, id=new_id)
pou_type = self.Controler.GetPouType(name, self.Debug)
if pou_type in ["function", "functionBlock"]:
change_menu = wx.Menu(title='')
if pou_type == "function":
new_id = wx.NewId()
- AppendMenu(change_menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Function Block")
+ AppendMenu(change_menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=_("Function Block"))
self.Bind(wx.EVT_MENU, self.GenerateChangePouTypeFunction(name, "functionBlock"), id=new_id)
new_id = wx.NewId()
- AppendMenu(change_menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Program")
+ AppendMenu(change_menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=_("Program"))
self.Bind(wx.EVT_MENU, self.GenerateChangePouTypeFunction(name, "program"), id=new_id)
- menu.AppendMenu(wx.NewId(), "Change POU Type To", change_menu)
+ menu.AppendMenu(wx.NewId(), _("Change POU Type To"), change_menu)
new_id = wx.NewId()
- AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Rename")
- self.Bind(wx.EVT_MENU, lambda ev: self.OnRenamePouMenu(ev, item), id=new_id)
+ AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=_("Rename"))
+ self.Bind(wx.EVT_MENU, self.OnRenamePouMenu, id=new_id)
new_id = wx.NewId()
- AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Delete")
- self.Bind(wx.EVT_MENU, lambda ev: self.OnRemovePouMenu(ev, item), id=new_id)
+ AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=_("Delete"))
+ self.Bind(wx.EVT_MENU, self.OnDeleteMenu, id=new_id)
self.PopupMenu(menu)
elif type == ITEM_CONFIGURATION:
menu = wx.Menu(title='')
new_id = wx.NewId()
- AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Add Resource")
+ AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=_("Add Resource"))
self.Bind(wx.EVT_MENU, self.GenerateAddResourceFunction(name), id=new_id)
new_id = wx.NewId()
- AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Delete")
- self.Bind(wx.EVT_MENU, lambda ev: self.OnRemoveConfigurationMenu(ev, item), id=new_id)
+ AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=_("Delete"))
+ self.Bind(wx.EVT_MENU, self.OnDeleteMenu, id=new_id)
self.PopupMenu(menu)
elif type in [ITEM_DATATYPE, ITEM_TRANSITION, ITEM_ACTION, ITEM_RESOURCE]:
menu = wx.Menu(title='')
new_id = wx.NewId()
- AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Delete")
- if type == ITEM_DATATYPE:
- self.Bind(wx.EVT_MENU, lambda ev: self.OnRemoveDataTypeMenu(ev, item), id=new_id)
- elif type == ITEM_TRANSITION:
- self.Bind(wx.EVT_MENU, lambda ev: self.OnRemoveTransitionMenu(ev, item), id=new_id)
- elif type == ITEM_ACTION:
- self.Bind(wx.EVT_MENU, lambda ev: self.OnRemoveActionMenu(ev, item), id=new_id)
- elif type == ITEM_RESOURCE:
- self.Bind(wx.EVT_MENU, lambda ev: self.OnRemoveResourceMenu(ev, item), id=new_id)
+ AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=_("Delete"))
+ self.Bind(wx.EVT_MENU, self.OnDeleteMenu, id=new_id)
self.PopupMenu(menu)
elif type in ITEMS_UNEDITABLE:
+ name = UNEDITABLE_NAMES_DICT[name]
if name == "Data Types":
menu = wx.Menu(title='')
new_id = wx.NewId()
- AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Add DataType")
+ AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=_("Add DataType"))
self.Bind(wx.EVT_MENU, self.OnAddDataTypeMenu, id=new_id)
self.PopupMenu(menu)
elif name in ["Functions", "Function Blocks", "Programs"]:
menu = wx.Menu(title='')
new_id = wx.NewId()
- AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Add Pou")
+ AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=_("Add Pou"))
self.Bind(wx.EVT_MENU, self.GenerateAddPouFunction({"Functions" : "function", "Function Blocks" : "functionBlock", "Programs" : "program"}[name]), id=new_id)
self.PopupMenu(menu)
elif name == "Configurations":
menu = wx.Menu(title='')
new_id = wx.NewId()
- AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Add Configuration")
+ AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=_("Add Configuration"))
self.Bind(wx.EVT_MENU, self.OnAddConfigurationMenu, id=new_id)
self.PopupMenu(menu)
elif name == "Transitions":
menu = wx.Menu(title='')
new_id = wx.NewId()
- AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Add Transition")
+ AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=_("Add Transition"))
parent = self.TypesTree.GetItemParent(item)
parent_type = self.TypesTree.GetPyData(parent)
while parent_type != ITEM_POU:
@@ -1862,7 +1870,7 @@
elif name == "Actions":
menu = wx.Menu(title='')
new_id = wx.NewId()
- AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Add Action")
+ AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=_("Add Action"))
parent = self.TypesTree.GetItemParent(item)
parent_type = self.TypesTree.GetPyData(parent)
while parent_type != ITEM_POU:
@@ -1873,7 +1881,7 @@
elif name == "Resources":
menu = wx.Menu(title='')
new_id = wx.NewId()
- AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Add Resource")
+ AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=_("Add Resource"))
parent = self.TypesTree.GetItemParent(item)
parent_type = self.TypesTree.GetPyData(parent)
while parent_type != ITEM_CONFIGURATION:
@@ -1903,7 +1911,7 @@
else:
self.InstancesTree.SetItemText(root, infos["name"])
self.InstancesTree.SetPyData(root, (infos["type"], infos.get("tagname", None)))
- self.InstancesTree.SetItemImage(root, self.InstancesTreeImageDict[infos["type"]])
+ self.InstancesTree.SetItemImage(root, self.TreeImageDict[infos["type"]])
if wx.VERSION >= (2, 6, 0):
item, root_cookie = self.InstancesTree.GetFirstChild(root)
@@ -2017,10 +2025,10 @@
menu = wx.Menu(title='')
new_id = wx.NewId()
- AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Graphic Panel")
+ AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=_("Graphic Panel"))
self.Bind(wx.EVT_MENU, self.AddVariableGraphicFunction(var_path), id=new_id)
new_id = wx.NewId()
- AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="CSV Log")
+ AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=_("CSV Log"))
self.PopupMenu(menu)
event.Skip()
@@ -2066,7 +2074,7 @@
root = self.LibraryTree.GetRootItem()
if not root.IsOk():
if wx.Platform == '__WXMSW__':
- root = self.LibraryTree.AddRoot("Block Types")
+ root = self.LibraryTree.AddRoot(_("Block Types"))
self.LibraryTree.SetPyData(root, {"type" : CATEGORY})
else:
root = self.LibraryTree.AddRoot("")
@@ -2075,12 +2083,13 @@
else:
category_item, root_cookie = self.LibraryTree.GetFirstChild(root, 0)
for category in blocktypes:
+ category_name = category["name"]
if not category_item.IsOk():
- category_item = self.LibraryTree.AppendItem(root, category["name"])
+ category_item = self.LibraryTree.AppendItem(root, _(category_name))
if wx.Platform != '__WXMSW__':
category_item, root_cookie = self.LibraryTree.GetNextChild(root, root_cookie)
else:
- self.LibraryTree.SetItemText(category_item, category["name"])
+ self.LibraryTree.SetItemText(category_item, _(category_name))
self.LibraryTree.SetPyData(category_item, {"type" : CATEGORY})
if wx.VERSION >= (2, 6, 0):
blocktype_item, category_cookie = self.LibraryTree.GetFirstChild(category_item)
@@ -2113,7 +2122,8 @@
if pydata is not None and pydata["type"] != CATEGORY:
blocktype = self.Controler.GetBlockType(self.LibraryTree.GetItemText(selected), pydata["inputs"], debug = self.Debug)
if blocktype:
- self.LibraryComment.SetValue(blocktype["comment"])
+ comment = blocktype["comment"]
+ self.LibraryComment.SetValue(_(comment) + blocktype.get("usage", ""))
else:
self.LibraryComment.SetValue("")
else:
@@ -2346,7 +2356,7 @@
#-------------------------------------------------------------------------------
def OnAddDataTypeMenu(self, event):
- dialog = DataTypeDialog(self, "Add a new data type", "Please enter data type name", "", wx.OK|wx.CANCEL)
+ dialog = DataTypeDialog(self, _("Add a new data type"), _("Please enter data type name"), "", wx.OK|wx.CANCEL)
dialog.SetDataTypeNames(self.Controler.GetProjectDataTypeNames(self.Debug))
if dialog.ShowModal() == wx.ID_OK:
self.Controler.ProjectAddDataType(dialog.GetValue())
@@ -2403,7 +2413,7 @@
return OnAddActionMenu
def OnAddConfigurationMenu(self, event):
- dialog = ConfigurationNameDialog(self, "Please enter configuration name", "Add new configuration")
+ dialog = ConfigurationNameDialog(self, _("Please enter configuration name"), _("Add new configuration"))
dialog.SetPouNames(self.Controler.GetProjectPouNames(self.Debug))
dialog.SetPouElementNames(self.Controler.GetProjectPouVariables(debug = self.Debug))
if dialog.ShowModal() == wx.ID_OK:
@@ -2418,7 +2428,7 @@
def GenerateAddResourceFunction(self, config_name):
def OnAddResourceMenu(event):
- dialog = ResourceNameDialog(self, "Please enter resource name", "Add new resource")
+ dialog = ResourceNameDialog(self, _("Please enter resource name"), _("Add new resource"))
dialog.SetPouNames(self.Controler.GetProjectPouNames(self.Debug))
dialog.SetPouElementNames(self.Controler.GetProjectPouVariables(debug = self.Debug))
if dialog.ShowModal() == wx.ID_OK:
@@ -2448,7 +2458,7 @@
def OnCreatePouFromMenu(self, event):
selected = self.TypesTree.GetSelection()
if self.TypesTree.GetPyData(selected) == ITEM_POU:
- dialog = PouNameDialog(self, "Please enter POU name", "Create a new POU from", "", wx.OK|wx.CANCEL)
+ dialog = PouNameDialog(self, _("Please enter POU name"), _("Create a new POU from"), "", wx.OK|wx.CANCEL)
dialog.SetPouNames(self.Controler.GetProjectPouNames(self.Debug))
if dialog.ShowModal() == wx.ID_OK:
self.Controler.ProjectCreatePouFrom(dialog.GetValue(), self.TypesTree.GetItemText(selected))
@@ -2463,7 +2473,8 @@
# Remove Project Elements Functions
#-------------------------------------------------------------------------------
- def OnRemoveDataTypeMenu(self, event, selected):
+ def OnRemoveDataTypeMenu(self, event):
+ selected = self.TypesTree.GetSelection()
if self.TypesTree.GetPyData(selected) == ITEM_DATATYPE:
name = self.TypesTree.GetItemText(selected)
if not self.Controler.DataTypeIsUsed(name, self.Debug):
@@ -2477,17 +2488,19 @@
self.RefreshTypesTree()
self.RefreshToolBar()
else:
- message = wx.MessageDialog(self, "\"%s\" is used by one or more POUs. It can't be removed!"%name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is used by one or more POUs. It can't be removed!")%name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
event.Skip()
- def OnRenamePouMenu(self, event, selected):
+ def OnRenamePouMenu(self, event):
+ selected = self.TypesTree.GetSelection()
if self.TypesTree.GetPyData(selected) == ITEM_POU:
wx.CallAfter(self.TypesTree.EditLabel, selected)
event.Skip()
- def OnRemovePouMenu(self, event, selected):
+ def OnRemovePouMenu(self, event):
+ selected = self.TypesTree.GetSelection()
if self.TypesTree.GetPyData(selected) == ITEM_POU:
name = self.TypesTree.GetItemText(selected)
if not self.Controler.PouIsUsed(name, self.Debug):
@@ -2504,12 +2517,13 @@
self.RefreshLibraryTree()
self.RefreshToolBar()
else:
- message = wx.MessageDialog(self, "\"%s\" is used by one or more POUs. It can't be removed!"%name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is used by one or more POUs. It can't be removed!")%name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
event.Skip()
- def OnRemoveTransitionMenu(self, event, selected):
+ def OnRemoveTransitionMenu(self, event):
+ selected = self.TypesTree.GetSelection()
if self.TypesTree.GetPyData(selected) == ITEM_TRANSITION:
transition = self.TypesTree.GetItemText(selected)
item = self.TypesTree.GetItemParent(selected)
@@ -2529,7 +2543,8 @@
self.RefreshTypesTree()
event.Skip()
- def OnRemoveActionMenu(self, event, selected):
+ def OnRemoveActionMenu(self, event):
+ selected = self.TypesTree.GetSelection()
if self.TypesTree.GetPyData(selected) == ITEM_ACTION:
action = self.TypesTree.GetItemText(selected)
item = self.TypesTree.GetItemParent(selected)
@@ -2549,7 +2564,8 @@
self.RefreshTypesTree()
event.Skip()
- def OnRemoveConfigurationMenu(self, event, selected):
+ def OnRemoveConfigurationMenu(self, event):
+ selected = self.TypesTree.GetSelection()
if self.TypesTree.GetPyData(selected) == ITEM_CONFIGURATION:
name = self.TypesTree.GetItemText(selected)
self.Controler.ProjectRemoveConfiguration(name)
@@ -2564,7 +2580,8 @@
self.RefreshInstancesTree()
event.Skip()
- def OnRemoveResourceMenu(self, event, selected):
+ def OnRemoveResourceMenu(self, event):
+ selected = self.TypesTree.GetSelection()
if self.TypesTree.GetPyData(selected) == ITEM_RESOURCE:
resource = self.TypesTree.GetItemText(selected)
item = self.TypesTree.GetItemParent(selected)
@@ -2586,7 +2603,7 @@
event.Skip()
def OnPLCOpenEditorMenu(self, event):
- wx.MessageBox("No documentation available.\nComing soon.")
+ wx.MessageBox(_("No documentation available.\nComing soon."))
#event.Skip()
def OnPLCOpenMenu(self, event):
@@ -2594,7 +2611,7 @@
event.Skip()
def OnAboutMenu(self, event):
- OpenHtmlFrame(self,"About PLCOpenEditor", os.path.join(CWD, "doc","about.html"), wx.Size(350, 350))
+ OpenHtmlFrame(self,_("About PLCOpenEditor"), os.path.join(CWD, "doc","about.html"), wx.Size(350, 350))
event.Skip()
@@ -2625,7 +2642,18 @@
for i in xrange(self.TabsOpened.GetPageCount()):
viewer = self.TabsOpened.GetPage(i)
viewer.ClearErrors()
-
+
+ RefreshFunctions = {
+ TITLE : RefreshTitle,
+ TOOLBAR : RefreshToolBar,
+ FILEMENU : RefreshFileMenu,
+ EDITMENU : RefreshEditMenu,
+ DISPLAYMENU : RefreshDisplayMenu,
+ TYPESTREE : RefreshTypesTree,
+ INSTANCESTREE : RefreshInstancesTree,
+ LIBRARYTREE : RefreshLibraryTree,
+ SCALING : RefreshScaling}
+
current_num = 0
def GetNewNum():
global current_num
@@ -2644,16 +2672,16 @@
class ScalingPanel(wx.Panel):
def _init_coll_ScalingPanelSizer_Items(self, parent):
- parent.AddWindow(self.staticText1, 0, border=10, flag=wx.GROW|wx.TOP|wx.LEFT)
+ parent.AddWindow(self.staticText1, 0, border=10, flag=wx.ALIGN_CENTER_VERTICAL|wx.TOP|wx.LEFT)
parent.AddWindow(self.XScale, 0, border=10, flag=wx.GROW|wx.TOP|wx.RIGHT)
- parent.AddWindow(self.staticText2, 0, border=10, flag=wx.GROW|wx.BOTTOM|wx.LEFT)
+ parent.AddWindow(self.staticText2, 0, border=10, flag=wx.ALIGN_CENTER_VERTICAL|wx.BOTTOM|wx.LEFT)
parent.AddWindow(self.YScale, 0, border=10, flag=wx.GROW|wx.BOTTOM|wx.RIGHT)
def _init_coll_ScalingPanelSizer_Growables(self, parent):
parent.AddGrowableCol(1)
def _init_sizers(self):
- self.ScalingPanelSizer = wx.FlexGridSizer(cols=2, hgap=0, rows=2, vgap=5)
+ self.ScalingPanelSizer = wx.FlexGridSizer(cols=2, hgap=5, rows=2, vgap=5)
self._init_coll_ScalingPanelSizer_Items(self.ScalingPanelSizer)
self._init_coll_ScalingPanelSizer_Growables(self.ScalingPanelSizer)
@@ -2666,16 +2694,16 @@
size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL)
self.staticText1 = wx.StaticText(id=ID_SCALINGPANELSTATICTEXT1,
- label='X Scale:', name='staticText1', parent=self,
- pos=wx.Point(0, 0), size=wx.Size(150, 17), style=0)
+ label=_('X Scale:'), name='staticText1', parent=self,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.XScale = wx.SpinCtrl(id=ID_SCALINGPANELXSCALE,
name='XScale', parent=self, pos=wx.Point(0, 0),
size=wx.Size(0, 24), style=0, min=0, max=2**16)
self.staticText2 = wx.StaticText(id=ID_SCALINGPANELSTATICTEXT2,
- label='Y Scale:', name='staticText2', parent=self,
- pos=wx.Point(0, 0), size=wx.Size(150, 17), style=0)
+ label=_('Y Scale:'), name='staticText2', parent=self,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.YScale = wx.SpinCtrl(id=ID_SCALINGPANELYSCALE,
name='YScale', parent=self, pos=wx.Point(0, 0),
@@ -2730,37 +2758,37 @@
parent.AddGrowableRow(0)
def _init_coll_ProjectPanelSizer_Items(self, parent):
- parent.AddWindow(self.staticText1, 0, border=10, flag=wx.GROW|wx.TOP|wx.LEFT)
+ parent.AddWindow(self.staticText1, 0, border=10, flag=wx.ALIGN_CENTER_VERTICAL|wx.TOP|wx.LEFT)
parent.AddWindow(self.ProjectName, 0, border=10, flag=wx.GROW|wx.TOP|wx.RIGHT)
- parent.AddWindow(self.staticText2, 0, border=10, flag=wx.GROW|wx.LEFT)
+ parent.AddWindow(self.staticText2, 0, border=10, flag=wx.ALIGN_CENTER_VERTICAL|wx.LEFT)
parent.AddWindow(self.ProjectVersion, 0, border=10, flag=wx.GROW|wx.RIGHT)
- parent.AddWindow(self.staticText3, 0, border=10, flag=wx.GROW|wx.LEFT)
+ parent.AddWindow(self.staticText3, 0, border=10, flag=wx.ALIGN_CENTER_VERTICAL|wx.LEFT)
parent.AddWindow(self.ProductName, 0, border=10, flag=wx.GROW|wx.RIGHT)
- parent.AddWindow(self.staticText4, 0, border=10, flag=wx.GROW|wx.LEFT)
+ parent.AddWindow(self.staticText4, 0, border=10, flag=wx.ALIGN_CENTER_VERTICAL|wx.LEFT)
parent.AddWindow(self.ProductVersion, 0, border=10, flag=wx.GROW|wx.RIGHT)
- parent.AddWindow(self.staticText5, 0, border=10, flag=wx.GROW|wx.BOTTOM|wx.LEFT)
+ parent.AddWindow(self.staticText5, 0, border=10, flag=wx.ALIGN_CENTER_VERTICAL|wx.BOTTOM|wx.LEFT)
parent.AddWindow(self.ProductRelease, 0, border=10, flag=wx.GROW|wx.BOTTOM|wx.RIGHT)
def _init_coll_ProjectPanelSizer_Growables(self, parent):
parent.AddGrowableCol(1)
def _init_coll_AuthorPanelSizer_Items(self, parent):
- parent.AddWindow(self.staticText6, 0, border=10, flag=wx.GROW|wx.TOP|wx.LEFT)
+ parent.AddWindow(self.staticText6, 0, border=10, flag=wx.ALIGN_CENTER_VERTICAL|wx.TOP|wx.LEFT)
parent.AddWindow(self.CompanyName, 0, border=10, flag=wx.GROW|wx.TOP|wx.RIGHT)
- parent.AddWindow(self.staticText7, 0, border=10, flag=wx.GROW|wx.LEFT)
+ parent.AddWindow(self.staticText7, 0, border=10, flag=wx.ALIGN_CENTER_VERTICAL|wx.LEFT)
parent.AddWindow(self.CompanyURL, 0, border=10, flag=wx.GROW|wx.RIGHT)
- parent.AddWindow(self.staticText8, 0, border=10, flag=wx.GROW|wx.LEFT)
+ parent.AddWindow(self.staticText8, 0, border=10, flag=wx.ALIGN_CENTER_VERTICAL|wx.LEFT)
parent.AddWindow(self.AuthorName, 0, border=10, flag=wx.GROW|wx.RIGHT)
- parent.AddWindow(self.staticText9, 0, border=10, flag=wx.GROW|wx.BOTTOM|wx.LEFT)
+ parent.AddWindow(self.staticText9, 0, border=10, flag=wx.ALIGN_CENTER_VERTICAL|wx.BOTTOM|wx.LEFT)
parent.AddWindow(self.Organization, 0, border=10, flag=wx.GROW|wx.BOTTOM|wx.RIGHT)
def _init_coll_AuthorPanelSizer_Growables(self, parent):
parent.AddGrowableCol(1)
def _init_coll_GraphicsPanelSizer_Items(self, parent):
- parent.AddWindow(self.staticText12, 0, border=10, flag=wx.GROW|wx.TOP|wx.LEFT|wx.RIGHT)
+ parent.AddWindow(self.staticText12, 0, border=10, flag=wx.ALIGN_CENTER_VERTICAL|wx.TOP|wx.LEFT|wx.RIGHT)
parent.AddSizer(self.GraphicsPageSizeSizer, 0, border=10, flag=wx.GROW|wx.LEFT|wx.RIGHT)
- parent.AddWindow(self.staticText15, 0, border=10, flag=wx.GROW|wx.LEFT|wx.RIGHT)
+ parent.AddWindow(self.staticText15, 0, border=10, flag=wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT)
parent.AddWindow(self.ScalingNotebook, 0, border=10, flag=wx.GROW|wx.BOTTOM|wx.LEFT|wx.RIGHT)
def _init_coll_GraphicsPanelSizer_Growables(self, parent):
@@ -2768,18 +2796,18 @@
parent.AddGrowableRow(3)
def _init_coll_GraphicsPageSizeSizer_Items(self, parent):
- parent.AddWindow(self.staticText13, 0, border=12, flag=wx.GROW|wx.LEFT)
+ parent.AddWindow(self.staticText13, 0, border=12, flag=wx.ALIGN_CENTER_VERTICAL|wx.LEFT)
parent.AddWindow(self.PageWidth, 0, border=0, flag=wx.GROW)
- parent.AddWindow(self.staticText14, 0, border=12, flag=wx.GROW|wx.LEFT)
+ parent.AddWindow(self.staticText14, 0, border=12, flag=wx.ALIGN_CENTER_VERTICAL|wx.LEFT)
parent.AddWindow(self.PageHeight, 0, border=0, flag=wx.GROW)
def _init_coll_GraphicsPageSizeSizer_Growables(self, parent):
parent.AddGrowableCol(1)
def _init_coll_MiscellaneousPanelSizer_Items(self, parent):
- parent.AddWindow(self.staticText10, 0, border=10, flag=wx.GROW|wx.TOP|wx.LEFT)
+ parent.AddWindow(self.staticText10, 0, border=10, flag=wx.ALIGN_CENTER_VERTICAL|wx.TOP|wx.LEFT)
parent.AddWindow(self.Language, 0, border=10, flag=wx.GROW|wx.TOP|wx.RIGHT)
- parent.AddWindow(self.staticText11, 0, border=10, flag=wx.GROW|wx.BOTTOM|wx.LEFT)
+ parent.AddWindow(self.staticText11, 0, border=10, flag=wx.BOTTOM|wx.LEFT)
parent.AddWindow(self.ContentDescription, 0, border=10, flag=wx.GROW|wx.BOTTOM|wx.RIGHT)
def _init_coll_MiscellaneousPanelSizer_Growables(self, parent):
@@ -2788,11 +2816,11 @@
def _init_sizers(self):
self.flexGridSizer1 = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=10)
- self.ProjectPanelSizer = wx.FlexGridSizer(cols=2, hgap=0, rows=5, vgap=15)
- self.AuthorPanelSizer = wx.FlexGridSizer(cols=2, hgap=0, rows=4, vgap=15)
- self.GraphicsPanelSizer = wx.FlexGridSizer(cols=1, hgap=0, rows=4, vgap=5)
- self.GraphicsPageSizeSizer = wx.FlexGridSizer(cols=2, hgap=0, rows=2, vgap=5)
- self.MiscellaneousPanelSizer = wx.FlexGridSizer(cols=2, hgap=0, rows=2, vgap=15)
+ self.ProjectPanelSizer = wx.FlexGridSizer(cols=2, hgap=5, rows=5, vgap=15)
+ self.AuthorPanelSizer = wx.FlexGridSizer(cols=2, hgap=5, rows=4, vgap=15)
+ self.GraphicsPanelSizer = wx.FlexGridSizer(cols=1, hgap=5, rows=4, vgap=5)
+ self.GraphicsPageSizeSizer = wx.FlexGridSizer(cols=2, hgap=5, rows=2, vgap=5)
+ self.MiscellaneousPanelSizer = wx.FlexGridSizer(cols=2, hgap=5, rows=2, vgap=15)
self._init_coll_flexGridSizer1_Items(self.flexGridSizer1)
self._init_coll_flexGridSizer1_Growables(self.flexGridSizer1)
@@ -2817,7 +2845,7 @@
wx.Dialog.__init__(self, id=ID_PROJECTDIALOG,
name='ProjectDialog', parent=prnt, pos=wx.Point(376, 223),
size=wx.Size(500, 350), style=wx.DEFAULT_DIALOG_STYLE,
- title='Project properties')
+ title=_('Project properties'))
self.SetClientSize(wx.Size(500, 350))
self.MainNotebook = wx.Notebook(id=ID_PROJECTDIALOGMAINNOTEBOOK,
@@ -2831,46 +2859,46 @@
size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL)
self.staticText1 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT1,
- label='Project Name (required):', name='staticText1', parent=self.ProjectPanel,
- pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)
+ label=_('Project Name (required):'), name='staticText1', parent=self.ProjectPanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.ProjectName = wx.TextCtrl(id=ID_PROJECTDIALOGPROJECTNAME,
name='ProjectName', parent=self.ProjectPanel, pos=wx.Point(0, 0),
size=wx.Size(0, 24), style=0)
self.staticText2 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT2,
- label='Project Version (optional):', name='staticText2', parent=self.ProjectPanel,
- pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)
+ label=_('Project Version (optional):'), name='staticText2', parent=self.ProjectPanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.ProjectVersion = wx.TextCtrl(id=ID_PROJECTDIALOGPROJECTVERSION,
name='ProjectVersion', parent=self.ProjectPanel, pos=wx.Point(0, 0),
size=wx.Size(0, 24), style=0)
self.staticText3 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT3,
- label='Product Name (required):', name='staticText3', parent=self.ProjectPanel,
- pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)
+ label=_('Product Name (required):'), name='staticText3', parent=self.ProjectPanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.ProductName = wx.TextCtrl(id=ID_PROJECTDIALOGPRODUCTNAME,
name='ProductName', parent=self.ProjectPanel, pos=wx.Point(0, 0),
size=wx.Size(0, 24), style=0)
self.staticText4 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT4,
- label='Product Version (required):', name='staticText4', parent=self.ProjectPanel,
- pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)
+ label=_('Product Version (required):'), name='staticText4', parent=self.ProjectPanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.ProductVersion = wx.TextCtrl(id=ID_PROJECTDIALOGPRODUCTVERSION,
name='ProductVersion', parent=self.ProjectPanel, pos=wx.Point(0, 0),
size=wx.Size(0, 24), style=0)
self.staticText5 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT5,
- label='Product Release (optional):', name='staticText5', parent=self.ProjectPanel,
- pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)
+ label=_('Product Release (optional):'), name='staticText5', parent=self.ProjectPanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.ProductRelease = wx.TextCtrl(id=ID_PROJECTDIALOGPRODUCTRELEASE,
name='ProductRelease', parent=self.ProjectPanel, pos=wx.Point(0, 0),
size=wx.Size(0, 24), style=0)
- self.MainNotebook.AddPage(self.ProjectPanel, "Project")
+ self.MainNotebook.AddPage(self.ProjectPanel, _("Project"))
# Author Panel elements
@@ -2879,38 +2907,38 @@
size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL)
self.staticText6 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT6,
- label='Company Name (required):', name='staticText6', parent=self.AuthorPanel,
- pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)
+ label=_('Company Name (required):'), name='staticText6', parent=self.AuthorPanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.CompanyName = wx.TextCtrl(id=ID_PROJECTDIALOGCOMPANYNAME,
name='CompanyName', parent=self.AuthorPanel, pos=wx.Point(0, 0),
size=wx.Size(0, 24), style=0)
self.staticText7 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT7,
- label='Company URL (optional):', name='staticText7', parent=self.AuthorPanel,
- pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)
+ label=_('Company URL (optional):'), name='staticText7', parent=self.AuthorPanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.CompanyURL = wx.TextCtrl(id=ID_PROJECTDIALOGCOMPANYURL,
name='CompanyURL', parent=self.AuthorPanel, pos=wx.Point(0, 0),
size=wx.Size(0, 24), style=0)
self.staticText8 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT8,
- label='Author Name (optional):', name='staticText8', parent=self.AuthorPanel,
- pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)
+ label=_('Author Name (optional):'), name='staticText8', parent=self.AuthorPanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.AuthorName = wx.TextCtrl(id=ID_PROJECTDIALOGAUTHORNAME,
name='AuthorName', parent=self.AuthorPanel, pos=wx.Point(0, 0),
size=wx.Size(0, 24), style=0)
self.staticText9 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT9,
- label='Organization (optional):', name='staticText9', parent=self.AuthorPanel,
- pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)
+ label=_('Organization (optional):'), name='staticText9', parent=self.AuthorPanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.Organization = wx.TextCtrl(id=ID_PROJECTDIALOGORGANIZATION,
name='Organization', parent=self.AuthorPanel, pos=wx.Point(0, 0),
size=wx.Size(0, 24), style=0)
- self.MainNotebook.AddPage(self.AuthorPanel, "Author")
+ self.MainNotebook.AddPage(self.AuthorPanel, _("Author"))
# Graphics Panel elements
@@ -2919,40 +2947,40 @@
size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL)
self.staticText12 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT12,
- label='Page Size (optional):', name='staticText12', parent=self.GraphicsPanel,
- pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)
+ label=_('Page Size (optional):'), name='staticText12', parent=self.GraphicsPanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.staticText13 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT13,
- label='Width:', name='staticText13', parent=self.GraphicsPanel,
- pos=wx.Point(0, 0), size=wx.Size(150, 17), style=0)
+ label=_('Width:'), name='staticText13', parent=self.GraphicsPanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.PageWidth = wx.SpinCtrl(id=ID_PROJECTDIALOGPAGEWIDTH,
name='PageWidth', parent=self.GraphicsPanel, pos=wx.Point(0, 0),
size=wx.Size(0, 24), style=0, min=0, max=2**16)
self.staticText14 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT14,
- label='Height:', name='staticText14', parent=self.GraphicsPanel,
- pos=wx.Point(0, 0), size=wx.Size(150, 17), style=0)
+ label=_('Height:'), name='staticText14', parent=self.GraphicsPanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.PageHeight = wx.SpinCtrl(id=ID_PROJECTDIALOGPAGEHEIGHT,
name='PageHeight', parent=self.GraphicsPanel, pos=wx.Point(0, 0),
size=wx.Size(0, 24), style=0, min=0, max=2**16)
self.staticText15 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT15,
- label='Scaling:', name='staticText15', parent=self.GraphicsPanel,
- pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)
+ label=_('Scaling:'), name='staticText15', parent=self.GraphicsPanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.ScalingNotebook = wx.Notebook(id=ID_PROJECTDIALOGSCALINGNOTEBOOK,
name='ScalingNotebook', parent=self.GraphicsPanel, pos=wx.Point(0,
0), size=wx.Size(0, 0), style=0)
self.Scalings = {}
- for language in ["FBD", "LD", "SFC"]:
+ for language, translation in [("FBD",_("FBD")), ("LD",_("LD")), ("SFC",_("SFC"))]:
window = ScalingPanel(self.ScalingNotebook)
self.Scalings[language] = window
- self.ScalingNotebook.AddPage(window, language)
-
- self.MainNotebook.AddPage(self.GraphicsPanel, "Graphics")
+ self.ScalingNotebook.AddPage(window, translation)
+
+ self.MainNotebook.AddPage(self.GraphicsPanel, _("Graphics"))
# Miscellaneous Panel elements
@@ -2961,22 +2989,22 @@
size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL)
self.staticText10 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT10,
- label='Language (optional):', name='staticText10', parent=self.MiscellaneousPanel,
- pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)
+ label=_('Language (optional):'), name='staticText10', parent=self.MiscellaneousPanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.Language = wx.ComboBox(id=ID_PROJECTDIALOGLANGUAGE,
name='Language', parent=self.MiscellaneousPanel, pos=wx.Point(0, 0),
size=wx.Size(0, 28), style=wx.CB_READONLY)
self.staticText11 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT11,
- label='Content Description (optional):', name='staticText11', parent=self.MiscellaneousPanel,
- pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)
+ label=_('Content Description (optional):'), name='staticText11', parent=self.MiscellaneousPanel,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.ContentDescription = wx.TextCtrl(id=ID_PROJECTDIALOGCONTENTDESCRIPTION,
name='ContentDescription', parent=self.MiscellaneousPanel, pos=wx.Point(0, 0),
size=wx.Size(0, 24), style=wx.TE_MULTILINE)
- self.MainNotebook.AddPage(self.MiscellaneousPanel, "Miscellaneous")
+ self.MainNotebook.AddPage(self.MiscellaneousPanel, _("Miscellaneous"))
self.ButtonSizer = self.CreateButtonSizer(wx.OK|wx.CANCEL|wx.CENTRE)
self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.ButtonSizer.GetAffirmativeButton().GetId())
@@ -2986,7 +3014,7 @@
def __init__(self, parent):
self._init_ctrls(parent)
- languages = ["", "en-US", "fr-FR"]
+ languages = ["", "en-US", "fr-FR", "zh-CN"]
for language in languages:
self.Language.Append(language)
@@ -3010,7 +3038,7 @@
text += " and %s"%item
else:
text += ", %s"%item
- message = wx.MessageDialog(self, "Form isn't complete. %s must be filled!"%text, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("Form isn't complete. %s must be filled!")%text, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
else:
@@ -3087,7 +3115,7 @@
else:
event(self, function)
- def __init__(self, parent, message, caption = "Please enter text", defaultValue = "",
+ def __init__(self, parent, message, caption = _("Please enter text"), defaultValue = "",
style = wx.OK|wx.CANCEL|wx.CENTRE, pos = wx.DefaultPosition):
wx.TextEntryDialog.__init__(self, parent, message, caption, defaultValue, style, pos)
@@ -3102,19 +3130,19 @@
def OnOK(self, event):
datatype_name = self.GetSizer().GetItem(1).GetWindow().GetValue()
if datatype_name == "":
- message = wx.MessageDialog(self, "You must type a name!", "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("You must type a name!"), _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif not TestIdentifier(datatype_name):
- message = wx.MessageDialog(self, "\"%s\" is not a valid identifier!"%datatype_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is not a valid identifier!")%datatype_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif datatype_name.upper() in IEC_KEYWORDS:
- message = wx.MessageDialog(self, "\"%s\" is a keyword. It can't be used!"%datatype_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is a keyword. It can't be used!")%datatype_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif datatype_name.upper() in self.DataTypeNames:
- message = wx.MessageDialog(self, "\"%s\" data type already exists!"%datatype_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" data type already exists!")%datatype_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
else:
@@ -3135,6 +3163,21 @@
ID_POUDIALOGSTATICTEXT2, ID_POUDIALOGSTATICTEXT3,
] = [wx.NewId() for _init_ctrls in range(7)]
+def GetTransitionLanguages():
+ _ = lambda x : x
+ return [_("IL"), _("ST"), _("LD"), _("FBD")]
+TRANSITION_LANGUAGES_DICT = dict([(_(language), language) for language in GetTransitionLanguages()])
+
+def GetPouTypes():
+ _ = lambda x : x
+ return [_("function"), _("functionBlock"), _("program")]
+POU_TYPES_DICT = dict([(_(pou_type), pou_type) for pou_type in GetPouTypes()])
+
+def GetPouLanguages():
+ _ = lambda x : x
+ return [_("IL"), _("ST"), _("LD"), _("FBD"), _("SFC")]
+POU_LANGUAGES_DICT = dict([(_(language), language) for language in GetPouLanguages()])
+
class PouDialog(wx.Dialog):
if wx.VERSION < (2, 6, 0):
def Bind(self, event, function, id = None):
@@ -3152,11 +3195,11 @@
parent.AddGrowableRow(0)
def _init_coll_MainSizer_Items(self, parent):
- parent.AddWindow(self.staticText1, 0, border=4, flag=wx.GROW|wx.TOP)
+ parent.AddWindow(self.staticText1, 0, border=4, flag=wx.ALIGN_CENTER_VERTICAL|wx.TOP)
parent.AddWindow(self.PouName, 0, border=0, flag=wx.GROW)
- parent.AddWindow(self.staticText2, 0, border=4, flag=wx.GROW|wx.TOP)
+ parent.AddWindow(self.staticText2, 0, border=4, flag=wx.ALIGN_CENTER_VERTICAL|wx.TOP)
parent.AddWindow(self.PouType, 0, border=0, flag=wx.GROW)
- parent.AddWindow(self.staticText3, 0, border=4, flag=wx.GROW|wx.TOP)
+ parent.AddWindow(self.staticText3, 0, border=4, flag=wx.ALIGN_CENTER_VERTICAL|wx.TOP)
parent.AddWindow(self.Language, 0, border=0, flag=wx.GROW)
def _init_coll_MainSizer_Growables(self, parent):
@@ -3164,7 +3207,7 @@
def _init_sizers(self):
self.flexGridSizer1 = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=10)
- self.MainSizer = wx.FlexGridSizer(cols=2, hgap=0, rows=3, vgap=15)
+ self.MainSizer = wx.FlexGridSizer(cols=2, hgap=5, rows=3, vgap=15)
self._init_coll_flexGridSizer1_Items(self.flexGridSizer1)
self._init_coll_flexGridSizer1_Growables(self.flexGridSizer1)
@@ -3177,20 +3220,20 @@
wx.Dialog.__init__(self, id=ID_POUDIALOG,
name='PouDialog', parent=prnt, pos=wx.Point(376, 223),
size=wx.Size(300, 200), style=wx.DEFAULT_DIALOG_STYLE,
- title='Create a new POU')
+ title=_('Create a new POU'))
self.SetClientSize(wx.Size(300, 200))
self.staticText1 = wx.StaticText(id=ID_POUDIALOGSTATICTEXT1,
- label='POU Name:', name='staticText1', parent=self,
- pos=wx.Point(0, 0), size=wx.Size(100, 17), style=0)
+ label=_('POU Name:'), name='staticText1', parent=self,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.PouName = wx.TextCtrl(id=ID_POUDIALOGPOUNAME,
name='POUName', parent=self, pos=wx.Point(0, 0),
size=wx.Size(0, 24), style=0)
self.staticText2 = wx.StaticText(id=ID_POUDIALOGSTATICTEXT2,
- label='POU Type:', name='staticText2', parent=self,
- pos=wx.Point(0, 0), size=wx.Size(100, 17), style=0)
+ label=_('POU Type:'), name='staticText2', parent=self,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.PouType = wx.ComboBox(id=ID_POUDIALOGPOUTYPE,
name='POUType', parent=self, pos=wx.Point(0, 0),
@@ -3198,8 +3241,8 @@
self.Bind(wx.EVT_COMBOBOX, self.OnTypeChanged, id=ID_POUDIALOGPOUTYPE)
self.staticText3 = wx.StaticText(id=ID_POUDIALOGSTATICTEXT3,
- label='Language:', name='staticText3', parent=self,
- pos=wx.Point(0, 0), size=wx.Size(100, 17), style=0)
+ label=_('Language:'), name='staticText3', parent=self,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.Language = wx.ComboBox(id=ID_POUDIALOGLANGUAGE,
name='Language', parent=self, pos=wx.Point(0, 0),
@@ -3213,10 +3256,10 @@
def __init__(self, parent, pou_type = None):
self._init_ctrls(parent)
- for option in ["function", "functionBlock", "program"]:
- self.PouType.Append(option)
+ for option in GetPouTypes():
+ self.PouType.Append(_(option))
if pou_type is not None:
- self.PouType.SetStringSelection(pou_type)
+ self.PouType.SetStringSelection(_(pou_type))
self.RefreshLanguage()
self.PouNames = []
@@ -3226,37 +3269,37 @@
error = []
pou_name = self.PouName.GetValue()
if pou_name == "":
- error.append("POU Name")
- if self.PouType.GetStringSelection() == "":
- error.append("POU Type")
- if self.Language.GetStringSelection() == "":
- error.append("Language")
+ error.append(_("POU Name"))
+ if self.PouType.GetSelection() == -1:
+ error.append(_("POU Type"))
+ if self.Language.GetSelection() == -1:
+ error.append(_("Language"))
if len(error) > 0:
text = ""
for i, item in enumerate(error):
if i == 0:
text += item
elif i == len(error) - 1:
- text += " and %s"%item
+ text += _(" and %s")%item
else:
- text += ", %s"%item
- message = wx.MessageDialog(self, "Form isn't complete. %s must be filled!"%text, "Error", wx.OK|wx.ICON_ERROR)
+ text += _(", %s")%item
+ message = wx.MessageDialog(self, _("Form isn't complete. %s must be filled!")%text, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif not TestIdentifier(pou_name):
- message = wx.MessageDialog(self, "\"%s\" is not a valid identifier!"%pou_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is not a valid identifier!")%pou_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif pou_name.upper() in IEC_KEYWORDS:
- message = wx.MessageDialog(self, "\"%s\" is a keyword. It can't be used!"%pou_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is a keyword. It can't be used!")%pou_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif pou_name.upper() in self.PouNames:
- message = wx.MessageDialog(self, "\"%s\" pou already exists!"%pou_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" pou already exists!")%pou_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif pou_name.upper() in self.PouElementNames:
- message = wx.MessageDialog(self, "A pou has an element with \"%s\" for name. It can generate a conflict. Do you wish to continue?"%pou_name, "Warning", wx.YES_NO|wx.ICON_EXCLAMATION)
+ message = wx.MessageDialog(self, _("A pou has an element with \"%s\" as name. It can generate a conflict. Do you wish to continue?")%pou_name, _("Warning"), wx.YES_NO|wx.ICON_EXCLAMATION)
result = message.ShowModal()
message.Destroy()
if result == wx.ID_YES:
@@ -3265,13 +3308,13 @@
self.EndModal(wx.ID_OK)
def RefreshLanguage(self):
- selection = self.Language.GetStringSelection()
+ selection = POU_LANGUAGES_DICT.get(self.Language.GetStringSelection(), "")
self.Language.Clear()
- for option in ["IL","ST","LD","FBD","SFC"]:
- if option != "SFC" or self.PouType.GetStringSelection() != "function":
- self.Language.Append(option)
- if self.Language.FindString(selection) != wx.NOT_FOUND:
- self.Language.SetStringSelection(selection)
+ for language in GetPouLanguages():
+ if language != "SFC" or POU_TYPES_DICT[self.PouType.GetStringSelection()] != "function":
+ self.Language.Append(language)
+ if self.Language.FindString(_(selection)) != wx.NOT_FOUND:
+ self.Language.SetStringSelection(_(selection))
def OnTypeChanged(self, event):
self.RefreshLanguage()
@@ -3288,15 +3331,15 @@
if item == "pouName":
self.PouName.SetValue(value)
elif item == "pouType":
- self.PouType.SetStringSelection(value)
+ self.PouType.SetStringSelection(_(value))
elif item == "language":
- self.Language.SetStringSelection(value)
+ self.Language.SetStringSelection(_(POU_LANGUAGES_DICT))
def GetValues(self):
values = {}
values["pouName"] = self.PouName.GetValue()
- values["pouType"] = self.PouType.GetStringSelection()
- values["language"] = self.Language.GetStringSelection()
+ values["pouType"] = POU_TYPES_DICT[self.PouType.GetStringSelection()]
+ values["language"] = POU_LANGUAGES_DICT[self.Language.GetStringSelection()]
return values
@@ -3309,6 +3352,11 @@
ID_POUTRANSITIONDIALOGSTATICTEXT2,
] = [wx.NewId() for _init_ctrls in range(5)]
+def GetTransitionLanguages():
+ _ = lambda x : x
+ return [_("IL"), _("ST"), _("LD"), _("FBD")]
+TRANSITION_LANGUAGES_DICT = dict([(_(language), language) for language in GetTransitionLanguages()])
+
class PouTransitionDialog(wx.Dialog):
if wx.VERSION < (2, 6, 0):
def Bind(self, event, function, id = None):
@@ -3326,9 +3374,9 @@
parent.AddGrowableRow(0)
def _init_coll_MainSizer_Items(self, parent):
- parent.AddWindow(self.staticText1, 0, border=4, flag=wx.GROW|wx.TOP)
+ parent.AddWindow(self.staticText1, 0, border=4, flag=wx.ALIGN_CENTER_VERTICAL|wx.TOP)
parent.AddWindow(self.TransitionName, 0, border=0, flag=wx.GROW)
- parent.AddWindow(self.staticText2, 0, border=4, flag=wx.GROW|wx.TOP)
+ parent.AddWindow(self.staticText2, 0, border=4, flag=wx.ALIGN_CENTER_VERTICAL|wx.TOP)
parent.AddWindow(self.Language, 0, border=0, flag=wx.GROW)
def _init_coll_MainSizer_Growables(self, parent):
@@ -3336,7 +3384,7 @@
def _init_sizers(self):
self.flexGridSizer1 = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=10)
- self.MainSizer = wx.FlexGridSizer(cols=2, hgap=0, rows=2, vgap=15)
+ self.MainSizer = wx.FlexGridSizer(cols=2, hgap=5, rows=2, vgap=15)
self._init_coll_flexGridSizer1_Items(self.flexGridSizer1)
self._init_coll_flexGridSizer1_Growables(self.flexGridSizer1)
@@ -3349,20 +3397,20 @@
wx.Dialog.__init__(self, id=ID_POUTRANSITIONDIALOG,
name='PouTransitionDialog', parent=prnt, pos=wx.Point(376, 223),
size=wx.Size(350, 200), style=wx.DEFAULT_DIALOG_STYLE,
- title='Create a new transition')
+ title=_('Create a new transition'))
self.SetClientSize(wx.Size(350, 160))
self.staticText1 = wx.StaticText(id=ID_POUTRANSITIONDIALOGSTATICTEXT1,
- label='Transition Name:', name='staticText1', parent=self,
- pos=wx.Point(0, 0), size=wx.Size(120, 17), style=0)
+ label=_('Transition Name:'), name='staticText1', parent=self,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.TransitionName = wx.TextCtrl(id=ID_POUTRANSITIONDIALOGTRANSITIONNAME,
name='TransitionName', parent=self, pos=wx.Point(0, 0),
size=wx.Size(0, 24), style=0)
self.staticText2 = wx.StaticText(id=ID_POUTRANSITIONDIALOGSTATICTEXT2,
- label='Language:', name='staticText2', parent=self,
- pos=wx.Point(0, 0), size=wx.Size(120, 17), style=0)
+ label=_('Language:'), name='staticText2', parent=self,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.Language = wx.ComboBox(id=ID_POUTRANSITIONDIALOGLANGUAGE,
name='Language', parent=self, pos=wx.Point(0, 0),
@@ -3376,8 +3424,8 @@
def __init__(self, parent):
self._init_ctrls(parent)
- for option in ["IL","ST","LD","FBD"]:
- self.Language.Append(option)
+ for language in GetTransitionLanguages():
+ self.Language.Append(_(language))
self.PouNames = []
self.PouElementNames = []
@@ -3386,35 +3434,35 @@
error = []
transition_name = self.TransitionName.GetValue()
if self.TransitionName.GetValue() == "":
- error.append("Transition Name")
- if self.Language.GetStringSelection() == "":
- error.append("Language")
+ error.append(_("Transition Name"))
+ if self.Language.GetSelection() == -1:
+ error.append(_("Language"))
if len(error) > 0:
text = ""
for i, item in enumerate(error):
if i == 0:
text += item
elif i == len(error) - 1:
- text += " and %s"%item
+ text += _(" and %s")%item
else:
- text += ", %s"%item
- message = wx.MessageDialog(self, "Form isn't complete. %s must be filled!"%text, "Error", wx.OK|wx.ICON_ERROR)
+ text += _(", %s")%item
+ message = wx.MessageDialog(self, _("Form isn't complete. %s must be filled!")%text, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif not TestIdentifier(transition_name):
- message = wx.MessageDialog(self, "\"%s\" is not a valid identifier!"%transition_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is not a valid identifier!")%transition_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif transition_name.upper() in IEC_KEYWORDS:
- message = wx.MessageDialog(self, "\"%s\" is a keyword. It can't be used!"%transition_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is a keyword. It can't be used!")%transition_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif transition_name.upper() in self.PouNames:
- message = wx.MessageDialog(self, "A pou with \"%s\" for name exists!"%transition_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("A pou with \"%s\" as name exists!")%transition_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif transition_name.upper() in self.PouElementNames:
- message = wx.MessageDialog(self, "\"%s\" element for this pou already exists!"%transition_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" element for this pou already exists!")%transition_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
else:
@@ -3431,12 +3479,12 @@
if item == "transitionName":
self.TransitionName.SetValue(value)
elif item == "language":
- self.Language.SetStringSelection(value)
+ self.Language.SetSelection(_(value))
def GetValues(self):
values = {}
values["transitionName"] = self.TransitionName.GetValue()
- values["language"] = self.Language.GetStringSelection()
+ values["language"] = TRANSITION_LANGUAGES_DICT[self.Language.GetStringSelection()]
return values
#-------------------------------------------------------------------------------
@@ -3448,6 +3496,11 @@
ID_POUACTIONDIALOGSTATICTEXT2,
] = [wx.NewId() for _init_ctrls in range(5)]
+def GetActionLanguages():
+ _ = lambda x : x
+ return [_("IL"), _("ST"), _("LD"), _("FBD")]
+ACTION_LANGUAGES_DICT = dict([(_(language), language) for language in GetActionLanguages()])
+
class PouActionDialog(wx.Dialog):
if wx.VERSION < (2, 6, 0):
def Bind(self, event, function, id = None):
@@ -3465,9 +3518,9 @@
parent.AddGrowableRow(0)
def _init_coll_MainSizer_Items(self, parent):
- parent.AddWindow(self.staticText1, 0, border=4, flag=wx.GROW|wx.TOP)
+ parent.AddWindow(self.staticText1, 0, border=4, flag=wx.ALIGN_CENTER_VERTICAL|wx.TOP)
parent.AddWindow(self.ActionName, 0, border=0, flag=wx.GROW)
- parent.AddWindow(self.staticText2, 0, border=4, flag=wx.GROW|wx.TOP)
+ parent.AddWindow(self.staticText2, 0, border=4, flag=wx.ALIGN_CENTER_VERTICAL|wx.TOP)
parent.AddWindow(self.Language, 0, border=0, flag=wx.GROW)
def _init_coll_MainSizer_Growables(self, parent):
@@ -3475,7 +3528,7 @@
def _init_sizers(self):
self.flexGridSizer1 = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=10)
- self.MainSizer = wx.FlexGridSizer(cols=2, hgap=0, rows=2, vgap=15)
+ self.MainSizer = wx.FlexGridSizer(cols=2, hgap=5, rows=2, vgap=15)
self._init_coll_flexGridSizer1_Items(self.flexGridSizer1)
self._init_coll_flexGridSizer1_Growables(self.flexGridSizer1)
@@ -3488,20 +3541,20 @@
wx.Dialog.__init__(self, id=ID_POUACTIONDIALOG,
name='PouActionDialog', parent=prnt, pos=wx.Point(376, 223),
size=wx.Size(320, 200), style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER,
- title='Create a new action')
+ title=_('Create a new action'))
self.SetClientSize(wx.Size(320, 160))
self.staticText1 = wx.StaticText(id=ID_POUACTIONDIALOGSTATICTEXT1,
- label='Action Name:', name='staticText1', parent=self,
- pos=wx.Point(0, 0), size=wx.Size(100, 17), style=0)
+ label=_('Action Name:'), name='staticText1', parent=self,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.ActionName = wx.TextCtrl(id=ID_POUACTIONDIALOGACTIONNAME,
name='ActionName', parent=self, pos=wx.Point(0, 0),
size=wx.Size(0, 24), style=0)
self.staticText2 = wx.StaticText(id=ID_POUACTIONDIALOGSTATICTEXT2,
- label='Language:', name='staticText2', parent=self,
- pos=wx.Point(0, 0), size=wx.Size(100, 17), style=0)
+ label=_('Language:'), name='staticText2', parent=self,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=0)
self.Language = wx.ComboBox(id=ID_POUACTIONDIALOGLANGUAGE,
name='Language', parent=self, pos=wx.Point(0, 0),
@@ -3515,8 +3568,8 @@
def __init__(self, parent):
self._init_ctrls(parent)
- for option in ["IL","ST","LD","FBD"]:
- self.Language.Append(option)
+ for option in GetActionLanguages():
+ self.Language.Append(_(option))
self.PouNames = []
self.PouElementNames = []
@@ -3525,35 +3578,35 @@
error = []
action_name = self.ActionName.GetValue()
if action_name == "":
- error.append("Action Name")
- if self.Language.GetStringSelection() == "":
- error.append("Language")
+ error.append(_("Action Name"))
+ if self.Language.GetSelection() == -1:
+ error.append(_("Language"))
if len(error) > 0:
text = ""
for i, item in enumerate(error):
if i == 0:
text += item
elif i == len(error) - 1:
- text += " and %s"%item
+ text += _(" and %s")%item
else:
- text += ", %s"%item
- message = wx.MessageDialog(self, "Form isn't complete. %s must be filled!"%text, "Error", wx.OK|wx.ICON_ERROR)
+ text += _(", %s")%item
+ message = wx.MessageDialog(self, _("Form isn't complete. %s must be filled!")%text, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif not TestIdentifier(action_name):
- message = wx.MessageDialog(self, "\"%s\" is not a valid identifier!"%action_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is not a valid identifier!")%action_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif action_name.upper() in IEC_KEYWORDS:
- message = wx.MessageDialog(self, "\"%s\" is a keyword. It can't be used!"%action_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is a keyword. It can't be used!")%action_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif action_name.upper() in self.PouNames:
- message = wx.MessageDialog(self, "A pou with \"%s\" for name exists!"%action_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("A pou with \"%s\" as name exists!")%action_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif action_name.upper() in self.PouElementNames:
- message = wx.MessageDialog(self, "\"%s\" element for this pou already exists!"%action_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" element for this pou already exists!")%action_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
else:
@@ -3570,12 +3623,12 @@
if item == "actionName":
self.ActionName.SetValue(value)
elif item == "language":
- self.Language.SetStringSelection(value)
+ self.Language.SetStringSelection(_(value))
def GetValues(self):
values = {}
values["actionName"] = self.ActionName.GetValue()
- values["language"] = self.Language.GetStringSelection()
+ values["language"] = ACTION_LANGUAGES_DICT[self.Language.GetStringSelection()]
return values
#-------------------------------------------------------------------------------
@@ -3591,7 +3644,7 @@
else:
event(self, function)
- def __init__(self, parent, message, caption = "Please enter configuration name", defaultValue = "",
+ def __init__(self, parent, message, caption = _("Please enter configuration name"), defaultValue = "",
style = wx.OK|wx.CANCEL|wx.CENTRE, pos = wx.DefaultPosition):
wx.TextEntryDialog.__init__(self, parent, message, caption, defaultValue, style, pos)
@@ -3608,23 +3661,23 @@
def OnOK(self, event):
config_name = self.GetSizer().GetItem(1).GetWindow().GetValue()
if config_name == "":
- message = wx.MessageDialog(self, "You must type a name!", "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("You must type a name!"), _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif not TestIdentifier(config_name):
- message = wx.MessageDialog(self, "\"%s\" is not a valid identifier!"%config_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is not a valid identifier!")%config_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif config_name.upper() in IEC_KEYWORDS:
- message = wx.MessageDialog(self, "\"%s\" is a keyword. It can't be used!"%config_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is a keyword. It can't be used!")%config_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif config_name.upper() in self.PouNames:
- message = wx.MessageDialog(self, "A pou with \"%s\" as name exists!"%config_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("A pou with \"%s\" as name exists!")%config_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif config_name.upper() in self.PouElementNames:
- message = wx.MessageDialog(self, "A pou has an element with \"%s\" for name. It can generate a conflict. Do you wish to continue?"%config_name, "Warning", wx.YES_NO|wx.ICON_EXCLAMATION)
+ message = wx.MessageDialog(self, _("A pou has an element with \"%s\" as name. It can generate a conflict. Do you wish to continue?")%config_name, _("Warning"), wx.YES_NO|wx.ICON_EXCLAMATION)
result = message.ShowModal()
message.Destroy()
if result == wx.ID_YES:
@@ -3654,7 +3707,7 @@
else:
event(self, function)
- def __init__(self, parent, message, caption = "Please enter resource name", defaultValue = "",
+ def __init__(self, parent, message, caption = _("Please enter resource name"), defaultValue = "",
style = wx.OK|wx.CANCEL|wx.CENTRE, pos = wx.DefaultPosition):
wx.TextEntryDialog.__init__(self, parent, message, caption, defaultValue, style, pos)
@@ -3671,23 +3724,23 @@
def OnOK(self, event):
resource_name = self.GetSizer().GetItem(1).GetWindow().GetValue()
if resource_name == "":
- message = wx.MessageDialog(self, "You must type a name!", "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("You must type a name!"), _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif not TestIdentifier(resource_name):
- message = wx.MessageDialog(self, "\"%s\" is not a valid identifier!"%resource_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is not a valid identifier!")%resource_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif resource_name.upper() in IEC_KEYWORDS:
- message = wx.MessageDialog(self, "\"%s\" is a keyword. It can't be used!"%resource_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("\"%s\" is a keyword. It can't be used!")%resource_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif resource_name.upper() in self.PouNames:
- message = wx.MessageDialog(self, "A pou with \"%s\" as name exists!"%resource_name, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self, _("A pou with \"%s\" as name exists!")%resource_name, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
elif resource_name.upper() in self.PouElementNames:
- message = wx.MessageDialog(self, "A pou has an element with \"%s\" for name. It can generate a conflict. Do you wish to continue?"%resource_name, "Warning", wx.YES_NO|wx.ICON_EXCLAMATION)
+ message = wx.MessageDialog(self, _("A pou has an element with \"%s\" as name. It can generate a conflict. Do you wish to continue?")%resource_name, _("Warning"), wx.YES_NO|wx.ICON_EXCLAMATION)
result = message.ShowModal()
message.Destroy()
if result == wx.ID_YES:
@@ -3789,6 +3842,25 @@
# 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):
"""
@@ -3814,25 +3886,34 @@
def GetNumberRows(self):
return len(self.data)
- def GetColLabelValue(self, col):
+ 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):
+ 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"]
- name = str(self.data[row].get(self.GetColLabelValue(col), ""))
- return name
+ 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)
+ 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):
@@ -3888,13 +3969,11 @@
Otherwise default to the default renderer.
"""
- typelist = None
- accesslist = None
for row in range(self.GetNumberRows()):
for col in range(self.GetNumberCols()):
editor = None
renderer = None
- colname = self.GetColLabelValue(col)
+ colname = self.GetColLabelValue(col, False)
if col != 0 and self.GetValueByName(row, "Edit"):
grid.SetReadOnly(row, col, False)
if colname == "Name":
@@ -3922,10 +4001,10 @@
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]))
+ 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(self.Parent.OptionList)
+ editor.SetParameters(",".join(map(_, self.Parent.OptionList)))
elif colname == "Type":
editor = wx.grid.GridCellTextEditor()
else:
@@ -3984,21 +4063,21 @@
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) != "Location":
+ 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"
+ 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"
+ message = _("Can affect a location only to local or global variables")
else:
try:
values = eval(data)
except:
- message = "Invalid value \"%s\" for location"%data
+ message = _("Invalid value \"%s\" for location")%data
values = None
if not isinstance(values, TupleType):
- message = "Invalid value \"%s\" for location"%data
+ message = _("Invalid value \"%s\" for location")%data
values = None
if values is not None and values[1] == "location":
location = values[0]
@@ -4007,20 +4086,20 @@
message = None
if location.startswith("%"):
if base_type != values[2]:
- message = "Incompatible data types between \"%s\" and \"%s\""%(values[2], variable_type)
+ 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
+ message = _("Incompatible size of data between \"%s\" and \"BOOL\"")%location
elif location[0] not in LOCATIONDATATYPES:
- message = "Unrecognized data size \"%s\""%location[0]
+ 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)
+ 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)
+ 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:
@@ -4037,7 +4116,7 @@
wx.CallAfter(self.ShowMessage, message)
def ShowMessage(self, message):
- message = wx.MessageDialog(self.ParentWindow, message, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self.ParentWindow, message, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
@@ -4145,8 +4224,8 @@
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(95, 17), style=0)
+ 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),
@@ -4154,22 +4233,22 @@
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(95, 17), style=0)
+ 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',
+ self.AddButton = wx.Button(id=ID_VARIABLEEDITORPANELADDBUTTON, label=_('Add'),
name='AddButton', parent=self.ControlPanel, pos=wx.Point(0, 0),
- size=wx.Size(72, 32), style=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',
+ self.DeleteButton = wx.Button(id=ID_VARIABLEEDITORPANELDELETEBUTTON, label=_('Delete'),
name='DeleteButton', parent=self.ControlPanel, pos=wx.Point(0, 0),
- size=wx.Size(72, 32), style=0)
+ size=wx.DefaultSize, style=0)
self.Bind(wx.EVT_BUTTON, self.OnDeleteButton, id=ID_VARIABLEEDITORPANELDELETEBUTTON)
self.UpButton = wx.Button(id=ID_VARIABLEEDITORPANELUPBUTTON, label='^',
@@ -4192,10 +4271,7 @@
self.Filter = "All"
self.FilterChoices = []
- self.FilterChoiceTransfer = {"All" : "All", "Interface" : "Interface",
- " Input" : "Input", " Output" : "Output", " InOut" : "InOut",
- " External" : "External", "Variables" : "Variables", " Local" : "Local",
- " Temp" : "Temp", "Global" : "Global", "Access" : "Access"}
+ self.FilterChoiceTransfer = GetFilterChoiceTransfer()
if element_type in ["config", "resource"]:
self.DefaultTypes = {"All" : "Global"}
@@ -4204,27 +4280,30 @@
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, [], ["#", "Name", "Class", "Type", "Location", "Initial Value", "Retain", "Constant"])
+ self.Table = VariableTable(self, [], GetVariableTableColnames(True))
if element_type not in ["config", "resource"]:
- self.FilterChoices = ["All","Interface"," Input"," Output"," InOut"," External","Variables"," Local"," Temp","Global","Access"]
+ self.FilterChoices = ["All", "Interface", " Input", " Output", " InOut", " External", "Variables", " Local", " Temp"]#,"Access"]
else:
- self.FilterChoices = ["All","Global","Access"]
+ 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, [], ["#", "Name", "Class", "Type", "Initial Value", "Retain", "Constant"])
- self.FilterChoices = ["All","Interface"," Input"," Output"," InOut"," External","Variables"," Local"," Temp"]
+ 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)
+ 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.ClassFilter.SetStringSelection(_(reverse_transfer[self.Filter]))
self.RefreshTypeList()
- self.OptionList = "Yes,No"
+ self.OptionList = GetAlternativeOptions()
if element_type == "function":
for base_type in self.Controler.GetBaseTypes():
@@ -4241,7 +4320,8 @@
attr = wx.grid.GridCellAttr()
attr.SetAlignment(self.ColAlignements[col], wx.ALIGN_CENTRE)
self.VariablesGrid.SetColAttr(col, attr)
- self.VariablesGrid.SetColSize(col, self.ColSizes[col])
+ self.VariablesGrid.SetColMinimalWidth(col, self.ColSizes[col])
+ self.VariablesGrid.AutoSizeColumn(col, False)
def SetTagName(self, tagname):
self.TagName = tagname
@@ -4361,22 +4441,22 @@
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 = 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 = 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 = 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 exists in this pou!"%value, "Error", wx.OK|wx.ICON_ERROR)
+ 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()
@@ -4408,13 +4488,13 @@
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)
+ 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)
+ 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)
@@ -4423,7 +4503,7 @@
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)
+ 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()
@@ -4526,8 +4606,12 @@
self.Table.ResetView(self.VariablesGrid)
#-------------------------------------------------------------------------------
-# Variables Editor Panel
-#-------------------------------------------------------------------------------
+# Debug Variables Panel
+#-------------------------------------------------------------------------------
+
+def GetDebugVariablesTableColnames():
+ _ = lambda x : x
+ return [_("Variable"), _("Value")]
class VariableTableItem(DebugDataConsumer):
@@ -4579,21 +4663,23 @@
def GetNumberRows(self):
return len(self.data)
- def GetColLabelValue(self, col):
+ 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):
+ def GetRowLabelValues(self, row, translate=True):
return row
def GetValue(self, row, col):
if row < self.GetNumberRows():
- return self.GetValueByName(row, self.GetColLabelValue(col))
+ return self.GetValueByName(row, self.GetColLabelValue(col, False))
return ""
def SetValue(self, row, col, value):
if col < len(self.colnames):
- self.SetValueByName(row, self.GetColLabelValue(col), value)
+ self.SetValueByName(row, self.GetColLabelValue(col, False), value)
def GetValueByName(self, row, colname):
if row < self.GetNumberRows():
@@ -4695,10 +4781,10 @@
try:
values = eval(data)
except:
- message = "Invalid value \"%s\" for debug variable"%data
+ message = _("Invalid value \"%s\" for debug variable")%data
values = None
if not isinstance(values, TupleType):
- message = "Invalid value \"%s\" for debug variable"%data
+ message = _("Invalid value \"%s\" for debug variable")%data
values = None
if values is not None and values[1] == "debug":
self.ParentWindow.InsertValue(row, values[0])
@@ -4706,7 +4792,7 @@
wx.CallAfter(self.ShowMessage, message)
def ShowMessage(self, message):
- message = wx.MessageDialog(self.ParentWindow, message, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self.ParentWindow, message, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
@@ -4773,7 +4859,7 @@
size=wx.Size(32, 32), style=0)
self.Bind(wx.EVT_BUTTON, self.OnDownButton, id=ID_DEBUGVARIABLEPANELDOWNBUTTON)
- self.DeleteButton = wx.Button(id=ID_DEBUGVARIABLEPANELDELETEBUTTON, label='Delete',
+ self.DeleteButton = wx.Button(id=ID_DEBUGVARIABLEPANELDELETEBUTTON, label=_('Delete'),
name='DeleteButton', parent=self, pos=wx.Point(0, 0),
size=wx.Size(72, 32), style=0)
self.Bind(wx.EVT_BUTTON, self.OnDeleteButton, id=ID_DEBUGVARIABLEPANELDELETEBUTTON)
@@ -4786,7 +4872,7 @@
self.Controler = controler
self.HasNewData = False
- self.Table = DebugVariableTable(self, [], ["Variable", "Value"])
+ self.Table = DebugVariableTable(self, [], GetDebugVariablesTableColnames())
self.VariablesGrid.SetTable(self.Table)
self.VariablesGrid.SetRowLabelSize(0)
@@ -4911,7 +4997,7 @@
block_name = " - ".join(self.Viewer.GetTagName().split("::")[1:])
text_width, text_height = dc.GetTextExtent(block_name)
dc.DrawText(block_name, margin_left, margin_top - text_height - self.TextMargin)
- dc.DrawText("Page: %d" % page, margin_left, margin_top + area_height + self.TextMargin)
+ dc.DrawText(_("Page: %d") % page, margin_left, margin_top + area_height + self.TextMargin)
# Calculate the position on the DC for centering the graphic
posX = area_width * ((page - 1) % self.PageGrid[0])
@@ -4941,12 +5027,12 @@
def Display_Exception_Dialog(e_type,e_value,e_tb):
trcbck_lst = []
for i,line in enumerate(traceback.extract_tb(e_tb)):
- trcbck = " " + str(i+1) + ". "
+ trcbck = " " + str(i+1) + _(". ")
if line[0].find(os.getcwd()) == -1:
- trcbck += "file : " + str(line[0]) + ", "
- else:
- trcbck += "file : " + str(line[0][len(os.getcwd()):]) + ", "
- trcbck += "line : " + str(line[1]) + ", " + "function : " + str(line[2])
+ trcbck += _("file : ") + str(line[0]) + _(", ")
+ else:
+ trcbck += _("file : ") + str(line[0][len(os.getcwd()):]) + _(", ")
+ trcbck += _("line : ") + str(line[1]) + _(", ") + _("function : ") + str(line[2])
trcbck_lst.append(trcbck)
# Allow clicking....
@@ -4955,7 +5041,7 @@
cap.ReleaseMouse()
dlg = wx.SingleChoiceDialog(None,
- """
+ _("""
An error happens.
Click on OK for saving an error report.
@@ -4966,9 +5052,9 @@
Error:
-""" +
- str(e_type) + " : " + str(e_value),
- "Error",
+""") +
+ str(e_type) + _(" : ") + str(e_value),
+ _("Error"),
trcbck_lst)
try:
res = (dlg.ShowModal() == wx.ID_OK)
@@ -4978,7 +5064,7 @@
return res
def Display_Error_Dialog(e_value):
- message = wx.MessageDialog(None, str(e_value), "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(None, str(e_value), _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
@@ -5036,30 +5122,6 @@
sys.excepthook = handle_exception
if __name__ == '__main__':
- def usage():
- print "\nUsage of PLCOpenEditor.py :"
- print "\n %s [Filepath]\n"%sys.argv[0]
-
- try:
- opts, args = getopt.getopt(sys.argv[1:], "h", ["help"])
- except getopt.GetoptError:
- # print help information and exit:
- usage()
- sys.exit(2)
-
- for o, a in opts:
- if o in ("-h", "--help"):
- usage()
- sys.exit()
-
- fileOpen = None
- if len(args) > 1:
- usage()
- sys.exit()
- elif len(args) == 1:
- fileOpen = args[0]
-
- app = wx.PySimpleApp()
wx.InitAllImageHandlers()
# Install a exception handle for bug reports
diff -r e0a6a5952d13 -r 127d524a5f1d RessourceEditor.py
--- a/RessourceEditor.py Mon Jul 06 11:24:37 2009 -0600
+++ b/RessourceEditor.py Thu Aug 20 09:03:31 2009 -0600
@@ -74,6 +74,14 @@
# Resource Editor class
#-------------------------------------------------------------------------------
+def GetTasksTableColnames():
+ _ = lambda x : x
+ return [_("Name"), _("Single"), _("Interval"), _("Priority")]
+
+def GetInstancesTableColnames():
+ _ = lambda x : x
+ return [_("Name"), _("Type"), _("Task")]
+
class ResourceTable(wx.grid.PyGridTableBase):
"""
@@ -113,16 +121,18 @@
def GetNumberRows(self):
return len(self.data)
- def GetColLabelValue(self, col):
+ 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):
+ def GetRowLabelValues(self, row, translate=True):
return row
def GetValue(self, row, col):
if row < self.GetNumberRows():
- name = str(self.data[row].get(self.GetColLabelValue(col), ""))
+ name = str(self.data[row].get(self.GetColLabelValue(col, False), ""))
return name
def GetValueByName(self, row, colname):
@@ -130,7 +140,7 @@
def SetValue(self, row, col, value):
if col < len(self.colnames):
- self.data[row][self.GetColLabelValue(col)] = value
+ self.data[row][self.GetColLabelValue(col, False)] = value
def SetValueByName(self, row, colname, value):
if colname in self.colnames:
@@ -188,7 +198,7 @@
for col in range(self.GetNumberCols()):
editor = None
renderer = None
- colname = self.GetColLabelValue(col)
+ colname = self.GetColLabelValue(col, False)
grid.SetReadOnly(row, col, False)
if colname in ["Name","Interval"]:
editor = wx.grid.GridCellTextEditor()
@@ -345,8 +355,8 @@
size=wx.Size(0, 0), style=wx.SUNKEN_BORDER)
self.staticText1 = wx.StaticText(id=ID_RESOURCEEDITORSTATICTEXT1,
- label=u'Tasks:', name='staticText2', parent=self, pos=wx.Point(0,
- 0), size=wx.Size(60, 17), style=wx.ALIGN_CENTER)
+ label=_(u'Tasks:'), name='staticText2', parent=self, pos=wx.Point(0,
+ 0), size=wx.DefaultSize, style=wx.ALIGN_CENTER)
self.TasksGrid = wx.grid.Grid(id=ID_RESOURCEEDITORTASKSGRID,
name='TasksGrid', parent=self, pos=wx.Point(0, 0),
@@ -360,14 +370,14 @@
else:
wx.grid.EVT_GRID_CELL_CHANGE(self.TasksGrid, self.OnTasksGridCellChange)
- self.AddTaskButton = wx.Button(id=ID_RESOURCEEDITORADDTASKBUTTON, label='Add Task',
+ self.AddTaskButton = wx.Button(id=ID_RESOURCEEDITORADDTASKBUTTON, label=_('Add Task'),
name='AddTaskButton', parent=self, pos=wx.Point(0, 0),
- size=wx.Size(102, 32), style=0)
+ size=wx.DefaultSize, style=0)
self.Bind(wx.EVT_BUTTON, self.OnAddTaskButton, id=ID_RESOURCEEDITORADDTASKBUTTON)
- self.DeleteTaskButton = wx.Button(id=ID_RESOURCEEDITORDELETETASKBUTTON, label='Delete Task',
+ self.DeleteTaskButton = wx.Button(id=ID_RESOURCEEDITORDELETETASKBUTTON, label=_('Delete Task'),
name='DeleteTaskButton', parent=self, pos=wx.Point(0, 0),
- size=wx.Size(102, 32), style=0)
+ size=wx.DefaultSize, style=0)
self.Bind(wx.EVT_BUTTON, self.OnDeleteTaskButton, id=ID_RESOURCEEDITORDELETETASKBUTTON)
self.UpTaskButton = wx.Button(id=ID_RESOURCEEDITORUPTASKBUTTON, label='^',
@@ -381,8 +391,8 @@
self.Bind(wx.EVT_BUTTON, self.OnDownTaskButton, id=ID_RESOURCEEDITORDOWNTASKBUTTON)
self.staticText2 = wx.StaticText(id=ID_RESOURCEEDITORSTATICTEXT2,
- label=u'Instances:', name='staticText1', parent=self,
- pos=wx.Point(0, 0), size=wx.Size(85, 17), style=wx.ALIGN_CENTER)
+ label=_(u'Instances:'), name='staticText1', parent=self,
+ pos=wx.Point(0, 0), size=wx.DefaultSize, style=wx.ALIGN_CENTER)
self.InstancesGrid = wx.grid.Grid(id=ID_RESOURCEEDITORINSTANCESGRID,
name='InstancesGrid', parent=self, pos=wx.Point(0, 0),
@@ -396,14 +406,14 @@
else:
wx.grid.EVT_GRID_CELL_CHANGE(self.InstancesGrid, self.OnInstancesGridCellChange)
- self.AddInstanceButton = wx.Button(id=ID_RESOURCEEDITORADDINSTANCEBUTTON, label='Add Instance',
+ self.AddInstanceButton = wx.Button(id=ID_RESOURCEEDITORADDINSTANCEBUTTON, label=_('Add Instance'),
name='AddInstanceButton', parent=self, pos=wx.Point(0, 0),
- size=wx.Size(122, 32), style=0)
+ size=wx.DefaultSize, style=0)
self.Bind(wx.EVT_BUTTON, self.OnAddInstanceButton, id=ID_RESOURCEEDITORADDINSTANCEBUTTON)
- self.DeleteInstanceButton = wx.Button(id=ID_RESOURCEEDITORDELETEINSTANCEBUTTON, label='Delete Instance',
+ self.DeleteInstanceButton = wx.Button(id=ID_RESOURCEEDITORDELETEINSTANCEBUTTON, label=_('Delete Instance'),
name='DeleteInstanceButton', parent=self, pos=wx.Point(0, 0),
- size=wx.Size(122, 32), style=0)
+ size=wx.DefaultSize, style=0)
self.Bind(wx.EVT_BUTTON, self.OnDeleteInstanceButton, id=ID_RESOURCEEDITORDELETEINSTANCEBUTTON)
self.UpInstanceButton = wx.Button(id=ID_RESOURCEEDITORUPINSTANCEBUTTON, label='^',
@@ -426,7 +436,7 @@
self.TagName = tagname
self.TasksDefaultValue = {"Name" : "", "Single" : "", "Interval" : "", "Priority" : 0}
- self.TasksTable = ResourceTable(self, [], ["Name", "Single", "Interval", "Priority"])
+ self.TasksTable = ResourceTable(self, [], GetTasksTableColnames())
self.TasksTable.SetColAlignements([wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_RIGHT, wx.ALIGN_RIGHT])
self.TasksTable.SetColSizes([200, 100, 100, 100])
self.TasksGrid.SetTable(self.TasksTable)
@@ -434,7 +444,7 @@
self.TasksTable.ResetView(self.TasksGrid)
self.InstancesDefaultValue = {"Name" : "", "Type" : "", "Task" : ""}
- self.InstancesTable = ResourceTable(self, [], ["Name", "Type", "Task"])
+ self.InstancesTable = ResourceTable(self, [], GetInstancesTableColnames())
self.InstancesTable.SetColAlignements([wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT])
self.InstancesTable.SetColSizes([200, 150, 150])
self.InstancesGrid.SetTable(self.InstancesTable)
@@ -593,4 +603,4 @@
self.TasksTable.AddError(infos[1:])
elif infos[0] == "instance":
self.InstancesTable.AddError(infos[1:])
-
\ No newline at end of file
+
diff -r e0a6a5952d13 -r 127d524a5f1d SFCViewer.py
--- a/SFCViewer.py Mon Jul 06 11:24:37 2009 -0600
+++ b/SFCViewer.py Thu Aug 20 09:03:31 2009 -0600
@@ -148,7 +148,7 @@
self.RemoveWire(output_wire)
else:
next = None
- action = step.GetActionConnector()
+ action = step.GetActionConnected()
if action:
self.DeleteActionBlock(action.GetParentBlock())
step.Clean()
@@ -230,7 +230,7 @@
else:
self.SelectedElement.OnLeftUp(event, self.GetLogicalDC(), self.Scaling)
self.SelectedElement.Refresh()
- wx.CallAfter(self.SetCursor, wx.NullCursor)
+ wx.CallAfter(self.SetCurrentCursor, 0)
elif self.Mode == MODE_WIRE and self.SelectedElement:
self.SelectedElement.ResetPoints()
self.SelectedElement.OnMotion(event, self.GetLogicalDC(), self.Scaling)
@@ -256,7 +256,7 @@
self.SelectedElement.SetSelected(True)
self.SelectedElement.OnRightUp(event, dc, self.Scaling)
self.SelectedElement.Refresh()
- wx.CallAfter(self.SetCursor, wx.NullCursor)
+ wx.CallAfter(self.SetCurrentCursor, 0)
event.Skip()
def OnViewerLeftDClick(self, event):
@@ -359,7 +359,7 @@
#-------------------------------------------------------------------------------
def AddInitialStep(self, pos):
- dialog = StepNameDialog(self.ParentWindow, "Please enter step name", "Add a new initial step", "", wx.OK|wx.CANCEL)
+ dialog = StepNameDialog(self.ParentWindow, _("Please enter step name"), _("Add a new initial step"), "", wx.OK|wx.CANCEL)
dialog.SetPouNames(self.Controler.GetProjectPouNames(self.Debug))
dialog.SetVariables(self.Controler.GetEditedElementInterfaceVars(self.TagName, self.Debug))
dialog.SetStepNames([block.GetName() for block in self.Blocks if isinstance(block, SFC_Step)])
@@ -381,7 +381,7 @@
def AddStep(self):
if self.SelectedElement in self.Wires or isinstance(self.SelectedElement, SFC_Step):
- dialog = StepNameDialog(self.ParentWindow, "Add a new step", "Please enter step name", "", wx.OK|wx.CANCEL)
+ dialog = StepNameDialog(self.ParentWindow, _("Add a new step"), _("Please enter step name"), "", wx.OK|wx.CANCEL)
dialog.SetPouNames(self.Controler.GetProjectPouNames(self.Debug))
dialog.SetVariables(self.Controler.GetEditedElementInterfaceVars(self.TagName, self.Debug))
dialog.SetStepNames([block.GetName() for block in self.Blocks if isinstance(block, SFC_Step)])
@@ -695,7 +695,7 @@
for block in self.Blocks:
if isinstance(block, SFC_Step):
choices.append(block.GetName())
- dialog = wx.SingleChoiceDialog(self.ParentWindow, "Add a new jump", "Please choose a target", choices, wx.OK|wx.CANCEL)
+ dialog = wx.SingleChoiceDialog(self.ParentWindow, _("Add a new jump"), _("Please choose a target"), choices, wx.OK|wx.CANCEL)
if dialog.ShowModal() == wx.ID_OK:
value = dialog.GetStringSelection()
self.SelectedElement.AddOutput()
@@ -723,7 +723,7 @@
if self.GetDrawingMode() == FREEDRAWING_MODE:
Viewer.EditStepContent(self, step)
else:
- dialog = StepNameDialog(self.ParentWindow, "Edit step name", "Please enter step name", step.GetName(), wx.OK|wx.CANCEL)
+ dialog = StepNameDialog(self.ParentWindow, _("Edit step name"), _("Please enter step name"), step.GetName(), wx.OK|wx.CANCEL)
dialog.SetPouNames(self.Controler.GetProjectPouNames(self.Debug))
dialog.SetVariables(self.Controler.GetEditedElementInterfaceVars(self.TagName, self.Debug))
dialog.SetStepNames([block.GetName() for block in self.Blocks if isinstance(block, SFC_Step) and block.GetName() != step.GetName()])
diff -r e0a6a5952d13 -r 127d524a5f1d TextViewer.py
--- a/TextViewer.py Mon Jul 06 11:24:37 2009 -0600
+++ b/TextViewer.py Thu Aug 20 09:03:31 2009 -0600
@@ -221,7 +221,7 @@
wx.CallAfter(self.RefreshModel)
else:
event.SetDragText("")
- message = wx.MessageDialog(self.ParentWindow, "Variable don't belong to this POU!", "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self.ParentWindow, _("Variable don't belong to this POU!"), _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
event.Skip()
diff -r e0a6a5952d13 -r 127d524a5f1d Viewer.py
--- a/Viewer.py Mon Jul 06 11:24:37 2009 -0600
+++ b/Viewer.py Thu Aug 20 09:03:31 2009 -0600
@@ -41,6 +41,18 @@
WINDOW_BORDER = 10
SCROLL_ZONE = 10
+CURSORS = None
+
+def ResetCursors():
+ global CURSORS
+ if CURSORS == None:
+ CURSORS = [wx.NullCursor,
+ wx.StockCursor(wx.CURSOR_HAND),
+ wx.StockCursor(wx.CURSOR_SIZENWSE),
+ wx.StockCursor(wx.CURSOR_SIZENESW),
+ wx.StockCursor(wx.CURSOR_SIZEWE),
+ wx.StockCursor(wx.CURSOR_SIZENS)]
+
def AppendMenu(parent, help, id, kind, text):
if wx.VERSION >= (2, 6, 0):
parent.Append(help=help, id=id, kind=kind, text=text)
@@ -64,6 +76,102 @@
ZOOM_FACTORS = [math.sqrt(2) ** x for x in xrange(-6, 7)]
+
+def GetVariableCreationFunction(variable_type):
+ def variableCreationFunction(viewer, id, specific_values):
+ return FBD_Variable(viewer, variable_type,
+ specific_values["name"],
+ specific_values["value_type"],
+ id,
+ specific_values["executionOrder"])
+ return variableCreationFunction
+
+def GetConnectorCreationFunction(connector_type):
+ def connectorCreationFunction(viewer, id, specific_values):
+ return FBD_Connector(viewer, connector_type,
+ specific_values["name"], id)
+ return connectorCreationFunction
+
+def commentCreationFunction(viewer, id, specific_values):
+ return Comment(viewer, specific_values["content"], id)
+
+def GetPowerRailCreationFunction(powerrail_type):
+ def powerRailCreationFunction(viewer, id, specific_values):
+ return LD_PowerRail(viewer, powerrail_type, id,
+ specific_values["connectors"])
+ return powerRailCreationFunction
+
+CONTACT_TYPES = {(True, "none"): CONTACT_REVERSE,
+ (False, "rising"): CONTACT_RISING,
+ (False, "falling"): CONTACT_FALLING}
+
+def contactCreationFunction(viewer, id, specific_values):
+ contact_type = CONTACT_TYPES.get((specific_values.get("negated", False),
+ specific_values.get("edge", "none")),
+ CONTACT_NORMAL)
+ return LD_Contact(viewer, contact_type, specific_values["name"], id)
+
+COIL_TYPES = {(True, "none", "none"): COIL_REVERSE,
+ (False, "none", "set"): COIL_SET,
+ (False, "none", "reset"): COIL_RESET,
+ (False, "rising", "none"): COIL_RISING,
+ (False, "falling", "none"): COIL_FALLING}
+
+def coilCreationFunction(viewer, id, specific_values):
+ coil_type = COIL_TYPES.get((specific_values.get("negated", False),
+ specific_values.get("edge", "none"),
+ specific_values.get("storage", "none")),
+ COIL_NORMAL)
+ return LD_Coil(viewer, coil_type, specific_values["name"], id)
+
+def stepCreationFunction(viewer, id, specific_values):
+ step = SFC_Step(viewer, specific_values["name"],
+ specific_values.get("initial", False), id)
+ if specific_values.get("action", None):
+ step.AddAction()
+ connector = step.GetActionConnector()
+ connector.SetPosition(wx.Point(*specific_values["action"]["position"]))
+ return step
+
+def transitionCreationFunction(viewer, id, specific_values):
+ transition = SFC_Transition(viewer, specific_values["condition_type"],
+ specific_values.get("condition", None),
+ specific_values["priority"], id)
+ return transition
+
+def GetDivergenceCreationFunction(divergence_type):
+ def divergenceCreationFunction(viewer, id, specific_values):
+ return SFC_Divergence(viewer, divergence_type,
+ specific_values["connectors"], id)
+ return divergenceCreationFunction
+
+def jumpCreationFunction(viewer, id, specific_values):
+ return SFC_Jump(viewer, specific_values["target"], id)
+
+def actionBlockCreationFunction(viewer, id, specific_values):
+ return SFC_ActionBlock(viewer, specific_values["actions"], id)
+
+ElementCreationFunctions = {
+ "input": GetVariableCreationFunction(INPUT),
+ "output": GetVariableCreationFunction(OUTPUT),
+ "inout": GetVariableCreationFunction(INOUT),
+ "connector": GetConnectorCreationFunction(CONNECTOR),
+ "continuation": GetConnectorCreationFunction(CONTINUATION),
+ "comment": commentCreationFunction,
+ "leftPowerRail": GetPowerRailCreationFunction(LEFTRAIL),
+ "rightPowerRail": GetPowerRailCreationFunction(RIGHTRAIL),
+ "contact": contactCreationFunction,
+ "coil": coilCreationFunction,
+ "step": stepCreationFunction,
+ "transition": transitionCreationFunction,
+ "selectionDivergence": GetDivergenceCreationFunction(SELECTION_DIVERGENCE),
+ "selectionConvergence": GetDivergenceCreationFunction(SELECTION_CONVERGENCE),
+ "simultaneousDivergence": GetDivergenceCreationFunction(SIMULTANEOUS_DIVERGENCE),
+ "simultaneousConvergence": GetDivergenceCreationFunction(SIMULTANEOUS_CONVERGENCE),
+ "jump": jumpCreationFunction,
+ "actionBlock": actionBlockCreationFunction,
+}
+
#-------------------------------------------------------------------------------
# Graphic elements Viewer base class
#-------------------------------------------------------------------------------
@@ -100,27 +208,27 @@
try:
values = eval(data)
except:
- message = "Invalid value \"%s\" for viewer block"%data
+ message = _("Invalid value \"%s\" for viewer block")%data
values = None
if not isinstance(values, TupleType):
- message = "Invalid value \"%s\" for viewer block"%data
+ message = _("Invalid value \"%s\" for viewer block")%data
values = None
if values is not None:
if values[1] == "debug":
pass
elif values[1] == "program":
- message = "Programs can't be used by other POUs!"
+ message = _("Programs can't be used by other POUs!")
elif values[1] in ["function", "functionBlock", "program"]:
name, type = self.ParentWindow.Controler.GetEditedElementType(self.ParentWindow.GetTagName(), self.ParentWindow.Debug)
words = self.ParentWindow.TagName.split("::")
if name == values[0]:
- message = "\"%s\" can't use itself!"%name
+ message = _("\"%s\" can't use itself!")%name
elif type == "function" and values[1] != "function":
- message = "Function Blocks can't be used in Functions!"
+ message = _("Function Blocks can't be used in Functions!")
elif words[0] == "T" and values[1] != "function":
- message = "Function Blocks can't be used in Transitions!"
+ message = _("Function Blocks can't be used in Transitions!")
elif self.ParentWindow.Controler.PouIsUsedBy(name, values[0], self.ParentWindow.Debug):
- message = "\"%s\" is already used by \"%s\"!"%(name, values[0])
+ message = _("\"%s\" is already used by \"%s\"!")%(name, values[0])
else:
blockname = values[2]
if len(values) > 3:
@@ -135,9 +243,9 @@
return
dialog.Destroy()
if blockname.upper() in [name.upper() for name in self.ParentWindow.Controler.GetProjectPouNames(self.ParentWindow.Debug)]:
- message = "\"%s\" pou already exists!"%blockname
+ message = _("\"%s\" pou already exists!")%blockname
elif blockname.upper() in [name.upper() for name in self.ParentWindow.Controler.GetEditedElementVariables(self.ParentWindow.GetTagName(), self.ParentWindow.Debug)]:
- message = "\"%s\" element for this pou already exists!"%blockname
+ message = _("\"%s\" element for this pou already exists!")%blockname
else:
id = self.ParentWindow.GetNewId()
block = FBD_Block(self.ParentWindow, values[0], blockname, id, inputs = blockinputs)
@@ -175,9 +283,9 @@
else:
self.AddParentVariableBlock(x, y, scaling, var_class, values[0], values[2])
else:
- message = "Unknown variable \"%s\" this POU!" % values[0]
+ message = _("Unknown variable \"%s\" for this POU!") % values[0]
else:
- message = "Variable don't belong to this POU!"
+ message = _("Variable don't belong to this POU!")
if message is not None:
wx.CallAfter(self.ShowMessage, message)
@@ -224,7 +332,7 @@
self.ParentWindow.Refresh(False)
def ShowMessage(self, message):
- message = wx.MessageDialog(self.ParentWindow, message, "Error", wx.OK|wx.ICON_ERROR)
+ message = wx.MessageDialog(self.ParentWindow, message, _("Error"), wx.OK|wx.ICON_ERROR)
message.ShowModal()
message.Destroy()
@@ -247,18 +355,18 @@
def _init_coll_AlignmentMenu_Items(self, parent):
# Create menu items
AppendMenu(parent, help='', id=ID_VIEWERALIGNMENTMENUITEMS0,
- kind=wx.ITEM_NORMAL, text=u'Left')
+ kind=wx.ITEM_NORMAL, text=_(u'Left'))
AppendMenu(parent, help='', id=ID_VIEWERALIGNMENTMENUITEMS1,
- kind=wx.ITEM_NORMAL, text=u'Center')
+ kind=wx.ITEM_NORMAL, text=_(u'Center'))
AppendMenu(parent, help='', id=ID_VIEWERALIGNMENTMENUITEMS2,
- kind=wx.ITEM_NORMAL, text=u'Right')
+ kind=wx.ITEM_NORMAL, text=_(u'Right'))
parent.AppendSeparator()
AppendMenu(parent, help='', id=ID_VIEWERALIGNMENTMENUITEMS4,
- kind=wx.ITEM_NORMAL, text=u'Top')
+ kind=wx.ITEM_NORMAL, text=_(u'Top'))
AppendMenu(parent, help='', id=ID_VIEWERALIGNMENTMENUITEMS5,
- kind=wx.ITEM_NORMAL, text=u'Middle')
+ kind=wx.ITEM_NORMAL, text=_(u'Middle'))
AppendMenu(parent, help='', id=ID_VIEWERALIGNMENTMENUITEMS6,
- kind=wx.ITEM_NORMAL, text=u'Bottom')
+ kind=wx.ITEM_NORMAL, text=_(u'Bottom'))
# Link menu event to corresponding called functions
self.Bind(wx.EVT_MENU, self.OnAlignLeftMenu,
id=ID_VIEWERALIGNMENTMENUITEMS0)
@@ -277,35 +385,35 @@
def _init_coll_ContextualMenu_Items(self, parent):
# Create menu items
AppendMenu(parent, help='', id=ID_VIEWERCONTEXTUALMENUITEMS0,
- kind=wx.ITEM_RADIO, text=u'No Modifier')
+ kind=wx.ITEM_RADIO, text=_(u'No Modifier'))
AppendMenu(parent, help='', id=ID_VIEWERCONTEXTUALMENUITEMS1,
- kind=wx.ITEM_RADIO, text=u'Negated')
+ kind=wx.ITEM_RADIO, text=_(u'Negated'))
AppendMenu(parent, help='', id=ID_VIEWERCONTEXTUALMENUITEMS2,
- kind=wx.ITEM_RADIO, text=u'Rising Edge')
+ kind=wx.ITEM_RADIO, text=_(u'Rising Edge'))
AppendMenu(parent, help='', id=ID_VIEWERCONTEXTUALMENUITEMS3,
- kind=wx.ITEM_RADIO, text=u'Falling Edge')
+ kind=wx.ITEM_RADIO, text=_(u'Falling Edge'))
parent.AppendSeparator()
AppendMenu(parent, help='', id=ID_VIEWERCONTEXTUALMENUITEMS5,
- kind=wx.ITEM_NORMAL, text=u'Add Wire Segment')
+ kind=wx.ITEM_NORMAL, text=_(u'Add Wire Segment'))
AppendMenu(parent, help='', id=ID_VIEWERCONTEXTUALMENUITEMS6,
- kind=wx.ITEM_NORMAL, text=u'Delete Wire Segment')
+ kind=wx.ITEM_NORMAL, text=_(u'Delete Wire Segment'))
parent.AppendSeparator()
AppendMenu(parent, help='', id=ID_VIEWERCONTEXTUALMENUITEMS8,
- kind=wx.ITEM_NORMAL, text=u'Add Divergence Branch')
+ kind=wx.ITEM_NORMAL, text=_(u'Add Divergence Branch'))
AppendMenu(parent, help='', id=ID_VIEWERCONTEXTUALMENUITEMS9,
- kind=wx.ITEM_NORMAL, text=u'Delete Divergence Branch')
+ kind=wx.ITEM_NORMAL, text=_(u'Delete Divergence Branch'))
parent.AppendSeparator()
AppendMenu(parent, help='', id=ID_VIEWERCONTEXTUALMENUITEMS11,
- kind=wx.ITEM_NORMAL, text=u'Clear Execution Order')
+ kind=wx.ITEM_NORMAL, text=_(u'Clear Execution Order'))
AppendMenu(parent, help='', id=ID_VIEWERCONTEXTUALMENUITEMS12,
- kind=wx.ITEM_NORMAL, text=u'Reset Execution Order')
+ kind=wx.ITEM_NORMAL, text=_(u'Reset Execution Order'))
parent.AppendSeparator()
- parent.AppendMenu(ID_VIEWERCONTEXTUALMENUITEMS14, "Alignment", self.AlignmentMenu)
+ parent.AppendMenu(ID_VIEWERCONTEXTUALMENUITEMS14, _("Alignment"), self.AlignmentMenu)
parent.AppendSeparator()
AppendMenu(parent, help='', id=ID_VIEWERCONTEXTUALMENUITEMS16,
- kind=wx.ITEM_NORMAL, text=u'Edit Block')
+ kind=wx.ITEM_NORMAL, text=_(u'Edit Block'))
AppendMenu(parent, help='', id=ID_VIEWERCONTEXTUALMENUITEMS17,
- kind=wx.ITEM_NORMAL, text=u'Delete')
+ kind=wx.ITEM_NORMAL, text=_(u'Delete'))
# Link menu event to corresponding called functions
self.Bind(wx.EVT_MENU, self.OnNoModifierMenu,
id=ID_VIEWERCONTEXTUALMENUITEMS0)
@@ -364,8 +472,12 @@
self.StartMousePos = None
self.StartScreenPos = None
+ # Initialize Cursors
+ ResetCursors()
+ self.CurrentCursor = 0
+
# Initialize Block, Wire and Comment numbers
- self.block_id = self.wire_id = self.comment_id = 0
+ self.wire_id = 0
# Initialize Viewer mode to Selection mode
self.Mode = MODE_SELECTION
@@ -414,6 +526,12 @@
self.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheelWindow)
self.Bind(wx.EVT_SIZE, self.OnMoveWindow)
+ def SetCurrentCursor(self, cursor):
+ global CURSORS
+ if self.CurrentCursor != cursor:
+ self.CurrentCursor = cursor
+ self.SetCursor(CURSORS[cursor])
+
def GetScrolledRect(self, rect):
rect.x, rect.y = self.CalcScrolledPosition(int(rect.x * self.ViewScale[0]),
int(rect.y * self.ViewScale[1]))
@@ -483,47 +601,53 @@
#-------------------------------------------------------------------------------
def AddBlock(self, block):
- self.block_id += 1
- self.Blocks[block] = self.block_id
+ self.Blocks[block.GetId()] = block
def AddWire(self, wire):
self.wire_id += 1
self.Wires[wire] = self.wire_id
def AddComment(self, comment):
- self.comment_id += 1
- self.Comments[comment] = self.comment_id
+ self.Comments[comment.GetId()] = comment
def IsBlock(self, block):
- return self.Blocks.get(block, False)
+ return self.Blocks.get(block.GetId(), False)
def IsWire(self, wire):
return self.Wires.get(wire, False)
def IsComment(self, comment):
- return self.Comments.get(comment, False)
+ return self.Comments.get(comment.GetId(), False)
def RemoveBlock(self, block):
- self.Blocks.pop(block)
+ self.Blocks.pop(block.GetId())
def RemoveWire(self, wire):
self.Wires.pop(wire)
def RemoveComment(self, comment):
- self.Comments.pop(comment)
+ self.Comments.pop(comment.GetId())
def GetElements(self, sort_blocks=False, sort_wires=False, sort_comments=False):
- blocks = self.Blocks.keys()
+ blocks = self.Blocks.values()
wires = self.Wires.keys()
- comments = self.Comments.keys()
+ comments = self.Comments.values()
if sort_blocks:
- blocks.sort(lambda x, y: cmp(self.Blocks[x], self.Blocks[y]))
+ blocks.sort(lambda x, y: cmp(x.GetId(), y.GetId()))
if sort_wires:
wires.sort(lambda x, y: cmp(self.Wires[x], self.Wires[y]))
if sort_comments:
- comments.sort(lambda x, y: cmp(self.Comments[x], self.Comments[y]))
+ comments.sort(lambda x, y: cmp(x.GetId(), y.GetId()))
return blocks + wires + comments
+ def GetConnectorByName(self, name):
+ for block in self.Blocks.itervalues():
+ if isinstance(block, FBD_Connector) and\
+ block.GetType() == CONNECTOR and\
+ block.GetName() == name:
+ return block
+ return None
+
def RefreshVisibleElements(self, xp = None, yp = None):
x, y = self.CalcUnscrolledPosition(0, 0)
if xp is not None:
@@ -533,11 +657,11 @@
width, height = self.GetClientSize()
screen = wx.Rect(int(x / self.ViewScale[0]), int(y / self.ViewScale[1]),
int(width / self.ViewScale[0]), int(height / self.ViewScale[1]))
- for comment in self.Comments:
+ for comment in self.Comments.itervalues():
comment.TestVisible(screen)
- for wire in self.Wires:
+ for wire in self.Wires.iterkeys():
wire.TestVisible(screen)
- for block in self.Blocks:
+ for block in self.Blocks.itervalues():
block.TestVisible(screen)
def GetElementIECPath(self, element):
@@ -556,6 +680,12 @@
iec_path = "%s.%s%d_%s"%(self.InstancePath, block.GetType(), block.GetId(), connectorname)
elif isinstance(block, FBD_Variable):
iec_path = "%s.%s"%(self.InstancePath, block.GetName())
+ elif isinstance(block, FBD_Connector):
+ connection = self.GetConnectorByName(block.GetName())
+ if connection is not None:
+ connector = connection.GetConnector()
+ if len(connector.Wires) == 1:
+ iec_path = self.GetElementIECPath(connector.Wires[0][0])
elif isinstance(element, LD_Contact):
iec_path = "%s.%s"%(self.InstancePath, element.GetName())
elif isinstance(element, SFC_Step):
@@ -582,12 +712,12 @@
def Flush(self):
self.DeleteDataConsumers()
- for block in self.Blocks:
+ for block in self.Blocks.itervalues():
block.Flush()
# Remove all elements
def CleanView(self):
- for block in self.Blocks.keys():
+ for block in self.Blocks.itervalues():
block.Clean()
self.ResetView()
@@ -617,7 +747,7 @@
def RefreshScaling(self, refresh=True):
properties = self.Controler.GetProjectProperties(self.Debug)
scaling = properties["scaling"][self.CurrentLanguage]
- if scaling != (0, 0):
+ if scaling[0] != 0 and scaling[1] != 0:
self.Scaling = scaling
if self.DrawGrid:
width = max(2, int(scaling[0] * self.ViewScale[0]))
@@ -667,7 +797,7 @@
pass
# Refresh Viewer elements
- def RefreshView(self):
+ def RefreshView(self, selection=None):
self.Inhibit(True)
self.current_id = 0
# Start by reseting Viewer
@@ -680,37 +810,19 @@
while instance is not None:
instance = self.Controler.GetEditedElementInstanceInfos(self.TagName, exclude = ids, debug = self.Debug)
if instance is not None:
- self.loadInstance(instance, ids)
+ self.loadInstance(instance, ids, selection)
self.RefreshScrollBars()
for wire in self.Wires:
if not wire.IsConnectedCompatible():
wire.SetValid(False)
if self.Debug:
- block = wire.EndConnected.GetParentBlock()
- if isinstance(block, LD_PowerRail):
- wire.SetValue(True)
- if isinstance(block, FBD_Block):
- blockname = block.GetName()
- connectorname = wire.EndConnected.GetName()
- if blockname != "":
- iec_path = "%s.%s.%s"%(self.InstancePath, blockname, connectorname)
- else:
- if connectorname == "":
- iec_path = "%s.%s%d"%(self.InstancePath, block.GetType(), block.GetId())
- else:
- iec_path = "%s.%s%d_%s"%(self.InstancePath, block.GetType(), block.GetId(), connectorname)
- if self.AddDataConsumer(iec_path.upper(), wire) is None:
- wire.SetValue("undefined")
- elif isinstance(block, FBD_Variable):
- iec_path = "%s.%s"%(self.InstancePath, block.GetName())
- if self.AddDataConsumer(iec_path.upper(), wire) is None:
- wire.SetValue("undefined")
- elif isinstance(block, FBD_Connector):
+ iec_path = self.GetElementIECPath(wire)
+ if self.AddDataConsumer(iec_path.upper(), wire) is None:
wire.SetValue("undefined")
if self.Debug:
- for block in self.Blocks.keys():
+ for block in self.Blocks.itervalues():
block.SpreadCurrent()
iec_path = self.GetElementIECPath(block)
if iec_path is not None:
@@ -770,229 +882,46 @@
self.SetScrollbars(SCROLLBAR_UNIT, SCROLLBAR_UNIT,
round(maxx / SCROLLBAR_UNIT) + width_incr, round(maxy / SCROLLBAR_UNIT) + height_incr,
xstart, ystart, True)
+
+ def SelectInGroup(self, element):
+ element.SetSelected(True)
+ if self.SelectedElement is None:
+ self.SelectedElement = element
+ elif isinstance(self.SelectedElement, Graphic_Group):
+ self.SelectedElement.SelectElement(element)
+ else:
+ group = Graphic_Group(self)
+ group.SelectElement(self.SelectedElement)
+ group.SelectElement(element)
+ self.SelectedElement = group
# Load instance from given informations
- def loadInstance(self, instance, ids):
+ def loadInstance(self, instance, ids, selection):
ids.append(instance["id"])
- self.current_id = max(self.current_id, instance["id"])
- if instance["type"] == "input":
- variable = FBD_Variable(self, INPUT, instance["name"], instance["value_type"], instance["id"], instance["executionOrder"])
- variable.SetPosition(instance["x"], instance["y"])
- variable.SetSize(instance["width"], instance["height"])
- self.AddBlock(variable)
- connectors = variable.GetConnectors()
- connectors["output"].SetPosition(wx.Point(*instance["connector"]["position"]))
- if instance["connector"]["negated"]:
- connectors["output"].SetNegated(True)
- if instance["connector"]["edge"]:
- connectors["output"].SetEdge(instance["connector"]["edge"])
- elif instance["type"] == "output":
- variable = FBD_Variable(self, OUTPUT, instance["name"], instance["value_type"], instance["id"], instance["executionOrder"])
- variable.SetPosition(instance["x"], instance["y"])
- variable.SetSize(instance["width"], instance["height"])
- self.AddBlock(variable)
- connectors = variable.GetConnectors()
- connectors["input"].SetPosition(wx.Point(*instance["connector"]["position"]))
- if instance["connector"]["negated"]:
- connectors["input"].SetNegated(True)
- if instance["connector"]["edge"]:
- connectors["input"].SetEdge(instance["connector"]["edge"])
- self.CreateWires(connectors["input"], instance["connector"]["links"], ids)
- elif instance["type"] == "inout":
- variable = FBD_Variable(self, INOUT, instance["name"], instance["value_type"], instance["id"], instance["executionOrder"])
- variable.SetPosition(instance["x"], instance["y"])
- variable.SetSize(instance["width"], instance["height"])
- self.AddBlock(variable)
- connectors = variable.GetConnectors()
- connectors["output"].SetPosition(wx.Point(*instance["connectors"]["output"]["position"]))
- connectors["input"].SetPosition(wx.Point(*instance["connectors"]["input"]["position"]))
- if instance["connectors"]["output"]["negated"]:
- connectors["output"].SetNegated(True)
- if instance["connectors"]["output"]["edge"]:
- connectors["output"].SetEdge(instance["connectors"]["output"]["edge"])
- if instance["connectors"]["input"]["negated"]:
- connectors["input"].SetNegated(True)
- if instance["connectors"]["input"]["edge"]:
- connectors["input"].SetEdge(instance["connectors"]["input"]["edge"])
- self.CreateWires(connectors["input"], instance["connectors"]["input"]["links"], ids)
- elif instance["type"] == "continuation":
- connection = FBD_Connector(self, CONTINUATION, instance["name"], instance["id"])
- connection.SetPosition(instance["x"], instance["y"])
- connection.SetSize(instance["width"], instance["height"])
- self.AddBlock(connection)
- connector = connection.GetConnector()
- connector.SetPosition(wx.Point(*instance["connector"]["position"]))
- elif instance["type"] == "connection":
- connection = FBD_Connector(self, CONNECTOR, instance["name"], instance["id"])
- connection.SetPosition(instance["x"], instance["y"])
- connection.SetSize(instance["width"], instance["height"])
- self.AddBlock(connection)
- connector = connection.GetConnector()
- connector.SetPosition(wx.Point(*instance["connector"]["position"]))
- self.CreateWires(connector, instance["connector"]["links"], ids)
- elif instance["type"] == "comment":
- comment = Comment(self, instance["content"], instance["id"])
- comment.SetPosition(instance["x"], instance["y"])
- comment.SetSize(instance["width"], instance["height"])
- self.AddComment(comment)
- elif instance["type"] == "leftPowerRail":
- leftpowerrail = LD_PowerRail(self, LEFTRAIL, instance["id"], [True for i in range(len(instance["connectors"]))])
- leftpowerrail.SetPosition(instance["x"], instance["y"])
- leftpowerrail.SetSize(instance["width"], instance["height"])
- self.AddBlock(leftpowerrail)
- connectors = leftpowerrail.GetConnectors()
- for i, connector in enumerate(instance["connectors"]):
- connectors[i].SetPosition(wx.Point(*connector["position"]))
- elif instance["type"] == "rightPowerRail":
- rightpowerrail = LD_PowerRail(self, RIGHTRAIL, instance["id"], [True for i in range(len(instance["connectors"]))])
- rightpowerrail.SetPosition(instance["x"], instance["y"])
- rightpowerrail.SetSize(instance["width"], instance["height"])
- self.AddBlock(rightpowerrail)
- connectors = rightpowerrail.GetConnectors()
- for i, connector in enumerate(instance["connectors"]):
- connectors[i].SetPosition(wx.Point(*connector["position"]))
- self.CreateWires(connectors[i], connector["links"], ids)
- elif instance["type"] == "contact":
- if instance["negated"]:
- negated = instance["negated"]
- else:
- negated = False
- if instance["edge"]:
- edge = instance["edge"]
- else:
- edge = "none"
- if negated and edge == "none":
- contact_type = CONTACT_REVERSE
- elif not negated and edge == "rising":
- contact_type = CONTACT_RISING
- elif not negated and edge == "falling":
- contact_type = CONTACT_FALLING
- else:
- contact_type = CONTACT_NORMAL
- contact = LD_Contact(self, contact_type, instance["name"], instance["id"])
- contact.SetPosition(instance["x"], instance["y"])
- contact.SetSize(instance["width"], instance["height"])
- self.AddBlock(contact)
- connectors = contact.GetConnectors()
- connectors["input"].SetPosition(wx.Point(*instance["connectors"]["input"]["position"]))
- self.CreateWires(connectors["input"], instance["connectors"]["input"]["links"], ids)
- connectors["output"].SetPosition(wx.Point(*instance["connectors"]["output"]["position"]))
- elif instance["type"] == "coil":
- if instance["negated"]:
- negated = instance["negated"]
- else:
- negated = False
- if instance["storage"]:
- storage = instance["storage"]
- else:
- storage = "none"
- if instance["edge"]:
- edge = instance["edge"]
- else:
- edge = "none"
- if negated and storage == "none" and edge == "none":
- coil_type = COIL_REVERSE
- elif not negated and edge == "none" and storage == "set":
- coil_type = COIL_SET
- elif not negated and edge == "none" and storage == "reset":
- coil_type = COIL_RESET
- elif not negated and storage == "none" and edge == "rising":
- coil_type = COIL_RISING
- elif not negated and storage == "none" and edge == "falling":
- coil_type = COIL_FALLING
- else:
- coil_type = COIL_NORMAL
- coil = LD_Coil(self, coil_type, instance["name"], instance["id"])
- coil.SetPosition(instance["x"], instance["y"])
- coil.SetSize(instance["width"], instance["height"])
- self.AddBlock(coil)
- connectors = coil.GetConnectors()
- connectors["input"].SetPosition(wx.Point(*instance["connectors"]["input"]["position"]))
- self.CreateWires(connectors["input"], instance["connectors"]["input"]["links"], ids)
- connectors["output"].SetPosition(wx.Point(*instance["connectors"]["output"]["position"]))
- elif instance["type"] == "step":
- if instance["initial"]:
- initial = instance["initial"]
- else:
- initial = False
- step = SFC_Step(self, instance["name"], initial, instance["id"])
- step.SetPosition(instance["x"], instance["y"])
- step.SetSize(instance["width"], instance["height"])
- self.AddBlock(step)
- if "output" in instance["connectors"]:
- step.AddOutput()
- if "action" in instance["connectors"]:
- step.AddAction()
- connectors = step.GetConnectors()
- if connectors["input"]:
- connectors["input"].SetPosition(wx.Point(*instance["connectors"]["input"]["position"]))
- self.CreateWires(connectors["input"], instance["connectors"]["input"]["links"], ids)
- if connectors["output"]:
- connectors["output"].SetPosition(wx.Point(*instance["connectors"]["output"]["position"]))
- if connectors["action"]:
- connectors["action"].SetPosition(wx.Point(*instance["connectors"]["action"]["position"]))
- elif instance["type"] == "transition":
- transition = SFC_Transition(self, instance["condition_type"], instance["condition"], instance["priority"], instance["id"])
- transition.SetPosition(instance["x"], instance["y"])
- transition.SetSize(instance["width"], instance["height"])
- self.AddBlock(transition)
- connectors = transition.GetConnectors()
- connectors["input"].SetPosition(wx.Point(*instance["connectors"]["input"]["position"]))
- self.CreateWires(connectors["input"], instance["connectors"]["input"]["links"], ids)
- connectors["output"].SetPosition(wx.Point(*instance["connectors"]["output"]["position"]))
- if instance["condition_type"] == "connection":
- self.CreateWires(connectors["connection"], instance["connectors"]["connection"]["links"], ids)
- elif instance["type"] in ["selectionDivergence", "selectionConvergence", "simultaneousDivergence", "simultaneousConvergence"]:
- if instance["type"] == "selectionDivergence":
- divergence = SFC_Divergence(self, SELECTION_DIVERGENCE,
- len(instance["connectors"]["outputs"]), instance["id"])
- elif instance["type"] == "selectionConvergence":
- divergence = SFC_Divergence(self, SELECTION_CONVERGENCE,
- len(instance["connectors"]["inputs"]), instance["id"])
- elif instance["type"] == "simultaneousDivergence":
- divergence = SFC_Divergence(self, SIMULTANEOUS_DIVERGENCE,
- len(instance["connectors"]["outputs"]), instance["id"])
- else:
- divergence = SFC_Divergence(self, SIMULTANEOUS_CONVERGENCE,
- len(instance["connectors"]["inputs"]), instance["id"])
- divergence.SetPosition(instance["x"], instance["y"])
- divergence.SetSize(instance["width"], instance["height"])
- self.AddBlock(divergence)
- connectors = divergence.GetConnectors()
- for i, input_connector in enumerate(instance["connectors"]["inputs"]):
- connector = connectors["inputs"][i]
- connector.SetPosition(wx.Point(*input_connector["position"]))
- self.CreateWires(connector, input_connector["links"], ids)
- for i, output_connector in enumerate(instance["connectors"]["outputs"]):
- connector = connectors["outputs"][i]
- connector.SetPosition(wx.Point(*output_connector["position"]))
- elif instance["type"] == "jump":
- jump = SFC_Jump(self, instance["target"], instance["id"])
- jump.SetPosition(instance["x"], instance["y"])
- jump.SetSize(instance["width"], instance["height"])
- self.AddBlock(jump)
- connector = jump.GetConnector()
- connector.SetPosition(wx.Point(*instance["connector"]["position"]))
- self.CreateWires(connector, instance["connector"]["links"], ids)
- elif instance["type"] == "actionBlock":
- actionBlock = SFC_ActionBlock(self, instance["actions"], instance["id"])
- actionBlock.SetPosition(instance["x"], instance["y"])
- actionBlock.SetSize(instance["width"], instance["height"])
- self.AddBlock(actionBlock)
- connector = actionBlock.GetConnector()
- connector.SetPosition(wx.Point(*instance["connector"]["position"]))
- self.CreateWires(connector, instance["connector"]["links"], ids)
+ self.current_id = max(self.current_id, instance["id"])
+ creation_function = ElementCreationFunctions.get(instance["type"], None)
+ connectors = {"inputs" : [], "outputs" : []}
+ specific_values = instance["specific_values"]
+ if creation_function is not None:
+ element = creation_function(self, instance["id"], specific_values)
+ if isinstance(element, SFC_Step):
+ if len(instance["inputs"]) > 0:
+ element.AddInput()
+ if len(instance["outputs"]) > 0:
+ element.AddOutput()
+ if isinstance(element, SFC_Transition) and specific_values["condition_type"] == "connection":
+ connector = element.GetConditionConnector()
+ self.CreateWires(connector, id, specific_values["connection"]["links"], ids, selection)
else:
- connectors = {"inputs" : [], "outputs" : []}
executionControl = False
- for input in instance["connectors"]["inputs"]:
+ for input in instance["inputs"]:
if input["negated"]:
connectors["inputs"].append((input["name"], None, "negated"))
elif input["edge"]:
connectors["inputs"].append((input["name"], None, input["edge"]))
else:
connectors["inputs"].append((input["name"], None, "none"))
- for output in instance["connectors"]["outputs"]:
+ for output in instance["outputs"]:
if output["negated"]:
connectors["outputs"].append((output["name"], None, "negated"))
elif output["edge"]:
@@ -1000,47 +929,52 @@
else:
connectors["outputs"].append((output["name"], None, "none"))
if len(connectors["inputs"]) > 0 and connectors["inputs"][0][0] == "EN":
- connectors["inputs"].pop(0)
- executionControl = True
+ connectors["inputs"].pop(0)
+ executionControl = True
if len(connectors["outputs"]) > 0 and connectors["outputs"][0][0] == "ENO":
connectors["outputs"].pop(0)
executionControl = True
- if instance["name"] is None:
- instance["name"] = ""
- block = FBD_Block(self, instance["type"], instance["name"],
- instance["id"], len(connectors["inputs"]),
- connectors=connectors, executionControl=executionControl,
- executionOrder=instance["executionOrder"])
- block.SetPosition(instance["x"], instance["y"])
- block.SetSize(instance["width"], instance["height"])
- self.AddBlock(block)
- connectors = block.GetConnectors()
- for i, input_connector in enumerate(instance["connectors"]["inputs"]):
- if i < len(connectors["inputs"]):
- connector = connectors["inputs"][i]
- connector.SetPosition(wx.Point(*input_connector["position"]))
- if input_connector["negated"]:
- connector.SetNegated(True)
- if input_connector["edge"] != "none":
- connector.SetEdge(input_connector["edge"])
- self.CreateWires(connector, input_connector["links"], ids)
- for i, output_connector in enumerate(instance["connectors"]["outputs"]):
- if i < len(connectors["outputs"]):
- connector = connectors["outputs"][i]
- if output_connector["negated"]:
- connector.SetNegated(True)
- if output_connector["edge"] != "none":
- connector.SetEdge(output_connector["edge"])
- connector.SetPosition(wx.Point(*output_connector["position"]))
-
- def CreateWires(self, start_connector, links, ids):
+ if specific_values["name"] is None:
+ specific_values["name"] = ""
+ element = FBD_Block(self, instance["type"], specific_values["name"],
+ instance["id"], len(connectors["inputs"]),
+ connectors=connectors, executionControl=executionControl,
+ executionOrder=specific_values["executionOrder"])
+ element.SetPosition(instance["x"], instance["y"])
+ element.SetSize(instance["width"], instance["height"])
+ if isinstance(element, Comment):
+ self.AddComment(element)
+ else:
+ self.AddBlock(element)
+ connectors = element.GetConnectors()
+ for i, input_connector in enumerate(instance["inputs"]):
+ if i < len(connectors["inputs"]):
+ connector = connectors["inputs"][i]
+ connector.SetPosition(wx.Point(*input_connector["position"]))
+ if input_connector.get("negated", False):
+ connector.SetNegated(True)
+ if input_connector.get("edge", "none") != "none":
+ connector.SetEdge(input_connector["edge"])
+ self.CreateWires(connector, instance["id"], input_connector["links"], ids, selection)
+ for i, output_connector in enumerate(instance["outputs"]):
+ if i < len(connectors["outputs"]):
+ connector = connectors["outputs"][i]
+ if output_connector.get("negated", False):
+ connector.SetNegated(True)
+ if output_connector.get("edge", "none") != "none":
+ connector.SetEdge(output_connector["edge"])
+ connector.SetPosition(wx.Point(*output_connector["position"]))
+ if selection is not None and selection[0].get(instance["id"], False):
+ self.SelectInGroup(element)
+
+ def CreateWires(self, start_connector, id, links, ids, selection=None):
for link in links:
refLocalId = link["refLocalId"]
if refLocalId is not None:
if refLocalId not in ids:
new_instance = self.Controler.GetEditedElementInstanceInfos(self.TagName, refLocalId, debug = self.Debug)
if new_instance is not None:
- self.loadInstance(new_instance, ids)
+ self.loadInstance(new_instance, ids, selection)
connected = self.FindElementById(refLocalId)
if connected is not None:
points = link["points"]
@@ -1053,6 +987,10 @@
wire.ConnectStartPoint(None, start_connector)
wire.ConnectEndPoint(None, end_connector)
self.AddWire(wire)
+ if selection is not None and (\
+ selection[1].get((id, refLocalId), False) or \
+ selection[1].get((refLocalId, id), False)):
+ self.SelectInGroup(wire)
def IsOfType(self, type, reference):
return self.Controler.IsOfType(type, reference, self.Debug)
@@ -1068,7 +1006,7 @@
#-------------------------------------------------------------------------------
def FindBlock(self, pos):
- for block in self.Blocks:
+ for block in self.Blocks.itervalues():
if block.HitTest(pos) or block.TestHandle(pos) != (0, 0):
return block
return None
@@ -1089,19 +1027,19 @@
return None
def FindBlockConnector(self, pos, direction = None, exclude = None):
- for block in self.Blocks:
+ for block in self.Blocks.itervalues():
result = block.TestConnector(pos, direction, exclude)
if result:
return result
return None
def FindElementById(self, id):
- for element in self.Blocks:
- if element.GetId() == id:
- return element
- for element in self.Comments:
- if element.GetId() == id:
- return element
+ block = self.Blocks.get(id, None)
+ if block is not None:
+ return block
+ comment = self.Comments.get(id, None)
+ if comment is not None:
+ return comment
return None
def SearchElements(self, bbox):
@@ -1492,7 +1430,7 @@
Graphic_Element.OnLeftUp(self.SelectedElement, event, dc, self.Scaling)
else:
self.SelectedElement.OnLeftUp(event, dc, self.Scaling)
- wx.CallAfter(self.SetCursor, wx.NullCursor)
+ wx.CallAfter(self.SetCurrentCursor, 0)
if self.Mode != MODE_SELECTION and not self.SavedMode:
wx.CallAfter(self.ParentWindow.ResetCurrentMode)
event.Skip()
@@ -1531,7 +1469,7 @@
Graphic_Element.OnRightUp(self.SelectedElement, event, dc, self.Scaling)
else:
self.SelectedElement.OnRightUp(event, dc, self.Scaling)
- wx.CallAfter(self.SetCursor, wx.NullCursor)
+ wx.CallAfter(self.SetCurrentCursor, 0)
elif not self.Debug:
self.PopupDefaultMenu(False)
event.Skip()
@@ -1683,7 +1621,7 @@
self.SelectedElement = None
self.RefreshBuffer()
self.RefreshScrollBars()
- self.SetCursor(wx.NullCursor)
+ wx.CallAfter(self.SetCurrentCursor, 0)
self.RefreshRect(self.GetScrolledRect(rect), False)
elif not self.Debug and keycode == wx.WXK_RETURN and self.SelectedElement is not None:
self.SelectedElement.OnLeftDClick(event, self.GetLogicalDC(), self.Scaling)
@@ -1855,9 +1793,9 @@
def AddNewComment(self, bbox):
if wx.VERSION >= (2, 5, 0):
- dialog = wx.TextEntryDialog(self.ParentWindow, "Edit comment", "Please enter comment text", "", wx.OK|wx.CANCEL|wx.TE_MULTILINE)
+ dialog = wx.TextEntryDialog(self.ParentWindow, _("Edit comment"), _("Please enter comment text"), "", wx.OK|wx.CANCEL|wx.TE_MULTILINE)
else:
- dialog = wx.TextEntryDialog(self.ParentWindow, "Edit comment", "Please enter comment text", "", wx.OK|wx.CANCEL)
+ dialog = wx.TextEntryDialog(self.ParentWindow, _("Edit comment"), _("Please enter comment text"), "", wx.OK|wx.CANCEL)
if dialog.ShowModal() == wx.ID_OK:
value = dialog.GetValue()
id = self.GetNewId()
@@ -1955,7 +1893,7 @@
dialog.SetPreviewFont(self.GetFont())
dialog.SetPouNames(self.Controler.GetProjectPouNames(self.Debug))
dialog.SetVariables(self.Controler.GetEditedElementInterfaceVars(self.TagName, self.Debug))
- dialog.SetStepNames([block.GetName() for block in self.Blocks if isinstance(block, SFC_Step)])
+ dialog.SetStepNames([block.GetName() for block in self.Blocks.itervalues() if isinstance(block, SFC_Step)])
dialog.SetMinStepSize((bbox.width, bbox.height))
if dialog.ShowModal() == wx.ID_OK:
id = self.GetNewId()
@@ -2027,10 +1965,10 @@
def AddNewJump(self, bbox):
choices = []
- for block in self.Blocks:
+ for block in self.Blocks.itervalues():
if isinstance(block, SFC_Step):
choices.append(block.GetName())
- dialog = wx.SingleChoiceDialog(self.ParentWindow, "Add a new jump", "Please choose a target", choices, wx.OK|wx.CANCEL)
+ dialog = wx.SingleChoiceDialog(self.ParentWindow, _("Add a new jump"), _("Please choose a target"), choices, wx.OK|wx.CANCEL)
if dialog.ShowModal() == wx.ID_OK:
id = self.GetNewId()
value = dialog.GetStringSelection()
@@ -2265,13 +2203,13 @@
dialog.SetPreviewFont(self.GetFont())
dialog.SetPouNames(self.Controler.GetProjectPouNames(self.Debug))
dialog.SetVariables(self.Controler.GetEditedElementInterfaceVars(self.TagName, self.Debug))
- dialog.SetStepNames([block.GetName() for block in self.Blocks if isinstance(block, SFC_Step) and block.GetName() != step.GetName()])
+ dialog.SetStepNames([block.GetName() for block in self.Blocks.itervalues() if isinstance(block, SFC_Step) and block.GetName() != step.GetName()])
dialog.SetMinStepSize(step.GetSize())
values = {"name" : step.GetName()}
connectors = step.GetConnectors()
- values["input"] = connectors["input"] != None
- values["output"] = connectors["output"] != None
- values["action"] = connectors["action"] != None
+ values["input"] = len(connectors["inputs"]) > 0
+ values["output"] = len(connectors["outputs"]) > 0
+ values["action"] = step.GetActionConnector() != None
dialog.SetValues(values)
if dialog.ShowModal() == wx.ID_OK:
values = dialog.GetValues()
@@ -2318,10 +2256,10 @@
def EditJumpContent(self, jump):
choices = []
- for block in self.Blocks:
+ for block in self.Blocks.itervalues():
if isinstance(block, SFC_Step):
choices.append(block.GetName())
- dialog = wx.SingleChoiceDialog(self.ParentWindow, "Edit jump target", "Please choose a target", choices, wx.OK|wx.CANCEL)
+ dialog = wx.SingleChoiceDialog(self.ParentWindow, _("Edit jump target"), _("Please choose a target"), choices, wx.OK|wx.CANCEL)
dialog.SetSelection(choices.index(jump.GetTarget()))
if dialog.ShowModal() == wx.ID_OK:
value = dialog.GetStringSelection()
@@ -2356,9 +2294,9 @@
def EditCommentContent(self, comment):
if wx.VERSION >= (2, 5, 0):
- dialog = wx.TextEntryDialog(self.ParentWindow, "Edit comment", "Please enter comment text", comment.GetContent(), wx.OK|wx.CANCEL|wx.TE_MULTILINE)
+ dialog = wx.TextEntryDialog(self.ParentWindow, _("Edit comment"), _("Please enter comment text"), comment.GetContent(), wx.OK|wx.CANCEL|wx.TE_MULTILINE)
else:
- dialog = wx.TextEntryDialog(self.ParentWindow, "Edit comment", "Please enter comment text", comment.GetContent(), wx.OK|wx.CANCEL)
+ dialog = wx.TextEntryDialog(self.ParentWindow, _("Edit comment"), _("Please enter comment text"), comment.GetContent(), wx.OK|wx.CANCEL)
if dialog.ShowModal() == wx.ID_OK:
value = dialog.GetValue()
rect = comment.GetRedrawRect(1, 1)
@@ -2452,6 +2390,7 @@
infos["x"], infos["y"] = step.GetPosition()
infos["width"], infos["height"] = step.GetSize()
infos["connectors"] = step.GetConnectors()
+ infos["action"] = step.GetActionConnector()
self.Controler.SetEditedElementStepInfos(self.TagName, stepid, infos)
def RefreshTransitionModel(self, transition):
@@ -2463,6 +2402,7 @@
infos["x"], infos["y"] = transition.GetPosition()
infos["width"], infos["height"] = transition.GetSize()
infos["connectors"] = transition.GetConnectors()
+ infos["connection"] = transition.GetConditionConnector()
self.Controler.SetEditedElementTransitionInfos(self.TagName, transitionid, infos)
def RefreshDivergenceModel(self, divergence):
@@ -2513,8 +2453,8 @@
def DeleteVariable(self, variable):
connectors = variable.GetConnectors()
- if connectors["output"]:
- elements = connectors["output"].GetConnectedBlocks()
+ if len(connectors["outputs"]) > 0:
+ elements = connectors["outputs"][0].GetConnectedBlocks()
else:
elements = []
variable.Clean()
@@ -2548,7 +2488,7 @@
def DeleteContact(self, contact):
connectors = contact.GetConnectors()
- elements = connectors["output"].GetConnectedBlocks()
+ elements = connectors["outputs"][0].GetConnectedBlocks()
contact.Clean()
self.RemoveBlock(contact)
self.Controler.RemoveEditedElementInstance(self.TagName, contact.GetId())
@@ -2557,7 +2497,7 @@
def DeleteCoil(self, coil):
connectors = coil.GetConnectors()
- elements = connectors["output"].GetConnectedBlocks()
+ elements = connectors["outputs"][0].GetConnectedBlocks()
coil.Clean()
self.RemoveBlock(coil)
self.Controler.RemoveEditedElementInstance(self.TagName, coil.GetId())
@@ -2567,7 +2507,8 @@
def DeletePowerRail(self, powerrail):
elements = []
if powerrail.GetType() == LEFTRAIL:
- for connector in powerrail.GetConnectors():
+ connectors = powerrail.GetConnectors()
+ for connector in connectors["outputs"]:
for element in connector.GetConnectedBlocks():
if element not in elements:
elements.append(element)
@@ -2580,12 +2521,13 @@
def DeleteStep(self, step):
elements = []
connectors = step.GetConnectors()
- if connectors["output"]:
- for element in connectors["output"].GetConnectedBlocks():
+ action_connector = step.GetActionConnector()
+ if len(connectors["outputs"]) > 0:
+ for element in connectors["outputs"][0].GetConnectedBlocks():
if element not in elements:
elements.append(element)
- if connectors["action"]:
- for element in connectors["action"].GetConnectedBlocks():
+ if action_connector is not None:
+ for element in action_connector.GetConnectedBlocks():
if element not in elements:
elements.append(element)
step.Clean()
@@ -2597,10 +2539,9 @@
def DeleteTransition(self, transition):
elements = []
connectors = transition.GetConnectors()
- if connectors["output"]:
- for element in connectors["output"].GetConnectedBlocks():
- if element not in elements:
- elements.append(element)
+ for element in connectors["outputs"][0].GetConnectedBlocks():
+ if element not in elements:
+ elements.append(element)
transition.Clean()
self.RemoveBlock(transition)
self.Controler.RemoveEditedElementInstance(self.TagName, transition.GetId())
@@ -2637,7 +2578,9 @@
def Cut(self):
if not self.Debug and (self.IsBlock(self.SelectedElement) or self.IsComment(self.SelectedElement) or isinstance(self.SelectedElement, Graphic_Group)):
- self.ParentWindow.SetCopyBuffer(self.SelectedElement.Clone(self))
+ blocks, wires = self.SelectedElement.GetDefinition()
+ text = self.Controler.GetEditedElementInstancesCopy(self.TagName, blocks, wires, self.Debug)
+ self.ParentWindow.SetCopyBuffer(text)
rect = self.SelectedElement.GetRedrawRect(1, 1)
self.SelectedElement.Delete()
self.SelectedElement = None
@@ -2649,42 +2592,30 @@
def Copy(self):
if not self.Debug and (self.IsBlock(self.SelectedElement) or self.IsComment(self.SelectedElement) or isinstance(self.SelectedElement, Graphic_Group)):
- self.ParentWindow.SetCopyBuffer(self.SelectedElement.Clone(self))
+ blocks, wires = self.SelectedElement.GetDefinition()
+ text = self.Controler.GetEditedElementInstancesCopy(self.TagName, blocks, wires, self.Debug)
+ self.ParentWindow.SetCopyBuffer(text)
def Paste(self):
- element = self.ParentWindow.GetCopyBuffer()
- if not self.Debug and element is not None and self.CanAddElement(element):
+ if not self.Debug:
+ element = self.ParentWindow.GetCopyBuffer()
mouse_pos = self.ScreenToClient(wx.GetMousePosition())
- if wx.Rect(0, 0, *self.GetClientSize()).InsideXY(mouse_pos.x, mouse_pos.y):
+ middle = wx.Rect(0, 0, *self.GetClientSize()).InsideXY(mouse_pos.x, mouse_pos.y)
+ if middle:
x, y = self.CalcUnscrolledPosition(mouse_pos.x, mouse_pos.y)
- block_size = element.GetSize()
- x = int(float(x) / self.ViewScale[0]) - block_size[0] / 2
- y = int(float(y) / self.ViewScale[1]) - block_size[1] / 2
else:
x, y = self.CalcUnscrolledPosition(0, 0)
- x = int(x / self.ViewScale[0]) + 30
- y = int(y / self.ViewScale[1]) + 30
- if self.Scaling is not None:
- new_pos = wx.Point(max(round_scaling(30, self.Scaling[0], 1),
- round_scaling(x, self.Scaling[0])),
- max(round_scaling(30, self.Scaling[1], 1),
- round_scaling(y, self.Scaling[1])))
+ new_pos = [int(x / self.ViewScale[0]), int(y / self.ViewScale[1])]
+ result = self.Controler.PasteEditedElementInstances(self.TagName, element, new_pos, middle, self.Debug)
+ if not isinstance(result, (StringType, UnicodeType)):
+ self.RefreshBuffer()
+ self.RefreshView(result)
+ self.ParentWindow.RefreshVariablePanel(self.TagName)
+ self.ParentWindow.RefreshInstancesTree()
else:
- new_pos = wx.Point(max(30, x), max(30, y))
- block = self.CopyBlock(element, new_pos)
- self.RefreshVisibleElements()
- if self.SelectedElement is not None:
- self.SelectedElement.SetSelected(False)
- self.SelectedElement = block
- self.SelectedElement.SetSelected(True)
- self.RefreshBuffer()
- self.RefreshScrollBars()
- self.ParentWindow.RefreshVariablePanel(self.TagName)
- self.ParentWindow.RefreshInstancesTree()
- else:
- message = wx.MessageDialog(self, "You can't paste the element in buffer here!", "Error", wx.OK|wx.ICON_ERROR)
- message.ShowModal()
- message.Destroy()
+ message = wx.MessageDialog(self, result, "Error", wx.OK|wx.ICON_ERROR)
+ message.ShowModal()
+ message.Destroy()
def CanAddElement(self, block):
if isinstance(block, Graphic_Group):
@@ -2698,17 +2629,11 @@
return False
def GenerateNewName(self, element, exclude={}):
- names = exclude.copy()
- if isinstance(element, FBD_Block):
- names.update(dict([(varname.upper(), True) for varname in self.Controler.GetEditedElementVariables(self.TagName, self.Debug)]))
- format = "Block%d"
- elif isinstance(element, SFC_Step):
- names.update(dict([(block.GetName().upper(), True) for block in self.Blocks if isinstance(block, SFC_Step)]))
+ if isinstance(element, SFC_Step):
format = "Step%d"
- i = 1
- while names.get((format%i).upper(), False):
- i += 1
- return format%i
+ else:
+ format = "Block%d"
+ return self.Controler.GenerateNewName(self.TagName, element.GetName(), format, exclude, self.Debug)
def IsNamedElement(self, element):
return isinstance(element, FBD_Block) and element.GetName() != "" or isinstance(element, SFC_Step)
@@ -2875,18 +2800,18 @@
int((xstart * SCROLLBAR_UNIT + window_size[0]) / self.ViewScale[1]), ystart * SCROLLBAR_UNIT + y + 1)
# Draw all elements
- for comment in self.Comments:
+ for comment in self.Comments.itervalues():
if comment != self.SelectedElement and (comment.IsVisible() or printing):
comment.Draw(dc)
- for wire in self.Wires:
+ for wire in self.Wires.iterkeys():
if wire != self.SelectedElement and (wire.IsVisible() or printing):
if not self.Debug or wire.GetValue() != True:
wire.Draw(dc)
if self.Debug:
- for wire in self.Wires:
+ for wire in self.Wires.iterkeys():
if wire != self.SelectedElement and (wire.IsVisible() or printing) and wire.GetValue() == True:
wire.Draw(dc)
- for block in self.Blocks:
+ for block in self.Blocks.itervalues():
if block != self.SelectedElement and (block.IsVisible() or printing):
block.Draw(dc)
diff -r e0a6a5952d13 -r 127d524a5f1d debian/changelog
--- a/debian/changelog Mon Jul 06 11:24:37 2009 -0600
+++ b/debian/changelog Thu Aug 20 09:03:31 2009 -0600
@@ -2,5 +2,5 @@
* Initial release (Closes: #nnnn)
- -- lolitech Tue, 13 Nov 2007 11:14:55 +0100
+ -- lolitech Tue, 13 Nov 2007 11:14:55 +0100
diff -r e0a6a5952d13 -r 127d524a5f1d examples/example.xml
--- a/examples/example.xml Mon Jul 06 11:24:37 2009 -0600
+++ b/examples/example.xml Thu Aug 20 09:03:31 2009 -0600
@@ -2,17 +2,17 @@
+ xsi:schemaLocation="http://www.plcopen.org/xml/tc6.xsd">
@@ -99,6 +99,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -203,13 +219,6 @@
-
-
-
-
-
- IN3
-
@@ -227,11 +236,9 @@
-
+
-
-
-
+
@@ -286,6 +293,29 @@
+
+
+
+
+
+ IN3
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+