dialogs/FBDVariableDialog.py
author laurent
Fri, 09 Dec 2011 11:26:10 +0100
changeset 600 7db729686416
parent 577 9dbb79722fbc
child 714 131ea7f237b9
permissions -rw-r--r--
Making variable panel not editable when showing variables of debugging block
#!/usr/bin/env python
# -*- coding: utf-8 -*-

#This file is part of PLCOpenEditor, a library implementing an IEC 61131-3 editor
#based on the plcopen standard. 
#
#Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD
#
#See COPYING file for copyrights details.
#
#This library is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public
#License as published by the Free Software Foundation; either
#version 2.1 of the License, or (at your option) any later version.
#
#This library is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#General Public License for more details.
#
#You should have received a copy of the GNU General Public
#License along with this library; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import wx

from graphics import *

#-------------------------------------------------------------------------------
#                          Create New Variable Dialog
#-------------------------------------------------------------------------------

[ID_FBDVARIABLEDIALOG, ID_FBDVARIABLEDIALOGSPACER, 
 ID_FBDVARIABLEDIALOGNAME, ID_FBDVARIABLEDIALOGCLASS, 
 ID_FBDVARIABLEDIALOGPREVIEW, ID_FBDVARIABLEDIALOGEXPRESSION,
 ID_FBDVARIABLEDIALOGEXECUTIONORDER, ID_FBDVARIABLEDIALOGSTATICTEXT1, 
 ID_FBDVARIABLEDIALOGSTATICTEXT2, ID_FBDVARIABLEDIALOGSTATICTEXT3, 
 ID_FBDVARIABLEDIALOGSTATICTEXT4, ID_FBDVARIABLEDIALOGSTATICTEXT5
] = [wx.NewId() for _init_ctrls in range(12)]

VARIABLE_CLASSES_DICT = {INPUT : _("Input"),
                         INOUT : _("InOut"),
                         OUTPUT : _("Output")}
VARIABLE_CLASSES_DICT_REVERSE = dict([(value, key) for key, value in VARIABLE_CLASSES_DICT.iteritems()])

class FBDVariableDialog(wx.Dialog):
    
    if wx.VERSION < (2, 6, 0):
        def Bind(self, event, function, id = None):
            if id is not None:
                event(self, id, function)
            else:
                event(self, function)
    
    def _init_coll_flexGridSizer1_Items(self, parent):
        parent.AddSizer(self.MainSizer, 0, border=20, flag=wx.GROW|wx.TOP|wx.LEFT|wx.RIGHT)
        parent.AddSizer(self.ButtonSizer, 0, border=20, flag=wx.ALIGN_RIGHT|wx.BOTTOM|wx.LEFT|wx.RIGHT)
        
    def _init_coll_flexGridSizer1_Growables(self, parent):
        parent.AddGrowableCol(0)
        parent.AddGrowableRow(0)
    
    def _init_coll_MainSizer_Items(self, parent):
        parent.AddSizer(self.TopSizer, 0, border=0, flag=wx.GROW)
        parent.AddWindow(self.staticText5, 0, border=0, flag=wx.GROW)
        parent.AddWindow(self.Preview, 0, border=0, flag=wx.GROW)
        
    def _init_coll_MainSizer_Growables(self, parent):
        parent.AddGrowableCol(0)
        parent.AddGrowableRow(2)
    
    def _init_coll_TopSizer_Items(self, parent):
        parent.AddSizer(self.LeftGridSizer, 1, border=5, flag=wx.GROW|wx.RIGHT)
        parent.AddSizer(self.RightGridSizer, 1, border=5, flag=wx.GROW|wx.LEFT)
    
    def _init_coll_LeftGridSizer_Items(self, parent):
        parent.AddWindow(self.staticText1, 0, border=0, flag=wx.GROW)
        parent.AddWindow(self.Class, 0, border=0, flag=wx.GROW)
        parent.AddWindow(self.staticText2, 0, border=0, flag=wx.GROW)
        parent.AddWindow(self.Expression, 0, border=0, flag=wx.GROW)
        parent.AddWindow(self.staticText3, 0, border=0, flag=wx.GROW)
        parent.AddWindow(self.ExecutionOrder, 0, border=0, flag=wx.GROW)
        parent.AddWindow(self.Spacer, 0, border=0, flag=wx.GROW)
    
    def _init_coll_LeftGridSizer_Growables(self, parent):
        parent.AddGrowableCol(0)
        parent.AddGrowableRow(2)
            
    def _init_coll_RightGridSizer_Items(self, parent):
        parent.AddWindow(self.staticText4, 0, border=0, flag=wx.GROW)
        parent.AddWindow(self.VariableName, 0, border=0, flag=wx.GROW)
        
    def _init_coll_RightGridSizer_Growables(self, parent):
        parent.AddGrowableCol(0)
        parent.AddGrowableRow(1)
        
    def _init_sizers(self):
        self.flexGridSizer1 = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=10)
        self.MainSizer = wx.FlexGridSizer(cols=1, hgap=0, rows=3, vgap=5)
        self.TopSizer = wx.BoxSizer(wx.HORIZONTAL)
        self.LeftGridSizer = wx.FlexGridSizer(cols=1, hgap=0, rows=7, vgap=5)
        self.RightGridSizer = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=5)

        self._init_coll_flexGridSizer1_Items(self.flexGridSizer1)
        self._init_coll_flexGridSizer1_Growables(self.flexGridSizer1)
        self._init_coll_MainSizer_Items(self.MainSizer)
        self._init_coll_MainSizer_Growables(self.MainSizer)
        self._init_coll_TopSizer_Items(self.TopSizer)
        self._init_coll_LeftGridSizer_Items(self.LeftGridSizer)
        self._init_coll_LeftGridSizer_Growables(self.LeftGridSizer)
        self._init_coll_RightGridSizer_Items(self.RightGridSizer)
        self._init_coll_RightGridSizer_Growables(self.RightGridSizer)
        
        self.SetSizer(self.flexGridSizer1)

    def _init_ctrls(self, prnt, ctrler):
        wx.Dialog.__init__(self, id=ID_FBDVARIABLEDIALOG,
              name='FBDVariableDialog', parent=prnt,
              size=wx.Size(400, 380), style=wx.DEFAULT_DIALOG_STYLE,
              title=_('Variable Properties'))
        self.SetClientSize(wx.Size(400, 380))

        self.staticText1 = wx.StaticText(id=ID_FBDVARIABLEDIALOGSTATICTEXT1,
              label=_('Class:'), name='staticText1', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)

        self.staticText2 = wx.StaticText(id=ID_FBDVARIABLEDIALOGSTATICTEXT2,
              label=_('Expression:'), name='staticText2', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)

        self.staticText3 = wx.StaticText(id=ID_FBDVARIABLEDIALOGSTATICTEXT3,
              label=_('Execution Order:'), name='staticText3', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)

        self.staticText4 = wx.StaticText(id=ID_FBDVARIABLEDIALOGSTATICTEXT4,
              label=_('Name:'), name='staticText4', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)

        self.staticText5 = wx.StaticText(id=ID_FBDVARIABLEDIALOGSTATICTEXT5,
              label=_('Preview:'), name='staticText5', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(0, 17), style=0)

        self.Class = wx.ComboBox(id=ID_FBDVARIABLEDIALOGCLASS,
              name='Class', parent=self, pos=wx.Point(0, 0),
              size=wx.Size(0, 28), style=wx.CB_READONLY)
        self.Bind(wx.EVT_COMBOBOX, self.OnClassChanged, id=ID_FBDVARIABLEDIALOGCLASS)
        
        self.VariableName = wx.ListBox(id=ID_FBDVARIABLEDIALOGNAME,
              name='Name', parent=self, pos=wx.Point(0, 0),
              size=wx.Size(0, 90), style=wx.LB_SINGLE|wx.LB_SORT)
        self.Bind(wx.EVT_LISTBOX, self.OnNameChanged, id=ID_FBDVARIABLEDIALOGNAME)

        self.Expression = wx.TextCtrl(id=ID_FBDVARIABLEDIALOGEXPRESSION,
              name='Expression', parent=self, pos=wx.Point(0, 0),
              size=wx.Size(0, 24), style=0)
        self.Bind(wx.EVT_TEXT, self.OnExpressionChanged, id=ID_FBDVARIABLEDIALOGEXPRESSION)

        self.ExecutionOrder = wx.SpinCtrl(id=ID_FBDVARIABLEDIALOGEXECUTIONORDER,
              name='ExecutionOrder', parent=self, pos=wx.Point(0, 0),
              size=wx.Size(0, 24), style=wx.SP_ARROW_KEYS, min=0)
        self.Bind(wx.EVT_SPINCTRL, self.OnExecutionOrderChanged, id=ID_FBDVARIABLEDIALOGEXECUTIONORDER)

        self.Spacer = wx.Panel(id=ID_FBDVARIABLEDIALOGSPACER,
              name='Spacer', parent=self, pos=wx.Point(0, 0),
              size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL)

        self.Preview = wx.Panel(id=ID_FBDVARIABLEDIALOGPREVIEW,
              name='Preview', parent=self, pos=wx.Point(0, 0),
              size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL|wx.SIMPLE_BORDER)
        self.Preview.SetBackgroundColour(wx.Colour(255,255,255))
        setattr(self.Preview, "GetDrawingMode", lambda:FREEDRAWING_MODE)
        setattr(self.Preview, "GetScaling", lambda:None)
        setattr(self.Preview, "IsOfType", ctrler.IsOfType)

        self.ButtonSizer = self.CreateButtonSizer(wx.OK|wx.CANCEL|wx.CENTRE)
        if wx.VERSION >= (2, 5, 0):
            self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.ButtonSizer.GetAffirmativeButton().GetId())
            self.Preview.Bind(wx.EVT_PAINT, self.OnPaint)
        else:
            self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.ButtonSizer.GetChildren()[0].GetSizer().GetChildren()[0].GetWindow().GetId())
            wx.EVT_PAINT(self.Preview, self.OnPaint)
        
        self._init_sizers()

    def __init__(self, parent, controler, transition = ""):
        self._init_ctrls(parent, controler)
        self.Transition = transition
        self.Variable = None
        self.VarList = []
        self.MinVariableSize = None
        
        for choice in VARIABLE_CLASSES_DICT.itervalues():
            self.Class.Append(choice)
        self.Class.SetStringSelection(VARIABLE_CLASSES_DICT[INPUT])

        self.RefreshNameList()
        self.Class.SetFocus()

    def SetPreviewFont(self, font):
        self.Preview.SetFont(font)

    def RefreshNameList(self):
        selected = self.VariableName.GetStringSelection()
        var_class = VARIABLE_CLASSES_DICT_REVERSE[self.Class.GetStringSelection()]
        self.VariableName.Clear()
        self.VariableName.Append("")
        for name, var_type, value_type in self.VarList:
            if var_type != "Input" or var_class == INPUT:
                self.VariableName.Append(name)
        if selected != "" and self.VariableName.FindString(selected) != wx.NOT_FOUND:
            self.VariableName.SetStringSelection(selected)
            self.Expression.Enable(False)
        else:
            self.VariableName.SetStringSelection("")
            #self.Expression.Enable(var_class == INPUT)
        self.VariableName.Enable(self.VariableName.GetCount() > 0)
            
    def SetMinVariableSize(self, size):
        self.MinVariableSize = size

    def SetVariables(self, vars):
        self.VarList = vars
        self.RefreshNameList()

    def SetValues(self, values):
        value_type = values.get("type", None)
        value_name = values.get("name", None)
        if value_type:
            self.Class.SetStringSelection(VARIABLE_CLASSES_DICT[value_type])
            self.RefreshNameList()
        if value_name:
            if self.VariableName.FindString(value_name) != wx.NOT_FOUND:
                self.VariableName.SetStringSelection(value_name)
                self.Expression.Enable(False)
            else:
                self.Expression.SetValue(value_name)
                self.VariableName.Enable(False)
        if "executionOrder" in values:
            self.ExecutionOrder.SetValue(values["executionOrder"])
        self.RefreshPreview()
        
    def GetValues(self):
        values = {}
        values["type"] = VARIABLE_CLASSES_DICT_REVERSE[self.Class.GetStringSelection()]
        expression = self.Expression.GetValue()
        if self.Expression.IsEnabled() and expression != "":
            values["name"] = expression
        else:
            values["name"] = self.VariableName.GetStringSelection()
        values["value_type"] = None
        for var_name, var_type, value_type in self.VarList:
            if var_name == values["name"]:
                values["value_type"] = value_type
        values["width"], values["height"] = self.Variable.GetSize()
        values["executionOrder"] = self.ExecutionOrder.GetValue()
        return values

    def OnOK(self, event):
        expression = self.Expression.GetValue()
        if self.Expression.IsEnabled():
            value = expression
        else:
            value = self.VariableName.GetStringSelection()
        if value == "":
            message = wx.MessageDialog(self, _("At least a variable or an expression must be selected!"), _("Error"), wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif value.upper() in IEC_KEYWORDS:
            message = wx.MessageDialog(self, _("\"%s\" is a keyword. It can't be used!")%value, _("Error"), wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        else:
            self.EndModal(wx.ID_OK)

    def OnClassChanged(self, event):
        self.RefreshNameList()
        self.RefreshPreview()
        event.Skip()

    def OnNameChanged(self, event):
        if self.VariableName.GetStringSelection() != "":
            self.Expression.Enable(False)
        elif VARIABLE_CLASSES_DICT_REVERSE[self.Class.GetStringSelection()] == INPUT:
            self.Expression.Enable(True)
        self.RefreshPreview()
        event.Skip()
    
    def OnExpressionChanged(self, event):
        if self.Expression.GetValue() != "":
            self.VariableName.Enable(False)
        else:
            self.VariableName.Enable(True)
        self.RefreshPreview()
        event.Skip()
    
    def OnExecutionOrderChanged(self, event):
        self.RefreshPreview()
        event.Skip()
    
    def RefreshPreview(self):
        dc = wx.ClientDC(self.Preview)
        dc.SetFont(self.Preview.GetFont())
        dc.Clear()
        expression = self.Expression.GetValue()
        if self.Expression.IsEnabled() and expression != "":
            name = expression
        else:
            name = self.VariableName.GetStringSelection()
        type = ""
        for var_name, var_type, value_type in self.VarList:
            if var_name == name:
                type = value_type
        classtype = VARIABLE_CLASSES_DICT_REVERSE[self.Class.GetStringSelection()]
        self.Variable = FBD_Variable(self.Preview, classtype, name, type, executionOrder = self.ExecutionOrder.GetValue())
        width, height = self.MinVariableSize
        min_width, min_height = self.Variable.GetMinSize()
        width, height = max(min_width, width), max(min_height, height)
        self.Variable.SetSize(width, height)
        clientsize = self.Preview.GetClientSize()
        x = (clientsize.width - width) / 2
        y = (clientsize.height - height) / 2
        self.Variable.SetPosition(x, y)
        self.Variable.Draw(dc)

    def OnPaint(self, event):
        self.RefreshPreview()
        event.Skip()