import datetime import os import pickle from PyQt4.QtCore import * from PyQt4.QtGui import * from sface.config import config from sface.sfiprocess import SfiProcess from sface.screens.sfascreen import SfaScreen from sface.sfidata import SfiData NAME_COLUMN = 0 #ROLE_COLUMN = 1 MEMBERSHIP_STATUS_COLUMN = 1 SERVER_MEMBERSHIP_STATUS_COLUMN = 2 # maximum length of a name to display before clipping NAME_MAX_LEN = 48 user_status = { "in": "Already Selected", "out": "Not Selected", "add": "To be Added", "remove": "To be Removed"} color_status = { "in": QColor.fromRgb(0, 250, 250), "add": QColor.fromRgb(0, 250, 0), "remove": QColor.fromRgb(250, 0, 0) } class UserNameDelegate(QStyledItemDelegate): def __init__(self, parent): QStyledItemDelegate.__init__(self, parent) def displayText(self, value, locale): data = str(QStyledItemDelegate.displayText(self, value, locale)) if (len(data)>NAME_MAX_LEN): data = data[:(NAME_MAX_LEN-3)] + "..." return QString(data) def paint(self, painter, option, index): model = index.model() data = str(self.displayText(index.data(), QLocale())) status_index = model.index(index.row(), MEMBERSHIP_STATUS_COLUMN, index.parent()) status_data = status_index.data().toString() fm = QFontMetrics(option.font) rect = QRect(option.rect) rect.setHeight(rect.height() - 2) rect.setWidth(fm.width(QString(data)) + 6) rect.setX(rect.x() + 5) rect.setY(rect.y() - 1) textRect = QRect(option.rect) textRect.setWidth(fm.width(QString(data)) + 6) textRect.setX(rect.x()) 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 option.state & QStyle.State_Selected: painter.fillRect(option.rect, option.palette.color(QPalette.Active, QPalette.Highlight)) for x in user_status.keys(): if (user_status[x] == status_data) and (x in color_status): painter.fillPath(path, color_status[x]) painter.setPen(QColor.fromRgb(0, 0, 0)) painter.drawText(textRect, Qt.AlignVCenter, QString(data)) painter.restore() class UserView(QTableView): def __init__(self, parent=None): QTableView.__init__(self, parent) self.setSelectionBehavior(QAbstractItemView.SelectRows) self.setSelectionMode(QAbstractItemView.SingleSelection) self.setAlternatingRowColors(True) self.setAttribute(Qt.WA_MacShowFocusRect, 0) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.setToolTip("Double click on a row to change its status.") self.setItemDelegateForColumn(0, UserNameDelegate(self)) def keyPressEvent(self, event): if (event.key() == Qt.Key_Space): self.toggleSelection() else: QTableView.keyPressEvent(self, event) def mouseDoubleClickEvent(self, event): self.toggleSelection() def toggleSelection(self): index = self.currentIndex() model = index.model() status_index = model.index(index.row(), MEMBERSHIP_STATUS_COLUMN, index.parent()) status_data = status_index.data().toString() server_status_data = model.index(index.row(), SERVER_MEMBERSHIP_STATUS_COLUMN, index.parent()).data().toString() node_index = model.index(index.row(), NAME_COLUMN, index.parent()) node_data = node_index.data().toString() # This is a hostname if status_data == user_status['in']: model.setData(status_index, QString(user_status['remove'])) elif status_data == user_status['out']: model.setData(status_index, QString(user_status['add'])) elif status_data in (user_status['add'], user_status['remove']): if server_status_data == user_status["in"]: model.setData(status_index, QString(user_status['in'])) else: model.setData(status_index, QString(user_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(), 0, current.parent()) node_data = node_index.data().toString() def hideUnusableColumns(self): self.hideColumn(SERVER_MEMBERSHIP_STATUS_COLUMN) class UserModel(QStandardItemModel): def __init__(self, rows=0, columns=4, parent=None): QStandardItemModel.__init__(self, rows, columns, parent) def updateModel(self, sliceRec): self.clear() added_persons = [] slice_persons = [] if sliceRec: #for pi in sliceRec.get_field("PI", default=[]): # name = str(pi) # if not name in added_persons: # slice_persons.append({"name": name, "role": "PI", "member": user_status["in"]}) # added_persons.append(name) for researcher in sliceRec.get_field("researcher", default=[]): name = str(researcher) if not name in added_persons: slice_persons.append({"name": name, "role": "researcher", "member": user_status["in"]}) added_persons.append(name) userNames = SfiData().getAuthorityHrns(type="user") for name in userNames: if not name in added_persons: slice_persons.append({"name": name, "role": "", "member": user_status["out"]}) added_persons.append(name) rootItem = self.invisibleRootItem() for person in slice_persons: rootItem.appendRow([self.readOnlyItem(person["name"]), self.readOnlyItem(person["member"]), self.readOnlyItem(person["member"])]) headers = QStringList() << "User Name" << "Status" << "ServerStatus" self.setHorizontalHeaderLabels(headers) def readOnlyItem(self, x): item = QStandardItem(QString(x)) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) return item def updateRecord(self, slicerec): change = False item = self.invisibleRootItem() children = item.rowCount() for row in range(0, children): childName = str(item.child(row, NAME_COLUMN).data(Qt.DisplayRole).toString()) childStatus = str(item.child(row, MEMBERSHIP_STATUS_COLUMN).data(Qt.DisplayRole).toString()) if (childStatus == user_status['add']): researcher = slicerec.get_field("researcher", []) researcher.append(childName) slicerec["researcher"] = researcher change = True elif (childStatus == user_status['remove']): if childName in slicerec.get_field("PI"): slicerec.get_field("PI").remove(childName) if childName in slicerec.get_field("researcher"): slicerec.get_field("researcher").remove(childName) change = True return change def getResearchers(self): researchers = [] item = self.invisibleRootItem() children = item.rowCount() for row in range(0, children): childName = str(item.child(row, NAME_COLUMN).data(Qt.DisplayRole).toString()) childStatus = str(item.child(row, MEMBERSHIP_STATUS_COLUMN).data(Qt.DisplayRole).toString()) if (childStatus == user_status['add']) or (childStatus == user_status['in']): researchers.append(childName) return researchers class UsersWidget(QWidget): def __init__(self, parent): QWidget.__init__(self, parent) self.process = SfiProcess(self) 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(self.slicename, 0, Qt.AlignLeft) toplayout.addStretch() toplayout.addWidget(searchlabel, 0, Qt.AlignRight) toplayout.addWidget(searchbox, 0, Qt.AlignRight) self.userView = UserView() refresh = QPushButton("Refresh", 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.addLayout(toplayout) layout.addWidget(self.userView) layout.addLayout(bottomlayout) self.setLayout(layout) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.userModel = UserModel(parent=self) self.connect(refresh, SIGNAL('clicked()'), self.refresh) self.connect(submit, SIGNAL('clicked()'), self.submit) self.updateView() def submitFinished(self): self.disconnect(self.process, SIGNAL('finished()'), self.submitFinished) faultString = self.process.getFaultString() if not faultString: self.setStatus("Slice user data submitted.") QTimer.singleShot(1000, self.refresh) else: self.setStatus("Slice user submit failed: %s" % (faultString)) def getSliceRecordFinished(self): self.disconnect(self.process, SIGNAL('finished()'), self.getSliceRecordFinished) faultString = self.process.getFaultString() if not faultString: self.setStatus("Slice record refreshed.") self.refreshAuthority() else: self.setStatus("Slice rec refresh error: %s" % (faultString)) def getAuthorityRecordFinished(self): self.disconnect(self.process, SIGNAL('finished()'), self.getAuthorityRecordFinished) faultString = self.process.getFaultString() if not faultString: self.setStatus("User data refreshed.") self.updateView() #self.parent().signalAll("usersUpdated") else: self.setStatus("Authority rec refresh error: %s" % (faultString)) def setStatus(self, msg, timeout=None): self.parent().setStatus(msg, timeout) def checkRunningProcess(self): if self.process.isRunning(): self.setStatus("There is already a process running. Please wait.") return True return False def submit(self): if self.checkRunningProcess(): return rec = SfiData().getSliceRecord() change = self.userModel.updateRecord(rec) if not change: self.setStatus("No change in slice data. Not submitting!", timeout=3000) return rec_file = config.getSliceRecordFile() file(rec_file, "w").write(rec.save_to_string()) self.connect(self.process, SIGNAL('finished()'), self.submitFinished) self.process.updateRecord(rec_file) self.setStatus("Sending slice record. This will take some time...") def refresh(self): if not config.getSlice(): self.setStatus("Slice not set yet!") return if self.process.isRunning(): self.setStatus("There is already a process running. Please wait.") return self.connect(self.process, SIGNAL('finished()'), self.getSliceRecordFinished) self.process.getSliceRecord() self.setStatus("Refreshing slice record. This will take some time...") def refreshAuthority(self): self.connect(self.process, SIGNAL('finished()'), self.getAuthorityRecordFinished) self.process.listRecords(config.getAuthority(), None) self.setStatus("Refreshing user records. This will take some time...") def updateView(self): sliceRec = SfiData().getSliceRecord() if not sliceRec: # wait until we've resolved the slicerecord before displaying # anything to the user. self.userModel.clear() else: self.userModel.updateModel(sliceRec) self.userView.setModel(self.userModel) self.userView.hideColumn(SERVER_MEMBERSHIP_STATUS_COLUMN) self.userView.resizeColumnToContents(0) def updateSliceName(self): self.slicename.setText("Slice : %s" % (config.getSlice() or "None")) class UserScreen(SfaScreen): def __init__(self, parent): SfaScreen.__init__(self, parent) slice = UsersWidget(self) self.init(slice, "Users", "OneLab SFA crawler") def configurationChanged(self): self.widget.updateSliceName() self.widget.updateView()