[GRASS-SVN] r43652 - grass/trunk/gui/wxpython/gui_modules

svn_grass at osgeo.org svn_grass at osgeo.org
Thu Sep 23 11:01:28 EDT 2010


Author: martinl
Date: 2010-09-23 15:01:28 +0000 (Thu, 23 Sep 2010)
New Revision: 43652

Modified:
   grass/trunk/gui/wxpython/gui_modules/gmodeler.py
Log:
wxGUI/modeler: progress in if-else statements handling
(merge r43651 from devbr6)


Modified: grass/trunk/gui/wxpython/gui_modules/gmodeler.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/gmodeler.py	2010-09-23 14:59:54 UTC (rev 43651)
+++ grass/trunk/gui/wxpython/gui_modules/gmodeler.py	2010-09-23 15:01:28 UTC (rev 43652)
@@ -324,8 +324,6 @@
                                            height = condition['size'][1],
                                            text = condition['text'],
                                            id = condition['id'])
-            # for action in conditionItem.GetItems():
-            #    action.SetCondition(conditionItem)
             self.AddItem(conditionItem)
 
         # define loops & if/else items
@@ -341,6 +339,20 @@
             for action in loopItem.GetItems():
                 action.SetBlock(loopItem)
         
+        for condition in gxmXml.conditions:
+            conditionItem = self.GetItem(condition['id'])
+            for b in condition['items'].keys():
+                alist = list()
+                for aId in condition['items'][b]:
+                    action = self.GetItem(aId)
+                    alist.append(action)
+                conditionItem.SetItems(alist, branch = b)
+            
+            items = conditionItem.GetItems()
+            for b in items.keys():
+                for action in items[b]:
+                    action.SetBlock(conditionItem)
+        
     def AddItem(self, newItem):
         """!Add item to the list"""
         iId = newItem.GetId()
@@ -1449,8 +1461,8 @@
         self.SetStatusText(layer.GetLog(), 0)
         
     def AddLine(self, rel):
-        """!Add connection
-
+        """!Add connection between model objects
+        
         @param rel relation
         """
         fromShape = rel.GetFrom()
@@ -1467,9 +1479,10 @@
                 rel.InsertLineControlPoint(point = wx.RealPoint(x, y))
         
         self._addEvent(rel)
-        if isinstance(fromShape, ModelCondition): ### ???
-            fromShape = toShape
-        fromShape.AddLine(rel, toShape)
+        try:
+            fromShape.AddLine(rel, toShape)
+        except TypeError:
+            pass # bug when connecting ModelCondition and ModelLoop - to be fixed
         
         self.canvas.diagram.AddShape(rel)
         rel.Show(True)
@@ -1521,7 +1534,7 @@
             item.Show(True)
             
             # connect items in the condition
-            # self.DefineCondition(item)
+            self.DefineCondition(item)
         
         # load variables
         self.variablePanel.Update()
@@ -1573,14 +1586,14 @@
             self.canvas.GetDiagram().RemoveShape(rel)
         loop.Clear()
         
-        for item in loop.GetItems():
+        for item in items:
             rel = ModelRelation(parent, item)
             dx = item.GetX() - parent.GetX()
             dy = item.GetY() - parent.GetY()
             loop.AddRelation(rel)
             if dx != 0:
                 rel.SetControlPoints(((parent.GetX(), parent.GetY() + dy / 2),
-                                     (parent.GetX() + dx, parent.GetY() + dy / 2)))
+                                      (parent.GetX() + dx, parent.GetY() + dy / 2)))
             self.AddLine(rel)
             parent = item
         
@@ -1604,7 +1617,28 @@
                                                         loop.GetY()))
         
         self.canvas.Refresh()
+
+    def DefineCondition(self, condition):
+        """!Define if-else statement with given list of items"""
+        parent = condition
+        items = condition.GetItems()
+        if not items['if'] and not items['else']:
+            return
         
+        # remove defined relations first
+        for rel in condition.GetRelations():
+            self.canvas.GetDiagram().RemoveShape(rel)
+        condition.Clear()
+
+        for branch in items.keys():
+            for item in items[branch]:
+                rel = ModelRelation(parent, item)
+                condition.AddRelation(rel)
+                self.AddLine(rel)
+                parent = item
+        
+        self.canvas.Refresh()
+        
 class ModelCanvas(ogl.ShapeCanvas):
     """!Canvas where model is drawn"""
     def __init__(self, parent):
@@ -1654,7 +1688,7 @@
         self.rels = list() # list of ModelRelations
         
         self.isEnabled = True
-        self.inBlock   = None
+        self.inBlock   = list() # list of related loops/conditions
         
     def __del__(self):
         pass
@@ -1699,31 +1733,42 @@
     def Update(self):
         pass
 
-    def SetBlock(self, item = None):
-        """!Register loop
+    def SetBlock(self, item):
+        """!Add object to the block (loop/condition)
 
-        @param item reference to ModelObject which defines block of ModelObject (None to unset)
+        @param item reference to ModelLoop or ModelCondition which
+        defines loops/condition
         """
-        self.inBlock = item
+        if item not in self.inBlock:
+            self.inBlock.append(item)
+        
+    def UnSetBlock(self, item):
+        """!Remove object from the block (loop/consition)
 
+        @param item reference to ModelLoop or ModelCondition which
+        defines loops/codition
+        """
+        if item in self.inBlock:
+            self.inBlock.remove(item)
+        
     def GetBlock(self):
-        """!Get related ModelObject which defines block
+        """!Get list of related ModelObject(s) which defines block
+        (loop/condition)
 
-        @return ModelLoop/ModelCondition instance
-        @return None if no block defined for this item
+        @return list of ModelObjects
         """
         return self.inBlock
     
     def GetBlockId(self):
-        """!Get id of ModelObject which defines block
+        """!Get list of related ids which defines block
 
-        @return item id 
-        @return None if action is not in the block
+        @return list of ids
         """
-        if self.inBlock:
-            return self.inBlock.GetId()
+        ret = list()
+        for mo in self.inBlock:
+            ret.append(mo.GetId())
         
-        return None
+        return ret
     
 class ModelAction(ModelObject, ogl.RectangleShape):
     """!Action class (GRASS module)"""
@@ -2169,6 +2214,7 @@
             elif drel['to'] is None:
                 drel['to'] = shape
                 rel = ModelRelation(drel['from'], drel['to'])
+                drel['from'].AddRelation(rel)
                 self.frame.AddLine(rel)
                 del self.frame.defineRelation
         
@@ -2223,7 +2269,7 @@
                 ids = dlg.GetItems()
                 for aId in ids['unchecked']:
                     action = self.frame.GetModel().GetItem(aId)
-                    action.SetBlock()
+                    action.UnSetBlock(shape)
                 for aId in ids['checked']:
                     action = self.frame.GetModel().GetItem(aId)
                     action.SetBlock(shape)
@@ -2240,6 +2286,20 @@
             dlg.CentreOnParent()
             if dlg.ShowModal() == wx.ID_OK:
                 shape.SetText(dlg.GetCondition())
+                ids = dlg.GetItems()
+                for b in ids.keys():
+                    alist = list()
+                    for aId in ids[b]['unchecked']:
+                        action = self.frame.GetModel().GetItem(aId)
+                        action.UnSetBlock(shape)
+                    for aId in ids[b]['checked']:
+                        action = self.frame.GetModel().GetItem(aId)
+                        action.SetBlock(shape)
+                        if action:
+                            alist.append(action)
+                    shape.SetItems(alist, branch = b)
+                self.frame.DefineCondition(shape)
+            self.frame.GetCanvas().Refresh()
             
             dlg.Destroy()
                    
@@ -2257,10 +2317,15 @@
         shape = self.GetShape()
         if isinstance(shape, ModelLoop):
             self.frame.DefineLoop(shape)
-        loop = shape.GetBlock()
-        if loop:
-            self.frame.DefineLoop(loop)
+        elif isinstance(shape, ModelCondition):
+            self.frame.DefineCondition(shape)
         
+        for mo in shape.GetBlock():
+            if isinstance(mo, ModelLoop):
+                self.frame.DefineLoop(mo)
+            elif isinstance(mo, ModelCondition):
+                self.frame.DefineCondition(mo)
+        
     def OnEndSize(self, x, y):
         """!Resize shape"""
         self.frame.ModelChanged()
@@ -2789,7 +2854,7 @@
             pos, size = self._getDim(node)
             text = self._filterValue(self._getNodeText(node, 'condition')).strip()
             aid = list()
-            for anode in node.findall('loop-item'):
+            for anode in node.findall('item'):
                 try:
                     aid.append(int(anode.text))
                 except ValueError:
@@ -2806,8 +2871,18 @@
         for node in self.root.findall('if-else'):
             pos, size = self._getDim(node)
             text = self._filterValue(self._getNodeText(node, 'condition')).strip()
-            aid = list()
-
+            aid = { 'if'   : list(),
+                    'else' : list() }
+            for b in aid.keys():
+                bnode = node.find(b)
+                if bnode is None:
+                    continue
+                for anode in bnode.findall('item'):
+                    try:
+                        aid[b].append(int(anode.text))
+                    except ValueError:
+                        pass
+            
             self.conditions.append({ 'pos'     : pos,
                                      'size'    : size,
                                      'text'    : text,
@@ -3015,7 +3090,7 @@
             self.fd.write('%s<condition>%s</condition>\n' %
                           (' ' * self.indent, self._filterValue(text)))
         for item in loop.GetItems():
-            self.fd.write('%s<loop-item>%d</loop-item>\n' %
+            self.fd.write('%s<item>%d</item>\n' %
                           (' ' * self.indent, item.GetId()))
         self.indent -= 4
         self.fd.write('%s</loop>\n' % (' ' * self.indent))
@@ -3031,9 +3106,18 @@
         if text:
             self.fd.write('%s<condition>%s</condition>\n' %
                           (' ' * self.indent, self._filterValue(text)))
-        for item in condition.GetItems():
-            self.fd.write('%s<condition-item>%d</condition-item>\n' %
-                          (' ' * self.indent, item.GetId()))
+        items = condition.GetItems()
+        for b in items.keys():
+            if len(items[b]) < 1:
+                continue
+            self.fd.write('%s<%s>\n' % (' ' * self.indent, b))
+            self.indent += 4
+            for item in items[b]:
+                self.fd.write('%s<item>%d</item>\n' %
+                              (' ' * self.indent, item.GetId()))
+            self.indent -= 4
+            self.fd.write('%s</%s>\n' % (' ' * self.indent, b))
+        
         self.indent -= 4
         self.fd.write('%s</if-else>\n' % (' ' * self.indent))
         
@@ -3854,10 +3938,6 @@
         """!Set loop id"""
         self.id = id
 
-    def SetItems(self, items):
-        """!Set items (id)"""
-        self.items = items
-
     def SetText(self, cond):
         """!Set loop text (condition)"""
         self.text = cond
@@ -3910,10 +3990,6 @@
         """!Do layout (virtual method)"""
         pass
     
-    def GetItems(self):
-        """!Get list of selected actions"""
-        return self.itemList.GetItems()
-    
     def GetCondition(self):
         """!Get loop condition"""
         return self.condText.GetValue()
@@ -3940,10 +4016,14 @@
                 self.AddText('(' + str(self.id) + ') ' + text)
             else:
                 self.AddText('(' + str(self.id) + ')')
-
+        
     def GetName(self):
         """!Get name"""
         return _("loop")
+    
+    def SetItems(self, items):
+        """!Set items (id)"""
+        self.items = items
 
 class ModelLoopDialog(ModelItemDialog):
     """!Loop properties dialog"""
@@ -3987,6 +4067,10 @@
         sizer.Fit(self.panel)
         
         self.Layout()
+        
+    def GetItems(self):
+        """!Get list of selected actions"""
+        return self.itemList.GetItems()
 
 class ItemPanel(wx.Panel):
     def __init__(self, parent, id = wx.ID_ANY,
@@ -4055,7 +4139,10 @@
                                        action.GetName(),
                                        action.GetLog()]
                 aId = action.GetBlockId()
-                if aId not in self.excludeId:
+                if len(aId) > 0:
+                    if aId[0] not in self.excludeId:
+                        aId = None
+                else:
                     aId = None
                 checked.append(aId)
             else:
@@ -4240,8 +4327,9 @@
                 break
         
 class ModelCondition(ModelItem, ogl.PolygonShape):
-    def __init__(self, parent, x, y, id = -1, width = None, height = None, text = '', items = []):
-        """!Defines a condition"""
+    def __init__(self, parent, x, y, id = -1, width = None, height = None, text = '',
+                 items = { 'if' : [], 'else' : [] }):
+        """!Defines a if-else condition"""
         ModelItem.__init__(self, parent, x, y, id, width, height, text, items)
         
         if not width:
@@ -4266,7 +4354,6 @@
             self.SetX(x)
             self.SetY(y)
             self.SetPen(wx.BLACK_PEN)
-            
             if text:
                 self.AddText('(' + str(self.id) + ') ' + text)
             else:
@@ -4284,6 +4371,15 @@
         """!Get object height"""
         return self.height
 
+    def SetItems(self, items, branch = 'if'):
+        """!Set items (id)
+
+        @param items list of items
+        @param branch 'if' / 'else'
+        """
+        if branch in ['if', 'else']:
+            self.items[branch] = items
+        
 class ModelConditionDialog(ModelItemDialog):
     """!Condition properties dialog"""
     def __init__(self, parent, shape, id = wx.ID_ANY, title = _("If-else properties"),
@@ -4362,6 +4458,11 @@
         if aId in self.itemListIf.GetItems()['checked']:
             self.itemListIf.CheckItemById(aId, False)
         
+    def GetItems(self):
+        """!Get items"""
+        return { 'if'   : self.itemListIf.GetItems(),
+                 'else' : self.itemListElse.GetItems() }
+        
 def main():
     app = wx.PySimpleApp()
     wx.InitAllImageHandlers()



More information about the grass-commit mailing list