editors/Viewer.py
changeset 1784 64beb9e9c749
parent 1782 5b6ad7a7fd9d
child 1834 cd42b426028b
equal deleted inserted replaced
1729:31e63e25b4cc 1784:64beb9e9c749
    44 SCROLL_ZONE = 10
    44 SCROLL_ZONE = 10
    45 
    45 
    46 CURSORS = None
    46 CURSORS = None
    47 SFC_Objects = (SFC_Step, SFC_ActionBlock, SFC_Transition, SFC_Divergence, SFC_Jump)
    47 SFC_Objects = (SFC_Step, SFC_ActionBlock, SFC_Transition, SFC_Divergence, SFC_Jump)
    48 
    48 
       
    49 
    49 def ResetCursors():
    50 def ResetCursors():
    50     global CURSORS
    51     global CURSORS
    51     if CURSORS == None:
    52     if CURSORS is None:
    52         CURSORS = [wx.NullCursor,
    53         CURSORS = [wx.NullCursor,
    53                    wx.StockCursor(wx.CURSOR_HAND),
    54                    wx.StockCursor(wx.CURSOR_HAND),
    54                    wx.StockCursor(wx.CURSOR_SIZENWSE),
    55                    wx.StockCursor(wx.CURSOR_SIZENWSE),
    55                    wx.StockCursor(wx.CURSOR_SIZENESW),
    56                    wx.StockCursor(wx.CURSOR_SIZENESW),
    56                    wx.StockCursor(wx.CURSOR_SIZEWE),
    57                    wx.StockCursor(wx.CURSOR_SIZEWE),
    57                    wx.StockCursor(wx.CURSOR_SIZENS)]
    58                    wx.StockCursor(wx.CURSOR_SIZENS)]
    58 
    59 
       
    60 
    59 def AppendMenu(parent, help, id, kind, text):
    61 def AppendMenu(parent, help, id, kind, text):
    60     if wx.VERSION >= (2, 6, 0):
    62     if wx.VERSION >= (2, 6, 0):
    61         parent.Append(help=help, id=id, kind=kind, text=text)
    63         parent.Append(help=help, id=id, kind=kind, text=text)
    62     else:
    64     else:
    63         parent.Append(helpString=help, id=id, kind=kind, item=text)
    65         parent.Append(helpString=help, id=id, kind=kind, item=text)
    64 
    66 
       
    67 
    65 if wx.Platform == '__WXMSW__':
    68 if wx.Platform == '__WXMSW__':
    66     faces = { 'times': 'Times New Roman',
    69     faces = {
    67               'mono' : 'Courier New',
    70         'times': 'Times New Roman',
    68               'helv' : 'Arial',
    71         'mono':  'Courier New',
    69               'other': 'Comic Sans MS',
    72         'helv':  'Arial',
    70               'size' : 10,
    73         'other': 'Comic Sans MS',
    71              }
    74         'size':  10,
       
    75     }
    72 else:
    76 else:
    73     faces = { 'times': 'Times',
    77     faces = {
    74               'mono' : 'Courier',
    78         'times': 'Times',
    75               'helv' : 'Helvetica',
    79         'mono':  'Courier',
    76               'other': 'new century schoolbook',
    80         'helv':  'Helvetica',
    77               'size' : 12,
    81         'other': 'new century schoolbook',
    78              }
    82         'size':  12,
       
    83     }
    79 
    84 
    80 if wx.Platform == '__WXMSW__':
    85 if wx.Platform == '__WXMSW__':
    81     MAX_ZOOMIN = 4
    86     MAX_ZOOMIN = 4
    82 else:
    87 else:
    83     MAX_ZOOMIN = 7
    88     MAX_ZOOMIN = 7
    84 ZOOM_FACTORS = [math.sqrt(2) ** x for x in xrange(-6, MAX_ZOOMIN)]
    89 ZOOM_FACTORS = [math.sqrt(2) ** x for x in xrange(-6, MAX_ZOOMIN)]
    85 
    90 
       
    91 
    86 def GetVariableCreationFunction(variable_type):
    92 def GetVariableCreationFunction(variable_type):
    87     def variableCreationFunction(viewer, id, specific_values):
    93     def variableCreationFunction(viewer, id, specific_values):
    88         return FBD_Variable(viewer, variable_type,
    94         return FBD_Variable(viewer,
    89                                     specific_values.name,
    95                             variable_type,
    90                                     specific_values.value_type,
    96                             specific_values.name,
    91                                     id,
    97                             specific_values.value_type,
    92                                     specific_values.execution_order)
    98                             id,
       
    99                             specific_values.execution_order)
    93     return variableCreationFunction
   100     return variableCreationFunction
       
   101 
    94 
   102 
    95 def GetConnectorCreationFunction(connector_type):
   103 def GetConnectorCreationFunction(connector_type):
    96     def connectorCreationFunction(viewer, id, specific_values):
   104     def connectorCreationFunction(viewer, id, specific_values):
    97         return FBD_Connector(viewer, connector_type,
   105         return FBD_Connector(viewer,
    98                                      specific_values.name, id)
   106                              connector_type,
       
   107                              specific_values.name,
       
   108                              id)
    99     return connectorCreationFunction
   109     return connectorCreationFunction
       
   110 
   100 
   111 
   101 def commentCreationFunction(viewer, id, specific_values):
   112 def commentCreationFunction(viewer, id, specific_values):
   102     return Comment(viewer, specific_values.content, id)
   113     return Comment(viewer, specific_values.content, id)
   103 
   114 
       
   115 
   104 def GetPowerRailCreationFunction(powerrail_type):
   116 def GetPowerRailCreationFunction(powerrail_type):
   105     def powerRailCreationFunction(viewer, id, specific_values):
   117     def powerRailCreationFunction(viewer, id, specific_values):
   106         return LD_PowerRail(viewer, powerrail_type, id,
   118         return LD_PowerRail(viewer,
   107                                     specific_values.connectors)
   119                             powerrail_type,
       
   120                             id,
       
   121                             specific_values.connectors)
   108     return powerRailCreationFunction
   122     return powerRailCreationFunction
   109 
   123 
   110 NEGATED_VALUE = lambda x: x if x is not None else False
   124 
   111 MODIFIER_VALUE = lambda x: x if x is not None else 'none'
   125 def NEGATED_VALUE(x):
       
   126     return x if x is not None else False
       
   127 
       
   128 
       
   129 def MODIFIER_VALUE(x):
       
   130     return x if x is not None else 'none'
       
   131 
   112 
   132 
   113 CONTACT_TYPES = {(True, "none"): CONTACT_REVERSE,
   133 CONTACT_TYPES = {(True, "none"): CONTACT_REVERSE,
   114                  (False, "rising"): CONTACT_RISING,
   134                  (False, "rising"): CONTACT_RISING,
   115                  (False, "falling"): CONTACT_FALLING}
   135                  (False, "falling"): CONTACT_FALLING}
       
   136 
   116 
   137 
   117 def contactCreationFunction(viewer, id, specific_values):
   138 def contactCreationFunction(viewer, id, specific_values):
   118     contact_type = CONTACT_TYPES.get((NEGATED_VALUE(specific_values.negated),
   139     contact_type = CONTACT_TYPES.get((NEGATED_VALUE(specific_values.negated),
   119                                       MODIFIER_VALUE(specific_values.edge)),
   140                                       MODIFIER_VALUE(specific_values.edge)),
   120                                      CONTACT_NORMAL)
   141                                      CONTACT_NORMAL)
   121     return LD_Contact(viewer, contact_type, specific_values.name, id)
   142     return LD_Contact(viewer, contact_type, specific_values.name, id)
   122 
   143 
       
   144 
   123 COIL_TYPES = {(True, "none", "none"): COIL_REVERSE,
   145 COIL_TYPES = {(True, "none", "none"): COIL_REVERSE,
   124               (False, "none", "set"): COIL_SET,
   146               (False, "none", "set"): COIL_SET,
   125               (False, "none", "reset"): COIL_RESET,
   147               (False, "none", "reset"): COIL_RESET,
   126               (False, "rising", "none"): COIL_RISING,
   148               (False, "rising", "none"): COIL_RISING,
   127               (False, "falling", "none"): COIL_FALLING}
   149               (False, "falling", "none"): COIL_FALLING}
       
   150 
   128 
   151 
   129 def coilCreationFunction(viewer, id, specific_values):
   152 def coilCreationFunction(viewer, id, specific_values):
   130     coil_type = COIL_TYPES.get((NEGATED_VALUE(specific_values.negated),
   153     coil_type = COIL_TYPES.get((NEGATED_VALUE(specific_values.negated),
   131                                 MODIFIER_VALUE(specific_values.edge),
   154                                 MODIFIER_VALUE(specific_values.edge),
   132                                 MODIFIER_VALUE(specific_values.storage)),
   155                                 MODIFIER_VALUE(specific_values.storage)),
   133                                COIL_NORMAL)
   156                                COIL_NORMAL)
   134     return LD_Coil(viewer, coil_type, specific_values.name, id)
   157     return LD_Coil(viewer, coil_type, specific_values.name, id)
   135 
   158 
       
   159 
   136 def stepCreationFunction(viewer, id, specific_values):
   160 def stepCreationFunction(viewer, id, specific_values):
   137     step = SFC_Step(viewer, specific_values.name,
   161     step = SFC_Step(viewer,
   138                             specific_values.initial, id)
   162                     specific_values.name,
       
   163                     specific_values.initial,
       
   164                     id)
   139     if specific_values.action is not None:
   165     if specific_values.action is not None:
   140         step.AddAction()
   166         step.AddAction()
   141         connector = step.GetActionConnector()
   167         connector = step.GetActionConnector()
   142         connector.SetPosition(wx.Point(*specific_values.action.position))
   168         connector.SetPosition(wx.Point(*specific_values.action.position))
   143     return step
   169     return step
   144 
   170 
       
   171 
   145 def transitionCreationFunction(viewer, id, specific_values):
   172 def transitionCreationFunction(viewer, id, specific_values):
   146     transition = SFC_Transition(viewer, specific_values.condition_type,
   173     transition = SFC_Transition(viewer,
   147                                         specific_values.condition,
   174                                 specific_values.condition_type,
   148                                         specific_values.priority, id)
   175                                 specific_values.condition,
       
   176                                 specific_values.priority,
       
   177                                 id)
   149     return transition
   178     return transition
       
   179 
   150 
   180 
   151 divergence_types = [SELECTION_DIVERGENCE,
   181 divergence_types = [SELECTION_DIVERGENCE,
   152                     SELECTION_CONVERGENCE, SIMULTANEOUS_DIVERGENCE, SIMULTANEOUS_CONVERGENCE]
   182                     SELECTION_CONVERGENCE, SIMULTANEOUS_DIVERGENCE, SIMULTANEOUS_CONVERGENCE]
       
   183 
   153 
   184 
   154 def GetDivergenceCreationFunction(divergence_type):
   185 def GetDivergenceCreationFunction(divergence_type):
   155     def divergenceCreationFunction(viewer, id, specific_values):
   186     def divergenceCreationFunction(viewer, id, specific_values):
   156         return SFC_Divergence(viewer, divergence_type,
   187         return SFC_Divergence(viewer, divergence_type,
   157                                       specific_values.connectors, id)
   188                               specific_values.connectors, id)
   158     return divergenceCreationFunction
   189     return divergenceCreationFunction
       
   190 
   159 
   191 
   160 def jumpCreationFunction(viewer, id, specific_values):
   192 def jumpCreationFunction(viewer, id, specific_values):
   161     return SFC_Jump(viewer, specific_values.target, id)
   193     return SFC_Jump(viewer, specific_values.target, id)
   162 
   194 
       
   195 
   163 def actionBlockCreationFunction(viewer, id, specific_values):
   196 def actionBlockCreationFunction(viewer, id, specific_values):
   164     return SFC_ActionBlock(viewer, specific_values.actions, id)
   197     return SFC_ActionBlock(viewer, specific_values.actions, id)
       
   198 
   165 
   199 
   166 ElementCreationFunctions = {
   200 ElementCreationFunctions = {
   167     "input": GetVariableCreationFunction(INPUT),
   201     "input": GetVariableCreationFunction(INPUT),
   168     "output": GetVariableCreationFunction(OUTPUT),
   202     "output": GetVariableCreationFunction(OUTPUT),
   169     "inout": GetVariableCreationFunction(INOUT),
   203     "inout": GetVariableCreationFunction(INOUT),
   182     "simultaneousConvergence": GetDivergenceCreationFunction(SIMULTANEOUS_CONVERGENCE),
   216     "simultaneousConvergence": GetDivergenceCreationFunction(SIMULTANEOUS_CONVERGENCE),
   183     "jump": jumpCreationFunction,
   217     "jump": jumpCreationFunction,
   184     "actionBlock": actionBlockCreationFunction,
   218     "actionBlock": actionBlockCreationFunction,
   185 }
   219 }
   186 
   220 
       
   221 
   187 def sort_blocks(block_infos1, block_infos2):
   222 def sort_blocks(block_infos1, block_infos2):
   188     x1, y1 = block_infos1[0].GetPosition()
   223     x1, y1 = block_infos1[0].GetPosition()
   189     x2, y2 = block_infos2[0].GetPosition()
   224     x2, y2 = block_infos2[0].GetPosition()
   190     if y1 == y2:
   225     if y1 == y2:
   191         return cmp(x1, x2)
   226         return cmp(x1, x2)
   192     else:
   227     else:
   193         return cmp(y1, y2)
   228         return cmp(y1, y2)
   194 
   229 
   195 #-------------------------------------------------------------------------------
   230 # -------------------------------------------------------------------------------
   196 #                       Graphic elements Viewer base class
   231 #                       Graphic elements Viewer base class
   197 #-------------------------------------------------------------------------------
   232 # -------------------------------------------------------------------------------
       
   233 
   198 
   234 
   199 # ID Constants for alignment menu items
   235 # ID Constants for alignment menu items
   200 [ID_VIEWERALIGNMENTMENUITEMS0, ID_VIEWERALIGNMENTMENUITEMS1,
   236 [
   201  ID_VIEWERALIGNMENTMENUITEMS2, ID_VIEWERALIGNMENTMENUITEMS4,
   237     ID_VIEWERALIGNMENTMENUITEMS0, ID_VIEWERALIGNMENTMENUITEMS1,
   202  ID_VIEWERALIGNMENTMENUITEMS5, ID_VIEWERALIGNMENTMENUITEMS6,
   238     ID_VIEWERALIGNMENTMENUITEMS2, ID_VIEWERALIGNMENTMENUITEMS4,
       
   239     ID_VIEWERALIGNMENTMENUITEMS5, ID_VIEWERALIGNMENTMENUITEMS6,
   203 ] = [wx.NewId() for _init_coll_AlignmentMenu_Items in range(6)]
   240 ] = [wx.NewId() for _init_coll_AlignmentMenu_Items in range(6)]
   204 
   241 
   205 # ID Constants for contextual menu items
   242 # ID Constants for contextual menu items
   206 [ID_VIEWERCONTEXTUALMENUITEMS0, ID_VIEWERCONTEXTUALMENUITEMS1,
   243 [
   207  ID_VIEWERCONTEXTUALMENUITEMS2, ID_VIEWERCONTEXTUALMENUITEMS3,
   244     ID_VIEWERCONTEXTUALMENUITEMS0, ID_VIEWERCONTEXTUALMENUITEMS1,
   208  ID_VIEWERCONTEXTUALMENUITEMS5, ID_VIEWERCONTEXTUALMENUITEMS6,
   245     ID_VIEWERCONTEXTUALMENUITEMS2, ID_VIEWERCONTEXTUALMENUITEMS3,
   209  ID_VIEWERCONTEXTUALMENUITEMS8, ID_VIEWERCONTEXTUALMENUITEMS9,
   246     ID_VIEWERCONTEXTUALMENUITEMS5, ID_VIEWERCONTEXTUALMENUITEMS6,
   210  ID_VIEWERCONTEXTUALMENUITEMS11, ID_VIEWERCONTEXTUALMENUITEMS12,
   247     ID_VIEWERCONTEXTUALMENUITEMS8, ID_VIEWERCONTEXTUALMENUITEMS9,
   211  ID_VIEWERCONTEXTUALMENUITEMS14, ID_VIEWERCONTEXTUALMENUITEMS16,
   248     ID_VIEWERCONTEXTUALMENUITEMS11, ID_VIEWERCONTEXTUALMENUITEMS12,
   212  ID_VIEWERCONTEXTUALMENUITEMS17,
   249     ID_VIEWERCONTEXTUALMENUITEMS14, ID_VIEWERCONTEXTUALMENUITEMS16,
       
   250     ID_VIEWERCONTEXTUALMENUITEMS17,
   213 ] = [wx.NewId() for _init_coll_ContextualMenu_Items in range(13)]
   251 ] = [wx.NewId() for _init_coll_ContextualMenu_Items in range(13)]
   214 
   252 
   215 
   253 
   216 class ViewerDropTarget(wx.TextDropTarget):
   254 class ViewerDropTarget(wx.TextDropTarget):
   217 
   255 
   228         y = int(y / self.ParentWindow.ViewScale[1])
   266         y = int(y / self.ParentWindow.ViewScale[1])
   229         scaling = self.ParentWindow.Scaling
   267         scaling = self.ParentWindow.Scaling
   230         message = None
   268         message = None
   231         try:
   269         try:
   232             values = eval(data)
   270             values = eval(data)
   233         except:
   271         except Exception:
   234             message = _("Invalid value \"%s\" for viewer block")%data
   272             message = _("Invalid value \"%s\" for viewer block") % data
   235             values = None
   273             values = None
   236         if not isinstance(values, TupleType):
   274         if not isinstance(values, TupleType):
   237             message = _("Invalid value \"%s\" for viewer block")%data
   275             message = _("Invalid value \"%s\" for viewer block") % data
   238             values = None
   276             values = None
   239         if values is not None:
   277         if values is not None:
   240             if values[1] == "debug":
   278             if values[1] == "debug":
   241                 pass
   279                 pass
   242             elif values[1] == "program":
   280             elif values[1] == "program":
   243                 message = _("Programs can't be used by other POUs!")
   281                 message = _("Programs can't be used by other POUs!")
   244             elif values[1] in ["function", "functionBlock"]:
   282             elif values[1] in ["function", "functionBlock"]:
   245                 words = tagname.split("::")
   283                 words = tagname.split("::")
   246                 if pou_name == values[0]:
   284                 if pou_name == values[0]:
   247                     message = _("\"%s\" can't use itself!")%pou_name
   285                     message = _("\"%s\" can't use itself!") % pou_name
   248                 elif pou_type == "function" and values[1] != "function":
   286                 elif pou_type == "function" and values[1] != "function":
   249                     message = _("Function Blocks can't be used in Functions!")
   287                     message = _("Function Blocks can't be used in Functions!")
   250                 elif self.ParentWindow.Controler.PouIsUsedBy(pou_name, values[0], self.ParentWindow.Debug):
   288                 elif self.ParentWindow.Controler.PouIsUsedBy(pou_name, values[0], self.ParentWindow.Debug):
   251                     message = _("\"{a1}\" is already used by \"{a2}\"!").format(a1 = pou_name, a2 = values[0])
   289                     message = _("\"{a1}\" is already used by \"{a2}\"!").format(a1=pou_name, a2=values[0])
   252                 else:
   290                 else:
   253                     blockname = values[2]
   291                     blockname = values[2]
   254                     if len(values) > 3:
   292                     if len(values) > 3:
   255                         blockinputs = values[3]
   293                         blockinputs = values[3]
   256                     else:
   294                     else:
   257                         blockinputs = None
   295                         blockinputs = None
   258                     if values[1] != "function" and blockname == "":
   296                     if values[1] != "function" and blockname == "":
   259                         blockname = self.ParentWindow.GenerateNewName(blocktype=values[0])
   297                         blockname = self.ParentWindow.GenerateNewName(blocktype=values[0])
   260                     if blockname.upper() in [name.upper() for name in self.ParentWindow.Controler.GetProjectPouNames(self.ParentWindow.Debug)]:
   298                     if blockname.upper() in [name.upper() for name in self.ParentWindow.Controler.GetProjectPouNames(self.ParentWindow.Debug)]:
   261                         message = _("\"%s\" pou already exists!")%blockname
   299                         message = _("\"%s\" pou already exists!") % blockname
   262                     elif blockname.upper() in [name.upper() for name in self.ParentWindow.Controler.GetEditedElementVariables(tagname, self.ParentWindow.Debug)]:
   300                     elif blockname.upper() in [name.upper() for name in self.ParentWindow.Controler.GetEditedElementVariables(tagname, self.ParentWindow.Debug)]:
   263                         message = _("\"%s\" element for this pou already exists!")%blockname
   301                         message = _("\"%s\" element for this pou already exists!") % blockname
   264                     else:
   302                     else:
   265                         id = self.ParentWindow.GetNewId()
   303                         id = self.ParentWindow.GetNewId()
   266                         block = FBD_Block(self.ParentWindow, values[0], blockname, id, inputs = blockinputs)
   304                         block = FBD_Block(self.ParentWindow, values[0], blockname, id, inputs=blockinputs)
   267                         width, height = block.GetMinSize()
   305                         width, height = block.GetMinSize()
   268                         if scaling is not None:
   306                         if scaling is not None:
   269                             x = round(float(x) / float(scaling[0])) * scaling[0]
   307                             x = round(float(x) / float(scaling[0])) * scaling[0]
   270                             y = round(float(y) / float(scaling[1])) * scaling[1]
   308                             y = round(float(y) / float(scaling[1])) * scaling[1]
   271                             width = round(float(width) / float(scaling[0]) + 0.5) * scaling[0]
   309                             width = round(float(width) / float(scaling[0]) + 0.5) * scaling[0]
   283                         self.ParentWindow.Refresh(False)
   321                         self.ParentWindow.Refresh(False)
   284             elif values[1] == "location":
   322             elif values[1] == "location":
   285                 if pou_type == "program":
   323                 if pou_type == "program":
   286                     location = values[0]
   324                     location = values[0]
   287                     if not location.startswith("%"):
   325                     if not location.startswith("%"):
   288                         dialog = wx.SingleChoiceDialog(self.ParentWindow.ParentWindow,
   326                         dialog = wx.SingleChoiceDialog(
   289                               _("Select a variable class:"), _("Variable class"),
   327                             self.ParentWindow.ParentWindow,
   290                               [_("Input"), _("Output"), _("Memory")],
   328                             _("Select a variable class:"),
   291                               wx.DEFAULT_DIALOG_STYLE|wx.OK|wx.CANCEL)
   329                             _("Variable class"),
       
   330                             [_("Input"), _("Output"), _("Memory")],
       
   331                             wx.DEFAULT_DIALOG_STYLE | wx.OK | wx.CANCEL)
   292                         if dialog.ShowModal() == wx.ID_OK:
   332                         if dialog.ShowModal() == wx.ID_OK:
   293                             selected = dialog.GetSelection()
   333                             selected = dialog.GetSelection()
   294                         else:
   334                         else:
   295                             selected = None
   335                             selected = None
   296                         dialog.Destroy()
   336                         dialog.Destroy()
   311                     var_name = dlg.GetValue() if dlg.ShowModal() == wx.ID_OK else None
   351                     var_name = dlg.GetValue() if dlg.ShowModal() == wx.ID_OK else None
   312                     dlg.Destroy()
   352                     dlg.Destroy()
   313                     if var_name is None:
   353                     if var_name is None:
   314                         return
   354                         return
   315                     elif var_name.upper() in [name.upper() for name in self.ParentWindow.Controler.GetProjectPouNames(self.ParentWindow.Debug)]:
   355                     elif var_name.upper() in [name.upper() for name in self.ParentWindow.Controler.GetProjectPouNames(self.ParentWindow.Debug)]:
   316                         message = _("\"%s\" pou already exists!")%var_name
   356                         message = _("\"%s\" pou already exists!") % var_name
   317                     elif not var_name.upper() in [name.upper() for name in self.ParentWindow.Controler.GetEditedElementVariables(tagname, self.ParentWindow.Debug)]:
   357                     elif not var_name.upper() in [name.upper() for name in self.ParentWindow.Controler.GetEditedElementVariables(tagname, self.ParentWindow.Debug)]:
   318                         if location[1] == "Q":
   358                         if location[1] == "Q":
   319                             var_class = OUTPUT
   359                             var_class = OUTPUT
   320                         else:
   360                         else:
   321                             var_class = INPUT
   361                             var_class = INPUT
   326                         self.ParentWindow.Controler.AddEditedElementPouVar(tagname, var_type, var_name, location=location, description=values[4])
   366                         self.ParentWindow.Controler.AddEditedElementPouVar(tagname, var_type, var_name, location=location, description=values[4])
   327                         self.ParentWindow.RefreshVariablePanel()
   367                         self.ParentWindow.RefreshVariablePanel()
   328                         self.ParentWindow.ParentWindow.RefreshPouInstanceVariablesPanel()
   368                         self.ParentWindow.ParentWindow.RefreshPouInstanceVariablesPanel()
   329                         self.ParentWindow.AddVariableBlock(x, y, scaling, var_class, var_name, var_type)
   369                         self.ParentWindow.AddVariableBlock(x, y, scaling, var_class, var_name, var_type)
   330                     else:
   370                     else:
   331                         message = _("\"%s\" element for this pou already exists!")%var_name
   371                         message = _("\"%s\" element for this pou already exists!") % var_name
   332             elif values[1] == "NamedConstant":
   372             elif values[1] == "NamedConstant":
   333                 if pou_type == "program":
   373                 if pou_type == "program":
   334                     initval = values[0]
   374                     initval = values[0]
   335                     var_name = values[3]
   375                     var_name = values[3]
   336                     dlg = wx.TextEntryDialog(
   376                     dlg = wx.TextEntryDialog(
   341                     var_name = dlg.GetValue() if dlg.ShowModal() == wx.ID_OK else None
   381                     var_name = dlg.GetValue() if dlg.ShowModal() == wx.ID_OK else None
   342                     dlg.Destroy()
   382                     dlg.Destroy()
   343                     if var_name is None:
   383                     if var_name is None:
   344                         return
   384                         return
   345                     elif var_name.upper() in [name.upper() for name in self.ParentWindow.Controler.GetProjectPouNames(self.ParentWindow.Debug)]:
   385                     elif var_name.upper() in [name.upper() for name in self.ParentWindow.Controler.GetProjectPouNames(self.ParentWindow.Debug)]:
   346                         message = _("\"%s\" pou already exists!")%var_name
   386                         message = _("\"%s\" pou already exists!") % var_name
   347                     elif not var_name.upper() in [name.upper() for name in self.ParentWindow.Controler.GetEditedElementVariables(tagname, self.ParentWindow.Debug)]:
   387                     elif not var_name.upper() in [name.upper() for name in self.ParentWindow.Controler.GetEditedElementVariables(tagname, self.ParentWindow.Debug)]:
   348                         var_class = INPUT
   388                         var_class = INPUT
   349                         var_type = values[2]
   389                         var_type = values[2]
   350                         self.ParentWindow.Controler.AddEditedElementPouVar(tagname, var_type, var_name, description=values[4], initval=initval)
   390                         self.ParentWindow.Controler.AddEditedElementPouVar(tagname, var_type, var_name, description=values[4], initval=initval)
   351                         self.ParentWindow.RefreshVariablePanel()
   391                         self.ParentWindow.RefreshVariablePanel()
   352                         self.ParentWindow.ParentWindow.RefreshPouInstanceVariablesPanel()
   392                         self.ParentWindow.ParentWindow.RefreshPouInstanceVariablesPanel()
   353                         self.ParentWindow.AddVariableBlock(x, y, scaling, var_class, var_name, var_type)
   393                         self.ParentWindow.AddVariableBlock(x, y, scaling, var_class, var_name, var_type)
   354                     else:
   394                     else:
   355                         message = _("\"%s\" element for this pou already exists!")%var_name
   395                         message = _("\"%s\" element for this pou already exists!") % var_name
   356             elif values[1] == "Global":
   396             elif values[1] == "Global":
   357                 var_name = values[0]
   397                 var_name = values[0]
   358                 dlg = wx.TextEntryDialog(
   398                 dlg = wx.TextEntryDialog(
   359                     self.ParentWindow.ParentWindow,
   399                     self.ParentWindow.ParentWindow,
   360                     _("Confirm or change variable name"),
   400                     _("Confirm or change variable name"),
   363                 var_name = dlg.GetValue() if dlg.ShowModal() == wx.ID_OK else None
   403                 var_name = dlg.GetValue() if dlg.ShowModal() == wx.ID_OK else None
   364                 dlg.Destroy()
   404                 dlg.Destroy()
   365                 if var_name is None:
   405                 if var_name is None:
   366                     return
   406                     return
   367                 elif var_name.upper() in [name.upper() for name in self.ParentWindow.Controler.GetProjectPouNames(self.ParentWindow.Debug)]:
   407                 elif var_name.upper() in [name.upper() for name in self.ParentWindow.Controler.GetProjectPouNames(self.ParentWindow.Debug)]:
   368                     message = _("\"%s\" pou already exists!")%var_name
   408                     message = _("\"%s\" pou already exists!") % var_name
   369                 elif not var_name.upper() in [name.upper() for name in self.ParentWindow.Controler.GetEditedElementVariables(tagname, self.ParentWindow.Debug)]:
   409                 elif not var_name.upper() in [name.upper() for name in self.ParentWindow.Controler.GetEditedElementVariables(tagname, self.ParentWindow.Debug)]:
   370                     self.ParentWindow.Controler.AddEditedElementPouExternalVar(tagname, values[2], var_name)
   410                     self.ParentWindow.Controler.AddEditedElementPouExternalVar(tagname, values[2], var_name)
   371                     self.ParentWindow.RefreshVariablePanel()
   411                     self.ParentWindow.RefreshVariablePanel()
   372                     self.ParentWindow.ParentWindow.RefreshPouInstanceVariablesPanel()
   412                     self.ParentWindow.ParentWindow.RefreshPouInstanceVariablesPanel()
   373                     self.ParentWindow.AddVariableBlock(x, y, scaling, INPUT, var_name, values[2])
   413                     self.ParentWindow.AddVariableBlock(x, y, scaling, INPUT, var_name, values[2])
   374                 else:
   414                 else:
   375                     message = _("\"%s\" element for this pou already exists!")%var_name
   415                     message = _("\"%s\" element for this pou already exists!") % var_name
   376             elif values[1] == "Constant":
   416             elif values[1] == "Constant":
   377                 self.ParentWindow.AddVariableBlock(x, y, scaling, INPUT, values[0], None)
   417                 self.ParentWindow.AddVariableBlock(x, y, scaling, INPUT, values[0], None)
   378             elif values[3] == tagname:
   418             elif values[3] == tagname:
   379                 if values[1] == "Output":
   419                 if values[1] == "Output":
   380                     var_class = OUTPUT
   420                     var_class = OUTPUT
   419         def AddVariableFunction(event):
   459         def AddVariableFunction(event):
   420             self.ParentWindow.AddVariableBlock(x, y, scaling, var_class, var_name, var_type)
   460             self.ParentWindow.AddVariableBlock(x, y, scaling, var_class, var_name, var_type)
   421         return AddVariableFunction
   461         return AddVariableFunction
   422 
   462 
   423     def ShowMessage(self, message):
   463     def ShowMessage(self, message):
   424         message = wx.MessageDialog(self.ParentWindow, message, _("Error"), wx.OK|wx.ICON_ERROR)
   464         message = wx.MessageDialog(self.ParentWindow, message, _("Error"), wx.OK | wx.ICON_ERROR)
   425         message.ShowModal()
   465         message.ShowModal()
   426         message.Destroy()
   466         message.Destroy()
   427 
   467 
   428 
   468 
   429 
       
   430 class DebugInstanceName(DebugDataConsumer):
   469 class DebugInstanceName(DebugDataConsumer):
   431     VALUE_TRANSLATION = {True: _("Active"), False: _("Inactive")}
   470     VALUE_TRANSLATION = {True: _("Active"), False: _("Inactive")}
   432     
   471 
   433     def __init__(self, parent):
   472     def __init__(self, parent):
   434         DebugDataConsumer.__init__(self)
   473         DebugDataConsumer.__init__(self)
   435         self.Parent = parent
   474         self.Parent = parent
   436         self.ActionLastState = None
   475         self.ActionLastState = None
   437         self.ActionState = None
   476         self.ActionState = None
   438         self.x_offset = 2
   477         self.x_offset = 2
   439         self.y_offset = 2
   478         self.y_offset = 2
   440         
   479 
   441     def SetValue(self, value):
   480     def SetValue(self, value):
   442         self.ActionState = value
   481         self.ActionState = value
   443         if self.ActionState != self.ActionLastState:
   482         if self.ActionState != self.ActionLastState:
   444             self.ActionLastState = self.ActionState
   483             self.ActionLastState = self.ActionState
   445             wx.CallAfter(self.Parent.ElementNeedRefresh, self)
   484             wx.CallAfter(self.Parent.ElementNeedRefresh, self)
   446 
   485 
   447     def GetInstanceName(self):
   486     def GetInstanceName(self):
   448         return _("Debug: %s") % self.Parent.InstancePath
   487         return _("Debug: %s") % self.Parent.InstancePath
   449 
   488 
   450     def GetRedrawRect(self):
   489     def GetRedrawRect(self):
   451         x, y = self.Parent.CalcUnscrolledPosition(self.x_offset, self.y_offset)        
   490         x, y = self.Parent.CalcUnscrolledPosition(self.x_offset, self.y_offset)
   452         dc = self.Parent.GetLogicalDC()
   491         dc = self.Parent.GetLogicalDC()
   453         ipw, iph = dc.GetTextExtent(self.GetInstanceName())
   492         ipw, iph = dc.GetTextExtent(self.GetInstanceName())
   454         vw, vh = 0, 0
   493         vw, vh = 0, 0
   455         for value in self.VALUE_TRANSLATION.itervalues():
   494         for value in self.VALUE_TRANSLATION.itervalues():
   456             w, h = dc.GetTextExtent(" (%s)" % value)
   495             w, h = dc.GetTextExtent(" (%s)" % value)
   460 
   499 
   461     def Draw(self, dc):
   500     def Draw(self, dc):
   462         scalex, scaley = dc.GetUserScale()
   501         scalex, scaley = dc.GetUserScale()
   463         dc.SetUserScale(1, 1)
   502         dc.SetUserScale(1, 1)
   464         x, y = self.Parent.CalcUnscrolledPosition(self.x_offset, self.y_offset)
   503         x, y = self.Parent.CalcUnscrolledPosition(self.x_offset, self.y_offset)
   465         
   504 
   466         text = self.GetInstanceName()
   505         text = self.GetInstanceName()
   467         if self.ActionState is not None:
   506         if self.ActionState is not None:
   468             text += " ("
   507             text += " ("
   469 
   508 
   470         dc.DrawText(text, x, y)
   509         dc.DrawText(text, x, y)
   471         tw, th = dc.GetTextExtent(text)                    
   510         tw, th = dc.GetTextExtent(text)
   472         if self.ActionState is not None:
   511         if self.ActionState is not None:
   473 
   512 
   474             text = self.VALUE_TRANSLATION[self.ActionState]
   513             text = self.VALUE_TRANSLATION[self.ActionState]
   475             if self.ActionState:
   514             if self.ActionState:
   476                 dc.SetTextForeground(wx.GREEN)
   515                 dc.SetTextForeground(wx.GREEN)
   477             dc.DrawText(text, x + tw, y)
   516             dc.DrawText(text, x + tw, y)
   478             if self.ActionState:
   517             if self.ActionState:
   479                 dc.SetTextForeground(wx.BLACK)
   518                 dc.SetTextForeground(wx.BLACK)
   480             tw = tw + dc.GetTextExtent(text)[0]
   519             tw = tw + dc.GetTextExtent(text)[0]
   481             
   520 
   482             text = ")"                    
   521             text = ")"
   483             dc.DrawText(text, x + tw, y)
   522             dc.DrawText(text, x + tw, y)
   484         dc.SetUserScale(scalex, scaley)
   523         dc.SetUserScale(scalex, scaley)
   485 
   524 
   486 """
       
   487 Class that implements a Viewer based on a wx.ScrolledWindow for drawing and
       
   488 manipulating graphic elements
       
   489 """
       
   490 
   525 
   491 class Viewer(EditorPanel, DebugViewer):
   526 class Viewer(EditorPanel, DebugViewer):
       
   527     """
       
   528     Class that implements a Viewer based on a wx.ScrolledWindow for drawing and
       
   529     manipulating graphic elements
       
   530     """
   492 
   531 
   493     if wx.VERSION < (2, 6, 0):
   532     if wx.VERSION < (2, 6, 0):
   494         def Bind(self, event, function, id = None):
   533         def Bind(self, event, function, id=None):
   495             if id is not None:
   534             if id is not None:
   496                 event(self, id, function)
   535                 event(self, id, function)
   497             else:
   536             else:
   498                 event(self, function)
   537                 event(self, function)
   499 
   538 
   533         else:
   572         else:
   534             menu.Check(ID_NO_MODIFIER, True)
   573             menu.Check(ID_NO_MODIFIER, True)
   535 
   574 
   536     # Add Alignment Menu items to the given menu
   575     # Add Alignment Menu items to the given menu
   537     def AddAlignmentMenuItems(self, menu):
   576     def AddAlignmentMenuItems(self, menu):
   538         [ID_ALIGN_LEFT, ID_ALIGN_CENTER, ID_ALIGN_RIGHT,
   577         [
   539          ID_ALIGN_TOP, ID_ALIGN_MIDDLE, ID_ALIGN_BOTTOM,
   578             ID_ALIGN_LEFT, ID_ALIGN_CENTER, ID_ALIGN_RIGHT,
       
   579             ID_ALIGN_TOP, ID_ALIGN_MIDDLE, ID_ALIGN_BOTTOM,
   540         ] = [wx.NewId() for i in xrange(6)]
   580         ] = [wx.NewId() for i in xrange(6)]
   541 
   581 
   542         # Create menu items
   582         # Create menu items
   543         self.AddMenuItems(menu, [
   583         self.AddMenuItems(menu, [
   544             (ID_ALIGN_LEFT, wx.ITEM_NORMAL, _(u'Left'), '', self.OnAlignLeftMenu),
   584             (ID_ALIGN_LEFT, wx.ITEM_NORMAL, _(u'Left'), '', self.OnAlignLeftMenu),
   585             (ID_ADD_VARIABLE, wx.ITEM_NORMAL, _(u'Variable'), '', self.GetAddMenuCallBack(self.AddNewVariable)),
   625             (ID_ADD_VARIABLE, wx.ITEM_NORMAL, _(u'Variable'), '', self.GetAddMenuCallBack(self.AddNewVariable)),
   586             (ID_ADD_CONNECTION, wx.ITEM_NORMAL, _(u'Connection'), '', self.GetAddMenuCallBack(self.AddNewConnection)),
   626             (ID_ADD_CONNECTION, wx.ITEM_NORMAL, _(u'Connection'), '', self.GetAddMenuCallBack(self.AddNewConnection)),
   587             None])
   627             None])
   588 
   628 
   589         if self.CurrentLanguage != "FBD":
   629         if self.CurrentLanguage != "FBD":
   590             [ID_ADD_POWER_RAIL, ID_ADD_CONTACT, ID_ADD_COIL,
   630             [
       
   631                 ID_ADD_POWER_RAIL, ID_ADD_CONTACT, ID_ADD_COIL,
   591             ] = [wx.NewId() for i in xrange(3)]
   632             ] = [wx.NewId() for i in xrange(3)]
   592 
   633 
   593             # Create menu items
   634             # Create menu items
   594             self.AddMenuItems(menu, [
   635             self.AddMenuItems(menu, [
   595                 (ID_ADD_POWER_RAIL, wx.ITEM_NORMAL, _(u'Power Rail'), '', self.GetAddMenuCallBack(self.AddNewPowerRail)),
   636                 (ID_ADD_POWER_RAIL, wx.ITEM_NORMAL, _(u'Power Rail'), '', self.GetAddMenuCallBack(self.AddNewPowerRail)),
   600                      (ID_ADD_COIL, wx.ITEM_NORMAL, _(u'Coil'), '', self.GetAddMenuCallBack(self.AddNewCoil))])
   641                      (ID_ADD_COIL, wx.ITEM_NORMAL, _(u'Coil'), '', self.GetAddMenuCallBack(self.AddNewCoil))])
   601 
   642 
   602             menu.AppendSeparator()
   643             menu.AppendSeparator()
   603 
   644 
   604         if self.CurrentLanguage == "SFC":
   645         if self.CurrentLanguage == "SFC":
   605             [ID_ADD_INITIAL_STEP, ID_ADD_STEP, ID_ADD_TRANSITION,
   646             [
   606              ID_ADD_ACTION_BLOCK, ID_ADD_DIVERGENCE, ID_ADD_JUMP,
   647                 ID_ADD_INITIAL_STEP, ID_ADD_STEP, ID_ADD_TRANSITION,
       
   648                 ID_ADD_ACTION_BLOCK, ID_ADD_DIVERGENCE, ID_ADD_JUMP,
   607             ] = [wx.NewId() for i in xrange(6)]
   649             ] = [wx.NewId() for i in xrange(6)]
   608 
   650 
   609             # Create menu items
   651             # Create menu items
   610             self.AddMenuItems(menu, [
   652             self.AddMenuItems(menu, [
   611                 (ID_ADD_INITIAL_STEP, wx.ITEM_NORMAL, _(u'Initial Step'), '', self.GetAddMenuCallBack(self.AddNewStep, True)),
   653                 (ID_ADD_INITIAL_STEP, wx.ITEM_NORMAL, _(u'Initial Step'), '', self.GetAddMenuCallBack(self.AddNewStep, True)),
   660         menu.Enable(ID_COPY, block)
   702         menu.Enable(ID_COPY, block)
   661         menu.Enable(ID_PASTE, self.ParentWindow.GetCopyBuffer() is not None)
   703         menu.Enable(ID_PASTE, self.ParentWindow.GetCopyBuffer() is not None)
   662 
   704 
   663     def _init_Editor(self, prnt):
   705     def _init_Editor(self, prnt):
   664         self.Editor = wx.ScrolledWindow(prnt, name="Viewer",
   706         self.Editor = wx.ScrolledWindow(prnt, name="Viewer",
   665             pos=wx.Point(0, 0), size=wx.Size(0, 0),
   707                                         pos=wx.Point(0, 0), size=wx.Size(0, 0),
   666             style=wx.HSCROLL | wx.VSCROLL)
   708                                         style=wx.HSCROLL | wx.VSCROLL)
   667         self.Editor.ParentWindow = self
   709         self.Editor.ParentWindow = self
   668 
   710 
   669     # Create a new Viewer
   711     # Create a new Viewer
   670     def __init__(self, parent, tagname, window, controler, debug = False, instancepath = ""):
   712     def __init__(self, parent, tagname, window, controler, debug=False, instancepath=""):
   671         self.VARIABLE_PANEL_TYPE = controler.GetPouType(tagname.split("::")[1])
   713         self.VARIABLE_PANEL_TYPE = controler.GetPouType(tagname.split("::")[1])
   672 
   714 
   673         EditorPanel.__init__(self, parent, tagname, window, controler, debug)
   715         EditorPanel.__init__(self, parent, tagname, window, controler, debug)
   674         DebugViewer.__init__(self, controler, debug)
   716         DebugViewer.__init__(self, controler, debug)
   675 
   717 
   676         # Adding a rubberband to Viewer
   718         # Adding a rubberband to Viewer
   677         self.rubberBand = RubberBand(viewer=self)
   719         self.rubberBand = RubberBand(viewer=self)
   678         self.Editor.SetBackgroundColour(wx.Colour(255,255,255))
   720         self.Editor.SetBackgroundColour(wx.Colour(255, 255, 255))
   679         self.Editor.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
   721         self.Editor.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
   680         self.ResetView()
   722         self.ResetView()
   681         self.LastClientSize = None
   723         self.LastClientSize = None
   682         self.Scaling = None
   724         self.Scaling = None
   683         self.DrawGrid = True
   725         self.DrawGrid = True
   720 
   762 
   721         self.ElementRefreshList = []
   763         self.ElementRefreshList = []
   722         self.ElementRefreshList_lock = Lock()
   764         self.ElementRefreshList_lock = Lock()
   723 
   765 
   724         dc = wx.ClientDC(self.Editor)
   766         dc = wx.ClientDC(self.Editor)
   725         font = wx.Font(faces["size"], wx.SWISS, wx.NORMAL, wx.NORMAL, faceName = faces["mono"])
   767         font = wx.Font(faces["size"], wx.SWISS, wx.NORMAL, wx.NORMAL, faceName=faces["mono"])
   726         dc.SetFont(font)
   768         dc.SetFont(font)
   727         width, height = dc.GetTextExtent("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
   769         width, height = dc.GetTextExtent("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
   728         while width > 260:
   770         while width > 260:
   729             faces["size"] -= 1
   771             faces["size"] -= 1
   730             font = wx.Font(faces["size"], wx.SWISS, wx.NORMAL, wx.NORMAL, faceName = faces["mono"])
   772             font = wx.Font(faces["size"], wx.SWISS, wx.NORMAL, wx.NORMAL, faceName=faces["mono"])
   731             dc.SetFont(font)
   773             dc.SetFont(font)
   732             width, height = dc.GetTextExtent("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
   774             width, height = dc.GetTextExtent("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
   733         self.SetFont(font)
   775         self.SetFont(font)
   734         self.MiniTextDC = wx.MemoryDC()
   776         self.MiniTextDC = wx.MemoryDC()
   735         self.MiniTextDC.SetFont(wx.Font(faces["size"] * 0.75, wx.SWISS, wx.NORMAL, wx.NORMAL, faceName = faces["helv"]))
   777         self.MiniTextDC.SetFont(wx.Font(faces["size"] * 0.75, wx.SWISS, wx.NORMAL, wx.NORMAL, faceName=faces["helv"]))
   736 
   778 
   737         self.CurrentScale = None
   779         self.CurrentScale = None
   738         self.SetScale(ZOOM_FACTORS.index(1.0), False)
   780         self.SetScale(ZOOM_FACTORS.index(1.0), False)
   739 
   781 
   740         self.RefreshHighlightsTimer = wx.Timer(self, -1)
   782         self.RefreshHighlightsTimer = wx.Timer(self, -1)
   774                 self.CurrentCursor = cursor
   816                 self.CurrentCursor = cursor
   775                 self.Editor.SetCursor(CURSORS[cursor])
   817                 self.Editor.SetCursor(CURSORS[cursor])
   776 
   818 
   777     def GetScrolledRect(self, rect):
   819     def GetScrolledRect(self, rect):
   778         rect.x, rect.y = self.Editor.CalcScrolledPosition(int(rect.x * self.ViewScale[0]),
   820         rect.x, rect.y = self.Editor.CalcScrolledPosition(int(rect.x * self.ViewScale[0]),
   779                                                    int(rect.y * self.ViewScale[1]))
   821                                                           int(rect.y * self.ViewScale[1]))
   780         rect.width = int(rect.width * self.ViewScale[0]) + 2
   822         rect.width = int(rect.width * self.ViewScale[0]) + 2
   781         rect.height = int(rect.height * self.ViewScale[1]) + 2
   823         rect.height = int(rect.height * self.ViewScale[1]) + 2
   782         return rect
   824         return rect
   783 
   825 
   784     def GetTitle(self):
   826     def GetTitle(self):
   897         return self.MiniTextDC.GetTextExtent(text)
   939         return self.MiniTextDC.GetTextExtent(text)
   898 
   940 
   899     def GetMiniFont(self):
   941     def GetMiniFont(self):
   900         return self.MiniTextDC.GetFont()
   942         return self.MiniTextDC.GetFont()
   901 
   943 
   902 #-------------------------------------------------------------------------------
   944     # -------------------------------------------------------------------------------
   903 #                         Element management functions
   945     #                         Element management functions
   904 #-------------------------------------------------------------------------------
   946     # -------------------------------------------------------------------------------
   905 
   947 
   906     def AddBlock(self, block):
   948     def AddBlock(self, block):
   907         self.Blocks[block.GetId()] = block
   949         self.Blocks[block.GetId()] = block
   908 
   950 
   909     def AddWire(self, wire):
   951     def AddWire(self, wire):
   953             if isinstance(block, FBD_Connector) and\
   995             if isinstance(block, FBD_Connector) and\
   954                block.GetType() == CONTINUATION and\
   996                block.GetType() == CONTINUATION and\
   955                block.GetName() == name:
   997                block.GetName() == name:
   956                 blocks.append(block)
   998                 blocks.append(block)
   957         return blocks
   999         return blocks
   958     
  1000 
   959     def GetConnectorByName(self, name):
  1001     def GetConnectorByName(self, name):
   960         for block in self.Blocks.itervalues():
  1002         for block in self.Blocks.itervalues():
   961             if isinstance(block, FBD_Connector) and\
  1003             if isinstance(block, FBD_Connector) and\
   962                block.GetType() == CONNECTOR and\
  1004                block.GetType() == CONNECTOR and\
   963                block.GetName() == name:
  1005                block.GetName() == name:
   964                 return block
  1006                 return block
   965         return None
  1007         return None
   966 
  1008 
   967     def RefreshVisibleElements(self, xp = None, yp = None):
  1009     def RefreshVisibleElements(self, xp=None, yp=None):
   968         x, y = self.Editor.CalcUnscrolledPosition(0, 0)
  1010         x, y = self.Editor.CalcUnscrolledPosition(0, 0)
   969         if xp is not None:
  1011         if xp is not None:
   970             x = xp * self.Editor.GetScrollPixelsPerUnit()[0]
  1012             x = xp * self.Editor.GetScrollPixelsPerUnit()[0]
   971         if yp is not None:
  1013         if yp is not None:
   972             y = yp * self.Editor.GetScrollPixelsPerUnit()[1]
  1014             y = yp * self.Editor.GetScrollPixelsPerUnit()[1]
   989             block = element.GetParentBlock()
  1031             block = element.GetParentBlock()
   990             if isinstance(block, FBD_Block):
  1032             if isinstance(block, FBD_Block):
   991                 blockname = block.GetName()
  1033                 blockname = block.GetName()
   992                 connectorname = element.GetName()
  1034                 connectorname = element.GetName()
   993                 if blockname != "":
  1035                 if blockname != "":
   994                     iec_path = "%s.%s.%s"%(instance_path, blockname, connectorname)
  1036                     iec_path = "%s.%s.%s" % (instance_path, blockname, connectorname)
   995                 else:
  1037                 else:
   996                     if connectorname == "":
  1038                     if connectorname == "":
   997                         iec_path = "%s.%s%d"%(instance_path, block.GetType(), block.GetId())
  1039                         iec_path = "%s.%s%d" % (instance_path, block.GetType(), block.GetId())
   998                     else:
  1040                     else:
   999                         iec_path = "%s.%s%d_%s"%(instance_path, block.GetType(), block.GetId(), connectorname)
  1041                         iec_path = "%s.%s%d_%s" % (instance_path, block.GetType(), block.GetId(), connectorname)
  1000             elif isinstance(block, FBD_Variable):
  1042             elif isinstance(block, FBD_Variable):
  1001                 iec_path = "%s.%s"%(instance_path, block.GetName())
  1043                 iec_path = "%s.%s" % (instance_path, block.GetName())
  1002             elif isinstance(block, FBD_Connector):
  1044             elif isinstance(block, FBD_Connector):
  1003                 connection = self.GetConnectorByName(block.GetName())
  1045                 connection = self.GetConnectorByName(block.GetName())
  1004                 if connection is not None:
  1046                 if connection is not None:
  1005                     connector = connection.GetConnector()
  1047                     connector = connection.GetConnector()
  1006                     if len(connector.Wires) == 1:
  1048                     if len(connector.Wires) == 1:
  1007                         iec_path = self.GetElementIECPath(connector.Wires[0][0])
  1049                         iec_path = self.GetElementIECPath(connector.Wires[0][0])
  1008         elif isinstance(element, LD_Contact):
  1050         elif isinstance(element, LD_Contact):
  1009             iec_path = "%s.%s"%(instance_path, element.GetName())
  1051             iec_path = "%s.%s" % (instance_path, element.GetName())
  1010         elif isinstance(element, SFC_Step):
  1052         elif isinstance(element, SFC_Step):
  1011             iec_path = "%s.%s.X"%(instance_path, element.GetName())
  1053             iec_path = "%s.%s.X" % (instance_path, element.GetName())
  1012         elif isinstance(element, SFC_Transition):
  1054         elif isinstance(element, SFC_Transition):
  1013             connectors = element.GetConnectors()
  1055             connectors = element.GetConnectors()
  1014             previous_steps = self.GetPreviousSteps(connectors["inputs"])
  1056             previous_steps = self.GetPreviousSteps(connectors["inputs"])
  1015             next_steps = self.GetNextSteps(connectors["outputs"])
  1057             next_steps = self.GetNextSteps(connectors["outputs"])
  1016             iec_path = "%s.%s->%s"%(instance_path, ",".join(previous_steps), ",".join(next_steps))
  1058             iec_path = "%s.%s->%s" % (instance_path, ",".join(previous_steps), ",".join(next_steps))
  1017         return iec_path
  1059         return iec_path
  1018 
  1060 
  1019     def GetWireModifier(self, wire):
  1061     def GetWireModifier(self, wire):
  1020         connector = wire.EndConnected
  1062         connector = wire.EndConnected
  1021         block = connector.GetParentBlock()
  1063         block = connector.GetParentBlock()
  1040             height = min_height
  1082             height = min_height
  1041         if element.Size != (width, height):
  1083         if element.Size != (width, height):
  1042             element.SetSize(width, height)
  1084             element.SetSize(width, height)
  1043             element.RefreshModel()
  1085             element.RefreshModel()
  1044 
  1086 
  1045 #-------------------------------------------------------------------------------
  1087     # -------------------------------------------------------------------------------
  1046 #                              Reset functions
  1088     #                              Reset functions
  1047 #-------------------------------------------------------------------------------
  1089     # -------------------------------------------------------------------------------
  1048 
  1090 
  1049     # Resets Viewer lists
  1091     # Resets Viewer lists
  1050     def ResetView(self):
  1092     def ResetView(self):
  1051         self.Blocks = {}
  1093         self.Blocks = {}
  1052         self.Wires = {}
  1094         self.Wires = {}
  1160             self.PagePen = wx.TRANSPARENT_PEN
  1202             self.PagePen = wx.TRANSPARENT_PEN
  1161         if refresh:
  1203         if refresh:
  1162             self.RefreshVisibleElements()
  1204             self.RefreshVisibleElements()
  1163             self.Editor.Refresh(False)
  1205             self.Editor.Refresh(False)
  1164 
  1206 
  1165 
  1207     # -------------------------------------------------------------------------------
  1166 #-------------------------------------------------------------------------------
  1208     #                          Refresh functions
  1167 #                          Refresh functions
  1209     # -------------------------------------------------------------------------------
  1168 #-------------------------------------------------------------------------------
       
  1169 
       
  1170 
  1210 
  1171     def ElementNeedRefresh(self, element):
  1211     def ElementNeedRefresh(self, element):
  1172         self.ElementRefreshList_lock.acquire()
  1212         self.ElementRefreshList_lock.acquire()
  1173         self.ElementRefreshList.append(element)
  1213         self.ElementRefreshList.append(element)
  1174         self.ElementRefreshList_lock.release()
  1214         self.ElementRefreshList_lock.release()
  1206         self.Flush()
  1246         self.Flush()
  1207         self.ResetView()
  1247         self.ResetView()
  1208         self.ResetBuffer()
  1248         self.ResetBuffer()
  1209         instance = {}
  1249         instance = {}
  1210         # List of ids of already loaded blocks
  1250         # List of ids of already loaded blocks
  1211         instances = self.Controler.GetEditedElementInstancesInfos(self.TagName, debug = self.Debug)
  1251         instances = self.Controler.GetEditedElementInstancesInfos(self.TagName, debug=self.Debug)
  1212         # Load Blocks until they are all loaded
  1252         # Load Blocks until they are all loaded
  1213         while len(instances) > 0:
  1253         while len(instances) > 0:
  1214             self.loadInstance(instances.popitem(0)[1], instances, selection)
  1254             self.loadInstance(instances.popitem(0)[1], instances, selection)
  1215 
  1255 
  1216         if (selection is not None and
  1256         if selection is not None and isinstance(self.SelectedElement, Graphic_Group):
  1217             isinstance(self.SelectedElement, Graphic_Group)):
       
  1218             self.SelectedElement.RefreshWireExclusion()
  1257             self.SelectedElement.RefreshWireExclusion()
  1219             self.SelectedElement.RefreshBoundingBox()
  1258             self.SelectedElement.RefreshBoundingBox()
  1220 
  1259 
  1221         self.RefreshScrollBars()
  1260         self.RefreshScrollBars()
  1222 
  1261 
  1223         if self.TagName.split("::")[0] == "A" and self.Debug:
  1262         if self.TagName.split("::")[0] == "A" and self.Debug:
  1224             self.AddDataConsumer("%s.Q" % self.InstancePath.upper(), self.InstanceName)
  1263             self.AddDataConsumer("%s.Q" % self.InstancePath.upper(), self.InstanceName)
  1225         
  1264 
  1226         for wire in self.Wires:
  1265         for wire in self.Wires:
  1227             if not wire.IsConnectedCompatible():
  1266             if not wire.IsConnectedCompatible():
  1228                 wire.SetValid(False)
  1267                 wire.SetValid(False)
  1229             if self.Debug:
  1268             if self.Debug:
  1230                 iec_path = self.GetElementIECPath(wire)
  1269                 iec_path = self.GetElementIECPath(wire)
  1300             extent = self.rubberBand.GetCurrentExtent()
  1339             extent = self.rubberBand.GetCurrentExtent()
  1301             maxx = max(maxx, extent.x + extent.width)
  1340             maxx = max(maxx, extent.x + extent.width)
  1302             maxy = max(maxy, extent.y + extent.height)
  1341             maxy = max(maxy, extent.y + extent.height)
  1303         maxx = int(maxx * self.ViewScale[0])
  1342         maxx = int(maxx * self.ViewScale[0])
  1304         maxy = int(maxy * self.ViewScale[1])
  1343         maxy = int(maxy * self.ViewScale[1])
  1305         self.Editor.SetScrollbars(SCROLLBAR_UNIT, SCROLLBAR_UNIT,
  1344         self.Editor.SetScrollbars(
       
  1345             SCROLLBAR_UNIT, SCROLLBAR_UNIT,
  1306             round(maxx / SCROLLBAR_UNIT) + width_incr, round(maxy / SCROLLBAR_UNIT) + height_incr,
  1346             round(maxx / SCROLLBAR_UNIT) + width_incr, round(maxy / SCROLLBAR_UNIT) + height_incr,
  1307             xstart, ystart, True)
  1347             xstart, ystart, True)
  1308 
  1348 
  1309     def EnsureVisible(self, block):
  1349     def EnsureVisible(self, block):
  1310         xstart, ystart = self.GetViewStart()
  1350         xstart, ystart = self.GetViewStart()
  1343 
  1383 
  1344     # Load instance from given informations
  1384     # Load instance from given informations
  1345     def loadInstance(self, instance, remaining_instances, selection):
  1385     def loadInstance(self, instance, remaining_instances, selection):
  1346         self.current_id = max(self.current_id, instance.id)
  1386         self.current_id = max(self.current_id, instance.id)
  1347         creation_function = ElementCreationFunctions.get(instance.type, None)
  1387         creation_function = ElementCreationFunctions.get(instance.type, None)
  1348         connectors = {"inputs" : [], "outputs" : []}
  1388         connectors = {"inputs": [], "outputs": []}
  1349         specific_values = instance.specific_values
  1389         specific_values = instance.specific_values
  1350         if creation_function is not None:
  1390         if creation_function is not None:
  1351             element = creation_function(self, instance.id, specific_values)
  1391             element = creation_function(self, instance.id, specific_values)
  1352             if isinstance(element, SFC_Step):
  1392             if isinstance(element, SFC_Step):
  1353                 if len(instance.inputs) > 0:
  1393                 if len(instance.inputs) > 0:
  1382                 executionControl = True
  1422                 executionControl = True
  1383             if len(connectors["outputs"]) > 0 and connectors["outputs"][0][0] == "ENO":
  1423             if len(connectors["outputs"]) > 0 and connectors["outputs"][0][0] == "ENO":
  1384                 connectors["outputs"].pop(0)
  1424                 connectors["outputs"].pop(0)
  1385                 executionControl = True
  1425                 executionControl = True
  1386             block_name = specific_values.name if specific_values.name is not None else ""
  1426             block_name = specific_values.name if specific_values.name is not None else ""
  1387             element = FBD_Block(self, instance.type, block_name,
  1427             element = FBD_Block(
  1388                       instance.id, len(connectors["inputs"]),
  1428                 self, instance.type, block_name,
  1389                       connectors=connectors, executionControl=executionControl,
  1429                 instance.id, len(connectors["inputs"]),
  1390                       executionOrder=specific_values.execution_order)
  1430                 connectors=connectors, executionControl=executionControl,
       
  1431                 executionOrder=specific_values.execution_order)
  1391         if isinstance(element, Comment):
  1432         if isinstance(element, Comment):
  1392             self.AddComment(element)
  1433             self.AddComment(element)
  1393         else:
  1434         else:
  1394             self.AddBlock(element)
  1435             self.AddBlock(element)
  1395             connectors = element.GetConnectors()
  1436             connectors = element.GetConnectors()
  1397         element.SetSize(instance.width, instance.height)
  1438         element.SetSize(instance.width, instance.height)
  1398         for i, output_connector in enumerate(instance.outputs):
  1439         for i, output_connector in enumerate(instance.outputs):
  1399             connector_pos = wx.Point(*output_connector.position)
  1440             connector_pos = wx.Point(*output_connector.position)
  1400             if isinstance(element, FBD_Block):
  1441             if isinstance(element, FBD_Block):
  1401                 connector = element.GetConnector(connector_pos,
  1442                 connector = element.GetConnector(connector_pos,
  1402                     output_name = output_connector.name)
  1443                                                  output_name=output_connector.name)
  1403             elif i < len(connectors["outputs"]):
  1444             elif i < len(connectors["outputs"]):
  1404                 connector = connectors["outputs"][i]
  1445                 connector = connectors["outputs"][i]
  1405             else:
  1446             else:
  1406                 connector = None
  1447                 connector = None
  1407             if connector is not None:
  1448             if connector is not None:
  1413                     connector.SetPosition(connector_pos)
  1454                     connector.SetPosition(connector_pos)
  1414         for i, input_connector in enumerate(instance.inputs):
  1455         for i, input_connector in enumerate(instance.inputs):
  1415             connector_pos = wx.Point(*input_connector.position)
  1456             connector_pos = wx.Point(*input_connector.position)
  1416             if isinstance(element, FBD_Block):
  1457             if isinstance(element, FBD_Block):
  1417                 connector = element.GetConnector(connector_pos,
  1458                 connector = element.GetConnector(connector_pos,
  1418                     input_name = input_connector.name)
  1459                                                  input_name=input_connector.name)
  1419             elif i < len(connectors["inputs"]):
  1460             elif i < len(connectors["inputs"]):
  1420                 connector = connectors["inputs"][i]
  1461                 connector = connectors["inputs"][i]
  1421             else:
  1462             else:
  1422                 connector = None
  1463                 connector = None
  1423             if connector is not None:
  1464             if connector is not None:
  1459             if end_connector is not None:
  1500             if end_connector is not None:
  1460                 if len(points) > 0:
  1501                 if len(points) > 0:
  1461                     wire = Wire(self)
  1502                     wire = Wire(self)
  1462                     wire.SetPoints(points)
  1503                     wire.SetPoints(points)
  1463                 else:
  1504                 else:
  1464                     wire = Wire(self,
  1505                     wire = Wire(
  1465                         [wx.Point(*start_connector.GetPosition()),
  1506                         self,
  1466                          start_connector.GetDirection()],
  1507                         [wx.Point(*start_connector.GetPosition()), start_connector.GetDirection()],
  1467                         [wx.Point(*end_connector.GetPosition()),
  1508                         [wx.Point(*end_connector.GetPosition()),   end_connector.GetDirection()])
  1468                          end_connector.GetDirection()])
       
  1469                 start_connector.Wires.append((wire, 0))
  1509                 start_connector.Wires.append((wire, 0))
  1470                 end_connector.Wires.append((wire, -1))
  1510                 end_connector.Wires.append((wire, -1))
  1471                 wire.StartConnected = start_connector
  1511                 wire.StartConnected = start_connector
  1472                 wire.EndConnected = end_connector
  1512                 wire.EndConnected = end_connector
  1473                 connected.RefreshConnectors()
  1513                 connected.RefreshConnectors()
  1474                 self.AddWire(wire)
  1514                 self.AddWire(wire)
  1475                 if selection is not None and (\
  1515                 if selection is not None and (
  1476                    selection[1].get((id, refLocalId), False) or \
  1516                    selection[1].get((id, refLocalId), False) or
  1477                    selection[1].get((refLocalId, id), False)):
  1517                    selection[1].get((refLocalId, id), False)):
  1478                     self.SelectInGroup(wire)
  1518                     self.SelectInGroup(wire)
  1479             else:
  1519             else:
  1480                 links_connected = False
  1520                 links_connected = False
  1481 
  1521 
  1485         return self.Controler.IsOfType(type, reference, self.Debug)
  1525         return self.Controler.IsOfType(type, reference, self.Debug)
  1486 
  1526 
  1487     def IsEndType(self, type):
  1527     def IsEndType(self, type):
  1488         return self.Controler.IsEndType(type)
  1528         return self.Controler.IsEndType(type)
  1489 
  1529 
  1490     def GetBlockType(self, type, inputs = None):
  1530     def GetBlockType(self, type, inputs=None):
  1491         return self.Controler.GetBlockType(type, inputs, self.Debug)
  1531         return self.Controler.GetBlockType(type, inputs, self.Debug)
  1492 
  1532 
  1493 #-------------------------------------------------------------------------------
  1533     # -------------------------------------------------------------------------------
  1494 #                          Search Element functions
  1534     #                          Search Element functions
  1495 #-------------------------------------------------------------------------------
  1535     # -------------------------------------------------------------------------------
  1496 
  1536 
  1497     def FindBlock(self, event):
  1537     def FindBlock(self, event):
  1498         dc = self.GetLogicalDC()
  1538         dc = self.GetLogicalDC()
  1499         pos = event.GetLogicalPosition(dc)
  1539         pos = event.GetLogicalPosition(dc)
  1500         for block in self.Blocks.itervalues():
  1540         for block in self.Blocks.itervalues():
  1508         for wire in self.Wires:
  1548         for wire in self.Wires:
  1509             if wire.HitTest(pos) or wire.TestHandle(event) != (0, 0):
  1549             if wire.HitTest(pos) or wire.TestHandle(event) != (0, 0):
  1510                 return wire
  1550                 return wire
  1511         return None
  1551         return None
  1512 
  1552 
  1513     def FindElement(self, event, exclude_group = False, connectors = True):
  1553     def FindElement(self, event, exclude_group=False, connectors=True):
  1514         dc = self.GetLogicalDC()
  1554         dc = self.GetLogicalDC()
  1515         pos = event.GetLogicalPosition(dc)
  1555         pos = event.GetLogicalPosition(dc)
  1516         if self.SelectedElement and not (exclude_group and isinstance(self.SelectedElement, Graphic_Group)):
  1556         if self.SelectedElement and not (exclude_group and isinstance(self.SelectedElement, Graphic_Group)):
  1517             if self.SelectedElement.HitTest(pos, connectors) or self.SelectedElement.TestHandle(event) != (0, 0):
  1557             if self.SelectedElement.HitTest(pos, connectors) or self.SelectedElement.TestHandle(event) != (0, 0):
  1518                 return self.SelectedElement
  1558                 return self.SelectedElement
  1519         for element in self.GetElements():
  1559         for element in self.GetElements():
  1520             if element.HitTest(pos, connectors) or element.TestHandle(event) != (0, 0):
  1560             if element.HitTest(pos, connectors) or element.TestHandle(event) != (0, 0):
  1521                 return element
  1561                 return element
  1522         return None
  1562         return None
  1523 
  1563 
  1524     def FindBlockConnector(self, pos, direction = None, exclude = None):
  1564     def FindBlockConnector(self, pos, direction=None, exclude=None):
  1525         result, error = self.FindBlockConnectorWithError(pos, direction, exclude)
  1565         result, error = self.FindBlockConnectorWithError(pos, direction, exclude)
  1526         return result
  1566         return result
  1527 
  1567 
  1528     def FindBlockConnectorWithError(self, pos, direction = None, exclude = None):
  1568     def FindBlockConnectorWithError(self, pos, direction=None, exclude=None):
  1529         error = False        
  1569         error = False
  1530         startblock = None
  1570         startblock = None
  1531         for block in self.Blocks.itervalues():
  1571         for block in self.Blocks.itervalues():
  1532             connector = block.TestConnector(pos, direction, exclude)
  1572             connector = block.TestConnector(pos, direction, exclude)
  1533             if connector:
  1573             if connector:
  1534                 if self.IsWire(self.SelectedElement):
  1574                 if self.IsWire(self.SelectedElement):
  1537                 if not avail or not self.BlockCompatibility(startblock, block, direction):
  1577                 if not avail or not self.BlockCompatibility(startblock, block, direction):
  1538                     connector = None
  1578                     connector = None
  1539                     error = True
  1579                     error = True
  1540                 return connector, error
  1580                 return connector, error
  1541         return None, error
  1581         return None, error
  1542     
  1582 
  1543     def FindElementById(self, id):
  1583     def FindElementById(self, id):
  1544         block = self.Blocks.get(id, None)
  1584         block = self.Blocks.get(id, None)
  1545         if block is not None:
  1585         if block is not None:
  1546             return block
  1586             return block
  1547         comment = self.Comments.get(id, None)
  1587         comment = self.Comments.get(id, None)
  1561             self.SelectedElement.SetSelected(False)
  1601             self.SelectedElement.SetSelected(False)
  1562         self.SelectedElement = Graphic_Group(self)
  1602         self.SelectedElement = Graphic_Group(self)
  1563         self.SelectedElement.SetElements(self.GetElements())
  1603         self.SelectedElement.SetElements(self.GetElements())
  1564         self.SelectedElement.SetSelected(True)
  1604         self.SelectedElement.SetSelected(True)
  1565 
  1605 
  1566 #-------------------------------------------------------------------------------
  1606     # -------------------------------------------------------------------------------
  1567 #                           Popup menu functions
  1607     #                           Popup menu functions
  1568 #-------------------------------------------------------------------------------
  1608     # -------------------------------------------------------------------------------
  1569 
  1609 
  1570     def GetForceVariableMenuFunction(self, iec_path, element):
  1610     def GetForceVariableMenuFunction(self, iec_path, element):
  1571         iec_type = self.GetDataType(iec_path)
  1611         iec_type = self.GetDataType(iec_path)
       
  1612 
  1572         def ForceVariableFunction(event):
  1613         def ForceVariableFunction(event):
  1573             if iec_type is not None:
  1614             if iec_type is not None:
  1574                 dialog = ForceVariableDialog(self.ParentWindow, iec_type, str(element.GetValue()))
  1615                 dialog = ForceVariableDialog(self.ParentWindow, iec_type, str(element.GetValue()))
  1575                 if dialog.ShowModal() == wx.ID_OK:
  1616                 if dialog.ShowModal() == wx.ID_OK:
  1576                     self.ParentWindow.AddDebugVariable(iec_path)
  1617                     self.ParentWindow.AddDebugVariable(iec_path)
  1609             if self.Editor.HasCapture():
  1650             if self.Editor.HasCapture():
  1610                 self.Editor.ReleaseMouse()
  1651                 self.Editor.ReleaseMouse()
  1611             self.Editor.PopupMenu(menu)
  1652             self.Editor.PopupMenu(menu)
  1612             menu.Destroy()
  1653             menu.Destroy()
  1613 
  1654 
  1614     def PopupBlockMenu(self, connector = None):
  1655     def PopupBlockMenu(self, connector=None):
  1615         menu = wx.Menu(title='')
  1656         menu = wx.Menu(title='')
  1616         if connector is not None and connector.IsCompatible("BOOL"):
  1657         if connector is not None and connector.IsCompatible("BOOL"):
  1617             self.AddBlockPinMenuItems(menu, connector)
  1658             self.AddBlockPinMenuItems(menu, connector)
  1618         else:
  1659         else:
  1619             edit = self.SelectedElement.GetType() in self.Controler.GetProjectPouNames(self.Debug)
  1660             edit = self.SelectedElement.GetType() in self.Controler.GetProjectPouNames(self.Debug)
  1660         start_connector = (
  1701         start_connector = (
  1661             self.SelectedElement.GetEndConnected()
  1702             self.SelectedElement.GetEndConnected()
  1662             if self.SelectedElement.GetStartConnected() in connected
  1703             if self.SelectedElement.GetStartConnected() in connected
  1663             else self.SelectedElement.GetStartConnected())
  1704             else self.SelectedElement.GetStartConnected())
  1664 
  1705 
  1665         self.AddWireMenuItems(menu, delete,
  1706         self.AddWireMenuItems(
       
  1707             menu, delete,
  1666             start_connector.GetDirection() == EAST and
  1708             start_connector.GetDirection() == EAST and
  1667             not isinstance(start_connector.GetParentBlock(), SFC_Step))
  1709             not isinstance(start_connector.GetParentBlock(), SFC_Step))
  1668 
  1710 
  1669         menu.AppendSeparator()
  1711         menu.AppendSeparator()
  1670         self.AddDefaultMenuItems(menu, block=True)
  1712         self.AddDefaultMenuItems(menu, block=True)
  1693         menu = wx.Menu(title='')
  1735         menu = wx.Menu(title='')
  1694         self.AddDefaultMenuItems(menu, block=block)
  1736         self.AddDefaultMenuItems(menu, block=block)
  1695         self.Editor.PopupMenu(menu)
  1737         self.Editor.PopupMenu(menu)
  1696         menu.Destroy()
  1738         menu.Destroy()
  1697 
  1739 
  1698 #-------------------------------------------------------------------------------
  1740     # -------------------------------------------------------------------------------
  1699 #                            Menu items functions
  1741     #                            Menu items functions
  1700 #-------------------------------------------------------------------------------
  1742     # -------------------------------------------------------------------------------
  1701 
  1743 
  1702     def OnAlignLeftMenu(self, event):
  1744     def OnAlignLeftMenu(self, event):
  1703         if self.SelectedElement is not None and isinstance(self.SelectedElement, Graphic_Group):
  1745         if self.SelectedElement is not None and isinstance(self.SelectedElement, Graphic_Group):
  1704             self.SelectedElement.AlignElements(ALIGN_LEFT, None)
  1746             self.SelectedElement.AlignElements(ALIGN_LEFT, None)
  1705             self.RefreshBuffer()
  1747             self.RefreshBuffer()
  1769             self.SelectedElement.DeleteSegment()
  1811             self.SelectedElement.DeleteSegment()
  1770             self.SelectedElement.Refresh()
  1812             self.SelectedElement.Refresh()
  1771 
  1813 
  1772     def OnReplaceWireMenu(self, event):
  1814     def OnReplaceWireMenu(self, event):
  1773         # Check that selected element is a wire before applying replace
  1815         # Check that selected element is a wire before applying replace
  1774         if (self.SelectedElement is not None and
  1816         if self.SelectedElement is not None and self.IsWire(self.SelectedElement):
  1775             self.IsWire(self.SelectedElement)):
       
  1776 
       
  1777             # Get wire redraw bbox to erase it from screen
  1817             # Get wire redraw bbox to erase it from screen
  1778             wire = self.SelectedElement
  1818             wire = self.SelectedElement
  1779             redraw_rect = wire.GetRedrawRect()
  1819             redraw_rect = wire.GetRedrawRect()
  1780 
  1820 
  1781             # Get connector at both ends of wire
  1821             # Get connector at both ends of wire
  1842             connection.SetPosition(start_point[0] - rel_pos[0],
  1882             connection.SetPosition(start_point[0] - rel_pos[0],
  1843                                    start_point[1] - rel_pos[1])
  1883                                    start_point[1] - rel_pos[1])
  1844 
  1884 
  1845             # Add Wire to Viewer and connect it to blocks
  1885             # Add Wire to Viewer and connect it to blocks
  1846             new_wire = Wire(self,
  1886             new_wire = Wire(self,
  1847                 [wx.Point(*start_point), connector.GetDirection()],
  1887                             [wx.Point(*start_point), connector.GetDirection()],
  1848                 [wx.Point(*end_point), end_connector.GetDirection()])
  1888                             [wx.Point(*end_point), end_connector.GetDirection()])
  1849             self.AddWire(new_wire)
  1889             self.AddWire(new_wire)
  1850             connector.Connect((new_wire, 0), False)
  1890             connector.Connect((new_wire, 0), False)
  1851             end_connector.Connect((new_wire, -1), False)
  1891             end_connector.Connect((new_wire, -1), False)
  1852             new_wire.ConnectStartPoint(None, connector)
  1892             new_wire.ConnectStartPoint(None, connector)
  1853             new_wire.ConnectEndPoint(None, end_connector)
  1893             new_wire.ConnectEndPoint(None, end_connector)
  1881         if self.SelectedElement is not None and self.IsBlock(self.SelectedElement):
  1921         if self.SelectedElement is not None and self.IsBlock(self.SelectedElement):
  1882             self.RemoveDivergenceBranch(self.SelectedElement)
  1922             self.RemoveDivergenceBranch(self.SelectedElement)
  1883 
  1923 
  1884     def OnEditBlockMenu(self, event):
  1924     def OnEditBlockMenu(self, event):
  1885         if self.SelectedElement is not None:
  1925         if self.SelectedElement is not None:
  1886             self.ParentWindow.EditProjectElement(ITEM_POU, "P::%s"%self.SelectedElement.GetType())
  1926             self.ParentWindow.EditProjectElement(ITEM_POU, "P::%s" % self.SelectedElement.GetType())
  1887 
  1927 
  1888     def OnAdjustBlockSizeMenu(self, event):
  1928     def OnAdjustBlockSizeMenu(self, event):
  1889         if self.SelectedElement is not None:
  1929         if self.SelectedElement is not None:
  1890             movex, movey = self.SelectedElement.SetBestSize(self.Scaling)
  1930             movex, movey = self.SelectedElement.SetBestSize(self.Scaling)
  1891             self.SelectedElement.RefreshModel(True)
  1931             self.SelectedElement.RefreshModel(True)
  1914             wx.CallAfter(func, self.rubberBand.GetCurrentExtent(), *args)
  1954             wx.CallAfter(func, self.rubberBand.GetCurrentExtent(), *args)
  1915         return AddMenuCallBack
  1955         return AddMenuCallBack
  1916 
  1956 
  1917     def GetAddToWireMenuCallBack(self, func, *args):
  1957     def GetAddToWireMenuCallBack(self, func, *args):
  1918         args += (self.SelectedElement,)
  1958         args += (self.SelectedElement,)
       
  1959 
  1919         def AddToWireMenuCallBack(event):
  1960         def AddToWireMenuCallBack(event):
  1920             func(wx.Rect(0, 0, 0, 0), *args)
  1961             func(wx.Rect(0, 0, 0, 0), *args)
  1921         return AddToWireMenuCallBack
  1962         return AddToWireMenuCallBack
  1922 
  1963 
  1923     def GetClipboardCallBack(self, func):
  1964     def GetClipboardCallBack(self, func):
  1924         def ClipboardCallback(event):
  1965         def ClipboardCallback(event):
  1925             wx.CallAfter(func)
  1966             wx.CallAfter(func)
  1926         return ClipboardCallback
  1967         return ClipboardCallback
  1927 
  1968 
  1928 #-------------------------------------------------------------------------------
  1969     # -------------------------------------------------------------------------------
  1929 #                          Mouse event functions
  1970     #                          Mouse event functions
  1930 #-------------------------------------------------------------------------------
  1971     # -------------------------------------------------------------------------------
  1931 
  1972 
  1932     def OnViewerMouseEvent(self, event):
  1973     def OnViewerMouseEvent(self, event):
  1933         self.ResetBuffer()
  1974         self.ResetBuffer()
  1934         if event.Leaving() and self.ToolTipElement is not None:
  1975         if event.Leaving() and self.ToolTipElement is not None:
  1935             self.ToolTipElement.DestroyToolTip()
  1976             self.ToolTipElement.DestroyToolTip()
  1936         elif (not event.Entering() and
  1977         elif (not event.Entering() and
  1937             gettime() - self.LastToolTipCheckTime > REFRESH_PERIOD):
  1978               gettime() - self.LastToolTipCheckTime > REFRESH_PERIOD):
  1938             self.LastToolTipCheckTime = gettime()
  1979             self.LastToolTipCheckTime = gettime()
  1939             element = None
  1980             element = None
  1940             if not event.Leaving() and not event.LeftUp() and not event.LeftDClick():
  1981             if not event.Leaving() and not event.LeftUp() and not event.LeftDClick():
  1941                 dc = self.GetLogicalDC()
  1982                 dc = self.GetLogicalDC()
  1942                 pos = event.GetLogicalPosition(dc)
  1983                 pos = event.GetLogicalPosition(dc)
  1989                     self.DrawingWire = False
  2030                     self.DrawingWire = False
  1990                     if self.SelectedElement is not None:
  2031                     if self.SelectedElement is not None:
  1991                         if element is None or element.TestHandle(event) == (0, 0):
  2032                         if element is None or element.TestHandle(event) == (0, 0):
  1992                             connector = self.FindBlockConnector(pos, self.SelectedElement.GetConnectionDirection())
  2033                             connector = self.FindBlockConnector(pos, self.SelectedElement.GetConnectionDirection())
  1993                         if connector is not None:
  2034                         if connector is not None:
  1994                             event.Dragging = lambda : True
  2035                             event.Dragging = lambda: True
  1995                             self.SelectedElement.OnMotion(event, dc, self.Scaling)
  2036                             self.SelectedElement.OnMotion(event, dc, self.Scaling)
  1996                         if self.SelectedElement.EndConnected is not None:
  2037                         if self.SelectedElement.EndConnected is not None:
  1997                             self.SelectedElement.ResetPoints()
  2038                             self.SelectedElement.ResetPoints()
  1998                             self.SelectedElement.GeneratePoints()
  2039                             self.SelectedElement.GeneratePoints()
  1999                             self.SelectedElement.RefreshModel()
  2040                             self.SelectedElement.RefreshModel()
  2128                             self.Editor.ReleaseMouse()
  2169                             self.Editor.ReleaseMouse()
  2129 
  2170 
  2130                         # Popup contextual menu
  2171                         # Popup contextual menu
  2131                         menu = wx.Menu()
  2172                         menu = wx.Menu()
  2132                         self.AddMenuItems(menu,
  2173                         self.AddMenuItems(menu,
  2133                             [(wx.NewId(), wx.ITEM_NORMAL, text, '', callback)
  2174                                           [(wx.NewId(), wx.ITEM_NORMAL, text, '', callback)
  2134                              for text, callback in items])
  2175                                            for text, callback in items])
  2135                         self.PopupMenu(menu)
  2176                         self.PopupMenu(menu)
  2136 
  2177 
  2137                     self.SelectedElement.StartConnected.HighlightParentBlock(False)
  2178                     self.SelectedElement.StartConnected.HighlightParentBlock(False)
  2138                     if self.DrawingWire:
  2179                     if self.DrawingWire:
  2139                         self.DrawingWire = False
  2180                         self.DrawingWire = False
  2235                         pou_type = {
  2276                         pou_type = {
  2236                             "program": ITEM_PROGRAM,
  2277                             "program": ITEM_PROGRAM,
  2237                             "functionBlock": ITEM_FUNCTIONBLOCK,
  2278                             "functionBlock": ITEM_FUNCTIONBLOCK,
  2238                         }.get(self.Controler.GetPouType(instance_type))
  2279                         }.get(self.Controler.GetPouType(instance_type))
  2239                         if pou_type is not None and instance_type in self.Controler.GetProjectPouNames(self.Debug):
  2280                         if pou_type is not None and instance_type in self.Controler.GetProjectPouNames(self.Debug):
  2240                             self.ParentWindow.OpenDebugViewer(pou_type,
  2281                             self.ParentWindow.OpenDebugViewer(
  2241                                 "%s.%s"%(self.GetInstancePath(True), self.SelectedElement.GetName()),
  2282                                 pou_type,
       
  2283                                 "%s.%s" % (self.GetInstancePath(True), self.SelectedElement.GetName()),
  2242                                 self.Controler.ComputePouName(instance_type))
  2284                                 self.Controler.ComputePouName(instance_type))
  2243                 else:
  2285                 else:
  2244                     iec_path = self.GetElementIECPath(self.SelectedElement)
  2286                     iec_path = self.GetElementIECPath(self.SelectedElement)
  2245                     if iec_path is not None:
  2287                     if iec_path is not None:
  2246                         if isinstance(self.SelectedElement, Wire):
  2288                         if isinstance(self.SelectedElement, Wire):
  2247                             if self.SelectedElement.EndConnected is not None:
  2289                             if self.SelectedElement.EndConnected is not None:
  2248                                 self.ParentWindow.OpenDebugViewer(ITEM_VAR_LOCAL, iec_path,
  2290                                 self.ParentWindow.OpenDebugViewer(
  2249                                         self.SelectedElement.EndConnected.GetType())
  2291                                     ITEM_VAR_LOCAL, iec_path,
       
  2292                                     self.SelectedElement.EndConnected.GetType())
  2250                         else:
  2293                         else:
  2251                             self.ParentWindow.OpenDebugViewer(ITEM_VAR_LOCAL, iec_path, "BOOL")
  2294                             self.ParentWindow.OpenDebugViewer(ITEM_VAR_LOCAL, iec_path, "BOOL")
  2252             elif event.ControlDown() and not event.ShiftDown():
  2295             elif event.ControlDown() and not event.ShiftDown():
  2253                 if not isinstance(self.SelectedElement, Graphic_Group):
  2296                 if not isinstance(self.SelectedElement, Graphic_Group):
  2254                     if isinstance(self.SelectedElement, FBD_Block):
  2297                     if isinstance(self.SelectedElement, FBD_Block):
  2255                         instance_type = self.SelectedElement.GetType()
  2298                         instance_type = self.SelectedElement.GetType()
  2256                     else:
  2299                     else:
  2257                         instance_type = None
  2300                         instance_type = None
  2258                     if instance_type in self.Controler.GetProjectPouNames(self.Debug):
  2301                     if instance_type in self.Controler.GetProjectPouNames(self.Debug):
  2259                         self.ParentWindow.EditProjectElement(ITEM_POU,
  2302                         self.ParentWindow.EditProjectElement(
  2260                                 self.Controler.ComputePouName(instance_type))
  2303                             ITEM_POU,
       
  2304                             self.Controler.ComputePouName(instance_type))
  2261                     else:
  2305                     else:
  2262                         self.SelectedElement.OnLeftDClick(event, self.GetLogicalDC(), self.Scaling)
  2306                         self.SelectedElement.OnLeftDClick(event, self.GetLogicalDC(), self.Scaling)
  2263             elif event.ControlDown() and event.ShiftDown():
  2307             elif event.ControlDown() and event.ShiftDown():
  2264                 movex, movey = self.SelectedElement.SetBestSize(self.Scaling)
  2308                 movex, movey = self.SelectedElement.SetBestSize(self.Scaling)
  2265                 self.SelectedElement.RefreshModel()
  2309                 self.SelectedElement.RefreshModel()
  2288                 else:
  2332                 else:
  2289                     self.Scroll(scrollx, scrolly)
  2333                     self.Scroll(scrollx, scrolly)
  2290                     self.RefreshScrollBars()
  2334                     self.RefreshScrollBars()
  2291                 self.RefreshVisibleElements()
  2335                 self.RefreshVisibleElements()
  2292         else:
  2336         else:
  2293             if (not event.Dragging() and
  2337             if not event.Dragging() and (gettime() - self.LastHighlightCheckTime) > REFRESH_PERIOD:
  2294                 gettime() - self.LastHighlightCheckTime > REFRESH_PERIOD):
       
  2295                 self.LastHighlightCheckTime = gettime()
  2338                 self.LastHighlightCheckTime = gettime()
  2296                 highlighted = self.FindElement(event, connectors=False)
  2339                 highlighted = self.FindElement(event, connectors=False)
  2297                 if self.HighlightedElement is not None and self.HighlightedElement != highlighted:
  2340                 if self.HighlightedElement is not None and self.HighlightedElement != highlighted:
  2298                     self.HighlightedElement.SetHighlighted(False)
  2341                     self.HighlightedElement.SetHighlighted(False)
  2299                     self.HighlightedElement = None
  2342                     self.HighlightedElement = None
  2306             if self.rubberBand.IsShown():
  2349             if self.rubberBand.IsShown():
  2307                 self.rubberBand.OnMotion(event, dc, self.Scaling)
  2350                 self.rubberBand.OnMotion(event, dc, self.Scaling)
  2308             elif not self.Debug and self.Mode == MODE_SELECTION and self.SelectedElement is not None:
  2351             elif not self.Debug and self.Mode == MODE_SELECTION and self.SelectedElement is not None:
  2309                 if self.DrawingWire:
  2352                 if self.DrawingWire:
  2310                     connector, errorHighlight = self.FindBlockConnectorWithError(pos, self.SelectedElement.GetConnectionDirection(), self.SelectedElement.EndConnected)
  2353                     connector, errorHighlight = self.FindBlockConnectorWithError(pos, self.SelectedElement.GetConnectionDirection(), self.SelectedElement.EndConnected)
  2311                     self.SelectedElement.ErrHighlight = errorHighlight;
  2354                     self.SelectedElement.ErrHighlight = errorHighlight
  2312                     if not connector or self.SelectedElement.EndConnected == None:
  2355                     if not connector or self.SelectedElement.EndConnected is None:
  2313                         self.SelectedElement.ResetPoints()
  2356                         self.SelectedElement.ResetPoints()
  2314                         movex, movey = self.SelectedElement.OnMotion(event, dc, self.Scaling)
  2357                         movex, movey = self.SelectedElement.OnMotion(event, dc, self.Scaling)
  2315                         self.SelectedElement.GeneratePoints()
  2358                         self.SelectedElement.GeneratePoints()
  2316                         if movex != 0 or movey != 0:
  2359                         if movex != 0 or movey != 0:
  2317                             self.RefreshRect(self.GetScrolledRect(self.SelectedElement.GetRedrawRect(movex, movey)), False)
  2360                             self.RefreshRect(self.GetScrolledRect(self.SelectedElement.GetRedrawRect(movex, movey)), False)
  2369             if position.y < SCROLL_ZONE and ystart > 0:
  2412             if position.y < SCROLL_ZONE and ystart > 0:
  2370                 move_window.y = -1
  2413                 move_window.y = -1
  2371             elif position.y > window_size[1] - SCROLL_ZONE:
  2414             elif position.y > window_size[1] - SCROLL_ZONE:
  2372                 move_window.y = 1
  2415                 move_window.y = 1
  2373             if move_window.x != 0 or move_window.y != 0:
  2416             if move_window.x != 0 or move_window.y != 0:
  2374                 self.RefreshVisibleElements(xp = xstart + move_window.x, yp = ystart + move_window.y)
  2417                 self.RefreshVisibleElements(xp=xstart + move_window.x, yp=ystart + move_window.y)
  2375                 self.Scroll(xstart + move_window.x, ystart + move_window.y)
  2418                 self.Scroll(xstart + move_window.x, ystart + move_window.y)
  2376                 self.RefreshScrollBars(move_window.x, move_window.y)
  2419                 self.RefreshScrollBars(move_window.x, move_window.y)
  2377 
  2420 
  2378     def BlockCompatibility(self, startblock=None, endblock=None, direction = None):
  2421     def BlockCompatibility(self, startblock=None, endblock=None, direction=None):
  2379         return True
  2422         return True
  2380 
  2423 
  2381     def GetPopupMenuItems(self):
  2424     def GetPopupMenuItems(self):
  2382         start_connector = self.SelectedElement.GetStartConnected()
  2425         start_connector = self.SelectedElement.GetStartConnected()
  2383         start_direction = start_connector.GetDirection()
  2426         start_direction = start_connector.GetDirection()
  2421                 else:
  2464                 else:
  2422                     items.append(
  2465                     items.append(
  2423                         (_(u'Variable'), self.GetAddToWireMenuCallBack(self.AddNewVariable, True)))
  2466                         (_(u'Variable'), self.GetAddToWireMenuCallBack(self.AddNewVariable, True)))
  2424         return items
  2467         return items
  2425 
  2468 
  2426 #-------------------------------------------------------------------------------
  2469     # -------------------------------------------------------------------------------
  2427 #                          Keyboard event functions
  2470     #                          Keyboard event functions
  2428 #-------------------------------------------------------------------------------
  2471     # -------------------------------------------------------------------------------
  2429 
  2472 
  2430     ARROW_KEY_MOVE = {
  2473     ARROW_KEY_MOVE = {
  2431         wx.WXK_LEFT: (-1, 0),
  2474         wx.WXK_LEFT: (-1, 0),
  2432         wx.WXK_RIGHT: (1, 0),
  2475         wx.WXK_RIGHT: (1, 0),
  2433         wx.WXK_UP: (0, -1),
  2476         wx.WXK_UP: (0, -1),
  2451             self.RefreshScrollBars()
  2494             self.RefreshScrollBars()
  2452             wx.CallAfter(self.SetCurrentCursor, 0)
  2495             wx.CallAfter(self.SetCurrentCursor, 0)
  2453             self.RefreshRect(self.GetScrolledRect(rect), False)
  2496             self.RefreshRect(self.GetScrolledRect(rect), False)
  2454         elif not self.Debug and keycode == wx.WXK_RETURN and self.SelectedElement is not None:
  2497         elif not self.Debug and keycode == wx.WXK_RETURN and self.SelectedElement is not None:
  2455             self.SelectedElement.OnLeftDClick(event, self.GetLogicalDC(), self.Scaling)
  2498             self.SelectedElement.OnLeftDClick(event, self.GetLogicalDC(), self.Scaling)
  2456         elif self.ARROW_KEY_MOVE.has_key(keycode):
  2499         elif keycode in self.ARROW_KEY_MOVE:
  2457             move = self.ARROW_KEY_MOVE[keycode]
  2500             move = self.ARROW_KEY_MOVE[keycode]
  2458             if event.ControlDown() and event.ShiftDown():
  2501             if event.ControlDown() and event.ShiftDown():
  2459                 self.Scroll({-1: 0, 0: xpos, 1: xmax}[move[0]],
  2502                 self.Scroll({-1: 0, 0: xpos, 1: xmax}[move[0]],
  2460                             {-1: 0, 0: ypos, 1: ymax}[move[1]])
  2503                             {-1: 0, 0: ypos, 1: ymax}[move[1]])
  2461                 self.RefreshVisibleElements()
  2504                 self.RefreshVisibleElements()
  2499             self.SetScale(self.CurrentScale - 1)
  2542             self.SetScale(self.CurrentScale - 1)
  2500             self.ParentWindow.RefreshDisplayMenu()
  2543             self.ParentWindow.RefreshDisplayMenu()
  2501         else:
  2544         else:
  2502             event.Skip()
  2545             event.Skip()
  2503 
  2546 
  2504 #-------------------------------------------------------------------------------
  2547     # -------------------------------------------------------------------------------
  2505 #                  Model adding functions from Drop Target
  2548     #                  Model adding functions from Drop Target
  2506 #-------------------------------------------------------------------------------
  2549     # -------------------------------------------------------------------------------
  2507 
  2550 
  2508     def AddVariableBlock(self, x, y, scaling, var_class, var_name, var_type):
  2551     def AddVariableBlock(self, x, y, scaling, var_class, var_name, var_type):
  2509         id = self.GetNewId()
  2552         id = self.GetNewId()
  2510         variable = FBD_Variable(self, var_class, var_name, var_type, id)
  2553         variable = FBD_Variable(self, var_class, var_name, var_type, id)
  2511         width, height = variable.GetMinSize()
  2554         width, height = variable.GetMinSize()
  2522         self.RefreshBuffer()
  2565         self.RefreshBuffer()
  2523         self.RefreshScrollBars()
  2566         self.RefreshScrollBars()
  2524         self.RefreshVisibleElements()
  2567         self.RefreshVisibleElements()
  2525         self.Editor.Refresh(False)
  2568         self.Editor.Refresh(False)
  2526 
  2569 
  2527 #-------------------------------------------------------------------------------
  2570     # -------------------------------------------------------------------------------
  2528 #                          Model adding functions
  2571     #                          Model adding functions
  2529 #-------------------------------------------------------------------------------
  2572     # -------------------------------------------------------------------------------
  2530 
  2573 
  2531     def GetScaledSize(self, width, height):
  2574     def GetScaledSize(self, width, height):
  2532         if self.Scaling is not None:
  2575         if self.Scaling is not None:
  2533             width = round(float(width) / float(self.Scaling[0]) + 0.4) * self.Scaling[0]
  2576             width = round(float(width) / float(self.Scaling[0]) + 0.4) * self.Scaling[0]
  2534             height = round(float(height) / float(self.Scaling[1]) + 0.4) * self.Scaling[1]
  2577             height = round(float(height) / float(self.Scaling[1]) + 0.4) * self.Scaling[1]
  2569         dialog.SetMinElementSize((bbox.width, bbox.height))
  2612         dialog.SetMinElementSize((bbox.width, bbox.height))
  2570         if dialog.ShowModal() == wx.ID_OK:
  2613         if dialog.ShowModal() == wx.ID_OK:
  2571             id = self.GetNewId()
  2614             id = self.GetNewId()
  2572             values = dialog.GetValues()
  2615             values = dialog.GetValues()
  2573             values.setdefault("name", "")
  2616             values.setdefault("name", "")
  2574             block = FBD_Block(self, values["type"], values["name"], id,
  2617             block = FBD_Block(
  2575                     values["extension"], values["inputs"],
  2618                 self, values["type"], values["name"], id,
  2576                     executionControl = values["executionControl"],
  2619                 values["extension"], values["inputs"],
  2577                     executionOrder = values["executionOrder"])
  2620                 executionControl=values["executionControl"],
       
  2621                 executionOrder=values["executionOrder"])
  2578             self.Controler.AddEditedElementBlock(self.TagName, id, values["type"], values.get("name", None))
  2622             self.Controler.AddEditedElementBlock(self.TagName, id, values["type"], values.get("name", None))
  2579             connector = None
  2623             connector = None
  2580             if wire is not None:
  2624             if wire is not None:
  2581                 for input_connector in block.GetConnectors()["inputs"]:
  2625                 for input_connector in block.GetConnectors()["inputs"]:
  2582                     if input_connector.IsCompatible(
  2626                     if input_connector.IsCompatible(
  2583                             wire.GetStartConnectedType()):
  2627                             wire.GetStartConnectedType()):
  2584                         connector = input_connector
  2628                         connector = input_connector
  2585                         break
  2629                         break
  2586             self.AddNewElement(block, bbox, wire, connector)
  2630             self.AddNewElement(block, bbox, wire, connector)
  2587             self.RefreshVariablePanel()
  2631             self.RefreshVariablePanel()
  2588             self.ParentWindow.RefreshPouInstanceVariablesPanel()                    
  2632             self.ParentWindow.RefreshPouInstanceVariablesPanel()
  2589         dialog.Destroy()
  2633         dialog.Destroy()
  2590 
  2634 
  2591     def AddNewVariable(self, bbox, exclude_input=False, wire=None):
  2635     def AddNewVariable(self, bbox, exclude_input=False, wire=None):
  2592         dialog = FBDVariableDialog(self.ParentWindow, self.Controler, self.TagName, exclude_input)
  2636         dialog = FBDVariableDialog(self.ParentWindow, self.Controler, self.TagName, exclude_input)
  2593         dialog.SetPreviewFont(self.GetFont())
  2637         dialog.SetPreviewFont(self.GetFont())
  2623 
  2667 
  2624     def AddNewComment(self, bbox):
  2668     def AddNewComment(self, bbox):
  2625         dialog = wx.TextEntryDialog(self.ParentWindow,
  2669         dialog = wx.TextEntryDialog(self.ParentWindow,
  2626                                     _("Edit comment"),
  2670                                     _("Edit comment"),
  2627                                     _("Please enter comment text"),
  2671                                     _("Please enter comment text"),
  2628                                     "", wx.OK|wx.CANCEL|wx.TE_MULTILINE)
  2672                                     "", wx.OK | wx.CANCEL | wx.TE_MULTILINE)
  2629         dialog.SetClientSize(wx.Size(400, 200))
  2673         dialog.SetClientSize(wx.Size(400, 200))
  2630         if dialog.ShowModal() == wx.ID_OK:
  2674         if dialog.ShowModal() == wx.ID_OK:
  2631             value = dialog.GetValue()
  2675             value = dialog.GetValue()
  2632             id = self.GetNewId()
  2676             id = self.GetNewId()
  2633             comment = Comment(self, value, id)
  2677             comment = Comment(self, value, id)
  2634             comment.SetPosition(bbox.x, bbox.y)
  2678             comment.SetPosition(bbox.x, bbox.y)
  2635             min_width, min_height = comment.GetMinSize()
  2679             min_width, min_height = comment.GetMinSize()
  2636             comment.SetSize(*self.GetScaledSize(max(min_width,bbox.width),max(min_height,bbox.height)))
  2680             comment.SetSize(*self.GetScaledSize(max(min_width, bbox.width), max(min_height, bbox.height)))
  2637             self.AddComment(comment)
  2681             self.AddComment(comment)
  2638             self.Controler.AddEditedElementComment(self.TagName, id)
  2682             self.Controler.AddEditedElementComment(self.TagName, id)
  2639             self.RefreshCommentModel(comment)
  2683             self.RefreshCommentModel(comment)
  2640             self.RefreshBuffer()
  2684             self.RefreshBuffer()
  2641             self.RefreshScrollBars()
  2685             self.RefreshScrollBars()
  2687             self.AddNewElement(powerrail, bbox, wire)
  2731             self.AddNewElement(powerrail, bbox, wire)
  2688 
  2732 
  2689     def AddNewStep(self, bbox, initial=False, wire=None):
  2733     def AddNewStep(self, bbox, initial=False, wire=None):
  2690         if wire is not None:
  2734         if wire is not None:
  2691             values = {
  2735             values = {
  2692                 "name": self.Controler.GenerateNewName(
  2736                 "name":   self.Controler.GenerateNewName(self.TagName, None, "Step%d", 0),
  2693                     self.TagName, None, "Step%d", 0),
  2737                 "input":  True,
  2694                 "input": True,
       
  2695                 "output": True,
  2738                 "output": True,
  2696                 "action":False}
  2739                 "action": False
       
  2740             }
  2697         else:
  2741         else:
  2698             dialog = SFCStepDialog(self.ParentWindow, self.Controler, self.TagName, initial)
  2742             dialog = SFCStepDialog(self.ParentWindow, self.Controler, self.TagName, initial)
  2699             dialog.SetPreviewFont(self.GetFont())
  2743             dialog.SetPreviewFont(self.GetFont())
  2700             dialog.SetMinElementSize((bbox.width, bbox.height))
  2744             dialog.SetMinElementSize((bbox.width, bbox.height))
  2701             values = (dialog.GetValues()
  2745             values = (dialog.GetValues()
  2734                 connector = transition.GetConditionConnector()
  2778                 connector = transition.GetConditionConnector()
  2735             else:
  2779             else:
  2736                 connector = transition.GetConnectors()["inputs"][0]
  2780                 connector = transition.GetConnectors()["inputs"][0]
  2737             self.AddNewElement(transition, bbox, wire, connector)
  2781             self.AddNewElement(transition, bbox, wire, connector)
  2738 
  2782 
  2739     def AddNewDivergence(self, bbox, poss_div_types = None, wire=None):
  2783     def AddNewDivergence(self, bbox, poss_div_types=None, wire=None):
  2740         dialog = SFCDivergenceDialog(self.ParentWindow, self.Controler, self.TagName, poss_div_types)
  2784         dialog = SFCDivergenceDialog(self.ParentWindow, self.Controler, self.TagName, poss_div_types)
  2741         dialog.SetPreviewFont(self.GetFont())
  2785         dialog.SetPreviewFont(self.GetFont())
  2742         dialog.SetMinElementSize((bbox.width, bbox.height))
  2786         dialog.SetMinElementSize((bbox.width, bbox.height))
  2743         if dialog.ShowModal() == wx.ID_OK:
  2787         if dialog.ShowModal() == wx.ID_OK:
  2744             id = self.GetNewId()
  2788             id = self.GetNewId()
  2752         choices = []
  2796         choices = []
  2753         for block in self.Blocks.itervalues():
  2797         for block in self.Blocks.itervalues():
  2754             if isinstance(block, SFC_Step):
  2798             if isinstance(block, SFC_Step):
  2755                 choices.append(block.GetName())
  2799                 choices.append(block.GetName())
  2756         dialog = wx.SingleChoiceDialog(self.ParentWindow,
  2800         dialog = wx.SingleChoiceDialog(self.ParentWindow,
  2757               _("Add a new jump"), _("Please choose a target"),
  2801                                        _("Add a new jump"),
  2758               choices, wx.DEFAULT_DIALOG_STYLE|wx.OK|wx.CANCEL)
  2802                                        _("Please choose a target"),
       
  2803                                        choices,
       
  2804                                        wx.DEFAULT_DIALOG_STYLE | wx.OK | wx.CANCEL)
  2759         if dialog.ShowModal() == wx.ID_OK:
  2805         if dialog.ShowModal() == wx.ID_OK:
  2760             id = self.GetNewId()
  2806             id = self.GetNewId()
  2761             jump = SFC_Jump(self, dialog.GetStringSelection(), id)
  2807             jump = SFC_Jump(self, dialog.GetStringSelection(), id)
  2762             self.Controler.AddEditedElementJump(self.TagName, id)
  2808             self.Controler.AddEditedElementJump(self.TagName, id)
  2763             self.AddNewElement(jump, bbox, wire)
  2809             self.AddNewElement(jump, bbox, wire)
  2773             actionblock = SFC_ActionBlock(self, dialog.GetValues(), id)
  2819             actionblock = SFC_ActionBlock(self, dialog.GetValues(), id)
  2774             self.Controler.AddEditedElementActionBlock(self.TagName, id)
  2820             self.Controler.AddEditedElementActionBlock(self.TagName, id)
  2775             self.AddNewElement(actionblock, bbox, wire)
  2821             self.AddNewElement(actionblock, bbox, wire)
  2776         dialog.Destroy()
  2822         dialog.Destroy()
  2777 
  2823 
  2778 #-------------------------------------------------------------------------------
  2824     # -------------------------------------------------------------------------------
  2779 #                          Edit element content functions
  2825     #                          Edit element content functions
  2780 #-------------------------------------------------------------------------------
  2826     # -------------------------------------------------------------------------------
  2781 
  2827 
  2782     def EditBlockContent(self, block):
  2828     def EditBlockContent(self, block):
  2783         dialog = FBDBlockDialog(self.ParentWindow, self.Controler, self.TagName)
  2829         dialog = FBDBlockDialog(self.ParentWindow, self.Controler, self.TagName)
  2784         dialog.SetPreviewFont(self.GetFont())
  2830         dialog.SetPreviewFont(self.GetFont())
  2785         dialog.SetMinElementSize(block.GetSize())
  2831         dialog.SetMinElementSize(block.GetSize())
  2786         old_values = {"name" : block.GetName(),
  2832         old_values = {
  2787                       "type" : block.GetType(),
  2833             "name":             block.GetName(),
  2788                       "extension" : block.GetExtension(),
  2834             "type":             block.GetType(),
  2789                       "inputs" : block.GetInputTypes(),
  2835             "extension":        block.GetExtension(),
  2790                       "executionControl" : block.GetExecutionControl(),
  2836             "inputs":           block.GetInputTypes(),
  2791                       "executionOrder" : block.GetExecutionOrder()}
  2837             "executionControl": block.GetExecutionControl(),
       
  2838             "executionOrder":   block.GetExecutionOrder()
       
  2839         }
  2792         dialog.SetValues(old_values)
  2840         dialog.SetValues(old_values)
  2793         if dialog.ShowModal() == wx.ID_OK:
  2841         if dialog.ShowModal() == wx.ID_OK:
  2794             new_values = dialog.GetValues()
  2842             new_values = dialog.GetValues()
  2795             rect = block.GetRedrawRect(1, 1)
  2843             rect = block.GetRedrawRect(1, 1)
  2796             if "name" in new_values:
  2844             if "name" in new_values:
  2797                 block.SetName(new_values["name"])
  2845                 block.SetName(new_values["name"])
  2798             else:
  2846             else:
  2799                 block.SetName("")
  2847                 block.SetName("")
  2800             block.SetSize(*self.GetScaledSize(new_values["width"], new_values["height"]))
  2848             block.SetSize(*self.GetScaledSize(new_values["width"], new_values["height"]))
  2801             block.SetType(new_values["type"], new_values["extension"], executionControl = new_values["executionControl"])
  2849             block.SetType(new_values["type"], new_values["extension"], executionControl=new_values["executionControl"])
  2802             block.SetExecutionOrder(new_values["executionOrder"])
  2850             block.SetExecutionOrder(new_values["executionOrder"])
  2803             rect = rect.Union(block.GetRedrawRect())
  2851             rect = rect.Union(block.GetRedrawRect())
  2804             self.RefreshBlockModel(block)
  2852             self.RefreshBlockModel(block)
  2805             self.RefreshBuffer()
  2853             self.RefreshBuffer()
  2806             if old_values["executionOrder"] != new_values["executionOrder"]:
  2854             if old_values["executionOrder"] != new_values["executionOrder"]:
  2815 
  2863 
  2816     def EditVariableContent(self, variable):
  2864     def EditVariableContent(self, variable):
  2817         dialog = FBDVariableDialog(self.ParentWindow, self.Controler, self.TagName)
  2865         dialog = FBDVariableDialog(self.ParentWindow, self.Controler, self.TagName)
  2818         dialog.SetPreviewFont(self.GetFont())
  2866         dialog.SetPreviewFont(self.GetFont())
  2819         dialog.SetMinElementSize(variable.GetSize())
  2867         dialog.SetMinElementSize(variable.GetSize())
  2820         old_values = {"expression" : variable.GetName(), "class" : variable.GetType(),
  2868         old_values = {
  2821                       "executionOrder" : variable.GetExecutionOrder()}
  2869             "expression":     variable.GetName(),
       
  2870             "class":          variable.GetType(),
       
  2871             "executionOrder": variable.GetExecutionOrder()
       
  2872         }
  2822         dialog.SetValues(old_values)
  2873         dialog.SetValues(old_values)
  2823         if dialog.ShowModal() == wx.ID_OK:
  2874         if dialog.ShowModal() == wx.ID_OK:
  2824             new_values = dialog.GetValues()
  2875             new_values = dialog.GetValues()
  2825             rect = variable.GetRedrawRect(1, 1)
  2876             rect = variable.GetRedrawRect(1, 1)
  2826             variable.SetName(new_values["expression"])
  2877             variable.SetName(new_values["expression"])
  2844 
  2895 
  2845     def EditConnectionContent(self, connection):
  2896     def EditConnectionContent(self, connection):
  2846         dialog = ConnectionDialog(self.ParentWindow, self.Controler, self.TagName, True)
  2897         dialog = ConnectionDialog(self.ParentWindow, self.Controler, self.TagName, True)
  2847         dialog.SetPreviewFont(self.GetFont())
  2898         dialog.SetPreviewFont(self.GetFont())
  2848         dialog.SetMinElementSize(connection.GetSize())
  2899         dialog.SetMinElementSize(connection.GetSize())
  2849         values = {"name" : connection.GetName(), "type" : connection.GetType()}
  2900         values = {"name": connection.GetName(), "type": connection.GetType()}
  2850         dialog.SetValues(values)
  2901         dialog.SetValues(values)
  2851         result = dialog.ShowModal()
  2902         result = dialog.ShowModal()
  2852         dialog.Destroy()
  2903         dialog.Destroy()
  2853         if result in [wx.ID_OK, wx.ID_YESTOALL]:
  2904         if result in [wx.ID_OK, wx.ID_YESTOALL]:
  2854             old_type = connection.GetType()
  2905             old_type = connection.GetType()
  2876 
  2927 
  2877     def EditContactContent(self, contact):
  2928     def EditContactContent(self, contact):
  2878         dialog = LDElementDialog(self.ParentWindow, self.Controler, self.TagName, "contact")
  2929         dialog = LDElementDialog(self.ParentWindow, self.Controler, self.TagName, "contact")
  2879         dialog.SetPreviewFont(self.GetFont())
  2930         dialog.SetPreviewFont(self.GetFont())
  2880         dialog.SetMinElementSize(contact.GetSize())
  2931         dialog.SetMinElementSize(contact.GetSize())
  2881         dialog.SetValues({"variable" : contact.GetName(),
  2932         dialog.SetValues({"variable": contact.GetName(),
  2882                           "modifier" : contact.GetType()})
  2933                           "modifier": contact.GetType()})
  2883         if dialog.ShowModal() == wx.ID_OK:
  2934         if dialog.ShowModal() == wx.ID_OK:
  2884             values = dialog.GetValues()
  2935             values = dialog.GetValues()
  2885             rect = contact.GetRedrawRect(1, 1)
  2936             rect = contact.GetRedrawRect(1, 1)
  2886             contact.SetName(values["variable"])
  2937             contact.SetName(values["variable"])
  2887             contact.SetType(values["modifier"])
  2938             contact.SetType(values["modifier"])
  2896 
  2947 
  2897     def EditCoilContent(self, coil):
  2948     def EditCoilContent(self, coil):
  2898         dialog = LDElementDialog(self.ParentWindow, self.Controler, self.TagName, "coil")
  2949         dialog = LDElementDialog(self.ParentWindow, self.Controler, self.TagName, "coil")
  2899         dialog.SetPreviewFont(self.GetFont())
  2950         dialog.SetPreviewFont(self.GetFont())
  2900         dialog.SetMinElementSize(coil.GetSize())
  2951         dialog.SetMinElementSize(coil.GetSize())
  2901         dialog.SetValues({"variable" : coil.GetName(),
  2952         dialog.SetValues({"variable": coil.GetName(),
  2902                           "modifier" : coil.GetType()})
  2953                           "modifier": coil.GetType()})
  2903         if dialog.ShowModal() == wx.ID_OK:
  2954         if dialog.ShowModal() == wx.ID_OK:
  2904             values = dialog.GetValues()
  2955             values = dialog.GetValues()
  2905             rect = coil.GetRedrawRect(1, 1)
  2956             rect = coil.GetRedrawRect(1, 1)
  2906             coil.SetName(values["variable"])
  2957             coil.SetName(values["variable"])
  2907             coil.SetType(values["modifier"])
  2958             coil.SetType(values["modifier"])
  2944         dialog = SFCStepDialog(self.ParentWindow, self.Controler, self.TagName, step.GetInitial())
  2995         dialog = SFCStepDialog(self.ParentWindow, self.Controler, self.TagName, step.GetInitial())
  2945         dialog.SetPreviewFont(self.GetFont())
  2996         dialog.SetPreviewFont(self.GetFont())
  2946         dialog.SetMinElementSize(step.GetSize())
  2997         dialog.SetMinElementSize(step.GetSize())
  2947         connectors = step.GetConnectors()
  2998         connectors = step.GetConnectors()
  2948         dialog.SetValues({
  2999         dialog.SetValues({
  2949             "name" : step.GetName(),
  3000             "name": step.GetName(),
  2950             "input": len(connectors["inputs"]) > 0,
  3001             "input": len(connectors["inputs"]) > 0,
  2951             "output": len(connectors["outputs"]) > 0,
  3002             "output": len(connectors["outputs"]) > 0,
  2952             "action": step.GetActionConnector() != None})
  3003             "action": step.GetActionConnector() is not None})
  2953         if dialog.ShowModal() == wx.ID_OK:
  3004         if dialog.ShowModal() == wx.ID_OK:
  2954             values = dialog.GetValues()
  3005             values = dialog.GetValues()
  2955             rect = step.GetRedrawRect(1, 1)
  3006             rect = step.GetRedrawRect(1, 1)
  2956 
  3007 
  2957             new_name = values["name"]
  3008             new_name = values["name"]
  2964                                 block.SetTarget(new_name)
  3015                                 block.SetTarget(new_name)
  2965                                 block.RefreshModel()
  3016                                 block.RefreshModel()
  2966                                 rect = rect.Union(block.GetRedrawRect())
  3017                                 rect = rect.Union(block.GetRedrawRect())
  2967                                 block.Refresh(rect)
  3018                                 block.Refresh(rect)
  2968             step.SetName(new_name)
  3019             step.SetName(new_name)
  2969             
  3020 
  2970             if values["input"]:
  3021             if values["input"]:
  2971                 step.AddInput()
  3022                 step.AddInput()
  2972             else:
  3023             else:
  2973                 step.RemoveInput()
  3024                 step.RemoveInput()
  2974             if values["output"]:
  3025             if values["output"]:
  2989 
  3040 
  2990     def EditTransitionContent(self, transition):
  3041     def EditTransitionContent(self, transition):
  2991         dialog = SFCTransitionDialog(self.ParentWindow, self.Controler, self.TagName, self.GetDrawingMode() == FREEDRAWING_MODE)
  3042         dialog = SFCTransitionDialog(self.ParentWindow, self.Controler, self.TagName, self.GetDrawingMode() == FREEDRAWING_MODE)
  2992         dialog.SetPreviewFont(self.GetFont())
  3043         dialog.SetPreviewFont(self.GetFont())
  2993         dialog.SetMinElementSize(transition.GetSize())
  3044         dialog.SetMinElementSize(transition.GetSize())
  2994         dialog.SetValues({"type":transition.GetType(),"value":transition.GetCondition(), "priority":transition.GetPriority()})
  3045         dialog.SetValues({
       
  3046             "type":     transition.GetType(),
       
  3047             "value":    transition.GetCondition(),
       
  3048             "priority": transition.GetPriority()
       
  3049         })
  2995         if dialog.ShowModal() == wx.ID_OK:
  3050         if dialog.ShowModal() == wx.ID_OK:
  2996             values = dialog.GetValues()
  3051             values = dialog.GetValues()
  2997             rect = transition.GetRedrawRect(1, 1)
  3052             rect = transition.GetRedrawRect(1, 1)
  2998             transition.SetType(values["type"],values["value"])
  3053             transition.SetType(values["type"], values["value"])
  2999             transition.SetPriority(values["priority"])
  3054             transition.SetPriority(values["priority"])
  3000             rect = rect.Union(transition.GetRedrawRect())
  3055             rect = rect.Union(transition.GetRedrawRect())
  3001             self.RefreshTransitionModel(transition)
  3056             self.RefreshTransitionModel(transition)
  3002             self.RefreshBuffer()
  3057             self.RefreshBuffer()
  3003             self.RefreshScrollBars()
  3058             self.RefreshScrollBars()
  3009         choices = []
  3064         choices = []
  3010         for block in self.Blocks.itervalues():
  3065         for block in self.Blocks.itervalues():
  3011             if isinstance(block, SFC_Step):
  3066             if isinstance(block, SFC_Step):
  3012                 choices.append(block.GetName())
  3067                 choices.append(block.GetName())
  3013         dialog = wx.SingleChoiceDialog(self.ParentWindow,
  3068         dialog = wx.SingleChoiceDialog(self.ParentWindow,
  3014               _("Edit jump target"), _("Please choose a target"),
  3069                                        _("Edit jump target"),
  3015               choices, wx.DEFAULT_DIALOG_STYLE|wx.OK|wx.CANCEL)
  3070                                        _("Please choose a target"),
       
  3071                                        choices,
       
  3072                                        wx.DEFAULT_DIALOG_STYLE | wx.OK | wx.CANCEL)
  3016         try:
  3073         try:
  3017             indx = choices.index(jump.GetTarget())
  3074             indx = choices.index(jump.GetTarget())
  3018             dialog.SetSelection(indx)
  3075             dialog.SetSelection(indx)
  3019         except ValueError:
  3076         except ValueError:
  3020             pass
  3077             pass
  3053     def EditCommentContent(self, comment):
  3110     def EditCommentContent(self, comment):
  3054         dialog = wx.TextEntryDialog(self.ParentWindow,
  3111         dialog = wx.TextEntryDialog(self.ParentWindow,
  3055                                     _("Edit comment"),
  3112                                     _("Edit comment"),
  3056                                     _("Please enter comment text"),
  3113                                     _("Please enter comment text"),
  3057                                     comment.GetContent(),
  3114                                     comment.GetContent(),
  3058                                     wx.OK|wx.CANCEL|wx.TE_MULTILINE)
  3115                                     wx.OK | wx.CANCEL | wx.TE_MULTILINE)
  3059         width, height = comment.GetSize()
  3116         width, height = comment.GetSize()
  3060         dialogSize = wx.Size(max(width + 30, 400), max(height + 60, 200))
  3117         dialogSize = wx.Size(max(width + 30, 400), max(height + 60, 200))
  3061         dialog.SetClientSize(dialogSize)
  3118         dialog.SetClientSize(dialogSize)
  3062         if dialog.ShowModal() == wx.ID_OK:
  3119         if dialog.ShowModal() == wx.ID_OK:
  3063             value = dialog.GetValue()
  3120             value = dialog.GetValue()
  3070             self.RefreshScrollBars()
  3127             self.RefreshScrollBars()
  3071             self.RefreshVisibleElements()
  3128             self.RefreshVisibleElements()
  3072             comment.Refresh(rect)
  3129             comment.Refresh(rect)
  3073         dialog.Destroy()
  3130         dialog.Destroy()
  3074 
  3131 
  3075 #-------------------------------------------------------------------------------
  3132     # -------------------------------------------------------------------------------
  3076 #                          Model update functions
  3133     #                          Model update functions
  3077 #-------------------------------------------------------------------------------
  3134     # -------------------------------------------------------------------------------
  3078 
  3135 
  3079     def RefreshBlockModel(self, block):
  3136     def RefreshBlockModel(self, block):
  3080         blockid = block.GetId()
  3137         blockid = block.GetId()
  3081         infos = {}
  3138         infos = {}
  3082         infos["type"] = block.GetType()
  3139         infos["type"] = block.GetType()
  3219         infos["x"], infos["y"] = actionblock.GetPosition()
  3276         infos["x"], infos["y"] = actionblock.GetPosition()
  3220         infos["width"], infos["height"] = actionblock.GetSize()
  3277         infos["width"], infos["height"] = actionblock.GetSize()
  3221         infos["connector"] = actionblock.GetConnector()
  3278         infos["connector"] = actionblock.GetConnector()
  3222         self.Controler.SetEditedElementActionBlockInfos(self.TagName, actionblockid, infos)
  3279         self.Controler.SetEditedElementActionBlockInfos(self.TagName, actionblockid, infos)
  3223 
  3280 
  3224 
  3281     # -------------------------------------------------------------------------------
  3225 #-------------------------------------------------------------------------------
  3282     #                          Model delete functions
  3226 #                          Model delete functions
  3283     # -------------------------------------------------------------------------------
  3227 #-------------------------------------------------------------------------------
       
  3228 
       
  3229 
  3284 
  3230     def DeleteBlock(self, block):
  3285     def DeleteBlock(self, block):
  3231         elements = []
  3286         elements = []
  3232         for output in block.GetConnectors()["outputs"]:
  3287         for output in block.GetConnectors()["outputs"]:
  3233             for element in output.GetConnectedBlocks():
  3288             for element in output.GetConnectedBlocks():
  3370     def DeleteActionBlock(self, actionblock):
  3425     def DeleteActionBlock(self, actionblock):
  3371         actionblock.Clean()
  3426         actionblock.Clean()
  3372         self.RemoveBlock(actionblock)
  3427         self.RemoveBlock(actionblock)
  3373         self.Controler.RemoveEditedElementInstance(self.TagName, actionblock.GetId())
  3428         self.Controler.RemoveEditedElementInstance(self.TagName, actionblock.GetId())
  3374 
  3429 
  3375 
  3430     # -------------------------------------------------------------------------------
  3376 #-------------------------------------------------------------------------------
  3431     #                            Editing functions
  3377 #                            Editing functions
  3432     # -------------------------------------------------------------------------------
  3378 #-------------------------------------------------------------------------------
       
  3379 
  3433 
  3380     def Cut(self):
  3434     def Cut(self):
  3381         if not self.Debug and (self.IsBlock(self.SelectedElement) or self.IsComment(self.SelectedElement) or isinstance(self.SelectedElement, Graphic_Group)):
  3435         if not self.Debug and (self.IsBlock(self.SelectedElement) or self.IsComment(self.SelectedElement) or isinstance(self.SelectedElement, Graphic_Group)):
  3382             blocks, wires = self.SelectedElement.GetDefinition()
  3436             blocks, wires = self.SelectedElement.GetDefinition()
  3383             text = self.Controler.GetEditedElementInstancesCopy(self.TagName, blocks, wires, self.Debug)
  3437             text = self.Controler.GetEditedElementInstancesCopy(self.TagName, blocks, wires, self.Debug)
  3416                 self.RefreshBuffer()
  3470                 self.RefreshBuffer()
  3417                 self.RefreshView(selection=result)
  3471                 self.RefreshView(selection=result)
  3418                 self.RefreshVariablePanel()
  3472                 self.RefreshVariablePanel()
  3419                 self.ParentWindow.RefreshPouInstanceVariablesPanel()
  3473                 self.ParentWindow.RefreshPouInstanceVariablesPanel()
  3420             else:
  3474             else:
  3421                 message = wx.MessageDialog(self.Editor, result, "Error", wx.OK|wx.ICON_ERROR)
  3475                 message = wx.MessageDialog(self.Editor, result, "Error", wx.OK | wx.ICON_ERROR)
  3422                 message.ShowModal()
  3476                 message.ShowModal()
  3423                 message.Destroy()
  3477                 message.Destroy()
  3424 
  3478 
  3425     def CanAddElement(self, block):
  3479     def CanAddElement(self, block):
  3426         if isinstance(block, Graphic_Group):
  3480         if isinstance(block, Graphic_Group):
  3504                 self.RefreshJumpModel(block)
  3558                 self.RefreshJumpModel(block)
  3505             elif isinstance(block, SFC_ActionBlock):
  3559             elif isinstance(block, SFC_ActionBlock):
  3506                 self.Controler.AddEditedElementActionBlock(self.TagName, block.GetId())
  3560                 self.Controler.AddEditedElementActionBlock(self.TagName, block.GetId())
  3507                 self.RefreshActionBlockModel(block)
  3561                 self.RefreshActionBlockModel(block)
  3508 
  3562 
  3509 #-------------------------------------------------------------------------------
  3563     # -------------------------------------------------------------------------------
  3510 #                         Find and Replace functions
  3564     #                         Find and Replace functions
  3511 #-------------------------------------------------------------------------------
  3565     # -------------------------------------------------------------------------------
  3512 
  3566 
  3513     def Find(self, direction, search_params):
  3567     def Find(self, direction, search_params):
  3514         if self.SearchParams != search_params:
  3568         if self.SearchParams != search_params:
  3515             self.ClearHighlights(SEARCH_RESULT_HIGHLIGHT)
  3569             self.ClearHighlights(SEARCH_RESULT_HIGHLIGHT)
  3516 
  3570 
  3547         else:
  3601         else:
  3548             if self.CurrentFindHighlight is not None:
  3602             if self.CurrentFindHighlight is not None:
  3549                 self.RemoveHighlight(*self.CurrentFindHighlight)
  3603                 self.RemoveHighlight(*self.CurrentFindHighlight)
  3550             self.CurrentFindHighlight = None
  3604             self.CurrentFindHighlight = None
  3551 
  3605 
  3552 #-------------------------------------------------------------------------------
  3606     # -------------------------------------------------------------------------------
  3553 #                        Highlights showing functions
  3607     #                        Highlights showing functions
  3554 #-------------------------------------------------------------------------------
  3608     # -------------------------------------------------------------------------------
  3555 
  3609 
  3556     def OnRefreshHighlightsTimer(self, event):
  3610     def OnRefreshHighlightsTimer(self, event):
  3557         self.RefreshView()
  3611         self.RefreshView()
  3558         event.Skip()
  3612         event.Skip()
  3559 
  3613 
  3588             if infos[0] in ["comment", "io_variable", "block", "connector", "coil", "contact", "step", "transition", "jump", "action_block"]:
  3642             if infos[0] in ["comment", "io_variable", "block", "connector", "coil", "contact", "step", "transition", "jump", "action_block"]:
  3589                 block = self.FindElementById(infos[1])
  3643                 block = self.FindElementById(infos[1])
  3590                 if block is not None:
  3644                 if block is not None:
  3591                     block.AddHighlight(infos[2:], start, end, highlight_type)
  3645                     block.AddHighlight(infos[2:], start, end, highlight_type)
  3592 
  3646 
  3593 #-------------------------------------------------------------------------------
  3647     # -------------------------------------------------------------------------------
  3594 #                            Drawing functions
  3648     #                            Drawing functions
  3595 #-------------------------------------------------------------------------------
  3649     # -------------------------------------------------------------------------------
  3596 
  3650 
  3597     def OnScrollWindow(self, event):
  3651     def OnScrollWindow(self, event):
  3598         if self.Editor.HasCapture() and self.StartMousePos is not None:
  3652         if self.Editor.HasCapture() and self.StartMousePos is not None:
  3599             return
  3653             return
  3600         if wx.Platform == '__WXMSW__':
  3654         if wx.Platform == '__WXMSW__':
  3601             wx.CallAfter(self.RefreshVisibleElements)
  3655             wx.CallAfter(self.RefreshVisibleElements)
  3602             self.Editor.Freeze()
  3656             self.Editor.Freeze()
  3603             wx.CallAfter(self.Editor.Thaw)
  3657             wx.CallAfter(self.Editor.Thaw)
  3604         elif event.GetOrientation() == wx.HORIZONTAL:
  3658         elif event.GetOrientation() == wx.HORIZONTAL:
  3605             self.RefreshVisibleElements(xp = event.GetPosition())
  3659             self.RefreshVisibleElements(xp=event.GetPosition())
  3606         else:
  3660         else:
  3607             self.RefreshVisibleElements(yp = event.GetPosition())
  3661             self.RefreshVisibleElements(yp=event.GetPosition())
  3608 
  3662 
  3609         # Handle scroll in debug to fully redraw area and ensuring
  3663         # Handle scroll in debug to fully redraw area and ensuring
  3610         # instance path is fully draw without flickering
  3664         # instance path is fully draw without flickering
  3611         if self.Debug and wx.Platform != '__WXMSW__':
  3665         if self.Debug and wx.Platform != '__WXMSW__':
  3612             x, y = self.GetViewStart()
  3666             x, y = self.GetViewStart()
  3625         if self.StartMousePos is None or self.StartScreenPos is None:
  3679         if self.StartMousePos is None or self.StartScreenPos is None:
  3626             rotation = event.GetWheelRotation() / event.GetWheelDelta()
  3680             rotation = event.GetWheelRotation() / event.GetWheelDelta()
  3627             if event.ShiftDown():
  3681             if event.ShiftDown():
  3628                 x, y = self.GetViewStart()
  3682                 x, y = self.GetViewStart()
  3629                 xp = max(0, min(x - rotation * 3, self.Editor.GetVirtualSize()[0] / self.Editor.GetScrollPixelsPerUnit()[0]))
  3683                 xp = max(0, min(x - rotation * 3, self.Editor.GetVirtualSize()[0] / self.Editor.GetScrollPixelsPerUnit()[0]))
  3630                 self.RefreshVisibleElements(xp = xp)
  3684                 self.RefreshVisibleElements(xp=xp)
  3631                 self.Scroll(xp, y)
  3685                 self.Scroll(xp, y)
  3632             elif event.ControlDown():
  3686             elif event.ControlDown():
  3633                 dc = self.GetLogicalDC()
  3687                 dc = self.GetLogicalDC()
  3634                 self.SetScale(self.CurrentScale + rotation, mouse_event = event)
  3688                 self.SetScale(self.CurrentScale + rotation, mouse_event=event)
  3635                 self.ParentWindow.RefreshDisplayMenu()
  3689                 self.ParentWindow.RefreshDisplayMenu()
  3636             else:
  3690             else:
  3637                 x, y = self.GetViewStart()
  3691                 x, y = self.GetViewStart()
  3638                 yp = max(0, min(y - rotation * 3, self.Editor.GetVirtualSize()[1] / self.Editor.GetScrollPixelsPerUnit()[1]))
  3692                 yp = max(0, min(y - rotation * 3, self.Editor.GetVirtualSize()[1] / self.Editor.GetScrollPixelsPerUnit()[1]))
  3639                 self.RefreshVisibleElements(yp = yp)
  3693                 self.RefreshVisibleElements(yp=yp)
  3640                 self.Scroll(x, yp)
  3694                 self.Scroll(x, yp)
  3641 
  3695 
  3642     def OnMoveWindow(self, event):
  3696     def OnMoveWindow(self, event):
  3643         client_size = self.GetClientSize()
  3697         client_size = self.GetClientSize()
  3644         if self.LastClientSize != client_size:
  3698         if self.LastClientSize != client_size:
  3645             self.LastClientSize = client_size
  3699             self.LastClientSize = client_size
  3646             self.RefreshScrollBars()
  3700             self.RefreshScrollBars()
  3647             self.RefreshVisibleElements()
  3701             self.RefreshVisibleElements()
  3648         event.Skip()
  3702         event.Skip()
  3649 
  3703 
  3650     def DoDrawing(self, dc, printing = False):
  3704     def DoDrawing(self, dc, printing=False):
  3651         if printing:
  3705         if printing:
  3652             if getattr(dc, "printing", False):
  3706             if getattr(dc, "printing", False):
  3653                 font = wx.Font(self.GetFont().GetPointSize(), wx.MODERN, wx.NORMAL, wx.NORMAL)
  3707                 font = wx.Font(self.GetFont().GetPointSize(), wx.MODERN, wx.NORMAL, wx.NORMAL)
  3654                 dc.SetFont(font)
  3708                 dc.SetFont(font)
  3655             else:
  3709             else:
  3682         for comment in self.Comments.itervalues():
  3736         for comment in self.Comments.itervalues():
  3683             if comment != self.SelectedElement and (comment.IsVisible() or printing):
  3737             if comment != self.SelectedElement and (comment.IsVisible() or printing):
  3684                 comment.Draw(dc)
  3738                 comment.Draw(dc)
  3685         for wire in self.Wires.iterkeys():
  3739         for wire in self.Wires.iterkeys():
  3686             if wire != self.SelectedElement and (wire.IsVisible() or printing):
  3740             if wire != self.SelectedElement and (wire.IsVisible() or printing):
  3687                  if not self.Debug or wire.GetValue() != True:
  3741                 if not self.Debug or not wire.GetValue():
  3688                     wire.Draw(dc)
  3742                     wire.Draw(dc)
  3689         if self.Debug:
  3743         if self.Debug:
  3690             for wire in self.Wires.iterkeys():
  3744             for wire in self.Wires.iterkeys():
  3691                 if wire != self.SelectedElement and (wire.IsVisible() or printing) and wire.GetValue() == True:
  3745                 if wire != self.SelectedElement and (wire.IsVisible() or printing) and wire.GetValue():
  3692                     wire.Draw(dc)
  3746                     wire.Draw(dc)
  3693         for block in self.Blocks.itervalues():
  3747         for block in self.Blocks.itervalues():
  3694             if block != self.SelectedElement and (block.IsVisible() or printing):
  3748             if block != self.SelectedElement and (block.IsVisible() or printing):
  3695                 block.Draw(dc)
  3749                 block.Draw(dc)
  3696 
  3750 
  3709         self.DoDrawing(dc)
  3763         self.DoDrawing(dc)
  3710         wx.BufferedPaintDC(self.Editor, dc.GetAsBitmap())
  3764         wx.BufferedPaintDC(self.Editor, dc.GetAsBitmap())
  3711         if self.Debug:
  3765         if self.Debug:
  3712             DebugViewer.RefreshNewData(self)
  3766             DebugViewer.RefreshNewData(self)
  3713         event.Skip()
  3767         event.Skip()
  3714 
       
  3715