'''
Accessible Access Control 1.0
2012-2104 Michigan Technological University
Supported in part by NSF grants: DUE-1140512, DUE-1245310 and IIS-1319363
Developer: Man Wang
Advisors:Dr. Steve Carr, Dr. Jean Mayo, Dr. Ching-Kuang Shene and Dr. Chaoli Wang
'''
'''
Created on Jan 23, 2012

@author: yifli
'''
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from Ui_QueryWindow import Ui_Form
from QueryOutput import QueryOutput
from commonFunction import Functions
import string
import re

class QueryWindow(QWidget):
    # file name, file type
    animateQuery0 = pyqtSignal(str, QGraphicsItem)
    # file name, file type, domains that can execute this file, types these domains can access, filenodes
    animateQuery1 = pyqtSignal(str, QGraphicsItem, list, set, list)
    # file name, access mode, file type, domains that can execute this file, types these domains can access in the mode, filenodes
    animateQuery2 = pyqtSignal(str, str, QGraphicsItem, list, set, list)
    # domain, mode, types, files 
    animateQuery3 = pyqtSignal(QGraphicsItem, str, set, list)
    # binary, file, mode, type of binary, type of file, domains that can execute the binary, intermediate domains
    animateQuery4 = pyqtSignal(str, str, str, QGraphicsItem, QGraphicsItem, list, set)
    # file, file type, domains that can execute this file
    animateQuery5 = pyqtSignal(str, QGraphicsItem, list)
    # file, access mode, file type, domains 
    animateQuery6 = pyqtSignal(str, str, QGraphicsItem, list)
    # fileNodes
    animateQuery7 = pyqtSignal(list)
    # mode, type file map
    animateQuery8 = pyqtSignal(str, dict)
    # file name, success, domain node, file type node, domain-type edge, default type node, file node
    animateQuery9 = pyqtSignal(str, bool, QGraphicsItem, QGraphicsItem, QGraphicsItem, QGraphicsItem, QGraphicsItem)
    # file name, success, domain node, file type node, edge, resulting domains
    animateQuery10 = pyqtSignal(str, bool, QGraphicsItem, QGraphicsItem, QGraphicsItem, list)
    
    def __init__(self, scene, parent = None):
        QWidget.__init__(self, parent)
        self.scene = scene
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.queryResultTextEdit = QueryOutput(scene,self)
        self.ui.runQueryLayout.addWidget(self.queryResultTextEdit)
        self.setLayout(self.ui.verticalLayout)
        self.ui.queryTypeGroupBox.setLayout(self.ui.queryTypeLayout)
        self.ui.queryInputGroupBox.setLayout(self.ui.queryInputLayout)
        self.ui.runQueryGroupBox.setLayout(self.ui.runQueryLayout)
    
        self.ui.queryListWidget.addItem('What is the powerset of the set of all categories')
        self.ui.queryListWidget.addItem('What are all possible levels')
        self.ui.queryListWidget.addItem('What levels can be read by a subject at a certain level')
        self.ui.queryListWidget.addItem('What levels can be written by a subject at a certain level')
        self.ui.queryListWidget.addItem('Can a subject at a certain level read or write an object at a certain level')
        self.ui.queryListWidget.addItem('What are the direct predecessors of a certain level')
        self.ui.queryListWidget.addItem('What are the direct successors of a certain level')
        self.ui.queryListWidget.addItem('Do subjects at the specified security level have access to the specified object')

        self.ui.queryListWidget.setCurrentRow(0)
        self.changeQueryInput()
        
        self.ui.queryListWidget.currentRowChanged.connect(self.changeQueryInput)
        self.ui.runQueryButton.clicked.connect(self.runQuery)
        self.ui.clearButton.clicked.connect(self.queryResultClear)
        
        self.animationEnabled = True
        
        self.count = 0
        self.prevCursor = None
    
    def queryResultClear(self):
        self.queryResultTextEdit.clear()
        self.scene.setAllEdgesNothighlighted()
        
    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Enter:
            self.runQuery()
    
    def clearAllInputspace(self):
        self.ui.file1LineEdit.clear()
        self.ui.file2LineEdit.clear()
    
    def changeQueryInput(self):
        self.clearAllInputspace()
        current = self.ui.queryListWidget.currentRow()
        if current == 2:
            '''
            the input format should be 'clearance, set(1,2,3) or clearance, (1,2,3)'
            '''
            self.ui.queryInputGroupBox.setVisible(True)
            self.ui.file1Label.setVisible(True)
            #self.ui.file1LineEdit = QCustomLineEdit(self.scene.main)
            self.ui.file1LineEdit.setVisible(True)
            self.ui.file1LineEdit.setEnabled(True)
            self.ui.file1LineEdit.setText('clearance,(1,2)')
            self.ui.file1LineEdit.isPlaceHolderActive = True
            self.ui.file1LineEdit.setStyleSheet("QCustomLineEdit{color: gray;}")
            self.ui.file1LineEdit.setCursorPosition(0)
#            self.ui.file1LineEdit.setPlaceholderText('clearance,(1,2)')
#            self.ui.file1LineEdit.placeHolderText = 'clearance,(1,2)'
            self.ui.file1Label.setText('Subject Level:')
            self.ui.file1Label.adjustSize()
            self.ui.file1Label.setToolTip('Input a security level, such as "clearance,(1,2)"')
            self.ui.file2Label.setVisible(False)
            self.ui.file2LineEdit.setVisible(False)
            self.ui.modeLabel.setVisible(False)
            self.ui.accessModeComboBox.setVisible(False)
            self.ui.domainLabel.setVisible(False)
            self.ui.domainComboBox.setVisible(False)
        elif current == 3:
            self.ui.queryInputGroupBox.setVisible(True)
            self.ui.file1Label.setVisible(True)
            self.ui.file1LineEdit.setVisible(True)
            self.ui.file1LineEdit.setText('clearance,(1,2)')
            self.ui.file1LineEdit.isPlaceHolderActive = True
            self.ui.file1LineEdit.setStyleSheet("QCustomLineEdit{color: gray;}")
            self.ui.file1LineEdit.setCursorPosition(0)
            self.ui.file1Label.setText('Subject Level:')
            self.ui.file1Label.adjustSize()
            self.ui.file1Label.setToolTip('Input a security level, such as "clearance,(1,2)"')
            self.ui.file2Label.setVisible(False)
            self.ui.file2LineEdit.setVisible(False)
            self.ui.modeLabel.setVisible(False)
            self.ui.accessModeComboBox.setVisible(False)
            self.ui.domainLabel.setVisible(False)
            self.ui.domainComboBox.setVisible(False)
        elif current == 4:
            self.ui.queryInputGroupBox.setVisible(True)
            self.ui.file1Label.setVisible(True)
            self.ui.file1LineEdit.setVisible(True)
            self.ui.file1LineEdit.setText('clearance,(1,2)')
            self.ui.file1LineEdit.isPlaceHolderActive = True       #// Member varible..
            self.ui.file1LineEdit.setStyleSheet("QCustomLineEdit{color: gray;}")
            self.ui.file1LineEdit.setCursorPosition(0)
            self.ui.file1Label.setText('Subject Level:')
            self.ui.file1Label.adjustSize()
            self.ui.file2Label.setVisible(True)
            self.ui.file1Label.setToolTip('Input a security level, such as "clearance,(1,2)"')
            self.ui.file2Label.setText('Object Level:')
            self.ui.file2Label.setToolTip('Input a security level, such as "clearance,(1,2)"')
            self.ui.file2Label.adjustSize()
            self.ui.file2LineEdit.setVisible(True)
            self.ui.file2LineEdit.setText('clearance,(1,2)')
            self.ui.file2LineEdit.isPlaceHolderActive = True
            self.ui.file2LineEdit.setStyleSheet("QCustomLineEdit{color: gray;}")
            self.ui.file2LineEdit.setCursorPosition(0)
            self.ui.modeLabel.setVisible(False)
            self.ui.accessModeComboBox.setVisible(False)
            self.ui.domainLabel.setVisible(False)
            self.ui.domainComboBox.setVisible(False)
        elif current == 0:
            self.ui.queryInputGroupBox.setVisible(False)
            self.ui.file1Label.setVisible(False)
            self.ui.file1LineEdit.setVisible(False)
            self.ui.file2Label.setVisible(False)
            self.ui.file2LineEdit.setVisible(False)
            self.ui.modeLabel.setVisible(False)
            self.ui.accessModeComboBox.setVisible(False)
            self.ui.domainLabel.setVisible(False)
            self.ui.domainComboBox.setVisible(False)
        elif current == 1:
            self.ui.queryInputGroupBox.setVisible(False)
            self.ui.file1Label.setVisible(False)
            self.ui.file1LineEdit.setVisible(False)
            self.ui.file2Label.setVisible(False)
            self.ui.file2LineEdit.setVisible(False)
            self.ui.modeLabel.setVisible(False)
            self.ui.accessModeComboBox.setVisible(False)
            self.ui.domainLabel.setVisible(False)
            self.ui.domainComboBox.setVisible(False)
        elif current == 5 or current == 6:
            self.ui.queryInputGroupBox.setVisible(True)
            self.ui.file1Label.setVisible(True)
            self.ui.file1LineEdit.setVisible(True)
            self.ui.file1LineEdit.setText('clearance,(1,2)')
            self.ui.file1LineEdit.isPlaceHolderActive = True
            self.ui.file1LineEdit.setStyleSheet("QCustomLineEdit{color: gray;}")
            self.ui.file1LineEdit.setCursorPosition(0)
            self.ui.file1Label.setText('Security Level:')
            self.ui.file1Label.setToolTip('Format: "clearance,(1,2)"')
            self.ui.file1Label.adjustSize()
            self.ui.file2Label.setVisible(False)
            self.ui.file2LineEdit.setVisible(False)
            self.ui.modeLabel.setVisible(False)
            self.ui.accessModeComboBox.setVisible(False)
            self.ui.domainLabel.setVisible(False)
            self.ui.domainComboBox.setVisible(False)
        elif current == 7:
            self.ui.queryInputGroupBox.setVisible(True)
            self.ui.file1Label.setVisible(True)
            self.ui.file1LineEdit.setVisible(True)
            self.ui.file1LineEdit.setText('clearance,(1,2)')
            self.ui.file1LineEdit.isPlaceHolderActive = True
            self.ui.file1LineEdit.setStyleSheet("QCustomLineEdit{color: gray;}")
            self.ui.file1LineEdit.setCursorPosition(0)
            self.ui.file1Label.setText('Security Level:')
            self.ui.file1Label.setToolTip('Format: "clearance,(1,2)"')
            self.ui.file1Label.adjustSize()
            self.ui.file2Label.setVisible(True)
            self.ui.file2LineEdit.setVisible(True)
            self.ui.file2Label.setText('Object:')
            self.ui.file2Label.setToolTip('Input an object, such as "/directory"')
            self.ui.file2Label.adjustSize()
            self.ui.file2LineEdit.setText('a file path or directory')
            self.ui.file2LineEdit.isPlaceHolderActive = True
            self.ui.file2LineEdit.setStyleSheet("QCustomLineEdit{color: gray;}")
            self.ui.file2LineEdit.setCursorPosition(0)
            self.ui.modeLabel.setVisible(False)
            self.ui.accessModeComboBox.setVisible(False)
            self.ui.domainLabel.setVisible(False)
            self.ui.domainComboBox.setVisible(False)
        
    def setOutputHighlight(self):
        lineCnt = self.queryResultTextEdit.toPlainText().count('\n')
        cursor = QTextCursor(self.queryResultTextEdit.textCursor())
        blockFormat = QTextBlockFormat(cursor.blockFormat())
        blockFormat.setBackground(QColor(qRgba(187,255,255, 10)))#155,246,143,128)))
        blockFormat.setNonBreakableLines(True)
        blockFormat.setPageBreakPolicy(QTextFormat.PageBreak_AlwaysBefore)
        cursor.setBlockFormat(blockFormat)
        it = QTextBlock.iterator(cursor.block().begin())
        while not it.atEnd():
            charFormat = QTextCharFormat(it.fragment().charFormat())
            #charFormat.setFont(QFont(QFont.Bold))
            tempCursor = QTextCursor(cursor)
            tempCursor.setPosition(it.fragment().position())
            tempCursor.setPosition(it.fragment().position() + it.fragment().length(), QTextCursor.KeepAnchor)
            tempCursor.setCharFormat(charFormat)
            self.count+=1
            
    def resetOutputText(self):
        cursor = QTextCursor(self.queryResultTextEdit.textCursor())
        blockFormat = QTextBlockFormat(cursor.blockFormat())
        blockFormat.setBackground(QColor("white"))
        blockFormat.setNonBreakableLines(True)
        blockFormat.setPageBreakPolicy(QTextFormat.PageBreak_AlwaysBefore)
        cursor.setBlockFormat(blockFormat)
        it = QTextBlock.iterator(cursor.block().begin())
        while it < self.prevCursor+1:
            charFormat = QTextCharFormat(it.fragment().charFormat())
            tempCursor = QTextCursor(cursor)
            tempCursor.setPosition(it.fragment().position())
            tempCursor.setPosition(it.fragment().position() + it.fragment().length(), QTextCursor.KeepAnchor)
            tempCursor.setCharFormat(charFormat)
            it+=1
        '''
        p = QPalette(self.queryResultTextEdit.palette())
        p.setPaletteBackgroundColor(QPalette.Base, QColor(255, 255, 255))
        self.queryResultTextEdit.setPalette(p)
        '''
        self.queryResultTextEdit.appendPlainText(self.prevText)
        self.cursor = cursor

    def validSecurityName(self, name):
        p=re.compile('^[a-zA-Z0-9]+,\(([0-9](,[0-9]+)*)?\)$')
        if p.match(name) is None:
            return False
        lenCate = len(self.scene.categories)
        clr, flgClr, cate = self.getClrCateFromLevel(name)
        if clr not in self.scene.clearances:
            return False
        if cate != ['']:
            for c in cate:
                numc=(int)(c)
                if numc > lenCate or numc <0:
                    return False
        return True

    def getClrFlg(self, clearance):
        for i in xrange(0, len(self.scene.clearances)):
            if self.scene.clearances[i] == clearance:
                return i
            
    def getCateSetFromString(self, cate):
        tempCate = cate[cate.find('(')+1:cate.find(')')].split(',')
        cateSet = set(tempCate)
        return cateSet,tempCate
    
    def getClrCateFromLevel(self, securityLevel):
        clr = securityLevel[:securityLevel.find(',')]
        flgClr = self.getClrFlg(clr)
        cateSet, cate = self.getCateSetFromString(securityLevel)
        return clr, flgClr, cate
        
    def getClrcateOfUser(self, username):
        for u in self.scene.main.ioHelper.userNodes:
            if u.name == username:
                clrNode = u.clrNode
                return clrNode.clearance, clrNode.flgClr, set(clrNode.category)
        return None, None, None
    
    def getClrcateOfObj(self, objname):
        for t in self.scene.main.ioHelper.typeNodes:
            if objname in t.dir:
                return t.clearance, self.getClrFlg(t.clearance), set(t.category)
        return None, -1, set('')
        
    def findReadableNodes(self, clr, cate, securityLevel):
        readableNodes = ''
        securityLevel = securityLevel.replace(' ', '')
        securityLevel = securityLevel[securityLevel.find(',')+1:]
        #if len(self.scene.items()) != 0:
        for level in self.scene.NdsLevels.values():
            for item in level:
                #if item in self.scene.items():
                Functions.computeCateNum(item,self.scene.categories)
                if item.flgClr == clr and item.categoryNumStr == securityLevel:
                    node = item
                    self.scene.growLevelLayout.getReadableNodes(node)
                if self.canRead(clr, cate, item):
                    #readableNodes += '\n('+item.clearance+',set'+item.categoryNumStr+')\n'
                    itemCatename = '['+Functions.getCateStrWithDelimiter(item.category, ',')+']'
                    readableNodes += '\n'+item.clearance+'\t'+itemCatename+'\n'
        return readableNodes
        
    def findWritableNodes(self, clr, cate, securityLevel):
        writableNodes = ''
        securityLevel = securityLevel.replace(' ', '')
        securityLevel = securityLevel[securityLevel.find(',')+1:]
        #if len(self.scene.items()) != 0:
        for level in self.scene.NdsLevels.values():
            for item in level:
                #if item in self.scene.items():
                Functions.computeCateNum(item,self.scene.categories)
                if item.flgClr == clr and item.categoryNumStr == securityLevel:
                    node = item
                    self.scene.growLevelLayout.getWritableNodes(node)
                if self.canWrite(clr, cate, item):
                    itemCatename = '['+Functions.getCateStrWithDelimiter(item.category, ',')+']'
                    writableNodes += '\n'+item.clearance+'\t'+itemCatename+'\n'
        return writableNodes
    
    def canRead(self, subClr, subCate, item):
        if item.flgClr <= subClr:
            itemCateSet, tempCateList = self.getCateSetFromString(item.categoryNumStr)
            subCateSet = set(subCate)
            if itemCateSet.issubset(subCateSet) or itemCateSet == set(['']):
                return True
        return False
            
    def canWrite(self, subClr, subCate, item):
        if item.flgClr >= subClr:
            itemCateSet, tempCateList = self.getCateSetFromString(item.categoryNumStr)
            if set(subCate).issubset(itemCateSet) or subCate == ['']:
                return True
        return False
        
    def canReadSL(self, clrFlg1, cateSet1, clrFlg2, cateSet2):
        if clrFlg1 >= clrFlg2:
            if cateSet2.issubset(cateSet1) or cateSet2 == set(['']):
                return True
        return False
        
    def canWriteSL(self, clrFlg1, cateSet1, clrFlg2, cateSet2):
        if clrFlg1 <= clrFlg2:
            if cateSet1.issubset(cateSet2) or cateSet1 == set(['']):
                return True
        return False
    
    def runQuery0(self):
        '''
        What is the powerset of the set of all categories
        '''
        output = ''
        clearance = self.scene.latticeNodes[0].clearance
        for V in self.scene.latticeNodes:
            if V.clearance == clearance:
                name = V.name[V.name.find('(')+1: V.name.rfind(')')]
                namelist = name.split('set')
                temp = namelist[1]
                category = '['+temp[temp.find('[')+1:temp.rfind(']')]+']'
                tmpclearanceLevel = category+'\n'
                output += '\n'+tmpclearanceLevel+'\n'
            else:
                break
        self.queryResultTextEdit.appendPlainText('[query 0] What is the powerset of the set of all categories')
        self.queryResultTextEdit.appendPlainText(output)
        
    def runQuery1(self):
        '''
        What are all possible levels
        '''
        output = ''
        for V in self.scene.latticeNodes:
            name = V.name[V.name.find('(')+1: V.name.rfind(')')]
            namelist = name.split('set')
            clearance = namelist[0].strip(',')
            temp = namelist[1]
            category = '['+temp[temp.find('[')+1:temp.rfind(']')]+']'
            tmpclearanceLevel = clearance+'\t'
            tmpclearanceLevel += category+'\n'
            self.clearanceLevel=tmpclearanceLevel
            output += self.clearanceLevel+'\n'
        self.queryResultTextEdit.appendPlainText('[query 1] What are all possible levels')
        self.queryResultTextEdit.appendPlainText(output)
        
    def runQuery2(self, subjLevel):
        '''
        What levels can be read by a subject at level
        '''
        self.clr, self.flgClr, self.cate = self.getClrCateFromLevel(subjLevel)
        readableNodes = self.findReadableNodes(self.flgClr, self.cate, subjLevel)
        self.queryResultTextEdit.appendPlainText('[query 2] What levels can be read by a subject at level (%s)' % subjLevel)
        self.queryResultTextEdit.appendPlainText(readableNodes)
        
    def runQuery3(self, subjLevel):
        '''
        What levels can be written by a subject at level
        '''
        self.clr, self.flgClr, self.cate = self.getClrCateFromLevel(subjLevel)
        writableNodes = self.findWritableNodes(self.flgClr, self.cate, subjLevel)
        self.queryResultTextEdit.appendPlainText('[query 3] What levels can be written by a subject at level (%s)' % subjLevel)
        self.queryResultTextEdit.appendPlainText(writableNodes)
        
    def runQuery4(self, subjLevel, objLevel):
        '''
        Can a subject at a certain level read or write an object at a certain level
        '''
        output = 'The subject can not read or write the object'
        self.clr, self.flgClr, self.cate = self.getClrCateFromLevel(subjLevel)
        objClr, objFlgclr, objCate =  self.getClrCateFromLevel(objLevel)
        objCateSet = set(objCate)
        cateSet = set(self.cate)
        if (self.flgClr>objFlgclr or self.flgClr == objFlgclr) and (objCateSet.issubset(cateSet) or objCateSet == set([''])):
            output = 'The subject can read but can not write the object'
        if (self.flgClr<objFlgclr or self.flgClr == objFlgclr) and cateSet.issubset(objCateSet):
            output = 'The subject can write but can not read the object'
        if self.flgClr == objFlgclr and cateSet == objCateSet:
            output = 'The subject can read and write the object'
        self.queryResultTextEdit.appendPlainText('[query 4] Can a subject at level (%s) read or write an object at level (%s)' % (subjLevel, objLevel))
        output = '\n'+output+'\n'
        self.queryResultTextEdit.appendPlainText(output)
                   
    def runQuery5(self, subjLevel):
        '''
        What levels are direct predecessors of a level
        '''
        clr, flgClr, cate = self.getClrCateFromLevel(subjLevel)
        cate = Functions.fromCateNum2Name(cate, self.scene.categories)
        cate = set(cate)
        preds = []
        for n in self.scene.latticeNodes:
            if n.clearance == clr and set(n.category) == cate:
                preds = n.parent
                break
        output=''
        for n in preds:
            catename = 'set('+Functions.getCateStrWithDelimiter(n.category, ',')+')'
            output += '\n'+n.clearance+'\t'+catename+'\n'
        if output == '':
            output = '\nNone\n'
        self.queryResultTextEdit.appendPlainText('[query 5] What levels are the direct predecessors of level (%s)' % subjLevel)
        self.queryResultTextEdit.appendPlainText(output)

    def runQuery6(self, subjLevel):
        '''
        What levels are direct successors of a level
        '''
        clr, flgClr, cate = self.getClrCateFromLevel(subjLevel)
        cate = Functions.fromCateNum2Name(cate, self.scene.categories)
        cate = set(cate)
        succes = []
        for n in self.scene.latticeNodes:
            if n.clearance == clr and set(n.category) == cate:
                succes = n.children
                break
        output=''
        for n in succes:
            catename = '['+Functions.getCateStrWithDelimiter(n.category, ',')+']'
            output += '\n'+n.clearance+'\t'+catename+'\n'
        if output == '':
            output = '\nNone\n'
        self.queryResultTextEdit.appendPlainText('[query 6] What levels are the direct successors of level (%s)' % subjLevel)
        self.queryResultTextEdit.appendPlainText(output)
          
    def runQuery7(self, securitylevel, objname):
        '''
        Whether a security level has access to an object
        '''
        name = Functions.securityLevelName(securitylevel)
        output = 'Subjects at security level "'+name+'" '
        oClr, oFlgClr, oCateSet = self.getClrcateOfObj(objname)
        SLFlgClr = self.getClrFlg(securitylevel.clearance)
        readable = self.canReadSL(SLFlgClr, securitylevel.categoryset, oFlgClr, oCateSet)
        writable = self.canWriteSL(SLFlgClr, securitylevel.categoryset, oFlgClr, oCateSet)
        if readable and writable:
            output+= 'can read and write object "'+objname+'"'
        elif readable:
            output+= 'can read object "'+objname+'"'
        elif writable:
            output+= 'can write object "'+objname+'"'
        else:
            output+= 'can neither read nor write object "'+objname+'"'
        self.queryResultTextEdit.appendPlainText('[query 7] Whether subjects at security level (%s) have access to object (%s)' % (securitylevel, objname))
        self.queryResultTextEdit.appendPlainText(output)
        
    def checkClearanceNodeNameFormat(self, name):
        name = name.replace(' ', '')
        if not self.validSecurityName(name):
            QMessageBox.critical(self, 'Error', 
                                 '%s is not a valid file name\n Input format: clearance,(1,2)' % name)
            return False
        return True
    
    def highlightLastAnswer(self):
        self.prevText = self.queryResultTextEdit.toPlainText()
        self.prevCursor = self.prevText.count('\n')
        self.queryResultTextEdit.clear()
        self.resetOutputText()
        self.setOutputHighlight()
        
    def runQuery(self, paras):
        Functions.checkExistInfo(self.scene.main)
        if self.scene.main.hasInfo:
            current = self.ui.queryListWidget.currentRow()
            self.scene.setAllEdgesNothighlighted()
            self.scene.mode = self.scene.Query
            if paras:
                self.getQueryResultFromCommandLineInput(current, paras)
            else:
                self.getQueryResult(current)
            
    def setQueryForQuestion(self, questionId):
        self.ui.queryListWidget.setCurrentRow(questionId)
        self.changeQueryInput()
        
    def getQueryResult(self, current):
        self.scene.latticeNodes = self.scene.main.ioHelper.latticeNodes
        self.highlightLastAnswer()
        if current == 0:
            self.runQuery0()
        elif current == 1:
            self.runQuery1()
        elif current == 2:
            filename = string.strip(str(self.ui.file1LineEdit.text()))
            if self.checkClearanceNodeNameFormat(filename):
                self.runQuery2(filename)
        elif current == 3:
            filename = string.strip(str(self.ui.file1LineEdit.text()))
            if self.checkClearanceNodeNameFormat(filename):
                self.runQuery3(filename)
        elif current == 4:
            filename = string.strip(str(self.ui.file1LineEdit.text()))
            filename2 = string.strip(str(self.ui.file2LineEdit.text()))
            if (self.checkClearanceNodeNameFormat(filename) and self.checkClearanceNodeNameFormat(filename2)):
                self.runQuery4(filename, filename2)
        elif current == 5:
            filename = string.strip(str(self.ui.file1LineEdit.text()))
            if self.checkClearanceNodeNameFormat(filename):
                self.runQuery5(filename)
        elif current == 6:
            filename = string.strip(str(self.ui.file1LineEdit.text()))
            if self.checkClearanceNodeNameFormat(filename):
                self.runQuery6(filename)
        elif current == 7:
            filename = string.strip(str(self.ui.file1LineEdit.text()))
            objname = string.strip(str(self.ui.file2LineEdit.text()))
            if self.checkClearanceNodeNameFormat(filename):
                self.runQuery7(filename, objname)
                    
    def getQueryResultFromCommandLineInput(self, queryId, paras):
        self.scene.latticeNodes = self.scene.main.ioHelper.latticeNodes
        counter = 0
        self.scene.main.hasInfo = True
        self.highlightLastAnswer()
        if queryId == 0:
            self.runQuery0()
        elif queryId == 1:
            self.runQuery1()
        elif queryId == 2:
            subjLevel = paras[counter]
            self.runQuery2(subjLevel)
        elif queryId == 3:
            subjLevel = paras[counter]
            self.runQuery3(subjLevel)
        elif queryId == 4:
            subjLevel = paras[counter]
            counter+=1
            objLevel = paras[counter]
            self.runQuery4(subjLevel, objLevel)
        elif queryId == 5:
            subjLevel = paras[counter]
            self.runQuery5(subjLevel)
        elif queryId == 6:
            subjLevel = paras[counter]
            self.runQuery6(subjLevel)
        elif queryId == 7:
            securitylevel = paras[counter]
            counter+=1
            objname = paras[counter]
            self.runQuery7(securitylevel, objname)