add tooltip to nodeview
[sface.git] / sface / screens / mainscreen.py
index ac0dedb..d43bd62 100644 (file)
@@ -9,6 +9,13 @@ from sface.config import config
 from sface.sfiprocess import SfiProcess
 from sface.screens.sfascreen import SfaScreen
 
+already_in_nodes = []
+
+node_status = { "in": "Already Selected",
+                "out": "Not Selected",
+                "add": "To be Added",
+                "remove": "To be Removed"}
+
 class NodeView(QTreeView):
     def __init__(self, parent):
         QTreeView.__init__(self, parent)
@@ -17,50 +24,80 @@ class NodeView(QTreeView):
         self.setItemsExpandable(True)
         self.setRootIsDecorated(True)
         self.setAlternatingRowColors(True)
+#        self.setSelectionMode(self.MultiSelection)
         self.setAttribute(Qt.WA_MacShowFocusRect, 0)
         self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
-
-class SelectDelegate(QStyledItemDelegate):
-    pass
+        self.setToolTip("Double click on a row to change its status")
+
+    def mouseDoubleClickEvent(self, event):
+        index = self.currentIndex()
+        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']))
+            else: model.setData(status_index, QString(node_status['out']))
+
+        model.emit(SIGNAL("dataChanged(QModelIndex, QModelIndex)"), hostname_index, hostname_index)
+                
+        
 
 class NodeNameDelegate(QStyledItemDelegate):
     def __init__(self, parent):
-        QStyledItemDelegate.__init__(self)
+        QStyledItemDelegate.__init__(self, parent)
 
     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()
 
-#         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 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() 
 
-        if data.startswith("*"): # already in the sliver
-            data = " %s " % data[1:]
+        path = QPainterPath()
+        path.addRoundedRect(x, y, w, h, 4, 4)
 
-            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()
+        painter.save()
+        painter.setRenderHint(QPainter.Antialiasing)
+        painter.drawRoundedRect(rect, 4, 4)
 
-            path = QPainterPath()
-            path.addRoundedRect(x, y, w, h, 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))
 
-            painter.save()
-            painter.setRenderHint(QPainter.Antialiasing)
-            painter.drawRoundedRect(rect, 4, 4)
+        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.restore()
-        else: # others, fall back to default view
-            QStyledItemDelegate.paint(self, painter, option, index)
+            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))
+
+        painter.restore()
 
 class TreeItem:
     def __init__(self, data, parent=None):
@@ -124,14 +161,6 @@ class TreeItem:
 
         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
@@ -148,8 +177,7 @@ class NodeModel(QAbstractItemModel):
         self.__initRoot()
 
     def __initRoot(self):
-        self.rootItem = TreeItem([QString("Testbed"), QString("Hostname"), QString("Selected")])
-
+        self.rootItem = TreeItem([QString("Testbed"), QString("Hostname"), QString("Status")])
 
     def getItem(self, index):
         if index.isValid():
@@ -158,7 +186,7 @@ class NodeModel(QAbstractItemModel):
         return self.rootItem
 
     def headerData(self, section, orientation, role):
-        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
+        if orientation == Qt.Horizontal and role in (Qt.DisplayRole, Qt.EditRole):
             return self.rootItem.data(section)
         return QVariant()
 
@@ -167,7 +195,6 @@ class NodeModel(QAbstractItemModel):
             return QModelIndex()
 
         parentItem = self.getItem(parent)
-            
         childItem = parentItem.child(row)
         if childItem:
             return self.createIndex(row, column, childItem)
@@ -193,11 +220,10 @@ class NodeModel(QAbstractItemModel):
 
         childItem = self.getItem(index)
         parentItem = childItem.parent()
-
         if parentItem is self.rootItem:
             return QModelIndex()
 
-        return self.createIndex(parentItem.row(), 0, parentItem)
+        return self.createIndex(parentItem.childNumber(), 0, parentItem)
 
     def rowCount(self, parent=QModelIndex()):
         parentItem = self.getItem(parent)
@@ -219,7 +245,7 @@ class NodeModel(QAbstractItemModel):
     def flags(self, index):
         if not index.isValid():
             return 0
-        return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable
+        return Qt.ItemIsEnabled | Qt.ItemIsSelectable# | Qt.ItemIsEditable
 
     def setData(self, index, value, role):
         if role != Qt.EditRole:
@@ -237,6 +263,8 @@ class SliceWidget(QWidget):
     def __init__(self, parent):
         QWidget.__init__(self, parent)
 
+        self.network_names = []
+
         slicename = QLabel ("Slice : %s"%(config.getSlice() or "None"),self)
         slicename.setScaledContents(False)
         searchlabel = QLabel ("Search: ", self)
@@ -253,13 +281,8 @@ class SliceWidget(QWidget):
         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)
 
         self.nodeNameDelegate = NodeNameDelegate(self)
-        self.selectDelegate = SelectDelegate(self)
 
         refresh = QPushButton("Update Slice Data", self)
         refresh.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
@@ -284,8 +307,14 @@ class SliceWidget(QWidget):
 
         self.updateView()
 
-    def filter(self, filter):
-        self.filterModel.setFilterRegExp(QRegExp(filter))
+    def filter(self, filter_string):
+        # for hierarchical models QSortFilterProxyModel applies the
+        # sort recursively. if the parent doesn't match the criteria
+        # we won't be able to match the children. so we need to match
+        # parent (by matching the network_names)
+        networks = ["^%s$" % n for n in self.network_names]
+        filters = networks + [str(filter_string)]
+        self.filterModel.setFilterRegExp(QRegExp('|'.join(filters)))
 
     def submit(self):
         self.parent().setStatus("TODO: Submit not implemented yet!", 3000)
@@ -314,33 +343,44 @@ class SliceWidget(QWidget):
         self.updateView()
 
     def updateView(self):
+        global already_in_nodes
+        already_in_nodes = []
+        self.network_names = []
         self.nodeModel.clear()
+        
         rspec_string = self.readSliceRSpec()
         if not rspec_string:
             return None
 
         networks = rspec_get_networks(rspec_string)
         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)
             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("true")], networkItem)
+                nodeItem = TreeItem([QString(""), QString("%s" % node), QString(node_status['in'])], networkItem)
                 networkItem.appendChild(nodeItem)
 
             for node in available_nodes:
-                nodeItem = TreeItem([QString(""), QString(node), QString("false")], networkItem)
+                nodeItem = TreeItem([QString(""), QString(node), QString(node_status['out'])], networkItem)
                 networkItem.appendChild(nodeItem)
 
             self.nodeModel.rootItem.appendChild(networkItem)
 
+        self.filterModel.setSourceModel(self.nodeModel)
+        self.filterModel.setFilterKeyColumn(-1)
+        self.filterModel.setDynamicSortFilter(True)
+
+        self.nodeView.setItemDelegateForColumn(1, self.nodeNameDelegate)
+        self.nodeView.setModel(self.filterModel)
         self.nodeView.expandAll()
         self.nodeView.resizeColumnToContents(1)
-        self.nodeView.setItemDelegateForColumn(1, self.nodeNameDelegate)
-        self.nodeView.setItemDelegateForColumn(2, self.selectDelegate)
 
 
 class MainScreen(SfaScreen):