Esempio n. 1
0
 def __init__(self,parent=None):
     FormParentClass.__init__(self,parent)
     self._message = QtGui.QMessageBox(self)
     self._wi = Ui_Data()
     self._wi.setupUi(self)
     self.setMinimumWidth(500)
     self._dataWidget = self
     self.fromAlarmGUI()
     self.api = panic.current()
     self.setCurrentAlarm(None)
     self.enableEditForm(False)
     self._parent = parent
Esempio n. 2
0
 def __init__(self,parent=None,refresh=0):
     FormParentClass.__init__(self,parent)
     self._message = QtGui.QMessageBox(self)
     self._wi = Ui_Data()
     self._wi.setupUi(self)
     [self._wi.severityCombo.addItem(s) for s in panic.SEVERITIES]
     
     self.setMinimumWidth(500)
     self._dataWidget = self
     self.fromAlarmGUI()
     self.api = panic.current()
     self.setCurrentAlarm(None)
     self.enableEditForm(False)
     self._parent = parent
     if refresh:
         self._timer = Qt.QTimer()
         self.connect(self._timer,Qt.SIGNAL("timeout()"), self.valueChanged)
         self._timer.start(refresh)
         print('AlarmForm._timer(%s)'%refresh)
Esempio n. 3
0
class AlarmForm(FormParentClass, iValidatedWidget):  #(QtGui.QWidget):

    __pyqtSignals__ = ("valueChanged", )

    def __init__(self, parent=None, refresh=0):
        FormParentClass.__init__(self, parent)
        self._message = QtGui.QMessageBox(self)
        self._wi = Ui_Data()
        self._wi.setupUi(self)
        [self._wi.severityCombo.addItem(s) for s in panic.SEVERITIES]

        self.setMinimumWidth(500)
        self._dataWidget = self
        self.fromAlarmGUI()
        self.api = panic.current()
        self.setCurrentAlarm(None)
        self.enableEditForm(False)
        self._parent = parent
        if refresh:
            self._timer = Qt.QTimer()
            self.connect(self._timer, Qt.SIGNAL("timeout()"),
                         self.valueChanged)
            self._timer.start(refresh)
            print('AlarmForm._timer(%s)' % refresh)

    def setCurrentAlarm(self, alarm=None):
        if isinstance(alarm, panic.Alarm):
            self._currentAlarm = alarm
        elif not alarm or alarm not in self.api:
            self._currentAlarm = panic.Alarm('')
        else:
            self._currentAlarm = self.api[alarm]
        print 'AlarmForm.setCurrentAlarm(%s)' % self._currentAlarm
        try:
            self._wi.formulaTextEdit.setModel(self._currentAlarm)
        except:
            traceback.print_exc()
        return self._currentAlarm

    def getCurrentAlarm(self, update=False):
        return self._currentAlarm

    def getSelectedAlarms(self):
        return [self._currentAlarm]

    def fromAlarmGUI(self):
        self.formulaeditor = FormulaEditor(self._dataWidget)
        #self._dataWidget._wi.frame)
        self._receiversLine = ReceiversForm()
        self.prepareLineWidget()
        #self._ui.gridLayout.addWidget(self._dataWidget)
        self._dataWidget._wi.formulaStacked.addWidget(self.formulaeditor)

        QtCore.QObject.connect(self._receiversLine._wi.okButton,
                               QtCore.SIGNAL("clicked(bool)"),
                               self.onPlusOk)  # Add
        QtCore.QObject.connect(self.formulaeditor._ui.rowEditButton,
                               QtCore.SIGNAL("clicked(bool)"), self.onRowEdit)

        QtCore.QObject.connect(self._dataWidget._wi.addReceiversButton,
                               QtCore.SIGNAL("clicked(bool)"), self.onPlus)
        QtCore.QObject.connect(self._dataWidget._wi.previewButton,
                               QtCore.SIGNAL("clicked()"),
                               self.showAlarmPreview)
        QtCore.QObject.connect(self._dataWidget._wi.cancelButton,
                               QtCore.SIGNAL("clicked()"),
                               self.onCancel)  # "Cancel"
        QtCore.QObject.connect(self._dataWidget._wi.saveButton,
                               QtCore.SIGNAL("clicked()"),
                               self.onSave)  # "Save"
        QtCore.QObject.connect(self._dataWidget._wi.editButton,
                               QtCore.SIGNAL("clicked()"),
                               self.onEdit)  # "Edit"
        QtCore.QObject.connect(self._dataWidget._wi.disabledCheckBox,
                               QtCore.SIGNAL("stateChanged(int)"),
                               self.onDisStateChanged)
        QtCore.QObject.connect(self._dataWidget._wi.ackCheckBox,
                               QtCore.SIGNAL("stateChanged(int)"),
                               self.onAckStateChanged)
        QtCore.QObject.connect(self._dataWidget._wi.deviceConfig,
                               QtCore.SIGNAL("clicked()"), self.onDeviceConfig)

        self._dataWidget._wi.nameLineEdit.setClickHook(self.onEdit)
        self._dataWidget._wi.deviceLineEdit.setClickHook(self.onEdit)
        self._dataWidget._wi.severityLineEdit.setClickHook(self.onEdit)
        self._dataWidget._wi.receiversLineEdit.setClickHook(self.onEdit)
        self._dataWidget._wi.descriptionTextEdit.setClickHook(self.onEdit)
        self._dataWidget._wi.formulaTextEdit.setClickHook(self.onEdit)

    def showAlarmPreview(self):
        self.preview = AlarmPreview(
            tag=self.getCurrentAlarm().tag,
            formula=self._wi.formulaTextEdit.toPlainText(),
            parent=self.parent())
        self.preview.connect(self.preview.upperPanel,
                             Qt.SIGNAL('onSave'),
                             lambda obj, s=self:
                             (s.enableEditForm(False), s.setAlarmData(obj)))
        from utils import WindowManager
        WindowManager.addWindow(self.preview)
        self.preview.show()

    def showAlarmReport(self):
        #qd = Qt.QDialog(self.parent())
        self.report = getAlarmReport(alarm=self.getCurrentAlarm(),
                                     parent=self.parent())
        self.report.setModal(True)
        #form.setParent(qd)
        self.report.exec_()

    def onSettingExpert(self):
        self.clearAlarmData()
        self.enableEditForm(False)

    def onDeviceConfig(self):
        panic.gui.actions.ShowConfig(self)

    ###########################################################################
    # AlarmEditor

    def onEdit(self, alarm=None):
        if alarm: self.setCurrentAlarm(alarm)
        alarm = self.getCurrentAlarm()
        print "AlarmForm.onEdit(%s)" % alarm

        self.setAlarmData(alarm)
        self.enableEditForm(True)

    def onNew(self):
        print 'onNew()'
        self.clearAlarmData()
        self.enableEditForm(True)
        self._tvl.updateStyle()

    def onSave(self):
        print 'onSave()' + '<' * 80
        if self.checkDataFields() and \
                self.validate('onSave',self._currentAlarm.tag):
            old_name = self.getCurrentAlarm().tag
            #<- it will save data and will remove unused alarm rows
            self.saveData(old_name=old_name)
            self.enableEditForm(False)
        else:
            self._message.critical(self, "Critical", "Alarm not saved!")
        self.valueChanged()

    def onCancel(self):
        print 'onCancel()'
        self.formulaeditor.Clr()
        self.setAlarmData()
        self.enableEditForm(not (
            self.getCurrentAlarm() and self.getCurrentAlarm().tag))

    def onPlus(self):
        self._receiversLine.show()

    def onRowEdit(self, bool):
        self.formulaeditor._ui.formulaLineEdit.setReadOnly(bool)

    def onPlusOk(self):
        text = self._dataWidget._wi.receiversLineEdit.text()
        newText = self._receiversLine._wi.receiversCombo.currentText()
        if text:
            newText = ','.join([str(text), str(newText)])
        self._dataWidget._wi.receiversLineEdit.setText(newText)

    def onReset(self, alarm=None):
        panic.gui.actions.ResetAlarm(self, alarm)

    def valueChanged(self, forced=False):
        timed = hasattr(self, '_timer')
        alarm = self.getCurrentAlarm()
        print('AlarmForm(%s).valueChanged(%s,%s)' % (alarm.tag, forced, timed))
        if timed or forced:
            dis = not alarm.get_enabled(force=True)
            ack = alarm.get_acknowledged(force=True)
            print('\tdis,ack = ', (dis, ack))
        if timed:
            alarm.set_active(alarm.get_time(True))
            alarm.set_state()

        self.emit(Qt.SIGNAL('valueChanged'))

    ###########################################################################

    def prepareLineWidget(self):
        #Setup of the State/Details/Reset line in the editor widget
        self.w = Qt.QWidget()
        self.w.setLayout(Qt.QHBoxLayout())
        self._tvl = AlarmValueLabel(self.w)
        #self._tvl.setShowQuality(False)
        self._tvl.connect(self, Qt.SIGNAL('valueChanged'),
                          self._tvl.updateStyle)
        self.connect(self, Qt.SIGNAL('valueChanged'),
                     self.update_button_states)
        self._detailsButton = Qt.QPushButton(self.w)
        self._detailsButton.setText('Last Report')
        self._detailsButton.setIcon(getThemeIcon("edit-find"))
        self._detailsButton.connect(self._detailsButton,
                                    Qt.SIGNAL("clicked()"),
                                    self.showAlarmReport)
        self._detailsButton.setEnabled(False)
        self._resetButton = Qt.QPushButton(self.w)
        self._resetButton.setText('Reset')
        self._resetButton.setIcon(getThemeIcon("edit-undo"))
        self._resetButton.connect(self._resetButton, Qt.SIGNAL("clicked()"),
                                  self.onReset)
        self._resetButton.setEnabled(False)
        self.w.layout().addWidget(self._tvl)
        self.w.layout().addWidget(self._detailsButton)
        self.w.layout().addWidget(self._resetButton)
        self._dataWidget._wi.horizontalLane.addWidget(self.w)

    def clearAlarmData(self):
        print "AlarmForm.clearAlarmData()"
        self.setCurrentAlarm()
        self._dataWidget._wi.nameLineEdit.clear()
        self._dataWidget._wi.deviceLineEdit.clear()
        self._dataWidget._wi.descriptionTextEdit.clear()
        self._dataWidget._wi.wikiLink.clear()
        self._dataWidget._wi.wikiLink.hide()
        # self._dataWidget._wi.wikiLink.show()
        self._dataWidget._wi.receiversLineEdit.clear()
        self._dataWidget._wi.severityLineEdit.clear()
        self._dataWidget._wi.formulaTextEdit.clear()
        self.formulaeditor.Clr()

    def setComboBox(self, comboBox, values, sort=False):
        #        print "setRecData"
        comboBox.clear()
        [comboBox.addItem(QtCore.QString(i)) for i in values]
        if sort: comboBox.model().sort(0, Qt.Qt.AscendingOrder)

    def setAlarmData(self, alarm=None):
        #This method is called from listWidget.currentRowChanged() event

        if alarm: self.setCurrentAlarm(alarm)
        print 'AlarmForm.setAlarmData(%s)' % (self.getCurrentAlarm())
        self.setWindowTitle('ALARM: %s' % self.getCurrentAlarm().tag)

        #print 'PanicGUI.setAlarmData(%d,%s@%s): %s-%s since %s,dis:%s,ack:%s'%(
        #i,self.alarm.tag,self.alarm.device,row.value,row.quality,
        #time.ctime(self.alarm.active),row.alarmDisabled,row.alarmAcknowledged)

        alarm = self.getCurrentAlarm()

        self._dataWidget._wi.nameLineEdit.setText(alarm.tag)
        self._dataWidget._wi.deviceLineEdit.setText(alarm.device)
        self._dataWidget._wi.descriptionTextEdit.setText(alarm.description)

        self._dataWidget._wi.severityLineEdit.setText(alarm.severity)
        self._dataWidget._wi.receiversLineEdit.setText(alarm.receivers)
        self._dataWidget._wi.formulaTextEdit.setText(alarm.formula)

        self._tvl.setModel(alarm)  #.device+'/'+alarm.get_attribute())
        self._dataWidget._wi.previewButton.setEnabled(True)
        self._dataWidget._wi.editButton.setEnabled(True)
        self.valueChanged(forced=True)

        # setup wiki link
        wiki_link = alarm.get_wiki_link()
        if len(wiki_link) > 0:
            self._dataWidget._wi.wikiLink.setText(
                '<qt><a href="' + alarm.get_wiki_link() +
                '">More info on Wiki...</a></qt>')
            self._dataWidget._wi.wikiLink.show()
            # self._dataWidget._wi.wikiLabel.show()
        else:
            self._dataWidget._wi.wikiLink.hide()
            # self._dataWidget._wi.wikiLabel.hide()

        return

    def update_button_states(self, alarm=None):
        alarm = alarm or self.getCurrentAlarm()
        #print('update_button_states(%s)'%alarm.tag)
        if alarm.active:
            self._detailsButton.setEnabled(True)
            self._resetButton.setEnabled(True)
        else:
            self._detailsButton.setEnabled(False)
            self._resetButton.setEnabled(False)
        setCheckBox(self._dataWidget._wi.disabledCheckBox,
                    not alarm.get_enabled())
        setCheckBox(self._dataWidget._wi.ackCheckBox, alarm.acknowledged)
        return

    def enableDelete(self, tmp):
        #        print "activeDelete"
        self._ui.deleteButton.setEnabled(tmp >= 0)
        return tmp >= 0

    def enableEditForm(self, b):
        """
        This method prepares the widget to be editable
        """
        #Enables writing of data widgets
        #self._ui.deleteButton.setEnabled(not b)
        self._dataWidget._wi.nameLineEdit.setReadOnly(not b)
        self._dataWidget._wi.descriptionTextEdit.setReadOnly(not b)
        self._dataWidget._wi.receiversLineEdit.setReadOnly(not b)
        self._dataWidget._wi.addReceiversButton.setEnabled(b)
        self._dataWidget._wi.editButton.setEnabled(not b)
        self._dataWidget._wi.cancelButton.setEnabled(b)
        self._dataWidget._wi.saveButton.setEnabled(b)
        self._dataWidget._wi.disabledCheckBox.setEnabled(not b)
        self._dataWidget._wi.ackCheckBox.setEnabled(not b)
        if b:
            #self._dataWidget._wi.formulaStacked.setCurrentIndex(1)
            self._dataWidget._wi.formulaTextEdit.onEdit(True)
            self._dataWidget._wi.deviceStackedLayout.setCurrentIndex(0)
            self._dataWidget._wi.severityStackedLayout.setCurrentIndex(0)

            #def prepareDataWidget(self)
            alarm = self.getCurrentAlarm()
            #Puts the widget in edit mode
            print 'In prepareDataWidget(%s)' % alarm.tag

            for i in range(self._dataWidget._wi.severityCombo.count()):
                if str(self._dataWidget._wi.severityCombo.itemText(i)).lower()\
                    ==(self.getCurrentAlarm().severity or 'WARNING').lower():
                    self._dataWidget._wi.severityCombo.setCurrentIndex(i)
                    break
            self.setComboBox(self._dataWidget._wi.deviceCombo,
                             values=[''] + self.api.devices.keys(),
                             sort=True)
            if self.getCurrentAlarm().device:
                for i in range(self._dataWidget._wi.deviceCombo.count()):
                    if str(self._dataWidget._wi.deviceCombo.itemText(i)).lower(
                    ) == self.getCurrentAlarm().device.lower():
                        self._dataWidget._wi.deviceCombo.setCurrentIndex(i)
                        break

            self.setComboBox(self._receiversLine._wi.receiversCombo,
                             self.api.get_phonebook().keys(),
                             sort=True)
            self._tvl.updateStyle()
            #End of prepareDataWidget(self)

            #self.formulaeditor._ui.formulaLineEdit.setText(alarm.formula)
            #self._dataWidget._wi.formulaTextEdit.toPlainText())
            #self.formulaeditor.expand_expression()
            #self.formulaeditor._ui.formulaLineEdit.setEnabled(True)
        else:
            #self._dataWidget._wi.formulaStacked.setCurrentIndex(0)
            self._dataWidget._wi.formulaTextEdit.onEdit(False)
            self._dataWidget._wi.deviceStackedLayout.setCurrentIndex(1)
            self._dataWidget._wi.severityStackedLayout.setCurrentIndex(1)
        return b

    ###########################################################################

    def getDataFields(self):
        widget, alarm = self._dataWidget, self.formulaeditor
        data = dict((k, str(s).strip()) for k, s in [
            ('tag', widget._wi.nameLineEdit.text()),
            ('description', widget._wi.descriptionTextEdit.toPlainText()),
            ('device', widget._wi.deviceCombo.currentText()),
            ('receivers', widget._wi.receiversLineEdit.text()),
            #('formula',str(alarm._ui.formulaLineEdit.text()).strip() \
            #   or str(widget._wi.formulaTextEdit.toPlainText()).strip()),
            ('formula', str(widget._wi.formulaTextEdit.toPlainText()).strip()),
            ('severity', str(widget._wi.severityCombo.currentText())),
        ])
        print 'getDataFields(%s): %s' % (data['tag'], data)
        return data

    def checkDataFields(self):
        data = self.getDataFields()
        must = ['tag', 'device', 'formula', 'severity', 'description']
        if not all(data[k] for k in must):
            self._message.warning(
                self, "Warning", "Fill these fields: %s" %
                ','.join(k for k in must if not data[k]))
            return False
        elif not clmatch('^[a-zA-Z_][a-zA-Z_0-9]*$', data['tag']):
            self._message.warning(
                self, "Warning",
                "Tag contains invalid characters: %s" % data['tag'])
            return False
        else:
            return True

    def saveData(self, old_name=None):
        print 'In saveData(%s)' % old_name
        data = self.getDataFields()
        widget = self._dataWidget
        widget._wi.deviceLineEdit.setText(data['device'])
        widget._wi.formulaTextEdit.setText(data['formula'])
        widget._wi.severityLineEdit.setText(data['severity'])
        tag, device = data['tag'], data['device']
        alarm = self.api.alarms.get(tag, None)

        if not old_name or old_name not in self.api:
            print "\tAlarm doesn't exist... creating new"
            try:
                self.api.add(**data)
            except Exception, e:
                Qt.QMessageBox.critical(self, "Error!", str(e),
                                        QtGui.QMessageBox.AcceptRole,
                                        QtGui.QMessageBox.AcceptRole)
                print traceback.format_exc()

        elif old_name == tag:
            print "\tAlarm exists ... modifying fields (%s)" % str(
                data.values())
            if device != self.api[tag].device:
                self.api.rename(tag, tag, new_device=device)
                alarm = self.api[tag]
                self._tvl.setModel(alarm)  #.device+'/'+alarm.get_attribute())
                self.valueChanged()
                #setAlarmModel() moved to AlarmGUI
                #self.AlarmRows[tag].setAlarmModel(self.api[tag])
            alarm.setup(write=True, **data)
Esempio n. 4
0
class AlarmForm(FormParentClass,iLDAPValidatedWidget): #(QtGui.QWidget):
    
    __pyqtSignals__ = ("valueChanged",)
    
    def __init__(self,parent=None):
        FormParentClass.__init__(self,parent)
        self._message = QtGui.QMessageBox(self)
        self._wi = Ui_Data()
        self._wi.setupUi(self)
        self.setMinimumWidth(500)
        self._dataWidget = self
        self.fromAlarmGUI()
        self.api = panic.current()
        self.setCurrentAlarm(None)
        self.enableEditForm(False)
        self._parent = parent
            
    def setCurrentAlarm(self,alarm=None):
        if isinstance(alarm,panic.Alarm):
            self._currentAlarm = alarm
        elif not alarm or alarm not in self.api:
            self._currentAlarm = panic.Alarm('')
        else:
            self._currentAlarm = self.api[alarm]
        print 'AlarmForm.setCurrentAlarm(%s)'%self._currentAlarm
        try: self._wi.formulaTextEdit.setModel(self._currentAlarm)
        except: traceback.print_exc()
        return self._currentAlarm
        
    def getCurrentAlarm(self,update=False):
        return self._currentAlarm
    
    def fromAlarmGUI(self):
        self.formulaeditor=FormulaEditor(self._dataWidget)#self._dataWidget._wi.frame)
        self._receiversLine=ReceiversForm()
        self.prepareLineWidget()
        #self._ui.gridLayout.addWidget(self._dataWidget)
        self._dataWidget._wi.formulaStacked.addWidget(self.formulaeditor)
        
        QtCore.QObject.connect(self._receiversLine._wi.okButton, QtCore.SIGNAL("clicked(bool)"), self.onPlusOk) # Add
        QtCore.QObject.connect(self.formulaeditor._ui.rowEditButton, QtCore.SIGNAL("clicked(bool)"), self.onRowEdit)
        
        QtCore.QObject.connect(self._dataWidget._wi.addReceiversButton, QtCore.SIGNAL("clicked(bool)"), self.onPlus)
        QtCore.QObject.connect(self._dataWidget._wi.previewButton, QtCore.SIGNAL("clicked()"), self.showAlarmPreview)
        QtCore.QObject.connect(self._dataWidget._wi.cancelButton, QtCore.SIGNAL("clicked()"), self.onCancel) # "Cancel"
        QtCore.QObject.connect(self._dataWidget._wi.saveButton, QtCore.SIGNAL("clicked()"), self.onSave) # "Save"
        QtCore.QObject.connect(self._dataWidget._wi.editButton, QtCore.SIGNAL("clicked()"), self.onEdit) # "Edit"
        QtCore.QObject.connect(self._dataWidget._wi.disabledCheckBox, QtCore.SIGNAL("stateChanged(int)"), self.onDisStateChanged)
        QtCore.QObject.connect(self._dataWidget._wi.ackCheckBox, QtCore.SIGNAL("stateChanged(int)"), self.onAckStateChanged)
        QtCore.QObject.connect(self._dataWidget._wi.deviceConfig, QtCore.SIGNAL("clicked()"), self.onDeviceConfig)
        
        self._dataWidget._wi.nameLineEdit.setClickHook(self.onEdit)
        self._dataWidget._wi.deviceLineEdit.setClickHook(self.onEdit)
        self._dataWidget._wi.severityLineEdit.setClickHook(self.onEdit)
        self._dataWidget._wi.receiversLineEdit.setClickHook(self.onEdit)
        self._dataWidget._wi.descriptionTextEdit.setClickHook(self.onEdit)
        self._dataWidget._wi.formulaTextEdit.setClickHook(self.onEdit)
        
    def showAlarmPreview(self):
        self.preview = AlarmPreview(tag=self.getCurrentAlarm().tag,formula=self._wi.formulaTextEdit.toPlainText(),parent=self.parent())
        self.preview.connect(self.preview.upperPanel,Qt.SIGNAL('onSave'),
            lambda obj,s=self:(s.enableEditForm(False),s.setAlarmData(obj)))
        from widgets import WindowManager
        WindowManager.addWindow(self.preview)
        self.preview.show()
        
    def showAlarmReport(self):
        #qd = Qt.QDialog(self.parent())
        self.report = getAlarmReport(alarm=self.getCurrentAlarm(),parent=self.parent())
        self.report.setModal(True)
        #form.setParent(qd)
        self.report.exec_()
        
    def onSettingExpert(self):
        self.clearAlarmData()
        self.enableEditForm(False)
        
    def onDeviceConfig(self):
        from widgets import dacWidget
        self.dac = dacWidget(device=self.getCurrentAlarm().device)
        self.dac.show()
        
    ###########################################################################
    # AlarmEditor

    def onEdit(self,alarm=None):
        if alarm: self.setCurrentAlarm(alarm)
        alarm = self.getCurrentAlarm()
        print "AlarmForm.onEdit(%s)"%alarm
        
        self.setAlarmData(alarm)
        self.enableEditForm(True)
        
    def onNew(self):
        print'onNew()'
        self.clearAlarmData()
        self.enableEditForm(True)
        self._tvl.updateStyle()

    def onSave(self):
        print'onSave()'+'<'*80
        if self.checkEmptyFields() and self.validate('onSave',self._currentAlarm.tag):
            old_name = self.getCurrentAlarm().tag
            self.saveData(old_name = old_name) #<- it will save data and will remove unused alarm rows
            self.enableEditForm(False)
        else:
            self._message.critical(self, "Critical", "Alarm not saved!")
        self.valueChanged()

    def onCancel(self):
        print'onCancel()'
        self.formulaeditor.Clr()
        self.setAlarmData()
        self.enableEditForm(not(self.getCurrentAlarm() and self.getCurrentAlarm().tag))
    
    def onPlus(self):
        self._receiversLine.show()

    def onRowEdit(self, bool):
        self.formulaeditor._ui.formulaLineEdit.setReadOnly(bool)

    def onPlusOk(self):
        text = self._dataWidget._wi.receiversLineEdit.text()
        newText = self._receiversLine._wi.receiversCombo.currentText()
        if text:
            newText = ','.join([str(text), str(newText)])
        self._dataWidget._wi.receiversLineEdit.setText(newText)
        
    def ResetAlarm(self,alarm=None):
        prompt,cmt=QtGui.QInputDialog,''
        alarms = [self.getCurrentAlarm()]
        msg = 'The following alarms will be reseted:\n\t'+'\n\t'.join([t.tag for t in alarms])
        print 'In AlarmGUI.ResetAlarm(): %s'%msg
        while len(cmt)==0:
            cmt, ok=prompt.getText(self,'Input dialog',msg+'\n\n'+'Must type a comment to continue:')
            if not ok: return
        comment=get_user()+': '+cmt
        for alarm in alarms:
            try: alarm.reset(comment) #It also tries to reset hidden alarms
            except: print traceback.format_exc()
        self.valueChanged()

    def AcknowledgeAlarm(self):
        """THIS METHOD IS NEVER CALLED!?!?!?!?!?!?!"""
        alarm = self.getCurrentAlarm()
        print 'In AlarmForm.AcknowledgeAlarm(%s)' % (alarm.tag)
        comment, ok = QtGui.QInputDialog.getText(self,'Input dialog','Type a comment to continue:')
        comment = get_user()+': '+comment
        if ok and len(str(comment)) != 0:
            try:
                alarm.reset(comment) #... Why it resets instead of Acknowledge?
                #taurus.Device(alarm.device).command_inout('Acknowledge',[tag, comment])
            except:
                print traceback.format_exc()
            self.valueChanged()
        elif ok and len(str(comment)) < 3:
            self.AcknowledgeAlarm()
            
    def valueChanged(self):
        print 'AlarmForm.valueChanged()'
        self.emit(Qt.SIGNAL('valueChanged'))
        
    ###########################################################################

    def prepareLineWidget(self):
        #Setup of the State/Details/Reset line in the editor widget
        self.w = Qt.QWidget()
        self.w.setLayout(Qt.QHBoxLayout())
        self._tvl = AlarmValueLabel(self.w)
        self._tvl.setShowQuality(False)
        self._detailsButton = Qt.QPushButton(self.w)
        self._detailsButton.setText('Last Report')
        self._detailsButton.setIcon(getThemeIcon("edit-find"))
        self._detailsButton.connect(self._detailsButton,Qt.SIGNAL("clicked()"),self.showAlarmReport)
        self._detailsButton.setEnabled(False)
        self._resetButton = Qt.QPushButton(self.w)
        self._resetButton.setText('Reset')
        self._resetButton.setIcon(getThemeIcon("edit-undo"))
        self._resetButton.connect(self._resetButton,Qt.SIGNAL("clicked()"),self.ResetAlarm)
        self._resetButton.setEnabled(False)
        self.w.layout().addWidget(self._tvl)
        self.w.layout().addWidget(self._detailsButton)
        self.w.layout().addWidget(self._resetButton)
        self._dataWidget._wi.horizontalLane.addWidget(self.w)

    def clearAlarmData(self):
        print "AlarmForm.clearAlarmData()"
        self.setCurrentAlarm()
        self._dataWidget._wi.nameLineEdit.clear()
        self._dataWidget._wi.deviceLineEdit.clear()
        self._dataWidget._wi.descriptionTextEdit.clear()
        self._dataWidget._wi.receiversLineEdit.clear()
        self._dataWidget._wi.severityLineEdit.clear()
        self._dataWidget._wi.formulaTextEdit.clear()
        self.formulaeditor.Clr()
        
    def setComboBox(self, comboBox, values, sort=False):
#        print "setRecData"
        comboBox.clear()
        [comboBox.addItem(QtCore.QString(i)) for i in values]
        if sort: comboBox.model().sort(0, Qt.Qt.AscendingOrder)

    def setAlarmData(self,alarm=None):
        #This method is called from listWidget.currentRowChanged() event
        
        if alarm: self.setCurrentAlarm(alarm)
        print 'AlarmForm.setAlarmData(%s)'%(self.getCurrentAlarm())
        self.setWindowTitle('ALARM: %s'%self.getCurrentAlarm().tag)

        #print 'PanicGUI.setAlarmData(%d,%s@%s): %s-%s since %s,dis:%s,ack:%s'%(
            #i,self.alarm.tag,self.alarm.device,row.value,row.quality,time.ctime(self.alarm.active),row.alarmDisabled,row.alarmAcknowledged)
            
        alarm = self.getCurrentAlarm()

        self._dataWidget._wi.nameLineEdit.setText(alarm.tag)
        self._dataWidget._wi.deviceLineEdit.setText(alarm.device)
        self._dataWidget._wi.descriptionTextEdit.setText(alarm.description)
        self._dataWidget._wi.severityLineEdit.setText(alarm.severity)
        self._dataWidget._wi.receiversLineEdit.setText(alarm.receivers)
        self._dataWidget._wi.formulaTextEdit.setText(alarm.formula)

        self._tvl.setModel(alarm.device+'/'+alarm.get_attribute())
        self._dataWidget._wi.previewButton.setEnabled(True)
        self._dataWidget._wi.editButton.setEnabled(True)
        if alarm.get_active():
            self._detailsButton.setEnabled(True)
            self._resetButton.setEnabled(True)
        else: 
            self._detailsButton.setEnabled(False)
            self._resetButton.setEnabled(False)
        setCheckBox(self._dataWidget._wi.disabledCheckBox,not alarm.get_enabled())
        setCheckBox(self._dataWidget._wi.ackCheckBox,alarm.acknowledged)
        return
        
    def enableDelete(self, tmp):
#        print "activeDelete"
        self._ui.deleteButton.setEnabled(tmp>=0)
        return tmp>=0

    def enableEditForm(self, b):
        """
        This method prepares the widget to be editable
        """
        #Enables writing of data widgets
        #self._ui.deleteButton.setEnabled(not b)
        self._dataWidget._wi.nameLineEdit.setReadOnly(not b)
        self._dataWidget._wi.descriptionTextEdit.setReadOnly(not b)
        self._dataWidget._wi.receiversLineEdit.setReadOnly(not b)
        self._dataWidget._wi.addReceiversButton.setEnabled(b)
        self._dataWidget._wi.editButton.setEnabled(not b)
        self._dataWidget._wi.cancelButton.setEnabled(b)
        self._dataWidget._wi.saveButton.setEnabled(b)
        self._dataWidget._wi.disabledCheckBox.setEnabled(not b)
        self._dataWidget._wi.ackCheckBox.setEnabled(not b)
        if b:
            #self._dataWidget._wi.formulaStacked.setCurrentIndex(1)
            self._dataWidget._wi.formulaTextEdit.onEdit(True)
            self._dataWidget._wi.deviceStackedLayout.setCurrentIndex(0)
            self._dataWidget._wi.severityStackedLayout.setCurrentIndex(0)
            
            #def prepareDataWidget(self)
            alarm = self.getCurrentAlarm()
            #Puts the widget in edit mode
            print 'In prepareDataWidget(%s)'%alarm.tag
            
            for i in range(self._dataWidget._wi.severityCombo.count()):
                if str(self._dataWidget._wi.severityCombo.itemText(i)).lower()==(self.getCurrentAlarm().severity or 'WARNING').lower():
                    self._dataWidget._wi.severityCombo.setCurrentIndex(i)
                    break
            self.setComboBox(self._dataWidget._wi.deviceCombo,values=['']+self.api.devices.keys(),sort=True)
            if self.getCurrentAlarm().device:
                for i in range(self._dataWidget._wi.deviceCombo.count()):
                    if str(self._dataWidget._wi.deviceCombo.itemText(i)).lower()==self.getCurrentAlarm().device.lower():
                        self._dataWidget._wi.deviceCombo.setCurrentIndex(i)
                        break
                    
            self.setComboBox(self._receiversLine._wi.receiversCombo,self.api.phonebook.keys(),sort=True)
            self._tvl.updateStyle()
            #End of prepareDataWidget(self)
            
            #self.formulaeditor._ui.formulaLineEdit.setText(alarm.formula) #self._dataWidget._wi.formulaTextEdit.toPlainText())
            #self.formulaeditor.expand_expression()
            #self.formulaeditor._ui.formulaLineEdit.setEnabled(True)
        else:
            #self._dataWidget._wi.formulaStacked.setCurrentIndex(0)
            self._dataWidget._wi.formulaTextEdit.onEdit(False)
            self._dataWidget._wi.deviceStackedLayout.setCurrentIndex(1)
            self._dataWidget._wi.severityStackedLayout.setCurrentIndex(1)
        return b

    ###########################################################################
    
    def getDataFields(self):
        widget,alarm = self._dataWidget,self.formulaeditor
        data = dict((k,str(s).strip()) for k,s in [
            ('tag',widget._wi.nameLineEdit.text()),
            ('description',widget._wi.descriptionTextEdit.toPlainText()),
            ('device',widget._wi.deviceCombo.currentText()),
            ('receivers',widget._wi.receiversLineEdit.text()),
            #('formula',str(alarm._ui.formulaLineEdit.text()).strip() or str(widget._wi.formulaTextEdit.toPlainText()).strip()),
            ('formula',str(widget._wi.formulaTextEdit.toPlainText()).strip()),
            ('severity',str(widget._wi.severityCombo.currentText())),
            ])
        print 'getDataFields(%s): %s'%(data['tag'],data)
        return data

    def checkEmptyFields(self):
        data = self.getDataFields()
        if all(data.values()): 
            return True
        else:
            self._message.warning(self, "Warning", "Fill these fields: %s" % ','.join(k for k,v in data.items() if not v))
            return False

    def saveData(self, old_name=None):
        print 'In saveData(%s)'%old_name
        data = self.getDataFields()
        widget = self._dataWidget
        widget._wi.deviceLineEdit.setText(data['device'])
        widget._wi.formulaTextEdit.setText(data['formula'])
        widget._wi.severityLineEdit.setText(data['severity'])
        tag,device = data['tag'],data['device']
        alarm = self.api.alarms.get(tag,None)
        
        if not old_name or old_name not in self.api:
            print "\tAlarm doesn't exist... creating new"
            try:
                self.api.add(**data)
            except Exception,e:
                Qt.QMessageBox.critical(self,"Error!",str(e), QtGui.QMessageBox.AcceptRole, QtGui.QMessageBox.AcceptRole)
                print traceback.format_exc()
        
        elif old_name == tag:
            print "\tAlarm exists ... modifying fields (%s)"%str(data.values())
            if device!=self.api[tag].device:
                self.api.rename(tag,tag,new_device=device)
                alarm = self.api[tag]
                self._tvl.setModel(alarm.device+'/'+alarm.get_attribute())
                self.valueChanged()
                #setAlarmModel() moved to AlarmGUI
                #self.AlarmRows[tag].setAlarmModel(self.api[tag])
            alarm.setup(write=True,**data)