Esempio n. 1
0
 def createAditionalParameters(self, count, enableIgnoreOption):
     """
     Creates aditional parameters upon creation of an attribute item
     """
     #editable item
     comboItem = QComboBox()
     comboItem.addItems([self.tr('Yes'), self.tr('No')])
     self.attributeTableWidget.setCellWidget(count, 2, comboItem)
     #ignored item
     comboItem = QComboBox()
     comboItem.addItems([self.tr('No'), self.tr('Yes')])
     comboItem.setEnabled(enableIgnoreOption)
     self.attributeTableWidget.setCellWidget(count, 3, comboItem)
Esempio n. 2
0
    def createDialog(self):
        """
        Create qt dialog
        """
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setStyleSheet("""QDialogButtonBox { 
            dialogbuttonbox-buttons-have-icons: 1;
            dialog-ok-icon: url(:/ok.png);
            dialog-cancel-icon: url(:/test-close-black.png);
        }""")
        self.buttonBox.setStandardButtons(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel)

        self.stepIdLabel = QLabel("%s" % self.stepId)
        stepTitleLayout = QGridLayout()

        # mandatory args
        self.argsLayout = QGridLayout()
        for i in xrange(len(self.stepData['obj'])):
            self.argsLayout.addWidget(QLabel(self.stepData['obj'][i]['name']),
                                      i, 0)
            typeParam = QRadioButton(self.stepData['obj'][i]['type'])
            typeParam.setEnabled(False)
            self.argsLayout.addWidget(typeParam, i, 1)
            if self.stepData['obj'][i]['type'] == 'string':
                typeParam.setChecked(True)
                self.argsLayout.addWidget(QTextEdit(), i, 2)
            if self.stepData['obj'][i]['type'] == "boolean":
                boolCombo = QComboBox()
                valBool = ["True", "False"]
                boolCombo.addItems(valBool)
                boolCombo.setEnabled(
                    False)  # feature not yet available in abstract mode
                typeParam.setChecked(True)
                self.argsLayout.addWidget(boolCombo, i, 2)

        mainLayout = QVBoxLayout()
        mainLayout.addLayout(stepTitleLayout)
        mainLayout.addLayout(self.argsLayout)
        mainLayout.addWidget(self.buttonBox)
        self.setLayout(mainLayout)

        self.setWindowTitle(self.tr("Step configuration"))
        self.resize(450, 250)
        self.center()
 def createGUIElements(self):
     ''' Build the GUI based on the parameters for the tool '''
     for i, param in enumerate(self.tooltypearray):
         # print 'creatgui element %d, %s' %(i, param)
         #Swap in the passed params if they exist... loop through each passed
         #param and see if it matches... if so swap it in
         if self.optional_params.has_key(str(param[0])):
             param[2] = self.optional_params[str(param[0])]
         #print "Key: %s , Val: %s" % (param[0],param[1])
         widgetTemp = QWidget(self.variableBox)
         widgetTemp.setObjectName(QString("test_widget").append(QString(i)))
         self.test_widget.append(widgetTemp)
         hlayout = QHBoxLayout(widgetTemp)
         self.hboxlayout.append(hlayout)
         hlayout.setMargin(4)
         hlayout.setSpacing(4)
         hlayout.setObjectName(QString("hboxlayout").append(QString(i)))
         test_text = QLabel(widgetTemp)
         self.test_text.append(test_text)
         test_text.setObjectName(QString("test_text").append(QString(i)))
         paramName = param[0].strip()
         if param[2].strip() == "Required":
             palette = test_text.palette()
             palette.setColor(QPalette.WindowText,Qt.red)
             test_text.setPalette(palette)
         test_text.setText(paramName)
         test_text_type = QLabel(widgetTemp)
         self.test_text_type.append(test_text_type)
         test_text_type.setObjectName(QString("test_text_type").append(QString(i)))
         paramName = param[1].strip()
         test_text_type.setText(QString("(").append(paramName).append(QString(")")))
         hlayout.addWidget(test_text)
         hlayout.addWidget(test_text_type)
         if param[1] == 'db_connection_hook':
             test_line = QComboBox(widgetTemp)
             db_connection_choices = get_db_connection_names()
             for i in db_connection_choices:
                 test_line.addItem(QString(i))
             self.test_line.append(test_line)
             test_line.setEnabled(True)
             test_line.setMinimumSize(QSize(200,0))
             test_line.setObjectName(QString("test_line").append(QString(i)))
             index = test_line.findText(param[2], Qt.MatchExactly)
             test_line.setCurrentIndex(index)
         else:
             test_line = QLineEdit(widgetTemp)
             self.test_line.append(test_line)
             test_line.setEnabled(True)
             test_line.setMinimumSize(QSize(200,0))
             test_line.setObjectName(QString("test_line").append(QString(i)))
             test_line.setText(QString(param[2]))
         hlayout.addWidget(test_line)
         # If we have a dir_path or file_path add a select button
         if (paramName == QString('dir_path')) or (paramName == QString('file_path')):
             pbnSelect = QPushButton(widgetTemp)
             pbnSelect.setObjectName(QString('pbnSelect').append(QString(i)))
             pbnSelect.setText(QString("Select..."))
             pbnSelectDelegate = FileDialogSignal(typeName=paramName,param=test_line)
             QObject.connect(pbnSelectDelegate.o, SIGNAL("buttonPressed(PyQt_PyObject,PyQt_PyObject)"),
                             self.on_pbnSelect_released)
             QObject.connect(pbnSelect, SIGNAL("released()"), pbnSelectDelegate.relayButtonSignal)
             self.test_line_delegates.append(pbnSelectDelegate)
             self.test_line_buttons.append(pbnSelect)
             hlayout.addWidget(pbnSelect)
         self.vboxlayout.addWidget(widgetTemp)
         self.adjustSize()
     # Jesse adding help text from opusHelp
     tool_path = self.optional_params.get('tool_path','')
     try:
         exec_stmt = 'from %s.%s import opusHelp' % (tool_path, self.module_name)
         exec exec_stmt
         help = QString(opusHelp())
         self.toolhelpEdit.insertPlainText(help)
     except Exception, e:
         help = 'could not find opusHelp function in tool module'
         self.toolhelpEdit.insertPlainText(help)
Esempio n. 4
0
class LDSControls(QFrame):
        
    STATIC_IMG = ('error_static.png','linz_static.png','busy_static.png','clean_static.png')
    ANIM_IMG   = ('error.gif','linz.gif','layer.gif','clean.gif')
    
    IMG_SPEED  = 100
    IMG_WIDTH  = 64
    IMG_HEIGHT = 64
    
    MAX_WD = 450
    
    GD_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../../bin/gdal/gdal-data'))
    STATUS = LU.enum('ERROR','IDLE','BUSY','CLEAN')
    
    def __init__(self,parent):
        super(LDSControls, self).__init__()
        self.parent = parent
        self.initConf()
        self.initEPSG()
        self.initUI()
        
    def initConf(self):
        '''Read files in conf dir ending in conf'''
        self.cflist = ConfigInitialiser.getConfFiles()
        #self.imgset = self.STATIC_IMG if ConfigWrapper().readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        #self.imgset = self.STATIC_IMG if self.parent.confconn.tp.src.confwrap.readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        sep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.SRCNAME,self.parent.confconn.uconf)
        self.imgset = self.STATIC_IMG if sep.confwrap.readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        self.parent.confconn.reg.closeEndPoint(self.parent.confconn.SRCNAME)
        
    def initEPSG(self):
        '''Read GDAL EPSG files, splitting by NZ(RSR) and RestOfTheWorld'''

        gcsf = gdal.FindFile('gdal','gcs.csv') 
        if not gcsf:
            gcsf = os.path.join(self.GD_PATH,'gcs.csv')
        pcsf = gdal.FindFile('gdal','pcs.csv') 
        if not pcsf: 
            pcsf = os.path.join(self.GD_PATH,'pcs.csv')
        gcs = ConfigInitialiser.readCSV(gcsf)
        pcs = ConfigInitialiser.readCSV(pcsf)

        self.nzlsr = [(e[0],e[0]+' - '+e[3]) for e in gcs if 'NZGD'     in e[1] or  'RSRGD'     in e[1]] \
                   + [(e[0],e[0]+' - '+e[1]) for e in pcs if 'NZGD'     in e[1] or  'RSRGD'     in e[1]]
        self.rowsr = [(e[0],e[0]+' - '+e[3]) for e in gcs if 'NZGD' not in e[1] and 'RSRGD' not in e[1]] \
                   + [(e[0],e[0]+' - '+e[1]) for e in pcs if 'NZGD' not in e[1] and 'RSRGD' not in e[1]]
                   
                   
    def initUI(self):
        
        # 0      1          2       3       4       5      6    7    8
        #'destname','lgselect','layer','uconf','group','epsg','fd','td','int'
        
        #self.rdest,rlgselect,self.rlayer,ruconf,self.rgroup,repsg,rfd,rtd,rint = readlist 
        
        QToolTip.setFont(QFont('SansSerif', 10))
        
        #labels
        destLabel = QLabel('Destination')
        lgLabel = QLabel('Group/Layer')
        epsgLabel = QLabel('EPSG')
        fromDateLabel = QLabel('From Date')
        toDateLabel = QLabel('To Date')
        confLabel = QLabel('User Config')
        
        self.view = QLabel() 
        self.view.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.view.setAlignment(Qt.AlignCenter)

        self.confcombo = QComboBox(self)
        self.confcombo.setToolTip('Enter your user config name (file) here')
        self.confcombo.addItems(self.cflist)
        self.confcombo.setEditable(False)
        #self.confcombo.currentIndexChanged.connect(self.doLGEditUpdate)
        
        #combos
        self.lgcombo = QComboBox(self)
        self.lgcombo.setMaximumWidth(self.MAX_WD)
        self.lgcombo.setDuplicatesEnabled(False)
        #self.lgcombo.setInsertPolicy(QComboBox.InsertAlphabetically)#?doesnt seem to work
        self.lgcombo.setToolTip('Select either Layer or Group entry')
        self.lgcombo.setEditable(False)
        self.sepindex = None
        #self.updateLGValues()
        
        self.epsgcombo = QComboBox(self)
        self.epsgcombo.setMaximumWidth(self.MAX_WD)
        self.epsgcombo.setToolTip('Setting an EPSG number here determines the output SR of the layer')  
        self.epsgcombo.addItems([i[1] for i in self.nzlsr])
        self.epsgcombo.insertSeparator(len(self.nzlsr))
        self.epsgcombo.addItems([i[1] for i in self.rowsr])
        self.epsgcombo.setEditable(True)
        self.epsgcombo.setEnabled(False)
        
        self.destlist = self.getConfiguredDestinations()
        self.destcombo = QComboBox(self)
        self.destcombo.setToolTip('Choose the desired output type')   
        self.destcombo.setEditable(False)
        self.destcombo.addItems(self.destlist)

        #date selection
        self.fromdateedit = QDateEdit()
        self.fromdateedit.setCalendarPopup(True)
        self.fromdateedit.setEnabled(False)
        
        self.todateedit = QDateEdit()
        self.todateedit.setCalendarPopup(True)
        self.todateedit.setEnabled(False)
        
        #check boxes
        self.epsgenable = QCheckBox()
        self.epsgenable.setCheckState(False)
        self.epsgenable.clicked.connect(self.doEPSGEnable)       
        
        self.fromdateenable = QCheckBox()
        self.fromdateenable.setCheckState(False)
        self.fromdateenable.clicked.connect(self.doFromDateEnable)
        
        self.todateenable = QCheckBox()
        self.todateenable.setCheckState(False) 
        self.todateenable.clicked.connect(self.doToDateEnable)
        
        self.progressbar = QProgressBar()
        self.progressbar.setRange(0,100)
        self.progressbar.setVisible(True)
        self.progressbar.setMinimumWidth(self.MAX_WD)
        
        
        #buttons        
        self.initbutton = QPushButton("waiting")
        self.initbutton.setToolTip('Initialise the Layer Configuration')
        self.initbutton.clicked.connect(self.doInitClickAction)
        
        self.cleanbutton = QPushButton("Clean")
        self.cleanbutton.setToolTip('Clean the selected layer/group from local storage')
        self.cleanbutton.clicked.connect(self.doCleanClickAction)
        
        self.replicatebutton = QPushButton("Replicate")
        self.replicatebutton.setToolTip('Execute selected replication')
        self.replicatebutton.clicked.connect(self.doReplicateClickAction)
        
        self.cancelbutton = QPushButton("Close")
        self.cancelbutton.setToolTip('Close the LDS Replicate application')       
        self.cancelbutton.clicked.connect(self.parent.close)


        #set dialog values using GPR
        self.updateGUIValues(self.parent.gvs)
        
        #set onchange here otherwise we get circular initialisation
        self.destcombo.currentIndexChanged.connect(self.doDestChanged)
        self.confcombo.currentIndexChanged.connect(self.doConfChanged)
        self.lgcombo.currentIndexChanged.connect(self.doLGComboChanged)

        self.setStatus(self.STATUS.IDLE)
        
        #grid
        grid = QGridLayout()
        grid.setSpacing(10)
        
        
        #placement section ------------------------------------
        #---------+---------+--------+---------+--------
        # dest LB |         | dest DD
        # grp LB  |         | grp DD
        # conf LB |         | conf DD
        # epsg L  | epsg CB | epsg DD
        # f dt L  | f dt CB | f dt DD
        # t td L  | t td CB | t td DD
        # icon    |       <- progress ->
        # layer B | <- . -> |repl B  | clean B | close B 
        #---------+---------+--------+---------+--------

        grid.addWidget(destLabel, 1, 0)
        grid.addWidget(self.destcombo, 1, 2)

        #grid.addWidget(layerLabel, 2, 0)
        grid.addWidget(lgLabel, 2, 0)
        grid.addWidget(self.lgcombo, 2, 2)
        
        grid.addWidget(confLabel, 3, 0)
        grid.addWidget(self.confcombo, 3, 2)
        
        #grid.addWidget(groupLabel, 4, 0)
        #grid.addWidget(self.groupEdit, 4, 2)
        
        grid.addWidget(epsgLabel, 5, 0)
        grid.addWidget(self.epsgenable, 5, 1)
        grid.addWidget(self.epsgcombo, 5, 2)

        grid.addWidget(fromDateLabel, 6, 0)
        grid.addWidget(self.fromdateenable, 6, 1)
        grid.addWidget(self.fromdateedit, 6, 2)
        
        grid.addWidget(toDateLabel, 7, 0)
        grid.addWidget(self.todateenable, 7, 1)
        grid.addWidget(self.todateedit, 7, 2)
        
        hbox3 = QHBoxLayout()
        hbox3.addWidget(self.view) 
        hbox3.addStretch(1)
        hbox3.addWidget(self.progressbar)

        #hbox3.addLayout(vbox2)
        #hbox3.addLayout(vbox3)
        
        hbox4 = QHBoxLayout()
        hbox4.addWidget(self.initbutton)
        hbox4.addStretch(1)
        hbox4.addWidget(self.replicatebutton)
        hbox4.addWidget(self.cleanbutton)
        hbox4.addWidget(self.cancelbutton)
        

        vbox = QVBoxLayout()
        #vbox.addStretch(1)
        vbox.addLayout(grid)
        vbox.addLayout(hbox3)
        vbox.addLayout(hbox4)
        
        self.setLayout(vbox)  
       
    #def setProgress(self,pct):
    #    self.progressbar.setValue(pct)
        
    def setStatus(self,status,message='',tooltip=None):
        '''Sets indicator icon and statusbar message'''
        self.parent.statusbar.showMessage(message)
        self.parent.statusbar.setToolTip(tooltip if tooltip else '')

        #progress
        loc = os.path.abspath(os.path.join(IMG_LOC,self.imgset[status]))
        #loc = os.path.abspath(os.path.join(os.path.dirname(__file__),self.parent.IMG_LOC,self.imgset[status]))
        self.progressbar.setVisible(status in (self.STATUS.BUSY, self.STATUS.CLEAN))
        
        #icon
        anim = QMovie(loc, QByteArray(), self)
        anim.setScaledSize(QSize(self.IMG_WIDTH,self.IMG_HEIGHT))
        anim.setCacheMode(QMovie.CacheAll)
        anim.setSpeed(self.IMG_SPEED)
        self.view.clear()
        self.view.setMovie(anim)
        anim.start()

        self.view.repaint()
        QApplication.processEvents(QEventLoop.AllEvents)

    def mainWindowEnable(self,enable=True):
        cons = (self.lgcombo, self.confcombo, self.destcombo, 
                self.initbutton, self.replicatebutton, self.cleanbutton, self.cancelbutton,
                self.epsgenable,self.fromdateenable,self.todateenable,
                self.parent.menubar)
        for c in cons:
            c.setEnabled(enable)
            
        if enable:
            self.epsgcombo.setEnabled(self.epsgenable.checkState())
            self.fromdateedit.setEnabled(self.fromdateenable.checkState())
            self.todateedit.setEnabled(self.todateenable.checkState())
        else:
            self.epsgcombo.setEnabled(False)
            self.fromdateedit.setEnabled(False)
            self.todateedit.setEnabled(False)
   
        QApplication.restoreOverrideCursor() if enable else QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) 

    def refreshLGCombo(self):
        '''Re index LG combobox since a refreshLG call (new dest?) will usually mean new groups'''
        self.lgcombo.clear()
        self.lgcombo.addItems([i[2] for i in self.parent.confconn.lglist])
        #NOTE the separator consumes an index, if not clearing the combobox selectively remove the old sepindex (assumes g preceeds l)
        #if self.sepindex:
        #    self.lgcombo.removeItem(self.sepindex)
        self.sepindex = [i[0] for i in self.parent.confconn.lglist].count(LORG.GROUP)
        self.lgcombo.insertSeparator(self.sepindex)
        
    def updateLGValues(self,uconf,lgval,dest):
        '''Sets the values displayed in the Layer/Group combo'''
        #because we cant seem to sort combobox entries and want groups at the top, clear and re-add
        #TRACE#        
        #pdb.set_trace()
        sf = None
        try:
            self.parent.confconn.initConnections(uconf,lgval,dest)
        except Exception as e:
            sf=1
            ldslog.error('Error Updating UC Values. '+str(e))
            
        if sf:
            self.setStatus(self.STATUS.ERROR,'Error Updating UC Values', str(e))
        else:
            self.setStatus(self.STATUS.IDLE)
            
        self.refreshLGCombo()
        
    def centre(self):
        
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
        
    
    def gprParameters(self,rdest):
        '''Zip default and GPR values'''
        return [x if LU.assessNone(x) else y for x,y in zip(self.parent.gpr.readsec(rdest),self.parent.DEF_RVALS[1:])]
    
    def getLCE(self,ln):
        '''Read layer parameters'''
        dep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.destname,self.parent.confconn.uconf)
        #sep = self.parent.confconn.reg.openEndPoint('WFS',self.parent.confconn.uconf)
        self.parent.confconn.reg.setupLayerConfig(self.parent.confconn.tp,None,dep,initlc=False)
        lce = dep.getLayerConf().readLayerParameters(ln)
        #self.parent.confconn.reg.closeEndPoint('WFS')
        self.parent.confconn.reg.closeEndPoint(self.parent.confconn.destname)
        sep,dep = None,None
        return lce
    
    
    def doDestChanged(self):
        '''Read the destname parameter and fill dialog with matching GPR values'''
        rdest = str(self.destlist[self.destcombo.currentIndex()])
        rvals = self.gprParameters(rdest)
        self.updateGUIValues([rdest]+rvals)    
        
        
    def doConfChanged(self):
        '''Read the user conf parameter and fill dialog with matching GPR values'''
        rdest = str(self.destlist[self.destcombo.currentIndex()])
        rlg,_,rep,rfd,rtd = self.gprParameters(rdest)
        ruc = str(self.cflist[self.confcombo.currentIndex()])
        self.updateGUIValues((rdest,rlg,ruc,rep,rfd,rtd))
        
        
    def doLGComboChanged(self):
        '''Read the layer/group value and change epsg to layer or gpr match'''
        #get a matching LG entry and test whether its a layer or group
        #lgi = self.parent.confconn.getLayerGroupIndex(self.lgcombo.currentText().toUtf8().data())
        lgi = self.parent.confconn.getLayerGroupIndex(LQ.readWidgetText(self.lgcombo.currentText()))
        #lgi can be none if we init a new group, in which case we use the GPR value
        if lgi:
            lge = self.parent.confconn.lglist[lgi]
            lce = self.getLCE(lge[1]) if lge[0]==LORG.LAYER else None
        else:
            lce = None
        
        #look for filled layer conf epsg OR use prefs stored in gpr
        if lce and LU.assessNone(lce.epsg):
            epsgval = lce.epsg
        else:
            rdest = str(self.destlist[self.destcombo.currentIndex()])
            _,_,epsgval,_,_ = self.gprParameters(rdest)
        epsgindex = [i[0] for i in self.nzlsr+[(0,0)]+self.rowsr].index(epsgval)
        if self.epsgcombo.currentIndex() != epsgindex:
            self.epsgcombo.setCurrentIndex(int(epsgindex))

        
    def updateGUIValues(self,readlist):
        '''Fill dialog values from provided list'''
        #TODO. Remove circular references when setCurrentIndex() triggers do###Changed()
        #Read user input
        rdest,self.rlgval,ruconf,repsg,rfd,rtd = readlist
        
        #--------------------------------------------------------------------
        
        #Destination Menu
        selecteddest = LU.standardiseDriverNames(rdest)
        if selecteddest not in self.destlist:
            self.destlist = self.getConfiguredDestinations()
            self.destcombo.addItem(selecteddest)
        destindex = self.destlist.index(selecteddest) if selecteddest else 0
        
        if self.destcombo.currentIndex() != destindex:
            self.destcombo.setCurrentIndex(destindex)
        
        #InitButton
        self.initbutton.setText('Layer Select')
        
        #Config File
        confindex = 0
        if LU.assessNone(ruconf):
            ruconf = ruconf.split('.')[0]
            if ruconf not in self.cflist:
                self.cflist += [ruconf,]
                self.confcombo.addItem(ruconf)
            confindex = self.cflist.index(ruconf)
            
        if self.confcombo.currentIndex() != confindex:
            self.confcombo.setCurrentIndex(confindex)
        #self.confEdit.setText(ruconf if LU.assessNone(ruconf) else '')
        
        #Layer/Group Selection
        self.updateLGValues(ruconf,self.rlgval,rdest)
        lgindex = None
        if LU.assessNone(self.rlgval):
            #index of list value
            lgindex = self.parent.confconn.getLayerGroupIndex(self.rlgval,col=1)
            
        if LU.assessNone(lgindex):
            #advance by 1 for sep
            lgindex += 1 if lgindex>self.sepindex else 0 
        else:
            #using the separator index sets the combo to blank
            lgindex = self.sepindex
        if self.lgcombo.currentIndex() != lgindex:
            self.lgcombo.setCurrentIndex(lgindex)
        #self.doLGEditUpdate()
        
        #EPSG
        #                                user > layerconf
        #useepsg = LU.precedence(repsg, lce.epsg if lce else None, None)
        epsgindex = [i[0] for i in self.nzlsr+[(None,None)]+self.rowsr].index(repsg)
        if self.epsgcombo.currentIndex() != epsgindex:
            self.epsgcombo.setCurrentIndex(epsgindex)
            
        #epsgedit = self.epsgcombo.lineEdit()
        #epsgedit.setText([e[1] for e in self.nzlsr+self.rowsr if e[0]==repsg][0])
        
        #epsgedit.setText([e for e in self.nzlsr+self.rowsr if re.match('^\s*(\d+).*',e).group(1)==repsg][0])
        
        #To/From Dates
        if LU.assessNone(rfd):
            self.fromdateedit.setDate(QDate(int(rfd[0:4]),int(rfd[5:7]),int(rfd[8:10])))
        else:
            early = DataStore.EARLIEST_INIT_DATE
            self.fromdateedit.setDate(QDate(int(early[0:4]),int(early[5:7]),int(early[8:10])))
            
        if LU.assessNone(rtd):
            self.todateedit.setDate(QDate(int(rtd[0:4]),int(rtd[5:7]),int(rtd[8:10]))) 
        else:
            today = DataStore.getCurrent()
            self.todateedit.setDate(QDate(int(today[0:4]),int(today[5:7]),int(today[8:10])))
            
        #Internal/External CheckBox
#        if LU.assessNone(rint):
#            self.internalTrigger.setChecked(rint.lower()==DataStore.CONF_INT)
#        else:
#            self.internalTrigger.setChecked(DataStore.DEFAULT_CONF==DataStore.CONF_INT)
        
        
    def getConfiguredDestinations(self):
        defml = ['',]+DataStore.DRIVER_NAMES.values()
        return [d for d in self.parent.gpr.getDestinations() if d in defml]
        
    def doEPSGEnable(self):
        self.epsgcombo.setEnabled(self.epsgenable.isChecked())
        
    def doFromDateEnable(self):
        self.fromdateedit.setEnabled(self.fromdateenable.isChecked())
          
    def doToDateEnable(self):
        self.todateedit.setEnabled(self.todateenable.isChecked())  
          
    def readParameters(self):
        '''Read values out of dialogs'''
        destination = LU.assessNone(str(self.destlist[self.destcombo.currentIndex()]))
        #lgindex = self.parent.confconn.getLayerGroupIndex(self.lgcombo.currentText().toUtf8().data())
        lgindex = self.parent.confconn.getLayerGroupIndex(LQ.readWidgetText(self.lgcombo.currentText()))
        #NB need to test for None explicitly since zero is a valid index
        lgval = self.parent.confconn.lglist[lgindex][1] if LU.assessNone(lgindex) else None       
        #uconf = LU.standardiseUserConfigName(str(self.confcombo.lineEdit().text()))
        #uconf = str(self.confcombo.lineEdit().text())
        uconf = str(self.cflist[self.confcombo.currentIndex()])
        ee = self.epsgenable.isChecked()
        epsg = None if ee is False else re.match('^\s*(\d+).*',str(self.epsgcombo.lineEdit().text())).group(1)
        fe = self.fromdateenable.isChecked()
        te = self.todateenable.isChecked()
        fd = None if fe is False else str(self.fromdateedit.date().toString('yyyy-MM-dd'))
        td = None if te is False else str(self.todateedit.date().toString('yyyy-MM-dd'))
        
        return destination,lgval,uconf,epsg,fe,te,fd,td
    
    def doInitClickAction(self):
        '''Initialise the LC on LC-button-click, action'''
        try:
            try:
                self.setStatus(self.STATUS.BUSY,'Opening Layer-Config Editor')  
                self.progressbar.setValue(0)
                self.parent.runLayerConfigAction()
            finally:
                self.setStatus(self.STATUS.IDLE,'Ready')
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Error in Layer-Config',str(sys.exc_info()))#e))
        
    def doCleanClickAction(self):
        '''Set clean anim and run clean'''
        #lgo = self.lgcombo.currentText().toUtf8().data()
        lgo = LQ.readWidgetText(self.lgcombo.currentText())
        
        try:
            self.setStatus(self.STATUS.CLEAN,'Running Clean '+lgo)
            self.progressbar.setValue(0)
            self.runReplicationScript(True)
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Failed Clean of '+lgo,str(sys.exc_info()))#e))
        
    def doReplicateClickAction(self):
        '''Set busy anim and run repl'''
        lgo = self.lgcombo.currentText()#.toUtf8().data()#only used for error messages
        try:
            self.setStatus(self.STATUS.BUSY,'Running Replicate '+lgo)
            self.progressbar.setValue(0)
            self.runReplicationScript(False)
            ldslog.debug('TRPfinish')
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Failed Replication of '+lgo,str(sys.exc_info()))#e))

    def runReplicationScript(self,clean=False):
        '''Run the layer/group repliction script'''
        destination,lgval,uconf,epsg,fe,te,fd,td = self.readParameters()
        uconf_path = LU.standardiseUserConfigName(uconf)
        destination_path = LU.standardiseLayerConfigName(destination)
        destination_driver = LU.standardiseDriverNames(destination)

        if not os.path.exists(uconf_path):
            self.userConfMessage(uconf_path)
            return
        elif not MainFileReader(uconf_path).hasSection(destination_driver):
            self.userConfMessage(uconf_path,destination_driver)
            return
        #-----------------------------------------------------
        #'destname','layer','uconf','group','epsg','fd','td','int'
     
        self.parent.gpr.write((destination_driver,lgval,uconf,epsg,fd,td))        
        ldslog.info(u'dest={0}, lg={1}, conf={2}, epsg={3}'.format(destination_driver,lgval,uconf,epsg))
        ldslog.info('fd={0}, td={1}, fe={2}, te={3}'.format(fd,td,fe,te))
        lgindex = self.parent.confconn.getLayerGroupIndex(lgval,col=1)
        #lorg = self.parent.confconn.lglist[lgindex][0]
        #----------don't need lorg in TP anymore but it is useful for sorting/counting groups
        #self.parent.confconn.tp.setLayerOrGroup(lorg)
        self.parent.confconn.tp.setLayerGroupValue(lgval)
        if self.fromdateenable.isChecked(): self.parent.confconn.tp.setFromDate(fd)
        if self.todateenable.isChecked(): self.parent.confconn.tp.setToDate(td)
        self.parent.confconn.tp.setUserConf(uconf)
        if self.epsgenable: self.parent.confconn.tp.setEPSG(epsg)
        
        #because clean state persists in TP
        if clean:
            self.parent.confconn.tp.setCleanConfig()
        else:
            self.parent.confconn.tp.clearCleanConfig()
        #(re)initialise the data source since uconf may have changed
        #>>#self.parent.confconn.tp.src = self.parent.confconn.initSourceWrapper()
        #--------------------------
        ###ep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.destname,self.parent.confconn.uconf)
        
        ###self.parent.confconn.reg.closeEndPoint(self.parent.confconn.destname)
        ###ep = None
        #Open ProcessRunner and run with TP(proc)/self(gui) instances
        #HACK temp add of dest_drv to PR call
        try:
            #TODO. Test for valid LC first
            self.tpr = ProcessRunner(self,destination_driver)
        except Exception as e:
            ldslog.error('Cannot create ProcessRunner {}. NB Possible missing Layer Config {}'.format(str(e),destination_path))
            self.layerConfMessage(destination_path)
            return
        #If PR has been successfully created we must vave a valid dst    
        ldslog.debug('TRPstart')
        self.tpr.start()
        
#     def quitProcessRunner(self):
#         self.tpr.join()
#         self.tpr.quit()
#         self.trp = None

        
    def userConfMessage(self,uconf,secname=None):
        ucans = QMessageBox.warning(self, 'User Config Missing/Incomplete', 
                                'Specified User-Config file, '+str(uconf)+' does not exist' if secname is None else 'User-Config file does not contain '+str(secname)+' section', 
                                'Back','Initialise User Config')
        if not ucans:
            #Retry
            ldslog.warn('Retry specifying UC')
            #self.confcombo.setCurrentIndex(0)
            return
        #Init
        ldslog.warn('Reset User Config Wizard')
        self.parent.runWizardAction()


    def layerConfMessage(self,dest):
        lcans = QMessageBox.warning(self, 'Layer Config Missing', 
                                'Required Layer-Config file, '+str(dest)+' does not exist', 
                                'Back','Run Layer Select')
        if not lcans:
            #Retry
            ldslog.warn('Retry specifying LC')
            #self.destcombo.setCurrentIndex(0)
            return
        #Init
        ldslog.warn('Reset Layer Config')
        self.doInitClickAction()
Esempio n. 5
0
class HydraulicsDialog(QDialog):
    def __init__(self, parent, params, new_proj=False):
        QDialog.__init__(self, parent)

        self.parent = parent
        self.params = params
        self.new_proj = new_proj

        self.setMinimumWidth(min_width)
        # self.setMinimumHeight(min_height)

        # Build dialog
        self.setWindowTitle('Options - Hydraulics')  # TODO: softcode
        self.setWindowModality(QtCore.Qt.ApplicationModal)

        self.fra_form = QFrame(self)
        fra_form_lay = QFormLayout(self.fra_form)
        fra_form_lay.setContentsMargins(10, 10, 10, 10)

        self.lbl_units = QLabel('Units system:')  # TODO: softocode
        self.cbo_units = QComboBox()
        fra_form_lay.addRow(self.lbl_units, self.cbo_units)

        self.lbl_flow_units = QLabel('Flow units:')  # TODO: softocode
        self.cbo_flow_units = QComboBox()
        fra_form_lay.addRow(self.lbl_flow_units, self.cbo_flow_units)

        self.lbl_headloss = QLabel('Head loss:')  # TODO: softocode
        self.cbo_headloss = QComboBox()
        fra_form_lay.addRow(self.lbl_headloss, self.cbo_headloss)

        self.chk_hydraulics = QCheckBox('Hydraulics:')  # TODO: softcode
        self.cbo_hydraulics = QComboBox()
        fra_form_lay.addRow(self.chk_hydraulics, self.cbo_hydraulics)

        self.txt_hydraulics_file = QLineEdit()
        fra_form_lay.addRow(None, self.txt_hydraulics_file)

        self.btn_hydraulics_file = QPushButton('File...')  # TODO: softcode
        fra_form_lay.addRow(None, self.btn_hydraulics_file)

        self.lbl_viscosity = QLabel('Viscosity:')  # TODO: softocode
        self.txt_viscosity = QLineEdit()
        fra_form_lay.addRow(self.lbl_viscosity, self.txt_viscosity)

        self.lbl_diffusivity = QLabel('Diffusivity:')  # TODO: softocode
        self.txt_diffusivity = QLineEdit()
        fra_form_lay.addRow(self.lbl_diffusivity, self.txt_diffusivity)

        self.lbl_spec_gravity = QLabel('Specific gravity:')  # TODO: softocode
        self.txt_spec_gravity = QLineEdit()
        fra_form_lay.addRow(self.lbl_spec_gravity, self.txt_spec_gravity)

        self.lbl_max_trials = QLabel('Max trials:')  # TODO: softocode
        self.txt_max_trials = QLineEdit()
        fra_form_lay.addRow(self.lbl_max_trials, self.txt_max_trials)

        self.lbl_accuracy = QLabel('Accuracy:')  # TODO: softocode
        self.txt_accuracy = QLineEdit()
        fra_form_lay.addRow(self.lbl_accuracy, self.txt_accuracy)

        self.lbl_unbalanced = QLabel('Unbalanced:')  # TODO: softcode
        self.fra_unbalanced = QFrame(self)
        fra_unbalanced_lay = QHBoxLayout(self.fra_unbalanced)
        fra_unbalanced_lay.setContentsMargins(0, 0, 0, 0)
        self.cbo_unbalanced = QComboBox()
        self.txt_unbalanced = QLineEdit()
        fra_unbalanced_lay.addWidget(self.cbo_unbalanced)
        fra_unbalanced_lay.addWidget(self.txt_unbalanced)
        fra_form_lay.addRow(self.lbl_unbalanced, self.fra_unbalanced)

        self.lbl_pattern = QLabel('Pattern:')  # TODO: softocode
        self.cbo_pattern = QComboBox()
        fra_form_lay.addRow(self.lbl_pattern, self.cbo_pattern)

        self.lbl_demand_mult = QLabel('Demand multiplier:')  # TODO: softocode
        self.txt_demand_mult = QLineEdit()
        fra_form_lay.addRow(self.lbl_demand_mult, self.txt_demand_mult)

        self.lbl_emitter_exp = QLabel('Emitter exponent:')  # TODO: softocode
        self.txt_emitter_exp = QLineEdit()
        fra_form_lay.addRow(self.lbl_emitter_exp, self.txt_emitter_exp)

        self.lbl_tolerance = QLabel('Tolerance:')  # TODO: softocode
        self.txt_tolerance = QLineEdit()
        fra_form_lay.addRow(self.lbl_tolerance, self.txt_tolerance)

        # Buttons
        self.fra_buttons = QFrame(self)
        fra_buttons_lay = QHBoxLayout(self.fra_buttons)
        self.btn_Cancel = QPushButton('Cancel')
        self.btn_Ok = QPushButton('OK')
        fra_buttons_lay.addWidget(self.btn_Ok)
        fra_buttons_lay.addWidget(self.btn_Cancel)

        # Add to main
        fra_main_lay = QVBoxLayout(self)
        fra_main_lay.setContentsMargins(0, 0, 0, 0)
        fra_main_lay.addWidget(self.fra_form)
        fra_main_lay.addWidget(self.fra_buttons)

        self.setup()

    def setup(self):

        # Fill units system combo box
        for unit in self.params.options.units_sys:
            self.cbo_units.addItem(self.params.options.units_sys_text[unit],
                                   unit)

        # Fill flow units combo box
        for fu in Options.units_flow[self.params.options.units]:
            self.cbo_flow_units.addItem(Options.units_flow_text[fu], fu)

        self.cbo_units.activated.connect(self.cbo_units_activated)
        # self.cbo_flow_units.activated.connect(self.cbo_flow_units_activated)

        for key, value in self.params.options.headlosses_text.iteritems():
            self.cbo_headloss.addItem(value, key)

        self.cbo_headloss.activated.connect(self.cbo_headloss_activated)

        self.chk_hydraulics.stateChanged.connect(self.chk_hydraulics_changed)
        self.btn_hydraulics_file.clicked.connect(self.btn_hydraulics_clicked)
        self.cbo_hydraulics.addItem(
            self.params.options.hydraulics.action_names[
                self.params.options.hydraulics.action_use],
            self.params.options.hydraulics.action_use)
        self.cbo_hydraulics.addItem(
            self.params.options.hydraulics.action_names[
                self.params.options.hydraulics.action_save],
            self.params.options.hydraulics.action_save)
        self.txt_hydraulics_file.setReadOnly(True)

        # - Unbalanced
        for id, text in self.params.options.unbalanced.unb_text.iteritems():
            self.cbo_unbalanced.addItem(text, id)

        self.cbo_unbalanced.activated.connect(self.cbo_unbalanced_changed)
        self.txt_unbalanced.setValidator(RegExValidators.get_pos_int_no_zero())
        self.txt_unbalanced.setText('1')

        # - Pattern
        self.cbo_pattern.addItem('None (=1.0)', None)
        for pattern_id, pattern in self.params.patterns.iteritems():
            self.cbo_pattern.addItem(pattern_id, pattern)

        # Buttons
        self.btn_Cancel.clicked.connect(self.btn_cancel_clicked)
        self.btn_Ok.clicked.connect(self.btn_ok_clicked)

        # Validators
        self.txt_viscosity.setValidator(RegExValidators.get_pos_decimals())
        self.txt_diffusivity.setValidator(RegExValidators.get_pos_decimals())
        self.txt_spec_gravity.setValidator(RegExValidators.get_pos_decimals())
        self.txt_max_trials.setValidator(RegExValidators.get_pos_int_no_zero())
        self.txt_accuracy.setValidator(RegExValidators.get_pos_decimals())
        self.txt_demand_mult.setValidator(RegExValidators.get_pos_decimals())
        self.txt_emitter_exp.setValidator(RegExValidators.get_pos_decimals())
        self.txt_tolerance.setValidator(RegExValidators.get_pos_decimals())

    def show(self):
        super(HydraulicsDialog, self).show()

        self.cbo_units.setCurrentIndex(
            self.cbo_units.findData(self.params.options.units))
        self.cbo_flow_units.setCurrentIndex(
            self.cbo_flow_units.findData(self.params.options.flow_units))
        self.cbo_headloss.setCurrentIndex(
            self.cbo_headloss.findData(self.params.options.headloss))

        self.chk_hydraulics.setChecked(
            self.params.options.hydraulics.use_hydraulics)
        self.btn_hydraulics_file.setEnabled(self.chk_hydraulics.isChecked())
        self.cbo_hydraulics.setEnabled(self.chk_hydraulics.isChecked())
        self.txt_hydraulics_file.setEnabled(self.chk_hydraulics.isChecked())

        if self.params.options.hydraulics.action is not None:
            self.cbo_hydraulics.setCurrentIndex(
                self.cbo_hydraulics.findData(
                    self.params.options.hydraulics.action))
        if self.params.options.hydraulics.file is not None:
            self.txt_hydraulics_file.setText(
                self.params.options.hydraulics.file)

        self.txt_viscosity.setText(str(self.params.options.viscosity))
        self.txt_diffusivity.setText(str(self.params.options.diffusivity))
        self.txt_spec_gravity.setText(str(self.params.options.spec_gravity))
        self.txt_max_trials.setText(str(self.params.options.trials))
        self.txt_accuracy.setText(str(self.params.options.accuracy))

        self.cbo_unbalanced.setCurrentIndex(
            self.cbo_unbalanced.findData(
                self.params.options.unbalanced.unbalanced))
        self.txt_unbalanced.setEnabled(self.cbo_unbalanced.currentIndex() != 0)
        self.txt_unbalanced.setText(str(self.params.options.unbalanced.trials))

        # Patterns
        if self.params.options.pattern is not None:
            if self.params.options.pattern is None:
                self.cbo_pattern.setCurrentIndex(0)
            else:
                for i in range(self.cbo_pattern.count()):
                    if self.params.options.pattern.id == self.cbo_pattern.itemText(
                            i):
                        self.cbo_pattern.setCurrentIndex(i)
                        break

        self.txt_demand_mult.setText(str(self.params.options.demand_mult))
        self.txt_emitter_exp.setText(str(self.params.options.emitter_exp))
        self.txt_tolerance.setText(str(self.params.options.tolerance))

    def cbo_units_activated(self):

        self.params.options.units = self.cbo_units.itemData(
            self.cbo_units.currentIndex())

        # Parameters combo box
        self.cbo_flow_units.clear()
        for fu in Options.units_flow[self.params.options.units]:
            self.cbo_flow_units.addItem(Options.units_flow_text[fu], fu)

    def cbo_headloss_activated(self):

        # Warning
        if not self.new_proj:
            QMessageBox.warning(
                self, Parameters.plug_in_name,
                u'Head loss units changed: the head loss values already present might need to be reviewed.',
                QMessageBox.Ok)

    def chk_hydraulics_changed(self):

        self.btn_hydraulics_file.setEnabled(self.chk_hydraulics.isChecked())
        self.cbo_hydraulics.setEnabled(self.chk_hydraulics.isChecked())
        self.txt_hydraulics_file.setEnabled(self.chk_hydraulics.isChecked())

    def btn_hydraulics_clicked(self):
        file_dialog = QFileDialog(self, 'Select hydraulics file')
        file_dialog.setLabelText(QFileDialog.Accept, 'Select')
        file_dialog.setLabelText(QFileDialog.Reject, 'Cancel')
        file_dialog.setFileMode(QFileDialog.AnyFile)

        file_dialog.exec_()

        hydraulics_file_path = file_dialog.selectedFiles()

        if not hydraulics_file_path or hydraulics_file_path[
                0] is None or hydraulics_file_path[0] == '':
            return

        self.txt_hydraulics_file.setText(hydraulics_file_path[0])

    def cbo_unbalanced_changed(self):
        self.txt_unbalanced.setEnabled(
            self.cbo_unbalanced.itemData(self.cbo_unbalanced.currentIndex()) ==
            self.params.options.unbalanced.unb_continue)

    def btn_cancel_clicked(self):
        self.setVisible(False)

    def btn_ok_clicked(self):

        if not self.check_params():
            return

        # Update parameters and options
        self.params.options.units = self.cbo_units.itemData(
            self.cbo_units.currentIndex())
        self.params.options.flow_units = self.cbo_flow_units.itemData(
            self.cbo_flow_units.currentIndex())
        self.params.options.headloss = self.cbo_headloss.itemData(
            self.cbo_headloss.currentIndex())
        self.params.options.hydraulics.use_hydraulics = self.chk_hydraulics.isChecked(
        )

        if self.params.options.hydraulics.action is not None:
            self.params.options.hydraulics.action = self.cbo_hydraulics.itemData(
                self.cbo_hydraulics.currentIndex())
            self.params.options.hydraulics.file = self.txt_hydraulics_file.text(
            )

        self.params.options.viscosity = float(self.txt_viscosity.text())
        self.params.options.diffusivity = float(self.txt_diffusivity.text())
        self.params.options.spec_gravity = float(self.txt_spec_gravity.text())
        self.params.options.trials = float(self.txt_max_trials.text())
        self.params.options.accuracy = float(self.txt_accuracy.text())

        self.params.options.unbalanced.unbalanced = self.cbo_unbalanced.itemData(
            self.cbo_unbalanced.currentIndex())
        self.params.options.unbalanced.trials = int(self.txt_unbalanced.text())

        self.params.options.pattern = self.cbo_pattern.itemData(
            self.cbo_pattern.currentIndex())
        self.params.options.demand_mult = float(self.txt_demand_mult.text())
        self.params.options.emitter_exp = float(self.txt_emitter_exp.text())
        self.params.options.tolerance = float(self.txt_tolerance.text())

        # Junctions
        self.parent.lbl_junction_demand.setText(
            pre_l('Demand', Options.units_flow[self.params.options.units]
                  [0]))  # TODO: softcode
        self.parent.lbl_junction_deltaz.setText(
            pre_l('Delta Z', Options.units_deltaz[
                self.params.options.units]))  # TODO: softcode

        # Reservoirs
        self.parent.lbl_reservoir_deltaz.setText(
            pre_l('Delta Z', Options.units_deltaz[
                self.params.options.units]))  # TODO: softcode
        self.parent.lbl_reservoir_pressure_head.setText(
            pre_l('Pressure head', Options.units_deltaz[
                self.params.options.units]))  # TODO: softcode

        # Tanks
        self.parent.lbl_tank_deltaz.setText(
            pre_l('Delta Z', Options.units_deltaz[
                self.params.options.units]))  # TODO: softcode
        self.parent.lbl_tank_level_init.setText(
            pre_l('Level init.', Options.units_deltaz[
                self.params.options.units]))  # TODO: softcode
        self.parent.lbl_tank_level_min.setText(
            pre_l('Level min', Options.units_deltaz[
                self.params.options.units]))  # TODO: softcode
        self.parent.lbl_tank_level_max.setText(
            pre_l('Level max', Options.units_deltaz[
                self.params.options.units]))  # TODO: softcode
        self.parent.lbl_tank_diameter.setText(
            pre_l('Diameter', Options.units_diameter_tanks[
                self.params.options.units]))  # TODO: softcode
        self.parent.lbl_tank_vol_min.setText(
            pre_l('Volume min', Options.units_volume[
                self.params.options.units]))  # TODO: softcode

        # Pipes
        self.parent.lbl_pipe_demand.setText(
            pre_l('Demand', Options.units_flow[self.params.options.units]
                  [0]))  # TODO: softcode
        self.parent.lbl_pipe_diameter.setText(
            pre_l('Diameter', Options.units_diameter_pipes[
                self.params.options.units]))  # TODO: softcode
        self.parent.lbl_pipe_roughness_val.setText(
            pre_l(
                'Value', Options.units_roughness[self.params.options.units][
                    self.params.options.headloss]))  # TODO: softcode

        self.params.options.headloss_units = self.cbo_headloss.itemData(
            self.cbo_headloss.currentIndex())

        self.parent.update_roughness_params(
            self.parent.cbo_pipe_roughness.itemData(
                self.parent.cbo_pipe_roughness.currentIndex())[
                    self.params.options.headloss])

        # self.parent.lbl_pipe_roughness.setText(
        #     pre_l(
        #         'Roughness',
        #         self.params.options.units_roughness[self.params.options.units][self.params.options.headloss_units]))

        # Pumps
        self.parent.lbl_pump_head.setText(
            pre_l('Head',
                  self.params.options.units_deltaz[self.params.options.units]))
        self.parent.lbl_pump_power.setText(
            pre_l('Power',
                  self.params.options.units_power[self.params.options.units]))

        # Valves
        valve_type = self.parent.cbo_valve_type.itemData(
            self.parent.cbo_valve_type.currentIndex())

        # Pressure valves
        if valve_type == Valve.type_psv or valve_type == Valve.type_prv or valve_type == Valve.type_pbv:
            self.parent.lbl_valve_setting.setText(
                pre_l(
                    'Pressure', self.params.options.units_pressure[
                        self.params.options.units]))
        # FCV valve: Flow
        if valve_type == Valve.type_fcv:
            self.parent.lbl_valve_setting.setText(
                pre_l('Flow', self.params.options.flow_units))
        # Throttle control valve
        elif valve_type == Valve.type_tcv:
            self.parent.lbl_valve_setting.setText(pre_l('Loss coeff.', '-'))
        # self.parent.lbl_valve_diameter.setText(pre_l('Pressure', self.params.options.units_diameter_pipes[self.params.options.units]))

        # Flow units
        units = self.cbo_flow_units.itemData(
            self.cbo_flow_units.currentIndex())
        self.parent.lbl_junction_demand.setText(pre_l('Demand',
                                                      units))  # TODO: softcode
        self.parent.lbl_pipe_demand.setText(pre_l('Demand',
                                                  units))  # TODO: softcode

        self.setVisible(False)

    def check_params(self):

        if self.chk_hydraulics.isChecked():
            if not os.path.isfile(self.txt_hydraulics_file.text()):
                QMessageBox.warning(
                    self, Parameters.plug_in_name,
                    u'Hydraulics option slected, but no valid file specified.',
                    QMessageBox.Ok)
                return False

        return True
Esempio n. 6
0
class SkinsTab(QWidget):

    def __init__(self):
        QWidget.__init__(self)
        vbox = QVBoxLayout(self)

        #Top Bar
        hbox = QHBoxLayout()
        self.radioDefault = QRadioButton("Default Skin")
        self.radioCustom = QRadioButton("Custom")
        self.comboSkins = QComboBox()
        self.skins = loader.load_gui_skins()
        for item in self.skins:
            self.comboSkins.addItem(item)
        hbox.addWidget(self.radioDefault)
        hbox.addWidget(self.radioCustom)
        hbox.addWidget(self.comboSkins)
        #Text Area
        self.txtStyle = QPlainTextEdit()
        self.txtStyle.setReadOnly(True)

        #Settings
        settings = QSettings()
        settings.beginGroup('preferences')
        settings.beginGroup('skins')
        if settings.value('default', True).toBool():
            self.radioDefault.setChecked(True)
            self.comboSkins.setEnabled(False)
        else:
            self.radioCustom.setChecked(True)
            index = self.comboSkins.findText(settings.value('selectedSkin', '').toString())
            self.comboSkins.setCurrentIndex(index)
            content = self.skins[str(self.comboSkins.currentText())]
            self.txtStyle.setPlainText(content)
        settings.endGroup()
        settings.endGroup()

        vbox.addLayout(hbox)
        vbox.addWidget(self.txtStyle)
        vbox.addWidget(QLabel('Requires restart the IDE'))

        #Signals
        self.connect(self.radioDefault, SIGNAL("clicked()"), self._default_clicked)
        self.connect(self.radioCustom, SIGNAL("clicked()"), self._custom_clicked)

    def _default_clicked(self):
        self.comboSkins.setEnabled(False)
        self.txtStyle.setPlainText('')

    def _custom_clicked(self):
        self.comboSkins.setEnabled(True)
        content = self.skins[str(self.comboSkins.currentText())]
        self.txtStyle.setPlainText(content)

    def save(self):
        settings = QSettings()
        settings.beginGroup('preferences')
        settings.beginGroup('skins')
        settings.setValue('default', self.radioDefault.isChecked())
        settings.setValue('selectedSkin', self.comboSkins.currentText())
        settings.endGroup()
        settings.endGroup()
Esempio n. 7
0
class TablaturePart(_base.Part):
    """Base class for tablature instrument part types."""

    octave = 0
    clef = None
    transposition = None
    tunings = ()  # may contain a list of tunings.
    tabFormat = ""  # can contain a tablatureFormat value.

    def createWidgets(self, layout):
        self.staffTypeLabel = QLabel()
        self.staffType = QComboBox()
        self.staffTypeLabel.setBuddy(self.staffType)
        self.staffType.setModel(listmodel.ListModel(tablatureStaffTypes, self.staffType, display=listmodel.translate))
        box = QHBoxLayout()
        layout.addLayout(box)
        box.addWidget(self.staffTypeLabel)
        box.addWidget(self.staffType)
        if self.tunings:
            self.createTuningWidgets(layout)
            self.staffType.activated.connect(self.slotTabEnable)
            self.slotTabEnable(0)

    def createTuningWidgets(self, layout):
        self.tuningLabel = QLabel()
        self.tuning = QComboBox()
        self.tuningLabel.setBuddy(self.tuning)
        tunings = [("", lambda: _("Default"))]
        tunings.extend(self.tunings)
        self.tuning.setModel(listmodel.ListModel(tunings, self.tuning, display=listmodel.translate_index(1)))
        self.tuning.setCurrentIndex(1)
        box = QHBoxLayout()
        layout.addLayout(box)
        box.addWidget(self.tuningLabel)
        box.addWidget(self.tuning)

    def translateWidgets(self):
        self.staffTypeLabel.setText(_("Staff type:"))
        self.staffType.model().update()
        if self.tunings:
            self.translateTuningWidgets()

    def translateTuningWidgets(self):
        self.tuningLabel.setText(_("Tuning:"))
        self.tuning.model().update()

    def slotTabEnable(self, enable):
        """Called when the user changes the staff type.
        
        Non-zero if the user wants a TabStaff.
        
        """
        self.tuning.setEnabled(bool(enable))

    def voiceCount(self):
        """Returns the number of voices.
        
        Inherit to make this user-settable.
        
        """
        return 1

    def build(self, data, builder):
        # First make assignments for the voices we want to create
        numVoices = self.voiceCount()
        if numVoices == 1:
            voices = (ly.util.mkid(data.name()),)
        elif numVoices == 2:
            order = 1, 2
            voices = "upper", "lower"
        elif numVoices == 3:
            order = 1, 3, 2
            voices = "upper", "middle", "lower"
        else:
            order = 1, 2, 3, 4
            voices = [ly.util.mkid(data.name(), "voice") + ly.util.int2text(i) for i in order]

        assignments = [data.assignMusic(name, self.octave, self.transposition) for name in voices]

        staffType = self.staffType.currentIndex()
        if staffType in (0, 2):
            # create a normal staff
            staff = ly.dom.Staff()
            seq = ly.dom.Seqr(staff)
            if self.clef:
                ly.dom.Clef(self.clef, seq)
            mus = ly.dom.Simr(seq)
            for a in assignments[:-1]:
                ly.dom.Identifier(a.name, mus)
                ly.dom.VoiceSeparator(mus)
            ly.dom.Identifier(assignments[-1].name, mus)
            builder.setMidiInstrument(staff, self.midiInstrument)

        if staffType in (1, 2):
            # create a tab staff
            tabstaff = ly.dom.TabStaff()
            if self.tabFormat:
                tabstaff.getWith()["tablatureFormat"] = ly.dom.Scheme(self.tabFormat)
            self.setTunings(tabstaff)
            sim = ly.dom.Simr(tabstaff)
            if numVoices == 1:
                ly.dom.Identifier(assignments[0].name, sim)
            else:
                for num, a in zip(order, assignments):
                    s = ly.dom.Seq(ly.dom.TabVoice(parent=sim))
                    ly.dom.Text("\\voice" + ly.util.int2text(num), s)
                    ly.dom.Identifier(a.name, s)

        if staffType == 0:
            # only a normal staff
            p = staff
        elif staffType == 1:
            # only a TabStaff
            builder.setMidiInstrument(tabstaff, self.midiInstrument)
            p = tabstaff
        else:
            # both TabStaff and normal staff
            p = ly.dom.StaffGroup()
            s = ly.dom.Sim(p)
            s.append(staff)
            s.append(tabstaff)

        builder.setInstrumentNamesFromPart(p, self, data)
        data.nodes.append(p)

    def setTunings(self, tab):
        if self.tunings and self.tuning.currentIndex() > 0:
            tuning = self.tunings[self.tuning.currentIndex() - 1][0]
            tab.getWith()["stringTunings"] = ly.dom.Scheme(tuning)
Esempio n. 8
0
class LDSControls(QFrame):
        
    STATIC_IMG = ('error_static.png','linz_static.png','busy_static.png','clean_static.png')
    ANIM_IMG   = ('error.gif','linz.gif','layer.gif','clean.gif')
    
    IMG_SPEED  = 100
    IMG_WIDTH  = 64
    IMG_HEIGHT = 64
    
    MAX_WD = 450
    
    GD_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../../bin/gdal/gdal-data'))
    STATUS = LU.enum('ERROR','IDLE','BUSY','CLEAN')
    
    def __init__(self,parent):
        super(LDSControls, self).__init__()
        self.parent = parent
        self.initConf()
        self.initEPSG()
        self.initUI()
        
    def initConf(self):
        '''Read files in conf dir ending in conf'''
        self.cflist = ConfigInitialiser.getConfFiles()
        #self.imgset = self.STATIC_IMG if ConfigWrapper().readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        #self.imgset = self.STATIC_IMG if self.parent.confconn.tp.src.confwrap.readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        sep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.SRCNAME,self.parent.confconn.uconf)
        self.imgset = self.STATIC_IMG if sep.confwrap.readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        self.parent.confconn.reg.closeEndPoint(self.parent.confconn.SRCNAME)
        
    def initEPSG(self):
        '''Read GDAL EPSG files, splitting by NZ(RSR) and RestOfTheWorld'''

        gcsf = gdal.FindFile('gdal','gcs.csv') 
        if not gcsf:
            gcsf = os.path.join(self.GD_PATH,'gcs.csv')
        pcsf = gdal.FindFile('gdal','pcs.csv') 
        if not pcsf: 
            pcsf = os.path.join(self.GD_PATH,'pcs.csv')
        gcs = ConfigInitialiser.readCSV(gcsf)
        pcs = ConfigInitialiser.readCSV(pcsf)

        self.nzlsr = [(e[0],e[0]+' - '+e[3]) for e in gcs if 'NZGD'     in e[1] or  'RSRGD'     in e[1]] \
                   + [(e[0],e[0]+' - '+e[1]) for e in pcs if 'NZGD'     in e[1] or  'RSRGD'     in e[1]]
        self.rowsr = [(e[0],e[0]+' - '+e[3]) for e in gcs if 'NZGD' not in e[1] and 'RSRGD' not in e[1]] \
                   + [(e[0],e[0]+' - '+e[1]) for e in pcs if 'NZGD' not in e[1] and 'RSRGD' not in e[1]]
                   
                   
    def initUI(self):
        
        # 0      1          2       3       4       5      6    7    8
        #'destname','lgselect','layer','uconf','group','epsg','fd','td','int'
        
        #self.rdest,rlgselect,self.rlayer,ruconf,self.rgroup,repsg,rfd,rtd,rint = readlist 
        
        QToolTip.setFont(QFont('SansSerif', 10))
        
        #labels
        destLabel = QLabel('Destination')
        lgLabel = QLabel('Group/Layer')
        epsgLabel = QLabel('EPSG')
        fromDateLabel = QLabel('From Date')
        toDateLabel = QLabel('To Date')
        confLabel = QLabel('User Config')
        
        self.view = QLabel() 
        self.view.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.view.setAlignment(Qt.AlignCenter)

        self.confcombo = QComboBox(self)
        self.confcombo.setToolTip('Enter your user config name (file) here')
        self.confcombo.addItems(self.cflist)
        self.confcombo.setEditable(False)
        #self.confcombo.currentIndexChanged.connect(self.doLGEditUpdate)
        
        #combos
        self.lgcombo = QComboBox(self)
        self.lgcombo.setMaximumWidth(self.MAX_WD)
        self.lgcombo.setDuplicatesEnabled(False)
        #self.lgcombo.setInsertPolicy(QComboBox.InsertAlphabetically)#?doesnt seem to work
        self.lgcombo.setToolTip('Select either Layer or Group entry')
        self.lgcombo.setEditable(False)
        self.sepindex = None
        #self.updateLGValues()
        
        self.epsgcombo = QComboBox(self)
        self.epsgcombo.setMaximumWidth(self.MAX_WD)
        self.epsgcombo.setToolTip('Setting an EPSG number here determines the output SR of the layer')  
        self.epsgcombo.addItems([i[1] for i in self.nzlsr])
        self.epsgcombo.insertSeparator(len(self.nzlsr))
        self.epsgcombo.addItems([i[1] for i in self.rowsr])
        self.epsgcombo.setEditable(True)
        self.epsgcombo.setEnabled(False)
        
        self.destlist = self.getConfiguredDestinations()
        self.destcombo = QComboBox(self)
        self.destcombo.setToolTip('Choose the desired output type')   
        self.destcombo.setEditable(False)
        self.destcombo.addItems(self.destlist)

        #date selection
        self.fromdateedit = QDateEdit()
        self.fromdateedit.setCalendarPopup(True)
        self.fromdateedit.setEnabled(False)
        
        self.todateedit = QDateEdit()
        self.todateedit.setCalendarPopup(True)
        self.todateedit.setEnabled(False)
        
        #check boxes
        self.epsgenable = QCheckBox()
        self.epsgenable.setCheckState(False)
        self.epsgenable.clicked.connect(self.doEPSGEnable)       
        
        self.fromdateenable = QCheckBox()
        self.fromdateenable.setCheckState(False)
        self.fromdateenable.clicked.connect(self.doFromDateEnable)
        
        self.todateenable = QCheckBox()
        self.todateenable.setCheckState(False) 
        self.todateenable.clicked.connect(self.doToDateEnable)
        
        self.progressbar = QProgressBar()
        self.progressbar.setRange(0,100)
        self.progressbar.setVisible(True)
        self.progressbar.setMinimumWidth(self.MAX_WD)
        
        
        #buttons        
        self.initbutton = QPushButton("waiting")
        self.initbutton.setToolTip('Initialise the Layer Configuration')
        self.initbutton.clicked.connect(self.doInitClickAction)
        
        self.cleanbutton = QPushButton("Clean")
        self.cleanbutton.setToolTip('Clean the selected layer/group from local storage')
        self.cleanbutton.clicked.connect(self.doCleanClickAction)
        
        self.replicatebutton = QPushButton("Replicate")
        self.replicatebutton.setToolTip('Execute selected replication')
        self.replicatebutton.clicked.connect(self.doReplicateClickAction)
        
        self.cancelbutton = QPushButton("Close")
        self.cancelbutton.setToolTip('Close the LDS Replicate application')       
        self.cancelbutton.clicked.connect(self.parent.close)


        #set dialog values using GPR
        self.updateGUIValues(self.parent.gvs)
        
        #set onchange here otherwise we get circular initialisation
        self.destcombo.currentIndexChanged.connect(self.doDestChanged)
        self.confcombo.currentIndexChanged.connect(self.doConfChanged)
        self.lgcombo.currentIndexChanged.connect(self.doLGComboChanged)

        self.setStatus(self.STATUS.IDLE)
        
        #grid
        grid = QGridLayout()
        grid.setSpacing(10)
        
        
        #placement section ------------------------------------
        #---------+---------+--------+---------+--------
        # dest LB |         | dest DD
        # grp LB  |         | grp DD
        # conf LB |         | conf DD
        # epsg L  | epsg CB | epsg DD
        # f dt L  | f dt CB | f dt DD
        # t td L  | t td CB | t td DD
        # icon    |       <- progress ->
        # layer B | <- . -> |repl B  | clean B | close B 
        #---------+---------+--------+---------+--------

        grid.addWidget(destLabel, 1, 0)
        grid.addWidget(self.destcombo, 1, 2)

        #grid.addWidget(layerLabel, 2, 0)
        grid.addWidget(lgLabel, 2, 0)
        grid.addWidget(self.lgcombo, 2, 2)
        
        grid.addWidget(confLabel, 3, 0)
        grid.addWidget(self.confcombo, 3, 2)
        
        #grid.addWidget(groupLabel, 4, 0)
        #grid.addWidget(self.groupEdit, 4, 2)
        
        grid.addWidget(epsgLabel, 5, 0)
        grid.addWidget(self.epsgenable, 5, 1)
        grid.addWidget(self.epsgcombo, 5, 2)

        grid.addWidget(fromDateLabel, 6, 0)
        grid.addWidget(self.fromdateenable, 6, 1)
        grid.addWidget(self.fromdateedit, 6, 2)
        
        grid.addWidget(toDateLabel, 7, 0)
        grid.addWidget(self.todateenable, 7, 1)
        grid.addWidget(self.todateedit, 7, 2)
        
        hbox3 = QHBoxLayout()
        hbox3.addWidget(self.view) 
        hbox3.addStretch(1)
        hbox3.addWidget(self.progressbar)

        #hbox3.addLayout(vbox2)
        #hbox3.addLayout(vbox3)
        
        hbox4 = QHBoxLayout()
        hbox4.addWidget(self.initbutton)
        hbox4.addStretch(1)
        hbox4.addWidget(self.replicatebutton)
        hbox4.addWidget(self.cleanbutton)
        hbox4.addWidget(self.cancelbutton)
        

        vbox = QVBoxLayout()
        #vbox.addStretch(1)
        vbox.addLayout(grid)
        vbox.addLayout(hbox3)
        vbox.addLayout(hbox4)
        
        self.setLayout(vbox)  
       
    #def setProgress(self,pct):
    #    self.progressbar.setValue(pct)
        
    def setStatus(self,status,message='',tooltip=None):
        '''Sets indicator icon and statusbar message'''
        self.parent.statusbar.showMessage(message)
        self.parent.statusbar.setToolTip(tooltip if tooltip else '')

        #progress
        loc = os.path.abspath(os.path.join(IMG_LOC,self.imgset[status]))
        #loc = os.path.abspath(os.path.join(os.path.dirname(__file__),self.parent.IMG_LOC,self.imgset[status]))
        self.progressbar.setVisible(status in (self.STATUS.BUSY, self.STATUS.CLEAN))
        
        #icon
        anim = QMovie(loc, QByteArray(), self)
        anim.setScaledSize(QSize(self.IMG_WIDTH,self.IMG_HEIGHT))
        anim.setCacheMode(QMovie.CacheAll)
        anim.setSpeed(self.IMG_SPEED)
        self.view.clear()
        self.view.setMovie(anim)
        anim.start()

        self.view.repaint()
        QApplication.processEvents(QEventLoop.AllEvents)

    def mainWindowEnable(self,enable=True):
        cons = (self.lgcombo, self.confcombo, self.destcombo, 
                self.initbutton, self.replicatebutton, self.cleanbutton, self.cancelbutton,
                self.epsgenable,self.fromdateenable,self.todateenable,
                self.parent.menubar)
        for c in cons:
            c.setEnabled(enable)
            
        if enable:
            self.epsgcombo.setEnabled(self.epsgenable.checkState())
            self.fromdateedit.setEnabled(self.fromdateenable.checkState())
            self.todateedit.setEnabled(self.todateenable.checkState())
        else:
            self.epsgcombo.setEnabled(False)
            self.fromdateedit.setEnabled(False)
            self.todateedit.setEnabled(False)
   
        QApplication.restoreOverrideCursor() if enable else QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) 

    def refreshLGCombo(self):
        '''Re index LG combobox since a refreshLG call (new dest?) will usually mean new groups'''
        self.lgcombo.clear()
        self.lgcombo.addItems([i[2] for i in self.parent.confconn.lglist])
        #NOTE the separator consumes an index, if not clearing the combobox selectively remove the old sepindex (assumes g preceeds l)
        #if self.sepindex:
        #    self.lgcombo.removeItem(self.sepindex)
        self.sepindex = [i[0] for i in self.parent.confconn.lglist].count(LORG.GROUP)
        self.lgcombo.insertSeparator(self.sepindex)
        
    def updateLGValues(self,uconf,lgval,dest):
        '''Sets the values displayed in the Layer/Group combo'''
        #because we cant seem to sort combobox entries and want groups at the top, clear and re-add
        #TRACE#        
        #pdb.set_trace()
        sf = None
        try:
            self.parent.confconn.initConnections(uconf,lgval,dest)
        except Exception as e:
            sf=1
            ldslog.error('Error Updating UC Values. '+str(e))
            
        if sf:
            self.setStatus(self.STATUS.ERROR,'Error Updating UC Values', str(e))
        else:
            self.setStatus(self.STATUS.IDLE)
            
        self.refreshLGCombo()
        
    def centre(self):
        
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
        
    
    def gprParameters(self,rdest):
        '''Zip default and GPR values'''
        return [x if LU.assessNone(x) else y for x,y in zip(self.parent.gpr.readsec(rdest),self.parent.DEF_RVALS[1:])]
    
    def getLCE(self,ln):
        '''Read layer parameters'''
        dep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.destname,self.parent.confconn.uconf)
        #sep = self.parent.confconn.reg.openEndPoint('WFS',self.parent.confconn.uconf)
        self.parent.confconn.reg.setupLayerConfig(self.parent.confconn.tp,None,dep,initlc=False)
        lce = dep.getLayerConf().readLayerParameters(ln)
        #self.parent.confconn.reg.closeEndPoint('WFS')
        self.parent.confconn.reg.closeEndPoint(self.parent.confconn.destname)
        sep,dep = None,None
        return lce
    
    
    def doDestChanged(self):
        '''Read the destname parameter and fill dialog with matching GPR values'''
        rdest = str(self.destlist[self.destcombo.currentIndex()])
        rvals = self.gprParameters(rdest)
        self.updateGUIValues([rdest]+rvals)    
        
        
    def doConfChanged(self):
        '''Read the user conf parameter and fill dialog with matching GPR values'''
        rdest = str(self.destlist[self.destcombo.currentIndex()])
        rlg,_,rep,rfd,rtd = self.gprParameters(rdest)
        ruc = str(self.cflist[self.confcombo.currentIndex()])
        self.updateGUIValues((rdest,rlg,ruc,rep,rfd,rtd))
        
        
    def doLGComboChanged(self):
        '''Read the layer/group value and change epsg to layer or gpr match'''
        #get a matching LG entry and test whether its a layer or group
        #lgi = self.parent.confconn.getLayerGroupIndex(self.lgcombo.currentText().toUtf8().data())
        lgi = self.parent.confconn.getLayerGroupIndex(LQ.readWidgetText(self.lgcombo.currentText()))
        #lgi can be none if we init a new group, in which case we use the GPR value
        if lgi:
            lge = self.parent.confconn.lglist[lgi]
            lce = self.getLCE(lge[1]) if lge[0]==LORG.LAYER else None
        else:
            lce = None
        
        #look for filled layer conf epsg OR use prefs stored in gpr
        if lce and LU.assessNone(lce.epsg):
            epsgval = lce.epsg
        else:
            rdest = str(self.destlist[self.destcombo.currentIndex()])
            _,_,epsgval,_,_ = self.gprParameters(rdest)
        epsgindex = [i[0] for i in self.nzlsr+[(0,0)]+self.rowsr].index(epsgval)
        if self.epsgcombo.currentIndex() != epsgindex:
            self.epsgcombo.setCurrentIndex(int(epsgindex))

        
    def updateGUIValues(self,readlist):
        '''Fill dialog values from provided list'''
        #TODO. Remove circular references when setCurrentIndex() triggers do###Changed()
        #Read user input
        rdest,self.rlgval,ruconf,repsg,rfd,rtd = readlist
        
        #--------------------------------------------------------------------
        
        #Destination Menu
        selecteddest = LU.standardiseDriverNames(rdest)
        if selecteddest not in self.destlist:
            self.destlist = self.getConfiguredDestinations()
            self.destcombo.addItem(selecteddest)
        destindex = self.destlist.index(selecteddest) if selecteddest else 0
        
        if self.destcombo.currentIndex() != destindex:
            self.destcombo.setCurrentIndex(destindex)
        
        #InitButton
        self.initbutton.setText('Layer Select')
        
        #Config File
        confindex = 0
        if LU.assessNone(ruconf):
            ruconf = ruconf.split('.')[0]
            if ruconf not in self.cflist:
                self.cflist += [ruconf,]
                self.confcombo.addItem(ruconf)
            confindex = self.cflist.index(ruconf)
            
        if self.confcombo.currentIndex() != confindex:
            self.confcombo.setCurrentIndex(confindex)
        #self.confEdit.setText(ruconf if LU.assessNone(ruconf) else '')
        
        #Layer/Group Selection
        self.updateLGValues(ruconf,self.rlgval,rdest)
        lgindex = None
        if LU.assessNone(self.rlgval):
            #index of list value
            lgindex = self.parent.confconn.getLayerGroupIndex(self.rlgval,col=1)
            
        if LU.assessNone(lgindex):
            #advance by 1 for sep
            lgindex += 1 if lgindex>self.sepindex else 0 
        else:
            #using the separator index sets the combo to blank
            lgindex = self.sepindex
        if self.lgcombo.currentIndex() != lgindex:
            self.lgcombo.setCurrentIndex(lgindex)
        #self.doLGEditUpdate()
        
        #EPSG
        #                                user > layerconf
        #useepsg = LU.precedence(repsg, lce.epsg if lce else None, None)
        epsgindex = [i[0] for i in self.nzlsr+[(None,None)]+self.rowsr].index(repsg)
        if self.epsgcombo.currentIndex() != epsgindex:
            self.epsgcombo.setCurrentIndex(epsgindex)
            
        #epsgedit = self.epsgcombo.lineEdit()
        #epsgedit.setText([e[1] for e in self.nzlsr+self.rowsr if e[0]==repsg][0])
        
        #epsgedit.setText([e for e in self.nzlsr+self.rowsr if re.match('^\s*(\d+).*',e).group(1)==repsg][0])
        
        #To/From Dates
        if LU.assessNone(rfd):
            self.fromdateedit.setDate(QDate(int(rfd[0:4]),int(rfd[5:7]),int(rfd[8:10])))
        else:
            early = DataStore.EARLIEST_INIT_DATE
            self.fromdateedit.setDate(QDate(int(early[0:4]),int(early[5:7]),int(early[8:10])))
            
        if LU.assessNone(rtd):
            self.todateedit.setDate(QDate(int(rtd[0:4]),int(rtd[5:7]),int(rtd[8:10]))) 
        else:
            today = DataStore.getCurrent()
            self.todateedit.setDate(QDate(int(today[0:4]),int(today[5:7]),int(today[8:10])))
            
        #Internal/External CheckBox
#        if LU.assessNone(rint):
#            self.internalTrigger.setChecked(rint.lower()==DataStore.CONF_INT)
#        else:
#            self.internalTrigger.setChecked(DataStore.DEFAULT_CONF==DataStore.CONF_INT)
        
        
    def getConfiguredDestinations(self):
        defml = ['',]+DataStore.DRIVER_NAMES.values()
        return [d for d in self.parent.gpr.getDestinations() if d in defml]
        
    def doEPSGEnable(self):
        self.epsgcombo.setEnabled(self.epsgenable.isChecked())
        
    def doFromDateEnable(self):
        self.fromdateedit.setEnabled(self.fromdateenable.isChecked())
          
    def doToDateEnable(self):
        self.todateedit.setEnabled(self.todateenable.isChecked())  
          
    def readParameters(self):
        '''Read values out of dialogs'''
        destination = LU.assessNone(str(self.destlist[self.destcombo.currentIndex()]))
        #lgindex = self.parent.confconn.getLayerGroupIndex(self.lgcombo.currentText().toUtf8().data())
        lgindex = self.parent.confconn.getLayerGroupIndex(LQ.readWidgetText(self.lgcombo.currentText()))
        #NB need to test for None explicitly since zero is a valid index
        lgval = self.parent.confconn.lglist[lgindex][1] if LU.assessNone(lgindex) else None       
        #uconf = LU.standardiseUserConfigName(str(self.confcombo.lineEdit().text()))
        #uconf = str(self.confcombo.lineEdit().text())
        uconf = str(self.cflist[self.confcombo.currentIndex()])
        ee = self.epsgenable.isChecked()
        epsg = None if ee is False else re.match('^\s*(\d+).*',str(self.epsgcombo.lineEdit().text())).group(1)
        fe = self.fromdateenable.isChecked()
        te = self.todateenable.isChecked()
        fd = None if fe is False else str(self.fromdateedit.date().toString('yyyy-MM-dd'))
        td = None if te is False else str(self.todateedit.date().toString('yyyy-MM-dd'))
        
        return destination,lgval,uconf,epsg,fe,te,fd,td
    
    def doInitClickAction(self):
        '''Initialise the LC on LC-button-click, action'''
        try:
            try:
                self.setStatus(self.STATUS.BUSY,'Opening Layer-Config Editor')  
                self.progressbar.setValue(0)
                self.parent.runLayerConfigAction()
            finally:
                self.setStatus(self.STATUS.IDLE,'Ready')
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Error in Layer-Config',str(sys.exc_info()))#e))
        
    def doCleanClickAction(self):
        '''Set clean anim and run clean'''
        #lgo = self.lgcombo.currentText().toUtf8().data()
        lgo = LQ.readWidgetText(self.lgcombo.currentText())
        
        try:
            self.setStatus(self.STATUS.CLEAN,'Running Clean '+lgo)
            self.progressbar.setValue(0)
            self.runReplicationScript(True)
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Failed Clean of '+lgo,str(sys.exc_info()))#e))
        
    def doReplicateClickAction(self):
        '''Set busy anim and run repl'''
        lgo = self.lgcombo.currentText()#.toUtf8().data()#only used for error messages
        try:
            self.setStatus(self.STATUS.BUSY,'Running Replicate '+lgo)
            self.progressbar.setValue(0)
            self.runReplicationScript(False)
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Failed Replication of '+lgo,str(sys.exc_info()))#e))

    def runReplicationScript(self,clean=False):
        '''Run the layer/group repliction script'''
        destination,lgval,uconf,epsg,fe,te,fd,td = self.readParameters()
        uconf_path = LU.standardiseUserConfigName(uconf)
        destination_path = LU.standardiseLayerConfigName(destination)
        destination_driver = LU.standardiseDriverNames(destination)

        if not os.path.exists(uconf_path):
            self.userConfMessage(uconf_path)
            return
        elif not MainFileReader(uconf_path).hasSection(destination_driver):
            self.userConfMessage(uconf_path,destination_driver)
            return
        #-----------------------------------------------------
        #'destname','layer','uconf','group','epsg','fd','td','int'
     
        self.parent.gpr.write((destination_driver,lgval,uconf,epsg,fd,td))        
        ldslog.info(u'dest={0}, lg={1}, conf={2}, epsg={3}'.format(destination_driver,lgval,uconf,epsg))
        ldslog.info('fd={0}, td={1}, fe={2}, te={3}'.format(fd,td,fe,te))
        lgindex = self.parent.confconn.getLayerGroupIndex(lgval,col=1)
        #lorg = self.parent.confconn.lglist[lgindex][0]
        #----------don't need lorg in TP anymore but it is useful for sorting/counting groups
        #self.parent.confconn.tp.setLayerOrGroup(lorg)
        self.parent.confconn.tp.setLayerGroupValue(lgval)
        if self.fromdateenable.isChecked(): self.parent.confconn.tp.setFromDate(fd)
        if self.todateenable.isChecked(): self.parent.confconn.tp.setToDate(td)
        self.parent.confconn.tp.setUserConf(uconf)
        if self.epsgenable: self.parent.confconn.tp.setEPSG(epsg)
        
        #because clean state persists in TP
        if clean:
            self.parent.confconn.tp.setCleanConfig()
        else:
            self.parent.confconn.tp.clearCleanConfig()
        #(re)initialise the data source since uconf may have changed
        #>>#self.parent.confconn.tp.src = self.parent.confconn.initSourceWrapper()
        #--------------------------
        ###ep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.destname,self.parent.confconn.uconf)
        
        ###self.parent.confconn.reg.closeEndPoint(self.parent.confconn.destname)
        ###ep = None
        #Open ProcessRunner and run with TP(proc)/self(gui) instances
        #HACK temp add of dest_drv to PR call
        try:
            #TODO. Test for valid LC first
            self.tpr = ProcessRunner(self,destination_driver)
        except Exception as e:
            ldslog.error('Cannot create ProcessRunner {}. NB Possible missing Layer Config {}'.format(str(e),destination_path))
            self.layerConfMessage(destination_path)
            return
        #If PR has been successfully created we must vave a valid dst    
        self.tpr.start()
        
    def quitProcessRunner(self):
        self.tpr.join()
        self.tpr.quit()
        self.trp = None

        
    def userConfMessage(self,uconf,secname=None):
        ucans = QMessageBox.warning(self, 'User Config Missing/Incomplete', 
                                'Specified User-Config file, '+str(uconf)+' does not exist' if secname is None else 'User-Config file does not contain '+str(secname)+' section', 
                                'Back','Initialise User Config')
        if not ucans:
            #Retry
            ldslog.warn('Retry specifying UC')
            #self.confcombo.setCurrentIndex(0)
            return
        #Init
        ldslog.warn('Reset User Config Wizard')
        self.parent.runWizardAction()


    def layerConfMessage(self,dest):
        lcans = QMessageBox.warning(self, 'Layer Config Missing', 
                                'Required Layer-Config file, '+str(dest)+' does not exist', 
                                'Back','Run Layer Select')
        if not lcans:
            #Retry
            ldslog.warn('Retry specifying LC')
            #self.destcombo.setCurrentIndex(0)
            return
        #Init
        ldslog.warn('Reset Layer Config')
        self.doInitClickAction()
Esempio n. 9
0
class AccountPanel(Panel):
    FIELDS = [
        ('nameEdit', 'name'),
        ('accountNumberEdit', 'account_number'),
        ('notesEdit', 'notes'),
    ]
    
    def __init__(self, mainwindow):
        Panel.__init__(self, mainwindow)
        self._setupUi()
        self.model = mainwindow.model.account_panel
        self.model.view = self
        self.typeComboBox = ComboboxModel(model=self.model.type_list, view=self.typeComboBoxView)
        self.currencyComboBox = ComboboxModel(model=self.model.currency_list, view=self.currencyComboBoxView)
        
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
    
    def _setupUi(self):
        self.setWindowTitle(tr("Account Info"))
        self.resize(274, 121)
        self.setModal(True)
        self.verticalLayout = QVBoxLayout(self)
        self.formLayout = QFormLayout()
        self.formLayout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow)
        self.label = QLabel(tr("Name"))
        self.formLayout.setWidget(0, QFormLayout.LabelRole, self.label)
        self.nameEdit = QLineEdit()
        self.formLayout.setWidget(0, QFormLayout.FieldRole, self.nameEdit)
        self.label_2 = QLabel(tr("Type"))
        self.formLayout.setWidget(1, QFormLayout.LabelRole, self.label_2)
        self.typeComboBoxView = QComboBox()
        self.formLayout.setWidget(1, QFormLayout.FieldRole, self.typeComboBoxView)
        self.label_3 = QLabel(tr("Currency"))
        self.formLayout.setWidget(2, QFormLayout.LabelRole, self.label_3)
        self.currencyComboBoxView = QComboBox()
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.currencyComboBoxView.sizePolicy().hasHeightForWidth())
        self.currencyComboBoxView.setSizePolicy(sizePolicy)
        self.currencyComboBoxView.setEditable(True)
        self.currencyComboBoxView.setInsertPolicy(QComboBox.NoInsert)
        self.formLayout.setWidget(2, QFormLayout.FieldRole, self.currencyComboBoxView)
        self.accountNumberLabel = QLabel(tr("Account #"))
        self.formLayout.setWidget(3, QFormLayout.LabelRole, self.accountNumberLabel)
        self.accountNumberEdit = QLineEdit()
        self.accountNumberEdit.setMaximumSize(QSize(80, 16777215))
        self.formLayout.setWidget(3, QFormLayout.FieldRole, self.accountNumberEdit)
        self.notesEdit = QPlainTextEdit()
        self.formLayout.setWidget(4, QFormLayout.FieldRole, self.notesEdit)
        self.label1 = QLabel(tr("Notes:"))
        self.formLayout.setWidget(4, QFormLayout.LabelRole, self.label1)
        self.verticalLayout.addLayout(self.formLayout)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Save)
        self.verticalLayout.addWidget(self.buttonBox)
        self.label.setBuddy(self.nameEdit)
        self.label_2.setBuddy(self.typeComboBoxView)
        self.label_3.setBuddy(self.currencyComboBoxView)
    
    def _loadFields(self):
        Panel._loadFields(self)
        self.currencyComboBoxView.setEnabled(self.model.can_change_currency)
Esempio n. 10
0
class ComboBoxPanel(QWidget):
    def __init__(self, parent, editable=False, spacerItemMove=False):
        QWidget.__init__(self, parent)
        while not isinstance(parent, QDialog):
            parent = parent.parent()
        self.setObjectName("ComboBoxPanel" +
                           str(len(parent.findChildren(ComboBoxPanel))))

        self.hLayoutBoxPanel = QHBoxLayout(self)
        self.hLayoutBoxPanel.setSpacing(0)
        self.hLayoutBoxPanel.setContentsMargins(0, 0, 0, 0)
        self.hLayoutBoxPanel.setObjectName(("hLayoutBoxPanel"))
        self.frameBoxPanel = QFrame(self)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frameBoxPanel.sizePolicy().hasHeightForWidth())
        self.frameBoxPanel.setSizePolicy(sizePolicy)
        self.frameBoxPanel.setFrameShape(QFrame.NoFrame)
        self.frameBoxPanel.setFrameShadow(QFrame.Raised)
        self.frameBoxPanel.setObjectName(("frameBoxPanel"))
        self.hLayoutframeBoxPanel = QHBoxLayout(self.frameBoxPanel)
        self.hLayoutframeBoxPanel.setSpacing(0)
        self.hLayoutframeBoxPanel.setMargin(0)
        self.hLayoutframeBoxPanel.setObjectName(("hLayoutframeBoxPanel"))
        self.captionLabel = QLabel(self.frameBoxPanel)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.captionLabel.sizePolicy().hasHeightForWidth())
        self.captionLabel.setSizePolicy(sizePolicy)
        self.captionLabel.setMinimumSize(QSize(200, 0))
        self.captionLabel.setMaximumSize(QSize(200, 16777215))
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.captionLabel.setFont(font)
        self.captionLabel.setObjectName(("captionLabel"))
        self.hLayoutframeBoxPanel.addWidget(self.captionLabel)

        self.comboBox = QComboBox(self.frameBoxPanel)
        self.comboBox.setEnabled(True)
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.comboBox.setFont(font)
        self.comboBox.setObjectName(self.objectName() + "_comboBox")
        self.comboBox.setMinimumWidth(70)
        # self.comboBox.setMaximumWidth(70)

        # self.hLayoutframeBoxPanel.addWidget(self.lineEdit)
        self.hLayoutframeBoxPanel.addWidget(self.comboBox)

        self.imageButton = QToolButton(self.frameBoxPanel)
        self.imageButton.setText((""))
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/convex_hull.png")), QIcon.Normal,
                       QIcon.Off)
        self.imageButton.setIcon(icon)
        self.imageButton.setObjectName(("imageButton"))
        self.imageButton.setVisible(False)
        self.hLayoutframeBoxPanel.addWidget(self.imageButton)

        self.hLayoutBoxPanel.addWidget(self.frameBoxPanel)
        if not spacerItemMove:
            spacerItem = QSpacerItem(10, 10, QSizePolicy.Expanding,
                                     QSizePolicy.Minimum)
            self.hLayoutBoxPanel.addItem(spacerItem)

        self.comboBox.currentIndexChanged.connect(self.comboBoxChanged)
        # self.comboBox.editTextChanged.connect(self.comboBoxEditTextChanged)
        self.imageButton.clicked.connect(self.imageButtonClicked)

        self.captionUnits = ""

        self.hasObject = False

        self.objectList = []
        if editable == True:
            self.lineEdit = QLineEdit(self.frameBoxPanel)
            self.lineEdit.setObjectName("lineEdit")
            self.hLayoutframeBoxPanel.insertWidget(1, self.lineEdit)
            self.comboBox.setLineEdit(self.lineEdit)
            self.lineEdit.returnPressed.connect(self.comboBoxEditTextChanged)

    def FindString(self, string):
        return self.comboBox.findText(string)

    def comboBoxEditTextChanged(self):
        self.comboBox.showPopup()

    def get_Count(self):
        return self.comboBox.count()

    Count = property(get_Count, None, None, None)

    def method_0(self):
        return self.comboBox.currentIndex(
        ) >= 0 and self.SelectedItem != None and self.SelectedItem != ""

    def method_3(self, string_0):
        return self.comboBox.findText(string_0)

    def method_11(self, string_0):
        if (self.IsEmpty):
            return "%s%s\t" % (string_0, self.Caption)
        return "%s%s\t%s %s" % (string_0, self.Caption, self.Value,
                                self.CaptionUnits)

    def comboBoxChanged(self):
        self.emit(SIGNAL("Event_0"), self)

    def IndexOf(self, item):
        if isinstance(item, str) or isinstance(item, QString):
            return self.comboBox.findText(item)
        else:
            return self.comboBox.findText(item.ToString())

    def Contains(self, item):
        compStr = None
        if isinstance(item, str):
            compStr = item
        elif isinstance(item, float) or isinstance(item, int):
            compStr = str(item)
        else:
            compStr = item.ToString()
        for i in range(self.comboBox.count()):
            comboItemstr = self.comboBox.itemText(i)
            if compStr == comboItemstr:
                return True
        return False

    def Clear(self):
        self.comboBox.clear()
        self.objectList = []
        self.hasObject = False

    def Add(self, item):
        if not isinstance(item, str) and not isinstance(item, QString):
            self.comboBox.addItem(item.ToString())
            self.objectList.append(item)
            self.hasObject = True
            return
        self.comboBox.addItem(item)
        self.hasObject = False

    def Insert(self, index, item):
        if not isinstance(item, str) and not isinstance(item, QString):
            self.comboBox.insertItem(index, item.ToString())
            self.objectList.insert(index, item)
            self.hasObject = True
            return
        self.comboBox.insertItem(index, item)
        self.hasObject = False

    def imageButtonClicked(self):
        self.emit(SIGNAL("Event_3"), self)

    def get_Caption(self):
        caption = self.captionLabel.text()
        findIndex = caption.indexOf("(")
        if findIndex > 0:
            val = caption.left(findIndex)
            return val
        return caption

    def set_Caption(self, captionStr):
        if captionStr == "":
            self.captionLabel.setText("")
            self.LabelWidth = 0
            return
        if self.CaptionUnits != "" and self.CaptionUnits != None:
            self.captionLabel.setText(captionStr + "(" +
                                      QString(self.CaptionUnits) + ")" + ":")
        else:
            self.captionLabel.setText(captionStr + ":")

    Caption = property(get_Caption, set_Caption, None, None)

    def get_CaptionUnits(self):
        return self.captionUnits

    def set_CaptionUnits(self, captionUnits):
        self.captionUnits = captionUnits

    CaptionUnits = property(get_CaptionUnits, set_CaptionUnits, None, None)

    def set_ButtonVisible(self, bool):
        self.imageButton.setVisible(bool)

    ButtonVisible = property(None, set_ButtonVisible, None, None)

    # def get_Value(self):
    #     return self.comboBox.currentIndex()

    # def set_Value(self, value):
    #     try:
    #         self.comboBox.setCurrentIndex(value)
    #     except:
    #         self.textBox.setText("")
    # Value = property(get_Value, set_Value, None, None)

    def get_IsEmpty(self):
        return self.comboBox.currentText() == "" or self.comboBox.currentIndex(
        ) == -1

    IsEmpty = property(get_IsEmpty, None, None, None)

    def get_ReadOnly(self):
        return self.textBox.isReadOnly()

    # def set_ReadOnly(self, bool):
    #     self.comboBox.setR.setReadOnly(bool)
    # ReadOnly = property(get_ReadOnly, set_ReadOnly, None, None)

    def set_LabelWidth(self, width):
        self.captionLabel.setMinimumSize(QSize(width, 0))
        self.captionLabel.setMaximumSize(QSize(width, 16777215))

    LabelWidth = property(None, set_LabelWidth, None, None)

    def set_Width(self, width):
        self.comboBox.setMinimumSize(QSize(width, 0))
        self.comboBox.setMaximumSize(QSize(width, 16777215))

    Width = property(None, set_Width, None, None)

    def set_Button(self, imageName):
        if imageName == None or imageName == "":
            self.imageButton.setVisible(False)
            return
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/" + imageName)), QIcon.Normal,
                       QIcon.Off)
        self.imageButton.setIcon(icon)
        self.imageButton.setVisible(True)

    Button = property(None, set_Button, None, None)

    def get_SelectedIndex(self):
        return self.comboBox.currentIndex()

    def set_SelectedIndex(self, index):
        if self.comboBox.count() == 0:
            return
        if index > self.comboBox.count() - 1:
            self.comboBox.setCurrentIndex(0)
        else:
            self.comboBox.setCurrentIndex(index)

    SelectedIndex = property(get_SelectedIndex, set_SelectedIndex, None, None)

    def get_Value(self):
        return self.comboBox.currentIndex()

    def set_Value(self, valueStr):
        if self.comboBox.count() == 0:
            return
        if valueStr == None:
            self.SelectedIndex = -1
            return
        self.comboBox.setCurrentIndex(self.comboBox.findText(str(valueStr)))

    Value = property(get_Value, set_Value, None, None)

    def get_Items(self):
        # if self.hasObject:
        #     return self.objectList
        itemList = []
        if self.comboBox.count() > 0:
            for i in range(self.comboBox.count()):
                itemList.append(self.comboBox.itemText(i))
        return itemList

    def set_AddItems(self, strList):
        self.Clear()
        if len(strList) != 0 and (not isinstance(strList[0], str)
                                  and not isinstance(strList[0], QString)):
            for obj in strList:
                self.comboBox.addItem(obj.ToString())
                self.objectList.append(obj)
            self.hasObject = True
            return
        self.comboBox.addItems(strList)

    Items = property(get_Items, set_AddItems, None, None)

    def get_Enabled(self):
        return self.comboBox.isEnabled()

    def set_Enabled(self, bool):
        self.comboBox.setEnabled(bool)

    Enabled = property(get_Enabled, set_Enabled, None, None)

    def get_Visible(self):
        return self.isVisible()

    def set_Visible(self, bool):
        self.setVisible(bool)

    Visible = property(get_Visible, set_Visible, None, None)

    def get_Editable(self):
        return self.comboBox.isEditable()

    def set_Editable(self, bool):
        self.comboBox.setEditable(bool)

    Editable = property(get_Editable, set_Editable, None, None)

    def get_SelectedItem(self):
        if self.comboBox.count() == 0:
            return None
        if self.hasObject:
            return self.objectList[self.SelectedIndex]
        return self.comboBox.currentText()

    def set_SelectedItem(self, val):
        index = self.comboBox.findText(val)
        self.comboBox.setCurrentIndex(index)

    SelectedItem = property(get_SelectedItem, set_SelectedItem, None, None)
Esempio n. 11
0
class Interface(QWidget):
    """Interface widget class."""
    def __init__(self, parent):
        super(Interface, self).__init__()
        self._preferences, vbox = parent, QVBoxLayout(self)
        self.toolbar_settings = settings.TOOLBAR_ITEMS

        groupBoxExplorer = QGroupBox(
            translations.TR_PREFERENCES_INTERFACE_EXPLORER_PANEL)
        #groupBoxToolbar = QGroupBox(
        #translations.TR_PREFERENCES_INTERFACE_TOOLBAR_CUSTOMIZATION)
        groupBoxLang = QGroupBox(
            translations.TR_PREFERENCES_INTERFACE_LANGUAGE)

        #Explorer
        vboxExplorer = QVBoxLayout(groupBoxExplorer)
        self._checkProjectExplorer = QCheckBox(
            translations.TR_PREFERENCES_SHOW_EXPLORER)
        self._checkSymbols = QCheckBox(
            translations.TR_PREFERENCES_SHOW_SYMBOLS)
        self._checkWebInspetor = QCheckBox(
            translations.TR_PREFERENCES_SHOW_WEB_INSPECTOR)
        self._checkFileErrors = QCheckBox(
            translations.TR_PREFERENCES_SHOW_FILE_ERRORS)
        self._checkMigrationTips = QCheckBox(
            translations.TR_PREFERENCES_SHOW_MIGRATION)
        vboxExplorer.addWidget(self._checkProjectExplorer)
        vboxExplorer.addWidget(self._checkSymbols)
        vboxExplorer.addWidget(self._checkWebInspetor)
        vboxExplorer.addWidget(self._checkFileErrors)
        vboxExplorer.addWidget(self._checkMigrationTips)
        #GUI - Toolbar
        #vbox_toolbar = QVBoxLayout(groupBoxToolbar)
        #hbox_select_items = QHBoxLayout()
        #label_toolbar = QLabel(translations.TR_PREFERENCES_TOOLBAR_ITEMS)
        #label_toolbar.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        #hbox_select_items.addWidget(label_toolbar)
        #self._comboToolbarItems = QComboBox()
        #self._load_combo_data(self._comboToolbarItems)
        #self._btnItemAdd = QPushButton(QIcon(":img/add"), '')
        #self._btnItemAdd.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        #self._btnItemAdd.setIconSize(QSize(16, 16))
        #self._btnItemRemove = QPushButton(QIcon(':img/delete'), '')
        #self._btnItemRemove.setIconSize(QSize(16, 16))
        #self._btnDefaultItems = QPushButton(
        #translations.TR_PREFERENCES_TOOLBAR_DEFAULT)
        #self._btnDefaultItems.setSizePolicy(QSizePolicy.Fixed,
        #QSizePolicy.Fixed)
        #self._btnItemRemove.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        #hbox_select_items.addWidget(self._comboToolbarItems)
        #hbox_select_items.addWidget(self._btnItemAdd)
        #hbox_select_items.addWidget(self._btnItemRemove)
        #hbox_select_items.addWidget(self._btnDefaultItems)
        #vbox_toolbar.addLayout(hbox_select_items)
        #self._toolbar_items = QToolBar()
        #self._toolbar_items.setObjectName("custom")
        #self._toolbar_items.setToolButtonStyle(Qt.ToolButtonIconOnly)
        #self._load_toolbar()
        #vbox_toolbar.addWidget(self._toolbar_items)
        #vbox_toolbar.addWidget(QLabel(
        #translations.TR_PREFERENCES_TOOLBAR_CONFIG_HELP))
        #Language
        vboxLanguage = QVBoxLayout(groupBoxLang)
        vboxLanguage.addWidget(
            QLabel(translations.TR_PREFERENCES_SELECT_LANGUAGE))
        self._comboLang = QComboBox()
        self._comboLang.setEnabled(False)
        vboxLanguage.addWidget(self._comboLang)
        vboxLanguage.addWidget(
            QLabel(translations.TR_PREFERENCES_REQUIRES_RESTART))

        #Load Languages
        self._load_langs()

        #Settings
        self._checkProjectExplorer.setChecked(settings.SHOW_PROJECT_EXPLORER)
        self._checkSymbols.setChecked(settings.SHOW_SYMBOLS_LIST)
        self._checkWebInspetor.setChecked(settings.SHOW_WEB_INSPECTOR)
        self._checkFileErrors.setChecked(settings.SHOW_ERRORS_LIST)
        self._checkMigrationTips.setChecked(settings.SHOW_MIGRATION_LIST)

        vbox.addWidget(groupBoxExplorer)
        #vbox.addWidget(groupBoxToolbar)
        vbox.addWidget(groupBoxLang)

        #Signals
        #self.connect(self._btnItemAdd, SIGNAL("clicked()"),
        #self.toolbar_item_added)
        #self.connect(self._btnItemRemove, SIGNAL("clicked()"),
        #self.toolbar_item_removed)
        #self.connect(self._btnDefaultItems, SIGNAL("clicked()"),
        #self.toolbar_items_default)

        self.connect(self._preferences, SIGNAL("savePreferences()"), self.save)

    #def toolbar_item_added(self):
    #data = self._comboToolbarItems.itemData(
    #self._comboToolbarItems.currentIndex())
    #if data not in self.toolbar_settings or data == 'separator':
    #selected = self.actionGroup.checkedAction()
    #if selected is None:
    #self.toolbar_settings.append(data)
    #else:
    #dataAction = selected.data()
    #self.toolbar_settings.insert(
    #self.toolbar_settings.index(dataAction) + 1, data)
    #self._load_toolbar()


##    def toolbar_item_removed(self):
#data = self._comboToolbarItems.itemData(
#self._comboToolbarItems.currentIndex())
#if data in self.toolbar_settings and data != 'separator':
#self.toolbar_settings.pop(self.toolbar_settings.index(data))
#self._load_toolbar()
#elif data == 'separator':
#self.toolbar_settings.reverse()
#self.toolbar_settings.pop(self.toolbar_settings.index(data))
#self.toolbar_settings.reverse()
#self._load_toolbar()

##    def toolbar_items_default(self):
#self.toolbar_settings = settings.TOOLBAR_ITEMS_DEFAULT
#self._load_toolbar()

##    def _load_combo_data(self, combo):
#self.toolbar_items = {
#'separator': [QIcon(':img/separator'), 'Add Separtor'],
#'new-file': [QIcon(resources.IMAGES['new']), self.tr('New File')],
#'new-project': [QIcon(resources.IMAGES['newProj']),
#self.tr('New Project')],
#'save-file': [QIcon(resources.IMAGES['save']),
#self.tr('Save File')],
#'save-as': [QIcon(resources.IMAGES['saveAs']), self.tr('Save As')],
#'save-all': [QIcon(resources.IMAGES['saveAll']),
#self.tr('Save All')],
#'save-project': [QIcon(resources.IMAGES['saveAll']),
#self.tr('Save Project')],
#'reload-file': [QIcon(resources.IMAGES['reload-file']),
#self.tr('Reload File')],
#'open-file': [QIcon(resources.IMAGES['open']),
#self.tr('Open File')],
#'open-project': [QIcon(resources.IMAGES['openProj']),
#self.tr('Open Project')],
#'activate-profile': [QIcon(resources.IMAGES['activate-profile']),
#self.tr('Activate Profile')],
#'deactivate-profile':
#[QIcon(resources.IMAGES['deactivate-profile']),
#self.tr('Deactivate Profile')],
#'print-file': [QIcon(resources.IMAGES['print']),
#self.tr('Print File')],
#'close-file':
#[self.style().standardIcon(QStyle.SP_DialogCloseButton),
#self.tr('Close File')],
#'close-projects':
#[self.style().standardIcon(QStyle.SP_DialogCloseButton),
#self.tr('Close Projects')],
#'undo': [QIcon(resources.IMAGES['undo']), self.tr('Undo')],
#'redo': [QIcon(resources.IMAGES['redo']), self.tr('Redo')],
#'cut': [QIcon(resources.IMAGES['cut']), self.tr('Cut')],
#'copy': [QIcon(resources.IMAGES['copy']), self.tr('Copy')],
#'paste': [QIcon(resources.IMAGES['paste']), self.tr('Paste')],
#'find': [QIcon(resources.IMAGES['find']), self.tr('Find')],
#'find-replace': [QIcon(resources.IMAGES['findReplace']),
#self.tr('Find/Replace')],
#'find-files': [QIcon(resources.IMAGES['find']),
#self.tr('Find In files')],
#'code-locator': [QIcon(resources.IMAGES['locator']),
#self.tr('Code Locator')],
#'splith': [QIcon(resources.IMAGES['splitH']),
#self.tr('Split Horizontally')],
#'splitv': [QIcon(resources.IMAGES['splitV']),
#self.tr('Split Vertically')],
#'follow-mode': [QIcon(resources.IMAGES['follow']),
#self.tr('Follow Mode')],
#'zoom-in': [QIcon(resources.IMAGES['zoom-in']), self.tr('Zoom In')],
#'zoom-out': [QIcon(resources.IMAGES['zoom-out']),
#self.tr('Zoom Out')],
#'indent-more': [QIcon(resources.IMAGES['indent-more']),
#self.tr('Indent More')],
#'indent-less': [QIcon(resources.IMAGES['indent-less']),
#self.tr('Indent Less')],
#'comment': [QIcon(resources.IMAGES['comment-code']),
#self.tr('Comment')],
#'uncomment': [QIcon(resources.IMAGES['uncomment-code']),
#self.tr('Uncomment')],
#'go-to-definition': [QIcon(resources.IMAGES['go-to-definition']),
#self.tr('Go To Definition')],
#'insert-import': [QIcon(resources.IMAGES['insert-import']),
#self.tr('Insert Import')],
#'run-project': [QIcon(resources.IMAGES['play']), 'Run Project'],
#'run-file': [QIcon(resources.IMAGES['file-run']), 'Run File'],
#'stop': [QIcon(resources.IMAGES['stop']), 'Stop'],
#'preview-web': [QIcon(resources.IMAGES['preview-web']),
#self.tr('Preview Web')]}
#for item in self.toolbar_items:
#combo.addItem(self.toolbar_items[item][0],
#self.toolbar_items[item][1], item)
#combo.model().sort(0)

##    def _load_toolbar(self):
#pass
##self._toolbar_items.clear()
##self.actionGroup = QActionGroup(self)
##self.actionGroup.setExclusive(True)
##for item in self.toolbar_settings:
##if item == 'separator':
##self._toolbar_items.addSeparator()
##else:
##action = self._toolbar_items.addAction(
##self.toolbar_items[item][0], self.toolbar_items[item][1])
##action.setData(item)
##action.setCheckable(True)
##self.actionGroup.addAction(action)

    def _load_langs(self):
        langs = file_manager.get_files_from_folder(resources.LANGS, '.qm')
        self._languages = ['English'] + \
            [file_manager.get_module_name(lang) for lang in langs]
        self._comboLang.addItems(self._languages)
        if (self._comboLang.count() > 1):
            self._comboLang.setEnabled(True)
        if settings.LANGUAGE:
            index = self._comboLang.findText(settings.LANGUAGE)
        else:
            index = 0
        self._comboLang.setCurrentIndex(index)

    def save(self):
        qsettings = IDE.ninja_settings()
        settings.TOOLBAR_ITEMS = self.toolbar_settings
        lang = self._comboLang.currentText()
        #preferences/interface
        qsettings.setValue('preferences/interface/showProjectExplorer',
                           self._checkProjectExplorer.isChecked())
        settings.SHOW_PROJECT_EXPLORER = self._checkProjectExplorer.isChecked()
        qsettings.setValue('preferences/interface/showSymbolsList',
                           self._checkSymbols.isChecked())
        settings.SHOW_SYMBOLS_LIST = self._checkSymbols.isChecked()
        qsettings.setValue('preferences/interface/showWebInspector',
                           self._checkWebInspetor.isChecked())
        settings.SHOW_WEB_INSPECTOR = self._checkWebInspetor.isChecked()
        qsettings.setValue('preferences/interface/showErrorsList',
                           self._checkFileErrors.isChecked())
        settings.SHOW_ERRORS_LIST = self._checkFileErrors.isChecked()
        qsettings.setValue('preferences/interface/showMigrationList',
                           self._checkMigrationTips.isChecked())
        settings.SHOW_MIGRATION_LIST = self._checkMigrationTips.isChecked()
        #qsettings.setValue('preferences/interface/toolbar',
        #settings.TOOLBAR_ITEMS)
        qsettings.setValue('preferences/interface/language', lang)
        lang = lang + '.qm'
        settings.LANGUAGE = os.path.join(resources.LANGS, lang)
Esempio n. 12
0
class SkinsTab(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        vbox = QVBoxLayout(self)

        #Top Bar
        hbox = QHBoxLayout()
        self.radioDefault = QRadioButton("Default Skin")
        self.radioCustom = QRadioButton("Custom")
        self.comboSkins = QComboBox()
        self.skins = loader.load_gui_skins()
        for item in self.skins:
            self.comboSkins.addItem(item)
        hbox.addWidget(self.radioDefault)
        hbox.addWidget(self.radioCustom)
        hbox.addWidget(self.comboSkins)
        #Text Area
        self.txtStyle = QPlainTextEdit()
        self.txtStyle.setReadOnly(True)

        #Settings
        settings = QSettings()
        settings.beginGroup('preferences')
        settings.beginGroup('skins')
        if settings.value('default', True).toBool():
            self.radioDefault.setChecked(True)
            self.comboSkins.setEnabled(False)
        else:
            self.radioCustom.setChecked(True)
            index = self.comboSkins.findText(
                settings.value('selectedSkin', '').toString())
            self.comboSkins.setCurrentIndex(index)
            content = self.skins[str(self.comboSkins.currentText())]
            self.txtStyle.setPlainText(content)
        settings.endGroup()
        settings.endGroup()

        vbox.addLayout(hbox)
        vbox.addWidget(self.txtStyle)
        vbox.addWidget(QLabel('Requires restart the IDE'))

        #Signals
        self.connect(self.radioDefault, SIGNAL("clicked()"),
                     self._default_clicked)
        self.connect(self.radioCustom, SIGNAL("clicked()"),
                     self._custom_clicked)

    def _default_clicked(self):
        self.comboSkins.setEnabled(False)
        self.txtStyle.setPlainText('')

    def _custom_clicked(self):
        self.comboSkins.setEnabled(True)
        content = self.skins[str(self.comboSkins.currentText())]
        self.txtStyle.setPlainText(content)

    def save(self):
        settings = QSettings()
        settings.beginGroup('preferences')
        settings.beginGroup('skins')
        settings.setValue('default', self.radioDefault.isChecked())
        settings.setValue('selectedSkin', self.comboSkins.currentText())
        settings.endGroup()
        settings.endGroup()
Esempio n. 13
0
class Master(QMainWindow):
    """A manager to synchronise and control experiment modules.
    
    Initiates the Andor camera and connects its completed acquisition
    signal to the image analysis and the image saving modules.
    Uses the queue module to create the list of sequences to run,
    and the bridge module to communicate with Dexter.
    This master module will define the run number. It must confirm that
    each Dexter sequence has run successfully in order to stay synchronised.
    Keyword arguments:
    state_config -- path to the file that saved the previous state.
                    Default directories for camera settings and image 
                    saving are also saved in this file.
    image_analysis -- a class inheriting QMainWindow that can perform all of the
                    required image analysis methods
    """
    def __init__(self,
                 state_config='.\\state',
                 image_analysis=settings_window):
        super().__init__()
        self.types = OrderedDict([('File#', int), ('Date', str),
                                  ('CameraConfig', str), ('SaveConfig', str),
                                  ('MasterGeometry', intstrlist),
                                  ('AnalysisGeometry', intstrlist),
                                  ('SequencesGeometry', intstrlist)])
        self.stats = OrderedDict([
            ('File#', 0), ('Date', time.strftime("%d,%B,%Y")),
            ('CameraConfig',
             '.\\andorcamera\\Standard modes\\ExExposure_config.dat'),
            ('SaveConfig', '.\\config\\config.dat'),
            ('MasterGeometry', [10, 10, 500, 150]),
            ('AnalysisGeometry', [1400, 400, 600, 500]),
            ('SequencesGeometry', [20, 100, 1000, 800])
        ])
        self.camera_pause = 0  # time in seconds to wait for camera to start acquisition.
        self.ts = {
            label: time.time()
            for label in
            ['init', 'waiting', 'blocking', 'msg start', 'msg end']
        }
        sv_dirs = event_handler.get_dirs(self.stats['SaveConfig'])
        # if not any(os.path.exists(svd) for svd in sv_dirs.values()): # ask user to choose valid config file
        startn = self.restore_state(file_name=state_config)
        # choose which image analyser to use from number images in sequence
        self.init_UI(startn)
        # initialise the thread controlling run # and emitting images
        self.rn = runnum(
            camera(config_file=self.stats['CameraConfig']),  # Andor camera
            event_handler(self.stats['SaveConfig']),  # image saver
            image_analysis(results_path=sv_dirs['Results Path: '],
                           im_store_path=sv_dirs['Image Storage Path: ']
                           ),  # image analysis
            atom_window(last_im_path=sv_dirs['Image Storage Path: ']
                        ),  # check if atoms are in ROIs to trigger experiment
            Previewer(),  # sequence editor
            n=startn,
            m=1,
            k=0)
        # now the signals are connected, send camera settings to image analysis
        if self.rn.cam.initialised > 2:
            check = self.rn.cam.ApplySettingsFromConfig(
                self.stats['CameraConfig'])

        self.rn.server.dxnum.connect(
            self.Dx_label.setText)  # synchronise run number
        self.rn.server.textin.connect(self.respond)  # read TCP messages
        self.status_label.setText('Initialising...')
        QTimer.singleShot(
            0, self.idle_state)  # takes a while for other windows to load

        # self.rn.check.showMaximized()
        self.rn.seq.setGeometry(*self.stats['SequencesGeometry'])
        self.rn.seq.show()
        self.rn.sw.setGeometry(*self.stats['AnalysisGeometry'])
        self.rn.sw.show()
        self.rn.sw.show_analyses(show_all=True)

        self.mon_win = MonitorStatus()
        self.mon_win.start_button.clicked.connect(self.start_monitor)
        self.mon_win.stop_button.clicked.connect(self.stop_monitor)
        self.rn.monitor.textin[str].connect(self.mon_win.set_label)
        self.rn.monitor.textin.connect(self.mon_win.set_connected)
        # set a timer to update the dates 2s after midnight:
        t0 = time.localtime()
        QTimer.singleShot((86402 - 3600 * t0[3] - 60 * t0[4] - t0[5]) * 1e3,
                          self.reset_dates)

    def idle_state(self):
        """When the master thread is not processing user events, it is in the idle states.
        The status label is also used as an indicator for DExTer's current state."""
        self.status_label.setText('Idle')

    def restore_state(self, file_name='./state'):
        """Use the data stored in the given file to restore the file # for
        synchronisation if it is the same day, and use the same config files."""
        try:
            with open(file_name, 'r') as f:
                for line in f:
                    if len(line.split(
                            '=')) == 2:  # there should only be one = per line
                        key, val = line.replace('\n', '').split('=')
                        try:
                            self.stats[key] = self.types[key](val)
                        except KeyError as e:
                            logger.warning(
                                'Failed to load PyDex state line: ' + line +
                                '\n' + str(e))
        except FileNotFoundError as e:
            logger.warning(
                'PyDex master settings could not find the state file.\n' +
                str(e))
        if self.stats['Date'] == time.strftime(
                "%d,%B,%Y"):  # restore file number
            return self.stats['File#']  # [Py]DExTer file number
        else:
            return 0

    def make_label_edit(self,
                        label_text,
                        layout,
                        position=[0, 0, 1, 1],
                        default_text='',
                        validator=False):
        """Make a QLabel with an accompanying QLineEdit and add them to the 
        given layout with an input validator. The position argument should
        be [row number, column number, row width, column width]."""
        label = QLabel(label_text, self)
        layout.addWidget(label, *position)
        line_edit = QLineEdit(self)
        if np.size(position) == 4:
            position[1] += 1
        layout.addWidget(line_edit, *position)
        line_edit.setText(default_text)
        if validator:
            line_edit.setValidator(validator)
        return label, line_edit

    def init_UI(self, startn=0):
        """Create all of the widget objects required
        startn: the initial run number loaded from previous state"""
        self.centre_widget = QWidget()
        self.centre_widget.layout = QGridLayout()
        self.centre_widget.setLayout(self.centre_widget.layout)
        self.setCentralWidget(self.centre_widget)

        #### menubar at top gives options ####
        menubar = self.menuBar()

        show_windows = menubar.addMenu('Windows')
        menu_items = []
        for window_title in [
                'Image Analyser', 'Camera Status', 'Image Saver', 'TCP Server',
                'Sequence Previewer', 'Atom Checker', 'Monitor'
        ]:
            menu_items.append(QAction(window_title, self))
            menu_items[-1].triggered.connect(self.show_window)
            show_windows.addAction(menu_items[-1])

        sync_menu = menubar.addMenu('Run Settings')
        self.sync_toggle = QAction('Sync with DExTer',
                                   sync_menu,
                                   checkable=True,
                                   checked=True)
        self.sync_toggle.setChecked(True)
        self.sync_toggle.toggled.connect(self.sync_mode)
        sync_menu.addAction(self.sync_toggle)

        self.check_rois = QAction('Trigger on atoms loaded',
                                  sync_menu,
                                  checkable=True,
                                  checked=False)
        self.check_rois.setChecked(False)
        self.check_rois.setEnabled(False)  # not functional yet
        sync_menu.addAction(self.check_rois)

        reset_date = QAction('Reset date', sync_menu, checkable=False)
        reset_date.triggered.connect(self.reset_dates)
        sync_menu.addAction(reset_date)

        #### status of the master program ####
        self.status_label = QLabel('Initiating...', self)
        self.centre_widget.layout.addWidget(self.status_label, 0, 0, 1, 3)

        Dx_label = QLabel('Run #: ', self)
        self.centre_widget.layout.addWidget(Dx_label, 1, 0, 1, 1)
        self.Dx_label = QLabel(str(startn), self)
        self.centre_widget.layout.addWidget(self.Dx_label, 1, 1, 1, 1)

        # actions that can be carried out
        self.actions = QComboBox(self)
        self.actions.addItems([
            'Run sequence', 'Multirun run', 'Pause multirun',
            'Resume multirun', 'Cancel multirun', 'TCP load sequence',
            'TCP load sequence from string', 'Save DExTer sequence',
            'Cancel Python Mode', 'Resync DExTer', 'Start acquisition'
        ])
        self.actions.resize(self.actions.sizeHint())
        self.centre_widget.layout.addWidget(self.actions, 2, 0, 1, 1)

        self.action_button = QPushButton('Go', self, checkable=False)
        self.action_button.clicked[bool].connect(self.start_action)
        self.action_button.resize(self.action_button.sizeHint())
        self.centre_widget.layout.addWidget(self.action_button, 2, 1, 1, 1)

        # text box to allow user to specify DExTer sequence file
        _, self.seq_edit = self.make_label_edit('DExTer sequence file: ',
                                                self.centre_widget.layout,
                                                position=[3, 0, 1, 1])
        # button to load sequence location from file browser
        self.seq_browse = QPushButton('Browse', self, checkable=False)
        self.seq_browse.clicked[bool].connect(self.browse_sequence)
        self.seq_browse.resize(self.seq_browse.sizeHint())
        self.centre_widget.layout.addWidget(self.seq_browse, 3, 2, 1, 1)

        #### choose main window position, dimensions: (xpos,ypos,width,height)
        self.setGeometry(*self.stats['MasterGeometry'])
        self.setWindowTitle('PyDex Master')
        self.setWindowIcon(QIcon('docs/pydexicon.png'))

    def reset_dates(self, auto=True):
        """Reset the date in the image saving and analysis, 
        then display the updated date"""
        t0 = time.localtime()
        self.stats['Date'] = time.strftime("%d,%B,%Y", t0)
        date = self.rn.reset_dates(t0)
        if not hasattr(self.sender(),
                       'text'):  # don't set timer if user pushed button
            QTimer.singleShot(
                (86402 - 3600 * t0[3] - 60 * t0[4] - t0[5]) * 1e3,
                self.reset_dates)  # set the next timer to reset dates
        logger.info(time.strftime("Date reset: %d %B %Y", t0))

    def show_window(self):
        """Show the window of the submodule or adjust its settings."""
        if self.sender().text() == 'Image Analyser':
            self.rn.sw.show()

        elif self.sender().text() == 'Camera Status':
            if self.rn.cam.initialised:
                msg = 'Current state: ' + self.rn.cam.AF.GetStatus(
                ) + '\nChoose a new config file: '
            else:
                msg = 'Camera not initialised. See log file for details. Press OK to retry.'
            newfile = self.rn.sw.try_browse(
                title='Choose new config file',
                file_type='config (*.dat);;all (*)',
                defaultpath=os.path.dirname(self.stats['CameraConfig']))
            text, ok = QInputDialog.getText(
                self,
                'Camera Status',
                msg,
                text=newfile if newfile else self.stats['CameraConfig'])
            if text and ok:
                if self.rn.cam.initialised > 2:
                    if self.rn.cam.AF.GetStatus() == 'DRV_ACQUIRING':
                        self.rn.cam.AF.AbortAcquisition()
                    check = self.rn.cam.ApplySettingsFromConfig(text)
                    if not any(check):
                        self.status_label.setText('Camera settings config: ' +
                                                  text)
                        self.stats['CameraConfig'] = text
                    else:
                        self.status_label.setText(
                            'Failed to update camera settings.')
                else:
                    self.reset_camera(text)

        elif self.sender().text() == 'Image Saver':
            text, ok = QInputDialog.getText(
                self,
                'Image Saver',
                self.rn.sv.print_dirs(self.rn.sv.dirs_dict.items()) +
                '\nEnter the path to a config file to reset the image saver: ',
                text=self.stats['SaveConfig'])
            if text and ok:
                remove_slot(self.rn.im_save, self.rn.sv.add_item, False)
                self.rn.sv = event_handler(text)
                if self.rn.sv.image_storage_path:
                    self.status_label.setText('Image Saver config: ' + text)
                    remove_slot(self.rn.im_save, self.rn.sv.add_item, True)
                    self.stats['SaveConfig'] = text
                else:
                    self.status_label.setText('Failed to find config file.')

        elif self.sender().text() == 'Sequence Previewer':
            self.rn.seq.show()
        elif self.sender().text() == 'TCP Server':
            info = 'Trigger server is running.\n' if self.rn.trigger.isRunning(
            ) else 'Trigger server stopped.\n'
            if self.rn.server.isRunning():
                msgs = self.rn.server.get_queue()
                info += "TCP server is running. %s queued message(s)." % len(
                    msgs)
                info += '\nCommand Enum | Length |\t Message\n'
                for enum, textlength, text in msgs[:5]:
                    info += enum + ' | ' + text[:20]
                    if textlength > 20: info += '...'
                    info += '\n'
                if len(msgs) > 5:
                    info += '...\n'
            else:
                info += "TCP server stopped."
            reply = QMessageBox.question(
                self, 'TCP Server Status',
                info + "\nDo you want to restart the server?",
                QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if reply == QMessageBox.Yes:
                self.action_button.setEnabled(True)
                self.rn.seq.mr.mr_queue = []
                self.rn.multirun = False
                self.rn.reset_server(
                    force=True)  # stop and then restart the servers
                self.rn.server.add_message(
                    TCPENUM['TCP read'],
                    'Sync DExTer run number\n' + '0' * 2000)
            elif reply == QMessageBox.No:
                self.rn.reset_server(
                    force=False)  # restart the server if it stopped
        elif self.sender().text() == 'Atom Checker':
            self.rn.check.showMaximized()
        elif self.sender().text() == 'Monitor':
            self.mon_win.show()

    def start_monitor(self, toggle=True):
        """Send a TCP command to the monitor to start its acquisition."""
        self.mon_win.start_check()
        self.rn.monitor.add_message(self.rn._n, 'start')

    def stop_monitor(self, toggle=True):
        """Send a TCP command to the monitor to stop its acquisition."""
        self.mon_win.start_check()
        self.rn.monitor.add_message(self.rn._n, 'stop')

    def browse_sequence(self, toggle=True):
        """Open the file browser to search for a sequence file, then insert
        the file path into the DExTer sequence file line edit
        start_dir: the directory to open initially."""
        try:
            if 'PyQt4' in sys.modules:
                file_name = QFileDialog.getOpenFileName(
                    self, 'Select A Sequence', '', 'Sequence (*.xml);;all (*)')
            elif 'PyQt5' in sys.modules:
                file_name, _ = QFileDialog.getOpenFileName(
                    self, 'Select A Sequence', '', 'Sequence (*.xml);;all (*)')
            if file_name:
                self.seq_edit.setText(file_name.replace('/', '\\'))
                self.rn.seq.load_seq_from_file(file_name)
        except OSError:
            pass  # user cancelled - file not found

    def reset_camera(self, ancam_config='./andorcamera/ExExposure_config.dat'):
        """Close the camera and then start it up again with the new setting.
        Sometimes after being in crop mode the camera fails to reset the 
        ROI and so must be closed and restarted."""
        try:
            self.rn.cam.SafeShutdown()
        except:
            logger.warning('Andor camera safe shutdown failed'
                           )  # probably not initialised
        self.rn.cam = camera(config_file=ancam_config)  # Andor camera
        remove_slot(self.rn.cam.AcquireEnd, self.rn.receive,
                    True)  # connect signal
        self.status_label.setText('Camera settings config: ' + ancam_config)
        self.stats['CameraConfig'] = ancam_config

    def start_action(self):
        """Perform the action currently selected in the actions combobox.
        Run sequence:   Start the camera acquisition, then make 
                        DExTer perform a single run of the 
                        sequence that is currently loaded.
        Multirun run:   Start the camera acquisition, then make 
                        DExTer perform a multirun with the preloaded
                        multirun settings.
        TCP load sequence from string: Tell DExTer to load in the sequence
                        from a string in XML format.
        TCP load sequence:  Tell DExTer to load in the sequence file at
                        the location in the 'DExTer sequence file' label.
        Cancel python mode: send the text 'python mode off' which triggers
                        DExTer to exit python mode.
        Resync DExTer:  send a null message just to resync the run number.
        Start acquisition:  start the camera acquiring without telling
                        DExTer to run. Used in unsynced mode."""
        action_text = self.actions.currentText()
        if action_text == 'Start acquisition' and self.action_button.text(
        ) == 'Go':
            if self.rn.cam.initialised > 2:
                if self.sync_toggle.isChecked():
                    QMessageBox.warning(
                        self, 'Unscyned acquisition',
                        'Warning: started acquisition in synced mode. Without messages to DExTer, the file ID will not update.'
                        +
                        '\nTry unchecking: "Run Settings" > "Sync with DExTer".'
                    )
                self.actions.setEnabled(
                    False)  # don't process other actions in this mode
                self.rn._k = 0  # reset image per run count
                self.action_button.setText('Stop acquisition')
                self.rn.cam.start()  # start acquisition
                self.wait_for_cam(
                )  # wait for camera to initialise before running
                self.status_label.setText('Camera acquiring')
            else:
                logger.warning(
                    'Master: Tried to start camera acquisition but camera is not initialised.'
                )
        elif action_text == 'Start acquisition' and self.action_button.text(
        ) == 'Stop acquisition':
            self.actions.setEnabled(True)
            self.action_button.setText('Go')
            self.end_run()

        if self.rn.server.isRunning():
            if action_text == 'Run sequence':
                # queue up messages: start acquisition, check run number
                self.action_button.setEnabled(
                    False)  # only process 1 run at a time
                self.rn._k = 0  # reset image per run count
                self.rn.server.add_message(TCPENUM['TCP read'],
                                           'start acquisition\n' + '0' * 2000)
                self.rn.monitor.add_message(self.rn._n, 'update run number')
            elif action_text == 'Multirun run':
                if self.rn.seq.mr.check_table():
                    if not self.sync_toggle.isChecked():
                        self.sync_toggle.setChecked(
                            True)  # it's better to multirun in synced mode
                        logger.warning(
                            'Multirun has changed the "sync with DExTer" setting.'
                        )
                    status = self.rn.seq.mr.check_mr_params(
                        self.rn.sv.results_path)  # add to queue if valid
                    self.check_mr_queue(
                    )  # prevent multiple multiruns occurring simultaneously
                else:
                    QMessageBox.warning(
                        self, 'Invalid multirun',
                        'All cells in the multirun table must be populated.')
            elif action_text == 'Resume multirun':
                self.rn.multirun_resume(self.status_label.text())
            elif action_text == 'Pause multirun':
                if 'multirun' in self.status_label.text():
                    self.rn.multirun_go(False, stillrunning=True)
            elif action_text == 'Cancel multirun':
                if 'multirun' in self.status_label.text() or self.rn.multirun:
                    if self.rn.check.checking:
                        self.rn.check.rh.trigger.emit(
                            1)  # send software trigger to end
                    self.rn.multirun_go(False)
                    self.rn.seq.mr.ind = 0
                    self.rn.seq.mr.reset_sequence(self.rn.seq.tr.copy())
            elif action_text == 'TCP load sequence from string':
                self.rn.server.add_message(TCPENUM[action_text],
                                           self.rn.seq.tr.seq_txt)
            elif action_text == 'TCP load sequence':
                self.rn.server.add_message(
                    TCPENUM[action_text],
                    self.seq_edit.text() + '\n' + '0' * 2000)
            elif action_text == 'Save DExTer sequence':
                self.rn.server.add_message(
                    TCPENUM['Save sequence'],
                    'save log file automatic name\n' + '0' * 2000)
            elif action_text == 'Cancel Python Mode':
                self.rn.server.add_message(TCPENUM['TCP read'],
                                           'python mode off\n' + '0' * 2000)
                self.rn.server.add_message(
                    TCPENUM['TCP read'],
                    'Resync DExTer\n' + '0' * 2000)  # for when it reconnects
            elif action_text == 'Resync DExTer':
                self.rn.server.add_message(TCPENUM['TCP read'],
                                           'Resync DExTer\n' + '0' * 2000)

    def trigger_exp_start(self, n=None):
        """Atom checker sends signal saying all ROIs have atoms in, start the experiment"""
        self.rn.check.timer.stop(
        )  # in case the timer was going to trigger the experiment as well
        remove_slot(self.rn.trigger.dxnum, self.reset_cam_signals,
                    True)  # swap signals when msg confirmed
        self.rn.trigger.add_message(TCPENUM['TCP read'],
                                    'Go!' * 600)  # trigger experiment
        # QTimer.singleShot(20, self.resend_exp_trigger) # wait in ms

    def resend_exp_trigger(self, wait=20):
        """DExTer doesn't always receive the first trigger, send another.
        wait -- time in ms before checking if the message was received."""
        if self.rn.check.checking:
            self.rn.trigger.add_message(TCPENUM['TCP read'],
                                        'Go!' * 600)  # in case the first fails
            QTimer.singleShot(wait, self.resend_exp_trigger)  # wait in ms

    def reset_cam_signals(self, toggle=True):
        """Stop sending images to the atom checker, send them to image analysis instead"""
        self.rn.check.checking = False
        remove_slot(self.rn.cam.AcquireEnd, self.rn.receive,
                    not self.rn.multirun)  # send images to analysis
        remove_slot(self.rn.cam.AcquireEnd, self.rn.mr_receive,
                    self.rn.multirun)
        remove_slot(self.rn.cam.AcquireEnd, self.rn.check_receive, False)
        remove_slot(self.rn.trigger.dxnum, self.reset_cam_signals,
                    False)  # only trigger once
        self.rn.trigger.add_message(TCPENUM['TCP read'],
                                    'Go!' * 600)  # flush TCP

    def sync_mode(self, toggle=True):
        """Toggle whether to receive the run number from DExTer,
        or whether to increment the run number every time the expected
        number of images per sequence is received."""
        remove_slot(self.rn.cam.AcquireEnd, self.rn.receive, toggle)
        remove_slot(self.rn.cam.AcquireEnd, self.rn.unsync_receive, not toggle)

    def wait_for_cam(self, timeout=10):
        """Wait (timeout / 10) ms, periodically checking whether the camera
        has started acquiring yet."""
        for i in range(int(timeout)):
            if self.rn.cam.AF.GetStatus() == 'DRV_ACQUIRING':
                time.sleep(self.camera_pause)  # wait for camera to initialise
                break
            time.sleep(1e-4)  # poll camera status to check if acquiring

    def check_mr_queue(self):
        """Check whether it is appropriate to start the queued multiruns.
        This prevents multiple multiruns being sent to DExTer at the same time."""
        num_mrs = len(self.rn.seq.mr.mr_queue)  # number of multiruns queued
        if num_mrs:
            if not self.rn.multirun:
                self.rn.multirun = True
                self.rn.server.add_message(
                    TCPENUM['TCP read'],  # send the first multirun to DExTer
                    'start measure %s' %
                    (self.rn.seq.mr.mr_param['measure'] + num_mrs - 1) + '\n' +
                    '0' * 2000)
            else:
                QTimer.singleShot(10e3,
                                  self.check_mr_queue)  # check again in 10s.

    def respond(self, msg=''):
        """Read the text from a TCP message and then execute the appropriate function."""
        self.ts['msg start'] = time.time()
        self.ts['waiting'] = time.time() - self.ts['msg end']
        if 'finished run' in msg:
            self.end_run(msg)
        elif 'start acquisition' in msg:
            self.status_label.setText('Running')
            if self.check_rois.isChecked(
            ):  # start experiment when ROIs have atoms
                remove_slot(self.rn.check.rh.trigger, self.trigger_exp_start,
                            True)
                self.rn.atomcheck_go()  # start camera acuiring
            elif self.rn.cam.initialised:
                self.rn.cam.start()  # start acquisition
                self.wait_for_cam(
                )  # wait for camera to initialise before running
            else:
                logger.warning('Run %s started without camera acquisition.' %
                               (self.rn._n))
            self.rn.server.priority_messages([
                (TCPENUM['Save sequence'],
                 'save log file automatic name\n' + '0' * 2000),
                (TCPENUM['Run sequence'],
                 'single run ' + str(self.rn._n) + '\n' + '0' * 2000),
                (TCPENUM['TCP read'],
                 'finished run ' + str(self.rn._n) + '\n' + '0' * 2000)
            ])  # second message confirms end
        elif 'start measure' in msg:
            remove_slot(self.rn.seq.mr.progress, self.status_label.setText,
                        True)
            if self.check_rois.isChecked(
            ):  # start experiment when ROIs have atoms
                remove_slot(self.rn.check.rh.trigger, self.trigger_exp_start,
                            True)
                self.rn.atomcheck_go()  # start camera acquiring
            elif self.rn.cam.initialised:
                self.rn.cam.start()  # start acquisition
                self.wait_for_cam()
            else:
                logger.warning('Run %s started without camera acquisition.' %
                               (self.rn._n))
            if 'restart' not in msg:
                self.rn.multirun_go(
                    msg
                )  # might be resuming multirun instead of starting a new one
        elif 'multirun run' in msg:
            if self.check_rois.isChecked(
            ):  # start experiment when ROIs have atoms
                remove_slot(self.rn.check.rh.trigger, self.trigger_exp_start,
                            True)
                self.rn.atomcheck_go()  # start camera in internal trigger mode
            self.rn.multirun_step(msg)
            self.rn._k = 0  # reset image per run count
        elif 'save and reset histogram' in msg:
            self.rn.multirun_save(msg)
        elif 'end multirun' in msg:
            remove_slot(self.rn.seq.mr.progress, self.status_label.setText,
                        False)
            self.rn.multirun_end(msg)
            # self.rn.server.save_times()
            self.end_run(msg)
        elif 'STOPPED' in msg:
            self.status_label.setText(msg)
        self.ts['msg end'] = time.time()
        self.ts['blocking'] = time.time() - self.ts['msg start']
        # self.print_times()

    def end_run(self, msg=''):
        """At the end of a single run or a multirun, stop the acquisition,
        check for unprocessed images, and check synchronisation.
        First, disconnect the server.textin signal from this slot to it
        only triggers once."""
        self.action_button.setEnabled(True)  # allow another command to be sent
        # reset atom checker trigger
        remove_slot(self.rn.check.rh.trigger, self.trigger_exp_start, False)
        if self.rn.trigger.connected:
            remove_slot(self.rn.trigger.textin, self.rn.trigger.clear_queue,
                        True)
            self.rn.trigger.add_message(TCPENUM['TCP read'],
                                        'end connection' * 150)
        try:
            unprocessed = self.rn.cam.EmptyBuffer()
            self.rn.cam.AF.AbortAcquisition()
        except Exception as e:
            logger.warning(
                'Failed to abort camera acquisition at end of run.\n' + str(e))
        # if unprocessed:
        #     reply = QMessageBox.question(self, 'Unprocessed Images',
        # "Process the remaining %s images from the buffer?"%len(unprocessed),
        #         QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        #     if reply == QMessageBox.Yes:
        #         for im in unprocessed:
        #             # image dimensions: (# kscans, width pixels, height pixels)
        #             self.rn.receive(im[0])
        self.idle_state()

    def print_times(self, keys=['waiting', 'blocking']):
        """Print the timings between messages."""
        print(*[key + ': %.4g,\t' % self.ts[key] for key in keys])

    def save_state(self, file_name='./state'):
        """Save the file number and date and config file paths so that they
        can be loaded again when the program is next started."""
        self.stats['File#'] = self.rn._n
        with open(file_name, 'w+') as f:
            for key, val in self.stats.items():
                f.write(key + '=' + str(val) + '\n')

    def closeEvent(self, event):
        """Proper shut down procedure"""
        try:
            self.rn.cam.SafeShutdown()
        except Exception as e:
            logger.warning('camera safe shutdown failed.\n' + str(e))
        self.rn.check.send_rois(
        )  # give ROIs from atom checker to image analysis
        self.rn.sw.save_settings('.\\imageanalysis\\default.config')
        for key, g in [['AnalysisGeometry',
                        self.rn.sw.geometry()],
                       ['SequencesGeometry',
                        self.rn.seq.geometry()],
                       ['MasterGeometry', self.geometry()]]:
            self.stats[key] = [g.x(), g.y(), g.width(), g.height()]
        for obj in self.rn.sw.mw + self.rn.sw.rw + [
                self.rn.sw, self.rn.seq, self.rn.server, self.rn.trigger,
                self.rn.check, self.mon_win
        ]:
            obj.close()
        self.save_state()
        event.accept()
Esempio n. 14
0
class NodeList(QWidget):
    def __init__(self, parent, mainWindow, dockBrowser):
        super(NodeList, self).__init__(parent)

        self.__browsers = dockBrowser
        # Necessary
        self.type = "views"
        self.icon = QIcon(":list.png")
        self.name = ""
        self.__mainWindow = mainWindow
        self.__parent = parent

        # Specific
        self.currentIndexDir = None
        self.currentNodeDir = None

        self.g_display()
        self.initCallback(dockBrowser)

        self.loader = loader.loader()
        self.lmodules = self.loader.modules
        self.taskmanager = TaskManager()
        self.env = env.env()

    def g_display(self):
        self.setMinimumSize(QSize(400, 300))
        self.createSubMenu()
        self.vlayout = QVBoxLayout(self)
        self.hlayout = QHBoxLayout()
        self.vlayout.addLayout(self.hlayout)

        self.initListView()
        self.initThumbsView()

        self.topButton = QPushButton(self)
        self.topButton.setFixedSize(QSize(32, 32))
        self.topButton.setFlat(True)
        self.topButton.setIcon(QIcon(":previous.png"))
        self.topButton.setIconSize(QSize(32, 32))
        self.hlayout.addWidget(self.topButton)

        self.listButton = QPushButton(self)
        self.listButton.setFixedSize(QSize(32, 32))
        self.listButton.setFlat(True)
        self.listButton.setIcon(QIcon(":list.png"))
        self.listButton.setIconSize(QSize(32, 32))
        self.hlayout.addWidget(self.listButton)

        self.thumButton = QPushButton(self)
        self.thumButton.setFixedSize(QSize(32, 32))
        self.thumButton.setFlat(True)
        self.thumButton.setIcon(QIcon(":image.png"))
        self.thumButton.setIconSize(QSize(32, 32))
        self.hlayout.addWidget(self.thumButton)

        self.thumSize = QComboBox()
        self.thumSize.setMaximumWidth(100)
        self.thumSize.addItem("Small")
        self.thumSize.addItem("Medium")
        self.thumSize.addItem("Large")
        self.connect(self.thumSize, SIGNAL("currentIndexChanged(QString)"),
                     self.sizeChanged)
        self.hlayout.addWidget(self.thumSize)

        self.thumButton.setEnabled(True)
        self.thumSize.setEnabled(False)
        self.listButton.setEnabled(False)

        self.comboBoxPath = NodeComboBox(self)
        self.comboBoxPath.setMinimumSize(QSize(251, 32))
        self.comboBoxPath.setMaximumSize(QSize(16777215, 32))
        self.hlayout.addWidget(self.comboBoxPath)

    def initListView(self):
        self.ListView = ListView(self, self.__mainWindow)
        self.ListModel = ListModel(self)
        self.ListModelFilter = QSortFilterProxyModel()
        self.ListModelFilter.setDynamicSortFilter(True)
        self.ListModelFilter.setSortCaseSensitivity(Qt.CaseInsensitive)
        self.ListModelFilter.setSourceModel(self.ListModel)
        self.ListView.setModels(self.ListModel, self.ListModelFilter)
        self.ListView.setModel(self.ListModelFilter)
        self.ListView.setSubMenu(self.submenuFile)

        self.vlayout.addWidget(self.ListView)

    def initThumbsView(self):
        self.ThumbsView = ThumbsView(self.__mainWindow, self)
        self.ThumbsItemModel = ThumbsItemModel(self.ThumbsView.thread)

        self.ThumbsView.setModels(self.ThumbsItemModel)
        self.ThumbsView.setSubMenu(self.submenuFile)
        self.vlayout.addWidget(self.ThumbsView)

    def initCallback(self, dockBrowser):
        self.connect(self.topButton, SIGNAL("clicked()"), self.moveToTop)

        self.connect(self.listButton, SIGNAL("clicked()"), self.listActivated)
        self.connect(self.thumButton, SIGNAL("clicked()"), self.thumbActivated)

        self.connect(self.comboBoxPath,
                     SIGNAL("currentIndexChanged(const QString & )"),
                     self.comboBoxPathChanged)
        self.connect(ConnectorCallback.instance, SIGNAL("reload"), self.reload,
                     Qt.BlockingQueuedConnection)
        self.connect(dockBrowser.treeView, SIGNAL("changeDirectory"),
                     self.loadFolder)
        self.connect(dockBrowser.treeView, SIGNAL("reloadNodeView"),
                     self.reload)
        dockBrowser.treeView.connect(self, SIGNAL("setIndexAndExpand"),
                                     dockBrowser.treeView.setIndexAndExpand)
        dockBrowser.treeView.connect(
            self, SIGNAL("setIndex"),
            dockBrowser.treeView.setCurrentIndexForChild)

    def moveToTop(self):
        if self.currentIndexDir <> None:
            index = self.__browsers.treeItemModel.indexWithNode(
                self.currentNodeDir)
            parent = self.__browsers.treeItemModel.parent(index)
            if parent:
                self.emit(SIGNAL("setIndexAndExpand"), self, parent)
                self.currentIndexDir = parent
            else:
                self.emit(SIGNAL("setIndexAndExpand"), self, index)
                self.currentIndexDir = index

    def comboBoxPathChanged(self, text):
        node = self.comboBoxPath.getNode(str(text))
        if node.this == self.currentNodeDir.this:
            return
        index = self.comboBoxPath.getBrowserIndex(str(text))
        self.loadFolder(node, index)
        self.emit(SIGNAL("setIndex"), self, self.currentIndexDir)

#    def comboBoxModeChanged(self, index):
#        if index == 0 :
#            self.ListView.setVisible(True)
#            self.ThumbsView.setVisible(False)
#        else :
#            self.ListView.setVisible(False)
#            self.ThumbsView.setVisible(True)
#        self.reloadChangedView()

    def listActivated(self):
        self.ListView.setVisible(True)
        self.ThumbsView.setVisible(False)
        self.reloadChangedView()

        #Desactivate thumb buttons
        self.thumButton.setEnabled(True)
        self.thumSize.setEnabled(False)
        self.listButton.setEnabled(False)

    def thumbActivated(self):
        self.ListView.setVisible(False)
        self.ThumbsView.setVisible(True)
        self.reloadChangedView()

        self.thumButton.setEnabled(False)
        self.thumSize.setEnabled(True)
        self.listButton.setEnabled(True)

    def reloadChangedView(self):
        if not self.visibleRegion().isEmpty():
            view = self.viewVisible()
            if view.getModel().currentNodeDir is not None and view.getModel(
            ).currentNodeDir.this == self.currentNodeDir.this:
                return
            self.loadFolder(self.currentNodeDir, self.currentIndexDir, 1)

    # Specific type views
    def loadFolder(self, node, indexFolder=None, force=None):
        if node is None:
            return
        if self.currentNodeDir is not None:
            if force is None and self.currentNodeDir.this == node.this:
                return
        if force <> 2 and str(self) <> str(self.__browsers.getChild()):
            return

        self.currentIndexDir = indexFolder
        self.currentNodeDir = node
        self.comboBoxPath.addPathAndSelect(node, indexFolder)

        if self.ThumbsView.isVisible():
            self.ThumbsView.loadFolder(node, force)
        if self.ListView.isVisible() or force == 2:
            self.ListView.loadFolder(node)
        if force == 2:
            self.emit(SIGNAL("setIndexAndExpand"), self, self.currentIndexDir)

    def setChildSelected(self):
        if str(self.__browsers.getChild()) <> str(self):
            index = self.__browsers.treeItemModel.indexWithNode(
                self.currentNodeDir)
            self.emit(SIGNAL("setIndexAndExpand"), self, index)

    def getListCurrentItems(self):
        view = self.viewVisible()
        return view.getListCurrentItems()

    def getListCurrentNode(self):
        view = self.viewVisible()
        return view.getListCurrentNode()

    def reload(self):
        self.loadFolder(self.currentNodeDir, self.currentIndexDir, 1)

    def refreshIndexBrowser(self):
        self.emit(SIGNAL("setIndex"), self, self.currentIndexDir)

    def viewVisible(self):
        if self.ListView.isVisible():
            return self.ListView
        if self.ThumbsView.isVisible():
            return self.ThumbsView
        return self.ListView

    def changeDirectoryBrowser(self, node):
        dockNodeTree = self.__mainWindow.dockNodeTree
        currentIndex = dockNodeTree.treeView.selectionModel().currentIndex()
        if currentIndex is None:
            return
        currentItem = dockNodeTree.treeItemModel.getItem(currentIndex)
        #if not node.next.empty():
        newcurrent = currentItem.childWithNode(node)
        if not newcurrent:
            return
        #
        index = dockNodeTree.treeItemModel.index(newcurrent.childNumber(), 0,
                                                 currentIndex)
        self.emit(SIGNAL("setIndexAndExpand"), self, index)
        #    #self.loadFolder(node, index)

    ###############
    ## CONTEXT  MENU ##
    ###############
    def createSubMenu(self):
        self.extractor = Extractor(self.__mainWindow)
        self.connect(self.extractor, SIGNAL("filled"), self.launchExtract)
        self.submenuFile = QMenu()
        self.submenuFile.addAction(QIcon(":exec.png"), "Open",
                                   self.openDefault, "Listview")
        self.menuModules = self.submenuFile.addMenu(QIcon(":exec.png"),
                                                    "Open With")
        self.menuTags = MenuTags(self, self.__mainWindow,
                                 self.getListCurrentNode)
        self.submenuFile.addSeparator()
        self.submenuFile.addAction(
            QIcon(":hexedit.png"),
            QApplication.translate("ListView", "Hexeditor", None,
                                   QApplication.UnicodeUTF8),
            self.launchHexedit, "Listview")
        self.submenuFile.addAction(
            QIcon(":extract.png"),
            QApplication.translate("ListView", "Extract", None,
                                   QApplication.UnicodeUTF8),
            self.extractNodes, "Listview")
        self.submenuFile.addSeparator()
        self.submenuFile.addAction(
            QIcon(":info.png"),
            QApplication.translate("ListView", "Property", None,
                                   QApplication.UnicodeUTF8),
            self.propertyNodes, "Listview")

    def launchExtract(self):
        res = self.extractor.getArgs()
        arg = self.env.libenv.argument("gui_input")
        lnodes = self.env.libenv.ListNode()
        lnodes.thisown = 0
        for node in res["nodes"]:
            lnodes.append(node)
        arg.thisown = 0
        arg.add_path("syspath", str(res["path"]))
        arg.add_lnode("files", lnodes)
        arg.add_bool("recursive", int(res["recurse"]))
        self.taskmanager.add("extract", arg, ["thread", "gui"])

    def extractNodes(self):
        self.extractor.launch(self.getListCurrentNode())

    def openDefault(self):
        nodes = self.getListCurrentNode()
        for node in nodes:
            arg = self.env.libenv.argument("gui_input")
            arg.thisown = 0
            ft = FILETYPE()
            try:
                mod = ft.findcompattype(node)[0]
                if self.lmodules[mod]:
                    conf = self.lmodules[mod].conf
                    cdl = conf.descr_l
                    for a in cdl:
                        if a.type == "node":
                            arg.add_node(a.name, node)
                self.taskmanager.add(mod, arg, ["thread", "gui"])
            except IndexError:
                arg.add_node("file", node)
                self.taskmanager.add("hexedit", arg, ["thread", "gui"])

    def launchHexedit(self):
        nodes = self.getListCurrentNode()
        for node in nodes:
            arg = self.env.libenv.argument("gui_input")
            arg.thisown = 0
            arg.add_node("file", node)
            self.taskmanager.add("hexedit", arg, ["thread", "gui"])

    def propertyNodes(self):
        if not self.__mainWindow.QPropertyDialog.isVisible():
            self.__mainWindow.QPropertyDialog.fillInfo(
                self.currentNodeDir, self.getListCurrentNode())
            iReturn = self.__mainWindow.QPropertyDialog.exec_()
            self.__mainWindow.QPropertyDialog.removeAttr()
        else:
            QMessageBox.critical(self, "Erreur", u"This box is already open")

# CALLBACK

    def sizeChanged(self, string):
        if string == "Small":
            self.ThumbsView.configure(64, 64)
        elif string == "Medium":
            self.ThumbsView.configure(96, 96)
        elif string == "Large":
            self.ThumbsView.configure(128, 128)
Esempio n. 15
0
class UpdateBox(QWidget):
    def __init__(self, base):
        QWidget.__init__(self)
        self.base = base
        self.showed = False
        self.setFixedSize(500, 120)

        self.text_edit = CompletionTextEdit()

        self.upload_button = ImageButton(base, 'action-upload.png',
                i18n.get('upload_image'))
        self.short_button = ImageButton(base, 'action-shorten.png',
                i18n.get('short_urls'))

        font = QFont()
        font.setPointSize(18)
        font.setBold(True)
        self.char_count = QLabel('140')
        self.char_count.setFont(font)

        self.update_button = QPushButton(i18n.get('update'))
        self.update_button.setToolTip(self.base.get_shortcut_string('Enter'))
        self.queue_button = QPushButton(i18n.get('add_to_queue'))
        self.queue_button.setToolTip(self.base.get_shortcut_string('P'))

        self.accounts_combo = QComboBox()

        buttons = QHBoxLayout()
        buttons.setSpacing(4)
        buttons.addWidget(self.accounts_combo)
        buttons.addWidget(self.upload_button)
        buttons.addWidget(self.short_button)
        buttons.addStretch(0)
        buttons.addWidget(self.char_count)
        buttons.addWidget(self.queue_button)
        buttons.addWidget(self.update_button)

        self.loader = BarLoadIndicator()

        self.error_message = ErrorLabel()

        self.update_button.clicked.connect(self.__update_status)
        self.queue_button.clicked.connect(self.__queue_status)
        self.short_button.clicked.connect(self.__short_urls)
        self.upload_button.clicked.connect(self.__upload_image)
        self.text_edit.textChanged.connect(self.__update_count)
        self.text_edit.quit.connect(self.closeEvent)
        self.text_edit.activated.connect(self.__update_status)
        self.text_edit.enqueued.connect(self.__queue_status)

        layout = QVBoxLayout()
        layout.setSpacing(0)
        layout.addWidget(self.text_edit)
        layout.addWidget(self.loader)
        layout.addSpacing(5)
        layout.addWidget(self.error_message)
        layout.addLayout(buttons)
        layout.setContentsMargins(5, 5, 5, 5)
        self.setLayout(layout)

        self.__clear()

    def __count_chars(self):
        message = self.text_edit.toPlainText()
        urls = [str(url) for url in get_urls(message) if len(url) > 23]
        for url in urls:
            message = message.replace(url, '0' * 23)
        return MAX_CHAR - len(message)

    def __update_count(self):
        remaining_chars = self.__count_chars()
        if remaining_chars <= 10:
            self.char_count.setStyleSheet("QLabel { color: #D40D12 }")
        elif remaining_chars > 10 and remaining_chars <= 20:
            self.char_count.setStyleSheet("QLabel { color: #D4790D }")
        else:
            self.char_count.setStyleSheet("QLabel { color: #000000 }")
        self.char_count.setText(str(remaining_chars))

    def __validate(self, message, accounts, index):
        if len(message) == 0:
            self.error(i18n.get('you_can_not_submit_an_empty_message'))
            return False

        if index == 0 and len(accounts) > 1:
            self.error(i18n.get('select_an_account_before_post'))
            return False

        if self.__count_chars() < 0:
            self.error(i18n.get('message_too_long'))
            return False

        return True

    def __short_urls(self):
        self.enable(False)
        message = unicode(self.text_edit.toPlainText())
        self.base.short_urls(message)

    def __upload_image(self):
        index = self.accounts_combo.currentIndex()
        accounts = self.base.core.get_registered_accounts()

        if index == 0 and len(accounts) > 1:
            self.error(i18n.get('select_an_account_before_post'))
            return False

        account_id = str(self.accounts_combo.itemData(index).toPyObject())
        filename = str(QFileDialog.getOpenFileName(self, i18n.get('upload_image'),
            self.base.home_path))
        if filename != '':
            self.enable(False)
            self.base.upload_media(account_id, filename)

    def __update_status(self):
        index = self.accounts_combo.currentIndex()
        accounts = self.base.core.get_registered_accounts()
        message = unicode(self.text_edit.toPlainText())

        if not self.__validate(message, accounts, index):
            self.enable(True)
            return

        self.enable(False)
        account_id = str(self.accounts_combo.itemData(index).toPyObject())

        if self.direct_message_to:
            self.base.send_direct_message(account_id, self.direct_message_to, message)
        else:
            if account_id == 'broadcast':
                self.base.broadcast_status(message)
            else:
                self.base.update_status(account_id, message, self.in_reply_to_id)

    def __queue_status(self):
        index = self.accounts_combo.currentIndex()
        accounts = self.base.core.get_registered_accounts()
        account_id = str(self.accounts_combo.itemData(index).toPyObject())
        message = unicode(self.text_edit.toPlainText())

        if not self.__validate(message, accounts, index):
            self.enable(True)
            return

        self.enable(False)
        self.base.push_status_to_queue(account_id, message)

    def __clear(self):
        self.account_id = None
        self.in_reply_to_id = None
        self.in_reply_to_user = None
        self.direct_message_to = None
        self.quoting = False
        self.message = None
        self.cursor_position = None
        self.text_edit.setText('')
        self.accounts_combo.setCurrentIndex(0)
        self.queue_button.setEnabled(True)
        self.loader.setVisible(False)
        self.error_message.setVisible(False)
        self.error_message.setText('')
        self.enable(True)
        self.showed = False

    def __show(self):
        self.update_friends_list()
        short_service = self.base.get_shorten_url_service()
        short_tooltip = "%s (%s)" % (i18n.get('short_url'), short_service)
        self.short_button.setToolTip(short_tooltip)
        upload_service = self.base.get_upload_media_service()
        upload_tooltip = "%s (%s)" % (i18n.get('upload_image'), upload_service)
        self.upload_button.setToolTip(upload_tooltip)
        self.accounts_combo.clear()
        accounts = self.base.core.get_registered_accounts()
        if len(accounts) > 1:
            self.accounts_combo.addItem('--', '')
        for account in accounts:
            protocol = get_protocol_from(account.id_)
            icon = QIcon(self.base.get_image_path('%s.png' % protocol))
            self.accounts_combo.addItem(icon, get_username_from(account.id_), account.id_)
        if len(accounts) > 1:
            icon = QIcon(self.base.get_image_path('action-conversation.png'))
            self.accounts_combo.addItem(icon, i18n.get('broadcast'), 'broadcast')
        if self.account_id:
            index = self.accounts_combo.findData(self.account_id)
            if index > 0:
                self.accounts_combo.setCurrentIndex(index)
            self.accounts_combo.setEnabled(False)
        if self.message:
            self.text_edit.setText(self.message)
            cursor = self.text_edit.textCursor()
            cursor.movePosition(self.cursor_position, QTextCursor.MoveAnchor)
            self.text_edit.setTextCursor(cursor)

        QWidget.show(self)
        self.showed = True

    def __on_timeout(self):
        self.error_message.setText('')
        self.error_message.setVisible(False)

    def show(self):
        if self.showed:
            return self.raise_()
        self.setWindowTitle(i18n.get('whats_happening'))
        self.__show()

    def show_for_reply(self, account_id, status):
        if self.showed:
            return self.raise_()
        title = "%s @%s" % (i18n.get('reply_to'), status.username)
        self.setWindowTitle(title)
        self.account_id = account_id
        self.in_reply_to_id = status.id_
        self.in_reply_to_user = status.username
        mentions = ' '.join(["@%s" % user for user in status.get_mentions()])
        self.message = "%s " % mentions
        self.cursor_position = QTextCursor.End
        self.__show()

    def show_for_send_direct(self, account_id, username):
        if self.showed:
            return self.raise_()
        title = "%s @%s" % (i18n.get('send_message_to'), username)
        self.setWindowTitle(title)
        self.account_id = account_id
        self.direct_message_to = username
        self.__show()
        self.queue_button.setEnabled(False)

    def show_for_reply_direct(self, account_id, status):
        if self.showed:
            return self.raise_()
        title = "%s @%s" % (i18n.get('send_message_to'), status.username)
        self.setWindowTitle(title)
        self.account_id = account_id
        self.direct_message_to = status.username
        self.__show()
        self.queue_button.setEnabled(False)

    def show_for_quote(self, account_id, status):
        if self.showed:
            return self.raise_()
        self.setWindowTitle(i18n.get('quoting'))
        self.account_id = account_id
        self.message = " RT @%s %s" % (status.username, status.text)
        self.cursor_position = QTextCursor.Start
        self.quoting = True
        self.__show()
        self.queue_button.setEnabled(False)

    def closeEvent(self, event=None):
        message = unicode(self.text_edit.toPlainText())

        if len(message) > 0:
            confirmation = self.base.show_confirmation_message(i18n.get('confirm_discard'),
                i18n.get('do_you_want_to_discard_message'))
            if not confirmation:
                return

        if event:
            event.ignore()
        self.__clear()
        self.hide()

    def enable(self, value):
        self.text_edit.setEnabled(value)
        if not self.account_id:
            self.accounts_combo.setEnabled(value)
        if self.in_reply_to_id or self.direct_message_to or self.quoting:
            self.queue_button.setEnabled(False)
        else:
            self.queue_button.setEnabled(value)
        self.upload_button.setEnabled(value)
        self.short_button.setEnabled(value)
        self.update_button.setEnabled(value)
        self.loader.setVisible(not value)

    def done(self):
        self.__clear()
        self.hide()

    def error(self, message):
        self.enable(True)
        self.error_message.setText(message)
        self.error_message.setVisible(True)
        self.timer = QTimer()
        self.timer.timeout.connect(self.__on_timeout)
        self.timer.start(5000)

    def after_short_url(self, message):
        if self.base.is_exception(message):
            self.error(i18n.get('error_shorting_url'))
        else:
            self.text_edit.setText(message)
        self.enable(True)

    def after_upload_media(self, media_url):
        if self.base.is_exception(media_url):
            self.error(i18n.get('error_uploading_image'))
        else:
            text_cursor = self.text_edit.textCursor()
            text_cursor.select(QTextCursor.WordUnderCursor)
            if text_cursor.selectedText() != '':
                media_url = " %s" % media_url
            text_cursor.clearSelection()
            text_cursor.insertText(media_url)
            self.text_edit.setTextCursor(text_cursor)
        self.enable(True)

    def update_friends_list(self):
        completer = QCompleter(self.base.load_friends_list_with_extras())
        self.text_edit.setCompleter(completer)
Esempio n. 16
0
class FilteringModule(PreprocessorModule):
    DEFAULT_SETTINGS = {
        'is_enabled': True,
        'methods': [True, False, False],
        'recent_sw_files': [],
        'min_df': None,
        'max_df': None,
    }

    English, Custom, DocumentFrequency = 0, 1, 2
    filtering_values = {
        English: 'english',
        Custom: [],
        DocumentFrequency: (None, None),
    }
    filter_names = {
        English: 'English stop words',
        Custom: 'Custom stop words',
        DocumentFrequency: 'Filter by token frequency',
    }

    filtering_methods = [True, False, False]

    dlgFormats = 'Only text files (*.txt)'
    recent_sw_files = []

    def __init__(self, data):
        data = data or self.DEFAULT_SETTINGS
        PreprocessorModule.__init__(
                self, 'Token filtering', True,
                data.get('is_enabled')
        )

        self.group = QButtonGroup(self, exclusive=False)

        # --- English ---
        cb = QCheckBox(self, text=self.filter_names[self.English])
        self.add_to_content_area(cb)
        self.group.addButton(cb, self.English)

        # --- Custom ---
        cb = QCheckBox(self, text=self.filter_names[self.Custom])
        self.add_to_content_area(cb)
        self.group.addButton(cb, self.Custom)

        # File browser.
        file_browser_layout = QHBoxLayout()
        file_browser_layout.setContentsMargins(20, 0, 0, 0)
        self.sw_file_combo = QComboBox()
        self.sw_file_combo.setMinimumWidth(200)
        file_browser_layout.addWidget(self.sw_file_combo)
        self.sw_file_combo.activated[int].connect(self.select_file)

        self.browse_button = QPushButton(self)
        self.browse_button.clicked.connect(self.browse_file)
        self.browse_button.setIcon(self.style()
                                   .standardIcon(QStyle.SP_DirOpenIcon))
        self.browse_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        file_browser_layout.addWidget(self.browse_button)

        # Reload button
        self.reload_button = QPushButton(self)
        self.reload_button.clicked.connect(self.on_reload_button_clicked)
        self.reload_button.setIcon(self.style()
                                   .standardIcon(QStyle.SP_BrowserReload))
        self.reload_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        file_browser_layout.addWidget(self.reload_button)

        self.add_layout_to_content_area(file_browser_layout)

        # --- DF ---
        df_info_text = """
        Remove all tokens that appear in less than 'min-df' documents.
        Remove all tokens that appear in more than 'max-df' documents.
        Values can be either integers or floats (ratio of documents).
        """
        cb = QCheckBox(self, text=self.filter_names[self.DocumentFrequency])
        self.add_to_content_area(cb)
        self.group.addButton(cb, self.DocumentFrequency)
        df_info_text = QLabel(df_info_text)
        df_info_text.setContentsMargins(0,0,0,0)
        df_info_text.setStyleSheet("""
        font-size: 11px;
        font-style: italic;
        """)
        self.add_to_content_area(df_info_text)
        # Min/Max-Df setter.
        df_setter_layout = QHBoxLayout()
        df_setter_layout.setContentsMargins(20, 0, 0, 0)
        self.min_df_input = QLineEdit()
        self.min_df_input.textChanged.connect(self.update_df_parameters)
        self.max_df_input = QLineEdit()
        self.max_df_input.textChanged.connect(self.update_df_parameters)
        df_setter_layout.addWidget(QLabel('Min-df:'))
        df_setter_layout.addWidget(self.min_df_input)
        df_setter_layout.addWidget(QLabel('Max-df:'))
        df_setter_layout.addWidget(self.max_df_input)

        self.add_layout_to_content_area(df_setter_layout)
        self.group.buttonClicked.connect(self.group_button_clicked)

        # Restore the widget to its previous state.
        self.restore_data(data)

    def str_to_num(self, s):
        if not s:
            return None

        try:
            return int(s)
        except ValueError:
            pass  # Not an int. Continue.
        try:
            return float(s)
        except ValueError:  # Not a float either.
            self.send_message('Input "{}" cannot be cast into a number.'
                              .format(s))
            return None

    def send_message(self, message):
        # Sends a message with the "message" signal, to the main widget.
        self.error_signal.emit(message)

    # --- File selection.
    def select_file(self, n):
        if n < len(self.recent_sw_files):
            name = self.recent_sw_files[n]
            del self.recent_sw_files[n]
            self.recent_sw_files.insert(0, name)

        if len(self.recent_sw_files) > 0:
            self.set_file_list()
            self.open_file(self.recent_sw_files[0])

    def set_file_list(self):
        self.sw_file_combo.clear()
        if not self.recent_sw_files:
            self.sw_file_combo.addItem('(none)')
        else:
            for file in self.recent_sw_files:
                self.sw_file_combo.addItem(os.path.split(file)[1])

    def browse_file(self):
        # Opens the file browser, starting at the home directory.
        start_file = os.path.expanduser('~/')
        # Get the file path from the browser window.
        path = QFileDialog.getOpenFileName(self, 'Open a stop words source',
                                           start_file, self.dlgFormats)
        if not path:
            return

        if path in self.recent_sw_files:
            self.recent_sw_files.remove(path)
        self.recent_sw_files.insert(0, path)
        self.set_file_list()
        self.open_file(path)

    def update_df_parameters(self):
        min_df = None if not self.min_df_input.text() else self.min_df_input.text()
        max_df = None if not self.max_df_input.text() else self.max_df_input.text()
        self.filtering_values[self.DocumentFrequency] = (min_df, max_df)
        self.notify_on_change()

    def open_file(self, path):
        try:
            with open(path) as f:  # Read most recent.
                self.filtering_values[self.Custom] = [sw.strip() for sw in
                                                      f.read().splitlines()]
                self.notify_on_change()
        except Exception:  # Raise an exception otherwise.
            self.send_message('Could not open "{}".'
                              .format(path))

    def on_reload_button_clicked(self):
        if self.recent_sw_files:
            self.select_file(0)
    # END File selection.

    def group_button_clicked(self):
        self.filtering_methods = [ch_box.isChecked() for ch_box in
                                  self.group.buttons()]

        self.enable_choice_settings()

        # Emit the signal.
        self.notify_on_change()

    def enable_choice_settings(self):
        self.sw_file_combo.setEnabled(self.filtering_methods[1])
        self.browse_button.setEnabled(self.filtering_methods[1])
        self.reload_button.setEnabled(self.filtering_methods[1])

        self.min_df_input.setEnabled(self.filtering_methods[2])
        self.max_df_input.setEnabled(self.filtering_methods[2])

    def get_pp_setting(self):
        flag_english = self.filtering_methods[0]
        flag_custom = self.filtering_methods[1]
        flag_df = self.filtering_methods[2]
        if flag_english and flag_custom:  # Use custom.
            stop_words = {
                'stop_words': stopwords.words('english') +
                              self.filtering_values[self.Custom]
            }
        elif flag_english and not flag_custom:
            stop_words = {
                'stop_words': 'english'
            }
        elif flag_custom:
            stop_words = {
                'stop_words': self.filtering_values[self.Custom]
            }
        else:
            stop_words = {}

        if flag_df:
            stop_words.update({
                'min_df': self.str_to_num(self.min_df_input.text()),
                'max_df': self.str_to_num(self.max_df_input.text()),
            })
        return stop_words

    def restore_data(self, data):
        self.recent_sw_files = data.get('recent_sw_files')
        self.min_df_input.setText(data.get('min_df'))
        self.max_df_input.setText(data.get('max_df'))
        self.filtering_methods = data.get('methods')

        for flag, ch_box in zip(self.filtering_methods, self.group.buttons()):
            ch_box.setChecked(flag)

        self.enable_choice_settings()  # Enable the settings if set.
        self.set_file_list()  # Fill the combo box with the recent sw files.
        self.select_file(0)  # Select the first file.

    def export_data(self):
        return {
            'is_enabled': self.enabled,
            'methods': self.filtering_methods,
            'recent_sw_files': self.recent_sw_files,
            'min_df': self.min_df_input.text(),
            'max_df': self.max_df_input.text(),
        }
Esempio n. 17
0
class MembersWidget(QWidget):
    def __init__(self, parent, logger):
        super(MembersWidget, self).__init__(parent)

        self.logger = logger
        layout = QVBoxLayout(self)
        layout.setSpacing(0)

        self.dropdown_members_dict = {}
        self.dropdown_members_model = DropdownModel(get_peers(), self.logger)
        self.dropdown_members = QComboBox(self)
        self.dropdown_members.setModel(self.dropdown_members_model)

        topLayout = QHBoxLayout()
        topLayout.setSpacing(10)
        topLayout.addWidget(self.dropdown_members, 1)
        self.requestLogsButton = QPushButton("Request Logfiles", self)
        topLayout.addWidget(self.requestLogsButton)
        layout.addLayout(topLayout)

        layout.addWidget(QLabel("Member Information:", self))
        self.memberInformationTable = QTreeWidget(self)
        self.memberInformationTable.setMaximumHeight(65)
        self.memberInformationTable.setSelectionMode(QTreeWidget.NoSelection)
        layout.addWidget(self.memberInformationTable, 0)

        layout.addWidget(QLabel("Send Message:", self))

        sendMessageLayout = QHBoxLayout()
        sendMessageLayout.setSpacing(10)
        messageInput = HistoryLineEdit(self, "Enter a message")
        self.sendMessageButton = QPushButton("Send", self)
        sendMessageLayout.addWidget(messageInput, 1)
        sendMessageLayout.addWidget(self.sendMessageButton)
        layout.addLayout(sendMessageLayout)

        layout.addWidget(QLabel("Log files:", self))
        logSplitter = QSplitter(Qt.Horizontal, self)

        logListWidget = QWidget(self)
        logListLayout = QVBoxLayout(logListWidget)
        logListLayout.setContentsMargins(0, 0, 0, 0)

        self.log_tree_view = QTreeWidget(logSplitter)
        self.log_tree_view.setAlternatingRowColors(True)
        self.log_tree_view.setColumnCount(1)
        self.log_tree_view.setHeaderHidden(True)
        self.log_tree_view.setItemsExpandable(False)
        self.log_tree_view.setIndentation(0)

        logListLayout.addWidget(self.log_tree_view, 1)

        logListBottomLayout = QHBoxLayout()
        self.logSizeLabel = QLabel(logListWidget)
        logListBottomLayout.addWidget(self.logSizeLabel, 1)

        self.clearLogsButton = QPushButton("Clear", logListWidget)
        self.clearLogsButton.setEnabled(False)
        self.clearLogsButton.clicked.connect(self.clearLogs)
        logListBottomLayout.addWidget(self.clearLogsButton, 0)

        logListLayout.addLayout(logListBottomLayout)

        logSplitter.addWidget(logListWidget)

        self.log_area = QTextEdit(logListWidget)
        self.log_area.setLineWrapMode(QTextEdit.WidgetWidth)
        self.log_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.log_area.setReadOnly(True)
        logSplitter.addWidget(self.log_area)

        logSplitter.setStretchFactor(0, 0)
        logSplitter.setStretchFactor(1, 1)

        layout.addWidget(logSplitter, 1)

        self.memberSelectionChanged()
        self.log_tree_view.selectionModel().selectionChanged.connect(self.displaySelectedLogfile)
        self.dropdown_members.currentIndexChanged.connect(self.memberSelectionChanged)
        self.requestLogsButton.clicked.connect(self.requestLogClicked)
        self.sendMessageButton.clicked.connect(partial(self.sendMessageToMember, messageInput))
        messageInput.returnPressed.connect(partial(self.sendMessageToMember, messageInput))

        get_notification_center().connectPeerAppended(self.dropdown_members_model.externalRowAppended)
        get_notification_center().connectPeerUpdated(self.dropdown_members_model.externalRowUpdated)
        get_notification_center().connectPeerRemoved(self.dropdown_members_model.externalRowRemoved)
        get_notification_center().connectPeerUpdated(self.updateMemberInformation)

    def destroy_widget(self):
        get_notification_center().disconnectPeerAppended(self.dropdown_members_model.externalRowAppended)
        get_notification_center().disconnectPeerUpdated(self.dropdown_members_model.externalRowUpdated)
        get_notification_center().disconnectPeerRemoved(self.dropdown_members_model.externalRowRemoved)
        get_notification_center().disconnectPeerUpdated(self.updateMemberInformation)

    def listLogfiles(self, basePath, sort=None):
        if sort is None:
            sort = lambda aFile: -self.getLogNumber(aFile)
        logList = [
            os.path.join(basePath, aFile)
            for aFile in os.listdir(basePath)
            if aFile.endswith(".log") and not os.path.isdir(os.path.join(basePath, aFile))
        ]
        return sorted(logList, key=sort)

    def getNumLogsToKeep(self, oldLogFiles, newLogFiles, logOffset):
        oldestNew = None
        for aLogFile in newLogFiles:
            oldestNew, _ = self.getLogDates(aLogFile)
            if oldestNew != None:
                break

        if oldestNew == None:
            # new new log file contains timestamps (they are probably all empty)
            return len(oldLogFiles)

        numToKeep = 0
        while numToKeep < len(oldLogFiles) - logOffset:
            curTime, _ = self.getLogDates(oldLogFiles[numToKeep])
            if curTime == None or curTime < oldestNew:
                # keep empty log files
                numToKeep = numToKeep + 1
            else:
                break
        return numToKeep

    def getLogDates(self, aLogFile):
        with codecs.open(aLogFile, "rb", "utf-8") as logContent:
            logLines = logContent.readlines()
            firstDate = None
            for aLine in logLines:
                firstDate = getLogLineTime(aLine)
                if firstDate != None:
                    break

            lastDate = None
            for aLine in reversed(logLines):
                lastDate = getLogLineTime(aLine)
                if lastDate != None:
                    break

            return firstDate, lastDate

    def getLogNumber(self, aLogFile):
        aLogFile = os.path.basename(aLogFile)
        try:
            return int(aLogFile[: aLogFile.rfind(".")])
        except:
            return -1

    def shiftLogFiles(self, oldLogFiles, numToKeep, shift, logOffset):
        renamedLogfiles = []
        for index, aFile in enumerate(oldLogFiles):
            logNum = self.getLogNumber(aFile)
            if logNum < logOffset:
                # don't touch up-to-date logs
                break
            if index < numToKeep:
                newName = os.path.join(os.path.dirname(aFile), "%d.log" % (logNum + shift))
                renamedLogfiles.append((len(oldLogFiles) - index - 1, aFile, newName))
                os.rename(aFile, newName)
            else:
                os.remove(aFile)
        return renamedLogfiles

    def handleNewLogFiles(self, basePath, tmpPath, logOffset=0):
        oldLogFiles = self.listLogfiles(basePath)
        newLogFiles = self.listLogfiles(tmpPath)

        # check how many log files are actually new
        numToKeep = self.getNumLogsToKeep(oldLogFiles, newLogFiles, logOffset)

        # rename / remove old log files to make room for the new ones
        numNew = len(newLogFiles) - (len(oldLogFiles) - logOffset - numToKeep)
        renamedLogfiles = self.shiftLogFiles(oldLogFiles, numToKeep, numNew, logOffset)

        # move new log files
        addedLogfiles = []
        for index, aLogFile in enumerate(reversed(newLogFiles)):
            shutil.move(aLogFile, basePath)
            if index < numNew:
                addedLogfiles.append((index + logOffset, os.path.join(basePath, os.path.basename(aLogFile))))
        shutil.rmtree(tmpPath, True)

        return numNew, addedLogfiles, renamedLogfiles

    def requestFinished(self):
        self.requestLogsButton.setEnabled(True)
        self.dropdown_members.setEnabled(True)

    @loggingSlot(QThread, object)
    def cb_log_transfer_success(self, thread, path):
        path = convert_string(path)

        basePath = os.path.dirname(path)
        tmpPath = os.path.join(basePath, "tmp")
        if not os.path.exists(tmpPath):
            os.makedirs(tmpPath)

        logsAdded = []
        if path.endswith(".tgz"):
            # extract received log files
            with contextlib.closing(tarfile.open(path, "r:gz")) as tarContent:
                tarContent.extractall(tmpPath)
            _, logsAdded, logsRenamed = self.handleNewLogFiles(basePath, tmpPath)
            self.requestFinished()
        else:
            # log comes from old version
            logNum = 0
            if thread.sender in self.logRequests:
                logNum, requestTime = self.logRequests[thread.sender]
                now = datetime.now()
                td = now - requestTime
                tdSeconds = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / 10 ** 6
                if tdSeconds > self.LOG_REQUEST_TIMEOUT:
                    # request timed out or was finished already
                    logNum = 0

            shutil.move(path, os.path.join(tmpPath, "%d.log" % logNum))

            numNew, logsAdded, logsRenamed = self.handleNewLogFiles(basePath, tmpPath, logNum)
            if numNew > 0 and logNum < 9:
                # there might be more new ones
                self.logRequests[thread.sender] = (logNum + 1, datetime.now())
                self.logger.debug("log seems to be new, another!!!")
                logsAdded.append((logNum + 1, None))
                self.request_log(thread.sender, logNum + 1)
            elif thread.sender in self.logRequests:
                # request finished
                del self.logRequests[thread.sender]
                self.requestFinished()
            else:
                self.requestFinished()

        if len(logsAdded) > 0 or len(logsRenamed) > 0:
            self.updateLogList(logsAdded, logsRenamed)

    @loggingSlot(QThread, object)
    def cb_log_transfer_error(self, _thread, message):
        if not self.isVisible():
            return False
        self.log_area.setText("Error while getting log (%s)" % message)
        self.requestFinished()

    def get_selected_log_member(self):
        member = convert_string(self.dropdown_members.currentText())
        if not member:
            return None

        if "(" in member:
            # member contains name, extract ID
            member = member[member.rfind("(") + 1 : member.rfind(")")]

        return member

    def request_log(self, member=None, logNum=0):
        if member == None:
            member = self.get_selected_log_member()
        if member != None:
            self.logger.debug("Requesting log %d from %s", logNum, member)
            get_server().call(
                "HELO_REQUEST_LOGFILE %s %d" % (DataReceiverThread.getOpenPort(category="log%s" % member), logNum),
                set([member]),
            )
        else:
            self.log_area.setText("No Member selected!")

    @loggingSlot()
    def requestLogClicked(self):
        self.requestLogsButton.setEnabled(False)
        self.dropdown_members.setEnabled(False)
        self.updateLogList([(0, None)])
        self.request_log()

    def listLogFilesForMember(self, member):
        if member is None:
            return []
        logDir = os.path.join(get_settings().get_main_config_dir(), "logs", member)
        if not os.path.exists(logDir):
            return []
        return self.listLogfiles(logDir)

    def numLogFilesForMember(self, member):
        return len(self.listLogFilesForMember(member))

    def requestTimedOut(self, item):
        if not sip.isdeleted(item) and item != None and item.data(0, Qt.UserRole) == None:
            self.log_tree_view.takeTopLevelItem(self.log_tree_view.indexFromItem(item).row())
            self.requestFinished()

    def formatFileSize(self, num):
        for x in ["Bytes", "KB", "MB", "GB", "TB"]:
            if num < 1024.0:
                return "%3.1f %s" % (num, x)
            num /= 1024.0

    def initializeLogItem(self, item, logFile):
        firstDate, lastDate = self.getLogDates(logFile)
        text = None
        tooltip = None
        if firstDate != None:
            text = firstDate.strftime("%Y-%m-%d %H:%M:%S")
            tooltip = u"File: %s\nFirst entry: %s\nLast entry: %s" % (
                logFile,
                firstDate.strftime("%Y-%m-%d %H:%M:%S"),
                lastDate.strftime("%Y-%m-%d %H:%M:%S"),
            )
        else:
            timestamp = datetime.fromtimestamp(os.path.getmtime(logFile)).strftime("%Y-%m-%d %H:%M:%S")
            text = u"%s" % os.path.basename(logFile)
            tooltip = u"File:%s\nModification Date: %s" % (logFile, timestamp)
        text = text + "\n%s" % self.formatFileSize(os.path.getsize(logFile))
        if tooltip != None:
            item.setData(0, Qt.ToolTipRole, QVariant(tooltip))
        item.setData(0, Qt.UserRole, logFile)
        item.setData(0, Qt.DisplayRole, QVariant(text))

    @loggingSlot()
    def clearLogs(self):
        for aLogFile in self.listLogFilesForMember(self.get_selected_log_member()):
            os.remove(aLogFile)
        self.updateLogList()

    def updateLogList(self, logsAdded=None, logsRenamed=None):
        selectedMember = self.get_selected_log_member()

        if logsAdded == None:
            self.log_tree_view.clear()
            logsAdded = []
            for index, logFile in enumerate(reversed(self.listLogFilesForMember(selectedMember))):
                logsAdded.append((index, logFile))
            if len(logsAdded) == 0:
                self.log_tree_view.clear()
                self.log_tree_view.addTopLevelItem(
                    QTreeWidgetItem(self.log_tree_view, QStringList("No logs available."))
                )
                self.log_tree_view.setSelectionMode(QTreeWidget.NoSelection)
                self.logSizeLabel.setText("No logs")
                self.clearLogsButton.setEnabled(False)
                return

        if logsRenamed != None:
            for index, oldName, newName in logsRenamed:
                # index + 1 because of the "requesting" item
                item = self.log_tree_view.topLevelItem(index + 1)
                if item != None:
                    itemLogFile = convert_string(item.data(0, Qt.UserRole).toString())
                    if itemLogFile != oldName:
                        self.logger.warning(
                            "index does not correspond to item in list:\n\t%s\n\t%s", itemLogFile, oldName
                        )
                    self.initializeLogItem(item, newName)

        if len(logsAdded) == 0:
            self.log_tree_view.takeTopLevelItem(0)
        else:
            for index, logFile in logsAdded:
                oldItem = self.log_tree_view.topLevelItem(index)
                item = None
                if oldItem != None and oldItem.data(0, Qt.UserRole) == None:
                    # requested item has been received
                    item = oldItem
                else:
                    item = QTreeWidgetItem()
                    oldItem = None

                if logFile == None:
                    item.setData(0, Qt.DisplayRole, QVariant("Requesting..."))
                    QTimer.singleShot(6000, partial(self.requestTimedOut, item))
                else:
                    self.initializeLogItem(item, logFile)

                if oldItem == None:
                    # else, the old item is being modified
                    self.log_tree_view.insertTopLevelItem(index, item)
                self.log_tree_view.setSelectionMode(QTreeWidget.SingleSelection)

        totalSize = 0
        for aLogFile in self.listLogFilesForMember(selectedMember):
            totalSize += os.path.getsize(aLogFile)

        self.logSizeLabel.setText("%s consumed" % self.formatFileSize(totalSize))
        self.clearLogsButton.setEnabled(True)
        # self.displaySelectedLogfile()

    def getSelectedLogContent(self):
        member = self.get_selected_log_member()
        if member == None:
            return "No Log selected."
        selection = self.log_tree_view.selectedIndexes()
        if len(selection) is 0:
            return "No Log selected."

        logPath = convert_string(selection[0].data(Qt.UserRole).toString())
        if logPath == None:
            return "ERROR: path is None"
        if not os.path.exists(logPath):
            return "File not found: " + logPath

        fcontent = ""
        try:
            with codecs.open(logPath, "r", "utf8") as fhandler:
                fcontent = fhandler.read()
        except Exception as e:
            self.logger.exception("Error reading file")
            fcontent = "Error reading file: %s" % str(e)
        return fcontent

    @loggingSlot(QItemSelection, QItemSelection)
    def displaySelectedLogfile(self, _new, _old):
        self.log_area.setText(self.getSelectedLogContent())

    @loggingSlot(int)
    def memberSelectionChanged(self, _new=None):
        self.updateLogList()
        isMemberSelected = self.get_selected_log_member() != None
        self.sendMessageButton.setEnabled(isMemberSelected)
        self.requestLogsButton.setEnabled(isMemberSelected)
        self.updateMemberInformation()

    @loggingSlot(object)
    def sendMessageToMember(self, lineEdit):
        selectedMember = self.get_selected_log_member()
        if selectedMember != None:
            get_server().call(convert_string(lineEdit.text()), set([selectedMember]))
            lineEdit.clear()

    @loggingSlot(object, object)
    def updateMemberInformation(self, peerID=None, peerInfo=None):
        if peerID != None and peerID != self.get_selected_log_member():
            # only update if selected member updated
            return

        self.memberInformationTable.clear()

        if self.get_selected_log_member() == None:
            self.memberInformationTable.setColumnCount(0)
            self.memberInformationTable.setHeaderLabel("No member selected.")
            return

        if peerInfo == None:
            peerInfo = get_peers().getPeerInfo(pID=self.get_selected_log_member())

        if peerInfo == None:
            self.memberInformationTable.setColumnCount(0)
            self.memberInformationTable.setHeaderLabel("No member information available.")
            return

        self.memberInformationTable.setColumnCount(len(peerInfo))
        headers = sorted(peerInfo.keys(), key=lambda s: s.lower())
        self.memberInformationTable.setHeaderLabels(QStringList(headers))
        item = QTreeWidgetItem(self.memberInformationTable)
        for col, header in enumerate(headers):
            item.setData(col, Qt.DisplayRole, QVariant(peerInfo[header]))
        for col in range(self.memberInformationTable.columnCount()):
            self.memberInformationTable.resizeColumnToContents(col)
Esempio n. 18
0
class StyleChooser(QWidget):
    def __init__(self, area_supported=False):
        QWidget.__init__(self)
        self._style = PlotStyle("StyleChooser Internal Style")
        self._styles = STYLES if area_supported else STYLES_LINE_ONLY

        self.setMinimumWidth(140)
        self.setMaximumHeight(25)

        layout = QHBoxLayout()
        layout.setMargin(0)
        layout.setSpacing(2)

        self.line_chooser = QComboBox()
        self.line_chooser.setToolTip("Select line style.")
        for style in self._styles:
            self.line_chooser.addItem(*style)

        self.marker_chooser = QComboBox()
        self.marker_chooser.setToolTip("Select marker style.")
        for marker in MARKERS:
            self.marker_chooser.addItem(*marker)

        self.thickness_spinner = QDoubleSpinBox()
        self.thickness_spinner.setToolTip("Line thickness")
        self.thickness_spinner.setMinimum(0.1)
        self.thickness_spinner.setDecimals(1)
        self.thickness_spinner.setSingleStep(0.1)

        self.size_spinner = QDoubleSpinBox()
        self.size_spinner.setToolTip("Marker Size")
        self.size_spinner.setMinimum(0.1)
        self.size_spinner.setDecimals(1)
        self.size_spinner.setSingleStep(0.1)

        layout.addWidget(self.line_chooser)
        layout.addWidget(self.thickness_spinner)
        layout.addWidget(self.marker_chooser)
        layout.addWidget(self.size_spinner)

        self.setLayout(layout)

        self.line_chooser.currentIndexChanged.connect(self._updateStyle)
        self.marker_chooser.currentIndexChanged.connect(self._updateStyle)
        self.thickness_spinner.valueChanged.connect(self._updateStyle)
        self.size_spinner.valueChanged.connect(self._updateStyle)

        self._updateLineStyleAndMarker(self._style.line_style,
                                       self._style.marker, self._style.width,
                                       self._style.size)
        self._layout = layout

    def getItemSizes(self):
        line_style_combo_width = self._layout.itemAt(0).sizeHint().width()
        thickness_spinner_width = self._layout.itemAt(1).sizeHint().width()
        marker_combo_width = self._layout.itemAt(2).sizeHint().width()
        size_spinner_width = self._layout.itemAt(3).sizeHint().width()
        return line_style_combo_width, thickness_spinner_width, marker_combo_width, size_spinner_width

    def _findLineStyleIndex(self, line_style):
        for index, style in enumerate(self._styles):
            if style[1] == line_style:
                return index
            elif style[1] is None and line_style == "":
                return index
        return -1

    def _findMarkerStyleIndex(self, marker):
        for index, style in enumerate(MARKERS):
            if style[1] == marker:
                return index
            elif style[1] is None and marker == "":
                return index
        return -1

    def _updateLineStyleAndMarker(self, line_style, marker, thickness, size):
        self.line_chooser.setCurrentIndex(self._findLineStyleIndex(line_style))
        self.marker_chooser.setCurrentIndex(self._findMarkerStyleIndex(marker))
        self.thickness_spinner.setValue(thickness)
        self.size_spinner.setValue(size)

    def _updateStyle(self):
        self.marker_chooser.setEnabled(
            self.line_chooser.currentText() != "Area")

        line_style = self.line_chooser.itemData(
            self.line_chooser.currentIndex())
        marker_style = self.marker_chooser.itemData(
            self.marker_chooser.currentIndex())
        thickness = float(self.thickness_spinner.value())
        size = float(self.size_spinner.value())

        self._style.line_style = str(line_style.toString())
        self._style.marker = str(marker_style.toString())
        self._style.width = thickness
        self._style.size = size

    def setStyle(self, style):
        """ @type style: PlotStyle """
        self._style.copyStyleFrom(style)
        self._updateLineStyleAndMarker(style.line_style, style.marker,
                                       style.width, style.size)

    def getStyle(self):
        """ @rtype: PlotStyle """
        style = PlotStyle("Generated Style from StyleChooser")
        style.copyStyleFrom(self._style)
        return style

    def createLabelLayout(self, layout=None):
        if layout is None:
            layout = QHBoxLayout()

        titles = ["Line Style", "Width", "Marker Style", "Size"]
        sizes = self.getItemSizes()
        for title, size in zip(titles, sizes):
            label = QLabel(title)
            label.setFixedWidth(size)
            layout.addWidget(label)

        return layout
Esempio n. 19
0
class StyleChooser(QWidget):

    def __init__(self, area_supported=False):
        QWidget.__init__(self)
        self._style = PlotStyle("StyleChooser Internal Style")
        self._styles = STYLES if area_supported else STYLES_LINE_ONLY

        self.setMinimumWidth(140)
        self.setMaximumHeight(25)

        layout = QHBoxLayout()
        layout.setMargin(0)
        layout.setSpacing(2)

        self.line_chooser = QComboBox()
        self.line_chooser.setToolTip("Select line style.")
        for style in self._styles:
            self.line_chooser.addItem(*style)

        self.marker_chooser = QComboBox()
        self.marker_chooser.setToolTip("Select marker style.")
        for marker in MARKERS:
            self.marker_chooser.addItem(*marker)

        self.thickness_spinner = QDoubleSpinBox()
        self.thickness_spinner.setToolTip("Line thickness")
        self.thickness_spinner.setMinimum(0.1)
        self.thickness_spinner.setDecimals(1)
        self.thickness_spinner.setSingleStep(0.1)

        self.size_spinner = QDoubleSpinBox()
        self.size_spinner.setToolTip("Marker Size")
        self.size_spinner.setMinimum(0.1)
        self.size_spinner.setDecimals(1)
        self.size_spinner.setSingleStep(0.1)

        layout.addWidget(self.line_chooser)
        layout.addWidget(self.thickness_spinner)
        layout.addWidget(self.marker_chooser)
        layout.addWidget(self.size_spinner)

        self.setLayout(layout)

        self.line_chooser.currentIndexChanged.connect(self._updateStyle)
        self.marker_chooser.currentIndexChanged.connect(self._updateStyle)
        self.thickness_spinner.valueChanged.connect(self._updateStyle)
        self.size_spinner.valueChanged.connect(self._updateStyle)

        self._updateLineStyleAndMarker(self._style.line_style, self._style.marker, self._style.width, self._style.size)
        self._layout = layout

    def getItemSizes(self):
        line_style_combo_width = self._layout.itemAt(0).sizeHint().width()
        thickness_spinner_width = self._layout.itemAt(1).sizeHint().width()
        marker_combo_width = self._layout.itemAt(2).sizeHint().width()
        size_spinner_width = self._layout.itemAt(3).sizeHint().width()
        return line_style_combo_width, thickness_spinner_width, marker_combo_width, size_spinner_width

    def _findLineStyleIndex(self, line_style):
        for index, style in enumerate(self._styles):
            if style[1] == line_style:
                return index
            elif style[1] is None and line_style == "":
                return index
        return -1

    def _findMarkerStyleIndex(self, marker):
        for index, style in enumerate(MARKERS):
            if style[1] == marker:
                return index
            elif style[1] is None and marker == "":
                return index
        return -1

    def _updateLineStyleAndMarker(self, line_style, marker, thickness, size):
        self.line_chooser.setCurrentIndex(self._findLineStyleIndex(line_style))
        self.marker_chooser.setCurrentIndex(self._findMarkerStyleIndex(marker))
        self.thickness_spinner.setValue(thickness)
        self.size_spinner.setValue(size)

    def _updateStyle(self):
        self.marker_chooser.setEnabled(self.line_chooser.currentText() != "Area")

        line_style = self.line_chooser.itemData(self.line_chooser.currentIndex())
        marker_style = self.marker_chooser.itemData(self.marker_chooser.currentIndex())
        thickness = float(self.thickness_spinner.value())
        size = float(self.size_spinner.value())

        self._style.line_style = str(line_style.toString())
        self._style.marker = str(marker_style.toString())
        self._style.width = thickness
        self._style.size = size

    def setStyle(self, style):
        """ @type style: PlotStyle """
        self._style.copyStyleFrom(style)
        self._updateLineStyleAndMarker(style.line_style, style.marker, style.width, style.size)

    def getStyle(self):
        """ @rtype: PlotStyle """
        style = PlotStyle("Generated Style from StyleChooser")
        style.copyStyleFrom(self._style)
        return style

    def createLabelLayout(self, layout=None):
        if layout is None:
            layout = QHBoxLayout()

        titles = ["Line Style", "Width", "Marker Style", "Size"]
        sizes = self.getItemSizes()
        for title, size in zip(titles, sizes):
            label = QLabel(title)
            label.setFixedWidth(size)
            layout.addWidget(label)

        return layout
Esempio n. 20
0
class GithubRepoWizardPage(QWizardPage):
    def __init__(self, github, parent=None):
        super(GithubRepoWizardPage, self).__init__(
            parent,
            title="Github Repository",
            subTitle="Configure the new Github repository")
        
        self.github = github
        
        # moreButton

        self.moreButton = QPushButton(
                "More",
                checkable=True,
                clicked=self.more)
        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        moreButtonHBox = QHBoxLayout()
        moreButtonHBox.addWidget(spacer)
        moreButtonHBox.addWidget(self.moreButton)

        #  LineEdits

        self.nameEdit = QLineEdit(textChanged=self.update)
        self.nameEdit.setValidator(QRegExpValidator(
                QRegExp(r'[a-zA-Z0-9-_]+[a-zA-Z0-9-_]*')))
        self.descriptionEdit = QLineEdit(textChanged=self.update)
        self.homepageEdit = QLineEdit(textChanged=self.update)
        
        # CheckBox

        self.privateCheckBox = QCheckBox(stateChanged=self.update)
        self.initCheckBox = QCheckBox(stateChanged=self.update)
        self.hasWikiCheckBox = QCheckBox(stateChanged=self.update)
        self.hasDownloadsCheckBox = QCheckBox(stateChanged=self.update)
        self.hasIssuesCheckBox = QCheckBox(stateChanged=self.update)
        
        # gitignoreComboBox

        self.gitignoreComboBox = QComboBox(currentIndexChanged=self.update)
        self.gitignoreComboBox.addItem('None')
        for i in gitignore_types(self.github):
            self.gitignoreComboBox.addItem(i)
            
        hbox2 = QHBoxLayout()
        hbox2.addWidget(QLabel(
            'Initialize this repository with a README and .gitignore'))
        hbox2.addWidget(self.initCheckBox)
        
        # Extension Form

        self.form_extension = QFormLayout()
        self.form_extension.addRow("Homepage", self.homepageEdit)  
        self.form_extension.addRow("Has wiki", self.hasWikiCheckBox)
        self.form_extension.addRow("Has issues", self.hasIssuesCheckBox)
        self.form_extension.addRow("Has downloads", self.hasDownloadsCheckBox)

        # Extension

        self.extension = QWidget()
        self.extension.setLayout(self.form_extension)

        # Form

        self.form = QFormLayout()
        self.form.addRow("Name: ", self.nameEdit)
        self.form.addRow("Description: ", self.descriptionEdit)
        self.form.addRow('Private', self.privateCheckBox)
        self.form.addRow(hbox2)
        self.form.addRow('Add .gitignore', self.gitignoreComboBox)
        self.form.addRow(moreButtonHBox)
        self.form.addRow(self.extension)
        
        # Layout

        self.mainLayout = QVBoxLayout()
        self.mainLayout.addLayout(self.form)
        self.setLayout(self.mainLayout)
    
        # Fields

        self.registerField('name*', self.nameEdit)
        self.registerField('description', self.descriptionEdit)
        self.registerField('private', self.privateCheckBox)
        self.registerField('auto_init', self.initCheckBox)
        self.registerField('gitignore', self.gitignoreComboBox, 'currentText')
        self.registerField('homepage', self.homepageEdit)
        self.registerField('has_issues', self.hasIssuesCheckBox)
        self.registerField('has_downloads', self.hasDownloadsCheckBox)
        self.registerField('has_wiki', self.hasWikiCheckBox)
        
        # Setup

        self.hasWikiCheckBox.toggle()
        self.hasDownloadsCheckBox.toggle()
        self.hasIssuesCheckBox.toggle()
        if not self.github.get_user().plan:
            self.privateCheckBox.setEnabled(False)
        
        self.extension.hide()

    def update(self):

        if self.initCheckBox.isChecked():
            self.gitignoreComboBox.setEnabled(True)
        else:
            self.gitignoreComboBox.setEnabled(False)

    def more(self):
            
        if self.moreButton.isChecked():
            self.moreButton.setText("Less")
            self.extension.show()
            self.wizard().resize(self.wizard().sizeHint())
        else:
            self.moreButton.setText("More")
            self.extension.hide()
            size = self.sizeHint()
            wizard_size = self.wizard().sizeHint()
            self.wizard().resize(wizard_size.width(), size.height())
Esempio n. 21
0
class StyleChooser(QWidget):
    styleChanged = pyqtSignal(str, str)

    STYLE_OFF = ("Off", None)
    STYLE_AREA = ("Area", "#")
    STYLE_SOLID = ("Solid", "-")
    STYLE_DASHED = ("Dashed", "--")
    STYLE_DOTTED = ("Dotted", ":")
    STYLE_DASH_DOTTED = ("Dash Dotted", "-.")

    STYLES = [STYLE_OFF, STYLE_AREA, STYLE_SOLID, STYLE_DASHED, STYLE_DOTTED, STYLE_DASH_DOTTED]
    STYLES_LINE_ONLY = [STYLE_OFF, STYLE_SOLID, STYLE_DASHED, STYLE_DOTTED, STYLE_DASH_DOTTED]

    MARKER_OFF = ("Off", None)
    MARKER_X = ("X", "x")
    MARKER_CIRCLE = ("Circle", "o")
    MARKER_POINT = ("Point", ".")
    MARKER_STAR = ("Star", "*")
    MARKER_DIAMOND = ("Diamond", "D")

    MARKERS = [MARKER_OFF, MARKER_X, MARKER_CIRCLE, MARKER_POINT, MARKER_STAR, MARKER_DIAMOND]

    """Combines a StyleChooser with a label"""
    def __init__(self, label, line_style=STYLE_OFF, marker_style=MARKER_OFF, area_supported=False, labeled=False):
        QWidget.__init__(self)

        self.__styles = StyleChooser.STYLES if area_supported else StyleChooser.STYLES_LINE_ONLY

        self.setMinimumWidth(140)
        if labeled:
            self.setMaximumHeight(45)
        else:
            self.setMaximumHeight(25)

        layout = QHBoxLayout()
        layout.setMargin(0)
        layout.setSpacing(2)

        self.line_chooser = QComboBox()
        self.line_chooser.setToolTip("Select line style.")
        for style in self.__styles:
            self.line_chooser.addItem(*style)

        self.marker_chooser = QComboBox()
        self.marker_chooser.setToolTip("Select marker style.")
        for marker in StyleChooser.MARKERS:
            self.marker_chooser.addItem(*marker)

        self.style_label = QLabel("%s:" % label)
        self.style_label.setAlignment(Qt.AlignLeft | Qt.AlignBottom)
        layout.addWidget(self.style_label)

        if labeled:
            labeled_line_chooser = self._createLabeledChooser("Line Style", self.line_chooser)
            labeled_marker_chooser = self._createLabeledChooser("Marker", self.marker_chooser)
            layout.addWidget(labeled_line_chooser)
            layout.addWidget(labeled_marker_chooser)
        else:
            layout.addWidget(self.line_chooser)
            layout.addWidget(self.marker_chooser)

        self.setLayout(layout)
        self.label = label

        self.line_chooser.currentIndexChanged.connect(self.updateStyle)
        self.marker_chooser.currentIndexChanged.connect(self.updateStyle)

        self.line_chooser.setCurrentIndex(self.__styles.index(line_style))
        self.marker_chooser.setCurrentIndex(StyleChooser.MARKERS.index(marker_style))

    def _createLabeledChooser(self, label, chooser):
        labeled_line_chooser = QWidget()
        llc_layout = QVBoxLayout()
        llc_layout.setMargin(0)
        llc_layout.addWidget(QLabel(label))
        llc_layout.addWidget(chooser)
        labeled_line_chooser.setLayout(llc_layout)
        return labeled_line_chooser

    def updateLineStyleAndMarker(self, line_style, marker):
        self.line_chooser.setCurrentIndex(self.__styles.index(line_style))
        self.marker_chooser.setCurrentIndex(StyleChooser.MARKERS.index(marker))


    def updateStyle(self):
        self.marker_chooser.setEnabled(self.line_chooser.currentText() != "Area")

        line_style = self.line_chooser.itemData(self.line_chooser.currentIndex())
        marker_style = self.marker_chooser.itemData(self.marker_chooser.currentIndex())

        line_style = str(line_style.toString())
        marker_style = str(marker_style.toString())

        self.styleChanged.emit(line_style, marker_style)
Esempio n. 22
0
class typicalWindow(QtGui.QMainWindow):
	def __init__(self):
		QtGui.QMainWindow.__init__(self)
		
		#window
		
		self.setWindowTitle(winTitle)
		self.central_widget=QWidget(self)
		self.setCentralWidget(self.central_widget)
		self.masterLayout=QGridLayout(self.central_widget)
		self.masterLayout.setAlignment(QtCore.Qt.AlignTop)
		
		#mainlayout
		self.vertical_order_layout=QtGui.QBoxLayout(2)
		self.vertical_order_layout.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignVCenter)
		self.masterLayout.addLayout(self.vertical_order_layout, 0,0,1,1)
		
		self.topDivideLayout=QGridLayout()
		self.botDivideLayout=QGridLayout()
		self.upper_layout=QGridLayout()
		
		
		self.topDivideLayout.addLayout(self.upper_layout, 0,0,1,1)
		
		self.lower_layout=QGridLayout()
		self.lower_layout.setAlignment(QtCore.Qt.AlignTop)
		self.botDivideLayout.addLayout(self.lower_layout, 0,0,1,1)
		
		self.midLayout=QGridLayout()
		self.midLayout.setAlignment(QtCore.Qt.AlignTop)
		
		self.base_layout=QGridLayout()
		self.base_layout.setAlignment(QtCore.Qt.AlignTop)
		self.botDivideLayout.addLayout(self.base_layout, 4,0,1,1)
		
		sshFile=open(os.path.join(__location__, styleSheetFile+".stylesheet"), 'r')
		self.styleData=sshFile.read()
		sshFile.close
		
		self.setStyleSheet(self.styleData)
		self.top=QtGui.QFrame(self)
		self.top.setFrameShape(QtGui.QFrame.StyledPanel)
		self.top.setLayout(self.topDivideLayout)
		
		self.bottom=QtGui.QFrame(self)
		self.bottom.setFrameShape(QtGui.QFrame.StyledPanel)
		self.bottom.setLayout(self.botDivideLayout)
		
		self.splitPlane=QtGui.QSplitter(QtCore.Qt.Vertical)
		self.splitPlane.addWidget(self.top)
		self.splitPlane.addWidget(self.bottom)
		self.splitPlane.setSizes([650, 650])
		self.vertical_order_layout.addWidget(self.splitPlane)
		
		#layouts
		self.window_layer_00=QGridLayout()
		self.upper_layout.addLayout(self.window_layer_00, 0,0,1,1)
		
		self.window_layer_01=QGridLayout()
		self.upper_layout.addLayout(self.window_layer_01,1,0,1,1)
		
		self.window_layer_02=QGridLayout()
		self.upper_layout.addLayout(self.window_layer_02, 2,0,1,1)
		
		self.window_layer_03=QGridLayout()
		self.upper_layout.addLayout(self.window_layer_03,3,0,1,1)
		
		self.window_layer_04=QGridLayout()
		self.upper_layout.addLayout(self.window_layer_04, 4,0,1,1)
		
		self.window_layer_05=QGridLayout()
		self.upper_layout.addLayout(self.window_layer_05,5,0,1,1)
		
		self.window_layer_06=QGridLayout()
		self.midLayout.addLayout(self.window_layer_06, 6,0,1,1)
		
		self.frame_layout=QGridLayout()
		self.frame_layout.setAlignment(QtCore.Qt.AlignTop)
		self.lower_layout.addLayout(self.frame_layout, 0,0,1,1)
		
		
		self.frameWidget=QtGui.QGridLayout()
		self.frameWidget.setContentsMargins(5,10,5,10)
		self.frameOverride=QtGui.QFrame()
		self.frameOverride.setStyleSheet("background-color: #434343; border-style: solid; border-width: 2px; border-color:#434343;border-radius:8px;")
		self.frameOverride.setFixedHeight(100)
		self.frame_layout.addLayout(self.frameWidget, 0,0,1,1)
		self.frame_layout.addWidget(self.frameOverride, 0,0,1,1)
		
		
		self.frame_title_layout=QGridLayout()
		self.frameWidget.addLayout(self.frame_title_layout, 0,0,1,1)
		self.frame_radio_layout=QGridLayout()
		self.frameWidget.addLayout(self.frame_radio_layout, 1,0,1,1)
		self.frame_btn_layout=QGridLayout()
		self.frameWidget.addLayout(self.frame_btn_layout, 2,0,1,1)
	
		self.btm_btn_layout=QtGui.QGridLayout()
		self.btm_btn_layout.setAlignment(QtCore.Qt.AlignTop)
		self.btm_btn_layout.setContentsMargins(5,10,5,10)	
		self.wbFrame=QtGui.QFrame()
		self.wbFrame.setStyleSheet("background-color: #434343; border-style: solid; border-width: 2px; border-color:#434343;border-radius:8px;")
		self.btm_over_layout=QtGui.QGridLayout()
		self.btm_over_layout.setAlignment(QtCore.Qt.AlignTop)
		self.btm_over_layout.addLayout(self.btm_btn_layout, 0,0,1,1)
		self.btm_over_layout.addWidget(self.wbFrame, 0,0,1,1)
		
		self.pkt_layout= QGridLayout()
		self.pkt_layout.setAlignment(QtCore.Qt.AlignTop)
		self.pkt_widget=QGridLayout()
		self.pkt_widget.setContentsMargins(5,5,5,5)	
		self.pkt_frame=QFrame()
		self.pkt_frame.setMinimumWidth(650)
		self.pkt_frame.setStyleSheet("background-color: #434343; border-style: solid; border-width: 2px; border-color:#434343;border-radius:8px;")
		self.base_layout.addLayout(self.pkt_layout, 0,0,1,1)
		
		self.wndw_layer_pkt=QtGui.QGridLayout()
		self.wndw_layer_pkt.setAlignment(QtCore.Qt.AlignTop)
		self.pkt_widget.addLayout(self.wndw_layer_pkt, 0,0,1,1)
		
		self.park_btn_pkt=QtGui.QBoxLayout(2)
		self.park_btn_pkt.setAlignment(QtCore.Qt.AlignTop)
		self.park_btn_pkt.setContentsMargins(5,2,5,8)
		self.wndw_layer_pkt.addLayout(self.park_btn_pkt, 0,0,1,1)
		self.park_frame=QtGui.QFrame()
		self.park_frame.setStyleSheet("background-color: #434343; border-style: solid; border-width: 2px; border-color:#434343;border-radius:8px;")
		
		
		#widgets
		self.drop_lbl_01=QLabel()
		self.drop_lbl_01.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
		self.drop_lbl_01.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.window_layer_01.addWidget(self.drop_lbl_01, 0,0,1,1)
		
		self.drop_01=QComboBox()
		self.window_layer_01.addWidget(self.drop_01, 0,1,1,1)
		QtCore.QObject.connect(self.drop_01, SIGNAL("currentIndexChanged(QString)"),
								self.on_drop_01_changed)
		self.drop_01.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.connect(self.drop_lbl_01, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick)
		
		self.drop_lbl_02=QLabel()
		self.drop_lbl_02.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
		self.drop_lbl_02.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.window_layer_01.addWidget(self.drop_lbl_02, 0,2,1,1)
		
		self.drop_02=QComboBox()
		self.window_layer_01.addWidget(self.drop_02, 0,3,1,1)
		QtCore.QObject.connect(self.drop_02, SIGNAL("currentIndexChanged(QString)"),
								self.on_drop_01_changed)
		self.drop_02.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.connect(self.drop_lbl_01, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick)
		
		self.button_01=QPushButton("Set")
		self.button_01.setToolTip("set")
		self.connect(self.button_01, SIGNAL('clicked()'), self.connectButton01)
		self.window_layer_01.addWidget(self.button_01, 0,4,1,1)
		
		self.button_02=QPushButton("Set2")
		self.button_02.setToolTip("set2")
		self.connect(self.button_02, SIGNAL('clicked()'), self.connectButton01)
		self.window_layer_01.addWidget(self.button_02, 0,5,1,1)

		self.drop_lbl_03=QLabel()
		self.drop_lbl_03.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
		self.drop_lbl_03.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.window_layer_02.addWidget(self.drop_lbl_03, 0,0,1,1)
		
		self.drop_03=QComboBox()
		self.window_layer_02.addWidget(self.drop_03, 0,1,1,1)
		QtCore.QObject.connect(self.drop_03, SIGNAL("currentIndexChanged(QString)"),
								self.on_drop_01_changed)
		self.drop_03.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.connect(self.drop_03, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick)

		self.button_03=QPushButton("button_03")
		self.button_03.setToolTip("button_03")
		self.connect(self.button_03, SIGNAL('clicked()'), self.connectButton01)
		self.window_layer_02.addWidget(self.button_03, 0,2,1,1)
		
		self.button_04=QPushButton("button_04")
		self.button_04.setToolTip("button_04")
		self.connect(self.button_04, SIGNAL('clicked()'), self.connectButton01)
		self.window_layer_02.addWidget(self.button_04, 0,3,1,1)
		
		self.button_05=QPushButton("button_05")
		self.button_05.setToolTip("button_05")
		self.connect(self.button_05, SIGNAL('clicked()'), self.connectButton01)
		self.window_layer_02.addWidget(self.button_05, 0,4,1,1)

		self.drop_04=QComboBox()
		self.window_layer_04.addWidget(self.drop_04, 0,2,1,1)
		QtCore.QObject.connect(self.drop_04, SIGNAL("currentIndexChanged(QString)"),
								self.on_drop_01_changed)
		self.drop_04.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.connect(self.drop_04, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick)

		self.list_frame=QFrame()
		self.list_frame.setStyleSheet("color: rgb"+str(buttonColoursDict.get("red")))
		self.list_layout=QHBoxLayout()
		self.list_frame.setLayout(self.list_layout)
		
		self.drop_list_builder_05=QComboBox()
		self.drop_list_builder_05.addItems(alist)
		QtCore.QObject.connect(self.drop_list_builder_05, SIGNAL("currentIndexChanged(QString)"),
								self.build)
		self.drop_list_builder_05.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.connect(self.drop_list_builder_05, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick)
		self.list_layout.addWidget(self.drop_list_builder_05)
		self.window_layer_04.addWidget(self.list_frame, 0,3,1,1)

		self.drop_list_06=QComboBox()
		QtCore.QObject.connect(self.drop_list_06, SIGNAL("currentIndexChanged(QString)"),
								self.load)
		self.drop_list_06.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.connect(self.drop_list_06, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick)
		if len(pres)<1:
			self.drop_list_06.setEnabled(0)
		else:
			self.drop_list_06.setEnabled(1)
		self.drop_list_06.addItems(alist2)
		self.list_layout.addWidget(self.drop_list_06)
		
		self.type_list_drop=QComboBox()
		self.type_list_drop.addItems(typesOfStuffInList)
		QtCore.QObject.connect(self.type_list_drop, SIGNAL("currentIndexChanged(QString)"),
								self.on_drop_01_changed)
		self.window_layer_04.addWidget(self.type_list_drop, 0,5,1,1)
		
		self.button_06=QPushButton("button_06")
		self.button_06.setToolTip("button_06")
		self.connect(self.button_06, SIGNAL('clicked()'), self.connectButton01)	
		self.window_layer_04.addWidget(self.button_06, 0,6,0,1)
		
		self.listWidg=QtGui.QTableWidget()
		self.listWidg.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.listWidg.customContextMenuRequested.connect(self.RightClick)
		self.connect(self.listWidg, SIGNAL("itemClicked(QTableWidgetItem *)"), self.clicked)
		self.connect(self.listWidg, SIGNAL("itemDoubleClicked(QTableWidgetItem *)"), self.dclicked)
		self.window_layer_05.addWidget(self.listWidg, 0,2,1,1)
		
		self.status_lbl=QLabel()
		self.status_lbl.setStyleSheet('background-color:transparent')
		self.status_lbl.setAlignment(QtCore.Qt.AlignCenter|QtCore.Qt.AlignVCenter)
		self.frame_title_layout.addWidget(self.status_lbl, 0,2,1,1)

		self.spaceHold=QLabel()
		self.spaceHold.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.spaceHold.setAlignment(QtCore.Qt.AlignCenter|QtCore.Qt.AlignVCenter)
		self.frame_title_layout.addWidget(self.spaceHold, 0,0,1,1)


		self.checkbox=QCheckBox("add")
		self.checkbox.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.checkbox.setContentsMargins(5,0,0,0)
		self.checkbox.setChecked(1)
		self.frame_title_layout.addWidget(self.checkbox, 0,1,1,1)
		
		self.radiobox=QGridLayout()

		self.radio=QRadioButton("radio")
		self.radio.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.radio.setChecked(1)
		self.radiobox.addWidget(self.radio, 0,0,1,1)
		
		
		self.newradio=QRadioButton("newradio")
		self.newradio.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.radiobox.addWidget(self.newradio, 0,1,1,1)
		
		self.frame_len_layout=QGridLayout()
		self.frame_len_layout.setAlignment(QtCore.Qt.AlignCenter|QtCore.Qt.AlignVCenter)
		#self.frame_title_layout.addWidget(self.frame_len_layout, 1,3,1,1)
		
		self.spaceHold=QLabel()
		self.spaceHold.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.spaceHold.setAlignment(QtCore.Qt.AlignCenter|QtCore.Qt.AlignVCenter)
		self.frame_title_layout.addWidget(self.spaceHold, 0,0,1,1)
		
		self.over=QRadioButton("over")
		self.over.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.radiobox.addWidget(self.over, 1,1,1,1)
		
		self.head_lbl=QLabel("from")
		self.head_lbl.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.radiobox.addWidget(self.head_lbl, 1, 4,1,1)
		
		self.head_field=QTextEdit("")
		self.head_field.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.radiobox.addWidget(self.head_field, 1, 5,1,1)
		
		self.toe_lbl=QLabel("til")
		self.toe_lbl.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.radiobox.addWidget(self.toe_lbl, 1, 6,1,1)
		
		self.toe_field=QTextEdit("")
		self.toe_field.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);")
		self.radiobox.addWidget(self.toe_field, 1, 7,1,1)
		
		self.fieldBox=QLineEdit()
		self.fieldBox.setVisible(0)
		self.fieldBox.setText(defaultText)
		
		self.go_btn=QPushButton("go")
		self.connect(self.go_btn, SIGNAL('clicked()'), self.go)
		self.frame_btn_layout.addWidget(self.go_btn, 0,0,0,1)
		
		self.look_btn=QPushButton("look")
		self.connect(self.look_btn, SIGNAL('clicked()'), self.go)
		self.frame_btn_layout.addWidget(self.look_btn, 0,1, 0,1)


		self.link_btn=QPushButton("link")
		self.connect(self.link_btn, SIGNAL('clicked()'), self.go)
		self.frame_btn_layout.addWidget(self.link_btn, 0,2,1,1)
		
		self.create_btn=QPushButton("create_btn")
		self.connect(self.create_btn, SIGNAL('clicked()'), self.go)
		self.frame_btn_layout.addWidget(self.create_btn, 0,3, 1,1)
		
		self.pocketTitle=QPushButton("title")
		self.pocketTitle.setObjectName('label')
		self.pocketTitle.setStyleSheet("QPushButton#label{font-weight:500; color: rgb"str(buttonColorDict).get("yello"))+"; button-color: rgba(255,255,255,0); font-size: 10pt; border-width: 0px; font-style: bold;}")
		self.connect(self.pocketTitle, SIGNAL('clicked()'), self.send)
		self.connect(self.pocketTitle, SIGNAL('customContextMenuRequested(QPoint)'), lambda: self.send())
		self.park_btn_pkt.addWidget(self.pocketTitle)

		self.a_btn=QPushButton("a_btn")
		self.a_btn.setStyleSheet("background-color: rgb"str(buttonColorDict).get("yello")))
		self.connect(self.a_btn, SIGNAL('clicked()'), self.go)
		self.park_btn_pkt.addWidget(self.a_btn)
		
		self.card_menu=QMenu("card")
		self.card_menuBar=self.menuBar()
		self.card_menuBar.addMenu(self.card_menu)
		self.park_btn_pkt.addWidget(self.card_menuBar)
		buttonGrp.append(self.card_menuBar)
		
		self.card_btn=QToolButton()
		self.card_btn.setPopupMode(QToolButton.MenuButtonPopup)
		self.card_btn.setMenu(self.card_menu)
		self.card_special_btn=QPushButton("card special")
		self.connect(self.card_special_btn, SIGNAL('clicked()'), self.card_special_callup)
		action=QtGui.QWidgetAction(self.card_btn)
		action.setDefaultWidget(self.card_special_btn)
		self.card_btn.menu().addAction(action)

		self.B_card_btn=QToolButton()
		self.B_card_btn.setPopupMode(QToolButton.MenuButtonPopup)
		self.B_card_btn.setMenu(self.card_menu)
		self.B_card_special_btn=QPushButton("card special")
		self.connect(self.B_card_special_btn, SIGNAL('clicked()'),self.B_card_special_callup)
		action=QtGui.QWidgetAction(self.B_card_btn)
		action.setDefaultWidget(self.B_card_special_btn)
		self.B_card_btn.menu().addAction(action)

	def buttonToggle(self):
		get_a_layout=self.park_btn_pkt
		get_size=get_a_layout.getContentsMargine()
		if get_size==(0,0,0,0):
			self.setvisible()
		else:
			self.setinvisible()
			
	def setinvisible(self):
		for each in buttonGrp:
			each.setVisible(0)
		self.park_btn_pkt.setContentsMargine(0,0,0,0)
		
	def setvisible(self):
		for each in buttonGrp:
			each.setVisible(1)
		self.park_btn_pkt.setContentsMargine(5,8,5,8)
		
	def onRightClick(self):
		path='//'
		command="xdg-open '%s'"%path
		subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
		
	def on_drop_01_changed(self):
		newcol1=self.listWidg.columnWidth(0)
		newcol2=self.listWidg.columnWidth(1)
		newcol3=self.listWidg.columnWidth(2)
		if newcol1==0:
			col1, col1, col1= 240, 160, 500
		else:
			col1, col1, col1= newcol1, newcol2, newcol3
		getPath='//'
		get_items=os.listdir(get_items)
		self.listWidg.clear()
		self.status_lbl.clear()
		self.drop_03.addItems(get_items)
		model, countdata, listArray	=self.get_listStuff()	
		if self.on_drop_01=="item1":
			buildListPath=pathList.get("listpathtype").replace(getUser, newUser)
			self.makeList(listpath, newUser, self.listWidg, model, stat_lab, listtype)
		elif self.on_drop_01=="item2":
			buildListPath=pathList.get("listpathtype2").replace(getUser, newUser)
			self.makeList(listpath, newUser, self.listWidg, model, stat_lab, listtype)
			
	def clicked(self):
		print "hi"
		
	def dclicked(self):
		print "hello"
		
	def get_listStuff(self):
		listArray=self.listWidg
		countdata=listArray.rowCount()
		model=listArray.model()
		return model, countdata, listArray
		
	def getListWidgetData(self):
		model, countdata, listArray	=self.get_listStuff()	
		dataInListWidget=[]
		for row in range(model.rowCount()):
			dataInListWidget.append([])
			for column in range(model.columnCount()):
				index = model.index(row, column)
				dataInListWidet[row].append(str(model.data(index).toString()))
		return dataInListWidget, countdata
		
	def listCreate(self):
		directory='//'
		getUser='******'
		(dataInListWidget, countdata)=self.getListWidgetData()
		self.listWidg.setRowCount(0)
		self.listWidg.setColumnCount(0)
		try:
			getFiles=[os.path.join(directory, o) for o in os.listdir(directory) if os.path.isdir(os.path.join(directory, o))]
			pass
		except:
			print "nothing found"
			return
		getFile=[(each) for each in getFiles if getpwuid(stat(each).st_uid).pw_name==getUser]
		getFiles.sort(key=lambda x: os.path.getmtime(x))
		fileDict=[]
		for each in getFiles:
			statbuf=os.stat(each)
			timeFormat=time.strftime('%m/%d/%Y', time.gmtime(os.path.getctime(each)))
			getAccTime=time.ctime(os.path.getmtime(each))
			if "  " in str(getAccTime):
				getAccTime=getAccTime.split("  ")
				getAccTime=getAccTime[1].split(" ")[1]
			else:
				getAccTime=getAccTime.split("  ")[3]
			timeFormat=timeFormat+"  "+getAccTime
			makeDict=(each, timeFormat)
			fileDict.append(makeDict)
		count=len(fileDict)
		fileDict=reversed(fileDict)
		dictItems=fileDict
		col1, col1, col1= 240, 160, 500
		headerLabels=["Name", "Date", "Path"]
		self.listWidg.setRowCount(count)
		self.listWidg.clear()
		self.listWidg.setSortingEnabled(True)
		self.listWidg.setColumnWidth(3)
		self.listWidg.setColumnWidth(0, col1)
		self.listWidg.setColumnWidth(1, col2)
		self.listWidg.setColumnWidth(2, col3)
		self.listWidg.setHorizontalHeaderLabels(headerLabels)
		getVerticalHeader=self.listWidg.verticalHeader()
		getVerticalHeader.setDefaultSelectionSize(20)
		self.listWidg.setSelectionBehavior(QAbstractItemView.SelectRows)
		self.listWidg.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
		self.listWidg.horizontalHeaderItem(0).setTextAlignment(QtCore.Qt.AlignLeft)
		self.listWidg.horizontalHeaderItem(1).setTextAlignment(QtCore.Qt.AlignLeft)
		self.listWidg.horizontalHeaderItem(2).setTextAlignment(QtCore.Qt.AlignLeft)
		for row, item in enumerate(dictItems):
			key=item[0].split('/')[-1]
			path='/'.join(item[0].split('/')[-1])
			path="/"+path
			value=item[1]
			getTable=self.listWidg
			name=QtGui.QTableWidgetItem(key)
			name.setFlage(QtCore.Qt.ItemIsEnabled|QtCore.Qt.ItemIsSelectable)
			self.listWidg.setItem(row, 0, name)
			timeStamp=QtGui.QTableWidgetItem(value)
			self.listWidg.setItem(row, 1, timeStamp)
			location=QtGui.QTableWidgetItem(path)
			self.listWidg.setItem(row, 2, location)
		self.status_lbl.setText(grabText)
		self.status_lbl.setObjectName('non_plan_label')
		self.status_lbl.setStyleSheet('QLabel#non_plan_label{font-weight: 500; color: orange; background-color: rgba(255,255,255,0);font-size: 9pt}')
	
	def is_listWid_item_selected(self):
		listW=self.listWidg
		(dataInListWidget, countdata)=self.getListWidgetData()
		get_string_id=[]
		for index in xrange(countdata):
			get=listW.item(index, 0).isSelected()
			if get==True:
				getObj=listW.item(index, 2).text()
				getObj=str(getObj)
				get_string_id.append(getObj)
			else:
				get=listW.item(index, 1).isSelected()
				if get==True:
					getObj=listW.item(index, 2).text()
					getObj=str(getObj)
					get_string_id.append(getObj)
				else:
					get=listW.item(index, 2).isSelected()
					if get==True:
						getObj=listW.item(index, 2).text()
						getObj=str(getObj)
						get_string_id.append(getObj)
		return get_string_id
		
	def build(self):
		list_build=self.drop_list_builder_05
		list_build_function=list_build.currentText()
		selected_in_list=self.is_listWid_item_selected()
		allthePaths=('//', '//')
		allthePathsDic={"firstPath":'//', "secondPath":'//'}
		#drop_list_builder_05
		getlisttype=self.type_list_drop
		listtype=getlisttype.currentText()
		if selected_in_list>1:
			getItems=[(each) for each in selected_in_list]
			nameToSave=' '.join(getItems)
			if listtype=="firstPath":
				suffixAppend="first"
				path=allthePathsDic.get("firstPath")
			if listtype=="secondPath":
				suffixAppend="second"
				path=allthePathsDic.get("secondPath")
		compareBucket=[]
		getitems=[(suffixAppend+":"+each.split("/")[-1]) for each in selected_in_list]
		name_to_save=' '.join(getitems)
		if list_build_function==list_build[1]:
			prompt="name of list:"
			getcomment=self.makeBody(prompt)
			if getComment==None:
				print "needs name"
				return
			else:
				pass
			getComment=getComment.replace(' ', '_')
			shotList=suffixAppend+"_"+getComment+"storedText.txt"
			fileBuild=path+shotList
			copyfilemessage="creating in "+fileBuild
			replay = QtGui.QMessageBox.question(None, 'Message' ,copyfilemessage, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
			if reply == QtGui.QMessageBox.Yes:
				if os.path.isfile(fileBuild)==True:
					cmessage="create over "+fileBuild
					replay = QtGui.QMessageBox.question(None, 'Message', cmessage, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
					if reply == QtGui.QMessageBox.Yes:
						inp=open(fileBuild, "w+")
						inp.write(name_to_save)
						inp.close()
						print "created "+fileBuild
					else:
						print "cancelled"
						return
				else:
					inp=open(fileBuild, "w+")
					inp.write(name_to_save)
					inp.close()
					print "created "+fileBuild
			else:
				print "cancelled"
				return
		elif list_build_function==list_build[2]:
			fileDict, list=self.getAllLists(allthePaths)
					
	def getAllLists(self, stuff):
		fileDict={}
		for each in stuff:
			getList, getnamesdic=self.obtain_presets(each)
			getnames=getnamesdic.keys()
			for eachp in eachn in map(None, getList, getnames):
				dictlist={eachn:eachp}
				fileDict.update(dictlist)
		return fileDict, getList
			
	def obtain_presets(self, morestuff):
		preset=False
		format=".txt"
		getpreset=[os.path.join(dirpath, name) for dirpath, dirnames, files in os.walk(morestuff) for name in files if name.lower().endswith(format)]
		preset=[(each) for each in getpreset if "storedText" in each]
		getlistnames={}
		for each in preset:
			getName=each.split("/")[-1]
			nam=getName.split("_")
			getpletename='_'.join(nam[:-1])
			diction={getpletename:nam[0]}
			getlistnames.update(diction)
		return preset, getlistnames
		
	# def obtain_files(self, stuff):
	# 	preset_name=[]
	# 	if presetis!=False:
	# 		for each in presetis:
	# 			pathsplit=each.split("/")[-1]
	# 			namefind=pathsplit.split("_")[0]
	# 			preset_name.append(namefind)
	# 	else:
	# 		preset_name=False
	# 	return preset_name
		
	def makeBody(self, prompt):
		text, ok=QtGui.QInputDialog.getText(None, 'Intput Dialog', prompt)
		if ok:
			project=(str(text))
		else:
			return
		return project
		
	def makeBodyFilled(self, prompt, message):
		text, ok=QtGui.QInputDialog.getText(None, 'Intput Dialog', prompt, QtGui.QLineEdit.Normal, message)
		if ok and text:
			project=(str(text))
		else:
			return
		return project

	def load(self):
		list_load=self.drop_list_06
		list_load_function=list_build.currentText()
		allthePaths=('//', '//')
		allthePathsDic={"firstPath":'//', "secondPath":'//'}
		# getlisttype=self.type_list_drop
		# listtype=getlisttype.currentText()
		# if selected_in_list>1:
		# 	getItems=[(each) for each in selected_in_list]
		# 	nameToSave=' '.join(getItems)
		# 	if listtype=="firstPath"
		# 		suffixAppend="first"
		# 		path=allthePathsDic.get("firstPath")
		# 	if listtype=="secondPath"
		# 		suffixAppend="second"
		# 		path=allthePathsDic.get("secondPath")
		# compareBucket=[]
		# getitems=[(suffixAppend+":"+each.split("/")[-1]) for each in selected_in_list]
		# name_to_save=' '.join(getitems)
		if list_load_function==presetlist[0]:
			prompt="name of list:"
			getcomment=self.makeBody(prompt)
			if getComment==None:
				print "needs name"
				return
			else:
				pass
			getComment=getComment.replace(' ', '_')
			shotList=suffixAppend+"_"+getComment+"storedText.txt"
			fileBuild=path+shotList
			copyfilemessage="creating in "+fileBuild
			replay = QtGui.QMessageBox.question(None, 'Message', copyfilemessage, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
			if reply == QtGui.QMessageBox.Yes:
				if os.path.isfile(fileBuild)==True:
					cmessage="create over "+fileBuild
					replay = QtGui.QMessageBox.question(None, 'Message' ,cmessage, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
					if reply == QtGui.QMessageBox.Yes:
						inp=open(fileBuild, "w+")
						inp.write(name_to_save)
						inp.close()
						print "created "+fileBuild
					else:
						print "cancelled"
						return
				else:
					inp=open(fileBuild, "w+")
					inp.write(name_to_save)
					inp.close()
					print "created "+fileBuild
			else:
				print "cancelled"
				return
		elif list_build_function==list_build[2]:
			fileDict, list=self.getAllLists(allthePaths)
			
	def reset_callup(self):
		allthePaths=('//', '//')
		allthePathsDic={"firstPath":'//', "secondPath":'//'}
		getlisttype=self.type_list_drop
		listtype=getlisttype.currentText()
		if listtype=="firstPath":
			directory=allthePathsDic.get("firstPath")
		getUser=getUser
		self.directory_for_taking(getUser, directory)
		
	def directory_for_taking(self, getUser, directory):
		model, countdata, listArray	=self.get_listStuff()
		# self.status_lbl

	def connectButton01(self):
		print "hi"
	def RightClick(self):
		print "hello"
	def go(self):
		print "go"
	def send(self):
		print "end"

	def card_special_callup(self):
		print "card_special_callup"
		
	def Bcard_special_callup(self):
		print "B_card_special_callup"

		
	def B_card_special_callup(self):
		print "B_card_special_callup"
Esempio n. 23
0
class TablaturePart(_base.Part):
    """Base class for tablature instrument part types."""

    octave = 0
    clef = None
    transposition = None
    tunings = ()  # may contain a list of tunings.
    tabFormat = ''  # can contain a tablatureFormat value.

    def createWidgets(self, layout):
        self.staffTypeLabel = QLabel()
        self.staffType = QComboBox()
        self.staffTypeLabel.setBuddy(self.staffType)
        self.staffType.setModel(
            listmodel.ListModel(tablatureStaffTypes,
                                self.staffType,
                                display=listmodel.translate))
        box = QHBoxLayout()
        layout.addLayout(box)
        box.addWidget(self.staffTypeLabel)
        box.addWidget(self.staffType)
        if self.tunings:
            self.createTuningWidgets(layout)
            self.staffType.activated.connect(self.slotTabEnable)
            self.slotTabEnable(0)

    def createTuningWidgets(self, layout):
        self.tuningLabel = QLabel()
        self.tuning = QComboBox()
        self.tuningLabel.setBuddy(self.tuning)
        tunings = [('', lambda: _("Default"))]
        tunings.extend(self.tunings)
        tunings.append(('', lambda: _("Custom tuning")))
        self.tuning.setModel(
            listmodel.ListModel(tunings,
                                self.tuning,
                                display=listmodel.translate_index(1)))
        self.tuning.setCurrentIndex(1)
        self.customTuning = QLineEdit(enabled=False)
        completionmodel.complete(
            self.customTuning,
            "scorewiz/completion/plucked_strings/custom_tuning")
        self.tuning.currentIndexChanged.connect(self.slotCustomTuningEnable)
        box = QHBoxLayout()
        layout.addLayout(box)
        box.addWidget(self.tuningLabel)
        box.addWidget(self.tuning)
        layout.addWidget(self.customTuning)

    def translateWidgets(self):
        self.staffTypeLabel.setText(_("Staff type:"))
        self.staffType.model().update()
        if self.tunings:
            self.translateTuningWidgets()

    def translateTuningWidgets(self):
        self.tuningLabel.setText(_("Tuning:"))
        self.customTuning.setToolTip('<qt>' + _(
            "Select custom tuning in the combobox and "
            "enter a custom tuning here, e.g. <code>e, a d g b e'</code>. "
            "Use absolute note names in the same language as you want to use "
            "in your document (by default: \"nederlands\")."))
        try:
            self.customTuning.setPlaceholderText(_("Custom tuning..."))
        except AttributeError:
            pass  # only in Qt 4.7+
        self.tuning.model().update()

    def slotTabEnable(self, enable):
        """Called when the user changes the staff type.
        
        Non-zero if the user wants a TabStaff.
        
        """
        self.tuning.setEnabled(bool(enable))
        if enable:
            self.slotCustomTuningEnable(self.tuning.currentIndex())
        else:
            self.customTuning.setEnabled(False)

    def slotCustomTuningEnable(self, index):
        self.customTuning.setEnabled(index > len(self.tunings))

    def voiceCount(self):
        """Returns the number of voices.
        
        Inherit to make this user-settable.
        
        """
        return 1

    def build(self, data, builder):
        # First make assignments for the voices we want to create
        numVoices = self.voiceCount()
        if numVoices == 1:
            voices = (ly.util.mkid(data.name()), )
        elif numVoices == 2:
            order = 1, 2
            voices = 'upper', 'lower'
        elif numVoices == 3:
            order = 1, 3, 2
            voices = 'upper', 'middle', 'lower'
        else:
            order = 1, 2, 3, 4
            voices = [
                ly.util.mkid(data.name(), "voice") + ly.util.int2text(i)
                for i in order
            ]

        assignments = [
            data.assignMusic(name, self.octave, self.transposition)
            for name in voices
        ]

        staffType = self.staffType.currentIndex()
        if staffType in (0, 2):
            # create a normal staff
            staff = ly.dom.Staff()
            seq = ly.dom.Seqr(staff)
            if self.clef:
                ly.dom.Clef(self.clef, seq)
            mus = ly.dom.Simr(seq)
            for a in assignments[:-1]:
                ly.dom.Identifier(a.name, mus)
                ly.dom.VoiceSeparator(mus)
            ly.dom.Identifier(assignments[-1].name, mus)
            builder.setMidiInstrument(staff, self.midiInstrument)

        if staffType in (1, 2):
            # create a tab staff
            tabstaff = ly.dom.TabStaff()
            if self.tabFormat:
                tabstaff.getWith()['tablatureFormat'] = ly.dom.Scheme(
                    self.tabFormat)
            self.setTunings(tabstaff)
            sim = ly.dom.Simr(tabstaff)
            if numVoices == 1:
                ly.dom.Identifier(assignments[0].name, sim)
            else:
                for num, a in zip(order, assignments):
                    s = ly.dom.Seq(ly.dom.TabVoice(parent=sim))
                    ly.dom.Text('\\voice' + ly.util.int2text(num), s)
                    ly.dom.Identifier(a.name, s)

        if staffType == 0:
            # only a normal staff
            p = staff
        elif staffType == 1:
            # only a TabStaff
            builder.setMidiInstrument(tabstaff, self.midiInstrument)
            p = tabstaff
        else:
            # both TabStaff and normal staff
            p = ly.dom.StaffGroup()
            s = ly.dom.Sim(p)
            s.append(staff)
            s.append(tabstaff)

        builder.setInstrumentNamesFromPart(p, self, data)
        data.nodes.append(p)

    def setTunings(self, tab):
        if self.tunings:
            i = self.tuning.currentIndex()
            if i == 0:
                return
            elif i > len(self.tunings):
                value = ly.dom.Text("\\stringTuning <{0}>".format(
                    self.customTuning.text()))
            else:
                tuning = self.tunings[self.tuning.currentIndex() - 1][0]
                value = ly.dom.Scheme(tuning)
            tab.getWith()['stringTunings'] = value
Esempio n. 24
0
class TablaturePart(_base.Part):
    """Base class for tablature instrument part types."""
    
    octave = 0
    clef = None
    transposition = None
    tunings = ()    # may contain a list of tunings.
    tabFormat = ''  # can contain a tablatureFormat value.
    
    def createWidgets(self, layout):
        self.staffTypeLabel = QLabel()
        self.staffType = QComboBox()
        self.staffTypeLabel.setBuddy(self.staffType)
        self.staffType.setModel(listmodel.ListModel(tablatureStaffTypes,
            self.staffType, display=listmodel.translate))
        box = QHBoxLayout()
        layout.addLayout(box)
        box.addWidget(self.staffTypeLabel)
        box.addWidget(self.staffType)
        if self.tunings:
            self.createTuningWidgets(layout)
            self.staffType.activated.connect(self.slotTabEnable)
            self.slotTabEnable(0)
        
    def createTuningWidgets(self, layout):
        self.tuningLabel = QLabel()
        self.tuning = QComboBox()
        self.tuningLabel.setBuddy(self.tuning)
        tunings = [('', lambda: _("Default"))]
        tunings.extend(self.tunings)
        tunings.append(('', lambda: _("Custom tuning")))
        self.tuning.setModel(listmodel.ListModel(tunings, self.tuning,
            display=listmodel.translate_index(1)))
        self.tuning.setCurrentIndex(1)
        self.customTuning = QLineEdit(enabled=False)
        completionmodel.complete(self.customTuning,
            "scorewiz/completion/plucked_strings/custom_tuning")
        self.tuning.currentIndexChanged.connect(self.slotCustomTuningEnable)
        box = QHBoxLayout()
        layout.addLayout(box)
        box.addWidget(self.tuningLabel)
        box.addWidget(self.tuning)
        layout.addWidget(self.customTuning)
    
    def translateWidgets(self):
        self.staffTypeLabel.setText(_("Staff type:"))
        self.staffType.model().update()
        if self.tunings:
            self.translateTuningWidgets()
    
    def translateTuningWidgets(self):
        self.tuningLabel.setText(_("Tuning:"))
        self.customTuning.setToolTip('<qt>' + _(
            "Select custom tuning in the combobox and "
            "enter a custom tuning here, e.g. <code>e, a d g b e'</code>. "
            "Use absolute note names in the same language as you want to use "
            "in your document (by default: \"nederlands\")."))
        try:
            self.customTuning.setPlaceholderText(_("Custom tuning..."))
        except AttributeError:
            pass # only in Qt 4.7+
        self.tuning.model().update()
    
    def slotTabEnable(self, enable):
        """Called when the user changes the staff type.
        
        Non-zero if the user wants a TabStaff.
        
        """
        self.tuning.setEnabled(bool(enable))
        if enable:
            self.slotCustomTuningEnable(self.tuning.currentIndex())
        else:
            self.customTuning.setEnabled(False)
    
    def slotCustomTuningEnable(self, index):
        self.customTuning.setEnabled(index > len(self.tunings))
    
    def voiceCount(self):
        """Returns the number of voices.
        
        Inherit to make this user-settable.
        
        """
        return 1
        
    def build(self, data, builder):
        # First make assignments for the voices we want to create
        numVoices = self.voiceCount()
        if numVoices == 1:
            voices = (ly.util.mkid(data.name()),)
        elif numVoices == 2:
            order = 1, 2
            voices = 'upper', 'lower'
        elif numVoices == 3:
            order = 1, 3, 2
            voices = 'upper', 'middle', 'lower'
        else:
            order = 1, 2, 3, 4
            voices = [ly.util.mkid(data.name(), "voice") + ly.util.int2text(i) for i in order]
        
        assignments = [data.assignMusic(name, self.octave, self.transposition)
                       for name in voices]
        
        staffType = self.staffType.currentIndex()
        if staffType in (0, 2):
            # create a normal staff
            staff = ly.dom.Staff()
            seq = ly.dom.Seqr(staff)
            if self.clef:
                ly.dom.Clef(self.clef, seq)
            mus = ly.dom.Simr(seq)
            for a in assignments[:-1]:
                ly.dom.Identifier(a.name, mus)
                ly.dom.VoiceSeparator(mus)
            ly.dom.Identifier(assignments[-1].name, mus)
            builder.setMidiInstrument(staff, self.midiInstrument)
        
        if staffType in (1, 2):
            # create a tab staff
            tabstaff = ly.dom.TabStaff()
            if self.tabFormat:
                tabstaff.getWith()['tablatureFormat'] = ly.dom.Scheme(self.tabFormat)
            self.setTunings(tabstaff)
            sim = ly.dom.Simr(tabstaff)
            if numVoices == 1:
                ly.dom.Identifier(assignments[0].name, sim)
            else:
                for num, a in zip(order, assignments):
                    s = ly.dom.Seq(ly.dom.TabVoice(parent=sim))
                    ly.dom.Text('\\voice' + ly.util.int2text(num), s)
                    ly.dom.Identifier(a.name, s)
        
        if staffType == 0:
            # only a normal staff
            p = staff
        elif staffType == 1:
            # only a TabStaff
            builder.setMidiInstrument(tabstaff, self.midiInstrument)
            p = tabstaff
        else:
            # both TabStaff and normal staff
            p = ly.dom.StaffGroup()
            s = ly.dom.Sim(p)
            s.append(staff)
            s.append(tabstaff)
        
        builder.setInstrumentNamesFromPart(p, self, data)
        data.nodes.append(p)

    def setTunings(self, tab):
        if self.tunings:
            i = self.tuning.currentIndex()
            if i == 0:
                return
            elif i > len(self.tunings):
                value = ly.dom.Text("\\stringTuning <{0}>".format(self.customTuning.text()))
            else:
                tuning = self.tunings[self.tuning.currentIndex() - 1][0]
                value = ly.dom.Scheme(tuning)
            tab.getWith()['stringTunings'] = value
Esempio n. 25
0
    def setup_left_panel(self):
        """Setup the UI for left panel.

        Generate all exposure, combobox, and edit button.
        """
        hazard = self.parent.step_kw_subcategory.selected_subcategory()
        left_panel_heading = QLabel(tr('Classifications'))
        left_panel_heading.setFont(big_font)
        self.left_layout.addWidget(left_panel_heading)

        inner_left_layout = QGridLayout()

        row = 0
        for exposure in exposure_all:
            special_case = False
            # Filter out unsupported exposure for the hazard
            if exposure in hazard['disabled_exposures']:
                # Remove from the storage if the exposure is disabled
                if self.layer_mode == layer_mode_continuous:
                    if exposure['key'] in self.thresholds:
                        self.thresholds.pop(exposure['key'])
                else:
                    if exposure['key'] in self.value_maps:
                        self.value_maps.pop(exposure['key'])
                continue
            # Trick for EQ raster for population #3853
            if exposure == exposure_population and hazard == hazard_earthquake:
                if is_raster_layer(self.parent.layer):
                    if self.layer_mode == layer_mode_continuous:
                        self.use_default_thresholds = True
                        special_case = True
                        # Set classification for EQ Raster for Population
                        self.thresholds[exposure_population['key']] = {
                            earthquake_mmi_scale['key']: {
                                'classes': default_classification_thresholds(
                                    earthquake_mmi_scale),
                                'active': True
                            }
                        }

            # Add label
            # Hazard on Exposure Classifications
            label = tr(
                '{hazard_name} on {exposure_name} Classifications').format(
                hazard_name=hazard['name'],
                exposure_name=exposure['name']
            )
            exposure_label = QLabel(label)

            # Add combo box
            exposure_combo_box = QComboBox()
            hazard_classifications = hazard.get('classifications')
            exposure_combo_box.addItem(tr('No classifications'))
            exposure_combo_box.setItemData(
                0, None, Qt.UserRole)

            current_index = 0
            i = 0
            # Iterate through all available hazard classifications
            for hazard_classification in hazard_classifications:
                # Skip if the classification is not for the exposure
                if 'exposures' in hazard_classification:
                    if exposure not in hazard_classification['exposures']:
                        continue
                exposure_combo_box.addItem(hazard_classification['name'])
                exposure_combo_box.setItemData(
                    i + 1, hazard_classification, Qt.UserRole)
                if self.layer_mode == layer_mode_continuous:
                    current_hazard_classifications = self.thresholds.get(
                        exposure['key'])
                else:
                    current_hazard_classifications = self.value_maps.get(
                        exposure['key'])
                if current_hazard_classifications:
                    current_hazard_classification = \
                        current_hazard_classifications.get(
                            hazard_classification['key'])
                    if current_hazard_classification:
                        is_active = current_hazard_classification.get('active')
                        if is_active:
                            current_index = i + 1
                i += 1
            # Set current classification
            exposure_combo_box.setCurrentIndex(current_index)

            # Add edit button
            exposure_edit_button = QPushButton(tr('Edit'))

            # For special case. Raster EQ on Population.
            if special_case:
                mmi_index = exposure_combo_box.findText(
                    earthquake_mmi_scale['name'])
                exposure_combo_box.setCurrentIndex(mmi_index)
                exposure_combo_box.setEnabled(False)
                exposure_edit_button.setEnabled(False)
                tool_tip_message = tr(
                    'InaSAFE use default classification for Raster Earthquake '
                    'hazard on population.')
                exposure_label.setToolTip(tool_tip_message)
                exposure_combo_box.setToolTip(tool_tip_message)
                exposure_edit_button.setToolTip(tool_tip_message)

            else:
                if current_index == 0:
                    # Disable if there is no classification chosen.
                    exposure_edit_button.setEnabled(False)
                exposure_edit_button.clicked.connect(
                    partial(self.edit_button_clicked,
                        edit_button=exposure_edit_button,
                        exposure_combo_box=exposure_combo_box,
                        exposure=exposure))
                exposure_combo_box.currentIndexChanged.connect(
                    partial(
                        self.classifications_combo_box_changed,
                        exposure=exposure,
                        exposure_combo_box=exposure_combo_box,
                        edit_button=exposure_edit_button))

            # Arrange in layout
            inner_left_layout.addWidget(exposure_label, row, 0)
            inner_left_layout.addWidget(exposure_combo_box, row, 1)
            inner_left_layout.addWidget(exposure_edit_button, row, 2)

            # Adding to step's attribute
            self.exposures.append(exposure)
            self.exposure_combo_boxes.append(exposure_combo_box)
            self.exposure_edit_buttons.append(exposure_edit_button)
            self.exposure_labels.append(label)
            if special_case:
                self.special_case_index = len(self.exposures) - 1

            row += 1

        self.left_layout.addLayout(inner_left_layout)
        # To push the inner_left_layout up
        self.left_layout.addStretch(1)
Esempio n. 26
0
class options(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self)
        self.init(parent)
        self.initShape()

    def init(self, parent):
        self.heditor = parent        

    def initShape(self):
        self.vbox = QVBoxLayout()
        self.optab = QTabWidget()

        self.fill = QWidget()

        self.createHexOptions()
#        self.createPageOptions()
        self.createPixelOptions()
        self.vbox.addWidget(self.optab)

        self.createButtons()
        self.vbox.addWidget(self.fill)

        self.setLayout(self.vbox)
        
    def createPageOptions(self):
        self.pagegrid = QGridLayout()
        self.pagegroup = QWidget()
        
        pagelabel = QLabel("Page size : ")
        self.sizeEdit = QFFSpinBox(self)
        self.sizeEdit.setMaximum(self.heditor.filesize)
        self.sizeEdit.setValue(self.heditor.pageSize)
#        psize = QString("%.2d" % self.heditor.pageSize)
#        self.sizeEdit.insert(psize)

        headerlabel = QLabel("Header size : ")
        self.headEdit = QFFSpinBox(self)
        self.headEdit.setMaximum(self.heditor.filesize)
        self.headEdit.setValue(self.heditor.pageHead)
#        phead = QString("%.2d" % self.heditor.pageHead)
#        self.headEdit.insert(phead)

        sparelabel = QLabel("Spare size : ")
        self.spareEdit = QFFSpinBox(self)
        self.spareEdit.setMaximum(self.heditor.filesize)
        self.spareEdit.setValue(self.heditor.pageSpare)
#        pspare = QString("%.2d" % self.heditor.pageSpare)
#        self.spareEdit.insert(pspare)
        
        ppb = QLabel("Pages per block:")
        self.pagesperblock = QComboBox()
        self.pagesperblock.addItem("8")
        self.pagesperblock.addItem("16")
        self.pagesperblock.addItem("32")
        self.pagesperblock.addItem("64")
        self.pagesperblock.addItem("128")
        self.pagesperblock.addItem("256")
        self.pagesperblock.addItem("512")
        self.pagesperblock.setCurrentIndex(2)

        lview = QLabel("Left indication: ")
        self.indic = QComboBox()
        self.indic.addItem("Offset")
        self.indic.addItem("Block")

#        self.pagesperlineEdit = QLineEdit()
#        ppl = QString("%.2d" % self.heditor.pagesPerBlock)
#        self.pagesperlineEdit.insert(ppl)

        self.pagegrid.addWidget(pagelabel, 0, 0)
        self.pagegrid.addWidget(self.sizeEdit, 0, 1)

        self.pagegrid.addWidget(headerlabel, 1, 0)
        self.pagegrid.addWidget(self.headEdit, 1, 1)

        self.pagegrid.addWidget(sparelabel, 2, 0)
        self.pagegrid.addWidget(self.spareEdit, 2, 1)

        self.pagegrid.addWidget(ppb, 3 ,0)
        self.pagegrid.addWidget(self.pagesperblock, 3, 1)

        self.pagegrid.addWidget(lview, 4, 0)
        self.pagegrid.addWidget(self.indic, 4, 1)

        self.pagegrid.addWidget(self.fill, 5, 0)
        self.pagegrid.setRowStretch(5, 1)
#        self.pagegrid.addWidget(self.fill, 6, 0)

#        self.pagegrid.addWidget(pagesperline, 6, 0)
#        self.pagegrid.addWidget(self.pagesperlineEdit, 7, 0)

        self.pagegroup.setLayout(self.pagegrid)
        self.vvbox.addWidget(self.pagegroup)

#        self.optab.insertTab(1, self.pagegroup, "Pages" )

#        self.vbox.addWidget(self.pagegroup)

    def createHexOptions(self):
        self.vvbox = QVBoxLayout()
        self.vcontainer = QWidget()

        self.hexgroup = QWidget()

        self.hexgrid = QGridLayout()

        groupebylabel = QLabel("Groupe by:")
        self.groupeby = QComboBox()
        self.groupeby.addItem("1")
        self.groupeby.addItem("2")
        self.groupeby.addItem("4")

        offsetlabel = QLabel("Offset as")
        self.offsetas = QComboBox()
        self.offsetas.addItem("Hexadecimal")
        self.offsetas.addItem("Decimal")


#        self.hexgrid.addWidget(groupebylabel, 0, 0)
#        self.hexgrid.addWidget(self.groupeby, 1, 0)
        self.hexgrid.addWidget(offsetlabel, 0, 0)
        self.hexgrid.addWidget(self.offsetas, 0, 1)
#        self.hexgrid.addWidget(self.fill, 2, 0)
#        self.hexgrid.setRowStretch(2, 1)

        self.hexgroup.setLayout(self.hexgrid)
        
        self.vvbox.addWidget(self.hexgroup)

        self.createPageOptions()

        self.vcontainer.setLayout(self.vvbox)

        self.optab.insertTab(0, self.vcontainer, "General")

#        self.vbox.addWidget(self.hexgroup)

        #Offset as decimal / hexadecimal

    def createPixelOptions(self):
        self.pixgroup = QWidget()

        self.pixgrid = QGridLayout()

        formatlabel = QLabel("Format :")
        self.format = QComboBox()
        self.format.addItem("RGB")
        self.format.addItem("Alpha RGB")
        self.format.addItem("Indexed 8bit")
        self.format.addItem("Mono")
        self.connect(self.format, SIGNAL("currentIndexChanged(const QString)"), self.formatChanged)

        colorlabel = QLabel("Indexed Color :")
        self.icolor = QComboBox()
        self.icolor.addItem("Green")
        self.icolor.addItem("Red")
        self.icolor.addItem("Blue")
        self.icolor.addItem("Ascii")
        self.icolor.addItem("256")
        self.icolor.setEnabled(False)


        slidelabel = QLabel("Resolution : ")

        self.sliderspin = QSpinBox(self)
        self.sliderspin.setMinimum(64)
        self.sliderspin.setMaximum(1024)
        self.sliderspin.setValue(self.heditor.wpixel.view.w)
        self.connect(self.sliderspin, SIGNAL("valueChanged(int)"), self.slidermoved)

        self.slider = QSlider(Qt.Horizontal)
        self.slider.setMinimum(64)
        self.slider.setMaximum(1024)
        self.slider.setValue(self.heditor.wpixel.view.w)
        self.slider.setSingleStep(1)

        self.zoomlabel = QLabel("Scale factor : 1")
        self.zoom = QSlider(Qt.Horizontal)
        self.zoom.setMinimum(1)
        self.zoom.setMaximum(5)
        self.zoom.setValue(1)
        self.zoom.setSingleStep(1)
        self.zoom.setTickInterval(1)
        self.zoom.setTickPosition(QSlider.TicksBelow)

        self.connect(self.slider, SIGNAL("sliderMoved(int)"), self.slidermoved)
        self.connect(self.zoom, SIGNAL("sliderMoved(int)"), self.scale)

        self.pixgrid.addWidget(formatlabel, 0, 0)
        self.pixgrid.addWidget(self.format, 0, 1)
        self.pixgrid.addWidget(colorlabel, 1, 0)
        self.pixgrid.addWidget(self.icolor, 1, 1)

        self.pixgrid.addWidget(slidelabel, 2, 0)
        self.pixgrid.addWidget(self.sliderspin, 2, 1, Qt.AlignLeft)

        self.pixgrid.addWidget(self.slider, 3, 0)
        self.pixgrid.addWidget(self.zoomlabel, 4, 0, Qt.AlignLeft)
        self.pixgrid.addWidget(self.zoom, 5, 0)

        self.pixgrid.addWidget(self.fill, 6, 0)
        self.pixgrid.setRowStretch(6, 1)

        self.pixgroup.setLayout(self.pixgrid)

        self.optab.insertTab(1, self.pixgroup, "Pixel")

    def setSliderLabel(self, value):
        cvalue = QString()
        cvalue = "%2.d" % value
        self.sliderlabel.setText(cvalue)
    
    def setZoomLabel(self, value):
        zvalue = QString("Scale factor : ")
        zvalue += "%2.d" % value
        self.zoomlabel.setText(zvalue)


    def createButtons(self):
        self.applyB = QPushButton("Apply")
        self.connect(self.applyB, SIGNAL('clicked()'), self.apply)



        self.vbox.addWidget(self.applyB)

    def checkValue(self, value):
        try:
            n = int(value)
            return n
        except ValueError:
            return -1

    def apply(self):
        #PAGE CHECK
        pagesize = self.sizeEdit.value()
        headsize = self.headEdit.value()
        sparesize = self.spareEdit.value()
        pagesperblock = self.checkValue(self.pagesperblock.currentText())

        if (pagesize < 0) or (headsize < 0) or (sparesize < 0) or (pagesperblock < 0):
            print "Wrong values"
        else:
            offas = self.offsetas.currentText()
            if offas == "Decimal":
                self.heditor.decimalview = True
            elif offas == "Hexadecimal":
                self.heditor.decimalview = False
            #Hexview refresh
            self.heditor.readOffset(self.heditor.currentOffset)
            #Pageview refresh
            if self.indic.currentText() == "Offset":
                self.heditor.pageOffView = True
            else:
                self.heditor.pageOffView = False

            self.heditor.refreshPageValues(headsize, pagesize, sparesize, pagesperblock)
            if self.heditor.wpage.scroll:
                self.heditor.wpage.scroll.refreshValues(self.heditor.pagesPerBlock, self.heditor.pageSize)
            self.heditor.wpage.view.refreshAllContent()
            #PageView scrollbar refres
            #Pixel View refresh
            format = self.format.currentText()
            if format == "Indexed 8bit":
                self.heditor.wpixel.view.format = 0
            elif format == "Mono":
                self.heditor.wpixel.view.format = 1
            elif format == "RGB":
                self.heditor.wpixel.view.format = 2
            elif format == "Alpha RGB":
                self.heditor.wpixel.view.format = 3

            if self.heditor.wpixel.scroll:
                self.heditor.wpixel.scroll.refreshValues()
            #Color
            icolor = self.icolor.currentText()
            if icolor == "Red":
                self.heditor.wpixel.view.icolor = 0
            elif icolor == "Green":
                self.heditor.wpixel.view.icolor = 1
            elif icolor == "Blue":
                self.heditor.wpixel.view.icolor = 2
            elif icolor == "Ascii":
                self.heditor.wpixel.view.icolor = 3
            elif icolor == "256":
                self.heditor.wpixel.view.icolor = 4

            pixoffset = self.heditor.wpixel.view.currentOffset
            self.heditor.wpixel.view.read_image(pixoffset)

    def slidermoved(self, value):       
        pixoffset = self.heditor.wpixel.view.currentOffset
        self.heditor.wpixel.view.w = value
        self.sliderspin.setValue(value)
#        self.setSliderLabel(value)
        self.heditor.wpixel.view.read_image(pixoffset)
        if self.heditor.wpixel.scroll:
            self.heditor.wpixel.scroll.refreshValues()
#        print value

    def scale(self, value):
        self.setZoomLabel(value)
        self.heditor.wpixel.view.scale = value
        pixoffset = self.heditor.wpixel.view.currentOffset
        self.heditor.wpixel.view.read_image(pixoffset)


    def formatChanged(self, format):
        if format == "Indexed 8bit":
            self.icolor.setEnabled(True)
        else:
            self.icolor.setEnabled(False)


    def keyPressEvent(self, kEvent):
        key = kEvent.key()
        if key == Qt.Key_Return or key == Qt.Key_Enter:
            self.apply()
Esempio n. 27
0
class TradingWidget(QFrame):
    """简单交易组件"""
    signal = QtCore.pyqtSignal(type(Event()))
    
    directionList = [DIRECTION_LONG,
                     DIRECTION_SHORT]
    
    offsetList = [OFFSET_OPEN,
                  OFFSET_CLOSE,
                  OFFSET_CLOSEYESTERDAY,
                  OFFSET_CLOSETODAY]
    
    priceTypeList = [PRICETYPE_LIMITPRICE,
                     PRICETYPE_VWAP,
                     PRICETYPE_TWAP]
    
    exchangeList = [EXCHANGE_NONE,
                    EXCHANGE_CFFEX,
                    EXCHANGE_SHFE,
                    EXCHANGE_DCE,
                    EXCHANGE_CZCE,
                    EXCHANGE_SSE,
                    EXCHANGE_SZSE,
                    EXCHANGE_SGE,
                    EXCHANGE_HKEX,
                    
                    EXCHANGE_CSI, 
                    EXCHANGE_HKH, 
                    EXCHANGE_HKS, 
                    EXCHANGE_JZ,  
                    EXCHANGE_SPOT,
                    EXCHANGE_IB,  
                    EXCHANGE_FX,  
                    EXCHANGE_INE, 
                    
                    EXCHANGE_SMART,
                    EXCHANGE_ICE,
                    EXCHANGE_CME,
                    EXCHANGE_NYMEX,
                    EXCHANGE_GLOBEX,
                    EXCHANGE_IDEALPRO]
    
    currencyList = [CURRENCY_NONE,
                    CURRENCY_CNY,
                    CURRENCY_USD]
    
    productClassList = [PRODUCT_NONE,
                        PRODUCT_EQUITY,
                        PRODUCT_FUTURES,
                        PRODUCT_OPTION,
                        PRODUCT_BOND,
                        PRODUCT_FOREX]
    
    # ----------------------------------------------------------------------
    def __init__(self, mainEngine, eventEngine, parent=None):
        """Constructor"""
        super(TradingWidget, self).__init__(parent)
        self.mainEngine = mainEngine
        self.eventEngine = eventEngine
        
        self.symbol = ''
        self.signalemit = None
        
        self.initUi()
        self.connectSignal()
    
    # ----------------------------------------------------------------------
    def initUi(self):
        """初始化界面"""
        self.setWindowTitle(u'交易')
        self.setMaximumWidth(500)
        self.setFrameShape(self.Box)  # 设置边框
        self.setLineWidth(1)
        
        # 左边部分
        labelSymbol = QLabel(u'代码')
        labelName = QLabel(u'名称')
        labelDirection = QLabel(u'方向类型')
        labelOffset = QLabel(u'开平')
        labelPrice = QLabel(u'价格')
        labelVolume = QLabel(u'数量')
        labelPriceType = QLabel(u'价格类型')
        labelExchange = QLabel(u'交易所')
        labelCurrency = QLabel(u'货币')
        labelProductClass = QLabel(u'产品类型')
        labelUrgency = QLabel(u'紧急度')
        
        self.lineSymbol = QLineEdit()
        self.lineName = QLineEdit()
        
        self.comboDirection = QComboBox()
        self.comboDirection.addItems(self.directionList)
        
        self.comboOffset = QComboBox()
        self.comboOffset.addItem('')
        self.comboOffset.addItems(self.offsetList)
        self.comboOffset.setEnabled(False)
        
        self.tickOffset = QCheckBox(u'指定')
        
        self.spinPrice = QDoubleSpinBox()
        self.spinPrice.setDecimals(4)
        self.spinPrice.setMinimum(0)
        self.spinPrice.setMaximum(100000)
        
        self.spinVolume = QSpinBox()
        self.spinVolume.setMinimum(0)
        self.spinVolume.setMaximum(1000000)
        
        self.comboPriceType = QComboBox()
        self.comboPriceType.addItems(self.priceTypeList)
        
        self.comboExchange = QComboBox()
        self.comboExchange.addItems(self.exchangeList)
        self.comboExchange.setEnabled(False)
        
        self.comboCurrency = QComboBox()
        self.comboCurrency.addItems(self.currencyList)
        self.comboCurrency.setEnabled(False)
        
        self.comboProductClass = QComboBox()
        self.comboProductClass.addItems(self.productClassList)
        self.comboProductClass.setEnabled(False)
        
        self.spinUrgency = QSpinBox()
        self.spinUrgency.setMinimum(1)
        self.spinUrgency.setMaximum(9)
        self.spinUrgency.setSingleStep(1)
        self.spinUrgency.setValue(5)
        
        gridleft = QGridLayout()
        gridleft.addWidget(labelSymbol, 0, 0)
        gridleft.addWidget(labelName, 1, 0)
        gridleft.addWidget(labelDirection, 2, 0)
        gridleft.addWidget(labelOffset, 3, 0)
        gridleft.addWidget(labelPrice, 4, 0)
        gridleft.addWidget(labelVolume, 5, 0)
        gridleft.addWidget(labelPriceType, 6, 0)
        gridleft.addWidget(labelUrgency, 7, 0)
        gridleft.addWidget(labelExchange, 8, 0)
        gridleft.addWidget(labelProductClass, 9, 0)
        gridleft.addWidget(labelCurrency, 10, 0)
        
        gridleft.addWidget(self.lineSymbol, 0, 1)
        gridleft.addWidget(self.lineName, 1, 1)
        gridleft.addWidget(self.comboDirection, 2, 1)
        
        hbox1 = QHBoxLayout()
        hbox1.addWidget(self.comboOffset)
        lable1 = QLabel()
        hbox1.addWidget(lable1)
        hbox1.addWidget(self.tickOffset)
        hbox1.setStretchFactor(self.comboOffset, 4)
        hbox1.setStretchFactor(lable1, 1)
        hbox1.setStretchFactor(self.tickOffset, 3)
        gridleft.addItem(hbox1, 3, 1)
        
        gridleft.addWidget(self.spinPrice, 4, 1)
        gridleft.addWidget(self.spinVolume, 5, 1)
        gridleft.addWidget(self.comboPriceType, 6, 1)
        gridleft.addWidget(self.spinUrgency, 7, 1)
        gridleft.addWidget(self.comboExchange, 8, 1)
        gridleft.addWidget(self.comboProductClass, 9, 1)
        gridleft.addWidget(self.comboCurrency, 10, 1)
        
        # 右边部分
        labelBid1 = QLabel(u'买一')
        labelBid2 = QLabel(u'买二')
        labelBid3 = QLabel(u'买三')
        labelBid4 = QLabel(u'买四')
        labelBid5 = QLabel(u'买五')
        
        labelAsk1 = QLabel(u'卖一')
        labelAsk2 = QLabel(u'卖二')
        labelAsk3 = QLabel(u'卖三')
        labelAsk4 = QLabel(u'卖四')
        labelAsk5 = QLabel(u'卖五')
        
        self.labelBidPrice1 = QLabel()
        self.labelBidPrice2 = QLabel()
        self.labelBidPrice3 = QLabel()
        self.labelBidPrice4 = QLabel()
        self.labelBidPrice5 = QLabel()
        self.labelBidVolume1 = QLabel()
        self.labelBidVolume2 = QLabel()
        self.labelBidVolume3 = QLabel()
        self.labelBidVolume4 = QLabel()
        self.labelBidVolume5 = QLabel()
        
        self.labelAskPrice1 = QLabel()
        self.labelAskPrice2 = QLabel()
        self.labelAskPrice3 = QLabel()
        self.labelAskPrice4 = QLabel()
        self.labelAskPrice5 = QLabel()
        self.labelAskVolume1 = QLabel()
        self.labelAskVolume2 = QLabel()
        self.labelAskVolume3 = QLabel()
        self.labelAskVolume4 = QLabel()
        self.labelAskVolume5 = QLabel()
        
        labelLast = QLabel(u'最新')
        self.labelLastPrice = QLabel()
        self.labelReturn = QLabel()
        
        self.labelLastPrice.setMinimumWidth(60)
        self.labelReturn.setMinimumWidth(60)
        
        gridRight = QGridLayout()
        gridRight.addWidget(labelAsk5, 0, 0)
        gridRight.addWidget(labelAsk4, 1, 0)
        gridRight.addWidget(labelAsk3, 2, 0)
        gridRight.addWidget(labelAsk2, 3, 0)
        gridRight.addWidget(labelAsk1, 4, 0)
        gridRight.addWidget(labelLast, 5, 0)
        gridRight.addWidget(labelBid1, 6, 0)
        gridRight.addWidget(labelBid2, 7, 0)
        gridRight.addWidget(labelBid3, 8, 0)
        gridRight.addWidget(labelBid4, 9, 0)
        gridRight.addWidget(labelBid5, 10, 0)
        
        gridRight.addWidget(self.labelAskPrice5, 0, 1)
        gridRight.addWidget(self.labelAskPrice4, 1, 1)
        gridRight.addWidget(self.labelAskPrice3, 2, 1)
        gridRight.addWidget(self.labelAskPrice2, 3, 1)
        gridRight.addWidget(self.labelAskPrice1, 4, 1)
        gridRight.addWidget(self.labelLastPrice, 5, 1)
        gridRight.addWidget(self.labelBidPrice1, 6, 1)
        gridRight.addWidget(self.labelBidPrice2, 7, 1)
        gridRight.addWidget(self.labelBidPrice3, 8, 1)
        gridRight.addWidget(self.labelBidPrice4, 9, 1)
        gridRight.addWidget(self.labelBidPrice5, 10, 1)
        
        gridRight.addWidget(self.labelAskVolume5, 0, 2)
        gridRight.addWidget(self.labelAskVolume4, 1, 2)
        gridRight.addWidget(self.labelAskVolume3, 2, 2)
        gridRight.addWidget(self.labelAskVolume2, 3, 2)
        gridRight.addWidget(self.labelAskVolume1, 4, 2)
        gridRight.addWidget(self.labelReturn, 5, 2)
        gridRight.addWidget(self.labelBidVolume1, 6, 2)
        gridRight.addWidget(self.labelBidVolume2, 7, 2)
        gridRight.addWidget(self.labelBidVolume3, 8, 2)
        gridRight.addWidget(self.labelBidVolume4, 9, 2)
        gridRight.addWidget(self.labelBidVolume5, 10, 2)
        
        # 发单按钮
        buttonSendOrder = QPushButton(u'发单')
        buttonCancelAll = QPushButton(u'全撤')
        
        size = buttonSendOrder.sizeHint()
        buttonSendOrder.setMinimumHeight(size.height() * 2)  # 把按钮高度设为默认两倍
        buttonCancelAll.setMinimumHeight(size.height() * 2)
        
        # 整合布局
        hbox = QHBoxLayout()
        hbox.addLayout(gridleft)
        hbox.addLayout(gridRight)
        
        vbox = QVBoxLayout()
        vbox.addLayout(hbox)
        vbox.addWidget(buttonSendOrder)
        vbox.addWidget(buttonCancelAll)
        vbox.addStretch()
        
        self.setLayout(vbox)
        
        # 关联更新
        buttonSendOrder.clicked.connect(self.sendOrder)
        buttonCancelAll.clicked.connect(self.cancelAll)
        self.lineSymbol.returnPressed.connect(self.updateSymbol)
        self.comboDirection.currentIndexChanged.connect(self.updateOffset)
        self.tickOffset.stateChanged.connect(self.updateOffset)
        
        self.labelAskPrice1.mouseDoubleClickEvent = self.ask1clicked
        self.labelAskPrice2.mouseDoubleClickEvent = self.ask2clicked
        self.labelAskPrice3.mouseDoubleClickEvent = self.ask3clicked
        self.labelAskPrice4.mouseDoubleClickEvent = self.ask4clicked
        self.labelAskPrice5.mouseDoubleClickEvent = self.ask5clicked
        
        self.labelBidPrice1.mouseDoubleClickEvent = self.bid1clicked
        self.labelBidPrice2.mouseDoubleClickEvent = self.bid2clicked
        self.labelBidPrice3.mouseDoubleClickEvent = self.bid3clicked
        self.labelBidPrice4.mouseDoubleClickEvent = self.bid4clicked
        self.labelBidPrice5.mouseDoubleClickEvent = self.bid5clicked
        
        self.labelLastPrice.mouseDoubleClickEvent = self.lastclicked
    
    def ask1clicked(self, a):
        self.askclicked(self.labelAskPrice1.text())
    
    def ask2clicked(self, a):
        self.askclicked(self.labelAskPrice2.text())
    
    def ask3clicked(self, a):
        self.askclicked(self.labelAskPrice3.text())
    
    def ask4clicked(self, a):
        self.askclicked(self.labelAskPrice4.text())
    
    def ask5clicked(self, a):
        self.askclicked(self.labelAskPrice5.text())
    
    def bid1clicked(self, a):
        self.bidclicked(self.labelBidPrice1.text())
    
    def bid2clicked(self, a):
        self.bidclicked(self.labelBidPrice2.text())
    
    def bid3clicked(self, a):
        self.bidclicked(self.labelBidPrice3.text())
    
    def bid4clicked(self, a):
        self.bidclicked(self.labelBidPrice4.text())
    
    def bid5clicked(self, a):
        self.bidclicked(self.labelBidPrice5.text())
    
    def lastclicked(self, a):
        self.setPrice(self.labelLastPrice.text())
    
    def setPrice(self, text):
        result = False
        if text is not None and len(text) > 0:
            price = float(str(text))
            if price > 0:
                self.spinPrice.setValue(price)
                result = True
        return result
    
    def askclicked(self, text):
        if self.setPrice(text):
            self.comboDirection.setCurrentIndex(self.directionList.index(DIRECTION_LONG))
            self.updateOffset()
    
    def bidclicked(self, text):
        if self.setPrice(text):
            self.comboDirection.setCurrentIndex(self.directionList.index(DIRECTION_SHORT))
            self.updateOffset()
    
    def updateOffset(self):
        if self.tickOffset.checkState():
            self.comboOffset.setEnabled(True)
            if self.comboProductClass.currentText() in (PRODUCT_EQUITY, PRODUCT_BOND):
                dir = self.comboDirection.currentText()
                if dir == DIRECTION_LONG:
                    self.comboOffset.setCurrentIndex(self.offsetList.index(OFFSET_OPEN) + 1)
                elif dir == DIRECTION_SHORT:
                    self.comboOffset.setCurrentIndex(self.offsetList.index(OFFSET_CLOSE) + 1)
            elif self.comboOffset.currentIndex() == 0:
                self.comboOffset.setCurrentIndex(1)
        else:
            self.comboOffset.setEnabled(False)
            self.comboOffset.setCurrentIndex(0)
    
    # ----------------------------------------------------------------------
    def updateSymbol(self):
        """合约变化"""
        # 读取组件数据
        symbol = str(self.lineSymbol.text())
        self.comboCurrency.setCurrentIndex(1)
        
        currency = safeUnicode(self.comboCurrency.currentText())
        gatewayName = safeUnicode('quantos')
        
        # 查询合约
        contract = self.mainEngine.getContract(symbol)
        
        # 清空价格数量
        self.spinPrice.setValue(0)
        self.spinVolume.setValue(0)
        
        if contract:
            gatewayName = contract.gatewayName
            self.lineName.setText(contract.name)
            p = self.lineName.palette()
            p.setColor(self.lineName.foregroundRole(), QtGui.QColor('black'))
            self.lineName.setPalette(p)
            exchange = contract.exchange
            productClass = contract.productClass
            self.comboExchange.setCurrentIndex(self.exchangeList.index(exchange))
            self.comboProductClass.setCurrentIndex(self.productClassList.index(productClass))
            self.spinPrice.setSingleStep(contract.priceTick)
            self.spinVolume.setSingleStep(contract.lotsize)
            
            self.updateOffset()
        
        else:
            self.comboExchange.setCurrentIndex(0)
            self.comboProductClass.setCurrentIndex(0)
            productClass = safeUnicode(self.comboProductClass.currentText())
            exchange = safeUnicode(self.comboExchange.currentText())
            self.lineName.setText(u'不存在')
            p = self.lineName.palette()
            p.setColor(self.lineName.foregroundRole(), QtGui.QColor('red'))
            self.lineName.setPalette(p)
        
        # 清空行情显示
        self.labelBidPrice1.setText('')
        self.labelBidPrice2.setText('')
        self.labelBidPrice3.setText('')
        self.labelBidPrice4.setText('')
        self.labelBidPrice5.setText('')
        self.labelBidVolume1.setText('')
        self.labelBidVolume2.setText('')
        self.labelBidVolume3.setText('')
        self.labelBidVolume4.setText('')
        self.labelBidVolume5.setText('')
        self.labelAskPrice1.setText('')
        self.labelAskPrice2.setText('')
        self.labelAskPrice3.setText('')
        self.labelAskPrice4.setText('')
        self.labelAskPrice5.setText('')
        self.labelAskVolume1.setText('')
        self.labelAskVolume2.setText('')
        self.labelAskVolume3.setText('')
        self.labelAskVolume4.setText('')
        self.labelAskVolume5.setText('')
        self.labelLastPrice.setText('')
        self.labelReturn.setText('')
        
        if contract:
            # 重新注册事件监听
            if self.signalemit != None:
                self.eventEngine.unregister(EVENT_TICK + self.symbol, self.signalemit)
            
            self.signalemit = self.signal.emit
            self.eventEngine.register(EVENT_TICK + symbol, self.signalemit)
            
            # 订阅合约
            self.mainEngine.subscribe(contract.symbol, gatewayName)
            
            # 更新组件当前交易的合约
            self.symbol = symbol

    # ----------------------------------------------------------------------
    def format_price(self, price):
        return int(price * 1000) / 1000

    # ----------------------------------------------------------------------
    def updateTick(self, event):
        """更新行情"""
        tick = event.dict_['data']

        if tick.symbol == self.symbol:
            contract = self.mainEngine.getContract(tick.symbol)
            price_tick = contract.priceTick

            self.labelBidPrice1.setText(str(self.format_price(tick.bidPrice1)))
            self.labelAskPrice1.setText(str(self.format_price(tick.askPrice1)))
            self.labelBidVolume1.setText(str(tick.bidVolume1))
            self.labelAskVolume1.setText(str(tick.askVolume1))
            
            if tick.bidPrice2:
                self.labelBidPrice2.setText(str(self.format_price(tick.bidPrice2)))
                self.labelBidPrice3.setText(str(self.format_price(tick.bidPrice3)))
                self.labelBidPrice4.setText(str(self.format_price(tick.bidPrice4)))
                self.labelBidPrice5.setText(str(self.format_price(tick.bidPrice5)))
                
                self.labelAskPrice2.setText(str(self.format_price(tick.askPrice2)))
                self.labelAskPrice3.setText(str(self.format_price(tick.askPrice3)))
                self.labelAskPrice4.setText(str(self.format_price(tick.askPrice4)))
                self.labelAskPrice5.setText(str(self.format_price(tick.askPrice5)))
                
                self.labelBidVolume2.setText(str(tick.bidVolume2))
                self.labelBidVolume3.setText(str(tick.bidVolume3))
                self.labelBidVolume4.setText(str(tick.bidVolume4))
                self.labelBidVolume5.setText(str(tick.bidVolume5))
                
                self.labelAskVolume2.setText(str(tick.askVolume2))
                self.labelAskVolume3.setText(str(tick.askVolume3))
                self.labelAskVolume4.setText(str(tick.askVolume4))
                self.labelAskVolume5.setText(str(tick.askVolume5))
            
            self.labelLastPrice.setText(str(self.format_price(tick.lastPrice)))
            if self.spinPrice.value() < 0.000001 and tick.lastPrice > 0.000001:
                self.spinPrice.setValue(tick.lastPrice)
            
            if tick.preClosePrice:
                rt = (old_div(tick.lastPrice, tick.preClosePrice)) - 1
                self.labelReturn.setText(('%.2f' % (rt * 100)) + '%')
            else:
                self.labelReturn.setText('')
    
    # ----------------------------------------------------------------------
    def connectSignal(self):
        """连接Signal"""
        self.signal.connect(self.updateTick)
    
    # ----------------------------------------------------------------------
    def sendOrder(self):
        """发单"""
        symbol = str(self.lineSymbol.text()).strip()
        exchange = safeUnicode(self.comboExchange.currentText())
        price = self.spinPrice.value()
        volume = self.spinVolume.value()
        gatewayName = safeUnicode('quantos')
        
        if len(symbol) <= 0 or len(exchange) <= 0 or price <= 0 or volume <= 0:
            return
        
        # 查询合约
        contract = self.mainEngine.getContract(symbol)

        if contract:
            gatewayName = contract.gatewayName
            exchange = contract.exchange  # 保证有交易所代码
        
        req = VtOrderReq()
        idx = symbol.find(".")
        if idx != -1:
            req.symbol = symbol[0:idx]
        else:
            req.symbol = symbol
        req.exchange = exchange
        req.price = price
        req.volume = volume
        req.direction = safeUnicode(self.comboDirection.currentText())
        req.priceType = safeUnicode(self.comboPriceType.currentText())
        req.offset = safeUnicode(self.comboOffset.currentText())
        req.urgency = self.spinUrgency.value()
        req.productClass = safeUnicode(self.comboProductClass.currentText())
        
        self.mainEngine.sendOrder(req, gatewayName)
    
    # ----------------------------------------------------------------------
    def cancelAll(self):
        """一键撤销所有委托"""
        l = self.mainEngine.getAllWorkingOrders()
        for order in l:
            req = VtCancelOrderReq()
            req.symbol = order.symbol
            req.exchange = order.exchange
            req.frontID = order.frontID
            req.sessionID = order.sessionID
            req.orderID = order.taskID
            self.mainEngine.cancelOrder(req, order.gatewayName)
    
    # ----------------------------------------------------------------------
    def closePosition(self, cell):
        """根据持仓信息自动填写交易组件"""
        # 读取持仓数据,cell是一个表格中的单元格对象
        pos = cell.data
        symbol = pos.symbol
        
        # 更新交易组件的显示合约
        self.lineSymbol.setText(symbol)
        self.updateSymbol()
        
        # 自动填写信息
        self.comboPriceType.setCurrentIndex(self.priceTypeList.index(PRICETYPE_LIMITPRICE))
        self.spinVolume.setValue(pos.enable)
        if pos.direction == DIRECTION_LONG or pos.direction == DIRECTION_NET:
            self.comboDirection.setCurrentIndex(self.directionList.index(DIRECTION_SHORT))
        else:
            self.comboDirection.setCurrentIndex(self.directionList.index(DIRECTION_LONG))
        
        if self.comboProductClass.currentText() not in (PRODUCT_EQUITY, PRODUCT_BOND):
            self.tickOffset.setChecked(True)
            self.comboOffset.setCurrentIndex(self.offsetList.index(OFFSET_CLOSE) + 1)
        elif self.tickOffset.checkState():
            self.comboOffset.setCurrentIndex(self.offsetList.index(OFFSET_CLOSE) + 1)
            
            # 价格留待更新后由用户输入,防止有误操作
    
    def fillSymbol(self, cell):
        
        tick = cell.data
        self.lineSymbol.setText(tick.symbol)
        
        self.updateSymbol()
        
        if type(cell) in (BidCell, AskCell):
            price = str(cell.text())
            if len(price) > 0:
                price = float(price)
                if price > 0:
                    self.spinPrice.setValue(price)
                    direction = DIRECTION_LONG if type(cell) is AskCell else DIRECTION_SHORT
                    self.comboDirection.setCurrentIndex(self.directionList.index(direction))
                    self.updateOffset()
Esempio n. 28
0
class reglageExpert(QWidget) :
	"""Class pour créer les widgets spécifiques pour les réglages plus fin sur la qualité d'encodage, sur le débit binaire des fichiers, ... """
	def __init__(self, listeFormat, comboFormat, parent=None) :
		super(reglageExpert, self).__init__(parent)
		self.listeFormat = listeFormat
		self.comboFormat = comboFormat
		self.format = self.comboFormat.currentIndex()
		self.parent = parent
		layout = QHBoxLayout(self)
		self.textLabel = QLabel(self)
		self.textLabel.hide()
		self.expert = QCheckBox(_(u"Réglage expert : "), self)
		self.qualite = QComboBox(self)
		layout.addWidget(self.expert)
		layout.addWidget(self.textLabel)
		layout.addWidget(self.qualite)
		layout.addStretch()
		i=1
		while i<9 :
			self.qualite.addItem(str(i))
			i	+=	1
		self.qualite.hide()
		self.changeFormat(self.comboFormat.currentIndex())
		self.connect(self.expert, SIGNAL("stateChanged(int)"), self.setExpert)
		self.connect(self.comboFormat, SIGNAL("currentIndexChanged(int)"), self.changeFormat)
		self.connect(self.qualite, SIGNAL("currentIndexChanged(int)"), self.changeQualite)

	def setExpert(self, state) :
		if state :
			self.qualite.show()
			self.textLabel.show()
		else :
			self.qualite.hide()
			self.textLabel.hide()

	def changeQualite(self,qualite) :
		self.changeFormat(self.comboFormat.currentIndex())

	def changeFormat(self, format) :
		if len(self.listeFormat) == 0 :
			return
		else :
			if self.listeFormat[format] == "mp3" or self.listeFormat[format] == "mp2" or self.listeFormat[format] == "ogg" :
				self.textLabel.setText(_(u"Qualité d'encodage"))
				self.qualite.setEnabled(True)
				self.C = u" -C %f " % (10.0*float(self.qualite.currentIndex()+1)/8.0)
			elif self.listeFormat[format] == "flac" :
				self.textLabel.setText(_(u"Taux de compression"))
				self.qualite.setEnabled(True)
				self.C = u" -C %d " % (self.qualite.currentIndex()+1)
			else :
				self.textLabel.setText(_(u"Non applicable, format non compressé"))
				self.qualite.setDisabled(True)
				self.C = u""

	def getExpertState(self) :
		return self.expert.isChecked()

	def getC(self) :
		return self.C

	def saveConfig(self, idsection="") :
		if idsection == "" :
			return 
		EkdConfig.set(idsection, u'format', unicode(self.comboFormat.currentIndex()))
		EkdConfig.set(idsection, u'expert', unicode(int(self.getExpertState())))
		EkdConfig.set(idsection, u'qualite', unicode(self.qualite.currentIndex()))


	def loadConfig(self, idsection="") :
		if idsection == "" :
			return 
		self.comboFormat.setCurrentIndex(int(EkdConfig.get(idsection, 'format')))
		self.expert.setChecked(int(EkdConfig.get(idsection, 'expert')))
		self.qualite.setCurrentIndex(int(EkdConfig.get(idsection, 'qualite')))
Esempio n. 29
0
class Dialog(QDialog):
    def __init__(self, mainwindow):
        super(Dialog, self).__init__(mainwindow)
        self._document = None

        layout = QGridLayout()
        self.setLayout(layout)

        self.versionLabel = QLabel()
        self.lilyChooser = lilychooser.LilyChooser()

        self.outputLabel = QLabel()
        self.outputCombo = QComboBox()

        self.resolutionLabel = QLabel()
        self.resolutionCombo = QComboBox(editable=True)

        self.antialiasLabel = QLabel()
        self.antialiasSpin = QSpinBox(minimum=1, maximum=128, value=1)

        self.modeLabel = QLabel()
        self.modeCombo = QComboBox()

        self.englishCheck = QCheckBox()
        self.deleteCheck = QCheckBox()

        self.commandLineLabel = QLabel()
        self.commandLine = QTextEdit(acceptRichText=False)

        self.buttons = QDialogButtonBox(QDialogButtonBox.Ok
                                        | QDialogButtonBox.Cancel)
        self.buttons.button(QDialogButtonBox.Ok).setIcon(
            icons.get("lilypond-run"))
        userguide.addButton(self.buttons, "engrave_custom")

        self.resolutionCombo.addItems(['100', '200', '300', '600', '1200'])
        self.resolutionCombo.setCurrentIndex(2)

        self.modeCombo.addItems(['preview', 'publish', 'debug'])
        layout.addWidget(self.versionLabel, 0, 0)
        layout.addWidget(self.lilyChooser, 0, 1, 1, 3)
        layout.addWidget(self.outputLabel, 1, 0)
        layout.addWidget(self.outputCombo, 1, 1, 1, 3)
        layout.addWidget(self.resolutionLabel, 2, 0)
        layout.addWidget(self.resolutionCombo, 2, 1)
        layout.addWidget(self.antialiasLabel, 2, 2, Qt.AlignRight)
        layout.addWidget(self.antialiasSpin, 2, 3)
        layout.addWidget(self.modeLabel, 3, 0)
        layout.addWidget(self.modeCombo, 3, 1, 1, 3)
        layout.addWidget(self.englishCheck, 4, 0, 1, 4)
        layout.addWidget(self.deleteCheck, 5, 0, 1, 4)
        layout.addWidget(self.commandLineLabel, 6, 0, 1, 4)
        layout.addWidget(self.commandLine, 7, 0, 1, 4)
        layout.addWidget(widgets.Separator(), 8, 0, 1, 4)
        layout.addWidget(self.buttons, 9, 0, 1, 4)

        app.translateUI(self)
        qutil.saveDialogSize(self, "engrave/custom/dialog/size",
                             QSize(480, 260))
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)

        model = listmodel.ListModel(formats,
                                    display=lambda f: f.title(),
                                    icon=lambda f: icons.file_type(f.type))
        self.outputCombo.setModel(model)

        s = QSettings()
        s.beginGroup("lilypond_settings")
        self.englishCheck.setChecked(s.value("no_translation", False, bool))
        self.deleteCheck.setChecked(
            s.value("delete_intermediate_files", True, bool))

        if s.value("default_output_target", "pdf", type("")) == "svg":
            self.outputCombo.setCurrentIndex(3)

        app.jobFinished.connect(self.slotJobFinished)
        self.outputCombo.currentIndexChanged.connect(self.makeCommandLine)
        self.modeCombo.currentIndexChanged.connect(self.makeCommandLine)
        self.deleteCheck.toggled.connect(self.makeCommandLine)
        self.resolutionCombo.editTextChanged.connect(self.makeCommandLine)
        self.antialiasSpin.valueChanged.connect(self.makeCommandLine)
        self.makeCommandLine()
        panelmanager.manager(
            mainwindow).layoutcontrol.widget().optionsChanged.connect(
                self.makeCommandLine)

    def translateUI(self):
        self.setWindowTitle(app.caption(_("Engrave custom")))
        self.versionLabel.setText(_("LilyPond Version:"))
        self.outputLabel.setText(_("Output Format:"))
        self.resolutionLabel.setText(_("Resolution:"))
        self.antialiasLabel.setText(_("Antialias Factor:"))
        self.modeLabel.setText(_("Engraving mode:"))
        self.modeCombo.setItemText(0, _("Preview"))
        self.modeCombo.setItemText(1, _("Publish"))
        self.modeCombo.setItemText(2, _("Layout Control"))
        self.englishCheck.setText(_("Run LilyPond with English messages"))
        self.deleteCheck.setText(_("Delete intermediate output files"))
        self.commandLineLabel.setText(_("Command line:"))
        self.buttons.button(QDialogButtonBox.Ok).setText(_("Run LilyPond"))
        self.outputCombo.update()

    def slotJobFinished(self, doc):
        if doc == self._document:
            self.buttons.button(QDialogButtonBox.Ok).setEnabled(True)
            self._document = None

    def setDocument(self, doc):
        self.lilyChooser.setLilyPondInfo(command.info(doc))
        if jobmanager.isRunning(doc):
            self._document = doc
            self.buttons.button(QDialogButtonBox.Ok).setEnabled(False)

    def makeCommandLine(self):
        """Reads the widgets and builds a command line."""
        f = formats[self.outputCombo.currentIndex()]
        self.resolutionCombo.setEnabled('resolution' in f.widgets)
        self.antialiasSpin.setEnabled('antialias' in f.widgets)
        cmd = ["$lilypond"]

        if self.modeCombo.currentIndex() == 0:  # preview mode
            cmd.append('-dpoint-and-click')
        elif self.modeCombo.currentIndex() == 1:  # publish mode
            cmd.append('-dno-point-and-click')
        else:  # debug mode
            args = panelmanager.manager(
                self.parent()).layoutcontrol.widget().preview_options()
            cmd.extend(args)

        if self.deleteCheck.isChecked():
            cmd.append('-ddelete-intermediate-files')
        else:
            cmd.append('-dno-delete-intermediate-files')
        d = {
            'version': self.lilyChooser.lilyPondInfo().version,
            'resolution': self.resolutionCombo.currentText(),
            'antialias': self.antialiasSpin.value(),
        }
        cmd.append("$include")
        cmd.extend(f.options(d))
        cmd.append("$filename")
        self.commandLine.setText(' '.join(cmd))

    def getJob(self, document):
        """Returns a Job to start."""
        filename, includepath = documentinfo.info(document).jobinfo(True)
        i = self.lilyChooser.lilyPondInfo()
        cmd = []
        for t in self.commandLine.toPlainText().split():
            if t == '$lilypond':
                cmd.append(i.abscommand() or i.command)
            elif t == '$filename':
                cmd.append(filename)
            elif t == '$include':
                cmd.extend('-I' + path for path in includepath)
            else:
                cmd.append(t)
        j = job.Job()
        j.directory = os.path.dirname(filename)
        j.command = cmd
        if self.englishCheck.isChecked():
            j.environment['LANG'] = 'C'
        j.setTitle("{0} {1} [{2}]".format(os.path.basename(i.command),
                                          i.versionString(),
                                          document.documentName()))
        return j
Esempio n. 30
0
class AnimationWindow(PyDialog):
    """
    +-------------------+
    | Animation         |
    +-------------------------+
    | icase   ______          |
    | scale   ______  Default |
    | time    ______  Default |
    |                         |
    | nframes ______  Default |
    | resolu. ______  Default |
    | Dir     ______  Browse  |
    | iFrame  ______          |
    |                         |
    | Animations:             |
    | o Scale, Phase, Time    |  # TODO: add time
    |                         |
    | x delete images         |
    | x repeat                |  # TODO: change to an integer
    | x make gif              |
    |                         |
    |      Step, RunAll       |
    |         Close           |
    +-------------------------+

    TODO: add key-frame support
    """
    def __init__(self, data, win_parent=None):
        PyDialog.__init__(self, data, win_parent)
        self.set_font_size(data['font_size'])
        self.istep = 0
        self._animate_type = 'time'

        self._updated_animation = False
        self._icase = data['icase']
        self._default_name = data['name']
        self._default_time = data['time']
        self._default_fps = data['frames/sec']
        self._default_resolution = data['resolution']

        self._scale = data['scale']
        self._default_scale = data['default_scale']
        self._default_is_scale = data['is_scale']

        self._phase = data['phase']
        self._default_phase = data['default_phase']

        self._default_dirname = data['dirname']
        self._default_gif_name = os.path.join(self._default_dirname,
                                              data['name'] + '.gif')

        self.animation_types = [
            'Animate Scale',
        ]
        #'Animate Phase',
        #'Animate Time',
        #'Animate Frequency Sweep'
        #]

        self.setWindowTitle('Animate Model')
        self.create_widgets()
        self.create_layout()
        self.set_connections()

        self.is_gui = False
        if hasattr(self.win_parent, '_updated_legend'):
            self.win_parent.is_animate_open = True
            self.is_gui = True

    def create_widgets(self):
        """creates the menu objects"""
        icase_max = 1000  # TODO: update 1000

        self.icase = QLabel("iCase:")
        self.icase_edit = QSpinBox(self)
        self.icase_edit.setRange(1, icase_max)
        self.icase_edit.setSingleStep(1)
        self.icase_edit.setValue(self._icase)
        self.icase_edit.setToolTip(
            'Case Number for the Scale/Phase Animation Type.\n'
            'Defaults to the result you had shown when you clicked "Create Animation".\n'
            'iCase can be seen by clicking "Apply" on a result.')

        self.scale = QLabel("Scale:")
        self.scale_edit = QLineEdit(str(self._scale))
        self.scale_button = QPushButton("Default")
        self.scale_edit.setToolTip('Scale factor of the "deflection"')
        self.scale_button.setToolTip('Sets the scale factor of the gif to %s' %
                                     self._scale)

        self.time = QLabel("Total Time (sec):")
        self.time_edit = QDoubleSpinBox(self)
        self.time_edit.setValue(self._default_time)
        self.time_edit.setRange(0.1, 10.0)
        self.time_edit.setDecimals(2)
        self.time_edit.setSingleStep(0.1)
        self.time_button = QPushButton("Default")
        self.time_edit.setToolTip("Total time of the gif")
        self.time_button.setToolTip('Sets the total time of the gif to %.2f' %
                                    self._default_time)

        self.fps = QLabel("Frames/Second:")
        self.fps_edit = QSpinBox(self)
        self.fps_edit.setRange(1, 60)
        self.fps_edit.setSingleStep(1)
        self.fps_edit.setValue(self._default_fps)
        self.fps_button = QPushButton("Default")
        self.fps_edit.setToolTip(
            "A higher FPS is smoother, but may not play well for large gifs")
        self.fps_button.setToolTip('Sets the FPS to %s' % self._default_fps)

        self.resolution = QLabel("Resolution Scale:")
        self.resolution_edit = QSpinBox(self)
        self.resolution_edit.setRange(1, 5)
        self.resolution_edit.setSingleStep(1)
        self.resolution_edit.setValue(self._default_resolution)
        self.resolution_button = QPushButton("Default")
        self.resolution_edit.setToolTip(
            'Scales the window resolution by an integer factor')
        self.resolution_button.setToolTip('Sets the resolution to %s' %
                                          self._default_resolution)

        #-----------------
        # Time plot
        self.icase_start = QLabel("iCase Start:")
        self.icase_start_edit = QSpinBox(self)
        self.icase_start_edit.setRange(0, icase_max)
        self.icase_start_edit.setSingleStep(1)
        self.icase_start_edit.setValue(self._icase)
        self.icase_start_button = QPushButton("Default")

        self.icase_end = QLabel("iCase End:")
        self.icase_end_edit = QSpinBox(self)
        self.icase_end_edit.setRange(0, icase_max)
        self.icase_end_edit.setSingleStep(1)
        self.icase_end_edit.setValue(self._icase)
        self.icase_end_button = QPushButton("Default")

        self.icase_delta = QLabel("iCase Delta:")
        self.icase_delta_edit = QSpinBox(self)
        self.icase_delta_edit.setRange(1, icase_max)
        self.icase_delta_edit.setSingleStep(1)
        self.icase_delta_edit.setValue(1)
        self.icase_delta_button = QPushButton("Default")

        self.min_value = QLabel("Min Value:")
        self.min_value_edit = QLineEdit(str(0.))
        #self.min_value_edit.setRange(1, 1000)
        #self.min_value_edit.setSingleStep(1)
        #self.min_value_edit.setValue(1)
        self.min_value_button = QPushButton("Default")

        self.max_value = QLabel("Max Value:")
        self.max_value_edit = QLineEdit(str(1.))
        #self.min_value_edit.setRange(1, 1000)  # TODO: update 1000
        #self.min_value_edit.setSingleStep(1)
        #self.min_value_edit.setValue(1)
        self.max_value_button = QPushButton("Default")

        self.icase_start_edit.setToolTip('The first frame of the animation')
        self.icase_end_edit.setToolTip(
            'The last frame of the animation\n'
            'Assumes icase_start + nframes * icase_delta = icase_end')
        self.icase_delta_edit.setToolTip(
            'The frame step size (to skip non-consecutive results).\n'
            'Frame skipping can be used to:\n'
            "  - skip across results that you don't want to plot\n"
            '  - adjust the FPS')

        self.min_value_edit.setToolTip(
            'Min value of the legend (not supported)')
        self.max_value_edit.setToolTip(
            'Max value of the legend (not supported)')
        #'time' : 0.,
        #'default_time' : 0,
        #'icase_start' : 10,
        #'icase_delta' : 3,
        #'min_value' : 0.,
        #'max_value' : 1000.,

        self.browse_folder = QLabel('Output Directory:')
        self.browse_folder_edit = QLineEdit(str(self._default_dirname))
        self.browse_folder_button = QPushButton('Browse')
        self.browse_folder_edit.setToolTip(
            'Location to save the png/gif files')

        self.gif = QLabel("Gif Filename:")
        self.gif_edit = QLineEdit(str(self._default_name + '.gif'))
        self.gif_button = QPushButton('Default')
        self.gif_edit.setToolTip('Name of the gif')
        self.gif_button.setToolTip('Sets the name of the gif to %s.gif' %
                                   self._default_name)

        # scale / phase
        self.animate_scale_radio = QRadioButton("Animate Scale")
        self.animate_phase_radio = QRadioButton("Animate Phase")
        self.animate_time_radio = QRadioButton("Animate Time")
        self.animate_freq_sweeep_radio = QRadioButton(
            "Animate Frequency Sweep")
        self.animate_scale_radio.setToolTip(
            'Animates the scale factor based on the "Animation Type"')
        self.animate_time_radio.setToolTip('Animates the time/load/mode step')

        self.animate_scale_radio.setChecked(self._default_is_scale)
        self.animate_phase_radio.setChecked(not self._default_is_scale)
        self.animate_time_radio.setChecked(False)

        msg = 'Scale : Animates the scale factor based on the "Animation Profile"\n'
        if self._default_phase is None:
            self.animate_phase_radio.setDisabled(True)
            self.animate_phase_radio.setToolTip('Animates the phase angle '
                                                '(only for complex results)')
            msg += 'Phase : Animates the phase angle (only for complex results)\n'
        else:
            self.animate_phase_radio.setToolTip("Animates the phase angle")
            msg += 'Phase : Animates the phase angle\n'
        msg += (
            'Time : Animates the time/load/mode step\n'
            'Freq Sweep : Animates a complex result across a range of frequencies '
            '(not supported)\n')

        self.animate_freq_sweeep_radio.setDisabled(True)
        self.animate_freq_sweeep_radio.setToolTip(
            'Animates a complex result across a range of frequencies (not supported)'
        )
        self.animation_type = QLabel("Animation Type:")
        animation_type = OrderedDict()
        #scale_msg = 'Scale\n'
        #phase_msg = 'Phase\n'
        #time_msg = 'Time\n'
        #animation_types = [
        #('Animate Scale', scale_msg),
        #('Animate Phase', phase_msg),
        #('Animate Time', time_msg),
        ##'Animate Frequency Sweep'
        #]

        if self._phase is not None:
            self.animation_types.append('Animate Phase')
        self.animation_types.append('Animate Time')

        self.animation_profile = QLabel("Animation Profile:")

        self.animation_profile_edit = QComboBox()
        for animation_profile in ANIMATION_PROFILES:
            self.animation_profile_edit.addItem(animation_profile)
        self.animation_profile_edit.setToolTip('The profile for a scaled GIF')

        self.animation_type_edit = QComboBox()
        # TODO: add a tooltip for each item
        for animation_type in self.animation_types:
            self.animation_type_edit.addItem(animation_type)
        #self.animation_type_edit.setToolTip('The profile for a scaled GIF')
        self.animation_type_edit.setToolTip(msg)

        self.csv_profile = QLabel("CSV profile:")
        self.csv_profile_edit = QLineEdit()
        self.csv_profile_browse_button = QPushButton('Browse')
        self.csv_profile_edit.setToolTip(
            'The path to the CSV file of (Scale1, Scale2, Scale3, ...)')

        widget = QWidget(self)
        horizontal_vertical_group = QButtonGroup(widget)
        horizontal_vertical_group.addButton(self.animate_scale_radio)
        horizontal_vertical_group.addButton(self.animate_phase_radio)
        horizontal_vertical_group.addButton(self.animate_time_radio)
        horizontal_vertical_group.addButton(self.animate_freq_sweeep_radio)

        # one / two sided
        self.onesided_radio = QRadioButton("One Sided")
        self.onesided_radio.setToolTip(
            "A one sided gif doesn't return to the starting point (e.g., 0 to 360 degrees)"
        )
        self.twosided_radio = QRadioButton("Two Sided")
        self.twosided_radio.setToolTip(
            'A two sided gif returns to the starting point (e.g., 0 to 10 to 0)'
        )

        if self._default_phase is None:
            self.onesided_radio.setChecked(False)
            self.twosided_radio.setChecked(True)
        else:
            self.onesided_radio.setChecked(True)
            self.twosided_radio.setChecked(False)
        widget = QWidget(self)
        horizontal_vertical_group = QButtonGroup(widget)
        horizontal_vertical_group.addButton(self.onesided_radio)
        horizontal_vertical_group.addButton(self.twosided_radio)

        # animate in gui
        self.animate_in_gui_checkbox = QCheckBox("Animate In GUI?")
        self.animate_in_gui_checkbox.setChecked(True)

        # make images
        self.make_images_checkbox = QCheckBox("Make images?")
        self.make_images_checkbox.setChecked(True)

        # make images
        self.overwrite_images_checkbox = QCheckBox("Overwrite images?")
        self.overwrite_images_checkbox.setChecked(True)

        # delete images when finished
        self.delete_images_checkbox = QCheckBox("Delete images when finished?")
        self.delete_images_checkbox.setChecked(True)

        # endless loop
        self.repeat_checkbox = QCheckBox("Repeat?")
        self.repeat_checkbox.setChecked(True)
        self.repeat_checkbox.setToolTip(
            "Repeating creates an infinitely looping gif")

        # endless loop
        self.make_gif_checkbox = QCheckBox("Make Gif?")
        if IS_IMAGEIO:
            self.make_gif_checkbox.setChecked(True)
        else:
            self.make_gif_checkbox.setChecked(False)
            self.make_gif_checkbox.setEnabled(False)
            self.make_gif_checkbox.setToolTip(
                'imageio is not available; install it')

        # bottom buttons
        self.step_button = QPushButton("Step")
        self.stop_button = QPushButton("Stop")
        self.run_button = QPushButton("Run All")

        #self.apply_button = QPushButton("Apply")
        #self.ok_button = QPushButton("OK")
        self.cancel_button = QPushButton("Close")

        #self.set_grid_time(enabled=False)
        #self.set_grid_scale(enabled=self._default_is_scale)
        if self._default_phase:
            self.on_animate_phase(force=True)
        else:
            self.on_animate_scale(force=True)

    def set_connections(self):
        """creates button actions"""
        self.scale_button.clicked.connect(self.on_default_scale)
        self.time_button.clicked.connect(self.on_default_time)

        self.fps_button.clicked.connect(self.on_default_fps)
        self.resolution_button.clicked.connect(self.on_default_resolution)
        self.browse_folder_button.clicked.connect(self.on_browse_folder)
        self.csv_profile_browse_button.clicked.connect(self.on_browse_csv)
        self.gif_button.clicked.connect(self.on_default_name)

        self.step_button.clicked.connect(self.on_step)
        self.stop_button.clicked.connect(self.on_stop)
        self.run_button.clicked.connect(self.on_run)

        #self.animate_scale_radio.clicked.connect(self.on_animate_scale)
        #self.animate_phase_radio.clicked.connect(self.on_animate_phase)
        #self.animate_time_radio.clicked.connect(self.on_animate_time)
        self.animation_type_edit.currentIndexChanged.connect(self.on_animate)
        #self.animate_freq_sweeep_radio

        #self.apply_button.clicked.connect(self.on_apply)
        #self.ok_button.clicked.connect(self.on_ok)
        self.cancel_button.clicked.connect(self.on_cancel)

        self.animate_in_gui_checkbox.clicked.connect(self.on_animate_in_gui)
        self.animate_in_gui_checkbox.setChecked(True)
        self.on_animate_in_gui()

    def on_animate_in_gui(self):
        animate_in_gui = self.animate_in_gui_checkbox.isChecked()
        enable = not animate_in_gui
        self.make_images_checkbox.setEnabled(enable)
        self.delete_images_checkbox.setEnabled(enable)
        self.make_gif_checkbox.setEnabled(enable)
        self.repeat_checkbox.setEnabled(enable)
        self.resolution_button.setEnabled(enable)
        self.resolution_edit.setEnabled(enable)
        self.gif_edit.setEnabled(enable)
        self.gif_button.setEnabled(enable)
        self.browse_folder_button.setEnabled(enable)
        self.browse_folder_edit.setEnabled(enable)
        self.step_button.setEnabled(enable)

    def on_animate(self, value):
        """
        animate pulldown

        Parameters
        ----------
        value : int
            index in animation_types
        """
        #animation_types = ['Animate Scale', 'Animate Phase', 'Animate Time',
        #'Animate Frequency Sweep']
        animation_type = self.animation_types[value]
        if animation_type == 'Animate Scale':
            self.on_animate_scale()
        elif animation_type == 'Animate Phase':
            self.on_animate_phase()
        elif animation_type == 'Animate Time':
            self.on_animate_time()
        else:
            raise NotImplementedError('value = ', value)

    def on_animate_time(self, force=False):
        """enables the secondary input"""
        #print('on_animate_time')
        if self._animate_type == 'scale' or force:
            self.set_grid_scale(False, 'time')
        self.set_grid_time(True, 'time')
        self._animate_type = 'time'

    def on_animate_scale(self, force=False):
        """enables the secondary input"""
        #print('on_animate_scale')
        self.set_grid_scale(True, 'scale')
        if self._animate_type == 'time' or force:
            self.set_grid_time(False, 'scale')
        self._animate_type = 'scale'

    def on_animate_phase(self, force=False):
        """enables the secondary input"""
        #print('on_animate_phase')
        if self._animate_type == 'scale' or force:
            self.set_grid_scale(False, 'phase')
        if self._animate_type == 'time' or force:
            self.set_grid_time(False, 'phase')
        self._animate_type = 'phase'

    def set_grid_scale(self, enabled=True, word=''):
        """enables/disables the secondary input"""
        #print('%s-set_grid_scale; enabled = %r' % (word, enabled))
        self.animation_profile.setEnabled(enabled)
        self.animation_profile_edit.setEnabled(enabled)

        # TODO: doesn't work...
        #self.csv_profile.setEnabled(enabled)
        #self.csv_profile_edit.setEnabled(enabled)
        #self.csv_profile_button.setEnabled(enabled)

    def set_grid_time(self, enabled=True, word=''):
        """enables/disables the secondary input"""
        #print('%s-set_grid_time; enabled = %r' % (word, enabled))
        self.icase_start.setEnabled(enabled)
        self.icase_start_edit.setEnabled(enabled)
        self.icase_start_button.setEnabled(enabled)

        self.icase_end.setEnabled(enabled)
        self.icase_end_edit.setEnabled(enabled)
        self.icase_end_button.setEnabled(enabled)

        self.icase_delta.setEnabled(enabled)
        self.icase_delta_edit.setEnabled(enabled)
        self.icase_delta_button.setEnabled(enabled)

        self.min_value.setEnabled(enabled)
        self.min_value_edit.setEnabled(enabled)
        self.min_value_button.setEnabled(enabled)

        self.max_value.setEnabled(enabled)
        self.max_value_edit.setEnabled(enabled)
        self.max_value_button.setEnabled(enabled)

        self.icase.setEnabled(not enabled)
        self.icase_edit.setEnabled(not enabled)
        self.fps.setEnabled(not enabled)
        self.fps_edit.setEnabled(not enabled)
        self.fps_button.setEnabled(not enabled)

    def on_browse_folder(self):
        """opens a folder dialog"""
        dirname = open_directory_dialog(self, 'Select a Directory')
        if not dirname:
            return
        self.browse_folder_edit.setText(dirname)

    def on_browse_csv(self):
        """opens a file dialog"""
        default_filename = ''
        file_types = 'Delimited Text (*.txt; *.dat; *.csv)'
        dirname = open_file_dialog(self, 'Select a CSV File', default_filename,
                                   file_types)
        if not dirname:
            return
        self.csv_profile_browse_button.setText(dirname)

    def on_default_name(self):
        """sets the default gif name"""
        self.gif_edit.setText(self._default_name + '.gif')

    def on_default_scale(self):
        """sets the default displacement scale factor"""
        self.scale_edit.setText(str(self._default_scale))
        self.scale_edit.setStyleSheet("QLineEdit{background: white;}")

    def on_default_time(self):
        """sets the default gif time"""
        self.time_edit.setValue(self._default_time)

    def on_default_fps(self):
        """sets the default FPS"""
        self.fps_edit.setValue(self._default_fps)

    def on_default_resolution(self):
        """sets the default image resolution scale factor"""
        self.resolution_edit.setValue(self._default_resolution)

    def create_layout(self):
        """displays the menu objects"""
        grid = QGridLayout()

        grid.addWidget(self.icase, 0, 0)
        grid.addWidget(self.icase_edit, 0, 1)

        grid.addWidget(self.scale, 1, 0)
        grid.addWidget(self.scale_edit, 1, 1)
        grid.addWidget(self.scale_button, 1, 2)

        grid.addWidget(self.time, 2, 0)
        grid.addWidget(self.time_edit, 2, 1)
        grid.addWidget(self.time_button, 2, 2)

        # spacer
        spacer = QLabel('')

        grid.addWidget(self.fps, 3, 0)
        grid.addWidget(self.fps_edit, 3, 1)
        grid.addWidget(self.fps_button, 3, 2)

        grid.addWidget(self.resolution, 4, 0)
        grid.addWidget(self.resolution_edit, 4, 1)
        grid.addWidget(self.resolution_button, 4, 2)

        grid.addWidget(self.browse_folder, 5, 0)
        grid.addWidget(self.browse_folder_edit, 5, 1)
        grid.addWidget(self.browse_folder_button, 5, 2)

        grid.addWidget(self.gif, 6, 0)
        grid.addWidget(self.gif_edit, 6, 1)
        grid.addWidget(self.gif_button, 6, 2)

        grid.addWidget(self.animation_type, 7, 0)
        grid.addWidget(self.animation_type_edit, 7, 1)

        grid.addWidget(spacer, 8, 0)

        #----------
        #Time
        grid_time = QGridLayout()
        grid_time.addWidget(self.icase_start, 0, 0)
        grid_time.addWidget(self.icase_start_edit, 0, 1)
        #grid_time.addWidget(self.icase_start_button, 0, 2)

        grid_time.addWidget(self.icase_end, 1, 0)
        grid_time.addWidget(self.icase_end_edit, 1, 1)
        #grid_time.addWidget(self.icase_end_button, 1, 2)

        grid_time.addWidget(self.icase_delta, 2, 0)
        grid_time.addWidget(self.icase_delta_edit, 2, 1)
        #grid_time.addWidget(self.icase_delta_button, 2, 2)

        #grid_time.addWidget(self.min_value, 3, 0)
        #grid_time.addWidget(self.min_value_edit, 3, 1)
        #grid_time.addWidget(self.min_value_button, 3, 2)

        #grid_time.addWidget(self.max_value, 4, 0)
        #grid_time.addWidget(self.max_value_edit, 4, 1)
        #grid_time.addWidget(self.max_value_button, 4, 2)
        grid_time.addWidget(spacer, 5, 0)

        #--------------
        grid_scale = QGridLayout()
        grid_scale.addWidget(self.animation_profile, 0, 0)
        grid_scale.addWidget(self.animation_profile_edit, 0, 1)

        #grid_scale.addWidget(self.csv_profile, 1, 0)
        #grid_scale.addWidget(self.csv_profile_edit, 1, 1)
        #grid_scale.addWidget(self.csv_profile_browse_button, 1, 2)

        self.csv_profile = QLabel("CSV profile:")
        self.csv_profile_edit = QLineEdit()
        self.csv_profile_button = QPushButton('Browse')

        #box_time = QVBoxLayout()
        # TODO: It's super annoying that the animate time box doesn't
        #       line up with the previous box
        box_scale = QGroupBox('Animate Scale')
        box_scale.setLayout(grid_scale)

        box_time = QGroupBox('Animate Time')
        box_time.setLayout(grid_time)
        #----------

        grid2 = QGridLayout()
        #grid2.addWidget(self.animate_scale_radio, 8, 0)
        #grid2.addWidget(self.animate_phase_radio, 8, 1)
        #grid2.addWidget(self.animate_time_radio, 8, 2)
        #grid2.addWidget(self.animate_freq_sweeep_radio, 8, 3)

        grid2.addWidget(self.animate_in_gui_checkbox, 10, 0)
        grid2.addWidget(self.make_images_checkbox, 11, 0)
        #grid2.addWidget(self.overwrite_images_checkbox, 11, 0)
        grid2.addWidget(self.delete_images_checkbox, 11, 1)
        grid2.addWidget(self.make_gif_checkbox, 11, 2)
        grid2.addWidget(self.repeat_checkbox, 12, 0)

        grid2.addWidget(spacer, 13, 0)
        grid_hbox = QHBoxLayout()
        grid_hbox.addWidget(spacer)
        grid_hbox.addLayout(grid2)
        grid_hbox.addWidget(spacer)

        # bottom buttons
        step_run_box = QHBoxLayout()
        step_run_box.addWidget(self.step_button)
        step_run_box.addWidget(self.stop_button)
        step_run_box.addWidget(self.run_button)

        ok_cancel_box = QHBoxLayout()
        ok_cancel_box.addWidget(self.cancel_button)

        vbox = QVBoxLayout()
        vbox.addLayout(grid)
        vbox.addWidget(box_scale)
        vbox.addWidget(box_time)
        #vbox.addLayout(checkboxes)
        vbox.addLayout(grid_hbox)
        vbox.addStretch()
        vbox.addLayout(step_run_box)
        vbox.addLayout(ok_cancel_box)
        self.setLayout(vbox)

    def on_step(self):
        """click the Step button"""
        passed, validate_out = self.on_validate()
        if passed:
            try:
                self._make_gif(validate_out, istep=self.istep)
                self.istep += 1
            except IndexError:
                self._make_gif(validate_out, istep=0)
                self.istep += 1

    def on_stop(self):
        passed, validate_out = self.on_validate()
        if passed:
            self._make_gif(validate_out, stop_animation=True)

    def on_run(self):
        """click the Run button"""
        self.istep = 0
        passed, validate_out = self.on_validate()
        if passed:
            self._make_gif(validate_out, istep=None)
        return passed

    def _make_gif(self, validate_out, istep=None, stop_animation=False):
        """interface for making the gif"""
        icase, scale, time, fps, animate_in_gui, magnify, output_dir, gifbase = validate_out

        gif_filename = None
        if not stop_animation and not animate_in_gui:
            if gifbase.lower().endswith('.gif'):
                gifbase = gifbase[:-4]
            gif_filename = os.path.join(output_dir, gifbase + '.gif')

        animate_scale = self.animate_scale_radio.isChecked()
        animate_phase = self.animate_phase_radio.isChecked()
        animate_time = self.animate_time_radio.isChecked()

        animate_scale = False
        animate_phase = False
        animate_time = False
        if self._animate_type == 'scale':
            animate_scale = True
        elif self._animate_type == 'phase':
            animate_phase = True
        elif self._animate_type == 'time':
            animate_time = True
        else:
            raise NotImplementedError(self._animate_type)

        make_images = self.make_images_checkbox.isChecked()
        delete_images = self.delete_images_checkbox.isChecked()
        make_gif = self.make_gif_checkbox.isChecked()
        key = str(self.animation_profile_edit.currentText())
        #profile = ANIMATION_PROFILES[key]

        #ANIMATION_PROFILES['0 to Scale'] = [0., 1.]
        #ANIMATION_PROFILES['0 to Scale to 0'] = [0., 1., 0.]
        if key == '0 to Scale':
            onesided = True
        else:
            onesided = False

        icase_start = self.icase_start_edit.value()
        icase_end = self.icase_end_edit.value()
        icase_delta = self.icase_delta_edit.value()

        #onesided = self.onesided_radio.isChecked()
        bool_repeat = self.repeat_checkbox.isChecked(
        )  # TODO: change this to an integer
        if bool_repeat:
            nrepeat = 0
        else:
            nrepeat = 1
        #self.out_data['is_shown'] = self.show_radio.isChecked()
        #icase = self._icase
        if self.is_gui:
            self.win_parent.win_parent.make_gif(
                gif_filename,
                scale,
                istep=istep,
                animate_scale=animate_scale,
                animate_phase=animate_phase,
                animate_time=animate_time,
                icase=icase,
                icase_start=icase_start,
                icase_end=icase_end,
                icase_delta=icase_delta,
                time=time,
                onesided=onesided,
                nrepeat=nrepeat,
                fps=fps,
                magnify=magnify,
                make_images=make_images,
                delete_images=delete_images,
                make_gif=make_gif,
                stop_animation=stop_animation,
                animate_in_gui=animate_in_gui,
            )

        self.out_data['clicked_ok'] = True
        self.out_data['close'] = True

    def on_validate(self):
        """checks to see if the input is valid"""
        icase, flag0 = self.check_int(self.icase_edit)
        scale, flag1 = self.check_float(self.scale_edit)
        time, flag2 = self.check_float(self.time_edit)
        fps, flag3 = self.check_float(self.fps_edit)
        animate_in_gui = self.animate_in_gui_checkbox.isChecked()

        if animate_in_gui:
            passed = all([flag0, flag1, flag2, flag3])
            return passed, (icase, scale, time, fps, animate_in_gui, None,
                            None, None)

        magnify, flag4 = self.check_int(self.resolution_edit)
        output_dir, flag5 = self.check_path(self.browse_folder_edit)
        gifbase, flag6 = self.check_name(self.gif_edit)
        passed = all([flag0, flag1, flag2, flag3, flag4, flag5, flag6])
        return passed, (icase, scale, time, fps, animate_in_gui, magnify,
                        output_dir, gifbase)

    @staticmethod
    def check_name(cell):
        """verifies that the data is string-able"""
        cell_value = cell.text()
        try:
            text = str(cell_value).strip()
        except UnicodeEncodeError:
            cell.setStyleSheet("QLineEdit{background: red;}")
            return None, False

        if len(text):
            cell.setStyleSheet("QLineEdit{background: white;}")
            return text, True
        else:
            cell.setStyleSheet("QLineEdit{background: red;}")
            return None, False

    def check_path(self, cell):
        """verifies that the path exists"""
        text, passed = self.check_name(cell)
        if not passed:
            return None, False

        if os.path.exists(text):
            cell.setStyleSheet("QLineEdit{background: white;}")
            return text, True
        else:
            cell.setStyleSheet("QLineEdit{background: red;}")
            return None, False

    #def on_ok(self):
    #"""click the OK button"""
    #passed = self.on_apply()
    #if passed:
    #self.win_parent._animation_window_shown = False
    #self.close()
    ##self.destroy()

    def on_cancel(self):
        """click the Cancel button"""
        self.on_stop()
        self.out_data['close'] = True
        self.close()
Esempio n. 31
0
class FilteringModule(PreprocessorModule):
    DEFAULT_SETTINGS = {
        'is_enabled': True,
        'methods': [True, False, False],
        'recent_sw_files': [],
        'min_df': None,
        'max_df': None,
    }

    English, Custom, DocumentFrequency = 0, 1, 2
    filtering_values = {
        English: 'english',
        Custom: [],
        DocumentFrequency: (None, None),
    }
    filter_names = {
        English: 'English stop words',
        Custom: 'Custom stop words',
        DocumentFrequency: 'Filter by token frequency',
    }

    filtering_methods = [True, False, False]

    dlgFormats = 'Only text files (*.txt)'
    recent_sw_files = []

    def __init__(self, data):
        data = data or self.DEFAULT_SETTINGS
        PreprocessorModule.__init__(self, 'Token filtering', True,
                                    data.get('is_enabled'))

        self.group = QButtonGroup(self, exclusive=False)

        # --- English ---
        cb = QCheckBox(self, text=self.filter_names[self.English])
        self.add_to_content_area(cb)
        self.group.addButton(cb, self.English)

        # --- Custom ---
        cb = QCheckBox(self, text=self.filter_names[self.Custom])
        self.add_to_content_area(cb)
        self.group.addButton(cb, self.Custom)

        # File browser.
        file_browser_layout = QHBoxLayout()
        file_browser_layout.setContentsMargins(20, 0, 0, 0)
        self.sw_file_combo = QComboBox()
        self.sw_file_combo.setMinimumWidth(200)
        file_browser_layout.addWidget(self.sw_file_combo)
        self.sw_file_combo.activated[int].connect(self.select_file)

        self.browse_button = QPushButton(self)
        self.browse_button.clicked.connect(self.browse_file)
        self.browse_button.setIcon(self.style().standardIcon(
            QStyle.SP_DirOpenIcon))
        self.browse_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        file_browser_layout.addWidget(self.browse_button)

        # Reload button
        self.reload_button = QPushButton(self)
        self.reload_button.clicked.connect(self.on_reload_button_clicked)
        self.reload_button.setIcon(self.style().standardIcon(
            QStyle.SP_BrowserReload))
        self.reload_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        file_browser_layout.addWidget(self.reload_button)

        self.add_layout_to_content_area(file_browser_layout)

        # --- DF ---
        df_info_text = """
        Remove all tokens that appear in less than 'min-df' documents.
        Remove all tokens that appear in more than 'max-df' documents.
        Values can be either integers or floats (ratio of documents).
        """
        cb = QCheckBox(self, text=self.filter_names[self.DocumentFrequency])
        self.add_to_content_area(cb)
        self.group.addButton(cb, self.DocumentFrequency)
        df_info_text = QLabel(df_info_text)
        df_info_text.setContentsMargins(0, 0, 0, 0)
        df_info_text.setStyleSheet("""
        font-size: 11px;
        font-style: italic;
        """)
        self.add_to_content_area(df_info_text)
        # Min/Max-Df setter.
        df_setter_layout = QHBoxLayout()
        df_setter_layout.setContentsMargins(20, 0, 0, 0)
        self.min_df_input = QLineEdit()
        self.min_df_input.textChanged.connect(self.update_df_parameters)
        self.max_df_input = QLineEdit()
        self.max_df_input.textChanged.connect(self.update_df_parameters)
        df_setter_layout.addWidget(QLabel('Min-df:'))
        df_setter_layout.addWidget(self.min_df_input)
        df_setter_layout.addWidget(QLabel('Max-df:'))
        df_setter_layout.addWidget(self.max_df_input)

        self.add_layout_to_content_area(df_setter_layout)
        self.group.buttonClicked.connect(self.group_button_clicked)

        # Restore the widget to its previous state.
        self.restore_data(data)

    def str_to_num(self, s):
        if not s:
            return None

        try:
            return int(s)
        except ValueError:
            pass  # Not an int. Continue.
        try:
            return float(s)
        except ValueError:  # Not a float either.
            self.send_message(
                'Input "{}" cannot be cast into a number.'.format(s))
            return None

    def send_message(self, message):
        # Sends a message with the "message" signal, to the main widget.
        self.error_signal.emit(message)

    # --- File selection.
    def select_file(self, n):
        if n < len(self.recent_sw_files):
            name = self.recent_sw_files[n]
            del self.recent_sw_files[n]
            self.recent_sw_files.insert(0, name)

        if len(self.recent_sw_files) > 0:
            self.set_file_list()
            self.open_file(self.recent_sw_files[0])

    def set_file_list(self):
        self.sw_file_combo.clear()
        if not self.recent_sw_files:
            self.sw_file_combo.addItem('(none)')
        else:
            for file in self.recent_sw_files:
                self.sw_file_combo.addItem(os.path.split(file)[1])

    def browse_file(self):
        # Opens the file browser, starting at the home directory.
        start_file = os.path.expanduser('~/')
        # Get the file path from the browser window.
        path = QFileDialog.getOpenFileName(self, 'Open a stop words source',
                                           start_file, self.dlgFormats)
        if not path:
            return

        if path in self.recent_sw_files:
            self.recent_sw_files.remove(path)
        self.recent_sw_files.insert(0, path)
        self.set_file_list()
        self.open_file(path)

    def update_df_parameters(self):
        min_df = None if not self.min_df_input.text(
        ) else self.min_df_input.text()
        max_df = None if not self.max_df_input.text(
        ) else self.max_df_input.text()
        self.filtering_values[self.DocumentFrequency] = (min_df, max_df)
        self.notify_on_change()

    def open_file(self, path):
        try:
            with open(path) as f:  # Read most recent.
                self.filtering_values[self.Custom] = [
                    sw.strip() for sw in f.read().splitlines()
                ]
                self.notify_on_change()
        except Exception:  # Raise an exception otherwise.
            self.send_message('Could not open "{}".'.format(path))

    def on_reload_button_clicked(self):
        if self.recent_sw_files:
            self.select_file(0)

    # END File selection.

    def group_button_clicked(self):
        self.filtering_methods = [
            ch_box.isChecked() for ch_box in self.group.buttons()
        ]

        self.enable_choice_settings()

        # Emit the signal.
        self.notify_on_change()

    def enable_choice_settings(self):
        self.sw_file_combo.setEnabled(self.filtering_methods[1])
        self.browse_button.setEnabled(self.filtering_methods[1])
        self.reload_button.setEnabled(self.filtering_methods[1])

        self.min_df_input.setEnabled(self.filtering_methods[2])
        self.max_df_input.setEnabled(self.filtering_methods[2])

    def get_pp_setting(self):
        flag_english = self.filtering_methods[0]
        flag_custom = self.filtering_methods[1]
        flag_df = self.filtering_methods[2]
        if flag_english and flag_custom:  # Use custom.
            stop_words = {
                'stop_words':
                stopwords.words('english') + self.filtering_values[self.Custom]
            }
        elif flag_english and not flag_custom:
            stop_words = {'stop_words': 'english'}
        elif flag_custom:
            stop_words = {'stop_words': self.filtering_values[self.Custom]}
        else:
            stop_words = {}

        if flag_df:
            stop_words.update({
                'min_df':
                self.str_to_num(self.min_df_input.text()),
                'max_df':
                self.str_to_num(self.max_df_input.text()),
            })
        return stop_words

    def restore_data(self, data):
        self.recent_sw_files = data.get('recent_sw_files')
        self.min_df_input.setText(data.get('min_df'))
        self.max_df_input.setText(data.get('max_df'))
        self.filtering_methods = data.get('methods')

        for flag, ch_box in zip(self.filtering_methods, self.group.buttons()):
            ch_box.setChecked(flag)

        self.enable_choice_settings()  # Enable the settings if set.
        self.set_file_list()  # Fill the combo box with the recent sw files.
        self.select_file(0)  # Select the first file.

    def export_data(self):
        return {
            'is_enabled': self.enabled,
            'methods': self.filtering_methods,
            'recent_sw_files': self.recent_sw_files,
            'min_df': self.min_df_input.text(),
            'max_df': self.max_df_input.text(),
        }
Esempio n. 32
0
class Ui_option(object):

    def createLine(self):
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)
        return line

    def createSquareLabel(self):
        label = QLabel()
        label.setEnabled(False)
        label.setFixedSize(24, 24)
        label.setFrameShape(QFrame.StyledPanel)
        return label

    def addVerticalStretch(self, page_layout):
        vert_spacer = QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Expanding)
        page_layout.addItem(vert_spacer, page_layout.rowCount(), 0, 1, page_layout.columnCount())

    def createConnSection(self, page_layout, label, combobox, num_column):
        conn_layout = QHBoxLayout()
        conn_layout.setSpacing(5)
        conn_layout.setContentsMargins(0, 0, 0, 0)
        conn_layout.addWidget(label)
        conn_layout.addItem(QSpacerItem(40, 20, QSizePolicy.Fixed, QSizePolicy.Minimum))
        conn_layout.addWidget(combobox, 1)

        page_layout.addLayout(conn_layout, page_layout.rowCount(), 0, 1, num_column)
        page_layout.addWidget(self.createLine(), page_layout.rowCount(), 0, 1, num_column)

        vert_spacer = QSpacerItem(20, 20, QSizePolicy.Fixed, QSizePolicy.Fixed)
        page_layout.addItem(vert_spacer, page_layout.rowCount(), 0, 1, num_column)

    def createConnPage(self):
        self.conn_page = QWidget()
        self.conn_page.setObjectName("conn_page")
        self.conn_page.setToolTip(QApplication.translate("option", 
            "<b>Add/Modify/Delete a connection for a MUD server.</b>"
            "<p>Set the IP or hostname and the port of the MUD server.<br/>"
            "You have to define a connection to use all the functionality "
            "related (accounts, aliases, macros and triggers).</p>"))

        page_layout = QGridLayout(self.conn_page)
        page_layout.setSpacing(7)
        page_layout.setContentsMargins(10, 20, 0, 10)
        page_layout.setColumnMinimumWidth(0, 100)

        self.label_conn = QLabel()
        self.label_conn.setText(QApplication.translate("option", "Connection"))
        page_layout.addWidget(self.label_conn, 0, 0)

        self.list_conn = QComboBox()
        self.list_conn.addItem(QApplication.translate("option", "Create New"))
        page_layout.addWidget(self.list_conn, 0, 1, 1, 2)

        self.label_name_conn = QLabel()
        self.label_name_conn.setText(QApplication.translate("option", "Name"))
        page_layout.addWidget(self.label_name_conn, 1, 0)

        self.name_conn = QLineEdit()
        page_layout.addWidget(self.name_conn, 1, 1, 1, 2)

        self.label_host_conn = QLabel()
        self.label_host_conn.setText(QApplication.translate("option", "Host"))
        page_layout.addWidget(self.label_host_conn, 2, 0)

        self.host_conn = QLineEdit()
        page_layout.addWidget(self.host_conn, 2, 1, 1, 2)

        self.label_port_conn = QLabel()
        self.label_port_conn.setText(QApplication.translate("option", "Port"))
        page_layout.addWidget(self.label_port_conn, 3, 0)

        page_layout.addItem(QSpacerItem(80, 20), 3, 1) # horizontal spacer

        self.port_conn = QLineEdit()
        self.port_conn.setMaxLength(8)
        page_layout.addWidget(self.port_conn, 3, 2)

        vert_spacer = QSpacerItem(271,20,QSizePolicy.Minimum,QSizePolicy.Fixed)
        page_layout.addItem(vert_spacer, 4, 0, 1, 3)

        buttons_box = QHBoxLayout()
        buttons_box.setSpacing(5)
        buttons_box.setContentsMargins(0, 0, 0, 0)

        self.save_conn = QPushButton()
        self.save_conn.setFixedHeight(28)
        self.save_conn.setIcon(QIcon(":/images/button-save.png"))
        self.save_conn.setText(QApplication.translate("option", "Save"))
        buttons_box.addWidget(self.save_conn)

        self.delete_conn = QPushButton()
        self.delete_conn.setFixedHeight(28)
        self.delete_conn.setIcon(QIcon(":/images/button-cancel.png"))
        self.delete_conn.setText(QApplication.translate("option", "Delete"))
        buttons_box.addWidget(self.delete_conn)

        page_layout.addLayout(buttons_box, 5, 0, 1, 3, Qt.AlignRight)
        self.addVerticalStretch(page_layout)
        return self.conn_page

    def createAccountPage(self):
        self.account_page = QWidget()
        self.account_page.setObjectName("account_page")
        self.account_page.setToolTip(QApplication.translate("option", 
            "<b>Manage the accounts.</b>"
            "<p>Set the Save account flag to activate/disactivate the automatic "
            "saving of the accounts during the connection phase.<br/>After that "
            "the account has been created, you can use it for auto-login by "
            "simply selecting the account in the main window.<br/>You can "
            "also erase an already saved account, or define a custom prompt "
            "(see the relative help box).</p>"))

        page_layout = QGridLayout(self.account_page)
        page_layout.setSpacing(10)
        page_layout.setContentsMargins(10, 20, 0, 10)
        page_layout.setColumnMinimumWidth(0, 130)

        self.save_account = QCheckBox()
        self.save_account.setText(QApplication.translate("option", "Save accounts"))
        page_layout.addWidget(self.save_account, 0, 0)

        self.label_conn_account = QLabel()
        self.label_conn_account.setText(QApplication.translate("option", "Connection"))

        self.list_conn_account = QComboBox()
        self.createConnSection(page_layout, self.label_conn_account, self.list_conn_account, 2)

        self.label_account_account = QLabel()
        self.label_account_account.setText(QApplication.translate("option", "Account"))
        page_layout.addWidget(self.label_account_account, 4, 0)

        self.list_account = QComboBox()
        page_layout.addWidget(self.list_account, 4, 1)

        buttons_box = QHBoxLayout()
        buttons_box.setSpacing(5)

        self.change_prompt = QPushButton()
        self.change_prompt.setEnabled(False)
        self.change_prompt.setFixedHeight(28)
        self.change_prompt.setIcon(QIcon(":/images/prompt.png"))
        self.change_prompt.setText(QApplication.translate("option", "Change Prompt"))
        buttons_box.addWidget(self.change_prompt)

        self.delete_account = QPushButton()
        self.delete_account.setEnabled(False)
        self.delete_account.setFixedHeight(28)
        self.delete_account.setIcon(QIcon(":/images/button-cancel.png"))
        self.delete_account.setText(QApplication.translate("option", "Delete"))
        buttons_box.addWidget(self.delete_account)
        page_layout.addLayout(buttons_box, 5, 0, 1, 2, Qt.AlignRight)

        self.box_prompt = QGroupBox()
        self.box_prompt.setTitle(QApplication.translate("option", "Prompt"))
        self.box_prompt.setToolTip(QApplication.translate("option", "<table>"
        "<tr><td colspan=3><b>Prompt format:</b></td></tr>"
        "<tr><td>%h</td><td>-></td><td>Current hit points</td></tr>"
        "<tr><td>%H</td><td>-></td><td>Maximum hit points</td></tr>"
        "<tr><td>%m</td><td>-></td><td>Current mana</td></tr>"
        "<tr><td>%M</td><td>-></td><td>Maximum mana</td></tr>"
        "<tr><td>%v</td><td>-></td><td>Current moves</td></tr>"
        "<tr><td>%V</td><td>-></td><td>Maximum moves</td></tr>"
        "<tr><td>*<td>-></td><td>Represent any char, repeated</td></tr>"
        "<tr><td colspan=2>&nbsp;</td><td>zero or more times</td></tr>"
        "<tr><td colspan=3>&nbsp;</td></tr>"
        "</table>"
        "<table>"
        "<tr><td><b>Example:</b></td></tr>"
        "<tr><td>[  %h/%Hhp %m/%Mmn %v/%Vmv *] ></td></tr>"
        "<tr><td>is a valid representation for:</td></tr>"
        "<tr><td>[  111/111hp 100/100mn 500/500mv 1000tnl] ></td></tr>"
        "</table>"))

        prompt_layout = QGridLayout(self.box_prompt)
        prompt_layout.setSpacing(5)
        prompt_layout.setContentsMargins(5, 5, 5, 5)

        label_normal = QLabel()
        label_normal.setText(QApplication.translate("option", "Normal"))
        prompt_layout.addWidget(label_normal, 0, 0)

        self.normal_prompt = QLineEdit()
        prompt_layout.addWidget(self.normal_prompt, 0, 1)

        label_fight = QLabel()
        label_fight.setText(QApplication.translate("option", "Fight"))
        prompt_layout.addWidget(label_fight, 1, 0)

        self.fight_prompt = QLineEdit()
        prompt_layout.addWidget(self.fight_prompt, 1, 1)

        self.save_prompt = QPushButton()
        self.save_prompt.setFixedHeight(28)
        self.save_prompt.setIcon(QIcon(":/images/button-save.png"))
        self.save_prompt.setText(QApplication.translate("option", "Save"))
        prompt_layout.addWidget(self.save_prompt, 2, 0, 1, 2, Qt.AlignRight)
        page_layout.addWidget(self.box_prompt, 6, 0, 1, 2)

        self.addVerticalStretch(page_layout)
        return self.account_page

    def createAliasPage(self):
        self.alias_page = QWidget()
        self.alias_page.setObjectName("alias_page")
        self.alias_page.setToolTip(QApplication.translate("option", 
            "<b>Add/Modify/Delete an alias.</b>"
            "<p>An alias is a textual shortcut that you can use to increase "
            "the typing speed. <br/>Thus, when you enter the text of the "
            "label you actually send to the server the text of the body.</p>"))

        page_layout = QGridLayout(self.alias_page)
        page_layout.setSpacing(7)
        page_layout.setContentsMargins(10, 20, 0, 10)
        page_layout.setColumnMinimumWidth(0, 80)

        self.label_conn_alias = QLabel()
        self.label_conn_alias.setText(QApplication.translate("option", "Connection"))
        self.list_conn_alias = QComboBox()
        self.createConnSection(page_layout, self.label_conn_alias, self.list_conn_alias, 3)

        self.label_alias_alias = QLabel()
        self.label_alias_alias.setText(QApplication.translate("option", "Alias"))
        page_layout.addWidget(self.label_alias_alias, 3, 0)

        page_layout.addItem(QSpacerItem(80, 20, QSizePolicy.Fixed, QSizePolicy.Minimum), 3, 1)

        self.list_alias = QComboBox()
        self.list_alias.setEnabled(False)
        page_layout.addWidget(self.list_alias, 3, 2)

        self.label_label_alias = QLabel()
        self.label_label_alias.setText(QApplication.translate("option", "Label"))
        page_layout.addWidget(self.label_label_alias, 4, 0)

        page_layout.addItem(QSpacerItem(80, 20, QSizePolicy.Fixed, QSizePolicy.Minimum), 4, 1)

        self.label_alias = QLineEdit()
        self.label_alias.setEnabled(False)
        page_layout.addWidget(self.label_alias, 4, 2)

        self.label_body_alias = QLabel()
        self.label_body_alias.setText(QApplication.translate("option", "Body"))
        page_layout.addWidget(self.label_body_alias, 5, 0)

        self.body_alias = QLineEdit()
        self.body_alias.setEnabled(False)
        page_layout.addWidget(self.body_alias, 5, 1, 1, 2)

        vert_spacer = QSpacerItem(20, 20, QSizePolicy.Minimum, QSizePolicy.Fixed)
        page_layout.addItem(vert_spacer, 6, 0, 1, 3)

        buttons_layout = QHBoxLayout()
        buttons_layout.setSpacing(5)
        buttons_layout.setContentsMargins(0, 0, 0, 0)

        self.save_alias = QPushButton()
        self.save_alias.setFixedHeight(28)
        self.save_alias.setIcon(QIcon(":/images/button-save.png"))
        self.save_alias.setText(QApplication.translate("option", "Save"))
        buttons_layout.addWidget(self.save_alias)

        self.delete_alias = QPushButton()
        self.delete_alias.setFixedHeight(28)
        self.delete_alias.setIcon(QIcon(":/images/button-cancel.png"))
        self.delete_alias.setText(QApplication.translate("option", "Delete"))
        buttons_layout.addWidget(self.delete_alias)
        page_layout.addLayout(buttons_layout, 7, 0, 1, 3, Qt.AlignRight)

        self.addVerticalStretch(page_layout)
        return self.alias_page

    def createMacroPage(self):
        self.macro_page = QWidget()
        self.macro_page.setObjectName("macro_page")
        self.macro_page.setToolTip(QApplication.translate("option", 
            "<b>Add/Modify/Delete a macro.</b>"
            "<p>A macro is a key-based shortcut to send some text to the server."
            "<br/>You can define a key (or a combination of keys, likes CTRL+A) "
            "that if pressed during the game fires the macro, which sends the "
            "command to the server.</p><p><b>NOTE:</b> You cannot use for a "
            "macro a key already used for a standard shortcut.</p>"))

        page_layout = QGridLayout(self.macro_page)
        page_layout.setSpacing(7)
        page_layout.setContentsMargins(10, 20, 0, 10)
        page_layout.setColumnMinimumWidth(0, 80)

        self.label_conn_macro = QLabel()

        self.list_conn_macro = QComboBox()
        self.createConnSection(page_layout, self.label_conn_macro, self.list_conn_macro, 3)

        self.label_macro_macro = QLabel()
        page_layout.addWidget(self.label_macro_macro, 3, 0)

        horiz_spacer = QSpacerItem(20, 20, QSizePolicy.Fixed,QSizePolicy.Minimum)
        page_layout.addItem(horiz_spacer, 3, 1)

        self.list_macro = QComboBox()
        self.list_macro.setEnabled(False)
        page_layout.addWidget(self.list_macro, 3, 2)

        self.label_keys_macro = QLabel()
        page_layout.addWidget(self.label_keys_macro, 4, 0)

        self.register_macro = QPushButton()
        self.register_macro.setEnabled(False)
        self.register_macro.setFixedHeight(28)
        page_layout.addWidget(self.register_macro, 4, 1)

        self.keys_macro = QLineEdit()
        self.keys_macro.setEnabled(False)
        self.keys_macro.setProperty("highlight_color",QVariant("#C8C8C8"))
        page_layout.addWidget(self.keys_macro, 4, 2)

        self.label_command_macro = QLabel()
        page_layout.addWidget(self.label_command_macro, 5, 0)

        self.command_macro = QLineEdit()
        self.command_macro.setEnabled(False)
        page_layout.addWidget(self.command_macro, 5, 1, 1, 2)

        vert_spacer = QSpacerItem(20, 20, QSizePolicy.Minimum, QSizePolicy.Fixed)
        page_layout.addItem(vert_spacer, 6, 0, 1, 3)

        buttons_layout = QHBoxLayout()
        buttons_layout.setSpacing(5)
        buttons_layout.setContentsMargins(0, 0, 0, 0)

        self.save_macro = QPushButton()
        self.save_macro.setFixedHeight(28)
        self.save_macro.setIcon(QIcon(":/images/button-save.png"))
        buttons_layout.addWidget(self.save_macro)

        self.delete_macro = QPushButton()
        self.delete_macro.setFixedHeight(28)
        self.delete_macro.setIcon(QIcon(":/images/button-cancel.png"))
        buttons_layout.addWidget(self.delete_macro)
        page_layout.addLayout(buttons_layout, 7, 0, 1, 3, Qt.AlignRight)
        self.addVerticalStretch(page_layout)

        self.label_conn_macro.setText(QApplication.translate("option", "Connection"))
        self.label_macro_macro.setText(QApplication.translate("option", "Macro"))
        self.label_keys_macro.setText(QApplication.translate("option", "Keys"))
        self.label_command_macro.setText(QApplication.translate("option", "Command"))
        self.register_macro.setText(QApplication.translate("option", "Register"))
        self.save_macro.setText(QApplication.translate("option", "Save"))
        self.delete_macro.setText(QApplication.translate("option", "Delete"))
        return self.macro_page

    def createKeyPad(self):
        def createKey(text, size):
            layout = QVBoxLayout()
            layout.addStretch(1)
            label = QLabel(text)
            label.setAlignment(Qt.AlignHCenter)
            layout.addWidget(label)
            line_input = QLineEdit()
            if size != -1:
                line_input.setFixedWidth(size)
            self.keypad_fields[text] = line_input
            layout.addWidget(line_input)
            return layout

        keypad = QWidget()
        self.keypad_fields = {}
        layout = QGridLayout(keypad)
        layout.setHorizontalSpacing(30)
        layout.setVerticalSpacing(15)
        layout.setContentsMargins(5, 5, 5, 5)
        layout.addLayout(createKey('7', 60), 0, 0)
        layout.addLayout(createKey('8', 60), 0, 1)
        layout.addLayout(createKey('9', 60), 0, 2)

        layout.addLayout(createKey('4', 60), 1, 0)
        layout.addLayout(createKey('5', 60), 1, 1)
        layout.addLayout(createKey('6', 60), 1, 2)

        layout.addLayout(createKey('1', 60), 2, 0)
        layout.addLayout(createKey('2', 60), 2, 1)
        layout.addLayout(createKey('3', 60), 2, 2)

        layout.addLayout(createKey('0', -1), 3, 0, 1, 2)
        layout.addLayout(createKey('.', 60), 3, 2)
        return keypad

    def createKeypadPage(self):
        self.keypad_page = QWidget()
        self.keypad_page.setObjectName("keypad_page")
        self.keypad_page.setToolTip(QApplication.translate("option", 
            "<b>Connect the keypad keys with custom actions</b>"
            "<p>Enter the text in the spaces to connect the correspondent key "
            "in order to use as a shortcut to send the text to the server.</p>"))

        page_layout = QGridLayout(self.keypad_page)
        page_layout.setSpacing(7)
        page_layout.setContentsMargins(10, 20, 0, 10)
        page_layout.setColumnMinimumWidth(0, 80)

        self.label_conn_keypad = QLabel()
        self.list_conn_keypad = QComboBox()
        self.createConnSection(page_layout, self.label_conn_keypad, self.list_conn_keypad, 1)
        page_layout.addWidget(self.createKeyPad(), 3, 0, 1, 1, Qt.AlignRight)
        self.addVerticalStretch(page_layout)

        self.save_keypad = QPushButton()
        self.save_keypad.setFixedHeight(28)
        self.save_keypad.setIcon(QIcon(":/images/button-save.png"))
        self.save_keypad.setText(QApplication.translate("option", "Save"))
        page_layout.addWidget(self.save_keypad, 4, 0, 1, 1, Qt.AlignRight)
        self.label_conn_keypad.setText(QApplication.translate("option", "Connection"))
        return self.keypad_page

    def createTriggerPage(self):
        self.trigger_page = QWidget()
        self.trigger_page.setObjectName("trigger_page")
        self.trigger_page.setToolTip(QApplication.translate("option",
            "<b>Add/Modify/Delete a trigger.</b>"
            "<p>A trigger is an event that happen when some text came from "
            "server.<br/>After has been received a text that match with the "
            "pattern (see the relative help box), the trigger can send another "
            "text to the server or highlight the incoming one.</p>"))

        page_layout = QGridLayout(self.trigger_page)
        page_layout.setSpacing(7)
        page_layout.setContentsMargins(10, 20, 0, 10)
        page_layout.setColumnMinimumWidth(1, 140)

        self.label_conn_trigger = QLabel()

        self.list_conn_trigger = QComboBox()
        self.createConnSection(page_layout, self.label_conn_trigger, self.list_conn_trigger, 2)

        self.label_trigger = QLabel()
        page_layout.addWidget(self.label_trigger, 3, 0, 1, 1)

        self.list_trigger = QComboBox()
        page_layout.addWidget(self.list_trigger, 3, 1, 1, 1)

        tooltip_pattern_trigger = QApplication.translate("option", 
        "<table width=\"350\">"
        "<tr><td colspan=3><b>Pattern special characters:</b></td></tr>"
        "<tr><td>*</td><td>-></td><td width=\"250\">A sequence of any chars</td></tr>"
        "<tr><td>?</td><td>-></td><td width=\"250\">Any single character</td></tr>"
        "<tr><td>%w</td><td>-></td><td width=\"250\">A sequence of alphanumeric chars</td></tr>"
        "<tr><td>%d</td><td>-></td><td width=\"250\">A sequence of numeric characters</td></tr>"
        "<tr><td colspan=3>Every time that you use the special chars %w or %d "
        "you can also put the relative extracted text in the command using the "
        "sintax %number where number represents the positional order of the "
        "special char.</td></tr>"
        "</table><br/>"
        "<table width=\"350\">"
        "<tr><td colspan=2><b>Example:</b></td></tr>"
        "<tr><td>Pattern:</td><td width=\"250\">%w the ogre is fighting against %w</td></tr>"
        "<tr><td>Command:</td><td width=\"250\">kill %2</td></tr>"
        "<tr><td colspan=2>The trigger will fire when an ogre will fight "
        "against an unknown enemy, and as reaction you will fight with the "
        "ogre against his enemy.</td></tr>"
        "</table>")

        self.label_pattern_trigger = QLabel()
        self.label_pattern_trigger.setToolTip(tooltip_pattern_trigger)
        page_layout.addWidget(self.label_pattern_trigger, 4, 0, 1, 1)

        self.pattern_trigger = QLineEdit()
        self.pattern_trigger.setToolTip(tooltip_pattern_trigger)
        page_layout.addWidget(self.pattern_trigger, 4, 1, 1, 1)

        self.case_trigger = QCheckBox()
        page_layout.addWidget(self.case_trigger, 5, 0, 1, 2, Qt.AlignLeft)

        self.label_command_trigger = QLabel()
        self.label_command_trigger.setText(QApplication.translate("option", "Command"))
        page_layout.addWidget(self.label_command_trigger, 6, 0)

        self.command_trigger = QLineEdit()
        page_layout.addWidget(self.command_trigger, 6, 1)

        self.label_color_trigger = QLabel()
        self.label_color_trigger.setText(QApplication.translate("option", "Change color to"))
        page_layout.addWidget(self.label_color_trigger, 7, 0)

        horiz_spacer = QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        page_layout.addItem(horiz_spacer, 7, 1)

        colors_layout = QHBoxLayout()
        colors_layout.setSpacing(3)

        self.text_color_trigger_button = QPushButton()
        self.text_color_trigger_button.setFixedHeight(28)
        self.text_color_trigger_button.setIcon(QIcon(":/images/button-color.png"))
        colors_layout.addWidget(self.text_color_trigger_button)

        self.text_color_trigger = self.createSquareLabel()
        colors_layout.addWidget(self.text_color_trigger)

        colors_spacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        colors_layout.addItem(colors_spacer)

        self.bg_color_trigger_button = QPushButton()
        self.bg_color_trigger_button.setFixedHeight(28)
        self.bg_color_trigger_button.setIcon(QIcon(":/images/button-color.png"))
        colors_layout.addWidget(self.bg_color_trigger_button)

        self.bg_color_trigger = self.createSquareLabel()
        colors_layout.addWidget(self.bg_color_trigger)
        page_layout.addLayout(colors_layout, 8, 0, 1, 2)

        horiz_spacer2 = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        page_layout.addItem(horiz_spacer2, 9, 0, 1, 2)

        buttons_layout = QHBoxLayout()
        buttons_layout.setSpacing(5)

        self.save_trigger = QPushButton()
        self.save_trigger.setFixedHeight(28)
        self.save_trigger.setIcon(QIcon(":/images/button-save.png"))
        buttons_layout.addWidget(self.save_trigger)

        self.delete_trigger = QPushButton()
        self.delete_trigger.setFixedHeight(28)
        self.delete_trigger.setIcon(QIcon(":/images/button-cancel.png"))
        buttons_layout.addWidget(self.delete_trigger)
        page_layout.addLayout(buttons_layout, 10, 0, 1, 2, Qt.AlignRight)

        self.label_conn_trigger.setText(QApplication.translate("option", "Connection"))
        self.label_trigger.setText(QApplication.translate("option", "Trigger"))
        self.label_pattern_trigger.setText(QApplication.translate("option", "Pattern"))
        self.case_trigger.setText(QApplication.translate("option", "Ignore case"))

        self.text_color_trigger_button.setText(QApplication.translate("option", "Text"))
        self.text_color_trigger.setProperty("label_color", QVariant(True))
        self.bg_color_trigger_button.setText(QApplication.translate("option", "Background"))
        self.bg_color_trigger.setProperty("label_color", QVariant(True))
        self.save_trigger.setText(QApplication.translate("option", "Save"))
        self.delete_trigger.setText(QApplication.translate("option", "Delete"))
        return self.trigger_page

    def createPrefPage(self):
        self.pref_page = QWidget()
        self.pref_page.setObjectName("pref_page")

        page_layout = QVBoxLayout(self.pref_page)
        page_layout.setSpacing(7)
        page_layout.setContentsMargins(10, 20, 0, 10)

        textBox = QGroupBox()
        textBox.setTitle(QApplication.translate("option", "Text inserted"))
        text_layout = QGridLayout(textBox)
        text_layout.setSpacing(7)
        text_layout.setContentsMargins(10, 10, 10, 10)

        self.echo_color_button = QPushButton()
        self.echo_color_button.setFixedHeight(28)
        self.echo_color_button.setIcon(QIcon(":/images/button-color.png"))
        self.echo_color_button.setText(QApplication.translate("option", "Echo Color"))
        text_layout.addWidget(self.echo_color_button, 0, 0)

        self.echo_color = self.createSquareLabel()
        self.echo_color.setProperty('label_color', QVariant(True))
        text_layout.addWidget(self.echo_color, 0, 3)

        horiz_spacer = QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        text_layout.addItem(horiz_spacer, 0, 4)

        self.label_cmd_separator = QLabel()
        self.label_cmd_separator.setText(QApplication.translate("option", "Command separator"))
        text_layout.addWidget(self.label_cmd_separator, 1, 0, 1, 2)

        self.cmd_separator = QLineEdit()
        self.cmd_separator.setFixedSize(24, 24)

        font = QtGui.QFont()
        font.setWeight(75)
        font.setBold(True)
        self.cmd_separator.setFont(font)
        self.cmd_separator.setMaxLength(1)
        self.cmd_separator.setAlignment(Qt.AlignCenter)
        text_layout.addWidget(self.cmd_separator, 1, 3)

        horiz_spacer2 = QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        text_layout.addItem(horiz_spacer2, 1, 4)

        self.keep_text = QCheckBox()
        self.keep_text.setText(QApplication.translate("option", "Keep text entered"))
        text_layout.addWidget(self.keep_text, 2, 0, 1, 4, Qt.AlignLeft)
        page_layout.addWidget(textBox)

        generalBox = QGroupBox()
        generalBox.setTitle(QApplication.translate("option", "General"))
        general_layout = QVBoxLayout(generalBox)
        general_layout.setSpacing(7)
        general_layout.setContentsMargins(10, 10, 10, 10)

        self.save_log = QCheckBox()
        self.save_log.setText(QApplication.translate("option", "Save log"))
        general_layout.addWidget(self.save_log, 0, Qt.AlignLeft)

        horiz_spacer = QSpacerItem(20, 20, QSizePolicy.Fixed, QSizePolicy.Minimum)
        general_layout.addItem(horiz_spacer)
        page_layout.addWidget(generalBox)

        horiz_spacer2 = QSpacerItem(20, 20, QSizePolicy.Fixed, QSizePolicy.Minimum)
        page_layout.addItem(horiz_spacer2)

        self.save_preferences = QPushButton()
        self.save_preferences.setFixedHeight(28)
        self.save_preferences.setIcon(QIcon(":/images/button-save.png"))
        self.save_preferences.setText(QApplication.translate("option", "Save"))
        page_layout.addWidget(self.save_preferences, 0, Qt.AlignRight)
        return self.pref_page

    def populatePages(self):
        self.page_container.addWidget(self.createConnPage())
        self.page_container.addWidget(self.createAccountPage())
        self.page_container.addWidget(self.createAliasPage())
        self.page_container.addWidget(self.createMacroPage())
        self.page_container.addWidget(self.createKeypadPage())
        self.page_container.addWidget(self.createTriggerPage())
        self.page_container.addWidget(self.createPrefPage())

    def createListOption(self):
        def addItem(label, icon_pixmap, width, height):
            item = QListWidgetItem(list_option)
            item.setText(label)
            item.setTextAlignment(Qt.AlignHCenter)
            item.setIcon(QIcon(icon_pixmap))
            item.setSizeHint(QSize(width, height))

        list_option = QListWidget()
        list_option.setAutoFillBackground(True)
        list_option.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        list_option.setTextElideMode(Qt.ElideNone)
        list_option.setMovement(QListView.Static)
        list_option.setFlow(QListView.TopToBottom)
        list_option.setProperty("isWrapping", QVariant(False))
        list_option.setSpacing(3)
        list_option.setViewMode(QListView.IconMode)

        items = []
        items.append((QApplication.translate("option", "Connections"), "connections.png"))
        items.append((QApplication.translate("option", "Accounts"), "accounts.png"))
        items.append((QApplication.translate("option", "Aliases"), "aliases.png"))
        items.append((QApplication.translate("option", "Macros"), "macros.png"))
        items.append((QApplication.translate("option", "Keypad"), "keypad.png"))
        items.append((QApplication.translate("option", "Triggers"), "triggers.png"))
        items.append((QApplication.translate("option", "Preferences"), "preferences.png"))

        max_width = 0
        for label, icon_name in items:
            w = list_option.fontMetrics().boundingRect(label).width()
            if w > max_width:
                max_width = w

        # An empiric method to align element in the center of the QListWidget
        max_width += 15
        total_height = 0

        for label, icon_name in items:
            icon_pixmap = QPixmap(":/images/" + icon_name)
            height = icon_pixmap.height() + list_option.fontMetrics().height() + 3
            total_height += height + 5
            addItem(label, icon_pixmap, max_width, height)

        list_option.setUniformItemSizes(True)
        list_option.setFixedWidth(max_width + 10)
        list_option.setMinimumHeight(total_height)
        return list_option

    def setupUi(self, option):
        option.setWindowTitle(QApplication.translate("option", "Option"))
        main_layout = QGridLayout(option)
        main_layout.setSpacing(5)
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setColumnStretch(1, 1)

        self.list_option = self.createListOption()
        main_layout.addWidget(self.list_option, 0, 0)

        self.page_container = QStackedLayout()
        self.page_container.setContentsMargins(0, 0, 0, 0)
        main_layout.addLayout(self.page_container, 0, 1)
        self.populatePages()

        main_layout.addWidget(self.createLine(), 1, 0, 1, 2)
        close_layout = QHBoxLayout()
        close_layout.setContentsMargins(0, 0, 5, 0)
        close_layout.setSpacing(5)

        close_option = QPushButton()
        close_option.setText(QApplication.translate("option", "Close"))
        option.connect(close_option, QtCore.SIGNAL("clicked()"), option.accept)
        close_layout.addWidget(close_option)
        main_layout.addLayout(close_layout, 2, 1, 1, 2, Qt.AlignRight)

        self.list_option.setCurrentRow(0)
        self.page_container.setCurrentIndex(0)

        option.setTabOrder(self.list_option, self.list_conn)
        option.setTabOrder(self.list_conn, self.name_conn)
        option.setTabOrder(self.name_conn, self.host_conn)
        option.setTabOrder(self.host_conn, self.port_conn)
        option.setTabOrder(self.port_conn, self.save_conn)
        option.setTabOrder(self.save_conn, self.delete_conn)
        option.setTabOrder(self.delete_conn, self.list_conn_account)
        option.setTabOrder(self.list_conn_account, self.list_account)
        option.setTabOrder(self.list_account, self.delete_account)
        option.setTabOrder(self.delete_account, self.list_conn_alias)
        option.setTabOrder(self.list_conn_alias, self.list_alias)
        option.setTabOrder(self.list_alias, self.label_alias)
        option.setTabOrder(self.label_alias, self.body_alias)
        option.setTabOrder(self.body_alias, self.save_alias)
        option.setTabOrder(self.save_alias, self.delete_alias)
        option.setTabOrder(self.delete_alias, self.list_conn_macro)
        option.setTabOrder(self.list_conn_macro, self.list_macro)
        option.setTabOrder(self.list_macro, self.register_macro)
        option.setTabOrder(self.register_macro, self.keys_macro)
        option.setTabOrder(self.keys_macro, self.command_macro)
        option.setTabOrder(self.command_macro, self.save_macro)
        option.setTabOrder(self.save_macro, self.delete_macro)
        option.setTabOrder(self.delete_macro, self.echo_color_button)
        option.setTabOrder(self.echo_color_button, self.save_log)
Esempio n. 33
0
class DbConnOptions(QWidget):
    def __init__(self, parent, conn_properties):        
        super(DbConnOptions, self).__init__(parent)
        
        self.plugin_manager = get_plugin_manager()
        self.available_types = {}
        self.conn_properties = None
        
        for dbplugin in self.plugin_manager.getPluginsOfCategory("db"):
            self.available_types[dbplugin.name] = dbplugin.plugin_object
                
        lay = QGridLayout(self)
        
        if len(self.available_types) == 0:
            lay.addWidget(QLabel("No DB plugin activated", parent), 0, 0, Qt.AlignRight)
            return
            
        lay.addWidget(QLabel("Name: ", parent), 0, 0, Qt.AlignRight)        
        self.nameCombo = QComboBox(parent)
        lay.addWidget(self.nameCombo, 0, 1)
        lay.addWidget(QLabel("Type: ", parent), 1, 0, Qt.AlignRight)
        self.typeCombo = QComboBox(parent)
        lay.addWidget(self.typeCombo, 1, 1)
        self.conn_details = QStackedWidget(parent)
        lay.addWidget(self.conn_details, 2, 0, 1, 2)        
        newConnButton = QPushButton("New Connection", parent)
        lay.addWidget(newConnButton, 3, 1)
        self.warningLbl = QLabel("The standard connection is used by the lunchinator internally to store messages etc." + \
                             " It can be used by plugins as well, but it cannot be changed.")
        self.warningLbl.setWordWrap(True)
        lay.addWidget(self.warningLbl, 4, 0, 4, 2)
        
        for p in self.available_types.values():
            w = p.create_db_options_widget(parent)
            if w == None:
                w = QLabel("Plugin not activated", parent)
            self.conn_details.addWidget(w)   
            
        self.typeCombo.addItems(self.available_types.keys())
        
        self.reset_connection_properties(conn_properties)  
        newConnButton.clicked.connect(self.new_conn)      
        
    def reset_connection_properties(self, conn_properties):
        try:
            self.nameCombo.currentIndexChanged.disconnect(self.name_changed)
            self.typeCombo.currentIndexChanged.disconnect(self.type_changed)
        except:
            pass
        
        self.conn_properties = deepcopy(conn_properties)
        self.nameCombo.clear()
        self.nameCombo.addItems(self.conn_properties.keys())
            
        type_name = self.conn_properties[str(self.nameCombo.currentText())]["plugin_type"]
        type_index = self.typeCombo.findText(type_name)
        self.typeCombo.setCurrentIndex(type_index)  
        self.conn_details.setCurrentIndex(type_index)
        
        self.fill_conn_details()       
        
        self.typeCombo.currentIndexChanged.connect(self.type_changed)
        self.nameCombo.currentIndexChanged.connect(self.name_changed)
    
    def store_conn_details(self):
        p = self.available_types[self.last_type]
        o = p.get_options_from_widget()
        if o:
            self.conn_properties[self.last_name].update(o)
            self.conn_properties[self.last_name]["plugin_type"] = self.last_type
        
    def fill_conn_details(self):        
        self.last_type = str(self.typeCombo.currentText())
        self.last_name = str(self.nameCombo.currentText())
        
        p = self.available_types[self.last_type]
        p.fill_options_widget(self.conn_properties[self.last_name])
            
        if self.nameCombo.currentText()=="Standard":
            self.typeCombo.setEnabled(False)
            self.conn_details.setEnabled(False)
            self.warningLbl.setVisible(True)
        else:
            self.typeCombo.setEnabled(True)
            self.conn_details.setEnabled(True)
            self.warningLbl.setVisible(False)
        
    @loggingSlot(int)
    def type_changed(self, index):
        self.conn_details.setCurrentIndex(index)
        self.store_conn_details()
        self.fill_conn_details()
        
    @loggingSlot(int)
    def name_changed(self, _index):
        type_name = self.conn_properties[str(self.nameCombo.currentText())]["plugin_type"]
        type_index = self.typeCombo.findText(type_name)
        if type_index == self.typeCombo.currentIndex():
            self.store_conn_details()
            self.fill_conn_details()
        else:
            self.typeCombo.setCurrentIndex(type_index)
            
    @loggingSlot()
    def new_conn(self):
        i = len(self.conn_properties)
        while u"Conn %d" % i in self.conn_properties:
            i += 1
        proposedName = u"Conn %d" % i
        
        new_conn_name = None
        while not new_conn_name or new_conn_name in self.conn_properties:
            if new_conn_name in self.conn_properties:
                msg = u"Connection \"%s\" already exists. Enter a different name:" % new_conn_name
            else:
                msg = u"Enter the name of the new connection:"
            new_conn_name, ok = QInputDialog.getText(self,
                                                     u"Connection Name",
                                                     msg,
                                                     QLineEdit.Normal,
                                                     proposedName)
            if not ok:
                return 
            new_conn_name = convert_string(new_conn_name)
        
        self.conn_properties[new_conn_name] = {"plugin_type" : str(self.typeCombo.currentText()) }
        self.nameCombo.addItem(new_conn_name)
        self.nameCombo.setCurrentIndex(self.nameCombo.count() - 1)
        
    def get_connection_properties(self):
        self.store_conn_details()
        return self.conn_properties
Esempio n. 34
0
class options(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self)
        self.init(parent)
        self.initShape()

    def init(self, parent):
        self.heditor = parent

    def initShape(self):
        self.vbox = QVBoxLayout()
        self.optab = QTabWidget()

        self.fill = QWidget()

        self.createHexOptions()
        #        self.createPageOptions()
        self.createPixelOptions()
        self.vbox.addWidget(self.optab)

        self.createButtons()
        self.vbox.addWidget(self.fill)

        self.setLayout(self.vbox)

    def createPageOptions(self):
        self.pagegrid = QGridLayout()
        self.pagegroup = QWidget()

        pagelabel = QLabel("Page size : ")
        self.sizeEdit = QFFSpinBox(self)
        self.sizeEdit.setMaximum(self.heditor.filesize)
        self.sizeEdit.setValue(self.heditor.pageSize)
        #        psize = QString("%.2d" % self.heditor.pageSize)
        #        self.sizeEdit.insert(psize)

        headerlabel = QLabel("Header size : ")
        self.headEdit = QFFSpinBox(self)
        self.headEdit.setMaximum(self.heditor.filesize)
        self.headEdit.setValue(self.heditor.pageHead)
        #        phead = QString("%.2d" % self.heditor.pageHead)
        #        self.headEdit.insert(phead)

        sparelabel = QLabel("Spare size : ")
        self.spareEdit = QFFSpinBox(self)
        self.spareEdit.setMaximum(self.heditor.filesize)
        self.spareEdit.setValue(self.heditor.pageSpare)
        #        pspare = QString("%.2d" % self.heditor.pageSpare)
        #        self.spareEdit.insert(pspare)

        ppb = QLabel("Pages per block:")
        self.pagesperblock = QComboBox()
        self.pagesperblock.addItem("8")
        self.pagesperblock.addItem("16")
        self.pagesperblock.addItem("32")
        self.pagesperblock.addItem("64")
        self.pagesperblock.addItem("128")
        self.pagesperblock.addItem("256")
        self.pagesperblock.addItem("512")
        self.pagesperblock.setCurrentIndex(2)

        lview = QLabel("Left indication: ")
        self.indic = QComboBox()
        self.indic.addItem("Offset")
        self.indic.addItem("Block")

        #        self.pagesperlineEdit = QLineEdit()
        #        ppl = QString("%.2d" % self.heditor.pagesPerBlock)
        #        self.pagesperlineEdit.insert(ppl)

        self.pagegrid.addWidget(pagelabel, 0, 0)
        self.pagegrid.addWidget(self.sizeEdit, 0, 1)

        self.pagegrid.addWidget(headerlabel, 1, 0)
        self.pagegrid.addWidget(self.headEdit, 1, 1)

        self.pagegrid.addWidget(sparelabel, 2, 0)
        self.pagegrid.addWidget(self.spareEdit, 2, 1)

        self.pagegrid.addWidget(ppb, 3, 0)
        self.pagegrid.addWidget(self.pagesperblock, 3, 1)

        self.pagegrid.addWidget(lview, 4, 0)
        self.pagegrid.addWidget(self.indic, 4, 1)

        self.pagegrid.addWidget(self.fill, 5, 0)
        self.pagegrid.setRowStretch(5, 1)
        #        self.pagegrid.addWidget(self.fill, 6, 0)

        #        self.pagegrid.addWidget(pagesperline, 6, 0)
        #        self.pagegrid.addWidget(self.pagesperlineEdit, 7, 0)

        self.pagegroup.setLayout(self.pagegrid)
        self.vvbox.addWidget(self.pagegroup)

#        self.optab.insertTab(1, self.pagegroup, "Pages" )

#        self.vbox.addWidget(self.pagegroup)

    def createHexOptions(self):
        self.vvbox = QVBoxLayout()
        self.vcontainer = QWidget()

        self.hexgroup = QWidget()

        self.hexgrid = QGridLayout()

        groupebylabel = QLabel("Groupe by:")
        self.groupeby = QComboBox()
        self.groupeby.addItem("1")
        self.groupeby.addItem("2")
        self.groupeby.addItem("4")

        offsetlabel = QLabel("Offset as")
        self.offsetas = QComboBox()
        self.offsetas.addItem("Hexadecimal")
        self.offsetas.addItem("Decimal")

        #        self.hexgrid.addWidget(groupebylabel, 0, 0)
        #        self.hexgrid.addWidget(self.groupeby, 1, 0)
        self.hexgrid.addWidget(offsetlabel, 0, 0)
        self.hexgrid.addWidget(self.offsetas, 0, 1)
        #        self.hexgrid.addWidget(self.fill, 2, 0)
        #        self.hexgrid.setRowStretch(2, 1)

        self.hexgroup.setLayout(self.hexgrid)

        self.vvbox.addWidget(self.hexgroup)

        self.createPageOptions()

        self.vcontainer.setLayout(self.vvbox)

        self.optab.insertTab(0, self.vcontainer, "General")

#        self.vbox.addWidget(self.hexgroup)

#Offset as decimal / hexadecimal

    def createPixelOptions(self):
        self.pixgroup = QWidget()

        self.pixgrid = QGridLayout()

        formatlabel = QLabel("Format :")
        self.format = QComboBox()
        self.format.addItem("RGB")
        self.format.addItem("Alpha RGB")
        self.format.addItem("Indexed 8bit")
        self.format.addItem("Mono")
        self.connect(self.format, SIGNAL("currentIndexChanged(const QString)"),
                     self.formatChanged)

        colorlabel = QLabel("Indexed Color :")
        self.icolor = QComboBox()
        self.icolor.addItem("Green")
        self.icolor.addItem("Red")
        self.icolor.addItem("Blue")
        self.icolor.addItem("Ascii")
        self.icolor.addItem("256")
        self.icolor.setEnabled(False)

        slidelabel = QLabel("Resolution : ")

        self.sliderspin = QSpinBox(self)
        self.sliderspin.setMinimum(64)
        self.sliderspin.setMaximum(1024)
        self.sliderspin.setValue(self.heditor.wpixel.view.w)
        self.connect(self.sliderspin, SIGNAL("valueChanged(int)"),
                     self.slidermoved)

        self.slider = QSlider(Qt.Horizontal)
        self.slider.setMinimum(64)
        self.slider.setMaximum(1024)
        self.slider.setValue(self.heditor.wpixel.view.w)
        self.slider.setSingleStep(1)

        self.zoomlabel = QLabel("Scale factor : 1")
        self.zoom = QSlider(Qt.Horizontal)
        self.zoom.setMinimum(1)
        self.zoom.setMaximum(5)
        self.zoom.setValue(1)
        self.zoom.setSingleStep(1)
        self.zoom.setTickInterval(1)
        self.zoom.setTickPosition(QSlider.TicksBelow)

        self.connect(self.slider, SIGNAL("sliderMoved(int)"), self.slidermoved)
        self.connect(self.zoom, SIGNAL("sliderMoved(int)"), self.scale)

        self.pixgrid.addWidget(formatlabel, 0, 0)
        self.pixgrid.addWidget(self.format, 0, 1)
        self.pixgrid.addWidget(colorlabel, 1, 0)
        self.pixgrid.addWidget(self.icolor, 1, 1)

        self.pixgrid.addWidget(slidelabel, 2, 0)
        self.pixgrid.addWidget(self.sliderspin, 2, 1, Qt.AlignLeft)

        self.pixgrid.addWidget(self.slider, 3, 0)
        self.pixgrid.addWidget(self.zoomlabel, 4, 0, Qt.AlignLeft)
        self.pixgrid.addWidget(self.zoom, 5, 0)

        self.pixgrid.addWidget(self.fill, 6, 0)
        self.pixgrid.setRowStretch(6, 1)

        self.pixgroup.setLayout(self.pixgrid)

        self.optab.insertTab(1, self.pixgroup, "Pixel")

    def setSliderLabel(self, value):
        cvalue = QString()
        cvalue = "%2.d" % value
        self.sliderlabel.setText(cvalue)

    def setZoomLabel(self, value):
        zvalue = QString("Scale factor : ")
        zvalue += "%2.d" % value
        self.zoomlabel.setText(zvalue)

    def createButtons(self):
        self.applyB = QPushButton("Apply")
        self.connect(self.applyB, SIGNAL('clicked()'), self.apply)

        self.vbox.addWidget(self.applyB)

    def checkValue(self, value):
        try:
            n = int(value)
            return n
        except ValueError:
            return -1

    def apply(self):
        #PAGE CHECK
        pagesize = self.sizeEdit.value()
        headsize = self.headEdit.value()
        sparesize = self.spareEdit.value()
        pagesperblock = self.checkValue(self.pagesperblock.currentText())

        if (pagesize < 0) or (headsize < 0) or (sparesize <
                                                0) or (pagesperblock < 0):
            print "Wrong values"
        else:
            offas = self.offsetas.currentText()
            if offas == "Decimal":
                self.heditor.decimalview = True
            elif offas == "Hexadecimal":
                self.heditor.decimalview = False
            #Hexview refresh
            self.heditor.readOffset(self.heditor.currentOffset)
            #Pageview refresh
            if self.indic.currentText() == "Offset":
                self.heditor.pageOffView = True
            else:
                self.heditor.pageOffView = False

            self.heditor.refreshPageValues(headsize, pagesize, sparesize,
                                           pagesperblock)
            if self.heditor.wpage.scroll:
                self.heditor.wpage.scroll.refreshValues(
                    self.heditor.pagesPerBlock, self.heditor.pageSize)
            self.heditor.wpage.view.refreshAllContent()
            #PageView scrollbar refres
            #Pixel View refresh
            format = self.format.currentText()
            if format == "Indexed 8bit":
                self.heditor.wpixel.view.format = 0
            elif format == "Mono":
                self.heditor.wpixel.view.format = 1
            elif format == "RGB":
                self.heditor.wpixel.view.format = 2
            elif format == "Alpha RGB":
                self.heditor.wpixel.view.format = 3

            if self.heditor.wpixel.scroll:
                self.heditor.wpixel.scroll.refreshValues()
            #Color
            icolor = self.icolor.currentText()
            if icolor == "Red":
                self.heditor.wpixel.view.icolor = 0
            elif icolor == "Green":
                self.heditor.wpixel.view.icolor = 1
            elif icolor == "Blue":
                self.heditor.wpixel.view.icolor = 2
            elif icolor == "Ascii":
                self.heditor.wpixel.view.icolor = 3
            elif icolor == "256":
                self.heditor.wpixel.view.icolor = 4

            pixoffset = self.heditor.wpixel.view.currentOffset
            self.heditor.wpixel.view.read_image(pixoffset)

    def slidermoved(self, value):
        pixoffset = self.heditor.wpixel.view.currentOffset
        self.heditor.wpixel.view.w = value
        self.sliderspin.setValue(value)
        #        self.setSliderLabel(value)
        self.heditor.wpixel.view.read_image(pixoffset)
        if self.heditor.wpixel.scroll:
            self.heditor.wpixel.scroll.refreshValues()
#        print value

    def scale(self, value):
        self.setZoomLabel(value)
        self.heditor.wpixel.view.scale = value
        pixoffset = self.heditor.wpixel.view.currentOffset
        self.heditor.wpixel.view.read_image(pixoffset)

    def formatChanged(self, format):
        if format == "Indexed 8bit":
            self.icolor.setEnabled(True)
        else:
            self.icolor.setEnabled(False)

    def keyPressEvent(self, kEvent):
        key = kEvent.key()
        if key == Qt.Key_Return or key == Qt.Key_Enter:
            self.apply()
Esempio n. 35
0
class UpdateIntervalDialog(QDialog):

    def __init__(self, parent, updater):

        QDialog.__init__(self, parent)

        self.updater = updater
        self.prop = MaeMoneyProperties.instance()
        self.setupUi()

    def setupUi(self):
        self.setWindowModality(Qt.WindowModal)

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.btnPauseUpdate = QPushButton()
        self.setPauseUpdateButtonStatus()
        self.layout.addWidget(self.btnPauseUpdate)

        self.comboBoxUpdInterval = QComboBox()
        self.comboBoxUpdInterval.addItem(self.tr("Pause update"), 0)
        self.comboBoxUpdInterval.addItem(
                self.tr("Update interval - %1s").arg(Properties.DEFAULT_UPDATE_INTERVAL),
                Properties.DEFAULT_UPDATE_INTERVAL)
        self.comboBoxUpdInterval.addItem(self.tr("Update interval - 25s"), 25)
        self.comboBoxUpdInterval.addItem(self.tr("Update interval - 1 min"), 60)
        self.comboBoxUpdInterval.addItem(self.tr("Update interval - 5 min"), 5 * 60)
        self.comboBoxUpdInterval.addItem(self.tr("Update interval - 15 min"), 15 * 60)
        self.comboBoxUpdInterval.addItem(self.tr("Update interval - 30 min"), 30 * 60)
        self.comboBoxUpdInterval.addItem(self.tr("Update interval - 45 min"), 45 * 60)
        self.comboBoxUpdInterval.addItem(self.tr("Update interval - 1 hr"), 1 * 60 * 60)
        self.comboBoxUpdInterval.addItem(self.tr("Update interval - 2 hr"), 2 * 60 * 60)
        self.setCurrentComboBoxUpdInterval()
        self.setComboBoxStatus()
        self.layout.addWidget(self.comboBoxUpdInterval)

        self.btnBackToMainApp = QPushButton(self.tr("Back to Main Application"))
        self.layout.addWidget(self.btnBackToMainApp)

        self.setWindowTitle(self.tr("Update Interval"))

        self.connect(self.btnPauseUpdate, SIGNAL("clicked()"), self.pauseUpdate)
        self.connect(self.comboBoxUpdInterval, SIGNAL("activated(int)"), self.updateIntervalSelected)
        self.connect(self.btnBackToMainApp, SIGNAL("clicked()"), self.accept)

    def setCurrentComboBoxUpdInterval(self):
        curInterval = self.prop.getUpdateInterval()
        index = self.comboBoxUpdInterval.findData(curInterval)
        if index >= 0:
            self.comboBoxUpdInterval.setCurrentIndex(index)
        else:
            qWarning("Update interval of %ds is not available." %(curInterval))
            qWarning("Resetting to default of %ds" %(Properties.DEFAULT_UPDATE_INTERVAL))
            self.prop.setUpdateInterval(Properties.DEFAULT_UPDATE_INTERVAL)
            self.setCurrentComboBoxUpdInterval()

    def updateIntervalSelected(self, index):
        if self.updater is not None:
            intervalSelected = self.comboBoxUpdInterval.itemData(index).toInt()[0]
            self.prop.setUpdateInterval(intervalSelected)
            if intervalSelected == 0:
                self.pauseUpdate()
            else:
                self.updater.terminate()
                self.updater.start()
                self.updater.setUpdateInterval(intervalSelected)
                self.setPauseUpdateButtonStatus()

    def pauseUpdate(self):
        if self.updater is not None:
            self.updater.terminate()
            self.setPauseUpdateButtonStatus()
            pauseInterval = 0
            index = self.comboBoxUpdInterval.findData(pauseInterval)
            self.comboBoxUpdInterval.setCurrentIndex(index)
            self.prop.setUpdateInterval(pauseInterval)

    def setPauseUpdateButtonStatus(self):
        if self.btnPauseUpdate is not None:
            if self.updater is not None and self.updater.isRunning():
                self.btnPauseUpdate.setText(self.tr("Timer currently active. Click to pause update"))
                self.btnPauseUpdate.setEnabled(True)
            else:
                self.btnPauseUpdate.setText(self.tr("Update not running"))
                self.btnPauseUpdate.setEnabled(False)

    def setComboBoxStatus(self):
        if self.comboBoxUpdInterval is not None:
            if self.updater is None:
                self.comboBoxUpdInterval.setEnabled(False)
            else:
                self.comboBoxUpdInterval.setEnabled(True)
Esempio n. 36
0
class UserPanelDlg(QDialog):
    def __init__(self, parent=None):
        super(UserPanelDlg, self).__init__(parent)
        self.setWindowTitle('Address Book - User Panel')
        self.resize(330, 164)

        self.parent = parent
        self.db = self.parent.db

        chooseLabel = QLabel('Choose User:'******'New user')
        self.editButton = QPushButton('Edit username')
        self.deleteButton = QPushButton('Delete user')
        self.connectButton = QPushButton('Connect')
        line = QFrame()
        line.setFrameShape(QFrame.VLine)
        line.setFrameShadow(QFrame.Sunken)

        add_l = pyqttools.add_to_layout
        hlayout1 = add_l(QHBoxLayout(), (chooseLabel, None))
        hlayout2 = add_l(QHBoxLayout(), (None, self.connectButton))
        vlayout1 = add_l(QVBoxLayout(),(None, hlayout1,self.userComboBox, None))
        vlayout2 = add_l(QVBoxLayout(), (newButton, self.editButton,
                                                            self.deleteButton))
        hlayout3 = add_l(QHBoxLayout(), (vlayout1, line, vlayout2))
        f_layout = add_l(QVBoxLayout(), (hlayout3, hlayout2))
        self.setLayout(f_layout)

        newButton.clicked.connect(self.add_user)
        self.editButton.clicked.connect(self.edit_user)
        self.deleteButton.clicked.connect(self.delete_user)
        self.connectButton.clicked.connect(self.accept)

        self.fill_combobox()

    def fill_combobox(self):
        users = self.db.get_users()
        self.userComboBox.clear()
        self.userComboBox.addItems(users)
        self.userComboBox.setEnabled(bool(users))
        self.enable_buttons()

    def enable_buttons(self):
        enable = bool(self.userComboBox.count() > 0)
        self.editButton.setEnabled(enable)
        self.deleteButton.setEnabled(enable)
        self.connectButton.setEnabled(enable)

    def add_user(self):
        AddOrEditUserDlg('', False, self).exec_()
        self.fill_combobox()

    def edit_user(self):
        AddOrEditUserDlg(self.userComboBox.currentText(), True, self).exec_()
        self.fill_combobox()

    def delete_user(self):
        user = self.userComboBox.currentText()
        reply = QMessageBox.question(self, 'Address Book - Delete User',
                      'Are sou sure that you want to delete {0}?'.format(user),
                                            QMessageBox.Yes|QMessageBox.Cancel)
        if reply == QMessageBox.Yes:
            self.db.delete_user(user)
            self.fill_combobox()

    def accept(self):
        self.user = self.userComboBox.currentText()
        QDialog.accept(self)

    def reject(self):
        self.parent.close()
        QDialog.reject(self)
Esempio n. 37
0
class FindInFilesDialog(QDialog, object):
    """ find in files dialog implementation """

    inProject = 0
    inDirectory = 1
    inOpenFiles = 2

    def __init__(self, where, what="", dirPath="", filters=[], parent=None):

        QDialog.__init__(self, parent)

        mainWindow = GlobalData().mainWindow
        self.editorsManager = mainWindow.editorsManagerWidget.editorsManager

        self.__cancelRequest = False
        self.__inProgress = False
        self.searchRegexp = None
        self.searchResults = []

        # Avoid pylint complains
        self.findCombo = None
        self.caseCheckBox = None
        self.wordCheckBox = None
        self.regexpCheckBox = None
        self.projectRButton = None
        self.openFilesRButton = None
        self.dirRButton = None
        self.dirEditCombo = None
        self.dirSelectButton = None
        self.filterCombo = None
        self.fileLabel = None
        self.progressBar = None
        self.findButton = None

        self.__createLayout()
        self.setWindowTitle("Find in files")

        # Restore the combo box values
        project = GlobalData().project
        if project.fileName != "":
            self.findFilesWhat = project.findFilesWhat
            self.findFilesDirs = project.findFilesDirs
            self.findFilesMasks = project.findFilesMasks
        else:
            settings = Settings()
            self.findFilesWhat = settings.findFilesWhat
            self.findFilesDirs = settings.findFilesDirs
            self.findFilesMasks = settings.findFilesMasks
        self.findCombo.addItems(self.findFilesWhat)
        self.findCombo.setEditText("")
        self.dirEditCombo.addItems(self.findFilesDirs)
        self.dirEditCombo.setEditText("")
        self.filterCombo.addItems(self.findFilesMasks)
        self.filterCombo.setEditText("")

        if where == self.inProject:
            self.setSearchInProject(what, filters)
        elif where == self.inDirectory:
            self.setSearchInDirectory(what, dirPath, filters)
        else:
            self.setSearchInOpenFiles(what, filters)

        return

    def __createLayout(self):
        """ Creates the dialog layout """

        self.resize(600, 300)
        self.setSizeGripEnabled(True)

        verticalLayout = QVBoxLayout(self)
        gridLayout = QGridLayout()

        # Combo box for the text to search
        findLabel = QLabel(self)
        findLabel.setText("Find text:")
        self.findCombo = QComboBox(self)
        self.__tuneCombo(self.findCombo)
        self.findCombo.lineEdit().setToolTip(
            "Regular expression to search for")
        self.findCombo.editTextChanged.connect(self.__someTextChanged)

        gridLayout.addWidget(findLabel, 0, 0, 1, 1)
        gridLayout.addWidget(self.findCombo, 0, 1, 1, 1)
        verticalLayout.addLayout(gridLayout)

        # Check boxes
        horizontalCBLayout = QHBoxLayout()
        self.caseCheckBox = QCheckBox(self)
        self.caseCheckBox.setText("Match &case")
        horizontalCBLayout.addWidget(self.caseCheckBox)
        self.wordCheckBox = QCheckBox(self)
        self.wordCheckBox.setText("Match whole &word")
        horizontalCBLayout.addWidget(self.wordCheckBox)
        self.regexpCheckBox = QCheckBox(self)
        self.regexpCheckBox.setText("Regular &expression")
        horizontalCBLayout.addWidget(self.regexpCheckBox)

        verticalLayout.addLayout(horizontalCBLayout)

        # Files groupbox
        filesGroupbox = QGroupBox(self)
        filesGroupbox.setTitle("Find in")
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            filesGroupbox.sizePolicy().hasHeightForWidth())
        filesGroupbox.setSizePolicy(sizePolicy)

        gridLayoutFG = QGridLayout(filesGroupbox)
        self.projectRButton = QRadioButton(filesGroupbox)
        self.projectRButton.setText("&Project")
        gridLayoutFG.addWidget(self.projectRButton, 0, 0)
        self.projectRButton.clicked.connect(self.__projectClicked)

        self.openFilesRButton = QRadioButton(filesGroupbox)
        self.openFilesRButton.setText("&Opened files only")
        gridLayoutFG.addWidget(self.openFilesRButton, 1, 0)
        self.openFilesRButton.clicked.connect(self.__openFilesOnlyClicked)

        self.dirRButton = QRadioButton(filesGroupbox)
        self.dirRButton.setText("&Directory tree")
        gridLayoutFG.addWidget(self.dirRButton, 2, 0)
        self.dirRButton.clicked.connect(self.__dirClicked)

        self.dirEditCombo = QComboBox(filesGroupbox)
        self.__tuneCombo(self.dirEditCombo)
        self.dirEditCombo.lineEdit().setToolTip("Directory to search in")
        gridLayoutFG.addWidget(self.dirEditCombo, 2, 1)
        self.dirEditCombo.editTextChanged.connect(self.__someTextChanged)

        self.dirSelectButton = QPushButton(filesGroupbox)
        self.dirSelectButton.setText("...")
        gridLayoutFG.addWidget(self.dirSelectButton, 2, 2)
        self.dirSelectButton.clicked.connect(self.__selectDirClicked)

        filterLabel = QLabel(filesGroupbox)
        filterLabel.setText("Files filter:")
        gridLayoutFG.addWidget(filterLabel, 3, 0)
        self.filterCombo = QComboBox(filesGroupbox)
        self.__tuneCombo(self.filterCombo)
        self.filterCombo.lineEdit().setToolTip("File names regular expression")
        gridLayoutFG.addWidget(self.filterCombo, 3, 1)
        self.filterCombo.editTextChanged.connect(self.__someTextChanged)

        verticalLayout.addWidget(filesGroupbox)

        # File label
        self.fileLabel = FitPathLabel(self)
        self.fileLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed)
        verticalLayout.addWidget(self.fileLabel)

        # Progress bar
        self.progressBar = QProgressBar(self)
        self.progressBar.setValue(0)
        self.progressBar.setOrientation(Qt.Horizontal)
        verticalLayout.addWidget(self.progressBar)

        # Buttons at the bottom
        buttonBox = QDialogButtonBox(self)
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Cancel)
        self.findButton = buttonBox.addButton("Find",
                                              QDialogButtonBox.AcceptRole)
        self.findButton.setDefault(True)
        self.findButton.clicked.connect(self.__process)
        verticalLayout.addWidget(buttonBox)

        buttonBox.rejected.connect(self.__onClose)
        return

    @staticmethod
    def __tuneCombo(comboBox):
        " Sets the common settings for a combo box "
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth( \
                            comboBox.sizePolicy().hasHeightForWidth() )
        comboBox.setSizePolicy(sizePolicy)
        comboBox.setEditable(True)
        comboBox.setInsertPolicy(QComboBox.InsertAtTop)
        comboBox.setAutoCompletion(False)
        comboBox.setDuplicatesEnabled(False)
        return

    def __onClose(self):
        " Triggered when the close button is clicked "

        self.__cancelRequest = True
        if not self.__inProgress:
            self.close()
        return

    def setSearchInProject(self, what="", filters=[]):
        " Set search ready for the whole project "

        if GlobalData().project.fileName == "":
            # No project loaded, fallback to opened files
            self.setSearchInOpenFiles(what, filters)
            return

        # Select the project radio button
        self.projectRButton.setEnabled(True)
        self.projectRButton.setChecked(True)
        self.dirEditCombo.setEnabled(False)
        self.dirSelectButton.setEnabled(False)

        openedFiles = self.editorsManager.getTextEditors()
        self.openFilesRButton.setEnabled(len(openedFiles) != 0)

        self.setFilters(filters)

        self.findCombo.setEditText(what)
        self.findCombo.lineEdit().selectAll()
        self.findCombo.setFocus()

        # Check searchability
        self.__testSearchability()
        return

    def setSearchInOpenFiles(self, what="", filters=[]):
        " Sets search ready for the opened files "

        openedFiles = self.editorsManager.getTextEditors()
        if len(openedFiles) == 0:
            # No opened files, fallback to search in dir
            self.setSearchInDirectory(what, "", filters)
            return

        # Select the radio buttons
        self.projectRButton.setEnabled(GlobalData().project.fileName != "")
        self.openFilesRButton.setEnabled(True)
        self.openFilesRButton.setChecked(True)
        self.dirEditCombo.setEnabled(False)
        self.dirSelectButton.setEnabled(False)

        self.setFilters(filters)

        self.findCombo.setEditText(what)
        self.findCombo.lineEdit().selectAll()
        self.findCombo.setFocus()

        # Check searchability
        self.__testSearchability()
        return

    def setSearchInDirectory(self, what="", dirPath="", filters=[]):
        " Sets search ready for the given directory "

        # Select radio buttons
        self.projectRButton.setEnabled(GlobalData().project.fileName != "")
        openedFiles = self.editorsManager.getTextEditors()
        self.openFilesRButton.setEnabled(len(openedFiles) != 0)
        self.dirRButton.setEnabled(True)
        self.dirRButton.setChecked(True)
        self.dirEditCombo.setEnabled(True)
        self.dirSelectButton.setEnabled(True)
        self.dirEditCombo.setEditText(dirPath)

        self.setFilters(filters)

        self.findCombo.setEditText(what)
        self.findCombo.lineEdit().selectAll()
        self.findCombo.setFocus()

        # Check searchability
        self.__testSearchability()
        return

    def setFilters(self, filters):
        " Sets up the filters "

        # Set filters if provided
        if filters:
            self.filterCombo.setEditText(";".join(filters))
        else:
            self.filterCombo.setEditText("")
        return

    def __testSearchability(self):
        " Tests the searchability and sets the Find button status "

        startTime = time.time()
        if self.findCombo.currentText().strip() == "":
            self.findButton.setEnabled(False)
            self.findButton.setToolTip("No text to search")
            return

        if self.dirRButton.isChecked():
            dirname = self.dirEditCombo.currentText().strip()
            if dirname == "":
                self.findButton.setEnabled(False)
                self.findButton.setToolTip("No directory path")
                return
            if not os.path.isdir(dirname):
                self.findButton.setEnabled(False)
                self.findButton.setToolTip("Path is not a directory")
                return

        # Now we need to match file names if there is a filter
        filtersText = self.filterCombo.currentText().strip()
        if filtersText == "":
            self.findButton.setEnabled(True)
            self.findButton.setToolTip("Find in files")
            return

        # Need to check the files match
        try:
            filterRe = re.compile(filtersText, re.IGNORECASE)
        except:
            self.findButton.setEnabled(False)
            self.findButton.setToolTip( "Incorrect files " \
                                        "filter regular expression" )
            return

        matched = False
        tooLong = False
        if self.projectRButton.isChecked():
            # Whole project
            for fname in GlobalData().project.filesList:
                if fname.endswith(sep):
                    continue
                matched = filterRe.match(fname)
                if matched:
                    break
                # Check the time, it might took too long
                if time.time() - startTime > 0.1:
                    tooLong = True
                    break

        elif self.openFilesRButton.isChecked():
            # Opened files
            openedFiles = self.editorsManager.getTextEditors()
            for record in openedFiles:
                matched = filterRe.match(record[1])
                if matched:
                    break
                # Check the time, it might took too long
                if time.time() - startTime > 0.1:
                    tooLong = True
                    break

        else:
            # Search in the dir
            if not dirname.endswith(sep):
                dirname += sep
            matched, tooLong = self.__matchInDir(dirname, filterRe, startTime)

        if matched:
            self.findButton.setEnabled(True)
            self.findButton.setToolTip("Find in files")
        else:
            if tooLong:
                self.findButton.setEnabled(True)
                self.findButton.setToolTip("Find in files")
            else:
                self.findButton.setEnabled(False)
                self.findButton.setToolTip("No files matched to search in")
        return

    @staticmethod
    def __matchInDir(path, filterRe, startTime):
        " Provides the 'match' and 'too long' statuses "
        matched = False
        tooLong = False
        for item in os.listdir(path):
            if time.time() - startTime > 0.1:
                tooLong = True
                return matched, tooLong
            if os.path.isdir(path + item):
                dname = path + item + sep
                matched, tooLong = FindInFilesDialog.__matchInDir(
                    dname, filterRe, startTime)
                if matched or tooLong:
                    return matched, tooLong
                continue
            if filterRe.match(path + item):
                matched = True
                return matched, tooLong
        return matched, tooLong

    def __projectClicked(self):
        " project radio button clicked "
        self.dirEditCombo.setEnabled(False)
        self.dirSelectButton.setEnabled(False)
        self.__testSearchability()
        return

    def __openFilesOnlyClicked(self):
        " open files only radio button clicked "
        self.dirEditCombo.setEnabled(False)
        self.dirSelectButton.setEnabled(False)
        self.__testSearchability()
        return

    def __dirClicked(self):
        " dir radio button clicked "
        self.dirEditCombo.setEnabled(True)
        self.dirSelectButton.setEnabled(True)
        self.dirEditCombo.setFocus()
        self.__testSearchability()
        return

    def __someTextChanged(self, text):
        " Text to search, filter or dir name has been changed "
        self.__testSearchability()
        return

    def __selectDirClicked(self):
        " The user selects a directory "
        dirName = QFileDialog.getExistingDirectory(
            self, "Select directory to search in",
            self.dirEditCombo.currentText(),
            QFileDialog.Options(QFileDialog.ShowDirsOnly))

        if dirName:
            self.dirEditCombo.setEditText(os.path.normpath(dirName))
        self.__testSearchability()
        return

    def __projectFiles(self, filterRe):
        " Project files list respecting the mask "
        mainWindow = GlobalData().mainWindow
        files = []
        for fname in GlobalData().project.filesList:
            if fname.endswith(sep):
                continue
            if filterRe is None or filterRe.match(fname):
                widget = mainWindow.getWidgetForFileName(fname)
                if widget is None:
                    # Do not check for broken symlinks
                    if isFileSearchable(fname, False):
                        files.append(ItemToSearchIn(fname, ""))
                else:
                    if widget.getType() in \
                                [ MainWindowTabWidgetBase.PlainTextEditor ]:
                        files.append(ItemToSearchIn(fname, widget.getUUID()))
            QApplication.processEvents()
            if self.__cancelRequest:
                raise Exception("Cancel request")
        return files

    def __openedFiles(self, filterRe):
        " Currently opened editor buffers "

        files = []
        openedFiles = self.editorsManager.getTextEditors()
        for record in openedFiles:
            uuid = record[0]
            fname = record[1]
            if filterRe is None or filterRe.match(fname):
                files.append(ItemToSearchIn(fname, uuid))
            QApplication.processEvents()
            if self.__cancelRequest:
                raise Exception("Cancel request")
        return files

    def __dirFiles(self, path, filterRe, files):
        " Files recursively for the dir "
        for item in os.listdir(path):
            QApplication.processEvents()
            if self.__cancelRequest:
                raise Exception("Cancel request")
            if os.path.isdir(path + item):
                if item in [".svn", ".cvs"]:
                    # It does not make sense to search in revision control dirs
                    continue
                anotherDir, isLoop = resolveLink(path + item)
                if not isLoop:
                    self.__dirFiles(anotherDir + sep, filterRe, files)
                continue
            if not os.path.isfile(path + item):
                continue
            realItem, isLoop = resolveLink(path + item)
            if isLoop:
                continue
            if filterRe is None or filterRe.match(realItem):
                found = False
                for itm in files:
                    if itm.fileName == realItem:
                        found = True
                        break
                if not found:
                    mainWindow = GlobalData().mainWindow
                    widget = mainWindow.getWidgetForFileName(realItem)
                    if widget is None:
                        if isFileSearchable(realItem):
                            files.append(ItemToSearchIn(realItem, ""))
                    else:
                        if widget.getType() in \
                                    [ MainWindowTabWidgetBase.PlainTextEditor ]:
                            files.append(
                                ItemToSearchIn(realItem, widget.getUUID()))
        return

    def __buildFilesList(self):
        " Builds the list of files to search in "
        filtersText = self.filterCombo.currentText().strip()
        if filtersText != "":
            filterRe = re.compile(filtersText, re.IGNORECASE)
        else:
            filterRe = None

        if self.projectRButton.isChecked():
            return self.__projectFiles(filterRe)

        if self.openFilesRButton.isChecked():
            return self.__openedFiles(filterRe)

        dirname = os.path.realpath(self.dirEditCombo.currentText().strip())
        files = []
        self.__dirFiles(dirname + sep, filterRe, files)
        return files

    def __process(self):
        " Search process "

        # Add entries to the combo box if required
        regexpText = self.findCombo.currentText()
        if regexpText in self.findFilesWhat:
            self.findFilesWhat.remove(regexpText)
        self.findFilesWhat.insert(0, regexpText)
        if len(self.findFilesWhat) > 32:
            self.findFilesWhat = self.findFilesWhat[:32]
        self.findCombo.clear()
        self.findCombo.addItems(self.findFilesWhat)

        filtersText = self.filterCombo.currentText().strip()
        if filtersText in self.findFilesMasks:
            self.findFilesMasks.remove(filtersText)
        self.findFilesMasks.insert(0, filtersText)
        if len(self.findFilesMasks) > 32:
            self.findFilesMasks = self.findFilesMasks[:32]
        self.filterCombo.clear()
        self.filterCombo.addItems(self.findFilesMasks)

        if self.dirRButton.isChecked():
            dirText = self.dirEditCombo.currentText().strip()
            if dirText in self.findFilesDirs:
                self.findFilesDirs.remove(dirText)
            self.findFilesDirs.insert(0, dirText)
            if len(self.findFilesDirs) > 32:
                self.findFilesDirs = self.findFilesDirs[:32]
            self.dirEditCombo.clear()
            self.dirEditCombo.addItems(self.findFilesDirs)

        # Save the combo values for further usage
        if GlobalData().project.fileName != "":
            GlobalData().project.setFindInFilesHistory(self.findFilesWhat,
                                                       self.findFilesDirs,
                                                       self.findFilesMasks)
        else:
            Settings().findFilesWhat = self.findFilesWhat
            Settings().findFilesDirs = self.findFilesDirs
            Settings().findFilesMasks = self.findFilesMasks

        self.__inProgress = True
        numberOfMatches = 0
        self.searchResults = []
        self.searchRegexp = None

        # Form the regexp to search
        if not self.regexpCheckBox.isChecked():
            regexpText = re.escape(regexpText)
        if self.wordCheckBox.isChecked():
            regexpText = "\\b%s\\b" % regexpText
        flags = re.UNICODE | re.LOCALE
        if not self.caseCheckBox.isChecked():
            flags |= re.IGNORECASE

        try:
            self.searchRegexp = re.compile(regexpText, flags)
        except:
            logging.error("Invalid search expression")
            self.close()
            return

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        self.fileLabel.setPath('Building list of files to search in...')
        QApplication.processEvents()
        try:
            files = self.__buildFilesList()
        except Exception, exc:
            if "Cancel request" in str(exc):
                QApplication.restoreOverrideCursor()
                self.close()
                return
            else:
                QApplication.restoreOverrideCursor()
                logging.error(str(exc))
                self.close()
                return
        QApplication.restoreOverrideCursor()
        QApplication.processEvents()

        if len(files) == 0:
            self.fileLabel.setPath('No files to search in')
            return

        self.progressBar.setRange(0, len(files))

        index = 1
        for item in files:

            if self.__cancelRequest:
                self.__inProgress = False
                self.close()
                return

            self.fileLabel.setPath( 'Matches: ' + str( numberOfMatches ) + \
                                    ' Processing: ' + item.fileName )

            item.search(self.searchRegexp)
            found = len(item.matches)
            if found > 0:
                numberOfMatches += found
                self.searchResults.append(item)

            self.progressBar.setValue(index)
            index += 1

            QApplication.processEvents()

        if numberOfMatches == 0:
            if len(files) == 1:
                self.fileLabel.setPath("No matches in 1 file.")
            else:
                self.fileLabel.setPath( "No matches in " + \
                                        str( len( files ) ) + " files." )
            self.__inProgress = False
        else:
            self.close()
        return
Esempio n. 38
0
class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self._document = None
        
        layout = QGridLayout()
        self.setLayout(layout)
        
        self.versionLabel = QLabel()
        self.versionCombo = QComboBox()
        
        self.outputLabel = QLabel()
        self.outputCombo = QComboBox()
        
        self.resolutionLabel = QLabel()
        self.resolutionCombo = QComboBox(editable=True)
        
        self.previewCheck = QCheckBox()
        self.verboseCheck = QCheckBox()
        self.englishCheck = QCheckBox()
        self.deleteCheck = QCheckBox()
        
        self.commandLineLabel = QLabel()
        self.commandLine = QTextEdit(acceptRichText=False)
        
        self.buttons = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.buttons.button(QDialogButtonBox.Ok).setIcon(icons.get("lilypond-run"))
        help.addButton(self.buttons, help_engrave_custom)
        
        self.resolutionCombo.addItems(['100', '200', '300', '600', '1200'])
        self.resolutionCombo.setCurrentIndex(2)
        
        layout.addWidget(self.versionLabel, 0, 0)
        layout.addWidget(self.versionCombo, 0, 1)
        layout.addWidget(self.outputLabel, 1, 0)
        layout.addWidget(self.outputCombo, 1, 1)
        layout.addWidget(self.resolutionLabel, 2, 0)
        layout.addWidget(self.resolutionCombo, 2, 1)
        layout.addWidget(self.previewCheck, 3, 0, 1, 2)
        layout.addWidget(self.verboseCheck, 4, 0, 1, 2)
        layout.addWidget(self.englishCheck, 5, 0, 1, 2)
        layout.addWidget(self.deleteCheck, 6, 0, 1, 2)
        layout.addWidget(self.commandLineLabel, 7, 0, 1, 2)
        layout.addWidget(self.commandLine, 8, 0, 1, 2)
        layout.addWidget(widgets.Separator(), 9, 0, 1, 2)
        layout.addWidget(self.buttons, 10, 0, 1, 2)
        
        app.translateUI(self)
        util.saveDialogSize(self, "engrave/custom/dialog/size", QSize(480, 260))
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        
        model = listmodel.ListModel(formats, display=lambda f: f.title(),
            icon=lambda f: icons.file_type(f.type))
        self.outputCombo.setModel(model)
        
        s = QSettings()
        s.beginGroup("lilypond_settings")
        self.englishCheck.setChecked(
            s.value("no_translation", False) in (True, "true"))
        self.deleteCheck.setChecked(
            s.value("delete_intermediate_files", True) not in (False, "false"))
        
        self.loadLilyPondVersions()
        self.selectLilyPondInfo(lilypondinfo.preferred())
        app.settingsChanged.connect(self.loadLilyPondVersions)
        app.jobFinished.connect(self.slotJobFinished)
        self.outputCombo.currentIndexChanged.connect(self.makeCommandLine)
        self.previewCheck.toggled.connect(self.makeCommandLine)
        self.verboseCheck.toggled.connect(self.makeCommandLine)
        self.deleteCheck.toggled.connect(self.makeCommandLine)
        self.resolutionCombo.editTextChanged.connect(self.makeCommandLine)
        self.makeCommandLine()
    
    def translateUI(self):
        self.setWindowTitle(app.caption(_("Engrave custom")))
        self.versionLabel.setText(_("LilyPond Version:"))
        self.outputLabel.setText(_("Output Format:"))
        self.resolutionLabel.setText(_("Resolution:"))
        self.previewCheck.setText(_(
            "Run LilyPond in preview mode (with Point and Click)"))
        self.verboseCheck.setText(_("Run LilyPond with verbose output"))
        self.englishCheck.setText(_("Run LilyPond with English messages"))
        self.deleteCheck.setText(_("Delete intermediate output files"))
        self.commandLineLabel.setText(_("Command line:"))
        self.buttons.button(QDialogButtonBox.Ok).setText(_("Run LilyPond"))
        self.outputCombo.update()
    
    def slotJobFinished(self, doc):
        if doc == self._document:
            self.buttons.button(QDialogButtonBox.Ok).setEnabled(True)
            self._document = None
    
    def setDocument(self, doc):
        self.selectLilyPondInfo(command.info(doc))
        if jobmanager.isRunning(doc):
            self._document = doc
            self.buttons.button(QDialogButtonBox.Ok).setEnabled(False)
        
    def loadLilyPondVersions(self):
        infos = lilypondinfo.infos() or [lilypondinfo.default()]
        infos.sort(key = lambda i: i.version() or (999,))
        self._infos = infos
        index = self.versionCombo.currentIndex()
        self.versionCombo.clear()
        for i in infos:
            icon = 'lilypond-run' if i.version() else 'dialog-error'
            text = _("LilyPond {version}").format(version=i.versionString())
            self.versionCombo.addItem(icons.get(icon), text)
        self.versionCombo.setCurrentIndex(index)
    
    def selectLilyPondInfo(self, info):
        if info in self._infos:
            self.versionCombo.setCurrentIndex(self._infos.index(info))
    
    def makeCommandLine(self):
        """Reads the widgets and builds a command line."""
        f = formats[self.outputCombo.currentIndex()]
        self.resolutionCombo.setEnabled('resolution' in f.widgets)
        cmd = ["$lilypond"]
        if self.verboseCheck.isChecked():
            cmd.append('--verbose')
        if self.previewCheck.isChecked():
            cmd.append('-dpoint-and-click')
        else:
            cmd.append('-dno-point-and-click')
        if self.deleteCheck.isChecked():
            cmd.append('-ddelete-intermediate-files')
        else:
            cmd.append('-dno-delete-intermediate-files')
        d = {
            'version': self._infos[self.versionCombo.currentIndex()].version,
            'resolution': self.resolutionCombo.currentText(),
        }
        cmd.append("$include")
        cmd.extend(f.options(d))
        cmd.append("$filename")
        self.commandLine.setText(' '.join(cmd))
    
    def getJob(self, document):
        """Returns a Job to start."""
        filename, mode, includepath = documentinfo.info(document).jobinfo(True)
        includepath.extend(documentinfo.info(document).includepath())
        i = self._infos[self.versionCombo.currentIndex()]
        cmd = []
        for t in self.commandLine.toPlainText().split():
            if t == '$lilypond':
                cmd.append(i.command)
            elif t == '$filename':
                cmd.append(filename)
            elif t == '$include':
                cmd.extend('-I' + path for path in includepath)
            else:
                cmd.append(t)
        j = job.Job()
        j.directory = os.path.dirname(filename)
        j.command = cmd
        if self.englishCheck.isChecked():
            j.environment['LANG'] = 'C'
        j.setTitle("{0} {1} [{2}]".format(
            os.path.basename(i.command), i.versionString(), document.documentName()))
        return j
Esempio n. 39
0
class Dialog(QDialog):
    def __init__(self, mainwindow):
        super(Dialog, self).__init__(mainwindow)
        self._document = None
        
        layout = QGridLayout()
        self.setLayout(layout)
        
        self.versionLabel = QLabel()
        self.lilyChooser = lilychooser.LilyChooser()
        
        self.outputLabel = QLabel()
        self.outputCombo = QComboBox()
        
        self.resolutionLabel = QLabel()
        self.resolutionCombo = QComboBox(editable=True)
        
        self.antialiasLabel = QLabel()
        self.antialiasSpin = QSpinBox(minimum=1, maximum=128, value=1)
        
        self.modeLabel = QLabel()
        self.modeCombo = QComboBox()
        
        self.englishCheck = QCheckBox()
        self.deleteCheck = QCheckBox()
        
        self.commandLineLabel = QLabel()
        self.commandLine = QTextEdit(acceptRichText=False)
        
        self.buttons = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.buttons.button(QDialogButtonBox.Ok).setIcon(icons.get("lilypond-run"))
        userguide.addButton(self.buttons, "engrave_custom")
        
        self.resolutionCombo.addItems(['100', '200', '300', '600', '1200'])
        self.resolutionCombo.setCurrentIndex(2)
        
        self.modeCombo.addItems(['preview', 'publish', 'debug'])
        layout.addWidget(self.versionLabel, 0, 0)
        layout.addWidget(self.lilyChooser, 0, 1, 1, 3)
        layout.addWidget(self.outputLabel, 1, 0)
        layout.addWidget(self.outputCombo, 1, 1, 1, 3)
        layout.addWidget(self.resolutionLabel, 2, 0)
        layout.addWidget(self.resolutionCombo, 2, 1)
        layout.addWidget(self.antialiasLabel, 2, 2, Qt.AlignRight)
        layout.addWidget(self.antialiasSpin, 2, 3)
        layout.addWidget(self.modeLabel, 3, 0)
        layout.addWidget(self.modeCombo, 3, 1, 1, 3)
        layout.addWidget(self.englishCheck, 4, 0, 1, 4)
        layout.addWidget(self.deleteCheck, 5, 0, 1, 4)
        layout.addWidget(self.commandLineLabel, 6, 0, 1, 4)
        layout.addWidget(self.commandLine, 7, 0, 1, 4)
        layout.addWidget(widgets.Separator(), 8, 0, 1, 4)
        layout.addWidget(self.buttons, 9, 0, 1, 4)
        
        app.translateUI(self)
        qutil.saveDialogSize(self, "engrave/custom/dialog/size", QSize(480, 260))
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        
        model = listmodel.ListModel(formats, display=lambda f: f.title(),
            icon=lambda f: icons.file_type(f.type))
        self.outputCombo.setModel(model)
        
        s = QSettings()
        s.beginGroup("lilypond_settings")
        self.englishCheck.setChecked(
            s.value("no_translation", False, bool))
        self.deleteCheck.setChecked(
            s.value("delete_intermediate_files", True, bool))
        
        if s.value("default_output_target", "pdf", type("")) == "svg":
            self.outputCombo.setCurrentIndex(3)
        
        app.jobFinished.connect(self.slotJobFinished)
        self.outputCombo.currentIndexChanged.connect(self.makeCommandLine)
        self.modeCombo.currentIndexChanged.connect(self.makeCommandLine)
        self.deleteCheck.toggled.connect(self.makeCommandLine)
        self.resolutionCombo.editTextChanged.connect(self.makeCommandLine)
        self.antialiasSpin.valueChanged.connect(self.makeCommandLine)
        self.makeCommandLine()
        panelmanager.manager(mainwindow).layoutcontrol.widget().optionsChanged.connect(self.makeCommandLine)
    
    def translateUI(self):
        self.setWindowTitle(app.caption(_("Engrave custom")))
        self.versionLabel.setText(_("LilyPond Version:"))
        self.outputLabel.setText(_("Output Format:"))
        self.resolutionLabel.setText(_("Resolution:"))
        self.antialiasLabel.setText(_("Antialias Factor:"))
        self.modeLabel.setText(_("Engraving mode:"))
        self.modeCombo.setItemText(0, _("Preview"))
        self.modeCombo.setItemText(1, _("Publish"))
        self.modeCombo.setItemText(2, _("Layout Control"))
        self.englishCheck.setText(_("Run LilyPond with English messages"))
        self.deleteCheck.setText(_("Delete intermediate output files"))
        self.commandLineLabel.setText(_("Command line:"))
        self.buttons.button(QDialogButtonBox.Ok).setText(_("Run LilyPond"))
        self.outputCombo.update()
    
    def slotJobFinished(self, doc):
        if doc == self._document:
            self.buttons.button(QDialogButtonBox.Ok).setEnabled(True)
            self._document = None
    
    def setDocument(self, doc):
        self.lilyChooser.setLilyPondInfo(command.info(doc))
        job = jobmanager.job(doc)
        if job and job.isRunning() and not jobattributes.get(job).hidden:
            self._document = doc
            self.buttons.button(QDialogButtonBox.Ok).setEnabled(False)
        
    def makeCommandLine(self):
        """Reads the widgets and builds a command line."""
        f = formats[self.outputCombo.currentIndex()]
        self.resolutionCombo.setEnabled('resolution' in f.widgets)
        self.antialiasSpin.setEnabled('antialias' in f.widgets)
        cmd = ["$lilypond"]
        
        if self.modeCombo.currentIndex() == 0:   # preview mode
            cmd.append('-dpoint-and-click')
        elif self.modeCombo.currentIndex() == 1: # publish mode
            cmd.append('-dno-point-and-click')
        else:                                    # debug mode
            args = panelmanager.manager(self.parent()).layoutcontrol.widget().preview_options()
            cmd.extend(args)
        
        if self.deleteCheck.isChecked():
            cmd.append('-ddelete-intermediate-files')
        else:
            cmd.append('-dno-delete-intermediate-files')
        d = {
            'version': self.lilyChooser.lilyPondInfo().version,
            'resolution': self.resolutionCombo.currentText(),
            'antialias': self.antialiasSpin.value(),
        }
        cmd.append("$include")
        cmd.extend(f.options(d))
        cmd.append("$filename")
        self.commandLine.setText(' '.join(cmd))
    
    def getJob(self, document):
        """Returns a Job to start."""
        filename, includepath = documentinfo.info(document).jobinfo(True)
        i = self.lilyChooser.lilyPondInfo()
        cmd = []
        for t in self.commandLine.toPlainText().split():
            if t == '$lilypond':
                cmd.append(i.abscommand() or i.command)
            elif t == '$filename':
                cmd.append(filename)
            elif t == '$include':
                cmd.extend('-I' + path for path in includepath)
            else:
                cmd.append(t)
        j = job.Job()
        j.directory = os.path.dirname(filename)
        j.command = cmd
        if self.englishCheck.isChecked():
            j.environment['LANG'] = 'C'
        j.setTitle("{0} {1} [{2}]".format(
            os.path.basename(i.command), i.versionString(), document.documentName()))
        return j
Esempio n. 40
0
class InterfaceTab(QWidget):

    def __init__(self, parent):
        QWidget.__init__(self, parent)
        vbox = QVBoxLayout(self)
        self._parent = parent

        groupBoxExplorer = QGroupBox(self.tr("Explorer Panel:"))
        groupBoxGui = QGroupBox(self.tr("GUI Customization:"))
        groupBoxLang = QGroupBox(self.tr("Language:"))

        #Explorer
        vboxExplorer = QVBoxLayout(groupBoxExplorer)
        self._checkProjectExplorer = QCheckBox(
            self.tr("Show Project Explorer."))
        self._checkSymbols = QCheckBox(self.tr("Show Symbols List."))
        self._checkWebInspetor = QCheckBox(self.tr("Show Web Inspector."))
        self._checkFileErrors = QCheckBox(self.tr("Show File Errors."))
        vboxExplorer.addWidget(self._checkProjectExplorer)
        vboxExplorer.addWidget(self._checkSymbols)
        vboxExplorer.addWidget(self._checkWebInspetor)
        vboxExplorer.addWidget(self._checkFileErrors)
        #GUI
        self._btnCentralRotate = QPushButton(
            QIcon(resources.IMAGES['splitCPosition']), '')
        self._btnCentralRotate.setIconSize(QSize(64, 64))
        self._btnCentralRotate.setCheckable(True)
        self._btnPanelsRotate = QPushButton(
            QIcon(resources.IMAGES['splitMPosition']), '')
        self._btnPanelsRotate.setIconSize(QSize(64, 64))
        self._btnPanelsRotate.setCheckable(True)
        self._btnCentralOrientation = QPushButton(
            QIcon(resources.IMAGES['splitCRotate']), '')
        self._btnCentralOrientation.setIconSize(QSize(64, 64))
        self._btnCentralOrientation.setCheckable(True)
        gridGuiConfig = QGridLayout(groupBoxGui)
        gridGuiConfig.addWidget(self._btnCentralRotate, 0, 0)
        gridGuiConfig.addWidget(self._btnPanelsRotate, 0, 1)
        gridGuiConfig.addWidget(self._btnCentralOrientation, 0, 2)
        gridGuiConfig.addWidget(QLabel(
            self.tr("Rotate Central")), 1, 0, Qt.AlignCenter)
        gridGuiConfig.addWidget(QLabel(
            self.tr("Rotate Lateral")), 1, 1, Qt.AlignCenter)
        gridGuiConfig.addWidget(QLabel(
            self.tr("Central Orientation")), 1, 2, Qt.AlignCenter)
        #Language
        vboxLanguage = QVBoxLayout(groupBoxLang)
        vboxLanguage.addWidget(QLabel(self.tr("Select Language:")))
        self._comboLang = QComboBox()
        self._comboLang.setEnabled(False)
        vboxLanguage.addWidget(self._comboLang)
        vboxLanguage.addWidget(QLabel(self.tr('Requires restart...')))

        #Load Languages
#        self.thread = ThreadLangs()
#        self.connect(self.thread, SIGNAL("finished()"), self.load_langs)
#        self.thread.start()
        self._load_langs()    # until the thread is working

        #Settings
        self._checkProjectExplorer.setChecked(
            settings.SHOW_PROJECT_EXPLORER)
        self._checkSymbols.setChecked(settings.SHOW_SYMBOLS_LIST)
        self._checkWebInspetor.setChecked(settings.SHOW_WEB_INSPECTOR)
        self._checkFileErrors.setChecked(settings.SHOW_ERRORS_LIST)
        #ui layout
        self._btnCentralRotate.setChecked(bin(settings.UI_LAYOUT)[-1] == '1')
        self._btnPanelsRotate.setChecked(bin(
            settings.UI_LAYOUT >> 1)[-1] == '1')
        self._btnCentralOrientation.setChecked(
            bin(settings.UI_LAYOUT >> 2)[-1] == '1')

        vbox.addWidget(groupBoxExplorer)
        vbox.addWidget(groupBoxGui)
        vbox.addWidget(groupBoxLang)

        #Signals
        self.connect(self._btnCentralRotate, SIGNAL('clicked()'),
            central_widget.CentralWidget().splitter_central_rotate)
        self.connect(self._btnPanelsRotate, SIGNAL('clicked()'),
            central_widget.CentralWidget().splitter_misc_rotate)
        self.connect(self._btnCentralOrientation, SIGNAL('clicked()'),
            central_widget.CentralWidget().splitter_central_orientation)

    def _load_langs(self):
#        self.disconnect(self.thread, SIGNAL("finished()"), self.load_langs)
        self._langs = file_manager.get_files_from_folder(
            resources.LANGS, '.qm')
        self._langs = ['english'] + \
            [file_manager.get_module_name(lang) for lang in self._langs]
#        if not self.thread.langs.keys() and len(self.langs) > 1:
#            self.comboLang.addItems(self.langs)
#        else:
#            self.comboLang.addItems(['english'] + self.thread.langs.keys())
        if(self._comboLang.count() > 1):
            self._comboLang.setEnabled(True)
        index = self._comboLang.findText(settings.LANGUAGE)
        self._comboLang.setCurrentIndex(index)

    def save(self):
        lang = self._comboLang.currentText()
        if lang not in self._langs:
            #TODO
#            self.parent().overlay.show()
#            core.download_lang(self.thread.langs[str(lang)])
            pass
        lang = unicode(lang)
        self._parent.overlay.hide()
        qsettings = QSettings()
        qsettings.beginGroup('preferences')
        qsettings.beginGroup('interface')
        qsettings.setValue('showProjectExplorer',
            self._checkProjectExplorer.isChecked())
        settings.SHOW_PROJECT_EXPLORER = self._checkProjectExplorer.isChecked()
        if settings.SHOW_PROJECT_EXPLORER:
            explorer_container.ExplorerContainer().add_tab_projects()
        else:
            explorer_container.ExplorerContainer().remove_tab_projects()
        qsettings.setValue('showSymbolsList', self._checkSymbols.isChecked())
        settings.SHOW_SYMBOLS_LIST = self._checkSymbols.isChecked()
        if settings.SHOW_SYMBOLS_LIST:
            explorer_container.ExplorerContainer().add_tab_symbols()
        else:
            explorer_container.ExplorerContainer().remove_tab_symbols()
        qsettings.setValue('showWebInspector',
            self._checkWebInspetor.isChecked())
        settings.SHOW_WEB_INSPECTOR = self._checkWebInspetor.isChecked()
        if settings.SHOW_WEB_INSPECTOR:
            explorer_container.ExplorerContainer().add_tab_inspector()
        else:
            explorer_container.ExplorerContainer().remove_tab_inspector()
        qsettings.setValue('showErrorsList',
            self._checkFileErrors.isChecked())
        settings.SHOW_ERRORS_LIST = self._checkFileErrors.isChecked()
        if settings.SHOW_ERRORS_LIST:
            explorer_container.ExplorerContainer().add_tab_errors()
        else:
            explorer_container.ExplorerContainer().remove_tab_errors()
        #ui layout
        uiLayout = 1 if self._btnCentralRotate.isChecked() else 0
        uiLayout += 2 if self._btnPanelsRotate.isChecked() else 0
        uiLayout += 4 if self._btnCentralOrientation.isChecked() else 0
        qsettings.setValue('uiLayout', uiLayout)
        qsettings.setValue('language', lang)
        lang = unicode(lang + '.qm')
        settings.LANGUAGE = os.path.join(resources.LANGS, lang)
        qsettings.endGroup()
        qsettings.endGroup()
Esempio n. 41
0
class PDFWidget(QWidget):
    scaleFactors = [0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0]
    scalePercents = ["25%", "50%", "75%", "100%", "125%", "150%", "200%"]

    def __init__(self):
        QWidget.__init__(self)
        self.hboxLayout = QVBoxLayout()
        self.setLayout(self.hboxLayout)
        self.setMenu()
        self.setPDFLabelScrollArea()

        self.connect(self.pageLineEdit, SIGNAL("valueChanged(int)"),
                     self.pdfLabel.setPage)
        self.connect(self.pdfLabel, SIGNAL("pageChanged"),
                     self.pageLineEdit.setPageNumberValue)
        self.connect(self.pdfLabel, SIGNAL("pageChanged"), self.scrollToTop)

        self.connect(self.scaleComboBox, SIGNAL("currentIndexChanged(int)"),
                     self.scaleDocument)

        self.connect(self.searchLineEdit, SIGNAL("returnPressed()"),
                     self.searchDocument)
        self.connect(self.findButton, SIGNAL("clicked()"), self.searchDocument)
        self.connect(self.clearButton, SIGNAL("clicked()"),
                     self.pdfLabel.setPage)
        self.connect(self.searchLineEdit, SIGNAL("textChanged(QString)"),
                     self.checkSearchText)
        self.connect(self, SIGNAL("setDocument"), self.setDocument)

    def setMenu(self):
        self.menuLayout = QHBoxLayout()
        self.hboxLayout.addLayout(self.menuLayout)
        self.pageLineEdit = PageLineEdit()
        self.pageLineEdit.setEnabled(False)
        self.menuLayout.addLayout(self.pageLineEdit)

        spacer = QSpacerItem(20, 20, QSizePolicy.Expanding,
                             QSizePolicy.Minimum)
        self.menuLayout.addItem(spacer)

        self.searchLayout = QHBoxLayout()
        self.menuLayout.addLayout(self.searchLayout)
        self.searchLabel = QLabel(self.tr("Search:"))
        self.searchLabel.setTextFormat(Qt.AutoText)
        self.searchLayout.addWidget(self.searchLabel)
        self.searchLineEdit = QLineEdit()
        self.searchLineEdit.setEnabled(False)
        self.searchLabel.setBuddy(self.searchLineEdit)
        self.searchLayout.addWidget(self.searchLineEdit)
        self.searchComboBox = QComboBox()
        self.searchComboBox.setEnabled(False)
        self.searchComboBox.insertItems(0, ["Forwards", "Backwards"])
        self.searchLayout.addWidget(self.searchComboBox)
        self.findButton = QPushButton("Find")
        self.findButton.setEnabled(False)
        self.searchLayout.addWidget(self.findButton)
        self.clearButton = QPushButton("Clear")
        self.clearButton.setEnabled(False)
        self.searchLayout.addWidget(self.clearButton)

        spacer = QSpacerItem(20, 20, QSizePolicy.Expanding,
                             QSizePolicy.Minimum)
        self.menuLayout.addItem(spacer)

        self.scaleLabel = QLabel("Scale:")
        self.menuLayout.addWidget(self.scaleLabel)
        self.scaleComboBox = QComboBox()
        self.scaleComboBox.setEnabled(False)
        self.scaleComboBox.insertItems(0, self.scalePercents)
        self.scaleComboBox.setCurrentIndex(3)
        self.scaleLabel.setBuddy(self.scaleComboBox)
        self.menuLayout.addWidget(self.scaleComboBox)

    def setPDFLabelScrollArea(self):
        self.pdfLabel = PDFLabel(self)
        self.scrollArea = QScrollArea()
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setAlignment(Qt.AlignCenter)
        self.scrollArea.setWidget(self.pdfLabel)
        self.hboxLayout.addWidget(self.scrollArea)

    def scrollToTop(self, value):
        self.scrollArea.verticalScrollBar().setValue(0)

    def setDocument(self, data):
        if self.pdfLabel.setDocument(data):
            self.searchLineEdit.setEnabled(True)
            self.searchComboBox.setEnabled(True)
            self.findButton.setEnabled(True)
            self.clearButton.setEnabled(True)
            self.scaleComboBox.setEnabled(True)
            self.pageLineEdit.setEnabled(True)
            self.pageLineEdit.setPageNumberValue(1)
            self.pageLineEdit.setMaximumPageNumber(
                self.pdfLabel.document().numPages())

    def setError(self, errorMessage):
        self.pdfLabel.setError(errorMessage)

    def setMessage(self, message):
        self.pdfLabel.setText(message)

    def checkSearchText(self, text):
        if text == "":
            self.pdfLabel.setPage()

    def scaleDocument(self, index):
        self.pdfLabel.setScale(self.scaleFactors[index])

    def searchDocument(self):
        if self.searchComboBox.currentIndex() == 0:
            location = self.pdfLabel.searchForwards(self.searchLineEdit.text())
        else:
            location = self.pdfLabel.searchBackwards(
                self.searchLineEdit.text())

        target = self.pdfLabel.matrix().mapRect(location).center().toPoint()
        self.scrollArea.ensureVisible(target.x(), target.y())
Esempio n. 42
0
class Sidebar(QWidget):
    """
    +----------------------+
    |        Results       |
    +======================+
    |                      |
    |  Name = Main         |
    |                      |
    |  +----------------+  |
    |  | ResultsWindow  |  |
    |  +----------------+  |
    |  |                |  |
    |  |  +----------+  |  |
    |  |  | - a      |  |  |
    |  |  |  - b1    |  |  |
    |  |  |  - b2    |  |  |
    |  |  |  - b3    |  |  |
    |  |  +----------+  |  |
    |  |                |  |
    |  +----------------+  |
    |                      |
    |                      |
    |         Apply        |
    +----------------------+

    For Nastran:
      - a: Subcase 1
       - b1. Displacement
       - b2. Stress
       - b3. Strain

    For Cart3d:
      - a1. Geometry
       - b1. ElementID
       - b2. Region
      - a2. Results Case 1
       - b1. U
       - b2. V
       - b3. W

    +--------------+
    |  Sub-Result  | (pulldown)
    +==============+
    | - a1         |
    | - a2         |
    | - a3         |
    | - a4         |
    +--------------+

    For Nastran:
      - a1: Displacement X
      - a2. Displacement Y
      - a3. Displacmenet Z
      - a4. Displacmenet Mag

    For Cart3d:
      - NA (Greyed Out)

    +----------------+
    |     Plot       | (pulldown)
    +================+
    | - Fringe       |
    | - Marker       |
    | - Displacement |
    +----------------+
    - Cart3d -> Fringe (disabled)


    +---------------+
    | Scale Display | (text box)
    +===============+
    | 0 < x < 1000  | (not for fringe)
    +---------------+

    +--------------+
    |   Location   | (pulldown)
    +==============+
    | - nodal      |
    | - centroidal |
    +--------------+
    (disabled)

    +------------------+
    |  Complex Method  | (pulldown)
    +==================+
    | - real           | (usually set to real and disabled)
    | - imag           |
    | - mag            |
    | - phase          |
    | - max over phase |
    +------------------+

    +--------------+
    |    Derive    | (pulldown; only for nodal results)
    +==============+
    | - derive/avg |  (default?)
    | - avg/derive |
    +--------------+
    """
    def __init__(self, parent, debug=False):
        """creates the buttons in the Sidebar, not the actual layout"""
        QWidget.__init__(self)
        self.parent = parent
        self.debug = debug

        name = 'main'
        data = []
        data = [
            ("Alice", None, [
                ("Keys", 1, []),
                ("Purse", 2, [
                    ("Cellphone", 3, [])
                    ])
                ]),
            ("Bob", None, [
                ("Wallet", None, [
                    ("Credit card", 4, []),
                    ("Money", 5, [])
                    ])
                ]),
            ]

        choices = ['keys2', 'purse2', 'cellphone2', 'credit_card2', 'money2']
        self.result_case_window = ResultsWindow('Case/Results', data, choices)

        data = [
            ('A', 1, []),
            #('B', 2, []),
            #('C', 3, []),
        ]
        self.result_data_window = ResultsWindow('Method', data, choices)
        self.result_data_window.setVisible(False)

        self.show_pulldown = False
        if self.show_pulldown:
            combo_options = ['a1', 'a2', 'a3']
            self.pulldown = QComboBox()
            self.pulldown.addItems(choices)
            self.pulldown.activated[str].connect(self.on_pulldown)

        self.apply_button = QPushButton('Apply', self)
        self.apply_button.clicked.connect(self.on_apply)

        self.name = str(name)
        self.names = [name]
        self.name_label = QLabel("Name:")
        self.name_pulldown = QComboBox()
        self.name_pulldown.addItem(name)
        self.name_pulldown.setDisabled(True)
        self.name_pulldown.currentIndexChanged.connect(self.on_update_name)

        self.setup_layout()

    def setup_layout(self):
        """creates the sidebar visual layout"""
        vbox = QVBoxLayout()
        hbox = QHBoxLayout()

        hbox.addWidget(self.name_label)
        hbox.addWidget(self.name_pulldown)
        vbox.addLayout(hbox)
        vbox.addWidget(self.result_case_window)
        vbox.addWidget(self.result_data_window)
        if self.show_pulldown:
            vbox.addWidget(self.pulldown)
        vbox.addWidget(self.apply_button)
        self.setLayout(vbox)

        self.clear_data()

    def update_method(self, method):
        if isinstance(method, string_types):
            datai = self.result_data_window.data[0]
            self.result_data_window.data[0] = (method, datai[1], datai[2])
            print('method=%s datai=%s' % (method, datai))
            self.result_data_window.update_data(self.result_data_window.data)
        else:
            return
             # pragma: no cover
            datai = self.result_data_window.data[0]

    def get_form(self):
        return self.result_case_window.data

    def update_results(self, data, name):
        """
        Updates the sidebar

        Parameters
        ----------
        data : List[tuple]
            the form data
        name : str
            the name that goes at the side
        """
        name = str(name)
        if name in self.names:
            i = self.names.index(name)
            self.name_pulldown.setCurrentIndex(i)
        else:
            self.name_pulldown.addItem(name)
            self.names.append(name)
        if len(self.names) >= 2:
            self.name_pulldown.setEnabled(True)
        self.name = name

        self.result_case_window.update_data(data)
        self.apply_button.setEnabled(True)

    def update_methods(self, data):
        """the methods is a hidden box"""
        self.result_data_window.update_data(data)
        self.apply_button.setEnabled(True)

    def clear_data(self):
        self.result_case_window.clear_data()
        self.result_data_window.clear_data()
        self.apply_button.setEnabled(False)

    def on_pulldown(self, event):
        print('pulldown...')

    def on_update_name(self, event):
        """user clicked the pulldown"""
        name = str(self.name_pulldown.currentText())
        data = self.parent._get_sidebar_data(name)
        #self.result_case_window.update_data(data)

    def on_apply(self, event):
        data = self.result_case_window.data
        valid_a, keys_a = self.result_case_window.treeView.get_row()

        data = self.result_data_window.data
        valid_b, keys_b = self.result_data_window.treeView.get_row()
        if valid_a and valid_b:
            if self.debug:  # pragma: no cover
                print('  rows1 = %s' % self.result_case_window.treeView.old_rows)
                print('        = %s' % str(keys_a))
                print('  rows2 = %s' % self.result_data_window.treeView.old_rows)
                print('        = %s' % str(keys_b))
            else:
                self.update_vtk_window(keys_a, keys_b)

    def update_vtk_window(self, keys_a, keys_b):
        if 0:  # pragma: no cover
            print('keys_a = %s' % str(keys_a))
            for i, key in enumerate(self.parent.case_keys):
                if key[1] == keys_a[0]:
                    break
            print('*i=%s key=%s' % (i, str(key)))
            #self.parent.update_vtk_window_by_key(i)
            result_name = key[1]
            #self.parent.cycle_results_explicit(result_name=result_name, explicit=True)
            #j = self.parent._get_icase(result_name)
            #j = i
        i = keys_a
        result_name = None
        self.parent._set_case(result_name, i, explicit=True)
    def toolTypeSelected(self, index):
        #print "Got a new selection"
        #print self.comboBox.itemText(index)

        self.typeSelection = str(self.comboBox.itemText(index))
        for testw in self.test_widget:
            self.vboxlayout.removeWidget(testw)
            testw.hide()
        self.tooltypearray = []
        self.test_widget = []
        self.test_text = []
        self.test_line = []

        # The tool_config will always have tool_config name
        self.tooltypearray.append(["Tool Config Name","tool_config",""])

        # Now look up the selected connection type and present to the user...
        # First we start at the tool_library
        tool_name = str(self.typeSelection)
        tool_node = self.tool_nodes[tool_name]
        for param_node in tool_node.find('params'):
            type_val = param_node.get('param_type')
            default_val = param_node.text or ''
            self.tooltypearray.append([param_node.get('name'), type_val, default_val])

        for i, param in enumerate(self.tooltypearray):
            # print "Key: %s , Val: %s" % (param[0],param[1])
            paramName = str(param[0] or '').strip()
            type_val = str(param[1] or '').strip()
            default_val = str(param[2] or '').strip()

            if (i==0):
                widgetTemp = QFrame(self.variableBox)
                widgetTemp.setFrameStyle(QFrame.Panel | QFrame.Raised)
                widgetTemp.setLineWidth(2)
            else:
                widgetTemp = QWidget(self.variableBox)
            widgetTemp.setObjectName(QString("test_widget").append(QString(i)))
            self.test_widget.append(widgetTemp)
            hlayout = QHBoxLayout(widgetTemp)
            self.hboxlayout.append(hlayout)
            hlayout.setMargin(4)
            hlayout.setSpacing(4)
            hlayout.setObjectName(QString("hboxlayout").append(QString(i)))
            test_text = QLabel(widgetTemp)
            self.test_text.append(test_text)
            test_text.setObjectName(QString("test_text").append(QString(i)))
            if type_val == "Required":
                palette = test_text.palette()
                palette.setColor(QPalette.WindowText,Qt.red)
                test_text.setPalette(palette)
            test_text.setText(paramName)
            test_text_type = QLabel(widgetTemp)
            self.test_text_type.append(test_text_type)
            test_text_type.setObjectName(QString("test_text_type").append(QString(i)))
            paramName = type_val
            test_text_type.setText(QString("(").append(paramName).append(QString(")")))
            hlayout.addWidget(test_text)
            hlayout.addWidget(test_text_type)
            if type_val == 'db_connection_hook':
                test_line = QComboBox(widgetTemp)
                db_connection_choices = get_db_connection_names()
                for i in db_connection_choices:
                    test_line.addItem(QString(i))
                self.test_line.append(test_line)
                test_line.setEnabled(True)
                test_line.setMinimumSize(QSize(200,0))
                test_line.setObjectName(QString("test_line").append(QString(i)))
            else:
                test_line = QLineEdit(widgetTemp)
                self.test_line.append(test_line)
                test_line.setEnabled(True)
                test_line.setMinimumSize(QSize(200,0))
                test_line.setObjectName(QString("test_line").append(QString(i)))
#            test_line = QLineEdit(widgetTemp)
#            self.test_line.append(test_line)
#            test_line.setEnabled(True)
#            test_line.setMinimumSize(QSize(200,0))
#            test_line.setObjectName(QString("test_line").append(QString(i)))
#            test_line.setText(QString(""))
            hlayout.addWidget(test_line)
            self.vboxlayout.addWidget(widgetTemp)
    def setup_left_panel(self):
        """Setup the UI for left panel.

        Generate all exposure, combobox, and edit button.
        """
        hazard = self.parent.step_kw_subcategory.selected_subcategory()
        left_panel_heading = QLabel(tr('Classifications'))
        left_panel_heading.setFont(big_font)
        self.left_layout.addWidget(left_panel_heading)

        inner_left_layout = QGridLayout()

        row = 0
        for exposure in exposure_all:
            special_case = False
            # Filter out unsupported exposure for the hazard
            if exposure in hazard['disabled_exposures']:
                # Remove from the storage if the exposure is disabled
                if self.layer_mode == layer_mode_continuous:
                    if exposure['key'] in self.thresholds:
                        self.thresholds.pop(exposure['key'])
                else:
                    if exposure['key'] in self.value_maps:
                        self.value_maps.pop(exposure['key'])
                continue
            # Trick for EQ raster for population #3853
            if exposure == exposure_population and hazard == hazard_earthquake:
                if is_raster_layer(self.parent.layer):
                    if self.layer_mode == layer_mode_continuous:
                        self.use_default_thresholds = True
                        special_case = True
                        # Set classification for EQ Raster for Population
                        self.thresholds[exposure_population['key']] = {
                            earthquake_mmi_scale['key']: {
                                'classes': default_classification_thresholds(
                                    earthquake_mmi_scale),
                                'active': True
                            }
                        }

            # Add label
            # Hazard on Exposure Classifications
            label = tr(
                '{hazard_name} on {exposure_name} Classifications').format(
                hazard_name=hazard['name'],
                exposure_name=exposure['name']
            )
            exposure_label = QLabel(label)

            # Add combo box
            exposure_combo_box = QComboBox()
            hazard_classifications = hazard.get('classifications')
            exposure_combo_box.addItem(tr('No classifications'))
            exposure_combo_box.setItemData(
                0, None, Qt.UserRole)

            current_index = 0
            i = 0
            # Iterate through all available hazard classifications
            for hazard_classification in hazard_classifications:
                # Skip if the classification is not for the exposure
                if 'exposures' in hazard_classification:
                    if exposure not in hazard_classification['exposures']:
                        continue
                exposure_combo_box.addItem(hazard_classification['name'])
                exposure_combo_box.setItemData(
                    i + 1, hazard_classification, Qt.UserRole)
                if self.layer_mode == layer_mode_continuous:
                    current_hazard_classifications = self.thresholds.get(
                        exposure['key'])
                else:
                    current_hazard_classifications = self.value_maps.get(
                        exposure['key'])
                if current_hazard_classifications:
                    current_hazard_classification = \
                        current_hazard_classifications.get(
                            hazard_classification['key'])
                    if current_hazard_classification:
                        is_active = current_hazard_classification.get('active')
                        if is_active:
                            current_index = i + 1
                i += 1
            # Set current classification
            exposure_combo_box.setCurrentIndex(current_index)

            # Add edit button
            exposure_edit_button = QPushButton(tr('Edit'))

            # For special case. Raster EQ on Population.
            if special_case:
                mmi_index = exposure_combo_box.findText(
                    earthquake_mmi_scale['name'])
                exposure_combo_box.setCurrentIndex(mmi_index)
                exposure_combo_box.setEnabled(False)
                exposure_edit_button.setEnabled(False)
                tool_tip_message = tr(
                    'InaSAFE use default classification for Raster Earthquake '
                    'hazard on population.')
                exposure_label.setToolTip(tool_tip_message)
                exposure_combo_box.setToolTip(tool_tip_message)
                exposure_edit_button.setToolTip(tool_tip_message)

            else:
                if current_index == 0:
                    # Disable if there is no classification chosen.
                    exposure_edit_button.setEnabled(False)
                exposure_edit_button.clicked.connect(
                    partial(self.edit_button_clicked,
                        edit_button=exposure_edit_button,
                        exposure_combo_box=exposure_combo_box,
                        exposure=exposure))
                exposure_combo_box.currentIndexChanged.connect(
                    partial(
                        self.classifications_combo_box_changed,
                        exposure=exposure,
                        exposure_combo_box=exposure_combo_box,
                        edit_button=exposure_edit_button))

            # Arrange in layout
            inner_left_layout.addWidget(exposure_label, row, 0)
            inner_left_layout.addWidget(exposure_combo_box, row, 1)
            inner_left_layout.addWidget(exposure_edit_button, row, 2)

            # Adding to step's attribute
            self.exposures.append(exposure)
            self.exposure_combo_boxes.append(exposure_combo_box)
            self.exposure_edit_buttons.append(exposure_edit_button)
            self.exposure_labels.append(label)
            if special_case:
                self.special_case_index = len(self.exposures) - 1

            row += 1

        self.left_layout.addLayout(inner_left_layout)
        # To push the inner_left_layout up
        self.left_layout.addStretch(1)
Esempio n. 45
0
 def createGUIElements(self):
     ''' Build the GUI based on the parameters for the tool '''
     for i, param in enumerate(self.tooltypearray):
         # print 'creatgui element %d, %s' %(i, param)
         #Swap in the passed params if they exist... loop through each passed
         #param and see if it matches... if so swap it in
         if self.optional_params.has_key(str(param[0])):
             param[2] = self.optional_params[str(param[0])]
         #print "Key: %s , Val: %s" % (param[0],param[1])
         widgetTemp = QWidget(self.variableBox)
         widgetTemp.setObjectName(QString("test_widget").append(QString(i)))
         self.test_widget.append(widgetTemp)
         hlayout = QHBoxLayout(widgetTemp)
         self.hboxlayout.append(hlayout)
         hlayout.setMargin(4)
         hlayout.setSpacing(4)
         hlayout.setObjectName(QString("hboxlayout").append(QString(i)))
         test_text = QLabel(widgetTemp)
         self.test_text.append(test_text)
         test_text.setObjectName(QString("test_text").append(QString(i)))
         paramName = param[0].strip()
         if param[2].strip() == "Required":
             palette = test_text.palette()
             palette.setColor(QPalette.WindowText, Qt.red)
             test_text.setPalette(palette)
         test_text.setText(paramName)
         test_text_type = QLabel(widgetTemp)
         self.test_text_type.append(test_text_type)
         test_text_type.setObjectName(
             QString("test_text_type").append(QString(i)))
         paramName = param[1].strip()
         test_text_type.setText(
             QString("(").append(paramName).append(QString(")")))
         hlayout.addWidget(test_text)
         hlayout.addWidget(test_text_type)
         if param[1] == 'db_connection_hook':
             test_line = QComboBox(widgetTemp)
             db_connection_choices = get_db_connection_names()
             for i in db_connection_choices:
                 test_line.addItem(QString(i))
             self.test_line.append(test_line)
             test_line.setEnabled(True)
             test_line.setMinimumSize(QSize(200, 0))
             test_line.setObjectName(
                 QString("test_line").append(QString(i)))
             index = test_line.findText(param[2], Qt.MatchExactly)
             test_line.setCurrentIndex(index)
         else:
             test_line = QLineEdit(widgetTemp)
             self.test_line.append(test_line)
             test_line.setEnabled(True)
             test_line.setMinimumSize(QSize(200, 0))
             test_line.setObjectName(
                 QString("test_line").append(QString(i)))
             test_line.setText(QString(param[2]))
         hlayout.addWidget(test_line)
         # If we have a dir_path or file_path add a select button
         if (paramName == QString('dir_path')) or (paramName
                                                   == QString('file_path')):
             pbnSelect = QPushButton(widgetTemp)
             pbnSelect.setObjectName(
                 QString('pbnSelect').append(QString(i)))
             pbnSelect.setText(QString("Select..."))
             pbnSelectDelegate = FileDialogSignal(typeName=paramName,
                                                  param=test_line)
             QObject.connect(
                 pbnSelectDelegate.o,
                 SIGNAL("buttonPressed(PyQt_PyObject,PyQt_PyObject)"),
                 self.on_pbnSelect_released)
             QObject.connect(pbnSelect, SIGNAL("released()"),
                             pbnSelectDelegate.relayButtonSignal)
             self.test_line_delegates.append(pbnSelectDelegate)
             self.test_line_buttons.append(pbnSelect)
             hlayout.addWidget(pbnSelect)
         self.vboxlayout.addWidget(widgetTemp)
         self.adjustSize()
     # Jesse adding help text from opusHelp
     tool_path = self.optional_params.get('tool_path', '')
     try:
         exec_stmt = 'from %s.%s import opusHelp' % (tool_path,
                                                     self.module_name)
         exec exec_stmt
         help = QString(opusHelp())
         self.toolhelpEdit.insertPlainText(help)
     except Exception, e:
         help = 'could not find opusHelp function in tool module'
         self.toolhelpEdit.insertPlainText(help)
Esempio n. 46
0
class EditLigneViewWidget(QDialog, FWidget):
    def __init__(self, table_p, report, parent, *args, **kwargs):
        QDialog.__init__(self, parent, *args, **kwargs)

        self.setWindowTitle(u"Modification")
        self.table_p = table_p
        self.rpt = report
        self.parent = parent

        self.out_op = True
        if self.rpt.type_ == Report.E:
            self.out_op = False

        self.selling_price_field = IntLineEdit(unicode(self.rpt.selling_price))
        self.cost_buying_field = IntLineEdit(unicode(self.rpt.cost_buying))
        self.qty_field = IntLineEdit(unicode(self.rpt.qty))

        self.date_field = FormatDate(QDate(self.rpt.date))
        self.date_field.setEnabled(False)

        butt = Button(u"Mise à jour")
        butt.clicked.connect(self.edit_report)
        cancel_but = Button(u"Annuler")
        cancel_but.clicked.connect(self.cancel)

        # Combobox widget
        i = 0
        self.liste_type = [Report.E, Report.S]
        self.box_type = QComboBox()
        self.box_type.setEnabled(False)
        for index in xrange(0, len(self.liste_type)):
            ty = self.liste_type[index]
            if ty == self.rpt.type_:
                i = index
            sentence = u"%(ty)s" % {'ty': ty}
            self.box_type.addItem(sentence, ty)
            self.box_type.setCurrentIndex(i)
        # Combobox widget
        # self.liste_store = Store.order_by(desc(Store.id)).all()
        # self.box_mag = QComboBox()
        # for index in xrange(0, len(self.liste_store)):
        #     op = self.liste_store[index]
        #     sentence = u"%(name)s" % {'name': op.name}
        #     self.box_mag.addItem(sentence, QVariant(op.id))
        # Combobox widget

        self.liste_product = Product.all()
        self.box_prod_field = QComboBox()
        self.box_prod_field.setEnabled(False)

        for index in xrange(0, len(self.liste_product)):
            prod = self.liste_product[index]
            if prod.name == self.rpt.product.name:
                i = index
            sentence = u"%(name)s" % {'name': prod.name}
            self.box_prod_field.addItem(sentence, prod.id)
            self.box_prod_field.setCurrentIndex(i)
        vbox = QVBoxLayout()
        formbox = QFormLayout()
        # editbox.addWidget(FormLabel((_(u"Store"))), 0, 1)
        # editbox.addWidget(self.box_mag, 1, 1)
        formbox.addRow(FormLabel(u"Type"), FormLabel(self.rpt.type_))
        formbox.addRow(FormLabel(u"Désignation"), self.box_prod_field)
        formbox.addRow(FormLabel(u"Quantité"), self.qty_field)
        formbox.addRow(FormLabel("Prix d'achat"), self.cost_buying_field)
        formbox.addRow(FormLabel("Prix vente"), self.selling_price_field)
        formbox.addRow(FormLabel(u"Date"), self.date_field)
        formbox.addRow(butt, cancel_but)
        vbox.addLayout(formbox)
        self.setLayout(vbox)

    def cancel(self):
        self.close()

    def edit_report(self):
        # type_ = self.box_type.currentIndex()
        # product = self.liste_product[self.box_prod.currentIndex()]
        if check_is_empty(self.qty_field):
            return
        if check_is_empty(self.selling_price_field):
            return
        if check_is_empty(self.cost_buying_field):
            return
        report = self.rpt
        report.qty = unicode(self.qty_field.text())
        report.selling_price = unicode(self.selling_price_field.text())
        report.cost_buying = unicode(self.cost_buying_field.text())
        try:
            report.save()
            self.cancel()
            self.table_p.refresh_()
            self.parent.Notify(u"le rapport a été mise à jour", "success")
        except Exception as e:
            self.parent.Notify(e, "error")
Esempio n. 47
0
class NodeList(QWidget):
    def __init__(self,  parent, mainWindow, dockBrowser):
        super(NodeList,  self).__init__(parent)
        
        self.__browsers = dockBrowser
        # Necessary
        self.type = "views"
        self.icon = QIcon(":list.png")
        self.name = ""
        self.__mainWindow = mainWindow
        self.__parent = parent
    
        # Specific
        self.currentIndexDir = None
        self.currentNodeDir = None
        
        self.g_display()
        self.initCallback(dockBrowser)

        self.loader = loader.loader()
        self.lmodules = self.loader.modules
        self.taskmanager = TaskManager()
        self.env = env.env()
        
    def g_display(self):
        self.setMinimumSize(QSize(400, 300))
        self.createSubMenu()
        self.vlayout = QVBoxLayout(self)
        self.hlayout = QHBoxLayout()
        self.vlayout.addLayout(self.hlayout)

        self.initListView()
        self.initThumbsView()
        
        self.topButton = QPushButton(self)
        self.topButton.setFixedSize(QSize(32,32))
        self.topButton.setFlat(True)
        self.topButton.setIcon(QIcon(":previous.png"))
        self.topButton.setIconSize(QSize(32,32))
        self.hlayout.addWidget(self.topButton)

        self.listButton = QPushButton(self)
        self.listButton.setFixedSize(QSize(32, 32))
        self.listButton.setFlat(True)
        self.listButton.setIcon(QIcon(":list.png"))
        self.listButton.setIconSize(QSize(32,32))
        self.hlayout.addWidget(self.listButton)

        self.thumButton = QPushButton(self)
        self.thumButton.setFixedSize(QSize(32, 32))
        self.thumButton.setFlat(True)
        self.thumButton.setIcon(QIcon(":image.png"))
        self.thumButton.setIconSize(QSize(32,32))
        self.hlayout.addWidget(self.thumButton)

        self.thumSize = QComboBox()
        self.thumSize.setMaximumWidth(100)
        self.thumSize.addItem("Small")
        self.thumSize.addItem("Medium")
        self.thumSize.addItem("Large")
        self.connect(self.thumSize, SIGNAL("currentIndexChanged(QString)"), self.sizeChanged)
        self.hlayout.addWidget(self.thumSize)


        self.thumButton.setEnabled(True)
        self.thumSize.setEnabled(False)
        self.listButton.setEnabled(False)
        
        self.comboBoxPath = NodeComboBox(self)
        self.comboBoxPath.setMinimumSize(QSize(251,32))
        self.comboBoxPath.setMaximumSize(QSize(16777215,32))
        self.hlayout.addWidget(self.comboBoxPath)
        
    def initListView(self):    
        self.ListView = ListView(self, self.__mainWindow)
	self.ListModel = ListModel(self)
        self.ListModelFilter = QSortFilterProxyModel()
        self.ListModelFilter.setDynamicSortFilter(True)
        self.ListModelFilter.setSortCaseSensitivity(Qt.CaseInsensitive)
        self.ListModelFilter.setSourceModel(self.ListModel) 
        self.ListView.setModels(self.ListModel, self.ListModelFilter)
        self.ListView.setModel(self.ListModelFilter)
        self.ListView.setSubMenu(self.submenuFile)

        self.vlayout.addWidget(self.ListView)
        
    def initThumbsView(self):
        self.ThumbsView = ThumbsView(self.__mainWindow, self)
        self.ThumbsItemModel = ThumbsItemModel(self.ThumbsView.thread)
        
        self.ThumbsView.setModels(self.ThumbsItemModel)
        self.ThumbsView.setSubMenu(self.submenuFile)
        self.vlayout.addWidget(self.ThumbsView)

    def initCallback(self, dockBrowser):
        self.connect(self.topButton, SIGNAL("clicked()"),  self.moveToTop)

        self.connect(self.listButton, SIGNAL("clicked()"),  self.listActivated)
        self.connect(self.thumButton, SIGNAL("clicked()"),  self.thumbActivated)

        self.connect(self.comboBoxPath, SIGNAL("currentIndexChanged(const QString & )"),  self.comboBoxPathChanged)
        self.connect(ConnectorCallback.instance, SIGNAL("reload"), self.reload,  Qt.BlockingQueuedConnection)        
        self.connect(dockBrowser.treeView, SIGNAL("changeDirectory"), self.loadFolder)
        self.connect(dockBrowser.treeView, SIGNAL("reloadNodeView"), self.reload)
        dockBrowser.treeView.connect(self, SIGNAL("setIndexAndExpand"), dockBrowser.treeView.setIndexAndExpand)
        dockBrowser.treeView.connect(self, SIGNAL("setIndex"), dockBrowser.treeView.setCurrentIndexForChild)
        
    def moveToTop(self):
        if self.currentIndexDir <> None :
            index = self.__browsers.treeItemModel.indexWithNode(self.currentNodeDir)
            parent = self.__browsers.treeItemModel.parent(index)
            if parent:
                self.emit(SIGNAL("setIndexAndExpand"), self, parent)
                self.currentIndexDir = parent
            else :
                self.emit(SIGNAL("setIndexAndExpand"), self, index)
                self.currentIndexDir  = index
    
    def comboBoxPathChanged(self, text):
        node = self.comboBoxPath.getNode(str(text))    
        if node.this == self.currentNodeDir.this :
            return
        index = self.comboBoxPath.getBrowserIndex(str(text))
        self.loadFolder(node, index)
        self.emit(SIGNAL("setIndex"), self, self.currentIndexDir)
  
#    def comboBoxModeChanged(self, index):
#        if index == 0 :
#            self.ListView.setVisible(True)
#            self.ThumbsView.setVisible(False)
#        else :
#            self.ListView.setVisible(False)
#            self.ThumbsView.setVisible(True)
#        self.reloadChangedView()
        
    def listActivated(self):
        self.ListView.setVisible(True)
        self.ThumbsView.setVisible(False)
        self.reloadChangedView()

        #Desactivate thumb buttons
        self.thumButton.setEnabled(True)
        self.thumSize.setEnabled(False)
        self.listButton.setEnabled(False)

    def thumbActivated(self):
        self.ListView.setVisible(False)
        self.ThumbsView.setVisible(True)
        self.reloadChangedView()

        self.thumButton.setEnabled(False)
        self.thumSize.setEnabled(True)
        self.listButton.setEnabled(True)

    def reloadChangedView(self):
        if not self.visibleRegion().isEmpty() :
            view = self.viewVisible()
            if view.getModel().currentNodeDir is not None and view.getModel().currentNodeDir.this == self.currentNodeDir.this :
                return
            self.loadFolder(self.currentNodeDir, self.currentIndexDir, 1)
  
    # Specific type views
    def loadFolder(self,  node, indexFolder = None,  force = None):
        if node is None :
            return
        if self.currentNodeDir is not None :
            if force is None and self.currentNodeDir.this == node.this:
                return
        if force <> 2 and str(self) <> str(self.__browsers.getChild()) :
            return
            
        self.currentIndexDir = indexFolder
        self.currentNodeDir = node
        self.comboBoxPath.addPathAndSelect(node, indexFolder)
        
        if self.ThumbsView.isVisible() :
            self.ThumbsView.loadFolder(node, force)
        if self.ListView.isVisible() or force == 2:
            self.ListView.loadFolder(node)
        if force == 2 :
            self.emit(SIGNAL("setIndexAndExpand"), self, self.currentIndexDir)
    
    def setChildSelected(self):
        if str(self.__browsers.getChild()) <> str(self) :
            index = self.__browsers.treeItemModel.indexWithNode(self.currentNodeDir)
            self.emit(SIGNAL("setIndexAndExpand"), self, index)

    def getListCurrentItems(self):
        view = self.viewVisible()
        return view.getListCurrentItems()
    
    def getListCurrentNode(self):
        view = self.viewVisible()
        return view.getListCurrentNode()
    
    def reload(self):
        self.loadFolder(self.currentNodeDir, self.currentIndexDir, 1)
    
    def refreshIndexBrowser(self):
        self.emit(SIGNAL("setIndex"), self, self.currentIndexDir)
        
    def viewVisible(self):
        if self.ListView.isVisible() :
            return self.ListView
        if self.ThumbsView.isVisible() :
            return self.ThumbsView
        return self.ListView

    def changeDirectoryBrowser(self, node):
        dockNodeTree = self.__mainWindow.dockNodeTree
        currentIndex = dockNodeTree.treeView.selectionModel().currentIndex()
        if currentIndex is None :
            return
        currentItem = dockNodeTree.treeItemModel.getItem(currentIndex)
        #if not node.next.empty():
        newcurrent = currentItem.childWithNode(node)
        if not newcurrent:
            return
        #            
        index = dockNodeTree.treeItemModel.index(newcurrent.childNumber(),  0,  currentIndex)
        self.emit(SIGNAL("setIndexAndExpand"), self, index)
        #    #self.loadFolder(node, index)

    ###############
    ## CONTEXT  MENU ##
    ###############
    def createSubMenu(self):
        self.extractor = Extractor(self.__mainWindow)
        self.connect(self.extractor, SIGNAL("filled"), self.launchExtract)
	self.submenuFile = QMenu()
        self.submenuFile.addAction(QIcon(":exec.png"),  "Open", self.openDefault, "Listview")
        self.menuModules = self.submenuFile.addMenu(QIcon(":exec.png"),  "Open With")
        self.menuTags = MenuTags(self, self.__mainWindow, self.getListCurrentNode)
        self.submenuFile.addSeparator()
        self.submenuFile.addAction(QIcon(":hexedit.png"), QApplication.translate("ListView", "Hexeditor", None, QApplication.UnicodeUTF8), self.launchHexedit, "Listview")
        self.submenuFile.addAction(QIcon(":extract.png"), QApplication.translate("ListView", "Extract", None, QApplication.UnicodeUTF8), self.extractNodes, "Listview")
        self.submenuFile.addSeparator()
        self.submenuFile.addAction(QIcon(":info.png"), QApplication.translate("ListView", "Property", None, QApplication.UnicodeUTF8), self.propertyNodes, "Listview")

    def launchExtract(self):
        res = self.extractor.getArgs()
        arg = self.env.libenv.argument("gui_input")
        lnodes = self.env.libenv.ListNode()
        lnodes.thisown = 0
        for node in res["nodes"]:
            lnodes.append(node)
        arg.thisown = 0
        arg.add_path("syspath", str(res["path"]))
        arg.add_lnode("files", lnodes)
        arg.add_bool("recursive", int(res["recurse"]))
        self.taskmanager.add("extract", arg, ["thread", "gui"])


    def extractNodes(self):
        self.extractor.launch(self.getListCurrentNode())

    def openDefault(self):
      nodes = self.getListCurrentNode()
      for node in nodes:
        arg = self.env.libenv.argument("gui_input")
        arg.thisown = 0 
        ft = FILETYPE()
        try:
          mod = ft.findcompattype(node)[0]
          if self.lmodules[mod]:
            conf = self.lmodules[mod].conf
            cdl = conf.descr_l
            for a in cdl:
              if a.type == "node":
                 arg.add_node(a.name, node)
          self.taskmanager.add(mod, arg, ["thread", "gui"])       
        except IndexError: 
          arg.add_node("file", node)
          self.taskmanager.add("hexedit", arg, ["thread", "gui"])        
 
    def launchHexedit(self):
        nodes = self.getListCurrentNode()
        for node in nodes:
            arg = self.env.libenv.argument("gui_input")
            arg.thisown = 0
            arg.add_node("file", node)
            self.taskmanager.add("hexedit", arg, ["thread", "gui"])

    def propertyNodes(self):
        if not self.__mainWindow.QPropertyDialog.isVisible():
            self.__mainWindow.QPropertyDialog.fillInfo(self.currentNodeDir, self.getListCurrentNode())
            iReturn = self.__mainWindow.QPropertyDialog.exec_()
            self.__mainWindow.QPropertyDialog.removeAttr()
        else:
            QMessageBox.critical(self, "Erreur", u"This box is already open")


# CALLBACK

    def sizeChanged(self, string):
        if string == "Small":
            self.ThumbsView.configure(64, 64)
        elif string == "Medium":
            self.ThumbsView.configure(96, 96)
        elif string == "Large":
            self.ThumbsView.configure(128, 128)
Esempio n. 48
0
    def toolTypeSelected(self, index):
        #print "Got a new selection"
        #print self.comboBox.itemText(index)

        self.typeSelection = str(self.comboBox.itemText(index))
        for testw in self.test_widget:
            self.vboxlayout.removeWidget(testw)
            testw.hide()
        self.tooltypearray = []
        self.test_widget = []
        self.test_text = []
        self.test_line = []

        # The tool_config will always have tool_config name
        self.tooltypearray.append(["Tool Config Name", "tool_config", ""])

        # Now look up the selected connection type and present to the user...
        # First we start at the tool_library
        tool_name = str(self.typeSelection)
        tool_node = self.tool_nodes[tool_name]
        for param_node in tool_node.find('params'):
            type_val = param_node.get('param_type')
            default_val = param_node.text or ''
            self.tooltypearray.append(
                [param_node.get('name'), type_val, default_val])

        for i, param in enumerate(self.tooltypearray):
            # print "Key: %s , Val: %s" % (param[0],param[1])
            paramName = str(param[0] or '').strip()
            type_val = str(param[1] or '').strip()
            default_val = str(param[2] or '').strip()

            if (i == 0):
                widgetTemp = QFrame(self.variableBox)
                widgetTemp.setFrameStyle(QFrame.Panel | QFrame.Raised)
                widgetTemp.setLineWidth(2)
            else:
                widgetTemp = QWidget(self.variableBox)
            widgetTemp.setObjectName(QString("test_widget").append(QString(i)))
            self.test_widget.append(widgetTemp)
            hlayout = QHBoxLayout(widgetTemp)
            self.hboxlayout.append(hlayout)
            hlayout.setMargin(4)
            hlayout.setSpacing(4)
            hlayout.setObjectName(QString("hboxlayout").append(QString(i)))
            test_text = QLabel(widgetTemp)
            self.test_text.append(test_text)
            test_text.setObjectName(QString("test_text").append(QString(i)))
            if type_val == "Required":
                palette = test_text.palette()
                palette.setColor(QPalette.WindowText, Qt.red)
                test_text.setPalette(palette)
            test_text.setText(paramName)
            test_text_type = QLabel(widgetTemp)
            self.test_text_type.append(test_text_type)
            test_text_type.setObjectName(
                QString("test_text_type").append(QString(i)))
            paramName = type_val
            test_text_type.setText(
                QString("(").append(paramName).append(QString(")")))
            hlayout.addWidget(test_text)
            hlayout.addWidget(test_text_type)
            if type_val == 'db_connection_hook':
                test_line = QComboBox(widgetTemp)
                db_connection_choices = get_db_connection_names()
                for i in db_connection_choices:
                    test_line.addItem(QString(i))
                self.test_line.append(test_line)
                test_line.setEnabled(True)
                test_line.setMinimumSize(QSize(200, 0))
                test_line.setObjectName(
                    QString("test_line").append(QString(i)))
            else:
                test_line = QLineEdit(widgetTemp)
                self.test_line.append(test_line)
                test_line.setEnabled(True)
                test_line.setMinimumSize(QSize(200, 0))
                test_line.setObjectName(
                    QString("test_line").append(QString(i)))
#            test_line = QLineEdit(widgetTemp)
#            self.test_line.append(test_line)
#            test_line.setEnabled(True)
#            test_line.setMinimumSize(QSize(200,0))
#            test_line.setObjectName(QString("test_line").append(QString(i)))
#            test_line.setText(QString(""))
            hlayout.addWidget(test_line)
            self.vboxlayout.addWidget(widgetTemp)
Esempio n. 49
0
class Interface(QWidget):
    """Interface widget class."""

    def __init__(self, parent):
        super(Interface, self).__init__()
        self._preferences, vbox = parent, QVBoxLayout(self)
        self.toolbar_settings = settings.TOOLBAR_ITEMS

        groupBoxExplorer = QGroupBox(
            translations.TR_PREFERENCES_INTERFACE_EXPLORER_PANEL)
        #groupBoxToolbar = QGroupBox(
            #translations.TR_PREFERENCES_INTERFACE_TOOLBAR_CUSTOMIZATION)
        groupBoxLang = QGroupBox(
            translations.TR_PREFERENCES_INTERFACE_LANGUAGE)

       #Explorer
        vboxExplorer = QVBoxLayout(groupBoxExplorer)
        self._checkProjectExplorer = QCheckBox(
            translations.TR_PREFERENCES_SHOW_EXPLORER)
        self._checkSymbols = QCheckBox(
            translations.TR_PREFERENCES_SHOW_SYMBOLS)
        self._checkWebInspetor = QCheckBox(
            translations.TR_PREFERENCES_SHOW_WEB_INSPECTOR)
        self._checkFileErrors = QCheckBox(
            translations.TR_PREFERENCES_SHOW_FILE_ERRORS)
        self._checkMigrationTips = QCheckBox(
            translations.TR_PREFERENCES_SHOW_MIGRATION)
        vboxExplorer.addWidget(self._checkProjectExplorer)
        vboxExplorer.addWidget(self._checkSymbols)
        vboxExplorer.addWidget(self._checkWebInspetor)
        vboxExplorer.addWidget(self._checkFileErrors)
        vboxExplorer.addWidget(self._checkMigrationTips)
        #GUI - Toolbar
        #vbox_toolbar = QVBoxLayout(groupBoxToolbar)
        #hbox_select_items = QHBoxLayout()
        #label_toolbar = QLabel(translations.TR_PREFERENCES_TOOLBAR_ITEMS)
        #label_toolbar.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        #hbox_select_items.addWidget(label_toolbar)
        #self._comboToolbarItems = QComboBox()
        #self._load_combo_data(self._comboToolbarItems)
        #self._btnItemAdd = QPushButton(QIcon(":img/add"), '')
        #self._btnItemAdd.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        #self._btnItemAdd.setIconSize(QSize(16, 16))
        #self._btnItemRemove = QPushButton(QIcon(':img/delete'), '')
        #self._btnItemRemove.setIconSize(QSize(16, 16))
        #self._btnDefaultItems = QPushButton(
            #translations.TR_PREFERENCES_TOOLBAR_DEFAULT)
        #self._btnDefaultItems.setSizePolicy(QSizePolicy.Fixed,
                                            #QSizePolicy.Fixed)
        #self._btnItemRemove.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        #hbox_select_items.addWidget(self._comboToolbarItems)
        #hbox_select_items.addWidget(self._btnItemAdd)
        #hbox_select_items.addWidget(self._btnItemRemove)
        #hbox_select_items.addWidget(self._btnDefaultItems)
        #vbox_toolbar.addLayout(hbox_select_items)
        #self._toolbar_items = QToolBar()
        #self._toolbar_items.setObjectName("custom")
        #self._toolbar_items.setToolButtonStyle(Qt.ToolButtonIconOnly)
        #self._load_toolbar()
        #vbox_toolbar.addWidget(self._toolbar_items)
        #vbox_toolbar.addWidget(QLabel(
            #translations.TR_PREFERENCES_TOOLBAR_CONFIG_HELP))
        #Language
        vboxLanguage = QVBoxLayout(groupBoxLang)
        vboxLanguage.addWidget(QLabel(
            translations.TR_PREFERENCES_SELECT_LANGUAGE))
        self._comboLang = QComboBox()
        self._comboLang.setEnabled(False)
        vboxLanguage.addWidget(self._comboLang)
        vboxLanguage.addWidget(QLabel(
            translations.TR_PREFERENCES_REQUIRES_RESTART))

       #Load Languages
        self._load_langs()

       #Settings
        self._checkProjectExplorer.setChecked(
            settings.SHOW_PROJECT_EXPLORER)
        self._checkSymbols.setChecked(settings.SHOW_SYMBOLS_LIST)
        self._checkWebInspetor.setChecked(settings.SHOW_WEB_INSPECTOR)
        self._checkFileErrors.setChecked(settings.SHOW_ERRORS_LIST)
        self._checkMigrationTips.setChecked(settings.SHOW_MIGRATION_LIST)

        vbox.addWidget(groupBoxExplorer)
        #vbox.addWidget(groupBoxToolbar)
        vbox.addWidget(groupBoxLang)

       #Signals
        #self.connect(self._btnItemAdd, SIGNAL("clicked()"),
                     #self.toolbar_item_added)
        #self.connect(self._btnItemRemove, SIGNAL("clicked()"),
                     #self.toolbar_item_removed)
        #self.connect(self._btnDefaultItems, SIGNAL("clicked()"),
                     #self.toolbar_items_default)

        self.connect(self._preferences, SIGNAL("savePreferences()"), self.save)

    #def toolbar_item_added(self):
        #data = self._comboToolbarItems.itemData(
            #self._comboToolbarItems.currentIndex())
        #if data not in self.toolbar_settings or data == 'separator':
            #selected = self.actionGroup.checkedAction()
            #if selected is None:
                #self.toolbar_settings.append(data)
            #else:
                #dataAction = selected.data()
                #self.toolbar_settings.insert(
                    #self.toolbar_settings.index(dataAction) + 1, data)
            #self._load_toolbar()

##    def toolbar_item_removed(self):
        #data = self._comboToolbarItems.itemData(
            #self._comboToolbarItems.currentIndex())
        #if data in self.toolbar_settings and data != 'separator':
            #self.toolbar_settings.pop(self.toolbar_settings.index(data))
            #self._load_toolbar()
        #elif data == 'separator':
            #self.toolbar_settings.reverse()
            #self.toolbar_settings.pop(self.toolbar_settings.index(data))
            #self.toolbar_settings.reverse()
            #self._load_toolbar()

##    def toolbar_items_default(self):
        #self.toolbar_settings = settings.TOOLBAR_ITEMS_DEFAULT
        #self._load_toolbar()

##    def _load_combo_data(self, combo):
        #self.toolbar_items = {
            #'separator': [QIcon(':img/separator'), 'Add Separtor'],
            #'new-file': [QIcon(resources.IMAGES['new']), self.tr('New File')],
            #'new-project': [QIcon(resources.IMAGES['newProj']),
                #self.tr('New Project')],
            #'save-file': [QIcon(resources.IMAGES['save']),
                #self.tr('Save File')],
            #'save-as': [QIcon(resources.IMAGES['saveAs']), self.tr('Save As')],
            #'save-all': [QIcon(resources.IMAGES['saveAll']),
                #self.tr('Save All')],
            #'save-project': [QIcon(resources.IMAGES['saveAll']),
                #self.tr('Save Project')],
            #'reload-file': [QIcon(resources.IMAGES['reload-file']),
                #self.tr('Reload File')],
            #'open-file': [QIcon(resources.IMAGES['open']),
                #self.tr('Open File')],
            #'open-project': [QIcon(resources.IMAGES['openProj']),
                #self.tr('Open Project')],
            #'activate-profile': [QIcon(resources.IMAGES['activate-profile']),
                #self.tr('Activate Profile')],
            #'deactivate-profile':
                #[QIcon(resources.IMAGES['deactivate-profile']),
                #self.tr('Deactivate Profile')],
            #'print-file': [QIcon(resources.IMAGES['print']),
                #self.tr('Print File')],
            #'close-file':
                #[self.style().standardIcon(QStyle.SP_DialogCloseButton),
                #self.tr('Close File')],
            #'close-projects':
                #[self.style().standardIcon(QStyle.SP_DialogCloseButton),
                #self.tr('Close Projects')],
            #'undo': [QIcon(resources.IMAGES['undo']), self.tr('Undo')],
            #'redo': [QIcon(resources.IMAGES['redo']), self.tr('Redo')],
            #'cut': [QIcon(resources.IMAGES['cut']), self.tr('Cut')],
            #'copy': [QIcon(resources.IMAGES['copy']), self.tr('Copy')],
            #'paste': [QIcon(resources.IMAGES['paste']), self.tr('Paste')],
            #'find': [QIcon(resources.IMAGES['find']), self.tr('Find')],
            #'find-replace': [QIcon(resources.IMAGES['findReplace']),
                #self.tr('Find/Replace')],
            #'find-files': [QIcon(resources.IMAGES['find']),
                #self.tr('Find In files')],
            #'code-locator': [QIcon(resources.IMAGES['locator']),
                #self.tr('Code Locator')],
            #'splith': [QIcon(resources.IMAGES['splitH']),
                #self.tr('Split Horizontally')],
            #'splitv': [QIcon(resources.IMAGES['splitV']),
                #self.tr('Split Vertically')],
            #'follow-mode': [QIcon(resources.IMAGES['follow']),
                #self.tr('Follow Mode')],
            #'zoom-in': [QIcon(resources.IMAGES['zoom-in']), self.tr('Zoom In')],
            #'zoom-out': [QIcon(resources.IMAGES['zoom-out']),
                #self.tr('Zoom Out')],
            #'indent-more': [QIcon(resources.IMAGES['indent-more']),
                #self.tr('Indent More')],
            #'indent-less': [QIcon(resources.IMAGES['indent-less']),
                #self.tr('Indent Less')],
            #'comment': [QIcon(resources.IMAGES['comment-code']),
                #self.tr('Comment')],
            #'uncomment': [QIcon(resources.IMAGES['uncomment-code']),
                #self.tr('Uncomment')],
            #'go-to-definition': [QIcon(resources.IMAGES['go-to-definition']),
                #self.tr('Go To Definition')],
            #'insert-import': [QIcon(resources.IMAGES['insert-import']),
                #self.tr('Insert Import')],
            #'run-project': [QIcon(resources.IMAGES['play']), 'Run Project'],
            #'run-file': [QIcon(resources.IMAGES['file-run']), 'Run File'],
            #'stop': [QIcon(resources.IMAGES['stop']), 'Stop'],
            #'preview-web': [QIcon(resources.IMAGES['preview-web']),
                #self.tr('Preview Web')]}
        #for item in self.toolbar_items:
            #combo.addItem(self.toolbar_items[item][0],
                #self.toolbar_items[item][1], item)
        #combo.model().sort(0)

##    def _load_toolbar(self):
        #pass
        ##self._toolbar_items.clear()
        ##self.actionGroup = QActionGroup(self)
        ##self.actionGroup.setExclusive(True)
        ##for item in self.toolbar_settings:
            ##if item == 'separator':
                ##self._toolbar_items.addSeparator()
            ##else:
                ##action = self._toolbar_items.addAction(
                    ##self.toolbar_items[item][0], self.toolbar_items[item][1])
                ##action.setData(item)
                ##action.setCheckable(True)
                ##self.actionGroup.addAction(action)

    def _load_langs(self):
        langs = file_manager.get_files_from_folder(
            resources.LANGS, '.qm')
        self._languages = ['English'] + \
            [file_manager.get_module_name(lang) for lang in langs]
        self._comboLang.addItems(self._languages)
        if(self._comboLang.count() > 1):
            self._comboLang.setEnabled(True)
        if settings.LANGUAGE:
            index = self._comboLang.findText(settings.LANGUAGE)
        else:
            index = 0
        self._comboLang.setCurrentIndex(index)

    def save(self):
        qsettings = IDE.ninja_settings()
        settings.TOOLBAR_ITEMS = self.toolbar_settings
        lang = self._comboLang.currentText()
        #preferences/interface
        qsettings.setValue('preferences/interface/showProjectExplorer',
                           self._checkProjectExplorer.isChecked())
        settings.SHOW_PROJECT_EXPLORER = self._checkProjectExplorer.isChecked()
        qsettings.setValue('preferences/interface/showSymbolsList',
                           self._checkSymbols.isChecked())
        settings.SHOW_SYMBOLS_LIST = self._checkSymbols.isChecked()
        qsettings.setValue('preferences/interface/showWebInspector',
                           self._checkWebInspetor.isChecked())
        settings.SHOW_WEB_INSPECTOR = self._checkWebInspetor.isChecked()
        qsettings.setValue('preferences/interface/showErrorsList',
                           self._checkFileErrors.isChecked())
        settings.SHOW_ERRORS_LIST = self._checkFileErrors.isChecked()
        qsettings.setValue('preferences/interface/showMigrationList',
                           self._checkMigrationTips.isChecked())
        settings.SHOW_MIGRATION_LIST = self._checkMigrationTips.isChecked()
        #qsettings.setValue('preferences/interface/toolbar',
                           #settings.TOOLBAR_ITEMS)
        qsettings.setValue('preferences/interface/language', lang)
        lang = lang + '.qm'
        settings.LANGUAGE = os.path.join(resources.LANGS, lang)
Esempio n. 50
0
class GotoLineWidget( QWidget ):
    " goto bar widget "

    maxHistory = 12

    def __init__( self, editorsManager, parent = None ):

        QWidget.__init__( self, parent )
        self.editorsManager = editorsManager

        self.__gotoHistory = []

        # Common graphics items
        closeButton = QToolButton( self )
        closeButton.setToolTip( "Click to close the dialog (ESC)" )
        closeButton.setIcon( PixmapCache().getIcon( "close.png" ) )
        closeButton.clicked.connect( self.hide )

        lineLabel = QLabel( self )
        lineLabel.setText( "Goto line:" )

        self.linenumberEdit = QComboBox( self )
        self.linenumberEdit.setEditable( True )
        self.linenumberEdit.setInsertPolicy( QComboBox.InsertAtTop )
        self.linenumberEdit.setAutoCompletion( False )
        self.linenumberEdit.setDuplicatesEnabled( False )
        sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Fixed )
        sizePolicy.setHorizontalStretch( 0 )
        sizePolicy.setVerticalStretch( 0 )
        sizePolicy.setHeightForWidth(
                self.linenumberEdit.sizePolicy().hasHeightForWidth() )
        self.linenumberEdit.setSizePolicy( sizePolicy )
        self.validator = QIntValidator( 1, 100000, self )
        self.linenumberEdit.setValidator( self.validator )
        self.linenumberEdit.editTextChanged.connect( self.__onEditTextChanged )
        self.linenumberEdit.lineEdit().returnPressed.connect( self.__onEnter )

        self.goButton = QToolButton( self )
        self.goButton.setToolTip( "Click to jump to the line (ENTER)" )
        self.goButton.setIcon( PixmapCache().getIcon( "gotoline.png" ) )
        self.goButton.setFocusPolicy( Qt.NoFocus )
        self.goButton.setEnabled( False )
        self.goButton.clicked.connect( self.__onGo )

        spacer = QWidget()
        spacer.setFixedWidth( 1 )

        horizontalLayout = QHBoxLayout( self )
        horizontalLayout.setMargin( 0 )

        horizontalLayout.addWidget( closeButton )
        horizontalLayout.addWidget( lineLabel )
        horizontalLayout.addWidget( self.linenumberEdit )
        horizontalLayout.addWidget( self.goButton )
        horizontalLayout.addWidget( spacer )
        return

    def keyPressEvent( self, event ):
        """ Handles the key press events """

        if event.key() == Qt.Key_Escape:
            activeWindow = self.editorsManager.currentWidget()
            if activeWindow:
                activeWindow.setFocus()
            event.accept()
            self.hide()
        return

    def __updateHistory( self, txt ):
        " Updates the combo history "

        while txt in self.__gotoHistory:
            self.__gotoHistory.remove( txt )
        self.__gotoHistory = [ txt ] + self.__gotoHistory
        self.__gotoHistory = self.__gotoHistory[ : GotoLineWidget.maxHistory ]

        self.linenumberEdit.clear()
        self.linenumberEdit.addItems( self.__gotoHistory )
        return

    def show( self ):
        " Overriden show() method "
        self.linenumberEdit.lineEdit().selectAll()
        QWidget.show( self )
        self.activateWindow()
        return

    def setFocus( self ):
        " Overridded setFocus "
        self.linenumberEdit.setFocus()
        return

    def updateStatus( self ):
        " Triggered when the current tab is changed "
        currentWidget = self.editorsManager.currentWidget()
        status = currentWidget.getType() in \
                    [ MainWindowTabWidgetBase.PlainTextEditor,
                      MainWindowTabWidgetBase.VCSAnnotateViewer ]
        self.linenumberEdit.setEnabled( status )
        self.goButton.setEnabled( status and
                                  self.linenumberEdit.currentText() != "" )
        return

    def __onGo( self ):
        " Triggered when the 'Go!' button is clicked "
        if self.linenumberEdit.currentText() == "":
            return

        currentWidget = self.editorsManager.currentWidget()
        if not currentWidget.getType() in \
                    [ MainWindowTabWidgetBase.PlainTextEditor,
                      MainWindowTabWidgetBase.VCSAnnotateViewer ]:
            return

        txt = self.linenumberEdit.currentText()
        self.__updateHistory( txt )
        editor = currentWidget.getEditor()
        line = min( int( txt ), editor.lines() ) - 1

        editor.setCursorPosition( line, 0 )
        editor.ensureLineVisible( line )
        currentWidget.setFocus()
        return

    def __onEditTextChanged( self, text ):
        " Triggered when the text has been changed "
        self.goButton.setEnabled( text != "" )
        return

    def __onEnter( self ):
        " Triggered when 'Enter' or 'Return' is clicked "
        self.__onGo()
        return

    def selectAll( self ):
        " Selects the line edit content "
        self.linenumberEdit.lineEdit().selectAll()
        return
Esempio n. 51
0
class RunsDialog(QtHelper.EnhancedQDialog):
    """
    Runs several dialog
    """
    RefreshRepository = pyqtSignal(str)
    def __init__(self, dialogName, parent = None, iRepo=None, lRepo=None, rRepo=None):
        """
        Constructor
        """
        QtHelper.EnhancedQDialog.__init__(self, parent)

        self.name = self.tr("Prepare a group of runs")
        self.projectReady = False
        self.iRepo = iRepo
        self.lRepo = lRepo
        self.rRepo = rRepo

        self.createDialog()
        self.createConnections()

    def createDialog(self):
        """
        Create qt dialog
        """
        self.setWindowTitle( self.name )

        mainLayout = QHBoxLayout()
        layoutTests = QHBoxLayout()
        layoutRepoTest = QVBoxLayout()

        self.prjCombo = QComboBox(self)
        self.prjCombo.setEnabled(False)

        self.repoTests = QTreeWidget(self)
        self.repoTests.setFrameShape(QFrame.NoFrame)
        if USE_PYQT5:
            self.repoTests.header().setSectionResizeMode(QHeaderView.Stretch)
        else:
            self.repoTests.header().setResizeMode(QHeaderView.Stretch)
        self.repoTests.setHeaderHidden(True)
        self.repoTests.setContextMenuPolicy(Qt.CustomContextMenu)
        self.repoTests.setIndentation(10)

        layoutRepoTest.addWidget(self.prjCombo)
        layoutRepoTest.addWidget(self.repoTests)

        self.testsList = QListWidget(self)

        layoutTests.addLayout( layoutRepoTest )
        layoutTests.addWidget( self.testsList )
        mainLayout.addLayout( layoutTests )

        buttonLayout = QVBoxLayout()

        self.okButton = QPushButton(self.tr("Execute All"), self)
        self.okButton.setEnabled(False)
        self.cancelButton = QPushButton(self.tr("Cancel"), self)
        self.upButton = QPushButton(self.tr("UP"), self)
        self.upButton.setEnabled(False)
        self.downButton = QPushButton(self.tr("DOWN"), self)
        self.downButton.setEnabled(False)
        self.clearButton = QPushButton(self.tr("Remove All"), self)
        self.delButton = QPushButton(self.tr("Remove"), self)
        self.delButton.setEnabled(False)

        self.runSimultaneous = QCheckBox(self.tr("Simultaneous Run"))
        
        self.schedImmed = QRadioButton(self.tr("Run Immediately"))
        self.schedImmed.setChecked(True)
        self.schedAt = QRadioButton(self.tr("Run At:"))
        self.schedAtDateTimeEdit = QDateTimeEdit(QDateTime.currentDateTime())
        self.schedAtDateTimeEdit.setEnabled(False)

        buttonLayout.addWidget(self.okButton)
        buttonLayout.addWidget(self.runSimultaneous)
        buttonLayout.addWidget(self.schedImmed)
        buttonLayout.addWidget(self.schedAt)
        buttonLayout.addWidget(self.schedAtDateTimeEdit)

        
        buttonLayout.addWidget( self.upButton )
        buttonLayout.addWidget( self.downButton )
        buttonLayout.addWidget( self.delButton )
        buttonLayout.addWidget( self.clearButton )

        buttonLayout.addWidget(self.cancelButton)

        mainLayout.addLayout(buttonLayout)

        self.setMinimumHeight(400)
        self.setMinimumWidth(750)
        self.setLayout(mainLayout)

    def initProjects(self, projects=[], defaultProject=1):
        """
        Initialize projects
        """
        # init date and time
        self.schedAtDateTimeEdit.setDateTime(QDateTime.currentDateTime()) 

        self.projectReady = False

        self.repoTests.clear()
        self.prjCombo.clear()
        self.testsList.clear()

        self.prjCombo.setEnabled(True)
        
        # insert data
        pname = ''
        for p in projects:
            self.prjCombo.addItem ( p['name']  )
            if defaultProject == p['project_id']:
                pname = p['name']
        
        for i in xrange(self.prjCombo.count()):
            item_text = self.prjCombo.itemText(i)
            if str(pname) == str(item_text):
                self.prjCombo.setCurrentIndex(i)

        self.projectReady = True
        self.RefreshRepository.emit(pname)

    def initializeTests(self, listing):
        """
        Initialize tests
        """
        self.repoTests.clear()
        self.testRoot = self.rRepo.Item(repo = self.iRepo.remote(), 
                                        parent = self.repoTests, txt = "Root", 
                                        type = QTreeWidgetItem.UserType+10, 
                                        isRoot = True )
        self.testRoot.setSelected(True)
        self.createRepository(listing=listing, parent=self.testRoot,fileincluded=True)
        self.repoTests.sortItems(0, Qt.AscendingOrder)

        self.hideItems(hideTsx=False, hideTpx=False, hideTcx=True, hideTdx=True, hideTxt=True, hidePy=True,
                                hideTux=False, hidePng=True, hideTgx=False, hideTax=False)

    def createRepository(self, listing, parent, fileincluded=True):
        """
        Create repository

        @param listing: 
        @type listing: list

        @param parent: 
        @type parent:

        @param fileincluded: 
        @type fileincluded: boolean
        """
        try:
            for dct in  listing:
                if dct["type"] == "folder":
                    item = self.rRepo.Item(repo = self.iRepo.remote(), parent = parent, 
                                           txt = dct["name"], propertiesFile=dct )
                    self.createRepository(  dct["content"] , item, fileincluded )
                else:
                    if fileincluded:
                        if dct["type"] == "file":
                            pname = self.iRepo.remote().getProjectName(dct["project"])
                            # {'modification': 1342259500, 'type': 'file', 'name': '__init__.py', 'size': '562 }
                            item = self.rRepo.Item(repo = self.iRepo.remote(), parent = parent, txt = dct["name"] ,
                                                   propertiesFile=dct, type = QTreeWidgetItem.UserType+0, 
                                                   projectId=dct["project"], projectName=pname )

        except Exception as e:
            self.error( "unable to create tree for runs: %s" % e )

    def onProjectChanged(self, projectItem):
        """
        Called when the project changed on the combo box
        """
        if self.projectReady:
            item_text = self.prjCombo.itemText(projectItem)
            self.RefreshRepository.emit(item_text)

    def createConnections (self):
        """
        create qt connections
         * ok
         * cancel
        """
        self.prjCombo.currentIndexChanged.connect(self.onProjectChanged)
        self.okButton.clicked.connect( self.acceptClicked )
        self.cancelButton.clicked.connect( self.reject )
        self.upButton.clicked.connect(self.upTest)
        self.downButton.clicked.connect(self.downTest)
        self.clearButton.clicked.connect(self.clearList)
        self.delButton.clicked.connect(self.delTest)

        self.testsList.itemClicked.connect(self.onItemSelected)
        self.testsList.itemSelectionChanged.connect(self.onItemSelectionChanged)

        self.schedAt.toggled.connect(self.onSchedAtActivated)

        self.repoTests.itemDoubleClicked.connect( self.onTestDoucleClicked )

    def onSchedAtActivated(self, toggled):
        """
        On sched at button activated
        """
        if toggled:
            self.schedAtDateTimeEdit.setEnabled(True)
        else:
            self.schedAtDateTimeEdit.setEnabled(False)

    def onItemSelectionChanged(self):
        """
        Called on item selection changed
        """
        self.onItemSelected(itm=None)

    def onItemSelected(self, itm):
        """
        Call on item selected
        """
        selectedItems = self.testsList.selectedItems()
        if len(selectedItems):
            self.delButton.setEnabled(True)
            self.upButton.setEnabled(True)
            self.downButton.setEnabled(True)
        else:
            self.delButton.setEnabled(False)
            self.upButton.setEnabled(False)
            self.downButton.setEnabled(False)

        if not self.testsList.count():
            self.okButton.setEnabled(False)

    def upTest(self):
        """
        Up test
        """
        currentRow = self.testsList.currentRow()
        currentItem = self.testsList.takeItem(currentRow)
        self.testsList.insertItem(currentRow - 1, currentItem)

    def downTest(self):
        """
        Down test
        """
        currentRow = self.testsList.currentRow()
        currentItem = self.testsList.takeItem(currentRow)
        self.testsList.insertItem(currentRow + 1, currentItem)


    def delTest(self):
        """
        Del test
        """
        currentRow = self.testsList.currentRow()
        currentItem = self.testsList.takeItem(currentRow)

    def clearList(self):
        """
        Clear test
        """
        self.testsList.clear()
        self.delButton.setEnabled(False)
        self.upButton.setEnabled(False)
        self.downButton.setEnabled(False)

        self.okButton.setEnabled(False)

    def iterateTree(self, item, hideTsx, hideTpx, hideTcx, hideTdx, hideTxt, 
                          hidePy, hideTux, hidePng, hideTgx, hideTax):
        """
        Iterate tree
        """
        child_count = item.childCount()
        for i in range(child_count):
            subitem = item.child(i)
            subchild_count = subitem.childCount()
            if subchild_count > 0:
                self.iterateTree(item=subitem, hideTsx=hideTsx, 
                                 hideTpx=hideTpx, hideTcx=hideTcx, 
                                 hideTdx=hideTdx, hideTxt=hideTxt,
                                 hidePy=hidePy, hideTux=hideTux, 
                                 hidePng=hidePng, hideTgx=hideTgx, hideTax=hideTax)
            else:
                if hideTux and subitem.getExtension() == self.rRepo.EXTENSION_TUX:
                    subitem.setHidden (True)
                elif hideTpx and subitem.getExtension() == self.rRepo.EXTENSION_TPX:
                    subitem.setHidden (True)
                elif hideTgx and subitem.getExtension() == self.rRepo.EXTENSION_TGX:
                    subitem.setHidden (True)
                elif hideTcx and subitem.getExtension() == self.rRepo.EXTENSION_TCX:
                    subitem.setHidden (True)
                elif hideTsx and  subitem.getExtension() == self.rRepo.EXTENSION_TSX:
                    subitem.setHidden (True)
                elif hideTdx and  subitem.getExtension() == self.rRepo.EXTENSION_TDX:
                    subitem.setHidden (True)
                elif hideTxt and  subitem.getExtension() == self.rRepo.EXTENSION_TXT:
                    subitem.setHidden (True)
                elif hidePy and  subitem.getExtension() == self.rRepo.EXTENSION_PY:
                    subitem.setHidden (True)
                elif hidePng and  subitem.getExtension() == self.rRepo.EXTENSION_PNG:
                    subitem.setHidden (True)
                elif hideTax and  subitem.getExtension() == self.rRepo.EXTENSION_TAx:
                    subitem.setHidden (True)
                else:
                    subitem.setHidden(False)

    def hideItems(self, hideTsx=False, hideTpx=False, hideTcx=False, hideTdx=False, hideTxt=False, hidePy=False, 
                        hideTux=False, hidePng=False, hideTgx=False, hideTax=False):
        """
        Hide items
        """
        root = self.repoTests.invisibleRootItem()
        self.iterateTree(item=root, hideTsx=hideTsx, hideTpx=hideTpx, hideTcx=hideTcx, 
                         hideTdx=hideTdx, hideTxt=hideTxt, hidePy=hidePy,
                         hideTux=hideTux, hidePng=hidePng, hideTgx=hideTgx, hideTax=hideTax)

    def onTestDoucleClicked(self, testItem):
        """
        On tests double clicked
        """
        if testItem.type() != QTreeWidgetItem.UserType+0:
            return

        self.okButton.setEnabled(True)

        currentProject = self.prjCombo.currentText()

        testName = "%s:%s" % (str(currentProject),testItem.getPath(withFileName = True))
        testItem = QListWidgetItem(testName )

        if testName.endswith(self.rRepo.EXTENSION_TUX):
            testItem.setIcon(QIcon(":/tux.png"))
        if testName.endswith(self.rRepo.EXTENSION_TSX):
            testItem.setIcon(QIcon(":/tsx.png"))
        if testName.endswith(self.rRepo.EXTENSION_TPX):
            testItem.setIcon(QIcon(":/tpx.png"))
        if testName.endswith(self.rRepo.EXTENSION_TGX):
            testItem.setIcon(QIcon(":/tgx.png"))
        if testName.endswith(self.rRepo.EXTENSION_TAX):
            testItem.setIcon(QIcon(":/tax.png"))
            
        self.testsList.addItem( testItem )

    def acceptClicked (self):
        """
        Called on accept button
        """
        self.accept()
    
    def getTests(self):
        """
        Returns all tests in the list
        """
        tests = []
        for i in xrange(self.testsList.count()):
            testItem = self.testsList.item(i)
            tests.append( str(testItem.text()) )

        runSimultaneous = False
        if self.runSimultaneous.isChecked(): runSimultaneous = True
        
        if self.schedImmed.isChecked():
            runAt = (0,0,0,0,0,0)
            return (tests, False, runAt, runSimultaneous)
        else:
            pydt = self.schedAtDateTimeEdit.dateTime().toPyDateTime()
            runAt = (pydt.year, pydt.month, pydt.day, pydt.hour, pydt.minute, pydt.second)
            return (tests, True, runAt, runSimultaneous)
Esempio n. 52
0
class CustomOption(QDialog):

     def __init__(self, parent=None):
        super(CustomOption, self).__init__(parent)

        self.options = {}

        self.enable = QCheckBox('Enable custom settings')
        self.lblFamily = QLabel('Family:')
        self.lblWavelet = QLabel('Wavelet:')
        self.lblSignal = QLabel('Extension:')
        self.lblLvls = QLabel('Levels:')
        self.waveletFamily = QComboBox()
        self.wavelet = QComboBox()
        self.signalEx = QComboBox()
        self.lvls = QSpinBox()
        self.lvls.setRange(2, 10)

        self.periodic = QCheckBox('Frequency')
        self.frequency = QSpinBox()
        self.frequency.setMinimum(2)
        self.frequency.hide()

        self.apply = QPushButton('Apply')
        self.cancel = QPushButton('Cancel')

        self.layout = QGridLayout()
        self.layout.addWidget(self.enable, 0, 0, 1, 2)
        self.layout.addWidget(self.lblFamily, 1, 0)
        self.layout.addWidget(self.waveletFamily, 1, 1)
        self.layout.addWidget(self.lblWavelet, 2, 0)
        self.layout.addWidget(self.wavelet, 2, 1)
        self.layout.addWidget(self.lblSignal, 3, 0)
        self.layout.addWidget(self.signalEx, 3, 1)
        self.layout.addWidget(self.lblLvls, 4, 0)
        self.layout.addWidget(self.lvls, 4, 1)
        self.layout.addWidget(self.periodic, 5, 0)
        self.layout.addWidget(self.frequency, 5, 1)
        self.layout.addWidget(self.apply, 6, 0)
        self.layout.addWidget(self.cancel, 6, 1)
        self.layout.setAlignment(Qt.AlignCenter)
        self.setLayout(self.layout)

        self.initComponents()
        self.initActions()

        self.updateWavelet()
        self.enableDisable()

     def initComponents(self):
        self.setWindowFlags(Qt.Tool)
        self.setWindowTitle('Custom settings')
        self.waveletFamily.addItems(pywt.families())
        self.signalEx.addItems(pywt.MODES.modes)
        self.periodic.clicked.connect(self.showFrequency)
        self.options['enable'] = False
        
        self.setStyleSheet('QPushButton {\
                    color: #333;\
                    border: 1px solid #555;\
                    border-radius: 11px;\
                    padding: 2px;\
                    background: qradialgradient(cx: 0.3, cy: -0.4,\
                    fx: 0.3, fy: -0.4,\
                    radius: 1.35, stop: 0 #fff, stop: 1 #888);\
                    min-width: 80px;}\
                QPushButton:hover {\
                    color: #fff;\
                    background: qradialgradient(cx: 0.3, cy: -0.4,\
                    fx: 0.3, fy: -0.4,\
                    radius: 1.35, stop: 0 #fff, stop: 1 #bbb);}\
                QPushButton:pressed {\
                    background: qradialgradient(cx: 0.4, cy: -0.1,\
                    fx: 0.4, fy: -0.1,\
                    radius: 1.35, stop: 0 #fff, stop: 1 #ddd);}\
                QPushButton:checked {\
                    background: qradialgradient(cx: 0.4, cy: -0.1,\
                    fx: 0.4, fy: -0.1,\
                    radius: 1.35, stop: 0 #fff, stop: 1 #ddd);}\
                QComboBox {\
                    color: #333;\
                    border: 1px solid #555;\
                    border-radius: 11px;\
                    padding: 1px 18px 1px 3px;\
                    background: qradialgradient(cx: 0.3, cy: -0.4,\
                    fx: 0.3, fy: -0.4,\
                    radius: 1.35, stop: 0 #fff, stop: 1 #888);\
                    min-width: 20px;}\
                QComboBox:hover {\
                    color: #fff;\
                    background: qradialgradient(cx: 0.3, cy: -0.4,\
                    fx: 0.3, fy: -0.4,\
                    radius: 1.35, stop: 0 #fff, stop: 1 #bbb);}\
                QComboBox::down-arrow {\
                     image: url(' + RES + ICONS + ARROW_DOWN + ');}\
                QComboBox::down-arrow:on {\
                     top: 1px;\
                     left: 1px;}\
                QComboBox::drop-down {\
                     subcontrol-origin: padding;\
                     subcontrol-position: top right;\
                     width: 15px;\
                     border-left-width: 1px;\
                     border-left-color: darkgray;\
                     border-left-style: solid;\
                     border-top-right-radius: 3px;\
                     border-bottom-right-radius: 3px;}\
                QToolButton {\
                    color: #333;\
                    border: 1px solid #555;\
                    border-radius: 11px;\
                    padding: 2px;\
                    background: qradialgradient(cx: 0.3, cy: -0.4,\
                    fx: 0.3, fy: -0.4,\
                    radius: 1.35, stop: 0 #fff, stop: 1 #888);\
                    min-width: 20px;}\
                QToolButton:hover {\
                    color: #fff;\
                    background: qradialgradient(cx: 0.3, cy: -0.4,\
                    fx: 0.3, fy: -0.4,\
                    radius: 1.35, stop: 0 #fff, stop: 1 #bbb);}\
                QToolButton:pressed {\
                    background: qradialgradient(cx: 0.4, cy: -0.1,\
                    fx: 0.4, fy: -0.1,\
                    radius: 1.35, stop: 0 #fff, stop: 1 #ddd);}\
                QToolButton:checked {\
                    background: qradialgradient(cx: 0.4, cy: -0.1,\
                    fx: 0.4, fy: -0.1,\
                    radius: 1.35, stop: 0 #fff, stop: 1 #ddd);}')

     def initActions(self):
        self.apply.clicked.connect(self.saveOptions)
        self.cancel.clicked.connect(self.close)
        self.waveletFamily.currentIndexChanged.connect(self.updateWavelet)
        self.enable.clicked.connect(self.enableDisable)

     def saveOptions(self):
        self.options['enable'] = self.enable.isChecked()
        self.options['wavelet'] = unicode(self.wavelet.currentText())
        self.options['signal'] = unicode(self.signalEx.currentText())
        self.options['lvls'] = self.lvls.value()
        if self.periodic.isChecked():
            self.options['frequency'] = self.frequency.value()
            
        self.close()

     def updateWavelet(self):
         self.wavelet.clear()
         self.wavelet.addItems(pywt.wavelist(self.waveletFamily.currentText()))

     def showFrequency(self):
         if self.periodic.isChecked():
             self.frequency.show()
         else:
             self.frequency.hide()

     def enableDisable(self):
         if self.enable.isChecked():
            self.waveletFamily.setEnabled(True)
            self.wavelet.setEnabled(True)
            self.lvls.setEnabled(True)
            self.signalEx.setEnabled(True)
         else:
            self.waveletFamily.setEnabled(False)
            self.wavelet.setEnabled(False)
            self.lvls.setEnabled(False)
            self.signalEx.setEnabled(False)
class ProxyConfigPage(QWizardPage):
    def __init__(self, parent=None,key=None):
        super(ProxyConfigPage, self).__init__(parent)
        
        self.parent = parent 
        self.key = key
        
        try:
            (pxytype,pxyhost,pxyport,pxyauth,pxyusr,pxypwd) = self.parent.mfr.readProxyConfig()
        except:
            (pxytype,pxyhost,pxyport,pxyauth,pxyusr,pxypwd) = (None,)*6
            
        #if we use enums for pxy types
        #pxytype = [a[0] for a in WFSDataStore.PROXY_TYPE.reverse.items() if a[1]==pxytype][0]

            
        self.setTitle(self.parent.plist.get(self.key)[1]+' Configuration Options')
        self.setSubTitle('Enter the hostname/ip-address, port number and authentication details of your HTTP proxy')

        QToolTip.setFont(QFont('SansSerif', 10))
        
        #labels
        directlabel = QLabel('Direct Connection')
        systemlabel = QLabel('Use System Proxy settings')
        proxylabel = QLabel('Configure Proxy')
        
        hostLabel = QLabel('Proxy Host')
        portLabel = QLabel('Proxy Port')
        authLabel = QLabel('Authentication')
        usrLabel = QLabel('Username')
        pwdLabel = QLabel('Password')
        
        
        #radio buttons
        self.directradio = QRadioButton()
        self.systemradio = QRadioButton()
        self.usrdefradio = QRadioButton()
        
        
        #edit boxes
        self.hostEdit = QLineEdit(pxyhost)
        self.hostEdit.setToolTip('Enter Proxy host (IP Address or hostname)')
        self.portEdit = QLineEdit(pxyport)
        self.portEdit.setToolTip('Enter Proxy port')
        
        #dropdown
        self.authSelect = QComboBox()
        self.authSelect.addItem('')
        self.authSelect.setToolTip('Select appropriate proxy authentication mechanism')
        self.authSelect.addItems(WFSDataStore.PROXY_AUTH)
        self.authSelect.setCurrentIndex(0 if LU.assessNone(pxyauth) is None else WFSDataStore.PROXY_AUTH.index(pxyauth))
        
        self.usrEdit = QLineEdit(pxyusr)
        self.usrEdit.setToolTip('Enter your proxy username (if required)')
        self.pwdEdit = QLineEdit('')#pxypwd
        self.usrEdit.setToolTip('Enter your proxy password (if required)')
        self.pwdEdit.setEchoMode(QLineEdit.Password)
        
        self.portEdit.setValidator(QRegExpValidator(QRegExp("\d{1,5}"), self))
        
        self.registerField(self.key+"host",self.hostEdit)
        self.registerField(self.key+"port",self.portEdit)
        self.registerField(self.key+"auth",self.authSelect,"currentIndex")
        self.registerField(self.key+"usr",self.usrEdit)
        self.registerField(self.key+"pwd",self.pwdEdit)
        
        self.registerField(self.key+WFSDataStore.PROXY_TYPE[0],self.directradio)
        self.registerField(self.key+WFSDataStore.PROXY_TYPE[1],self.systemradio)
        self.registerField(self.key+WFSDataStore.PROXY_TYPE[2],self.usrdefradio)

        #grid
        grid1 = QGridLayout()
        grid1.setSpacing(10)
        
        grid2 = QGridLayout()
        grid2.setSpacing(10)
        
        #layout
        hbox = QHBoxLayout()
        grid1.addWidget(self.directradio,1,0)
        grid1.addWidget(directlabel,1,1)
        grid1.addWidget(self.systemradio,2,0)
        grid1.addWidget(systemlabel,2,1)
        grid1.addWidget(self.usrdefradio,3,0)
        grid1.addWidget(proxylabel,3,1)
        hbox.addLayout(grid1)
        hbox.addStretch(1)
        
        
        self.gbox = QGroupBox('Proxy Configuration')

        #dsu
        subs = False
        if pxytype == WFSDataStore.PROXY_TYPE[1]:
            #system
            self.systemradio.setChecked(True)
        elif pxytype == WFSDataStore.PROXY_TYPE[2]:
            #user_defined
            self.usrdefradio.setChecked(True)
            subs = True
        else:
            #direct (default)
            self.directradio.setChecked(True)
            
        self.setUserDefined(subs)
        
        self.directradio.clicked.connect(self.disableUserDefined)
        self.systemradio.clicked.connect(self.disableUserDefined)
        self.usrdefradio.clicked.connect(self.enableUserDefined)
        
        grid2.addWidget(hostLabel, 1, 0)
        grid2.addWidget(self.hostEdit, 1, 2)
        
        grid2.addWidget(portLabel, 2, 0)
        grid2.addWidget(self.portEdit, 2, 2)
        
        grid2.addWidget(authLabel, 3, 0)
        grid2.addWidget(self.authSelect, 3, 2)
        
        grid2.addWidget(usrLabel, 4, 0)
        grid2.addWidget(self.usrEdit, 4, 2)
        
        grid2.addWidget(pwdLabel, 5, 0)
        grid2.addWidget(self.pwdEdit, 5, 2)
             
        self.gbox.setLayout(grid2)
        
        #layout    
        vbox = QVBoxLayout()
        vbox.addLayout(hbox)
        vbox.insertWidget(1,self.gbox)
        self.setLayout(vbox)  
        
    def selectConfFile(self):
        self.fileEdit.setText(QFileDialog.getOpenFileName())

    def nextId(self):
        #now go to selected dest configger
        #return int(self.field("ldsdest").toString())
    
        if self.testConnection():
            return self.field("ldsdest")
        return self.parent.plist.get('proxy')[0]
    
    def disableUserDefined(self):
        self.setUserDefined(False)
        
    def enableUserDefined(self):
        self.setUserDefined(True)
        
    def setUserDefined(self,udval):
        self.gbox.setEnabled(udval)
        self.hostEdit.setEnabled(udval)
        self.portEdit.setEnabled(udval)
        self.authSelect.setEnabled(udval)
        self.usrEdit.setEnabled(udval)
        self.pwdEdit.setEnabled(udval)
        
    def testConnection(self):
        if not self.usrdefradio.isChecked(): 
            return True
        if not any(f for f in (self.hostEdit.isModified(),self.portEdit.isModified(),
                               self.usrEdit.isModified(),self.pwdEdit.isModified())):
            return False
        proxydata = {'type':'USER','host':str(self.hostEdit.text()),'port':str(self.portEdit.text()),
                     'auth':str(WFSDataStore.PROXY_AUTH[self.authSelect.currentIndex()-1]),
                     'user':str(self.usrEdit.text()),'pass':str(self.pwdEdit.text())}
        wfsdata = {'key':'00112233445566778899aabbccddeeff'}#key not necessary but config tester checks format
        lds = LDSDataStore(None,{'Proxy':proxydata,'WFS':wfsdata}) 
        lds.applyConfigOptions()
        
        try:
            #use website likely to be up (that isn't LDS so error is distinct)
            lds.initDS('http://www.google.com/',False)
        except DatasourceConnectException as dce:
            QMessageBox.warning(self, 'Connection Error', 'Cannot connect to network using proxy parameters provided {}'.format(dce), 'OK')
            return False
        except DatasourceOpenException as dse:
            QMessageBox.info(self, 'Connection Warning', 'Connection parameters confirmed, Datasource initialisation untested. Continuing.\n{}'.format(dse), 'OK')
            return True
        except RuntimeError as rte:
            QMessageBox.warning(self, 'RuntimeError', 'Error connecting to network: '+str(rte), 'OK')
            return False
        return True
Esempio n. 54
0
class WSystem(QWidget, Logger.ClassLogger):
    """
    System widget
    """
    # action, description, misc, parameters
    AddStep = pyqtSignal(str, str, str, dict)
    UpdateStep = pyqtSignal(str, str, str, dict)
    CancelEdit = pyqtSignal()

    def __init__(self, parent):
        """
        Constructor
        """
        QWidget.__init__(self)

        self.createActions()
        self.createWidgets()
        self.createToolbar()
        self.createConnections()

    def createActions(self):
        """
        Create qt actions
        """
        self.addAction = QPushButton(QIcon(":/add_black.png"), '&Add Action',
                                     self)
        self.addAction.setMinimumHeight(40)
        self.addAction.setMaximumWidth(150)
        self.cancelAction = QtHelper.createAction(self,
                                                  "&Cancel",
                                                  self.cancelStep,
                                                  icon=QIcon(":/undo.png"),
                                                  tip='Cancel update')
        self.cancelAction.setEnabled(False)

        self.optionsAction = QtHelper.createAction(
            self,
            "&",
            self.openOptions,
            icon=QIcon(":/system-small.png"),
            tip='System options')

    def openOptions(self):
        """
        Open options dialog
        """
        if self.optionsDialog.exec_() == QDialog.Accepted:
            pass

    def createWidgets(self):
        """
        Create qt widgets
        """
        self.optionsDialog = OptionsDialog(self)

        self.validatorUpper = ValidatorUpper(self)
        self.validatorAll = ValidatorAll(self)
        self.validatorInt = QIntValidator(self)

        self.actionsComboBox = QComboBox(self)
        self.actionsComboBox.setMinimumHeight(40)
        for i in xrange(len(GuiSteps.ACTION_SYSTEM_DESCR)):
            if not len(GuiSteps.ACTION_SYSTEM_DESCR[i]):
                self.actionsComboBox.insertSeparator(i + 1)
            else:
                el = GuiSteps.ACTION_SYSTEM_DESCR[i].keys()
                self.actionsComboBox.addItem(list(el)[0])

        self.labelActionDescr = QLabel(self)
        self.labelActionDescr.hide()
        self.descriptionLine = QLineEdit(self)
        self.descriptionLine.setPlaceholderText("Step purpose description")
        self.descriptionLine.hide()

        actionsLayout = QHBoxLayout()
        actionsLayout.addWidget(self.actionsComboBox)

        actionLayout1 = QGridLayout()
        actionLayout1.addLayout(actionsLayout, 0, 1)

        self.createWidgetSession()
        self.createWidgetText()
        self.createWidgetShortcut()
        self.createWidgetScreen()

        actionLayout2 = QGridLayout()
        actionLayout2.addWidget(self.sessionGroup, 1, 0)
        actionLayout2.addWidget(self.textGroup, 1, 0)
        actionLayout2.addWidget(self.shortcutGroup, 1, 0)
        actionLayout2.addWidget(self.screenGroup, 1, 0)

        font = QFont()
        font.setBold(True)

        labelAct = QLabel(self.tr("Action: "))
        labelAct.setFont(font)

        self.arrowLabel = QLabel("")
        self.arrowLabel.setPixmap(
            QPixmap(":/arrow-right.png").scaledToWidth(32))

        self.arrowLabel2 = QLabel("")
        self.arrowLabel2.setPixmap(
            QPixmap(":/arrow-right.png").scaledToWidth(32))

        layoutFinal = QHBoxLayout()
        layoutFinal.addWidget(labelAct)
        layoutFinal.addLayout(actionLayout1)
        layoutFinal.addWidget(self.arrowLabel)
        layoutFinal.addLayout(actionLayout2)
        layoutFinal.addWidget(self.arrowLabel2)
        layoutFinal.addWidget(self.addAction)

        layoutFinal.addStretch(1)
        self.setLayout(layoutFinal)

    def createToolbar(self):
        """
        Create toolbar
        """
        pass

    def createWidgetScreen(self):
        """
        Create screen widget
        """
        self.screenGroup = QGroupBox(self.tr(""))

        # text
        self.checkComboBox = QComboBox(self)
        self.checkComboBox.addItems([
            GuiSteps.OP_ANY, GuiSteps.OP_CONTAINS, GuiSteps.OP_NOTCONTAINS,
            GuiSteps.OP_REGEXP, GuiSteps.OP_NOTREGEXP, GuiSteps.OP_STARTSWITH,
            GuiSteps.OP_NOTSTARTSWITH, GuiSteps.OP_ENDSWITH,
            GuiSteps.OP_NOTENDSWITH
        ])

        self.screenLine = QLineEdit(self)
        self.screenLine.setMinimumWidth(300)
        self.screenLine.setEnabled(False)
        self.screenLine.hide()
        self.screenArea = QTextEdit(self)
        self.screenArea.setMinimumWidth(300)
        self.screenArea.setEnabled(False)

        self.screenCombo = QComboBox(self)
        self.screenCombo.addItems(LIST_TYPES)
        self.screenCombo.setEnabled(False)

        self.screenSaveCombo = QComboBox(self)
        self.screenSaveCombo.addItems(["VARIABLE", "CACHE"])
        self.screenSaveLine = QLineEdit(self)
        self.screenSaveLine.setMinimumWidth(300)
        self.screenSaveLine.setEnabled(False)

        mainTextlayout = QGridLayout()
        mainTextlayout.addWidget(QLabel(self.tr("Checking if the screen: ")),
                                 0, 0)
        mainTextlayout.addWidget(self.checkComboBox, 0, 1)
        mainTextlayout.addWidget(QLabel(self.tr("The value:")), 1, 0)
        mainTextlayout.addWidget(self.screenCombo, 1, 1)
        mainTextlayout.addWidget(self.screenLine, 2, 1)
        mainTextlayout.addWidget(self.screenArea, 2, 1)
        mainTextlayout.addWidget(QLabel(self.tr("And save the screen in:")), 0,
                                 2)
        mainTextlayout.addWidget(self.screenSaveCombo, 1, 2)
        mainTextlayout.addWidget(self.screenSaveLine, 2, 2)

        self.screenGroup.setLayout(mainTextlayout)
        self.screenGroup.hide()

    def createWidgetText(self):
        """
        Create text widget
        """
        self.textGroup = QGroupBox(self.tr(""))

        # text
        self.textLine = QLineEdit(self)
        self.textLine.setMinimumWidth(300)
        self.textCombo = QComboBox(self)
        self.textCombo.addItems(LIST_TYPES)

        mainTextlayout = QGridLayout()
        mainTextlayout.addWidget(QLabel(self.tr("Send the value:")), 0, 0)
        mainTextlayout.addWidget(self.textCombo, 0, 1)
        mainTextlayout.addWidget(self.textLine, 0, 2)

        self.textGroup.setLayout(mainTextlayout)
        self.textGroup.hide()

    def createWidgetShortcut(self):
        """
        Create shortcut widget
        """
        self.shortcutGroup = QGroupBox(self.tr(""))

        # text
        self.shortcutComboBox = QComboBox()
        self.shortcutComboBox.addItems([KEY_CTRLC, KEY_ENTER])
        self.shortcutComboBox.setMinimumWidth(300)

        mainTextlayout = QGridLayout()
        mainTextlayout.addWidget(QLabel(self.tr("Shortcut:")), 0, 0)
        mainTextlayout.addWidget(self.shortcutComboBox, 0, 1)

        self.shortcutGroup.setLayout(mainTextlayout)
        self.shortcutGroup.hide()

    def createWidgetSession(self):
        """
        Create session widget
        """
        self.sessionGroup = QGroupBox(self.tr(""))

        # login
        self.loginLine = QLineEdit(self)
        self.loginLine.setMinimumWidth(300)
        self.loginCombo = QComboBox(self)
        self.loginCombo.addItems(LIST_TYPES)

        # password
        self.pwdLine = QLineEdit(self)
        self.pwdLine.setMinimumWidth(300)
        self.pwdCombo = QComboBox(self)
        self.pwdCombo.addItems(LIST_TYPES)

        # ip
        self.ipLine = QLineEdit(self)
        self.ipLine.setMinimumWidth(300)
        self.ipCombo = QComboBox(self)
        self.ipCombo.addItems(LIST_TYPES)

        # port
        self.portLine = QLineEdit(self)
        self.portLine.setMinimumWidth(300)
        self.portLine.setText("22")
        self.portLine.setValidator(self.validatorInt)
        self.portCombo = QComboBox(self)
        self.portCombo.addItems(LIST_TYPES)

        # agent support
        self.useAgent = QCheckBox("Use with agent mode")

        mainTextlayout = QGridLayout()
        mainTextlayout.addWidget(QLabel(self.tr("Host:")), 0, 0)
        mainTextlayout.addWidget(self.ipCombo, 0, 1)
        mainTextlayout.addWidget(self.ipLine, 0, 2)
        mainTextlayout.addWidget(QLabel(self.tr("Port (optional):")), 1, 0)
        mainTextlayout.addWidget(self.portCombo, 1, 1)
        mainTextlayout.addWidget(self.portLine, 1, 2)
        mainTextlayout.addWidget(QLabel(self.tr("Login:"******"Password:"******"""
        Create qt connections
        """
        self.actionsComboBox.currentIndexChanged.connect(self.onActionChanged)
        self.addAction.clicked.connect(self.addStep)

        self.ipCombo.currentIndexChanged.connect(self.onIpTypeChanged)
        self.portCombo.currentIndexChanged.connect(self.onPortTypeChanged)
        self.loginCombo.currentIndexChanged.connect(self.onLoginTypeChanged)
        self.pwdCombo.currentIndexChanged.connect(self.onPwdTypeChanged)

        self.textCombo.currentIndexChanged.connect(self.onTextTypeChanged)
        self.screenCombo.currentIndexChanged.connect(self.onScreenTypeChanged)
        self.checkComboBox.currentIndexChanged.connect(
            self.onScreenOperatorChanged)
        self.screenSaveCombo.currentIndexChanged.connect(
            self.onScreenSaveChanged)

    def pluginDataAccessor(self):
        """
        Return data to plugin
        """
        return {"data": ""}

    def onPluginImport(self, dataJson):
        """
        Received data from plugins
        """
        if "steps" not in dataJson:
            QMessageBox.warning(self, "Assistant Automation", "bad import")
            return

        if not isinstance(dataJson['steps'], list):
            QMessageBox.warning(self, "Assistant Automation", "bad import")
            return

        if not ('ip' in dataJson and 'login' in dataJson
                and 'password' in dataJson):
            QMessageBox.warning(self, "Assistant Automation", "bad import")
            return

        # emit open session
        parameters = {
            'dest-ip': dataJson['ip'],
            'dest-port': 22,
            'login': dataJson['login'],
            'password': dataJson['password'],
            'from-cache-ip': False,
            'from-alias-ip': False,
            'from-cache-port': False,
            'from-alias-port': False,
            'from-cache-login': False,
            'from-alias-login': False,
            'from-cache-pwd': False,
            'from-alias-pwd': False,
            'agent-support': False
        }
        self.AddStep.emit(GuiSteps.SYSTEM_SESSION, EMPTY_VALUE, EMPTY_VALUE,
                          parameters)

        for stp in dataJson['steps']:
            if isinstance(stp, dict):

                # new in v16
                fromCache = False
                fromAlias = False
                if "type-value" in stp:
                    if stp["type-value"].lower() == "cache": fromCache = True
                    if stp["type-value"].lower() == "alias": fromAlias = True
                # end of new

                if stp["action-name"] == "SEND":
                    parameters = {
                        'text': stp["action-value"],
                        'from-cache': fromCache,
                        'from-alias': fromAlias
                    }
                    self.AddStep.emit(GuiSteps.SYSTEM_TEXT, EMPTY_VALUE,
                                      EMPTY_VALUE, parameters)
                elif stp["action-name"] == "EXPECT":
                    op = "Contains"
                    if stp["action-type"] == "REGEX":
                        op = "RegEx"
                    parameters = {
                        'value': stp["action-value"],
                        'from-cache': fromCache,
                        'from-alias': fromAlias,
                        'operator': op,
                        'to-cache': False,
                        'cache-key': ''
                    }
                    self.AddStep.emit(GuiSteps.SYSTEM_CHECK_SCREEN,
                                      EMPTY_VALUE, EMPTY_VALUE, parameters)
                else:
                    QMessageBox.warning(
                        self, "Assistant Automation",
                        "action not yet supported: %s" % stp["action-name"])

        # close
        self.AddStep.emit(GuiSteps.SYSTEM_CLOSE, EMPTY_VALUE, EMPTY_VALUE, {})

    def onScreenOperatorChanged(self):
        """
        On screen operator changed
        """
        if self.checkComboBox.currentText() == GuiSteps.OP_ANY:
            self.screenLine.setEnabled(False)
            self.screenArea.setEnabled(False)
            self.screenCombo.setEnabled(False)
        else:
            self.screenLine.setEnabled(True)
            self.screenArea.setEnabled(True)
            self.screenCombo.setEnabled(True)

    def onScreenSaveChanged(self):
        """
        On screen save changed
        """
        if self.screenSaveCombo.currentText() == "VARIABLE":
            self.screenSaveLine.setEnabled(False)
        else:
            self.screenSaveLine.setEnabled(True)

    def onScreenTypeChanged(self):
        """
        On screen type changed
        """
        if self.screenCombo.currentText() in ["TEXT"]:
            self.screenArea.show()
            self.screenLine.hide()
        else:
            self.screenLine.show()
            self.screenArea.hide()
            if self.screenCombo.currentText() in ["CACHE"]:
                self.screenLine.setValidator(self.validatorAll)

            if self.screenCombo.currentText() == "ALIAS":
                self.screenLine.setText(self.screenLine.text().upper())
                self.screenLine.setValidator(self.validatorUpper)

    def onTextTypeChanged(self):
        """
        On text type changed
        """
        if self.textCombo.currentText() in ["TEXT", "CACHE"]:
            self.textLine.setValidator(self.validatorAll)

        if self.textCombo.currentText() == "ALIAS":
            self.textLine.setText(self.textLine.text().upper())
            self.textLine.setValidator(self.validatorUpper)

    def onLoginTypeChanged(self):
        """
        On login type changed
        """
        if self.loginCombo.currentText() in ["TEXT", "CACHE"]:
            self.loginLine.setValidator(self.validatorAll)

        if self.loginCombo.currentText() == "ALIAS":
            self.loginLine.setText(self.loginLine.text().upper())
            self.loginLine.setValidator(self.validatorUpper)

    def onPwdTypeChanged(self):
        """
        On password type changed
        """
        if self.pwdCombo.currentText() in ["TEXT", "CACHE"]:
            self.pwdLine.setValidator(self.validatorAll)

        if self.pwdCombo.currentText() == "ALIAS":
            self.pwdLine.setText(self.pwdLine.text().upper())
            self.pwdLine.setValidator(self.validatorUpper)

    def onIpTypeChanged(self):
        """
        On ip type changed
        """
        if self.ipCombo.currentText() in ["TEXT", "CACHE"]:
            self.ipLine.setValidator(self.validatorAll)

        if self.ipCombo.currentText() == "ALIAS":
            self.ipLine.setText(self.ipLine.text().upper())
            self.ipLine.setValidator(self.validatorUpper)

    def onPortTypeChanged(self):
        """
        On port type changed
        """
        if self.portCombo.currentText() in ["TEXT"]:
            self.portLine.setText("22")
            self.portLine.setValidator(self.validatorInt)

        if self.portCombo.currentText() in ["CACHE"]:
            self.portLine.setValidator(self.validatorAll)

        if self.portCombo.currentText() == "ALIAS":
            self.portLine.setText(self.portLine.text().upper())
            self.portLine.setValidator(self.validatorUpper)

    def onActionChanged(self):
        """
        On action changed
        """
        descr = 'No description available!'
        i = 0
        for el in GuiSteps.ACTION_SYSTEM_DESCR:
            if isinstance(el, dict):
                if self.actionsComboBox.currentText() in el:
                    descr = GuiSteps.ACTION_SYSTEM_DESCR[i][
                        self.actionsComboBox.currentText()]
                    break
            i += 1
        self.labelActionDescr.setText("%s\n" % descr)

        if self.actionsComboBox.currentText() in [GuiSteps.SYSTEM_SESSION]:
            self.sessionGroup.show()
            self.textGroup.hide()
            self.shortcutGroup.hide()
            self.screenGroup.hide()

            self.arrowLabel.show()
            self.arrowLabel2.show()

        elif self.actionsComboBox.currentText() in [GuiSteps.SYSTEM_CLOSE]:
            self.sessionGroup.hide()
            self.textGroup.hide()
            self.shortcutGroup.hide()
            self.screenGroup.hide()

            self.arrowLabel.hide()
            self.arrowLabel2.show()

        elif self.actionsComboBox.currentText() in [
                GuiSteps.SYSTEM_CLEAR_SCREEN
        ]:
            self.sessionGroup.hide()
            self.textGroup.hide()
            self.shortcutGroup.hide()
            self.screenGroup.hide()

            self.arrowLabel.hide()
            self.arrowLabel2.show()

        elif self.actionsComboBox.currentText() in [GuiSteps.SYSTEM_TEXT]:
            self.sessionGroup.hide()
            self.textGroup.show()
            self.shortcutGroup.hide()
            self.screenGroup.hide()

            self.arrowLabel.show()
            self.arrowLabel2.show()

        elif self.actionsComboBox.currentText() in [GuiSteps.SYSTEM_SHORTCUT]:
            self.sessionGroup.hide()
            self.textGroup.hide()
            self.shortcutGroup.show()
            self.screenGroup.hide()

            self.arrowLabel.show()
            self.arrowLabel2.show()

        elif self.actionsComboBox.currentText() in [
                GuiSteps.SYSTEM_CHECK_SCREEN
        ]:
            self.sessionGroup.hide()
            self.textGroup.hide()
            self.shortcutGroup.hide()
            self.screenGroup.show()

            self.arrowLabel.show()
            self.arrowLabel2.show()

        else:
            self.sessionGroup.hide()
            self.textGroup.hide()
            self.shortcutGroup.hide()
            self.screenGroup.hide()

            self.arrowLabel.hide()
            self.arrowLabel2.hide()

    def addStep(self):
        """
        Add step
        """
        action = self.actionsComboBox.currentText()
        descr = self.descriptionLine.text()
        descr = unicode(descr).replace('"', '')

        signal = self.AddStep
        if self.cancelAction.isEnabled():
            signal = self.UpdateStep

        if action in [GuiSteps.SYSTEM_SESSION]:
            fromCacheIp = False
            if self.ipCombo.currentText() == "CACHE": fromCacheIp = True
            fromAliasIp = False
            if self.ipCombo.currentText() == "ALIAS": fromAliasIp = True

            fromCachePort = False
            if self.portCombo.currentText() == "CACHE": fromCachePort = True
            fromAliasPort = False
            if self.portCombo.currentText() == "ALIAS": fromAliasPort = True

            fromCacheLogin = False
            if self.loginCombo.currentText() == "CACHE": fromCacheLogin = True
            fromAliasLogin = False
            if self.loginCombo.currentText() == "ALIAS": fromAliasLogin = True

            fromCachePwd = False
            if self.pwdCombo.currentText() == "CACHE": fromCachePwd = True
            fromAliasPwd = False
            if self.pwdCombo.currentText() == "ALIAS": fromAliasPwd = True

            newIp = self.ipLine.text()
            if not len(newIp):
                QMessageBox.warning(self, "Assistant",
                                    "Please to provide a ip!")
                return

            newPort = self.portLine.text()
            if not len(newPort):
                QMessageBox.warning(self, "Assistant",
                                    "Please to provide a port!")
                return

            newLogin = self.loginLine.text()
            if not len(newLogin):
                QMessageBox.warning(self, "Assistant",
                                    "Please to provide a login!")
                return

            newPwd = self.pwdLine.text()
            agentSupport = "False"
            if self.useAgent.isChecked(): agentSupport = "True"

            parameters = {
                'dest-ip': newIp,
                'dest-port': newPort,
                'login': newLogin,
                'password': newPwd,
                'from-cache-ip': fromCacheIp,
                'from-alias-ip': fromAliasIp,
                'from-cache-port': fromCachePort,
                'from-alias-port': fromAliasPort,
                'from-cache-login': fromCacheLogin,
                'from-alias-login': fromAliasLogin,
                'from-cache-pwd': fromCachePwd,
                'from-alias-pwd': fromAliasPwd,
                'agent-support': agentSupport
            }
            signal.emit(str(action), unicode(descr), EMPTY_VALUE, parameters)

        elif action in [GuiSteps.SYSTEM_CLOSE]:
            signal.emit(str(action), unicode(descr), EMPTY_VALUE, {})

        elif action in [GuiSteps.SYSTEM_CLEAR_SCREEN]:
            signal.emit(str(action), unicode(descr), EMPTY_VALUE, {})

        elif action in [GuiSteps.SYSTEM_TEXT]:
            fromCache = False
            if self.textCombo.currentText() == "CACHE": fromCache = True
            fromAlias = False
            if self.textCombo.currentText() == "ALIAS": fromAlias = True

            newText = self.textLine.text()
            if not len(newText):
                QMessageBox.warning(self, "Assistant",
                                    "Please to provide text!")
                return
            parameters = {
                'text': newText,
                'from-cache': fromCache,
                'from-alias': fromAlias
            }
            signal.emit(str(action), unicode(descr), EMPTY_VALUE, parameters)

        elif action in [GuiSteps.SYSTEM_SHORTCUT]:

            newShortcut = self.shortcutComboBox.currentText()
            parameters = {'shortcut': newShortcut}
            signal.emit(str(action), unicode(descr), EMPTY_VALUE, parameters)

        elif action in [GuiSteps.SYSTEM_CHECK_SCREEN]:
            op = self.checkComboBox.currentText()
            fromCache = False
            if self.screenCombo.currentText() == "CACHE": fromCache = True
            fromAlias = False
            if self.screenCombo.currentText() == "ALIAS": fromAlias = True

            toCache = False
            if self.screenSaveCombo.currentText() == "CACHE": toCache = True
            keyCache = self.screenSaveLine.text()

            newText = ""
            if op != GuiSteps.OP_ANY:
                if fromCache or fromAlias:
                    newText = self.screenLine.text()
                else:
                    newText = self.screenArea.toPlainText()
                if not len(newText):
                    QMessageBox.warning(self, "Assistant",
                                        "Please to provide value to search!")
                    return

            parameters = {
                'value': newText,
                'from-cache': fromCache,
                'from-alias': fromAlias,
                'operator': op,
                'to-cache': toCache,
                'cache-key': keyCache
            }
            signal.emit(str(action), unicode(descr), EMPTY_VALUE, parameters)

        else:
            signal.emit(str(action), unicode(descr), EMPTY_VALUE, {})

    def cancelStep(self):
        """
        Cancel step
        """
        self.addAction.setText("&Add")

        buttonFont = QFont()
        buttonFont.setBold(False)
        self.addAction.setFont(buttonFont)
        self.cancelAction.setEnabled(False)

        self.CancelEdit.emit()

    def finalizeUpdate(self):
        """
        Finalize the update of the step
        """
        self.addAction.setText("&Add Action")

        buttonFont = QFont()
        buttonFont.setBold(False)
        self.addAction.setFont(buttonFont)
        self.cancelAction.setEnabled(False)

    def editStep(self, stepData):
        """
        Edit step
        """
        self.addAction.setText("&Update")
        buttonFont = QFont()
        buttonFont.setBold(True)
        self.addAction.setFont(buttonFont)

        self.cancelAction.setEnabled(True)

        # set the current value for actions combo
        for i in xrange(self.actionsComboBox.count()):
            item_text = self.actionsComboBox.itemText(i)
            if unicode(stepData["action"]) == unicode(item_text):
                self.actionsComboBox.setCurrentIndex(i)
                break

        # and then refresh options
        self.onActionChanged()

        # finally fill all fields
        self.descriptionLine.setText(stepData["description"])

        if self.actionsComboBox.currentText() in [GuiSteps.SYSTEM_SESSION]:
            self.ipLine.setText(stepData["parameters"]["dest-ip"])
            self.portLine.setText("%s" % stepData["parameters"]["dest-port"])
            self.loginLine.setText(stepData["parameters"]["login"])
            self.pwdLine.setText(stepData["parameters"]["password"])

            if stepData["parameters"]["from-cache-ip"]:
                self.ipLine.setValidator(self.validatorAll)
                self.ipCombo.setCurrentIndex(INDEX_CACHE)
            elif stepData["parameters"]["from-alias-ip"]:
                self.ipLine.setValidator(self.validatorUpper)
                self.ipCombo.setCurrentIndex(INDEX_ALIAS)
            else:
                self.ipLine.setValidator(self.validatorAll)
                self.ipCombo.setCurrentIndex(INDEX_TEXT)

            if stepData["parameters"]["from-cache-port"]:
                self.portLine.setValidator(self.validatorAll)
                self.portCombo.setCurrentIndex(INDEX_CACHE)
            elif stepData["parameters"]["from-alias-port"]:
                self.portLine.setValidator(self.validatorUpper)
                self.portCombo.setCurrentIndex(INDEX_ALIAS)
            else:
                self.portLine.setValidator(self.validatorInt)
                self.portCombo.setCurrentIndex(INDEX_TEXT)

            if stepData["parameters"]["from-cache-login"]:
                self.loginLine.setValidator(self.validatorAll)
                self.loginCombo.setCurrentIndex(INDEX_CACHE)
            elif stepData["parameters"]["from-alias-login"]:
                self.loginLine.setValidator(self.validatorUpper)
                self.loginCombo.setCurrentIndex(INDEX_ALIAS)
            else:
                self.loginLine.setValidator(self.validatorAll)
                self.loginCombo.setCurrentIndex(INDEX_TEXT)

            if stepData["parameters"]["from-cache-pwd"]:
                self.pwdLine.setValidator(self.validatorAll)
                self.pwdCombo.setCurrentIndex(INDEX_CACHE)
            elif stepData["parameters"]["from-alias-pwd"]:
                self.pwdLine.setValidator(self.validatorUpper)
                self.pwdCombo.setCurrentIndex(INDEX_ALIAS)
            else:
                self.pwdLine.setValidator(self.validatorAll)
                self.pwdCombo.setCurrentIndex(INDEX_TEXT)

        if self.actionsComboBox.currentText() in [GuiSteps.SYSTEM_CLOSE]:
            pass

        if self.actionsComboBox.currentText() in [
                GuiSteps.SYSTEM_CLEAR_SCREEN
        ]:
            pass

        if self.actionsComboBox.currentText() in [GuiSteps.SYSTEM_TEXT]:

            if stepData["parameters"]["from-cache"]:
                self.textLine.setValidator(self.validatorAll)
                self.textCombo.setCurrentIndex(INDEX_CACHE)
            elif stepData["parameters"]["from-alias"]:
                self.textLine.setValidator(self.validatorUpper)
                self.textCombo.setCurrentIndex(INDEX_ALIAS)
            else:
                self.textLine.setValidator(self.validatorAll)
                self.textCombo.setCurrentIndex(INDEX_TEXT)

            self.textLine.setText(stepData["parameters"]["text"])

        if self.actionsComboBox.currentText() in [GuiSteps.SYSTEM_SHORTCUT]:

            for i in xrange(self.shortcutComboBox.count()):
                item_text = self.shortcutComboBox.itemText(i)
                if unicode(stepData["parameters"]["shortcut"]) == unicode(
                        item_text):
                    self.shortcutComboBox.setCurrentIndex(i)
                    break

        if self.actionsComboBox.currentText() in [
                GuiSteps.SYSTEM_CHECK_SCREEN
        ]:

            if stepData["parameters"]["from-cache"]:
                self.screenLine.setValidator(self.validatorAll)
                self.screenCombo.setCurrentIndex(INDEX_CACHE)
                self.screenLine.setText(stepData["parameters"]["value"])
            elif stepData["parameters"]["from-alias"]:
                self.screenLine.setValidator(self.validatorUpper)
                self.screenCombo.setCurrentIndex(INDEX_ALIAS)
                self.screenLine.setText(stepData["parameters"]["value"])
            else:
                self.screenCombo.setCurrentIndex(INDEX_TEXT)
                self.screenArea.setPlainText(stepData["parameters"]["value"])

            for i in xrange(self.checkComboBox.count()):
                item_text = self.checkComboBox.itemText(i)
                if unicode(stepData["parameters"]["operator"]) == unicode(
                        item_text):
                    self.checkComboBox.setCurrentIndex(i)
                    break

            if stepData["parameters"]["to-cache"]:
                self.screenSaveCombo.setCurrentIndex(1)
                self.screenSaveLine.setText(
                    stepData["parameters"]["cache-key"])
            else:
                self.screenSaveCombo.setCurrentIndex(0)

    def getTimeout(self):
        """
        Return timeout value
        """
        return self.optionsDialog.timeoutLine.text()

    def setTimeout(self, timeout):
        """
        Set the timeout
        """
        return self.optionsDialog.timeoutLine.setText(timeout)

    def getAgentName(self):
        """
        Return the agent name
        """
        return self.optionsDialog.agentNameLine.text()

    def getAgentList(self):
        """
        Return the agent list
        """
        return self.optionsDialog.agentsList
Esempio n. 55
0
class QuestionDlg(QDialog):
    def __init__(self,parent=None):
        super(QuestionDlg,self).__init__(parent)
        # self.setStyleSheet("background-image:url('image/panelbg.jpg'); border: 2px; border-radius 2px;")
        self.setWindowFlags(Qt.CustomizeWindowHint)
        # self.setStyleSheet("border: 2px; border-radius 2px;")
        # self.setWindowFlags(Qt.FramelessWindowHint)
        
        tabWidget=QTabWidget(self)
        tabWidget.currentChanged.connect(self.changeTab)
        # tabWidget.setTabShape(QTabWidget.Triangular)
        tabWidget.setStyleSheet("QTabWidget::pane{border:0px;}\
            QTabBar::tab { height: 60px; width: 260px; color:rgb(0, 0, 255); font-size:20px; font-weight:bold;} \
            QTabBar::tab:hover{background:rgb(255,255, 255, 100);} \
            QTabBar::tab:selected{border-color:green;background-color:white;color:green;}")
        # tabWidget.setStyleSheet("QTabBar::tab:hover{background:rgb(255,255, 255, 100);}")
        self.btngroup = QButtonGroup()

        w1=QWidget()
        w1.setAccessibleName("w1tab")
        self.w1title = QComboBox()
        self.btn_start = QPushButton("开始")
        self.choicenum_text = QComboBox()
        self.choicenum_text.setObjectName('w1combonums')
        # self.w1title.setStyleSheet("background-image:url('image/panelbg.jpg');")

        titleLayout, btnlayout, bottomlayout = self.genOneTab(tabtitle = self.w1title, tabbtn=self.btn_start, tabnums=self.choicenum_text)

        tab1layout = QVBoxLayout()
        tab1layout.addLayout(titleLayout)       
        tab1layout.addLayout(btnlayout)
        tab1layout.addLayout(bottomlayout)
                
        w1.setLayout(tab1layout)
        # w1.setStyleSheet("background-image: url(image/bg.gif);")
        w1.setStyleSheet("background-color: QLinearGradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffffff, stop: 1 #228888);")
        # w1.setStyleSheet("border-image: url(image/bg2.gif);")
        # firstUi.setupUi(w1)
        w2=QWidget()
        w2.setAccessibleName("w2tab")
        self.w2title = QComboBox()
        self.btn_start2 = QPushButton("开始")
        self.choicenum_text2 = QComboBox()
        self.choicenum_text2.setObjectName('w2combonums')
        titleLayout2, btnlayout2, bottomlayout2 = self.genOneTab(tabtitle = self.w2title, tabbtn=self.btn_start2, tabnums=self.choicenum_text2, strwhere = "where studentsn like '04%' ")
        tab2layout = QVBoxLayout()
        tab2layout.addLayout(titleLayout2)       
        tab2layout.addLayout(btnlayout2)
        tab2layout.addLayout(bottomlayout2)
        w2.setLayout(tab2layout)
        # w2.setStyleSheet("background-image: url(image/bg.gif);")
        w2.setStyleSheet("background-color: QLinearGradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffffff, stop: 1 #228888);")

        tabWidget.addTab(w1,"三(3)班")
        tabWidget.addTab(w2,"三(4)班")
        tabWidget.resize(760,700)
        # print(tabWidget.parentWidget())
        btnclose = QPushButton(self)
        btnclose.setText("╳")
        btnclose.setGeometry(735, 5, 20, 20)
        btnclose.setStyleSheet("background-color:rgb(0,100,0); color:rgb(255,255,255)")
        btnclose.clicked.connect(self.close)
        btnMinimized = QPushButton(self)
        btnMinimized.setText("▁")
        btnMinimized.setGeometry(710, 5, 20, 20)
        btnMinimized.setStyleSheet("background-color:rgb(0,100,0); color:rgb(255,255,255)")
        btnMinimized.clicked.connect(lambda: self.showMinimized())
        btnSysMenu = QPushButton(self)
        btnSysMenu.setText("▼")
        btnSysMenu.setGeometry(685, 5, 20, 20)
        btnSysMenu.setStyleSheet("background-color:rgb(0,100,0); color:rgb(255,255,255)")
        btnSysMenu.clicked.connect(lambda: self.showMinimized())
        popMenu = QMenu(self)
        entry1 = popMenu.addAction("初始化")
        self.connect(entry1,SIGNAL('triggered()'), self.initStudent)
        entry2 = popMenu.addAction("清除提问人员")
        self.connect(entry2,SIGNAL('triggered()'), self.deleteTmpdata)
        btnSysMenu.setMenu(popMenu)
        btnSysMenu.setStyleSheet("QPushButton::menu-indicator {image: url('image/sysmenu.png');subcontrol-position: right center;}")

        self.lstchoices = []
        self.threadcounter = 0
        # self.createDb()
        cur = conn.cursor()
        # today = datetime.date.today() 
        # cur.execute("delete from tmprecord where datequestion= '" +str(today) + "'") #delete tmp date no today
        cur.execute("delete from tmprecord where 1=1" )
        # cur.execute("delete from tmprecord where datequestion!= '" +str(today) + "'") #delete tmp date no today
        conn.commit()

        cur.execute("select studentsn from student ")
        self.studentSnlst = cur.fetchall()
        cur.close()

        # self.btncolor = self.btngroup.buttons()[0].palette().color(1).getRgb()
        # for i in list(range(0, self.studentNums)):
        # for isn in self.studentSnlst:
        #     self.btngroup.button(int(isn[0])).setStyleSheet("border-image: url(image/ex_stu.png);")
            # print(isn)
        # for i in list(range(0, self.studentNums)):
            # self.btngroup.buttons()[i].setStyleSheet("background-color: rgb(120,220,220);")
            # self.btngroup.buttons()[i].setStyleSheet("border-image: url(image/ex_stu.png);")
            # self.btngroup.buttons()[i].setStyleSheet("background-image: url(image/ex_stu.png);background-size:20px 20px;")

        # print("background-color: rgb(120,220,220);", "background-color: rgb" + str(self.btncolor) + ";")
        self.setWindowTitle("课堂随机提问")
        self.setWindowIcon(QIcon("image/start.ico"))
        self.setGeometry(100, 20, 760, 700)

        self.connect(self.btn_start, SIGNAL("clicked()"), self.startChoice)
        self.connect(self.w1title, SIGNAL("currentIndexChanged(int)"), self.changeTitle)
        self.connect(self.btn_start2, SIGNAL("clicked()"), self.startChoice)
        self.connect(self.w2title, SIGNAL("currentIndexChanged(int)"), self.changeTitle)

    def initStudent(self):
        cur = conn.cursor()
        cur.execute("update student set wrongquestions=0")
        conn.commit()
        cur.execute("update student set rightquestions=0")
        conn.commit()

        # cur.execute("select * from student")
        # print(cur.fetchall())
        cur.close()

    def deleteTmpdata(self):
        cur = conn.cursor()
        cur.execute("delete from tmprecord where 1=1" )
        conn.commit()
        cur.close()

    def changeTab(self, curtab):
        if curtab == 0:
            strwhere = " and studentsn like '03%' "
        elif curtab == 1:
            strwhere = " and studentsn like '04%' "

        self.lstchoices = []
        self.threadcounter = 0
        cur = conn.cursor()   
        cur.execute("select studentsn from student where 1=1 " + strwhere)
        self.studentSnlst = cur.fetchall()
        for isn in self.studentSnlst:
            self.btngroup.button(int(isn[0])).setStyleSheet("border-image: url(image/ex_stu.png); color:dark;")
            self.btngroup.button(int(isn[0])).setIcon(QIcon())
            # self.btngroup.buttons()[i].setStyleSheet("background-color: rgb(120,220,220);")  
            # self.btngroup.buttons()[i].setStyleSheet("border-image: url(image/ex_stu.png);")
            curmenu = self.btngroup.button(int(isn[0])).menu()
            curmenu.actions()[0].setEnabled(True)
            curmenu.actions()[1].setEnabled(True)
            
        cur.close()

    def mousePressEvent(self, event):
        self.offset = event.pos()
        # print(self.offset)
    def mouseMoveEvent(self, event):
        x=event.globalX()
        y=event.globalY()
        x_w = self.offset.x()
        y_w = self.offset.y()
        self.move(x-x_w, y-y_w)

    def genOneTab(self, tabtitle="", tabbtn="", tabnums="", strwhere = "where studentsn like '03%' "):
        # tabtitle.setFixedHeight(40)
        # tabtitle.setFixedWidth(160)
        tabtitle.setFont(QFont('Courier New', 20))
        tabtitle.setStyleSheet("border: 3px solid blue;\
            border-radius: 6px; \
            padding: 1px 18px 1px 20px;\
            min-width: 8em;")
        model = tabtitle.model()
        for row in ["随堂演板", "随堂提问"]:
            item = QStandardItem(str(row))
            item.setForeground(QColor('blue'))
            item.setBackground(QColor(0,200,50, 130))
            font = item.font()
            font.setPointSize(20)
            item.setFont(font)
            model.appendRow(item)
        tabtitle.setCurrentIndex(0)
        titleLayout = QHBoxLayout()
        tabtitle.setMinimumHeight(50);
        titleLayout.addWidget(tabtitle)
        titleLayout.setAlignment(tabtitle, Qt.AlignCenter)
       
        btnlayout = QGridLayout()
        
        cur = conn.cursor()
        strsql = "select studentsn, studentname from student " + strwhere
        cur.execute(strsql)
     
        tmpnum = 0
        for item in cur.fetchall():
            irow = tmpnum // 7
            icol = tmpnum % 7
            tmpnum += 1
            btnlayout.setRowMinimumHeight(irow, 80)
            tmpbtn = QPushButton(item[1])
            tmpbtn.setFont(QFont('宋体', 16))
            tmpbtn.setSizePolicy(QSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding))

            popMenu = QMenu(self)
            entry1 = popMenu.addAction("正确")
            self.connect(entry1,SIGNAL('triggered()'), lambda item=item[0]: self.answerRight(item))
            entry2 = popMenu.addAction("错误")
            self.connect(entry2,SIGNAL('triggered()'), lambda item=item[0]: self.answerWrong(item))
            entry3 = popMenu.addAction("替换")
            self.connect(entry3,SIGNAL('triggered()'), lambda item=item[0]: self.resetStudent(item))
            tmpbtn.setMenu(popMenu)
            tmpbtn.setAutoDefault(False)
            self.btngroup.addButton(tmpbtn, int(item[0]))
            btnlayout.addWidget(tmpbtn, irow, icol)

        tabbtn.setIcon(QIcon("image/start.png"))
        tabbtn.setStyleSheet("border: 5px solid yellow;")
        tabbtn.setFixedHeight(45)
        tabbtn.setFixedWidth(100)
        tabbtn.setFont(QFont('宋体', 20))
        # tabnums.setFixedHeight(40)
        # tabnums.setFixedWidth(60)
        tabnums.setFont(QFont('Courier New', 20))
        tabnums.setStyleSheet("border: 5px solid blue; color:red;font-weight:bold;font-size:26px;\
            border-radius: 6px; \
            padding: 1px 1px 1px 1px;\
            min-width: 2em; ")
        # tabnums.VerticalContentAlignment="Center"
        # tabnums.addItems(["1", "2", "3", "4", "5", "6"])
        model = tabnums.model()
        for row in list(range(1, 7)):
            item = QStandardItem(str(row))
            # item.setStyleSheet("background-color:rgb(0,0,255)")
            item.setForeground(QColor('red'))
            item.setBackground(QColor(0,200,50, 130))
            # font = item.font()
            # font.setPointSize(16)
            # item.setFont(font)
            model.appendRow(item)
        tabnums.setCurrentIndex(2)

        bottomlayout = QHBoxLayout()
        bottomlayout.setSizeConstraint(QLayout.SetFixedSize)
        bottomlayout.addStretch(10)
        bottomlayout.addWidget(tabbtn)
        bottomlayout.setSpacing(5)
        bottomlayout.addWidget(tabnums)
     
        cur.close()
        return(titleLayout, btnlayout, bottomlayout)

    def changeTitle(self, curindex):
        # whichtabpage = self.sender().parentWidget().parentWidget().parentWidget()
        # print(whichtabpage.tabText(0), whichtabpage1)
        for isn in self.studentSnlst:
            self.btngroup.button(int(isn[0])).setStyleSheet("border-image: url(image/ex_stu.png);")
            self.btngroup.button(int(isn[0])).setIcon(QIcon())
            # self.btngroup.buttons()[i].setStyleSheet("background-color: rgb(120,220,220);")  
            # self.btngroup.buttons()[i].setStyleSheet("border-image: url(image/ex_stu.png);")
            curmenu = self.btngroup.button(int(isn[0])).menu()
            curmenu.actions()[0].setEnabled(True)
            curmenu.actions()[1].setEnabled(True)

        whichtabpage = self.sender().parentWidget().accessibleName()
        if whichtabpage == "w1tab":
            if curindex == 1:
                self.choicenum_text.setCurrentIndex(0)
                self.choicenum_text.setEnabled(False)
            else:
                self.choicenum_text.setEnabled(True)
                self.choicenum_text.setCurrentIndex(2)
        else:
            if curindex == 1:
                self.choicenum_text2.setCurrentIndex(0)
                self.choicenum_text2.setEnabled(False)
            else:
                self.choicenum_text2.setEnabled(True)
                self.choicenum_text2.setCurrentIndex(2)

    def startChoice(self): 
        self.lstchoices = []
        self.threadcounter = 0
        whichtabpage = self.sender().parentWidget().accessibleName()
        if whichtabpage == "w1tab":
            strwhere = " and studentsn like '03%' "
            tabCombonums = self.findChild(QComboBox, 'w1combonums')
        else:
            strwhere = " and studentsn like '04%' "
            tabCombonums = self.findChild(QComboBox, 'w2combonums')

        # for i in list(range(0, self.studentNums)):
        cur = conn.cursor()   
        # cur.execute("select studentsn from student where 1=1 " + strwhere)
        # self.studentSnlst = cur.fetchall()

        # for isn in self.studentSnlst:
        #     self.btngroup.button(int(isn[0])).setStyleSheet("border-image: url(image/ex_stu.png);")
        #     self.btngroup.button(int(isn[0])).setIcon(QIcon())
        #     # self.btngroup.buttons()[i].setStyleSheet("background-color: rgb(120,220,220);")  
        #     # self.btngroup.buttons()[i].setStyleSheet("border-image: url(image/ex_stu.png);")
        #     curmenu = self.btngroup.button(int(isn[0])).menu()
        #     curmenu.actions()[0].setEnabled(True)
        #     curmenu.actions()[1].setEnabled(True)

        allstudent = []
        lstrecord = ['0000', '1111']
        if tabCombonums.isEnabled():
            cur.execute("select studentsn from tmprecord where 1=1 " + strwhere)  
            for item in cur.fetchall():
                lstrecord.append(item[0])
        # print(lstrecord, 'record', "select studentsn from student where studentsn like '03%' and studentsn not in " + str(tuple(lstrecord)))
        cur.execute("select studentsn from student where studentsn not in " + str(tuple(lstrecord)) + strwhere)
        for item in cur.fetchall():
            allstudent.append(item[0])

        nums = int(tabCombonums.currentText())
        if nums >= len(allstudent):
            cur.execute("delete from tmprecord where datequestion like '%%' ") #delete tmp date no today
            conn.commit()
            allstudent = []
            cur.execute("select studentsn from student where 1=1 " + strwhere)
            for item in cur.fetchall():
                allstudent.append(item[0])
        # print(tabCombonums.currentText())
        cur.close()
        for i in range(10):
            thread = MyThread(self)
            thread.trigger.connect(self.choicestudent)
            thread.setup(allstudent, nums)            # just setting up a parameter
            thread.start()

    def choicestudent(self, allstudent, num): 
        for isn in self.studentSnlst:
            self.btngroup.button(int(isn[0])).setStyleSheet("border-image: url(image/ex_stu.png);")
            # self.btngroup.buttons()[i].setStyleSheet("background-color: rgb(120,220,220);")
        random.seed()
        self.lstchoices = random.sample(allstudent, num)
        for ibtn in self.lstchoices:
            self.btngroup.button(int(ibtn)).setStyleSheet("border: 6px solid rgb(255,0,0); color:black; font-size:26px;")
            # self.btngroup.button(int(ibtn)).setStyleSheet("border-image: url(image/ex_stu_ok.png); color:dark;")
            # self.btngroup.button(int(ibtn)).setStyleSheet("background-color: red; color:white;")
            # self.btngroup.buttons()[ibtn].setStyleSheet("background-color: red; color:white;")

        self.threadcounter += 1
        if self.threadcounter == 10:
            for isn in self.studentSnlst:
                self.btngroup.button(int(isn[0])).setStyleSheet("border-image: url(image/ex_stu.png);")
            for ibtn in self.lstchoices:
                self.btngroup.button(int(ibtn)).setStyleSheet("border: 6px solid rgb(255,0,0); color:black; font-size:26px;")

            cur = conn.cursor()
            if self.choicenum_text.isEnabled():
                for ibtn in self.lstchoices:
                    today = datetime.date.today()
                    strsql = "insert into tmprecord values (?, ?, ?)" 
                    cur.execute(strsql, (None, ibtn, today))
                    conn.commit()

            # cur.execute("select * from tmprecord")
            # tmpaa = []
            # for item in cur.fetchall():
            #     tmpaa.append(item[1])
            #     # print(item[1], sep="|", end="--")
            # tmpaa.sort()
            # print(tmpaa)
            
            cur.close()
                # print(self.btngroup.buttons()[ibtn].text())
            self.threadcounter = 0

    def choiceOneStudent(self, curbtn, num=1):
        # print(self.findChildren(QComboBox))
        if curbtn[:2] == "03":
            strwhere = " and studentsn like '03%' "
            tabCombonums = self.findChild(QComboBox, 'w1combonums')
        elif  curbtn[:2] == "04":
            strwhere = " and studentsn like '04%' "
            tabCombonums = self.findChild(QComboBox, 'w2combonums')

        allstudent = []
        cur = conn.cursor()   
        lstrecord = ['0000', '1111']
        if tabCombonums.isEnabled():
            cur.execute("select studentsn from tmprecord where 1=1 " + strwhere)  
            for item in cur.fetchall():
                lstrecord.append(item[0])
        cur.execute("select studentsn from student where studentsn not in " + str(tuple(lstrecord)) + strwhere)
        for item in cur.fetchall():
            allstudent.append(item[0])

        # cur.execute("select * from tmprecord")
        # print(cur.fetchall(), '111111111111111111')
        random.seed()
        otherbtn = random.sample(allstudent, num)[0]
        # self.btngroup.button(int(otherbtn)).setStyleSheet("background-color: red; color:white;")
        # self.btngroup.button(int(otherbtn)).setStyleSheet("border-image: url(image/ex_stu_ok.png);")
        self.btngroup.button(int(otherbtn)).setStyleSheet("border: 6px solid rgb(255,0,0); color:black; font-size:26px;")
        self.btngroup.button(int(otherbtn)).setFocus()

        # print(self.lstchoices, 'choice one another00000000000000001')
        self.lstchoices.remove(curbtn)
        self.lstchoices.append(otherbtn)
        # print(self.lstchoices, 'choice one another000000000000000002')

        # cur.execute("delete from tmprecord where studentsn='" + curbtn + "'") # can not delete ,because this student is ill.
        # conn.commit()
        if tabCombonums.isEnabled():
            today = datetime.date.today()
            cur.execute("insert into tmprecord values (?, ?, ?)", (None, otherbtn, today))
            conn.commit()
        # cur.execute("select * from tmprecord")
        # print(cur.fetchall(), '2222222222222')

        cur.close()

    def answerRight(self, value):
        if value not in self.lstchoices:
            return

        self.btngroup.button(int(value)).setIcon(QIcon("image/smile.png"))
        self.btngroup.button(int(value)).setIconSize(QSize(20,20))

        cur = conn.cursor()
        cur.execute("select rightquestions from student where studentsn='" + value + "'")
        studentRightQuestions = cur.fetchall()[0][0] + 1
        cur.execute("update student set rightquestions=" + str(studentRightQuestions) + " where studentsn='" + value + "'")
        conn.commit()
        
        curmenu = self.btngroup.button(int(value)).menu()
        if not curmenu.actions()[1].isEnabled (): # must delete wrongquestionnums
            cur.execute("select wrongquestions from student where studentsn='" + value + "'")
            studentWrongQuestions = cur.fetchall()[0][0] - 1
            cur.execute("update student set wrongquestions=" + str(studentWrongQuestions) + " where studentsn='" + value + "'")
            conn.commit()
        curmenu.actions()[0].setEnabled(False)
        curmenu.actions()[1].setEnabled(True)
        # curmenu.actions()[2].setEnabled(False)
        
        # cur.execute("select * from student where studentsn='" + value + "'")
        # print(cur.fetchall(), 'right-------')

        cur.close()

    def answerWrong(self, value):
        if value not in self.lstchoices:
            return

        self.btngroup.button(int(value)).setIcon(QIcon("image/cry.png"))
        self.btngroup.button(int(value)).setIconSize(QSize(20,20))
        # self.btngroup.button(int(value)).setStyleSheet("border-image: url(image/ex_stu.png);")

        cur = conn.cursor()
        cur.execute("select wrongquestions from student where studentsn='" + value + "'")
        studentWrongQuestions = cur.fetchall()[0][0] + 1
        cur.execute("update student set wrongquestions=" + str(studentWrongQuestions) + " where studentsn='" + value + "'")
        conn.commit()

        curmenu = self.btngroup.button(int(value)).menu()
        if not curmenu.actions()[0].isEnabled (): # must delete wrongquestionnums
            cur.execute("select rightquestions from student where studentsn='" + value + "'")
            studentRightQuestions = cur.fetchall()[0][0] - 1
            cur.execute("update student set rightquestions=" + str(studentRightQuestions) + " where studentsn='" + value + "'")
            conn.commit()
        curmenu.actions()[0].setEnabled(True)
        curmenu.actions()[1].setEnabled(False)

        # cur.execute("select * from student where studentsn='" + value + "'")
        # print(cur.fetchall(), 'wrong--')

        cur.close()

    def resetStudent(self, value):
        if value not in self.lstchoices:
            return

        # self.btngroup.button(int(value)).setStyleSheet("background-color: rgb(120,220,220);")
        self.btngroup.button(int(value)).setIcon(QIcon())
        self.btngroup.button(int(value)).setStyleSheet("border-image: url(image/ex_stu.png);")
        self.btngroup.button(int(value)).setAutoDefault(False)

        cur = conn.cursor()

        curmenu = self.btngroup.button(int(value)).menu()
        if not curmenu.actions()[0].isEnabled():
            cur.execute("select rightquestions from student where studentsn='" + value + "'")
            studentRightQuestions = cur.fetchall()[0][0] - 1
            cur.execute("update student set rightquestions=" + str(studentRightQuestions) + " where studentsn='" + value + "'")
            conn.commit()
        if not curmenu.actions()[1].isEnabled():
            cur.execute("select wrongquestions from student where studentsn='" + value + "'")
            studentWrongQuestions = cur.fetchall()[0][0] - 1
            cur.execute("update student set wrongquestions=" + str(studentWrongQuestions) + " where studentsn='" + value + "'")
            conn.commit()
        cur.close()

        curmenu.actions()[0].setEnabled(True)
        curmenu.actions()[1].setEnabled(True)
        self.choiceOneStudent(value)

    def createDb(self):
        cur = conn.cursor()
        sqlstr = 'create table student (id integer primary key, \
            studentsn varchar(20), \
            studentname varchar(20), \
            rightquestions integer, \
            wrongquestions integer)'
        # print(sqlstr)

        sqlstr2 = 'create table tmprecord (id integer primary key, \
            studentsn varchar(20), \
            datequestion date)'

        strdelete = "delete from student where 1=1"
        cur.execute(strdelete)
        conn.commit()
        strdelete = "delete from tmprecord where 1=1"
        cur.execute(strdelete)
        conn.commit()
        # print(sqlstr2)

        # cur.execute(sqlstr) 
        # conn.commit()
        # cur.execute(sqlstr2) 
        # conn.commit()

        # insert example data
        a03lst = ["曾忆谊","赵佳泉","翁文秀","林珑","郑铭洁","林泽思","吴崇霖","陈思嘉","欧阳月孜","郭展羽","詹伟哲","黄佳仪","杨秋霞","周奕子","林楚杰","欧伊涵","许腾誉","陈唯凯","陈树凯","林彦君","张钰佳","高锴","杨博凯","林妙菲","林楚鸿","陈展烯","姚静茵","吴欣桐","范思杰","肖佳","马思广","许一帆","姚奕帆","陈海珣","吴黛莹","吴育桐","肖凯帆","林欣阳","叶茂霖","姚楷臻","陈嘉豪","陈琦","杨子楷","陈炎宏","陈幸仪","杨景畅","罗暖婷","郑馨"]
        a04lst = ["罗恩琪","王可","曾祥威","谢濡婷","温嘉凯","许洁仪","肖欣淇","陈凯佳","林天倩","李乐海","吴文慧","黄文婷","万誉","陈进盛","张裕涵","陈振嘉","王巧玲","林珮琪","陈炜楷","杨健","赵泽锴","张凤临","蔡子丹","陈烨杰","廖妍希","林树超","夏培轩","陈锦森","李星","蔡依婷","姚容创","姚凯扬","沈嘉克","周凡","张玉川","邱金迅","陈菲敏","陈星翰","朱煜楷","郑泽洪","钱剑非","罗奕丰","陈杜炜","林知钦"]
        strsql = "insert into student values (?, ?, ?,?,?)" 
        for i in list(range(0,len(a03lst))):
            cur.execute(strsql, (None, "03"+str(i+1).zfill(2), a03lst[i], 0, 0))
            conn.commit()
        strsql = "insert into student values (?, ?, ?,?,?)" 
        for i in list(range(0,len(a04lst))):
            cur.execute(strsql, (None, "04"+str(i+1).zfill(2), a04lst[i], 0, 0))
            conn.commit()
        cur.close()
Esempio n. 56
0
class GithubRepoWizardPage(QWizardPage):
    def __init__(self, github, parent=None):
        super(GithubRepoWizardPage,
              self).__init__(parent,
                             title="Github Repository",
                             subTitle="Configure the new Github repository")

        self.github = github

        # moreButton

        self.moreButton = QPushButton("More",
                                      checkable=True,
                                      clicked=self.more)
        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        moreButtonHBox = QHBoxLayout()
        moreButtonHBox.addWidget(spacer)
        moreButtonHBox.addWidget(self.moreButton)

        #  LineEdits

        self.nameEdit = QLineEdit(textChanged=self.update)
        self.nameEdit.setValidator(
            QRegExpValidator(QRegExp(r'[a-zA-Z0-9-_]+[a-zA-Z0-9-_]*')))
        self.descriptionEdit = QLineEdit(textChanged=self.update)
        self.homepageEdit = QLineEdit(textChanged=self.update)

        # CheckBox

        self.privateCheckBox = QCheckBox(stateChanged=self.update)
        self.initCheckBox = QCheckBox(stateChanged=self.update)
        self.hasWikiCheckBox = QCheckBox(stateChanged=self.update)
        self.hasDownloadsCheckBox = QCheckBox(stateChanged=self.update)
        self.hasIssuesCheckBox = QCheckBox(stateChanged=self.update)

        # gitignoreComboBox

        self.gitignoreComboBox = QComboBox(currentIndexChanged=self.update)
        self.gitignoreComboBox.addItem('None')
        for i in gitignore_types(self.github):
            self.gitignoreComboBox.addItem(i)

        hbox2 = QHBoxLayout()
        hbox2.addWidget(
            QLabel('Initialize this repository with a README and .gitignore'))
        hbox2.addWidget(self.initCheckBox)

        # Extension Form

        self.form_extension = QFormLayout()
        self.form_extension.addRow("Homepage", self.homepageEdit)
        self.form_extension.addRow("Has wiki", self.hasWikiCheckBox)
        self.form_extension.addRow("Has issues", self.hasIssuesCheckBox)
        self.form_extension.addRow("Has downloads", self.hasDownloadsCheckBox)

        # Extension

        self.extension = QWidget()
        self.extension.setLayout(self.form_extension)

        # Form

        self.form = QFormLayout()
        self.form.addRow("Name: ", self.nameEdit)
        self.form.addRow("Description: ", self.descriptionEdit)
        self.form.addRow('Private', self.privateCheckBox)
        self.form.addRow(hbox2)
        self.form.addRow('Add .gitignore', self.gitignoreComboBox)
        self.form.addRow(moreButtonHBox)
        self.form.addRow(self.extension)

        # Layout

        self.mainLayout = QVBoxLayout()
        self.mainLayout.addLayout(self.form)
        self.setLayout(self.mainLayout)

        # Fields

        self.registerField('name*', self.nameEdit)
        self.registerField('description', self.descriptionEdit)
        self.registerField('private', self.privateCheckBox)
        self.registerField('auto_init', self.initCheckBox)
        self.registerField('gitignore', self.gitignoreComboBox, 'currentText')
        self.registerField('homepage', self.homepageEdit)
        self.registerField('has_issues', self.hasIssuesCheckBox)
        self.registerField('has_downloads', self.hasDownloadsCheckBox)
        self.registerField('has_wiki', self.hasWikiCheckBox)

        # Setup

        self.hasWikiCheckBox.toggle()
        self.hasDownloadsCheckBox.toggle()
        self.hasIssuesCheckBox.toggle()
        if not self.github.get_user().plan:
            self.privateCheckBox.setEnabled(False)

        self.extension.hide()

    def update(self):

        if self.initCheckBox.isChecked():
            self.gitignoreComboBox.setEnabled(True)
        else:
            self.gitignoreComboBox.setEnabled(False)

    def more(self):

        if self.moreButton.isChecked():
            self.moreButton.setText("Less")
            self.extension.show()
            self.wizard().resize(self.wizard().sizeHint())
        else:
            self.moreButton.setText("More")
            self.extension.hide()
            size = self.sizeHint()
            wizard_size = self.wizard().sizeHint()
            self.wizard().resize(wizard_size.width(), size.height())