Rewrite LDPowerRailDialog
authorLaurent Bessard
Wed, 12 Jun 2013 09:36:59 +0200
changeset 1249 b956c924cbbd
parent 1248 2f08985625c0
child 1250 7e6de17c687a
Rewrite LDPowerRailDialog
dialogs/BlockPreviewDialog.py
dialogs/ConnectionDialog.py
dialogs/LDPowerRailDialog.py
editors/Viewer.py
--- a/dialogs/BlockPreviewDialog.py	Wed Jun 12 00:20:05 2013 +0200
+++ b/dialogs/BlockPreviewDialog.py	Wed Jun 12 09:36:59 2013 +0200
@@ -98,6 +98,18 @@
         """
         self.MinElementSize = size
     
+    def GetMinElementSize(self):
+        """
+        Get minimal graphic element size
+        @return: Tuple containing minimal size (width, height) or None if no
+        element defined
+        May be overridden by inherited classes
+        """
+        if self.Element is None:
+            return None
+        
+        return self.Element.GetMinSize()
+    
     def SetPreviewFont(self, font):
         """
         Set font of Preview panel
@@ -205,7 +217,7 @@
         
         # Calculate block size according to graphic element min size due to its
         # parameters and graphic element min size defined
-        min_width, min_height = self.Element.GetMinSize()
+        min_width, min_height = self.GetMinElementSize()
         width = max(self.MinElementSize[0], min_width)
         height = max(self.MinElementSize[1], min_height)
         self.Element.SetSize(width, height)
--- a/dialogs/ConnectionDialog.py	Wed Jun 12 00:20:05 2013 +0200
+++ b/dialogs/ConnectionDialog.py	Wed Jun 12 09:36:59 2013 +0200
@@ -32,6 +32,11 @@
 #                       Set Connection Parameters Dialog
 #-------------------------------------------------------------------------------
 
+"""
+Class that implements a dialog for defining parameters of a connection graphic
+element
+"""
+
 class ConnectionDialog(BlockPreviewDialog):
     
     def __init__(self, parent, controller, tagname, apply_button=False):
@@ -123,6 +128,15 @@
         # Connector radio button is default control having keyboard focus
         self.TypeRadioButtons[CONNECTOR].SetFocus()
     
+    def GetConnectionType(self):
+        """
+        Return type selected for connection
+        @return: Type selected (CONNECTOR or CONTINUATION)
+        """
+        return (CONNECTOR
+                if self.TypeRadioButtons[CONNECTOR].GetValue()
+                else CONTINUATION)
+    
     def SetValues(self, values):
         """
         Set default connection parameters
@@ -148,9 +162,7 @@
         @return: {parameter_name: parameter_value,...}
         """
         values = {
-            "type": (CONNECTOR 
-                     if self.TypeRadioButtons[CONNECTOR].GetValue()
-                     else CONTINUATION),
+            "type": self.GetConnectionType(),
             "name": self.ConnectionName.GetValue()}
         values["width"], values["height"] = self.Element.GetSize()
         return values
@@ -221,9 +233,7 @@
         """
         # Set graphic element displayed, creating a FBD connection element
         self.Element = FBD_Connector(self.Preview, 
-                (CONNECTOR
-                 if self.TypeRadioButtons[CONNECTOR].GetValue()
-                 else CONTINUATION),
+                self.GetConnectionType(),
                 self.ConnectionName.GetValue())
         
         # Call BlockPreviewDialog function
--- a/dialogs/LDPowerRailDialog.py	Wed Jun 12 00:20:05 2013 +0200
+++ b/dialogs/LDPowerRailDialog.py	Wed Jun 12 09:36:59 2013 +0200
@@ -23,126 +23,165 @@
 
 import wx
 
-from graphics import *
+from graphics.GraphicCommons import LEFTRAIL, RIGHTRAIL, LD_LINE_SIZE
+from graphics.LD_Objects import LD_PowerRail
+from BlockPreviewDialog import BlockPreviewDialog
 
 #-------------------------------------------------------------------------------
-#                      Edit Ladder Power Rail Properties Dialog
+#                    Set Ladder Power Rail Parameters Dialog
 #-------------------------------------------------------------------------------
 
-class LDPowerRailDialog(wx.Dialog):
+"""
+Class that implements a dialog for defining parameters of a power rail graphic
+element
+"""
+
+class LDPowerRailDialog(BlockPreviewDialog):
     
-    def __init__(self, parent, controller, type = LEFTRAIL, number = 1):
-        wx.Dialog.__init__(self, parent, size=wx.Size(350, 260),
-              title=_('Power Rail Properties'))
+    def __init__(self, parent, controller, tagname):
+        """
+        Constructor
+        @param parent: Parent wx.Window of dialog for modal
+        @param controller: Reference to project controller
+        @param tagname: Tagname of project POU edited
+        """
+        BlockPreviewDialog.__init__(self, parent, controller, tagname,
+              size=wx.Size(350, 260), title=_('Power Rail Properties'))
         
+        # Create dialog main sizer
         main_sizer = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=10)
         main_sizer.AddGrowableCol(0)
         main_sizer.AddGrowableRow(0)
         
+        # Create a sizer for dividing power rail parameters in two columns
         column_sizer = wx.BoxSizer(wx.HORIZONTAL)
         main_sizer.AddSizer(column_sizer, border=20, 
               flag=wx.GROW|wx.TOP|wx.LEFT|wx.RIGHT)
         
+        # Create a sizer for left column
         left_gridsizer = wx.FlexGridSizer(cols=1, hgap=0, rows=5, vgap=5)
         left_gridsizer.AddGrowableCol(0)
         column_sizer.AddSizer(left_gridsizer, 1, border=5, 
               flag=wx.GROW|wx.RIGHT)
         
+        # Create label for connection type
         type_label = wx.StaticText(self, label=_('Type:'))
         left_gridsizer.AddWindow(type_label, flag=wx.GROW)
         
-        self.LeftPowerRail = wx.RadioButton(self,
-              label=_('Left PowerRail'), style=wx.RB_GROUP)
-        self.LeftPowerRail.SetValue(True)
-        self.Bind(wx.EVT_RADIOBUTTON, self.OnTypeChanged, self.LeftPowerRail)
-        left_gridsizer.AddWindow(self.LeftPowerRail, flag=wx.GROW)
+        # Create radio buttons for selecting power rail type
+        self.TypeRadioButtons = {}
+        first = True
+        for type, label in [(LEFTRAIL, _('Left PowerRail')),
+                            (RIGHTRAIL, _('Right PowerRail'))]:
+            radio_button = wx.RadioButton(self, label=label, 
+                  style=(wx.RB_GROUP if first else 0))
+            radio_button.SetValue(first)
+            self.Bind(wx.EVT_RADIOBUTTON, self.OnTypeChanged, radio_button)
+            left_gridsizer.AddWindow(radio_button, flag=wx.GROW)
+            self.TypeRadioButtons[type] = radio_button
+            first = False
         
-        self.RightPowerRail = wx.RadioButton(self, label=_('Right PowerRail'))
-        self.Bind(wx.EVT_RADIOBUTTON, self.OnTypeChanged, self.RightPowerRail)
-        left_gridsizer.AddWindow(self.RightPowerRail, flag=wx.GROW)
-        
+        # Create label for power rail pin number
         pin_number_label = wx.StaticText(self, label=_('Pin number:'))
         left_gridsizer.AddWindow(pin_number_label, flag=wx.GROW)
         
+        # Create spin control for defining power rail pin number
         self.PinNumber = wx.SpinCtrl(self, min=1, max=50,
               style=wx.SP_ARROW_KEYS)
         self.Bind(wx.EVT_SPINCTRL, self.OnPinNumberChanged, self.PinNumber)
         left_gridsizer.AddWindow(self.PinNumber, flag=wx.GROW)
         
+        # Create a sizer for right column
         right_gridsizer = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=5)
         right_gridsizer.AddGrowableCol(0)
         right_gridsizer.AddGrowableRow(1)
         column_sizer.AddSizer(right_gridsizer, 1, border=5, 
               flag=wx.GROW|wx.LEFT)
         
-        preview_label = wx.StaticText(self, label=_('Preview:'))
-        right_gridsizer.AddWindow(preview_label, flag=wx.GROW)
-        
-        self.Preview = wx.Panel(self,
-              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", controller.IsOfType)
-        self.Preview.Bind(wx.EVT_PAINT, self.OnPaint)
+        # Add preview panel and associated label to sizers
+        right_gridsizer.AddWindow(self.PreviewLabel, flag=wx.GROW)
         right_gridsizer.AddWindow(self.Preview, flag=wx.GROW)
         
-        button_sizer = self.CreateButtonSizer(wx.OK|wx.CANCEL|wx.CENTRE)
-        main_sizer.AddSizer(button_sizer, border=20, 
+        # Add buttons sizer to sizers
+        main_sizer.AddSizer(self.ButtonSizer, border=20, 
               flag=wx.ALIGN_RIGHT|wx.BOTTOM|wx.LEFT|wx.RIGHT)
         
         self.SetSizer(main_sizer)
         
-        self.Type = type
-        if type == LEFTRAIL:
-            self.LeftPowerRail.SetValue(True)
-        elif type == RIGHTRAIL:
-            self.RightPowerRail.SetValue(True)
-        self.PinNumber.SetValue(number)
-        
-        self.PowerRailMinSize = (0, 0)
-        self.PowerRail = None
-        
-        self.LeftPowerRail.SetFocus()
-
-    def SetPreviewFont(self, font):
-        self.Preview.SetFont(font)
-
-    def SetMinSize(self, size):
-        self.PowerRailMinSize = size
-        self.RefreshPreview()    
+        # Left Power Rail radio button is default control having keyboard focus
+        self.TypeRadioButtons[LEFTRAIL].SetFocus()
+    
+    def GetMinElementSize(self):
+        """
+        Get minimal graphic element size
+        @return: Tuple containing minimal size (width, height) or None if no
+        element defined
+        May be overridden by inherited classes
+        """
+        return (2, LD_LINE_SIZE * self.PinNumber.GetValue())
+    
+    def GetPowerRailType(self):
+        """
+        Return type selected for power rail
+        @return: Type selected (LEFTRAIL or RIGHTRAIL)
+        """
+        return (LEFTRAIL
+                if self.TypeRadioButtons[LEFTRAIL].GetValue()
+                else RIGHTRAIL)
+    
+    def SetValues(self, values):
+        """
+        Set default power rail parameters
+        @param values: Power rail parameters values
+        """
+        # For each parameters defined, set corresponding control value
+        for name, value in values.items():
+            
+            # Parameter is power rail type
+            if name == "type":
+                self.TypeRadioButtons[value].SetValue(True)
+            
+            # Parameter is power rail pin number
+            elif name == "pin_number":
+                self.PinNumber.SetValue(value)
 
     def GetValues(self):
-        values = {}
-        values["type"] = self.Type
-        values["number"] = self.PinNumber.GetValue()
-        values["width"], values["height"] = self.PowerRail.GetSize()
+        """
+        Return power rail parameters defined in dialog
+        @return: {parameter_name: parameter_value,...}
+        """
+        values = {
+            "type": self.GetPowerRailType(),
+            "pin_number": self.PinNumber.GetValue()}
+        values["width"], values["height"] = self.Element.GetSize()
         return values
 
     def OnTypeChanged(self, event):
-        if self.LeftPowerRail.GetValue():
-            self.Type = LEFTRAIL
-        elif self.RightPowerRail.GetValue():
-            self.Type = RIGHTRAIL
+        """
+        Called when power rail type changed
+        @param event: wx.RadioButtonEvent
+        """
         self.RefreshPreview()
         event.Skip()
 
     def OnPinNumberChanged(self, event):
+        """
+        Called when power rail pin number value changed
+        @param event: wx.SpinEvent
+        """
         self.RefreshPreview()
         event.Skip()
 
     def RefreshPreview(self):
-        dc = wx.ClientDC(self.Preview)
-        dc.SetFont(self.Preview.GetFont())
-        dc.Clear()
-        self.PowerRail = LD_PowerRail(self.Preview, self.Type, connectors = self.PinNumber.GetValue())
-        min_width, min_height = 2, LD_LINE_SIZE * self.PinNumber.GetValue()
-        width, height = max(min_width, self.PowerRailMinSize[0]), max(min_height, self.PowerRailMinSize[1])
-        self.PowerRail.SetSize(width, height)
-        clientsize = self.Preview.GetClientSize()
-        self.PowerRail.SetPosition((clientsize.width - width) / 2, (clientsize.height - height) / 2)
-        self.PowerRail.Draw(dc)
-
-    def OnPaint(self, event):
-        self.RefreshPreview()
-        event.Skip()
+        """
+        Refresh preview panel of graphic element
+        Override BlockPreviewDialog function
+        """
+        
+        # Set graphic element displayed, creating a power rail element
+        self.Element = LD_PowerRail(self.Preview, 
+                self.GetPowerRailType(), 
+                connectors = self.PinNumber.GetValue())
+        
+        # Call BlockPreviewDialog function
+        BlockPreviewDialog.RefreshPreview(self)
--- a/editors/Viewer.py	Wed Jun 12 00:20:05 2013 +0200
+++ b/editors/Viewer.py	Wed Jun 12 09:36:59 2013 +0200
@@ -2321,13 +2321,13 @@
         dialog.Destroy()
 
     def AddNewPowerRail(self, bbox):
-        dialog = LDPowerRailDialog(self.ParentWindow, self.Controler)
+        dialog = LDPowerRailDialog(self.ParentWindow, self.Controler, self.TagName)
         dialog.SetPreviewFont(self.GetFont())
-        dialog.SetMinSize((bbox.width, bbox.height))
+        dialog.SetMinElementSize((bbox.width, bbox.height))
         if dialog.ShowModal() == wx.ID_OK:
             id = self.GetNewId()
             values = dialog.GetValues()
-            powerrail = LD_PowerRail(self, values["type"], id, values["number"])
+            powerrail = LD_PowerRail(self, values["type"], id, values["pin_number"])
             powerrail.SetPosition(bbox.x, bbox.y)
             powerrail.SetSize(*self.GetScaledSize(values["width"], values["height"]))
             self.AddBlock(powerrail)
@@ -2599,23 +2599,21 @@
         dialog.Destroy()
 
     def EditPowerRailContent(self, powerrail):
-        connectors = powerrail.GetConnectors()
-        type = powerrail.GetType()
-        if type == LEFTRAIL:
-            pin_number = len(connectors["outputs"])
-        else:
-            pin_number = len(connectors["inputs"])
-        dialog = LDPowerRailDialog(self.ParentWindow, self.Controler, type, pin_number)
+        dialog = LDPowerRailDialog(self.ParentWindow, self.Controler, self.TagName)
         dialog.SetPreviewFont(self.GetFont())
-        dialog.SetMinSize(powerrail.GetSize())
+        dialog.SetMinElementSize(powerrail.GetSize())
+        powerrail_type = powerrail.GetType()
+        dialog.SetValues({
+            "type": powerrail.GetType(),
+            "pin_number": len(powerrail.GetConnectors()[
+                    ("outputs" if powerrail_type == LEFTRAIL else "inputs")])})
         if dialog.ShowModal() == wx.ID_OK:
-            old_type = powerrail.GetType()
             values = dialog.GetValues()
             rect = powerrail.GetRedrawRect(1, 1)
-            powerrail.SetType(values["type"], values["number"])
+            powerrail.SetType(values["type"], values["pin_number"])
             powerrail.SetSize(*self.GetScaledSize(values["width"], values["height"]))
             rect = rect.Union(powerrail.GetRedrawRect())
-            if old_type != values["type"]:
+            if powerrail_type != values["type"]:
                 id = powerrail.GetId()
                 self.Controler.RemoveEditedElementInstance(self.TagName, id)
                 self.Controler.AddEditedElementPowerRail(self.TagName, id, values["type"])