Make tags children of nodes
[sface.git] / sface / screens / mainscreen.py
index 53e263a..4792179 100644 (file)
@@ -4,7 +4,6 @@ from PyQt4.QtCore import *
 from PyQt4.QtGui import *
 
 from sfa.util.rspecHelper import RSpec
-from sface.sfahelper import *
 from sface.config import config
 from sface.sfiprocess import SfiProcess
 from sface.screens.sfascreen import SfaScreen
@@ -16,6 +15,18 @@ node_status = { "in": "Already Selected",
                 "add": "To be Added",
                 "remove": "To be Removed"}
 
+tag_status = { "in": "Already Set",
+                "out": "Not Set",
+                "add": "To be Added",
+                "remove": "To be Removed"}
+
+def itemType(index):
+    if index.parent().parent().isValid():
+        return "tag"
+    else:
+        return "node"
+
+
 class NodeView(QTreeView):
     def __init__(self, parent):
         QTreeView.__init__(self, parent)
@@ -34,20 +45,36 @@ class NodeView(QTreeView):
         model = index.model()
         status_index = model.index(index.row(), 2, index.parent())
         status_data = status_index.data().toString()
-        hostname_index = model.index(index.row(), 1, index.parent())
-        hostname_data = hostname_index.data().toString()
-
-        if status_data == node_status['in']:
-            model.setData(status_index, QString(node_status['remove']))
-        elif status_data == node_status['out']:
-            model.setData(status_index, QString(node_status['add']))
-        elif status_data in (node_status['add'], node_status['remove']):
-            if hostname_data in already_in_nodes: model.setData(status_index, QString(node_status['in']))
+        node_index = model.index(index.row(), 1, index.parent())
+        node_data = node_index.data().toString()
+
+        if itemType(node_index) == "tag":
+            if status_data == tag_status['in']:
+                model.setData(status_index, QString(tag_status['remove']))
+            elif status_data == tag_status['add']:
+                model.setData(status_index, QString(tag_status['out']))
+            elif status_data == tag_status['remove']:
+                model.setData(status_index, QString(tag_status['in']))
             else: model.setData(status_index, QString(node_status['out']))
-
-        model.emit(SIGNAL("dataChanged(QModelIndex, QModelIndex)"), hostname_index, hostname_index)
-                
+        else:
+            # This is a hostname
+            if status_data == node_status['in']:
+                model.setData(status_index, QString(node_status['remove']))
+            elif status_data == node_status['out']:
+                model.setData(status_index, QString(node_status['add']))
+            elif status_data in (node_status['add'], node_status['remove']):
+                if node_data in already_in_nodes: model.setData(status_index, QString(node_status['in']))
+                else: model.setData(status_index, QString(node_status['out']))
+
+        model.emit(SIGNAL("dataChanged(QModelIndex, QModelIndex)"), node_index, node_index)
+
+    def currentChanged(self, current, previous):
+        model = current.model()
+        node_index = model.index(current.row(), 1, current.parent())
+        node_data = node_index.data().toString()
+        self.emit(SIGNAL('hostnameClicked(QString)'), node_data)
         
+                
 
 class NodeNameDelegate(QStyledItemDelegate):
     def __init__(self, parent):
@@ -55,50 +82,89 @@ class NodeNameDelegate(QStyledItemDelegate):
 
     def paint(self, painter, option, index):
         model = index.model()
-        data = "%s" % index.data().toString()
         status_index = model.index(index.row(), 2, index.parent())
         status_data = status_index.data().toString()
 
-        if status_data not in (node_status['in'], node_status['remove'], node_status['add']):
-            # default view
-            QStyledItemDelegate.paint(self, painter, option, index)
-            return
-
         fm = QFontMetrics(option.font)
         rect = option.rect
-        rect.setWidth(fm.width(QString(data)) + 8)
-        rect.setHeight(rect.height() - 2)
-        rect.setX(rect.x() + 4)
-        x, y, h, w = rect.x(), rect.y(), rect.height(), rect.width() 
-
-        path = QPainterPath()
-        path.addRoundedRect(x, y, w, h, 4, 4)
-
-        painter.save()
-        painter.setRenderHint(QPainter.Antialiasing)
-        painter.drawRoundedRect(rect, 4, 4)
-
-        if status_data == node_status['in']: # already in the slice
-            painter.fillPath(path, QColor.fromRgb(0, 250, 0))
-            painter.setPen(QColor.fromRgb(0, 0, 0))
-            painter.drawText(option.rect, 0, QString(data))
-
-        elif status_data == node_status['add']: # newly added to the slice
-            painter.fillPath(path, QColor.fromRgb(0, 250, 0))
-            painter.setPen(QColor.fromRgb(0, 0, 0))
-            painter.drawText(option.rect, 0, QString(data))
-            painter.drawRect(x + w + 10, y + 3, 10, 10)
-            painter.fillRect(x + w + 10, y + 3, 10, 10, QColor.fromRgb(0, 250, 0))
-
-        elif status_data == node_status['remove']: # removed from the slice
-            painter.fillPath(path, QColor.fromRgb(250, 0, 0))
-            painter.setPen(QColor.fromRgb(0, 0, 0))
-            painter.drawText(option.rect, 0, QString(data))
-            painter.drawRect(x + w + 10, y + 3, 10, 10)
-            painter.fillRect(x + w + 10, y + 3, 10, 10, QColor.fromRgb(250, 0, 0))
+
+        if itemType(index) == "node":
+            data = "%s" % index.data().toString()
+            #if status_data not in (node_status['in'], node_status['remove'], node_status['add']):
+            # default view
+            #    QStyledItemDelegate.paint(self, painter, option, index)
+            #    return
+
+            rect.setHeight(rect.height() - 2)
+            rect.setWidth(fm.width(QString(data)) + 6)
+            rect.setX(rect.x() + 5)
+            rect.setY(rect.y() - 1)
+            x, y, h, w = rect.x(), rect.y(), rect.height(), rect.width()
+
+            path = QPainterPath()
+            path.addRoundedRect(x - 1, y + 1, w, h, 4, 4)
+
+            painter.save()
+            painter.setRenderHint(QPainter.Antialiasing)
+
+            if status_data == node_status['in']: # already in the slice
+                painter.fillPath(path, QColor("cyan"))
+                painter.setPen(QColor.fromRgb(0, 0, 0))
+                painter.drawText(option.rect, 0, QString(data))
+
+            elif status_data == node_status['add']: # newly added to the slice
+                painter.fillPath(path, QColor.fromRgb(0, 250, 0))
+                painter.setPen(QColor.fromRgb(0, 0, 0))
+                painter.drawText(option.rect, 0, QString(data))
+
+            elif status_data == node_status['remove']: # removed from the slice
+                painter.fillPath(path, QColor.fromRgb(250, 0, 0))
+                painter.setPen(QColor.fromRgb(0, 0, 0))
+                painter.drawText(option.rect, 0, QString(data))
+
+            else:
+                painter.setPen(QColor.fromRgb(0, 0, 0))
+                painter.drawText(option.rect, 0, QString(data))
+
+        else:
+            indent = 16
+            tag = index.data().toStringList()
+            data = "%s: %s" % (tag[0], tag[1])
+            rect.setHeight(rect.height() - 2)
+            rect.setWidth(fm.width(QString(data)) + 6 + indent)
+            rect.setX(rect.x() + 4 + indent)
+            rect.setY(rect.y() - 1)
+
+            x, y, h, w = rect.x(), rect.y(), rect.height(), rect.width()
+
+            path = QPainterPath()
+            path.addRoundedRect(x - 1, y + 1, w, h, 4, 4)
+
+            painter.save()
+            painter.setRenderHint(QPainter.Antialiasing)
+
+            if status_data == tag_status['in']: # already in the slice
+                painter.fillPath(path, QColor("cyan"))
+                painter.setPen(QColor.fromRgb(0, 0, 0))
+                painter.drawText(option.rect, 0, QString(data))
+
+            elif status_data == tag_status['add']: # newly added to the slice
+                painter.fillPath(path, QColor.fromRgb(0, 250, 0))
+                painter.setPen(QColor.fromRgb(0, 0, 0))
+                painter.drawText(option.rect, 0, QString(data))
+
+            elif status_data == tag_status['remove']: # removed from the slice
+                painter.fillPath(path, QColor.fromRgb(250, 0, 0))
+                painter.setPen(QColor.fromRgb(0, 0, 0))
+                painter.drawText(option.rect, 0, QString(data))
+
+            else:
+                painter.setPen(QColor.fromRgb(0, 0, 0))
+                painter.drawText(option.rect, 0, QString(data))
 
         painter.restore()
 
+
 class TreeItem:
     def __init__(self, data, parent=None):
         self.parentItem = parent
@@ -251,6 +317,13 @@ class NodeModel(QAbstractItemModel):
         item = self.getItem(index)
         return item.data(index.column())
 
+    def nodestatus(self, index):
+        if not index.isValid():
+            return QVariant()
+
+        item = self.getItem(index)
+        return item.nodestatus(index.column())
+
     def flags(self, index):
         if not index.isValid():
             return 0
@@ -267,23 +340,23 @@ class NodeModel(QAbstractItemModel):
         return ret
 
 
-
 class SliceWidget(QWidget):
     def __init__(self, parent):
         QWidget.__init__(self, parent)
 
         self.network_names = []
-        self.process = None
+        self.process = SfiProcess(self)
 
-        slicename = QLabel ("Slice : %s"%(config.getSlice() or "None"),self)
-        slicename.setScaledContents(False)
+        self.slicename = QLabel("", self)
+        self.updateSliceName()
+        self.slicename.setScaledContents(False)
         searchlabel = QLabel ("Search: ", self)
         searchlabel.setScaledContents(False)
         searchbox = QLineEdit(self)
         searchbox.setAttribute(Qt.WA_MacShowFocusRect, 0)
 
         toplayout = QHBoxLayout()
-        toplayout.addWidget(slicename, 0, Qt.AlignLeft)
+        toplayout.addWidget(self.slicename, 0, Qt.AlignLeft)
         toplayout.addStretch()
         toplayout.addWidget(searchlabel, 0, Qt.AlignRight)
         toplayout.addWidget(searchbox, 0, Qt.AlignRight)
@@ -314,9 +387,36 @@ class SliceWidget(QWidget):
         self.connect(refresh, SIGNAL('clicked()'), self.refresh)
         self.connect(submit, SIGNAL('clicked()'), self.submit)
         self.connect(searchbox, SIGNAL('textChanged(QString)'), self.filter)
+        self.connect(self.nodeView, SIGNAL('hostnameClicked(QString)'),
+                     self.nodeSelectionChanged)
 
         self.updateView()
 
+    def submitFinished(self):
+        self.setStatus("<font color='green'>Slice data submitted.</font>")
+        QTimer.singleShot(1000, self.refresh)
+
+    def refreshFinished(self):
+        self.setStatus("<font color='green'>Slice data updated.</font>", timeout=5000)
+        self.updateView()
+        self.parent().signalAll("rspecUpdated")
+
+    def readSliceRSpec(self):
+        rspec_file = config.getSliceRSpecFile()
+        if os.path.exists(rspec_file):
+            xml = open(rspec_file).read()
+            return RSpec(xml)
+        return None
+
+    def setStatus(self, msg, timeout=None):
+        self.parent().setStatus(msg, timeout)
+
+    def checkRunningProcess(self):
+        if self.process.isRunning():
+            self.setStatus("<font color='red'>There is already a process running. Please wait.</font>")
+            return True
+        return False
+
     def filter(self, filter_string):
         # for hierarchical models QSortFilterProxyModel applies the
         # sort recursively. if the parent doesn't match the criteria
@@ -327,13 +427,10 @@ class SliceWidget(QWidget):
         self.filterModel.setFilterRegExp(QRegExp('|'.join(filters)))
 
     def submit(self):
-        xml = self.readSliceRSpec()
-        rspec = RSpec(xml)
-
-        if self.process:
-            self.parent().setStatus("<font color='red'>There is already a process running. Please wait.</font>", 
-                                    timeout=None)
+        if self.checkRunningProcess():
             return
+
+        rspec = self.readSliceRSpec()
         
         no_change = True
         all_child = self.nodeModel.rootItem.allChildItems()
@@ -349,47 +446,31 @@ class SliceWidget(QWidget):
                 rspec.remove_sliver(hostname)
                 no_change = False
 
-            
-        self.process = SfiProcess()
-        outfile = self.process.applyRSpec(rspec)
-        self.parent().setStatus("Sending slice data (RSpec). This may take some time...", timeout=None)
-        
-        self.connect(self.process, SIGNAL('finished()'), self.refreshFinished)
-        self.connect(self.process, SIGNAL('finished()'), self.refresh)
+        if no_change:
+            self.setStatus("<font color=red>No change in slice data. Not submitting!</font>", timeout=3000)
+            return
 
-    def submitFinished(self):
-        del self.process
-        self.process = None
-        self.parent().setStatus("<font color='green'>Slice data submitted.</font>", timeout=None)
+        self.disconnect(self.process, SIGNAL('finished()'), self.refreshFinished)
+        self.connect(self.process, SIGNAL('finished()'), self.submitFinished)
 
-    def readSliceRSpec(self):
-        rspec_file = config.getSliceRSpecFile()
-        if os.path.exists(rspec_file):
-            xml = open(rspec_file).read()
-            return xml
-        return None
+        self.process.applyRSpec(rspec)
+        self.setStatus("Sending slice data (RSpec). This will take some time...")
+        
 
     def refresh(self):
         if not config.getSlice():
-            self.parent().setStatus("<font color='red'>Slice not set yet!</font>", timeout=None)
+            self.setStatus("<font color='red'>Slice not set yet!</font>")
             return
 
-        if self.process:
-            self.parent().setStatus("<font color='red'>There is already a process running. Please wait.</font>", 
-                                    timeout=None)
+        if self.process.isRunning():
+            self.setStatus("<font color='red'>There is already a process running. Please wait.</font>")
             return
 
-        self.process = SfiProcess()
-        outfile = self.process.getRSpecFromSM()
-        self.parent().setStatus("Updating slice data. This may take some time...", timeout=None)
-        
+        self.disconnect(self.process, SIGNAL('finished()'), self.submitFinished)
         self.connect(self.process, SIGNAL('finished()'), self.refreshFinished)
 
-    def refreshFinished(self):
-        del self.process
-        self.process = None
-        self.parent().setStatus("<font color='green'>Slice data updated.</font>", timeout=5000)
-        self.updateView()
+        self.process.getRSpecFromSM()
+        self.setStatus("Updating slice data. This will take some time...")
 
     def updateView(self):
         global already_in_nodes
@@ -397,27 +478,41 @@ class SliceWidget(QWidget):
         self.network_names = []
         self.nodeModel.clear()
         
-        rspec_string = self.readSliceRSpec()
-        if not rspec_string:
+        rspec = self.readSliceRSpec()
+        if not rspec:
             return None
 
-        networks = rspec_get_networks(rspec_string)
+        networks = rspec.get_network_list()
         for network in networks:
             self.network_names.append(network)
-            networkItem = TreeItem([QString(network), QString(""), QString("")], self.nodeModel.rootItem)
-
-            all_nodes = rspec_get_nodes_from_network(rspec_string, network)
-            sliver_nodes = rspec_get_sliver_nodes_from_network(rspec_string, network)
+            data = [QString(network), QString(""), QString("")]
+            #taglist = QStringList()
+            #attrs = rspec.get_default_sliver_attributes(network)
+            #for (name, value) in attrs:
+            #    taglist.append(QString("%s/%s" % (name, value)))
+            #    taglist.append(QString("in"))
+            #data.append(taglist)
+            networkItem = TreeItem(data, self.nodeModel.rootItem)
+            all_nodes = rspec.get_node_list(network)
+            sliver_nodes = rspec.get_sliver_list(network)
             available_nodes = filter(lambda x:x not in sliver_nodes, all_nodes)
 
             already_in_nodes += sliver_nodes
 
             for node in sliver_nodes:
-                nodeItem = TreeItem([QString(""), QString("%s" % node), QString(node_status['in'])], networkItem)
+                data = [QString(""), QString(node), QString(node_status['in'])]
+                nodeItem = TreeItem(data, networkItem)
                 networkItem.appendChild(nodeItem)
 
+                attrs = rspec.get_sliver_attributes(node, network)
+                for (name, value) in attrs:
+                    tagstring = QStringList([name, value])
+                    data = [QString(""), tagstring, QString(tag_status['in'])]
+                    tagItem = TreeItem(data, nodeItem)
+                    nodeItem.appendChild(tagItem)
+
             for node in available_nodes:
-                nodeItem = TreeItem([QString(""), QString(node), QString(node_status['out'])], networkItem)
+                nodeItem = TreeItem([QString(""), QString(node), QString(node_status['out']), QString("")], networkItem)
                 networkItem.appendChild(nodeItem)
 
             self.nodeModel.rootItem.appendChild(networkItem)
@@ -431,6 +526,11 @@ class SliceWidget(QWidget):
         self.nodeView.expandAll()
         self.nodeView.resizeColumnToContents(1)
 
+    def updateSliceName(self):
+        self.slicename.setText("Slice : %s" % (config.getSlice() or "None"))
+
+    def nodeSelectionChanged(self, hostname):
+        self.parent().nodeSelectionChanged(hostname)
 
 class MainScreen(SfaScreen):
     def __init__(self, parent):
@@ -438,3 +538,14 @@ class MainScreen(SfaScreen):
 
         slice = SliceWidget(self)
         self.init(slice, "Main Window", "OneLab Federation GUI")
+
+    def rspecUpdated(self):
+        self.mainwin.rspecWindow.updateView()
+        
+    def configurationChanged(self):
+        self.widget.updateSliceName()
+        self.widget.updateView()
+        self.mainwin.rspecWindow.updateView()
+
+    def nodeSelectionChanged(self, hostname):
+        self.mainwin.nodeSelectionChanged(hostname)