colorize using the select column
[sface.git] / sface / screens / mainscreen.py
index f552896..ae18c9d 100644 (file)
 
+import os
 from PyQt4.QtCore import *
 from PyQt4.QtGui import *
 
+from sfa.util.rspecHelper import RSpec
 from sface.sfahelper import *
-from sface.sficonfig import config
+from sface.config import config
+from sface.sfiprocess import SfiProcess
 from sface.screens.sfascreen import SfaScreen
 
+class NodeView(QTreeView):
+    def __init__(self, parent):
+        QTreeView.__init__(self, parent)
+
+        self.setAnimated(True)
+        self.setItemsExpandable(True)
+        self.setRootIsDecorated(True)
+        self.setAlternatingRowColors(True)
+        self.setAttribute(Qt.WA_MacShowFocusRect, 0)
+        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
+
+class SelectDelegate(QStyledItemDelegate):
+    pass
+
+class NodeNameDelegate(QStyledItemDelegate):
+    def __init__(self, parent):
+        QStyledItemDelegate.__init__(self)
+
+    def paint(self, painter, option, index):
+        data = "%s" % index.data().toString()
+        model = index.model()
+        select_index = model.index(index.row(), 2, index.parent())
+        select_data = select_index.data().toString()
+#         if select_data == "false":
+#             print select_data
+#             model.setData(index, QString("*%s" % data), Qt.EditRole)
+#             model.setData(select_index, QString("true"), Qt.EditRole)
+
+
+        if select_data == "true": # already in the sliver
+            fm = QFontMetrics(option.font)
+            rect = option.rect
+            rect.setWidth(fm.width(QString(data)))
+            rect.setHeight(rect.height() - 2)
+            rect.setX(rect.x() + 1)
+            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)
+            painter.fillPath(path, QColor.fromRgb(0, 250, 0))
+            painter.setPen(QColor.fromRgb(0, 0, 0))
+            painter.drawText(option.rect, 0, QString(data))
+            painter.restore()
+        else: # others, fall back to default view
+            QStyledItemDelegate.paint(self, painter, option, index)
+
+class TreeItem:
+    def __init__(self, data, parent=None):
+        self.parentItem = parent
+        self.itemData = data
+        self.childItems = []
+
+    def clear(self):
+        for child in self.childItems:
+            child.clear()
+            del child
+        del self.childItems
+        self.childItems = []
+
+    def appendChild(self, child):
+        self.childItems.append(child)
+
+    def child(self, row):
+        return self.childItems[row]
+    
+    def childCount(self):
+        return len(self.childItems)
+
+    def childNumber(self):
+        if self.parentItem:
+            return self.parentItem.childItems.index(self)
+        return 0
+
+    def columnCount(self):
+        return len(self.itemData)
+
+    def data(self, column):
+        return self.itemData[column]
+
+    def insertChildren(self, position, count, columns):
+        if position < 0 or position > len(self.childItems):
+            return False
+        
+        for row in range(count):
+            data = self.data(columns)
+            item = TreeItem(data, self)
+            self.childItems.insert(position, item)
+
+        return True
+
+    def insertColumns(self, position, columns):
+        if position < 0 or position > len(self.itemData):
+            return False
+
+        for column in range(columns):
+            self.itemData.insert(position, QVariant())
+        
+        for child in self.childItems:
+            child.insertColumns(position, columns)
+        
+        return True
+
+    def setData(self, column, value):
+        if column < 0 or column >= len(self.itemData):
+            return False
+
+        self.itemData[column] = value
+        return True
+
+    def row(self):
+        if (self.parentItem):
+            try:
+                return self.parentItem.childItems.index(self)
+            except ValueError:
+                return 0
+        return 0
+    
+    def parent(self):
+        return self.parentItem
+
+
+
+class NodeModel(QAbstractItemModel):
+    def __init__(self, parent):
+        QAbstractItemModel.__init__(self, parent)
+        self.__initRoot()
+
+    def clear(self):
+        self.rootItem.clear()
+        self.__initRoot()
+
+    def __initRoot(self):
+        self.rootItem = TreeItem([QString("Testbed"), QString("Hostname"), QString("Selected")])
+
+
+    def getItem(self, index):
+        if index.isValid():
+            item = index.internalPointer()
+            if item: return item
+        return self.rootItem
+
+    def headerData(self, section, orientation, role):
+        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
+            return self.rootItem.data(section)
+        return QVariant()
+
+    def index(self, row, column, parent):
+        if not self.hasIndex(row, column, parent):
+            return QModelIndex()
+
+        parentItem = self.getItem(parent)
+            
+        childItem = parentItem.child(row)
+        if childItem:
+            return self.createIndex(row, column, childItem)
+        else:
+            return QModelIndex()
+
+    def insertColumns(self, position, columns, parent):
+        self.beginInsertColumns(parent, position, position + columns -1)
+        ret = self.rootItem.insertColumns(position, columns)
+        self.endInsertColumns()
+        return ret
+
+    def insertRows(self, position, rows, parent):
+        parentItem = self.getItem(parent)
+        self.beginInsertRows(parent, position, position + rows -1)
+        ret = parentItem.insertChildren(position, rows, self.rootItem.columnCount())
+        self.endInsertRows()
+        return ret
+
+    def parent(self, index):
+        if not index.isValid():
+            return QModelIndex()
+
+        childItem = self.getItem(index)
+        parentItem = childItem.parent()
+
+        if parentItem is self.rootItem:
+            return QModelIndex()
+
+        return self.createIndex(parentItem.row(), 0, parentItem)
+
+    def rowCount(self, parent=QModelIndex()):
+        parentItem = self.getItem(parent)
+        return parentItem.childCount()
+
+    def columnCount(self, parent=None):
+        return self.rootItem.columnCount()
+
+    def data(self, index, role):
+        if not index.isValid():
+            return QVariant()
+
+        if role != Qt.DisplayRole and role != Qt.EditRole:
+            return QVariant()
+
+        item = self.getItem(index)
+        return item.data(index.column())
+
+    def flags(self, index):
+        if not index.isValid():
+            return 0
+        return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable
+
+    def setData(self, index, value, role):
+        if role != Qt.EditRole:
+            return False
+
+        item = self.getItem(index)
+        ret = item.setData(index.column(), value)
+        if ret:
+            self.emit(SIGNAL("dataChanged(QModelIndex, QModelIndex)"), index, index)
+        return ret
+
+
 
 class SliceWidget(QWidget):
-    def __init__(self, parent=None):
+    def __init__(self, parent):
         QWidget.__init__(self, parent)
 
-        self.nodeView = QTreeView(self)
-        self.nodeView.setRootIsDecorated(False)
-        self.nodeView.setAlternatingRowColors(True)
-        self.nodeView.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
+        slicename = QLabel ("Slice : %s"%(config.getSlice() or "None"),self)
+        slicename.setScaledContents(False)
+        searchlabel = QLabel ("Search: ", self)
+        searchlabel.setScaledContents(False)
+        searchbox = QLineEdit(self)
+        searchbox.setAttribute(Qt.WA_MacShowFocusRect, 0)
 
-        self.nodeModel = QStandardItemModel(0, 3, self)
-        self.nodeModel.setHeaderData(0, Qt.Horizontal, QString("Testbed"))
-        self.nodeModel.setHeaderData(1, Qt.Horizontal, QString("Hostname"))
-        self.nodeModel.setHeaderData(2, Qt.Horizontal, QString("IsIn"))
+        toplayout = QHBoxLayout()
+        toplayout.addWidget(slicename, 0, Qt.AlignLeft)
+        toplayout.addStretch()
+        toplayout.addWidget(searchlabel, 0, Qt.AlignRight)
+        toplayout.addWidget(searchbox, 0, Qt.AlignRight)
 
+        self.nodeView = NodeView(self)
+        self.nodeModel = NodeModel(self)
+        self.filterModel = QSortFilterProxyModel(self) # enable filtering
+        self.filterModel.setSourceModel(self.nodeModel)
+        self.nodeView.setModel(self.filterModel)
+        self.filterModel.setDynamicSortFilter(True)
         self.nodeView.setModel(self.nodeModel)
 
-        label = QLabel("<a href='refresh'>Refresh</a>", self)
-        label.setScaledContents(False)
-        self.connect(label, SIGNAL('linkActivated(QString)'), self.refresh)
+        self.nodeNameDelegate = NodeNameDelegate(self)
+        self.selectDelegate = SelectDelegate(self)
 
-        slicename = QLabel ("Slice : %s"%(config.getSlice() or "None"),self)
+        refresh = QPushButton("Update Slice Data", self)
+        refresh.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
+        submit = QPushButton("Submit", self)
+        submit.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
+
+        bottomlayout = QHBoxLayout()
+        bottomlayout.addWidget(refresh, 0, Qt.AlignLeft)
+        bottomlayout.addStretch()
+        bottomlayout.addWidget(submit, 0, Qt.AlignRight)
 
         layout = QVBoxLayout()
-        layout.addWidget(label)
-        layout.addWidget(slicename)
+        layout.addLayout(toplayout)
         layout.addWidget(self.nodeView)
+        layout.addLayout(bottomlayout)
         self.setLayout(layout)
         self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
+
+        self.connect(refresh, SIGNAL('clicked()'), self.refresh)
+        self.connect(submit, SIGNAL('clicked()'), self.submit)
+        self.connect(searchbox, SIGNAL('textChanged(QString)'), self.filter)
+
+        self.updateView()
+
+    def filter(self, filter):
+        self.filterModel.setFilterRegExp(QRegExp(filter))
+
+    def submit(self):
+        self.parent().setStatus("TODO: Submit not implemented yet!", 3000)
         
+    def readSliceRSpec(self):
+        rspec_file = config.getSliceRSpecFile()
+        if os.path.exists(rspec_file):
+            xml = open(rspec_file).read()
+            return xml
+        return None
 
-    def refresh(self, link=None):
-        data = SfaData()
-        if not data.getSlice(): 
-            print 'slice not set yet'
+    def refresh(self):
+        if not config.getSlice():
+            self.parent().setStatus("<font color='red'>Slice not set yet!</font>", timeout=None)
             return
-        if not data.SFACE_DEBUG:
-            rspec_string = data.getRSpecFromSM()
-        else:
-            print 'SFACE_DEBUG : using local file'
-            import os
-            rspec_string = open(os.path.expanduser("~/.sfi/%s.rspec"%data.getSlice())).read()
 
-        networks = self.rspec_get_networks(rspec_string)
-        networks.reverse()
+        self.process = SfiProcess()
+        outfile = self.process.getRSpecFromSM()
+        self.parent().setStatus("Updating slice data. This may take some time...", timeout=None)
+        
+        self.connect(self.process, SIGNAL('finished()'), self.refreshFinished)
+
+    def refreshFinished(self):
+        del self.process
+        self.parent().setStatus("<font color='green'>Slice data updated.</font>", timeout=5000)
+        self.updateView()
 
+    def updateView(self):
+        self.nodeModel.clear()
+        rspec_string = self.readSliceRSpec()
+        if not rspec_string:
+            return None
+
+        networks = rspec_get_networks(rspec_string)
         for network in networks:
-#            nodes = self.rspec_get_sliver_nodes_from_network(rspec_string, network)
-#            for node in nodes: self.addNode(network, node, True)
-#            nodes = self.rspec_get_other_nodes_from_network(rspec_string, network)
-#            for node in nodes: self.addNode(network, node, False)
-            # hacky - i'm just gettin used to this xml navigation stuff
-            xml_nodes = self.rspec_get_xml_nodes_from_network(rspec_string, network)
-            from lxml import etree
-            # addNode inserts before, so let's start with the ones that are not in
-            for xml_node in xml_nodes:
-                if not xml_node.xpath('sliver'): 
-                    self.addNode(network,xml_node.xpath('hostname/text()')[0],False)
-            for xml_node in xml_nodes:
-                if xml_node.xpath('sliver'): 
-                    self.addNode(network,xml_node.xpath('hostname/text()')[0],True)
-                
-
-    def addNode(self, testbed, hostname, mark):
-        self.nodeModel.insertRow(0)
-        self.nodeModel.setData(self.nodeModel.index(0,0), QString(testbed))
-        self.nodeModel.setData(self.nodeModel.index(0,1), QString(hostname))
-        if mark:msg="x"
-        else:   msg="-"
-        self.nodeModel.setData(self.nodeModel.index(0,2), QString(msg))
+            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)
+            available_nodes = filter(lambda x:x not in sliver_nodes, all_nodes)
+
+            for node in sliver_nodes:
+                nodeItem = TreeItem([QString(""), QString("%s" % node), QString("true")], networkItem)
+                networkItem.appendChild(nodeItem)
+
+            for node in available_nodes:
+                nodeItem = TreeItem([QString(""), QString(node), QString("false")], networkItem)
+                networkItem.appendChild(nodeItem)
+
+            self.nodeModel.rootItem.appendChild(networkItem)
+
+        self.nodeView.expandAll()
+        self.nodeView.resizeColumnToContents(1)
+        self.nodeView.setItemDelegateForColumn(1, self.nodeNameDelegate)
+        self.nodeView.setItemDelegateForColumn(2, self.selectDelegate)
 
 
 class MainScreen(SfaScreen):
-    def __init__(self, parent=None):
+    def __init__(self, parent):
         SfaScreen.__init__(self, parent)
 
         slice = SliceWidget(self)
-        self.init(slice, "Main Window", "PlanetLab Federation GUI")
-#        slice.refresh()
+        self.init(slice, "Main Window", "OneLab Federation GUI")