def closeEvent(self, event): if not self.trayIcon.isVisible() and Configuration.icon: self.trayIcon.show() self.hide() event.ignore() else: termine = True # On vérifie que tous les téléchargements soient finis for download in self.downloads.instance.downloads: if download.state == 3: termine = False # Si il y a un download en cours on affiche la fenêtre if not termine and not Configuration.close_window: # Un petit messageBox avec bouton clickable :) msgBox = QMessageBox(QMessageBox.Question, u"Voulez-vous vraiment quitter?", u"Un ou plusieurs téléchargements sont en cours, et pyRex ne gère pas encore la reprise des téléchargements. Si vous quittez maintenant, toute progression sera perdue!") checkBox = QCheckBox(u"Ne plus afficher ce message", msgBox) checkBox.blockSignals(True) msgBox.addButton(checkBox, QMessageBox.ActionRole) msgBox.addButton("Annuler", QMessageBox.NoRole) yesButton = msgBox.addButton("Valider", QMessageBox.YesRole) msgBox.exec_() if msgBox.clickedButton() == yesButton: # On save l'état du bouton à cliquer if checkBox.checkState() == Qt.Checked: Configuration.close_window = True Configuration.write_config() event.accept() else: event.ignore() else: event.accept()
class BoolConfigControl(ConfigControl): def __init__(self, config_item): ConfigControl.__init__(self, config_item) self._init_ui() self.update_from_config() def _init_ui(self): lbl_bool = QLabel(self._config_item.tag()) lbl_bool.setFixedWidth(self.LABEL_WIDTH) self._chk_box = QCheckBox() self._chk_box.setTristate(False) hbox = QHBoxLayout() hbox.setContentsMargins(0, 0, 0, 0) hbox.addWidget(lbl_bool) hbox.addWidget(self._chk_box) hbox.addStretch() self.setLayout(hbox) def update_from_config(self): state = 2 if self._config_item.value() == True else 0 self._chk_box.setCheckState(state) def save_to_config(self): value = True if self._chk_box.checkState() == 2 else False self._config_item.set(value)
class BoolConfigControl(ConfigControl): def __init__(self, config_item): ConfigControl.__init__(self, config_item) self._init_ui() self.update_from_config() def _init_ui(self): lbl_bool = QLabel(self._config_item.tag()) lbl_bool.setFixedWidth(self.LABEL_WIDTH) self._chk_box = QCheckBox() self._chk_box.setTristate(False) hbox = QHBoxLayout() hbox.setContentsMargins(0, 0, 0, 0) hbox.addWidget(lbl_bool) hbox.addWidget(self._chk_box) hbox.addStretch() self.setLayout(hbox) def update_from_config(self): state = 2 if self._config_item.value() == True else 0 self._chk_box.setCheckState(state) def save_to_config(self): value = True if self._chk_box.checkState() == 2 else False self._config_item.set(value)
class DialogComputeScores(QDialog): """Dialog to set the parameters to compute scores automatically. Example (replace `parent` by the parent widget): dialog = DialogComputeScores(parent) max_score, penalize = dialog.exec_() """ def __init__(self, parent=None): super(DialogComputeScores, self).__init__(parent) self.setWindowTitle(_('Compute default scores')) layout = QFormLayout() self.setLayout(layout) self.score = widgets.InputScore(parent=self) self.penalize = QCheckBox(_('Penalize incorrect answers'), self) buttons = QDialogButtonBox((QDialogButtonBox.Ok | QDialogButtonBox.Cancel)) layout.addRow(_('Maximum score'), self.score) layout.addRow(_('Penalizations'), self.penalize) layout.addRow(buttons) buttons.accepted.connect(self.accept) buttons.rejected.connect(self.reject) def exec_(self): """Shows the dialog and waits until it is closed. Returns the tuple (max_score, penalize) or (None, None) if the user cancels. """ success = False score = None penalize = None while not success: result = super(DialogComputeScores, self).exec_() if result == QDialog.Accepted: if self.score.text(): score = self.score.value() if score is not None and score > 0: penalize = self.penalize.checkState() == Qt.Checked success = True if not success: QMessageBox.critical(self, _('Error'), _('Enter a valid score.')) else: score, penalize = None, None success = True return (score, penalize)
class DialogComputeScores(QDialog): """Dialog to set the parameters to compute scores automatically. Example (replace `parent` by the parent widget): dialog = DialogComputeScores(parent) max_score, penalize = dialog.exec_() """ def __init__(self, parent=None): super(DialogComputeScores, self).__init__(parent) self.setWindowTitle(_('Compute default scores')) layout = QFormLayout() self.setLayout(layout) self.score = widgets.InputScore(parent=self) self.penalize = QCheckBox(_('Penalize incorrect answers'), self) buttons = QDialogButtonBox((QDialogButtonBox.Ok | QDialogButtonBox.Cancel)) layout.addRow(_('Maximum score'), self.score) layout.addRow(_('Penalizations'), self.penalize) layout.addRow(buttons) buttons.accepted.connect(self.accept) buttons.rejected.connect(self.reject) def exec_(self): """Shows the dialog and waits until it is closed. Returns the tuple (max_score, penalize) or (None, None) if the user cancels. """ success = False score = None penalize = None while not success: result = super(DialogComputeScores, self).exec_() if result == QDialog.Accepted: if self.score.text(): score = self.score.value() if score is not None and score > 0: penalize = self.penalize.checkState() == Qt.Checked success = True if not success: QMessageBox.critical(self, _('Error'), _('Enter a valid score.')) else: score, penalize = None, None success = True return (score, penalize)
class EkdBoolPropertie(EkdPropertie): """ Définition de la propriété correspondant à un Booléen """ def __init__(self, prop, name, value, section=None): super(EkdBoolPropertie, self).__init__(prop, name, value, EkdPropertie.BOOL, section) self.widget = QCheckBox(name) if int(self.value) != Qt.Unchecked : self.widget.setChecked(True) # Quand on change la valeur de la propriété, on met à jour EkdConfig self.connect(self.widget, SIGNAL("stateChanged(int)"), self.updateState) def updateState(self): self.value = self.widget.checkState() EkdConfig.set(self.section, self.id, self.value)
class Dialog_edge(QDialog): def __init__(self, edge, line_name, proc_ev): super(Dialog_edge, self).__init__() # Entry window name self.setWindowTitle("Line {}-{}".format(line_name[0], line_name[1])) # Entry forms self.entry_susceptance = QLineEdit() self.entry_susceptance.setText(str(edge["susceptance"])) self.entry_susceptance.setValidator(QDoubleValidator(0.01, 10, 2)) self.entry_status = QCheckBox() self.entry_status.setChecked(edge["status"]) self.layout = QFormLayout() self.layout.addRow("Susceptance", self.entry_susceptance) self.layout.addRow("Connected", self.entry_status) # Entry window set button self.button = QPushButton() self.button.setText("Set") self.button.clicked.connect(partial(self.button_click, edge)) self.layout.addWidget(self.button) # Set entry window layout self.setLayout(self.layout) self.proc_ev = proc_ev self.show() # Assign entries to edge properties def button_click(self, edge): edge['status'] = True if self.entry_status.checkState() == 2 else False edge['susceptance'] = float(self.entry_susceptance.text()) print "New parameters set" print "susceptance {}, status {}".format(edge['susceptance'], edge['status']) # Set the event to restart simulation after closing dialog window def closeEvent(self, *args, **kwargs): QDialog.closeEvent(self, *args, **kwargs) self.proc_ev.set() print "You just closed the edge-dialog window, simulation can continue!!!"
def initUI(self): self.setMinimumSize(QSize(150, 450)) self.setMaximumSize(QSize(150, 450)) layout = QVBoxLayout(self) self.setLayout(layout) #Create widgets l_sprite = QLabel(self) i_sprite = QSpinBox(self) i_trainerclass = QComboBox(self) i_name = QLineEdit(self) i_gender = QComboBox(self) l_songid = QLabel("Song:", self) i_songid = QSpinBox(self) i_doublebattle = QCheckBox("Double battle", self) i_choosemoves = QCheckBox("Explicit movesets", self) l_items = QLabel("Items:") i_item1 = QComboBox(self) i_item2 = QComboBox(self) i_item3 = QComboBox(self) i_item4 = QComboBox(self) #fill lists, set ranges values i_sprite.setRange(0, 255) i_songid.setRange(0, 0b01111111) i_trainerclass.addItems(self.trainerclasses) l_sprite.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) l_sprite.setMinimumSize(120, 64) l_sprite.setAlignment(Qt.AlignCenter) i_gender.addItems(['Male', 'Female']) i_item1.addItems(self.itemslist) i_item2.addItems(self.itemslist) i_item3.addItems(self.itemslist) i_item4.addItems(self.itemslist) #Set fields according to the trainer object i_sprite.setValue(self.trainer.trainerspriteid) i_name.setText(self.trainer.getName().getText()) i_songid.setValue(self.trainer.getSong()) i_trainerclass.setCurrentIndex(self.trainer.trainerclass) i_doublebattle.setChecked(self.trainer.doublebattle) i_choosemoves.setChecked(self.trainer.customMoves()) i_gender.setCurrentIndex(not self.trainer.isMale()) i_item1.setCurrentIndex(self.trainer.item1) i_item2.setCurrentIndex(self.trainer.item2) i_item3.setCurrentIndex(self.trainer.item3) i_item4.setCurrentIndex(self.trainer.item4) #Add all to layout layout.addWidget(l_sprite) layout.addWidget(i_sprite) layout.addWidget(i_gender) layout.addWidget(i_trainerclass) layout.addWidget(i_name) layout.addWidget(i_name) layout.addWidget(l_songid) layout.addWidget(i_songid) layout.addWidget(i_doublebattle) layout.addWidget(i_choosemoves) layout.addWidget(l_items) layout.addWidget(i_item1) layout.addWidget(i_item2) layout.addWidget(i_item3) layout.addWidget(i_item4) #Connect to signals i_sprite.valueChanged.connect(self.updateSprite) i_choosemoves.stateChanged.connect(self.chooseMovesChanged) #Keep values for future refs self.l_sprite = l_sprite self.i_sprite = i_sprite self.i_trainerclass = i_trainerclass self.i_gender = i_gender self.i_name = i_name self.i_songid = i_songid self.i_item1 = i_item1 self.i_item2 = i_item2 self.i_item3 = i_item3 self.i_item4 = i_item4 self.i_doublebattle = i_doublebattle self.i_choosemoves = i_choosemoves self.updateSprite() self.chooseMovesChanged(i_choosemoves.checkState())
class NewOrEditUserViewWidget(QDialog, FWidget): def __init__(self, pp=None, owner=None, parent=None, *args, **kwargs): QDialog.__init__(self, parent, *args, **kwargs) self.setWindowTitle(u"Nouvel utilisateur") self.parent = parent self.pp = pp self.owner = owner vbox = QVBoxLayout() formbox = QFormLayout() self.checked = QCheckBox("Active") self.error_mssg = "" if self.owner: self.new = False self.title = u"Modification de l'utilisateur {}".format( self.owner.username) self.succes_msg = u"L'utilisateur a été bien mise à jour" if self.owner.isactive: self.checked.setCheckState(Qt.Checked) else: self.checked.setCheckState(Qt.Checked) self.new = True self.succes_msg = u"L'utilisateur a été bien enregistré" self.title = u"Création d'un nouvel utilisateur" self.owner = Owner() # self.checked.setToolTip(msg) self.setWindowTitle(self.title) self.username_field = LineEdit(self.owner.username) self.username_field.setEnabled(self.new) self.password_field = LineEdit() self.password_field.setEchoMode(LineEdit.PasswordEchoOnEdit) self.password_field_v = LineEdit() self.password_field_v.setEchoMode(LineEdit.PasswordEchoOnEdit) self.password_field_v.textChanged.connect( self.check_password_is_valide) self.phone_field = IntLineEdit(self.owner.phone) self.liste_group = [Owner.ADMIN, Owner.USER] # Combobox widget self.box_group = QComboBox() for index in self.liste_group: self.box_group.addItem(u'%(group)s' % {'group': index}) butt = Button_save(u"Enregistrer") butt.clicked.connect(self.add_or_edit_user) cancel_but = Button(u"Annuler") cancel_but.clicked.connect(self.cancel) formbox.addRow(FLabel(u"Identifiant"), self.username_field) formbox.addRow(FLabel(u"Mot de passe"), self.password_field) if self.new: formbox.addRow( FLabel(u"Verification du Mot de passe"), self.password_field_v) formbox.addRow(FLabel(u"Numero de Téléphone"), self.phone_field) formbox.addRow(FLabel(u"Groupe"), self.box_group) formbox.addRow(cancel_but, butt) vbox.addWidget(self.checked) vbox.addLayout(formbox) self.setLayout(vbox) def cancel(self): self.close() def is_valide(self): # print("isactive") if (check_is_empty(self.username_field)): return False if (check_is_empty(self.password_field)): return False if (self.new and check_is_empty(self.password_field_v)): return False if (not self.check_password_is_valide()): return False return True def check_password_is_valide(self): self.password = str(self.password_field.text()) self.password_v = str( self.password_field_v.text()) if self.new else self.owner.password if is_valide_codition_field( self.password_field_v, "Les mots de passe sont differents" if self.new else "Mot de passe incorrect", self.password != self.password_v): return return True def add_or_edit_user(self): # print(""" add User """) if not self.is_valide(): print("is not valide") return username = str(self.username_field.text()).strip() password = str(self.password_field.text()).strip() phone = str(self.phone_field.text()) group = self.liste_group[self.box_group.currentIndex()] status = False if self.checked.checkState() == Qt.Checked: status = True ow = self.owner ow.username = username ow.password = Owner().crypt_password( password) if self.new else password ow.phone = phone ow.group = group ow.isactive = status try: ow.save() self.close() self.accept() if self.pp: self.pp.refresh_() self.parent.Notify("L'identifiant %s a été enregistré" % ow.username, "success") except IntegrityError as e: field_error( self.name_field, u"L'utilisateurs %s existe déjà dans la base de donnée" % ow.username)
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()
class RawView(QWidget, Logger.ClassLogger): """ Raw view widget """ def __init__(self, parent, data, toCsv=False, toHtml=False, toXml=False, toPrinter=False, toTxt=False, toPdf=False): """ Raw view widget @param parent: @type parent: """ QWidget.__init__(self, parent) self.parent = parent self.__data = data self.toCsv = toCsv self.toXml = toXml self.toCsv = toCsv self.toHtml = toHtml self.toPrinter = toPrinter self.toTxt = toTxt self.toPdf = toPdf self.createActions() self.createWidgets() self.createToolbars() self.createConnections() def createWidgets(self): """ Create qt widgets """ # prepare menu self.toolbar = QToolBar(self) self.toolbar.setStyleSheet( "QToolBar { border: 0px }") # remove 3D border self.toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) self.toolbarPlugins = QToolBar(self) self.toolbarPlugins.setStyleSheet( "QToolBar { border: 0px }") # remove 3D border self.toolbarPlugins.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) self.pluginsBox = QGroupBox("Plugins") self.pluginsBox.setStyleSheet(""" QGroupBox { font: normal; border: 1px solid silver; border-radius: 2px; } QGroupBox { padding-bottom: 10px; background-color: #FAFAFA; } QGroupBox::title { subcontrol-position: bottom center;} """) layoutPlugins = QHBoxLayout() layoutPlugins.addWidget(self.toolbarPlugins) layoutPlugins.setContentsMargins(0, 0, 0, 0) self.pluginsBox.setLayout(layoutPlugins) self.pluginsBox.hide() self.exportBox = QGroupBox("Exports") self.exportBox.setStyleSheet(""" QGroupBox { font: normal; border: 1px solid silver; border-radius: 2px; } QGroupBox { padding-bottom: 10px; background-color: #FAFAFA; } QGroupBox::title { subcontrol-position: bottom center;} """) layoutExports = QHBoxLayout() layoutExports.addWidget(self.toolbar) layoutExports.setContentsMargins(0, 0, 0, 0) self.exportBox.setLayout(layoutExports) layout = QVBoxLayout() if self.toXml: self.txtEdit = QtHelper.RawXmlEditor(parent=self) self.txtEdit.setText(self.__data) # self.txtEdit.setUtf8(True) self.txtEdit.setFont(QFont("Courier", 9)) else: self.txtEdit = QtHelper.RawEditor(parent=self) self.txtEdit.setTabStopWidth(10) self.txtEdit.setText(self.__data) self.txtEdit.setFont(QFont("Courier", 9)) self.txtEdit.setMinimumWidth(650) self.txtEdit.setMinimumHeight(400) self.delGroup = QGroupBox("Remove line") self.delTG = QCheckBox("TESTGLOBAL") self.delTP = QCheckBox("TESTPLAN") self.delTS = QCheckBox("TESTSUITE") self.delTU = QCheckBox("TESTUNIT") self.delTA = QCheckBox("TESTABSTRACT") self.delTC = QCheckBox("TESTCASE") self.delSTP = QCheckBox("STEP") layoutDel = QHBoxLayout() layoutDel.addWidget(self.delTG) layoutDel.addWidget(self.delTP) layoutDel.addWidget(self.delTS) layoutDel.addWidget(self.delTU) layoutDel.addWidget(self.delTA) layoutDel.addWidget(self.delTC) layoutDel.addWidget(self.delSTP) self.delGroup.setLayout(layoutDel) if self.toXml: self.delGroup.setEnabled(False) layoutToolbars = QHBoxLayout() layoutToolbars.addWidget(self.exportBox) layoutToolbars.addWidget(self.pluginsBox) layoutToolbars.addStretch(1) layoutToolbars.setContentsMargins(5, 0, 0, 0) layout.addLayout(layoutToolbars) layout.addWidget(self.delGroup) layout.addWidget(self.txtEdit) if not self.toXml: self.rawFind = QtHelper.RawFind(parent=self, editor=self.txtEdit, buttonNext=True) layout.addWidget(self.rawFind) self.setLayout(layout) def createConnections(self): """ All qt connections """ self.delTG.stateChanged.connect(self.onRemoveLines) self.delTP.stateChanged.connect(self.onRemoveLines) self.delTS.stateChanged.connect(self.onRemoveLines) self.delTU.stateChanged.connect(self.onRemoveLines) self.delTA.stateChanged.connect(self.onRemoveLines) self.delTC.stateChanged.connect(self.onRemoveLines) self.delSTP.stateChanged.connect(self.onRemoveLines) def createActions(self): """ Qt Actions """ self.saveCsvAction = QtHelper.createAction(self, "&To CSV", self.saveCsv, tip='Save to CSV file', icon=QIcon(":/csv.png")) self.saveTxtAction = QtHelper.createAction( self, "&To TXT", self.saveTxt, tip='Save to TXT file', icon=QIcon(":/file-txt.png")) self.saveHtmlAction = QtHelper.createAction(self, "&To HTML", self.saveHtml, tip='Save to HTML file', icon=QIcon(":/web.png")) self.savePdfAction = QtHelper.createAction(self, "&To PDF", self.savePdf, tip='Save to PDF file', icon=QIcon(":/to_pdf.png")) self.saveXmlAction = QtHelper.createAction(self, "&To XML", self.saveXml, tip='Save to XML file', icon=QIcon(":/xml.png")) self.toPrinterAction = QtHelper.createAction( self, "&To Printer", self.savePrinter, tip='Print', icon=QIcon(":/printer.png")) def createToolbars(self): """ Toolbar creation """ self.toolbar.setObjectName("Export toolbar") if self.toCsv: self.toolbar.addAction(self.saveCsvAction) if self.toTxt: self.toolbar.addAction(self.saveTxtAction) if self.toHtml: self.toolbar.addAction(self.saveHtmlAction) if self.toPdf: self.toolbar.addAction(self.savePdfAction) if self.toXml: self.toolbar.addAction(self.saveXmlAction) if self.toPrinter: self.toolbar.addAction(self.toPrinterAction) self.toolbar.setIconSize(QSize(16, 16)) def registerPlugin(self, pluginAction): """ Register plugin """ self.toolbarPlugins.addAction(pluginAction) self.toolbarPlugins.setIconSize(QSize(16, 16)) self.pluginsBox.show() def onRemoveLines(self): """ Called to remove lines """ ret = [] for l in self.__data.splitlines(): if self.delTG.checkState() and l.startswith("TESTGLOBAL"): continue elif self.delTP.checkState() and l.startswith("TESTPLAN"): continue elif self.delTS.checkState() and l.startswith("TESTSUITE"): continue elif self.delTU.checkState() and l.startswith("TESTUNIT"): continue elif self.delTA.checkState() and l.startswith("TESTABSTRACT"): continue elif self.delTC.checkState() and l.startswith("TESTCASE"): continue elif self.delSTP.checkState() and l.startswith("STEP"): continue else: ret.append(l) self.txtEdit.setText("\n".join(ret)) del ret def savePrinter(self): """ Save to printer """ printer = QPrinter() dialog = QPrintDialog(printer, self) dialog.setWindowTitle("Print") if dialog.exec_() != QDialog.Accepted: return if QtHelper.IS_QT5: # new in v18 self.fileName = printer self.txtEdit.page().toHtml(self.__toPrinter) else: doc = QTextDocument() doc.setPlainText(self.txtEdit.text()) doc.print_(printer) def __toPrinter(self, html): """ New in v18 Callback from QWebpage """ textEdit = QTextEdit(self) textEdit.setHtml(html) textEdit.print(self.fileName) textEdit.deleteLater() self.fileName = None def saveCsv(self): """ Save to csv file """ fileName = QFileDialog.getSaveFileName( self, "Save CSV file", "", "CSV file (*.csv);;All Files (*.*)") # new in v17.1 if QtHelper.IS_QT5: _filename, _type = fileName else: _filename = fileName # end of new if _filename: try: f = open(_filename, 'w') f.write(self.txtEdit.toPlainText()) f.close() except Exception as e: self.error('unable to save report file as txt: %s' % str(e)) def saveTxt(self): """ Save to txt file """ fileName = QFileDialog.getSaveFileName( self, "Save TXT file", "", "TXT file (*.txt);;All Files (*.*)") # new in v17.1 if QtHelper.IS_QT5: _filename, _type = fileName else: _filename = fileName # end of new if _filename: try: f = open(_filename, 'w') f.write(self.txtEdit.toPlainText()) f.close() except Exception as e: self.error('unable to save report file as txt: %s' % str(e)) def saveXml(self): """ Save to xml file """ fileName = QFileDialog.getSaveFileName( self, "Save XML file", "", "XML file (*.xml);;All Files (*.*)") # new in v17.1 if QtHelper.IS_QT5: _filename, _type = fileName else: _filename = fileName # end of new if _filename: try: with codecs.open(_filename, "w", "utf-8") as f: f.write(self.txtEdit.text()) except Exception as e: self.error('unable to save design file as xml: %s' % str(e)) def saveHtml(self): """ Save to html file """ fileName = QFileDialog.getSaveFileName( self, "Save HTML file", "", "HTML file (*.html);;All Files (*.*)") # new in v17.1 if QtHelper.IS_QT5: _filename, _type = fileName else: _filename = fileName # end of new if _filename: try: f = open(_filename, 'w') f.write(self.txtEdit.toHtml()) f.close() except Exception as e: self.error('unable to save report file as html: %s' % str(e)) def savePdf(self): """ Save pdf file """ fileName = QFileDialog.getSaveFileName( self, 'Save to PDF', "", "PDF file (*.pdf);;All Files (*.*)") # new in v17.1 if QtHelper.IS_QT5: _filename, _type = fileName else: _filename = fileName # end of new if _filename: printer = QPrinter(QPrinter.HighResolution) printer.setPageSize(QPrinter.A4) printer.setColorMode(QPrinter.Color) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(_filename) doc = QTextDocument() if self.toXml: doc.setPlainText(self.txtEdit.text()) else: doc.setHtml(self.txtEdit.toHtml()) doc.print_(printer)
class InterfaceTab(QWidget): def __init__(self, parent): QWidget.__init__(self) vbox = QVBoxLayout(self) self._main = parent groupBoxExplorer = QGroupBox('Explorer Panel:') groupBoxGui = QGroupBox('GUI Customization:') #Explorer vboxExplorer = QVBoxLayout(groupBoxExplorer) self.checkProjectExplorer = QCheckBox('Show Project Explorer.') self.checkSymbols = QCheckBox('Show Symbols List.') vboxExplorer.addWidget(self.checkProjectExplorer) vboxExplorer.addWidget(self.checkSymbols) #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("Rotate Central"), 1, 0, Qt.AlignCenter) gridGuiConfig.addWidget(QLabel("Rotate Lateral"), 1, 1, Qt.AlignCenter) gridGuiConfig.addWidget(QLabel("Central Orientation"), 1, 2, Qt.AlignCenter) #Settings settings = QSettings() settings.beginGroup('preferences') settings.beginGroup('interface') self.checkProjectExplorer.setCheckState(settings.value('showProjectExplorer', Qt.Checked).toInt()[0]) self.checkSymbols.setCheckState(settings.value('showSymbolsList', Qt.Checked).toInt()[0]) self.btnCentralRotate.setChecked(settings.value('centralRotate', False).toBool()) self.btnPanelsRotate.setChecked(settings.value('panelsRotate', False).toBool()) self.btnCentralOrientation.setChecked(settings.value('centralOrientation', False).toBool()) settings.endGroup() settings.endGroup() vbox.addWidget(groupBoxExplorer) vbox.addWidget(groupBoxGui) #Signals self.connect(self.btnCentralRotate, SIGNAL('clicked()'), parent._splitter_central_rotate) self.connect(self.btnPanelsRotate, SIGNAL('clicked()'), parent._splitter_main_rotate) self.connect(self.btnCentralOrientation, SIGNAL('clicked()'), parent._splitter_central_orientation) def save(self): settings = QSettings() settings.beginGroup('preferences') settings.beginGroup('interface') settings.setValue('showProjectExplorer', self.checkProjectExplorer.checkState()) settings.setValue('showSymbolsList', self.checkSymbols.checkState()) settings.setValue('centralRotate', self.btnCentralRotate.isChecked()) settings.setValue('panelsRotate', self.btnPanelsRotate.isChecked()) settings.setValue('centralOrientation', self.btnCentralOrientation.isChecked()) settings.endGroup() settings.endGroup()
class ErrorLogDialog(QDialog): def __init__(self, parent): super(ErrorLogDialog, self).__init__(parent, Qt.WindowStaysOnTopHint) self._empty = True self._initUI() self.setWindowTitle("Error") get_notification_center().connectLogMessage(self._checkLogMessage) for record in getCachedLogRecords(): self._checkLogMessage(record) def sizeHint(self): return QSize(400, 200) def _initUI(self): layout = QVBoxLayout(self) layout.setContentsMargins(0, 10, 0, 0) layout.setSpacing(0) labelLayout = QHBoxLayout() labelLayout.addWidget(QLabel(u"Sorry, something went wrong:", self)) labelLayout.setContentsMargins(10, 0, 0, 0) layout.addLayout(labelLayout) layout.addSpacing(5) self._errorLog = QTextEdit(self) self._errorLog.setReadOnly(True) self._errorLog.setWordWrapMode(QTextOption.NoWrap) self._errorLog.setTextColor(QColor(180, 0, 0)) self._errorLog.setObjectName(u"__ERROR_LOG_") self._errorLog.setFrameShape(QFrame.StyledPanel) if getPlatform() == PLATFORM_MAC: self._errorLog.setStyleSheet("QFrame#__ERROR_LOG_{border-width: 1px; border-top-style: solid; border-right-style: none; border-bottom-style: solid; border-left-style: none; border-color:palette(mid)}"); layout.addWidget(self._errorLog) bottomWidget = QWidget(self) bottomLayout = QHBoxLayout(bottomWidget) self._notAgain = QCheckBox(u"Please, no more error messages!", self) bottomLayout.addWidget(self._notAgain, 1, Qt.AlignTop) buttonBox = QDialogButtonBox(QDialogButtonBox.Close, Qt.Horizontal, self) buttonBox.rejected.connect(self.reject) bottomLayout.addWidget(buttonBox) layout.addWidget(bottomWidget) @loggingSlot() def reject(self): self._errorLog.clear() self._empty = True return QDialog.reject(self) @loggingSlot(object) def _checkLogMessage(self, record): try: if self._notAgain.checkState() == Qt.Checked: return if record.levelno >= logging.ERROR: recMsg = record.msg if not isinstance(recMsg, basestring): recMsg = unicode(recMsg) err = convert_string(recMsg) % record.args component = record.name if component.startswith("lunchinator."): component = component[12:] msg = u"%s - In component %s (%s:%d):\n%s" % (strftime("%H:%M:%S", localtime(record.created)), component, record.pathname, record.lineno, err) if record.exc_info: out = StringIO() traceback.print_tb(record.exc_info[2], file=out) msg += u"\nStack trace:\n" + out.getvalue() + formatException(record.exc_info) + u"\n" self._errorLog.append(msg) self._empty = False if not self.isVisible(): self.showNormal() self.raise_() self.activateWindow() except: from lunchinator.log import getCoreLogger getCoreLogger().info(formatException())
class InterfaceTab(QWidget): def __init__(self, parent): QWidget.__init__(self) vbox = QVBoxLayout(self) self._main = parent groupBoxExplorer = QGroupBox('Explorer Panel:') groupBoxGui = QGroupBox('GUI Customization:') #Explorer vboxExplorer = QVBoxLayout(groupBoxExplorer) self.checkProjectExplorer = QCheckBox('Show Project Explorer.') self.checkSymbols = QCheckBox('Show Symbols List.') vboxExplorer.addWidget(self.checkProjectExplorer) vboxExplorer.addWidget(self.checkSymbols) #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("Rotate Central"), 1, 0, Qt.AlignCenter) gridGuiConfig.addWidget(QLabel("Rotate Lateral"), 1, 1, Qt.AlignCenter) gridGuiConfig.addWidget(QLabel("Central Orientation"), 1, 2, Qt.AlignCenter) #Settings settings = QSettings() settings.beginGroup('preferences') settings.beginGroup('interface') self.checkProjectExplorer.setCheckState( settings.value('showProjectExplorer', Qt.Checked).toInt()[0]) self.checkSymbols.setCheckState( settings.value('showSymbolsList', Qt.Checked).toInt()[0]) self.btnCentralRotate.setChecked( settings.value('centralRotate', False).toBool()) self.btnPanelsRotate.setChecked( settings.value('panelsRotate', False).toBool()) self.btnCentralOrientation.setChecked( settings.value('centralOrientation', False).toBool()) settings.endGroup() settings.endGroup() vbox.addWidget(groupBoxExplorer) vbox.addWidget(groupBoxGui) #Signals self.connect(self.btnCentralRotate, SIGNAL('clicked()'), parent._splitter_central_rotate) self.connect(self.btnPanelsRotate, SIGNAL('clicked()'), parent._splitter_main_rotate) self.connect(self.btnCentralOrientation, SIGNAL('clicked()'), parent._splitter_central_orientation) def save(self): settings = QSettings() settings.beginGroup('preferences') settings.beginGroup('interface') settings.setValue('showProjectExplorer', self.checkProjectExplorer.checkState()) settings.setValue('showSymbolsList', self.checkSymbols.checkState()) settings.setValue('centralRotate', self.btnCentralRotate.isChecked()) settings.setValue('panelsRotate', self.btnPanelsRotate.isChecked()) settings.setValue('centralOrientation', self.btnCentralOrientation.isChecked()) settings.endGroup() settings.endGroup()
class WellExportDialog(QDialog): def __init__(self): super(WellExportDialog, self).__init__() self.resize(400, 300) self.initUI() self.export_Button.clicked.connect(self.export_well) self.button_box.rejected.connect(self.close) self.select_Button.clicked.connect(self.select_file) self.well_comboBox.currentIndexChanged.connect( self.populate_log_listWidget) self.update_well_comboBox() def initUI(self): self.setWindowIcon(QIcon(':/icon/export')) self.setWindowTitle("Export Well") self.layout = QGridLayout(self) # add QLabel self.label_0 = QLabel(self) self.label_0.setGeometry(QRect(0, 24, 31, 20)) self.label_0.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter) self.label_0.setText("Well to export:") self.layout.addWidget(self.label_0, 0, 0) # add QComboBox self.well_comboBox = QComboBox(self) self.well_comboBox.setGeometry(QRect(10, 10, 101, 24)) self.layout.addWidget(self.well_comboBox, 0, 1, 1, 1) # add QCheckBox self.checkbox = QCheckBox(self) self.checkbox.setText("Full LAS") self.checkbox.setCheckState(Qt.Unchecked) self.layout.addWidget(self.checkbox, 0, 2) # add QListWidget self.logs_listWidget = QListWidget(self) self.logs_listWidget.setGeometry(QRect(0, 0, 101, 201)) # self.well_comboBox.setMaximumHeight(151) self.layout.addWidget(self.logs_listWidget, 1, 1) # add QLabel self.label_1 = QLabel(self) self.label_1.setGeometry(QRect(0, 24, 31, 20)) self.label_1.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter) self.label_1.setText("Output File:") self.layout.addWidget(self.label_1, 2, 0) # add QLineEdit self.file_path_lineEdit = QLineEdit(self) self.file_path_lineEdit.setGeometry(QRect(50, 24, 81, 20)) self.layout.addWidget(self.file_path_lineEdit, 2, 1) # add Button self.select_Button = QPushButton(self) self.select_Button.setMaximumSize(QSize(61, 24)) self.select_Button.setText("Select") self.layout.addWidget(self.select_Button, 2, 2) # add QDialogButtonBox self.button_box = QDialogButtonBox(self) self.export_Button = self.button_box.addButton( "Export", QDialogButtonBox.ApplyRole) self.button_box.addButton(QDialogButtonBox.Cancel) self.layout.addWidget(self.button_box, 3, 0, 1, 3) def update_well_comboBox(self): survey_file = CONF.survey_dir / '.survey' if survey_file.exists(): dnames = get_data_files(CONF.well_dir) self.well_comboBox.addItems(dnames) def populate_log_listWidget(self): self.logs_listWidget.clear() well = ppp.Well( str(CONF.well_dir / ".{}".format(self.well_comboBox.currentText()))) # self.logs_listWidget.addItems(well.logs) for name in well.logs: new_item = QListWidgetItem(name, self.logs_listWidget) new_item.setFlags(new_item.flags() | Qt.ItemIsUserCheckable) new_item.setCheckState(Qt.Unchecked) def export_well(self): file_name = str(self.file_path_lineEdit.text()) if not file_name: QMessageBox().information(self, "Info", "Please select ouput file.") pass else: well = well = ppp.Well( str(CONF.well_dir / ".{}".format(self.well_comboBox.currentText()))) logs_to_export = [] for i in range(self.logs_listWidget.count()): item = self.logs_listWidget.item(i) if item.checkState() == Qt.Checked: logs_to_export.append(str(item.text())) full = True if self.checkbox.checkState() == Qt.Checked \ else False well.export(file_name, logs_to_export, full) QMessageBox().information(self, "Info", "Succeed!") def select_file(self): fl = QFileDialog.getSaveFileName(self, 'Save File', str(CONF.well_dir)) self.file_path_lineEdit.setText(fl)
class clothCheck_UI(QtGui.QWidget): def __init__(self): super(clothCheck_UI, self).__init__() self.initUI() def initUI(self): self.setWindowTitle("Check cloth scene health") self.checklayout = QVBoxLayout() self.checkLayout = QBoxLayout(2) self.playlist_names = QComboBox() self.checklayout.addLayout(self.checkLayout) self.check_all = QPushButton("check all") self.connect(self.check_all, SIGNAL("clicked()"),lambda: self._check_all()) self.checkLayout.addWidget(self.check_all) self.check_none = QPushButton("check none") self.connect(self.check_none, SIGNAL("clicked()"),lambda: self._check_none()) self.checkLayout.addWidget(self.check_none) self.checkRange = QCheckBox("Framerange") self.checkRange.setCheckState(0) self.checkLayout.addWidget(self.checkRange) self.nuc_category = QLabel("Nucleus") self.nuc_enable = QCheckBox("nuc enabled") self.nuc_enable.setCheckState(1) self.checkLayout.addWidget(self.nuc_enable) self.checkLayout.addWidget(self.nuc_category) self.nuc_strt = QCheckBox("Nucleus startframe") self.nuc_strt.setCheckState(1) self.checkLayout.addWidget(self.nuc_strt) self.space_scale = QCheckBox("space scale") self.space_scale.setCheckState(1) self.checkLayout.addWidget(self.space_scale) self.nuc_subs = QCheckBox("substeps") self.nuc_subs.setCheckState(1) self.checkLayout.addWidget(self.nuc_subs) self.coll_iter = QCheckBox("collision iterations") self.coll_iter.setCheckState(1) self.checkLayout.addWidget(self.coll_iter) self.rgd_category = QLabel("Rigids") self.checkLayout.addWidget(self.rgd_category) self.rgd_pnt_mass = QCheckBox("rgd point mass") self.rgd_pnt_mass.setCheckState(1) self.checkLayout.addWidget(self.rgd_pnt_mass) self.clth_category = QLabel("Cloth") self.checkLayout.addWidget(self.clth_category) self.scale_rel = QCheckBox("scale relations") self.scale_rel.setCheckState(1) self.checkLayout.addWidget(self.scale_rel) self.trap_check = QCheckBox("trapped check") self.trap_check.setCheckState(1) self.checkLayout.addWidget(self.trap_check) self.clth_enable = QCheckBox("enabled") self.clth_enable.setCheckState(1) self.checkLayout.addWidget(self.clth_enable) self.dyn_cnstrnt_category = QLabel("Dynamic Constraints") self.checkLayout.addWidget(self.dyn_cnstrnt_category) self.dyncnstrnt_exc = QCheckBox("dconstrnt exclusions") self.dyncnstrnt_exc.setCheckState(1) self.checkLayout.addWidget(self.dyncnstrnt_exc) self.dyncnstrnt_cmp = QCheckBox("dconstrnt component") self.dyncnstrnt_cmp.setCheckState(1) self.checkLayout.addWidget(self.dyncnstrnt_cmp) self.dry_button = QPushButton("dry run") self.connect(self.dry_button, SIGNAL("clicked()"),lambda: self.dry_run()) self.checkLayout.addWidget(self.dry_button) self.doit_button = QPushButton("check cloth scene") self.connect(self.doit_button, SIGNAL("clicked()"),lambda: self.checkit()) self.checkLayout.addWidget(self.doit_button) self.close_button = QPushButton("close") self.connect(self.close_button, SIGNAL("clicked()"),lambda: self.gotoAppend()) # self.checkLayout.addWidget(self.label) self.checkLayout.addWidget(self.close_button) self.setLayout(self.checklayout) def gotoAppend(self): self.close() def dry_run(self): get_baseTools=mockTools.mToolKit() get_baseTools.troubleshoot_clth() def checkit(self): check_dict={} getrange={"range":self.checkRange.checkState()} check_dict.update(getrange) getnucstart={"nucstart":self.nuc_strt.checkState()} check_dict.update(getnucstart) getnucenable={"nucenable":self.nuc_enable.checkState()} check_dict.update(getnucenable) getspcscl={"nuc_spc_scl":self.space_scale.checkState()} check_dict.update(getspcscl) getnucsubstp={"nuc_sub_stp":self.nuc_subs.checkState()} check_dict.update(getnucsubstp) getnuccoliter={"nuc_col_itr":self.coll_iter.checkState()} check_dict.update(getnuccoliter) getrdgmss={"rgd_mass":self.rgd_pnt_mass.checkState()} check_dict.update(getrdgmss) getsclerel={"scl_rel":self.scale_rel.checkState()} check_dict.update(getsclerel) getdyncnstrntexcl={"dyn_cnstrnt_exc":self.dyncnstrnt_exc.checkState()} check_dict.update(getdyncnstrntexcl) getdyncnstrntcmpl={"dyn_cnstrnt_exc":self.dyncnstrnt_cmp.checkState()} check_dict.update(getdyncnstrntcmpl) getclthenble={"clthenable":self.clth_enable.checkState()} check_dict.update(getclthenble) getclthtrpchk={"clth_trp_chk":self.trap_check.checkState()} check_dict.update(getclthtrpchk) get_baseTools=mockTools.mToolKit() get_baseTools.set_troubleshoot(check_dict) def _check_all(self): self.checkRange.setCheckState(1) self.nuc_strt.setCheckState(1) self.clth_enable.setCheckState(1) self.nuc_enable.setCheckState(1) self.space_scale.setCheckState(1) self.nuc_subs.setCheckState(1) self.coll_iter.setCheckState(1) self.rgd_pnt_mass.setCheckState(1) self.scale_rel.setCheckState(1) self.dyncnstrnt_exc.setCheckState(1) self.dyncnstrnt_cmp.setCheckState(1) self.clth_enable.setCheckState(1) def _check_none(self): self.checkRange.setCheckState(0) self.nuc_strt.setCheckState(0) self.clth_enable.setCheckState(0) self.nuc_enable.setCheckState(0) self.space_scale.setCheckState(0) self.nuc_subs.setCheckState(0) self.coll_iter.setCheckState(0) self.rgd_pnt_mass.setCheckState(0) self.scale_rel.setCheckState(0) self.dyncnstrnt_exc.setCheckState(0) self.dyncnstrnt_cmp.setCheckState(0) self.trap_check.setCheckState(0)
class TabGeneral(QWidget): def __init__(self): QWidget.__init__(self) v_box = QVBoxLayout(self) self.setFixedWidth(500) self.settings = QSettings('NINJA-IDE', 'Kunai') #Groups self.gbox_Home = QGroupBox('On Start:') self.gbox_Close = QGroupBox("On Close:") self.gbox_Routes = QGroupBox('Routes:') v_box.addWidget(self.gbox_Home) v_box.addWidget(self.gbox_Close) v_box.addWidget(self.gbox_Routes) self.settings.beginGroup('Preferences') self.settings.beginGroup('General') #Home #Layout v_home = QVBoxLayout() ##CheckBox self.ch_lastSesionFiles = QCheckBox('Load files from last session.') self.ch_lastSesionFiles.setCheckState( self.settings.value('load_files', 2).toInt()[0]) self.ch_activatePlugins = QCheckBox('Activate Plugins.') self.ch_activatePlugins.setCheckState( self.settings.value('activate_plugins', 2).toInt()[0]) self.ch_notifyUpdates = QCheckBox( 'Nofity me for new available updates.') self.ch_notifyUpdates.setCheckState( self.settings.value('notify_updates', 0).toInt()[0]) v_home.addWidget(self.ch_lastSesionFiles) v_home.addWidget(self.ch_activatePlugins) v_home.addWidget(self.ch_notifyUpdates) self.gbox_Home.setLayout(v_home) #Close #Layout v_close = QVBoxLayout() ##CheckBox self.ch_saveState = QCheckBox('Save the window position and geometry.') self.ch_saveState.setCheckState( self.settings.value('save_position_geometry', 0).toInt()[0]) self.ch_confirmExit = QCheckBox('Confirm Exit.') self.ch_confirmExit.setCheckState( self.settings.value('confirm_exit', 2).toInt()[0]) v_close.addWidget(self.ch_saveState) v_close.addWidget(self.ch_confirmExit) self.gbox_Close.setLayout(v_close) #Routes #Layout g_routes = QGridLayout() ##TextBox self.txt_startRoute = QLineEdit() self.txt_startRoute.setText( self.settings.value('start_route', '').toString()) self.txt_projectRoute = QLineEdit() self.txt_projectRoute.setText( self.settings.value('project_route', '').toString()) self.txt_xtraPlugins = QLineEdit() self.txt_xtraPlugins.setText( self.settings.value('extra_plugins_route', '').toString()) ##Button self.btn_startRoute = QPushButton( QIcon(resources.images['openFolder']), '') self.btn_projectRoute = QPushButton( QIcon(resources.images['openFolder']), '') self.btn_xtraPlugins = QPushButton( QIcon(resources.images['openFolder']), '') def load_start_route(): self.txt_startRoute.setText(load_directory(self, 'Start Route')) def load_project_route(): self.txt_projectRoute.setText(load_directory( self, 'Project Route')) def load_xtra_plugins_route(): self.txt_xtraPlugins.setText( load_directory(self, 'Extra Plugins Route')) self.settings.endGroup() #End General Preferences self.settings.endGroup() #Signal self.connect(self.btn_startRoute, SIGNAL('clicked()'), load_start_route) self.connect(self.btn_projectRoute, SIGNAL('clicked()'), load_project_route) self.connect(self.btn_xtraPlugins, SIGNAL('clicked()'), load_xtra_plugins_route) g_routes.addWidget(QLabel('Start Route:'), 0, 0, Qt.AlignRight) g_routes.addWidget(QLabel('Project Files:'), 1, 0, Qt.AlignRight) #g_routes.addWidget(QLabel('Extra Plugins Route:'), 2, 0, Qt.AlignRight) g_routes.addWidget(self.txt_startRoute, 0, 1) g_routes.addWidget(self.txt_projectRoute, 1, 1) #g_routes.addWidget(self.txt_xtraPlugins, 2 ,1) g_routes.addWidget(self.btn_startRoute, 0, 2) g_routes.addWidget(self.btn_projectRoute, 1, 2) #g_routes.addWidget(self.btn_xtraPlugins, 2, 2) self.gbox_Routes.setLayout(g_routes) def save_state(self): self.settings.beginGroup('Preferences') self.settings.beginGroup('General') #CheckBox self.settings.setValue('load_files', self.ch_lastSesionFiles.checkState()) self.settings.setValue('activate_plugins', self.ch_activatePlugins.checkState()) self.settings.setValue('save_position_geometry', self.ch_saveState.checkState()) self.settings.setValue('confirm_exit', self.ch_confirmExit.checkState()) self.settings.setValue('notify_updates', self.ch_notifyUpdates.checkState()) #TextBox self.settings.setValue('start_route', self.txt_startRoute.text()) self.settings.setValue('project_route', self.txt_projectRoute.text()) self.settings.setValue('extra_plugins_route', self.txt_xtraPlugins.text()) self.settings.endGroup() #End General Preferences self.settings.endGroup()
class MainUI(remembering.RememberingMainWindow): """Main UI.""" _programs_file = os.path.join(multiplatform.data_dir, 'encuentro.data') def __init__(self, version, app_quit): super(MainUI, self).__init__() self.app_quit = app_quit self.finished = False self.version = version self.setWindowTitle('Encuentro') self.programs_data = data.ProgramsData(self, self._programs_file) self._touch_config() self.downloaders = {} for downtype, dloader_class in all_downloaders.iteritems(): self.downloaders[downtype] = dloader_class() # finish all gui stuff self.big_panel = central_panel.BigPanel(self) self.episodes_list = self.big_panel.episodes self.episodes_download = self.big_panel.downloads_widget self.setCentralWidget(self.big_panel) # the setting of menubar should be almost in the end, because it may # trigger the wizard, which needs big_panel and etc. self.action_play = self.action_download = None self.filter_line = self.filter_cbox = self.needsomething_alert = None self._menubar() systray.show(self) if config.get('autorefresh'): ue = update.UpdateEpisodes(self) ue.background() else: # refresh data if never done before or if last # update was 7 days ago last_refresh = config.get('autorefresh_last_time') if last_refresh is None or (dt.datetime.now() - last_refresh > dt.timedelta(7)): ue = update.UpdateEpisodes(self) ue.background() self.show() self.episodes_download.load_pending() logger.debug("Main UI started ok") def _touch_config(self): """Do some config processing.""" # log the config, but without user and pass safecfg = config.sanitized_config() logger.debug("Configuration loaded: %s", safecfg) # we have a default for download dir if not config.get('downloaddir'): config['downloaddir'] = multiplatform.get_download_dir() # maybe clean some config if self.programs_data.reset_config_from_migration: config['user'] = '' config['password'] = '' config.pop('cols_width', None) config.pop('cols_order', None) config.pop('selected_row', None) def have_config(self): """Return if some config is needed.""" return config.get('user') and config.get('password') def have_metadata(self): """Return if metadata is needed.""" return bool(self.programs_data) def _menubar(self): """Set up the menu bar.""" menubar = self.menuBar() # applications menu menu_appl = menubar.addMenu(u'&Aplicación') icon = self.style().standardIcon(QStyle.SP_BrowserReload) action_reload = QAction(icon, '&Refrescar', self) action_reload.setShortcut('Ctrl+R') action_reload.setToolTip(u'Recarga la lista de programas') action_reload.triggered.connect(self.refresh_episodes) menu_appl.addAction(action_reload) icon = self.style().standardIcon(QStyle.SP_FileDialogDetailedView) action_preferences = QAction(icon, u'&Preferencias', self) action_preferences.triggered.connect(self.open_preferences) action_preferences.setToolTip( u'Configurar distintos parámetros del programa') menu_appl.addAction(action_preferences) menu_appl.addSeparator() icon = self.style().standardIcon(QStyle.SP_MessageBoxInformation) _act = QAction(icon, '&Acerca de', self) _act.triggered.connect(self.open_about_dialog) _act.setToolTip(u'Muestra información de la aplicación') menu_appl.addAction(_act) icon = self.style().standardIcon(QStyle.SP_DialogCloseButton) _act = QAction(icon, '&Salir', self) _act.setShortcut('Ctrl+Q') _act.setToolTip(u'Sale de la aplicación') _act.triggered.connect(self.on_close) menu_appl.addAction(_act) # program menu menu_prog = menubar.addMenu(u'&Programa') icon = self.style().standardIcon(QStyle.SP_ArrowDown) self.action_download = QAction(icon, '&Descargar', self) self.action_download.setShortcut('Ctrl+D') self.action_download.setEnabled(False) self.action_download.setToolTip(TTIP_DOWNLOAD_D) self.action_download.triggered.connect(self.download_episode) menu_prog.addAction(self.action_download) icon = self.style().standardIcon(QStyle.SP_MediaPlay) self.action_play = QAction(icon, '&Reproducir', self) self.action_play.setEnabled(False) self.action_play.setToolTip(TTIP_PLAY_D) self.action_play.triggered.connect(self.on_play_action) menu_prog.addAction(self.action_play) # toolbar for buttons toolbar = self.addToolBar('main') toolbar.addAction(self.action_download) toolbar.addAction(self.action_play) toolbar.addSeparator() toolbar.addAction(action_reload) toolbar.addAction(action_preferences) # filter text and button, to the right spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) toolbar.addWidget(spacer) toolbar.addWidget(QLabel(u"Filtro: ")) self.filter_line = QLineEdit() self.filter_line.setMaximumWidth(150) self.filter_line.textChanged.connect(self.on_filter_changed) toolbar.addWidget(self.filter_line) self.filter_cbox = QCheckBox(u"Sólo descargados") self.filter_cbox.stateChanged.connect(self.on_filter_changed) toolbar.addWidget(self.filter_cbox) # if needed, a warning that stuff needs to be configured icon = self.style().standardIcon(QStyle.SP_MessageBoxWarning) m = u"Necesita configurar algo; haga click aquí para abrir el wizard" self.needsomething_alert = QAction(icon, m, self) self.needsomething_alert.triggered.connect(self._start_wizard) toolbar.addAction(self.needsomething_alert) if not config.get('nowizard'): self._start_wizard() self._review_need_something_indicator() def _start_wizard(self, _=None): """Start the wizard if needed.""" if not self.have_config() or not self.have_metadata(): dlg = wizard.WizardDialog(self) dlg.exec_() self._review_need_something_indicator() def on_filter_changed(self, _): """The filter text has changed, apply it in the episodes list.""" text = self.filter_line.text() cbox = self.filter_cbox.checkState() self.episodes_list.set_filter(text, cbox) # after applying filter, nothing is selected, so check buttons # (easiest way to clean them all) self.check_download_play_buttons() def _review_need_something_indicator(self): """Hide/show/enable/disable different indicators if need sth.""" needsomething = bool(not self.have_config() or not self.have_metadata()) self.needsomething_alert.setVisible(needsomething) def shutdown(self): """Stop everything and quit. This shutdown con be called at any time, even on init, so we have extra precautions about which attributes we have. """ signal.emit('save_state') config.save() self.finished = True programs_data = getattr(self, 'programs_data', None) if programs_data is not None: programs_data.save() downloaders = getattr(self, 'downloaders', {}) for downloader in downloaders.itervalues(): downloader.shutdown() # bye bye self.app_quit() def on_close(self, _): """Close signal.""" if self._should_close(): self.shutdown() def closeEvent(self, event): """All is being closed.""" if self._should_close(): self.shutdown() else: event.ignore() def _should_close(self): """Still time to decide if want to close or not.""" logger.info("Attempt to close the program") pending = self.episodes_download.pending() if not pending: # all fine, save all and quit logger.info("Saving states and quitting") return True logger.debug("Still %d active downloads when trying to quit", pending) # stuff pending m = (u"Hay programas todavía en proceso de descarga!\n" u"¿Seguro quiere salir del programa?") QMB = QMessageBox dlg = QMB(u"Guarda!", m, QMB.Question, QMB.Yes, QMB.No, QMB.NoButton) opt = dlg.exec_() if opt != QMB.Yes: logger.info("Quit cancelled") return False # quit anyway, put all downloading and pending episodes to none logger.info("Fixing episodes, saving state and exiting") for program in self.programs_data.values(): state = program.state if state == Status.waiting or state == Status.downloading: program.state = Status.none return True def show_message(self, err_type, text): """Show different messages to the user.""" if self.finished: logger.debug("Ignoring message: %r", text) return logger.debug("Showing a message: %r", text) # error text can be produced by windows, try to to sanitize it if isinstance(text, str): try: text = text.decode("utf8") except UnicodeDecodeError: try: text = text.decode("latin1") except UnicodeDecodeError: text = repr(text) QMB = QMessageBox dlg = QMB(u"Atención: " + err_type, text, QMB.Warning, QMB.Ok, QMB.NoButton, QMB.NoButton) dlg.exec_() def refresh_episodes(self, _=None): """Update and refresh episodes.""" ue = update.UpdateEpisodes(self) ue.interactive() def download_episode(self, _=None): """Download the episode(s).""" episode_ids = self.episodes_list.selected_items() for episode_id in episode_ids: episode = self.programs_data[episode_id] self.queue_download(episode) @defer.inline_callbacks def queue_download(self, episode): """User indicated to download something.""" logger.debug("Download requested of %s", episode) if episode.state != Status.none: logger.debug( "Download denied, episode %s is not in downloadeable " "state.", episode.episode_id) return # queue self.episodes_download.append(episode) self.episodes_list.episode_info.update(episode) self.check_download_play_buttons() if self.episodes_download.downloading: return logger.debug("Downloads: starting") while self.episodes_download.pending(): episode = self.episodes_download.prepare() try: filename, episode = yield self._episode_download(episode) except CancelledError: logger.debug("Got a CancelledError!") self.episodes_download.end(error=u"Cancelado") except BadCredentialsError: logger.debug("Bad credentials error!") msg = (u"Error con las credenciales: hay que configurar " u"usuario y clave correctos") self.show_message('BadCredentialsError', msg) self.episodes_download.end(error=msg) except EncuentroError, e: orig_exc = e.orig_exc msg = "%s(%s)" % (orig_exc, e) err_type = e.__class__.__name__ logger.exception("Custom Encuentro error: %s (%r)", e, orig_exc) notify(err_type, msg) self.episodes_download.end(error=u"Error: " + msg) except Exception, e: logger.exception("Unknown download error: %s (%r)", e, e) err_type = e.__class__.__name__ notify(err_type, str(e)) self.episodes_download.end(error=u"Error: " + str(e)) else:
class TabInterface(QWidget): def __init__(self, parent): QWidget.__init__(self) v_box = QVBoxLayout(self) self.setFixedWidth(500) self.settings = QSettings('NINJA-IDE', 'Kunai') #groups self.gbox_bars = QGroupBox('Lateral Bars:') self.gbox_fonts = QGroupBox('Fonts:') self.gbox_tabs = QGroupBox('Editor Tabs:') self.gbox_tabsPosition = QGroupBox('Tabs Position:') v_box.addWidget(self.gbox_bars) v_box.addWidget(self.gbox_fonts) v_box.addWidget(self.gbox_tabs) v_box.addWidget(self.gbox_tabsPosition) self.settings.beginGroup('Preferences') self.settings.beginGroup('Interface') #Lateral Bars ##Checks self.ch_simbols = QCheckBox('Show Simbols List.') self.ch_simbols.setCheckState( self.settings.value('show_simbol_list', 2).toInt()[0]) self.ch_files = QCheckBox('Show Files List.') self.ch_files.setCheckState( self.settings.value('show_files_list', 2).toInt()[0]) v_bars = QVBoxLayout() v_bars.addWidget(self.ch_simbols) v_bars.addWidget(self.ch_files) self.gbox_bars.setLayout(v_bars) #Buttons self.btn_editor_font = QPushButton( self.settings.value('editor_font', 'Monospace, 10').toString()) #self.btn_simbol_font = QPushButton(self.settings.value('simbol_list_font','Monospace, 10').toString()) #self.btn_message_font = QPushButton(self.settings.value('window_message_font','Monospace, 10').toString()) def load_editor_font(): self.btn_editor_font.setText( load_font( self, self.get_font_from_string(self.btn_editor_font.text()))) def load_simbol_font(): self.btn_simbol_font.setText(load_font()) def load_message_font(): self.btn_message_font.setText(load_font()) #SIGNALS self.connect(self.btn_editor_font, SIGNAL("clicked()"), load_editor_font) #self.connect(self.btn_simbol_font, SIGNAL ("clicked()"), load_simbol_font) #self.connect(self.btn_message_font, SIGNAL("clicked()"), load_message_font) g_font = QGridLayout() g_font.addWidget(QLabel('Editor Font:'), 0, 0, Qt.AlignRight) #g_font.addWidget(QLabel('Simbol List:'),1, 0, Qt.AlignRight) #g_font.addWidget(QLabel('Messages Window:'),2,0,Qt.AlignRight) g_font.addWidget(self.btn_editor_font, 0, 1) #g_font.addWidget(self.btn_simbol_font, 1, 1) #g_font.addWidget(self.btn_message_font, 2, 1) self.gbox_fonts.setLayout(g_font) #Edition Tabs #Checks self.ch_showEditTabs = QCheckBox('Show Editor Tabs') self.ch_showEditTabs.setCheckState( self.settings.value('show_editor_tabs', 2).toInt()[0]) self.ch_showClose = QCheckBox('Show Close Button on Tabs') self.ch_showClose.setCheckState( self.settings.value('show_close_tabs', 2).toInt()[0]) self.ch_hidePanel = QCheckBox('F11 hide/show side Panels') self.ch_hidePanel.setCheckState( self.settings.value('hide_show_panels', 2).toInt()[0]) #Option self.opt_left = QRadioButton('Left') self.opt_right = QRadioButton('Right') if (self.settings.value('next_tabs_location', 1).toInt()[0] == 1): self.opt_right.setChecked(True) else: self.opt_left.setChecked(True) h_optionNewFiles = QHBoxLayout() h_optionNewFiles.addWidget(QLabel('Location for New Files Tabs')) h_optionNewFiles.addWidget(self.opt_left) h_optionNewFiles.addWidget(self.opt_right) v_tabs = QVBoxLayout() v_tabs.addWidget(self.ch_showEditTabs) v_tabs.addWidget(self.ch_showClose) v_tabs.addLayout(h_optionNewFiles) #v_tabs.addWidget(self.ch_hidePanel) self.gbox_tabs.setLayout(v_tabs) #Tabs Position #Buttons #self.btn_orientation_change = QPushButton self.btn_hchange = QPushButton(QIcon(resources.images['splitCRotate']), '') self.btn_hchange.setIconSize(QSize(64, 64)) self.btn_right_vchange = QPushButton( QIcon(resources.images['splitMRotate']), '') self.btn_right_vchange.setIconSize(QSize(64, 64)) #SIGNAL self.connect(self.btn_hchange, SIGNAL('clicked()'), parent._splitter_central_rotate) self.connect(self.btn_right_vchange, SIGNAL('clicked()'), parent._splitter_main_rotate) self.settings.endGroup() #End General Preferences self.settings.endGroup() g_tabPosition = QGridLayout() g_tabPosition.addWidget(self.btn_hchange, 0, 0) g_tabPosition.addWidget(self.btn_right_vchange, 0, 1) g_tabPosition.addWidget(QLabel('Vertical Change'), 1, 0, Qt.AlignCenter) g_tabPosition.addWidget(QLabel('Horizontal Change'), 1, 1, Qt.AlignCenter) self.gbox_tabsPosition.setLayout(g_tabPosition) #Fonts def get_font_from_string(self, font): if (font.isEmpty()): return QFont("Monospace", 10) listFont = font.remove(' ').split(',') ret = QFont(listFont[0], listFont[1].toInt()[0]) return ret def save_state(self, parent): self.settings.beginGroup('Preferences') self.settings.beginGroup('Interface') #CheckBox self.settings.setValue('show_simbol_list', self.ch_simbols.checkState()) self.settings.setValue('show_files_list', self.ch_files.checkState()) self.settings.setValue('show_editor_tabs', self.ch_showEditTabs.checkState()) self.settings.setValue('show_close_tabs', self.ch_showClose.checkState()) self.settings.setValue('hide_show_panels', self.ch_hidePanel.checkState()) #OptionButton if (self.opt_right.isChecked()): self.settings.setValue('next_tabs_location', 1) else: self.settings.setValue('next_tabs_location', 0) #Fonts self.settings.setValue('editor_font', self.btn_editor_font.text()) #self.settings.setValue('simbol_list_font', self.btn_simbol_font.text()) #self.settings.setValue('window_message_font', self.btn_message_font.text()) #Panels Positions if (parent.get_splitter_position_0() == CentralWidget): self.settings.setValue('central_tab_position', 0) self.settings.setValue('container_tab_position', 1) else: self.settings.setValue('central_tab_position', 1) self.settings.setValue('container_tab_position', 0) if (parent.get_splitter_main_position_0() == QSplitter): self.settings.setValue('main_tab_position', 0) self.settings.setValue('properties_tab_position', 1) else: self.settings.setValue('main_tab_position', 1) self.settings.setValue('properties_tab_position', 0) self.settings.endGroup() #End Interface Preferences self.settings.endGroup()
class OrganizationTableWidget(FWidget): def __init__(self, parent, *args, **kwargs): super(FWidget, self).__init__(parent=parent, *args, **kwargs) self.organization = Organization().get(id=1) print(self.organization) self.parent = parent vbox = QVBoxLayout() # vbox.addWidget(FPageTitle(u"Utilisateur: %s " % # self.organisation.name_orga)) self.liste_devise = Organization.DEVISE # Combobox widget self.box_devise = QComboBox() for index, value in enumerate(self.liste_devise): self.box_devise.addItem( "{} {}".format(self.liste_devise[value], value)) if self.organization.devise == value: self.box_devise.setCurrentIndex(index) self.checked = QCheckBox("Active") if self.organization.is_login: self.checked.setCheckState(Qt.Checked) self.checked.setToolTip(u"""Cocher si vous voulez pour deactive le login continue à utiliser le systeme""") self.name_orga = LineEdit(self.organization.name_orga) self.phone = IntLineEdit(str(self.organization.phone)) self.bp = LineEdit(self.organization.bp) self.adress_org = QTextEdit(self.organization.adress_org) self.email_org = LineEdit(self.organization.email_org) formbox = QFormLayout() formbox.addRow(FormLabel(u"Nom de l'organisation:"), self.name_orga) formbox.addRow(FormLabel(u"Tel:"), self.phone) formbox.addRow(FormLabel(u"Activer le login"), self.checked) formbox.addRow(FormLabel(u"Devise :"), self.box_devise) formbox.addRow(FormLabel(u"B.P:"), self.bp) formbox.addRow(FormLabel(u"E-mail:"), self.email_org) formbox.addRow(FormLabel(u"Adresse complete:"), self.adress_org) butt = Button_save(u"Enregistrer") butt.clicked.connect(self.save_edit) formbox.addRow("", butt) vbox.addLayout(formbox) self.setLayout(vbox) def save_edit(self): ''' add operation ''' name_orga = unicode(self.name_orga.text()) if check_is_empty(self.name_orga): return if check_is_empty(self.phone): return orga = Organization().get(id=1) orga.name_orga = name_orga orga.phone = unicode(self.phone.text()) orga.is_login = True if self.checked.checkState() == Qt.Checked else False orga.devise = str(self.box_devise.currentText().split()[1]) orga.email_org = unicode(self.email_org.text()) orga.bp = unicode(self.bp.text()) orga.adress_org = unicode(self.adress_org.toPlainText()) orga.save() print(orga.is_login) self.parent.parent.Notify(u"Le Compte %s a été mise à jour" % orga.name_orga, "success")
class GeneralTab(QWidget): def __init__(self): QWidget.__init__(self) vbox = QVBoxLayout(self) groupBoxStart = QGroupBox('On Start:') groupBoxClose = QGroupBox('On Close:') groupBoxWorkspace = QGroupBox('Workspace and Project:') #Start vboxStart = QVBoxLayout(groupBoxStart) self.checkLastSession = QCheckBox('Load files from last session') self.checkActivatePlugins = QCheckBox('Activate Plugins') self.checkNotifyUpdates = QCheckBox( 'Nofity me for new available updates.') vboxStart.addWidget(self.checkLastSession) vboxStart.addWidget(self.checkActivatePlugins) vboxStart.addWidget(self.checkNotifyUpdates) #Close vboxClose = QVBoxLayout(groupBoxClose) self.checkConfirmExit = QCheckBox('Confirm Exit.') vboxClose.addWidget(self.checkConfirmExit) #Workspace and Project gridWorkspace = QGridLayout(groupBoxWorkspace) self.txtWorkspace = QLineEdit() self.txtWorkspace.setReadOnly(True) self.btnWorkspace = QPushButton(QIcon(resources.images['openFolder']), '') gridWorkspace.addWidget(QLabel('Workspace'), 0, 0, Qt.AlignRight) gridWorkspace.addWidget(self.txtWorkspace, 0, 1) gridWorkspace.addWidget(self.btnWorkspace, 0, 2) self.txtExtensions = QLineEdit() gridWorkspace.addWidget(QLabel('Supported Extensions:'), 1, 0, Qt.AlignRight) gridWorkspace.addWidget(self.txtExtensions, 1, 1) self.txtPythonPath = QLineEdit() self.btnPythonPath = QPushButton(QIcon(resources.images['open']), '') gridWorkspace.addWidget(QLabel('Python Path:'), 2, 0, Qt.AlignRight) gridWorkspace.addWidget(self.txtPythonPath, 2, 1) gridWorkspace.addWidget(self.btnPythonPath, 2, 2) gridWorkspace.addWidget( QLabel('(This property need to be configured for Windows)'), 3, 1, Qt.AlignRight) #Settings settings = QSettings() settings.beginGroup('preferences') settings.beginGroup('general') self.checkLastSession.setCheckState( settings.value('loadFiles', Qt.Checked).toInt()[0]) self.checkActivatePlugins.setCheckState( settings.value('activatePlugins', Qt.Checked).toInt()[0]) self.checkNotifyUpdates.setCheckState( settings.value('notifyUpdates', Qt.Checked).toInt()[0]) self.checkConfirmExit.setCheckState( settings.value('confirmExit', Qt.Checked).toInt()[0]) self.txtWorkspace.setText(settings.value('workspace', '').toString()) self.txtPythonPath.setText( settings.value('pythonPath', resources.python_path).toString()) extensions = tuple( settings.value('extensions', list(manage_files.supported_extensions)).toList()) extensions = ', '.join([str(e.toString()) for e in extensions]) self.txtExtensions.setText(extensions) settings.endGroup() settings.endGroup() vbox.addWidget(groupBoxStart) vbox.addWidget(groupBoxClose) vbox.addWidget(groupBoxWorkspace) #Signals self.connect(self.btnWorkspace, SIGNAL("clicked()"), self._load_workspace) self.connect(self.btnPythonPath, SIGNAL("clicked()"), self._load_python_path) def _load_workspace(self): path = str(QFileDialog.getExistingDirectory(self, 'Select Workspace')) self.txtWorkspace.setText(path) def _load_python_path(self): path = str(QFileDialog.getOpenFileName(self, 'Select Python Path')) self.txtPythonPath.setText(path) def save(self): settings = QSettings() settings.beginGroup('preferences') settings.beginGroup('general') settings.setValue('loadFiles', self.checkLastSession.checkState()) settings.setValue('activatePlugins', self.checkActivatePlugins.checkState()) settings.setValue('notifyUpdates', self.checkNotifyUpdates.checkState()) settings.setValue('confirmExit', self.checkConfirmExit.checkState()) settings.setValue('workspace', self.txtWorkspace.text()) settings.setValue('pythonPath', self.txtPythonPath.text()) resources.python_path = str(self.txtPythonPath.text()) resources.workspace = str(self.txtWorkspace.text()) extensions = str(self.txtExtensions.text()).split(',') extensions = [e.strip() for e in extensions] settings.setValue('extensions', extensions) manage_files.supported_extensions = tuple(extensions) settings.endGroup() settings.endGroup()
class dbsElectrodeControlsDialog(QDialog): def __init__(self, callback, parent=None): QDialog.__init__(self, parent) self.callback = callback self.create_widgets() #self.layout_widgets() self.create_connections() self.setModal(False) self.setWindowTitle('Electrode Controls') self.layout().setSizeConstraint(QLayout.SetFixedSize) self.saved_params = dict() def create_widgets(self): gridLayout = QGridLayout() groupBox = QGroupBox( 'Rendering controls' ) groupBox.setFlat(True) groupBox2 = QGroupBox( 'DBSCAN centroids' ) groupBox2.setFlat(True) groupBox3 = QGroupBox( 'Electrode filter' ) groupBox3.setFlat(True) gridLayout.addWidget(groupBox) gridLayout.addWidget(groupBox3) gridLayout.addWidget(groupBox2) # rendering controls self.visi_label = QLabel( 'show electrodes' ) self.visi = QCheckBox() self.visi.setChecked(False) self.fall_off_label = QLabel( 'fall-off' ) self.fall_off = QSlider(Qt.Horizontal) self.fall_off.setRange(1, 100) # data set dependent self.thickness_label = QLabel( 'thickness' ) self.thickness = QSlider(Qt.Horizontal) self.thickness.setRange(1, 100) # data set dependent self.trans_label = QLabel( 'force translucency' ) self.forced_translucency = QCheckBox() self.forced_translucency.setChecked(False) # dbscan controls #self.view_button_grp = QButtonGroup() self.all_electrodes = QRadioButton('show all') self.only_clusters = QRadioButton('show clusters') self.only_noise = QRadioButton('show noise') self.all_electrodes.setEnabled(False) self.all_electrodes.setChecked(True) self.only_clusters.setEnabled(False) self.only_noise.setEnabled(False) #self.view_button_grp.addButton( self.all_electrodes ) #self.view_button_grp.addButton( self.only_clusters ) #self.view_button_grp.addButton( self.only_noise ) #gridLayout.addWidget(self.view_button_grp) self.eps_label = QLabel( 'epsilon' ) self.eps_spinbox = QDoubleSpinBox() self.eps_spinbox.setRange(0.1, 10) self.eps_spinbox.setSingleStep(0.1) self.min_points_label = QLabel( 'min points' ) self.min_spinbox = QSpinBox() self.min_spinbox.setRange(1, 20) self.min_spinbox.setSingleStep(1) self.button = QPushButton('Recalculate') self.button.setCheckable(True) self.browser = QTextBrowser() vbox = QVBoxLayout() vbox2 = QVBoxLayout() vbox3 = QVBoxLayout() vbox.addWidget( self.visi_label ) vbox.addWidget( self.visi ) vbox.addWidget( self.fall_off_label ) vbox.addWidget( self.fall_off ) vbox.addWidget( self.thickness_label ) vbox.addWidget( self.thickness ) vbox.addWidget( self.trans_label ) vbox.addWidget( self.forced_translucency ) vbox2.addWidget( self.eps_label ) vbox2.addWidget( self.eps_spinbox ) vbox2.addWidget( self.min_points_label ) vbox2.addWidget( self.min_spinbox ) vbox2.addWidget( self.button ) vbox2.addWidget( self.browser ) vbox3.addWidget( self.all_electrodes ) vbox3.addWidget( self.only_clusters ) vbox3.addWidget( self.only_noise ) groupBox.setLayout(vbox) groupBox2.setLayout(vbox2) groupBox3.setLayout(vbox3) self.setLayout(gridLayout) self.layout().setSizeConstraint( QLayout.SetFixedSize ) def create_connections(self): self.visi.stateChanged.connect(self.__toggleVisibility) self.fall_off.valueChanged.connect(self.__setOpacityFalloff) self.thickness.valueChanged.connect(self.__setLineThickness) self.forced_translucency.stateChanged.connect(self.__toggleForceTranslucency) self.button.pressed.connect(self.__calculateDBSCANClusters) self.all_electrodes.toggled.connect(self.__setElectrodeTypeVisible) self.only_clusters.toggled.connect(self.__setElectrodeTypeVisible) self.only_noise.toggled.connect(self.__setElectrodeTypeVisible) def __setElectrodeTypeVisible(self): av = self.parent().active_vol vdata = self.parent()._vdata[av] if self.all_electrodes.isChecked(): vdata.setAllElectrodesVisible() elif self.only_clusters.isChecked(): vdata.setElectrodeClustersVisible() elif self.only_noise.isChecked(): vdata.setElectrodeNoiseVisible() def __calculateDBSCANClusters(self): av = self.parent().active_vol vdata = self.parent()._vdata[av] vdata.setDBSCANEps( self.eps_spinbox.value() ) vdata.setDBSCANMinPts( self.min_spinbox.value() ) vdata.clusterWithDBSCAN() count = vdata.electrode_centroid_clustering.dbscan_clusters labels = vdata.electrode_centroid_clustering.dbscan_results.labels_ out = 'Estimated number of clusters: %d\n' % count #self.browser.setText('Estimated number of clusters: %d' % count) for patnum, score in enumerate(labels): out += 'Patient {0}: {1}\n'.format(patnum, score) self.browser.setText(out) vdata.setElectrodeClustersVisible() self.only_clusters.setChecked(True) def __toggleVisibility(self): av = self.parent().active_vol vdata = self.parent()._vdata[av]._electrodes on = False if self.visi.checkState(): on = True self.all_electrodes.setEnabled(True) self.only_clusters.setEnabled(True) self.only_noise.setEnabled(True) else: self.all_electrodes.setEnabled(False) self.only_clusters.setEnabled(False) self.only_noise.setEnabled(False) for electrode in vdata: electrode.setVis(on) self.apply() def __toggleForceTranslucency(self): av = self.parent().active_vol vdata = self.parent()._vdata[av]._electrodes on = False if self.forced_translucency.checkState(): on = True for electrode in vdata: electrode.forceTranslucency(on) self.apply() def __setOpacityFalloff(self): av = self.parent().active_vol vdata = self.parent()._vdata[av]._electrodes #self.fall_off.setValue( vdata[-1].fall_off ) for electrode in vdata: electrode.setFallOff(self.fall_off.value() / 10.0) self.apply() def __setLineThickness(self): av = self.parent().active_vol vdata = self.parent()._vdata[av]._electrodes for electrode in vdata: electrode.setThickness(self.thickness.value() / 10.0) self.apply() def saveCurrentParams(self, av, fresh_load = False): #av = self.parent().active_vol #vdata = self.parent()._vdata[av]._electrodes if av not in self.saved_params.keys(): self.saved_params[av] = ElectrodeParameters() self.saved_params[av].electrodes_show = self.visi.isChecked() self.saved_params[av].electrodes_all = self.all_electrodes.isChecked() self.saved_params[av].electrodes_clusters = self.only_clusters.isChecked() self.saved_params[av].electrodes_noise = self.only_noise.isChecked() self.saved_params[av].falloff = self.fall_off.value() self.saved_params[av].thickness = self.thickness.value() self.saved_params[av].transp = self.forced_translucency.isChecked() self.saved_params[av].fresh_load = fresh_load def updateWidgetValues(self, av, default = False): #av = self.parent().active_vol #vdata = self.parent()._vdata[av]._electrodes if av not in self.saved_params.keys(): self.saved_params[av] = ElectrodeParameters() if default: # todo: need to have default values in one place for assignment self.visi.setChecked( False ) self.all_electrodes.setChecked( False ) self.only_clusters.setChecked( False ) self.only_noise.setChecked( False ) self.fall_off.setValue( 1 ) self.thickness.setValue( 10 ) self.forced_translucency.setChecked( False ) else: self.visi.setChecked( self.saved_params[av].electrodes_show ) self.all_electrodes.setChecked( self.saved_params[av].electrodes_all ) self.only_clusters.setChecked( self.saved_params[av].electrodes_clusters ) self.only_noise.setChecked( self.saved_params[av].electrodes_noise ) self.fall_off.setValue( self.saved_params[av].falloff ) self.thickness.setValue( self.saved_params[av].thickness ) self.forced_translucency.setChecked( self.saved_params[av].transp ) def apply(self): av = self.parent().active_vol self.parent().vol_qvtk_widgets[av].update()
class CheckTrait(QWidget): """ \brief An- bzw. Abwählbare Eigenschaft. Diese Eigensachft ist ähnlich wie CharaTrait mit den Eigenschaften im Speicher verknpüft, allerdings besitzen sie keine Werte, sondern sind nur an- oder Abwählbar. Beispiel für eine solche Eigenscahft sind die Nachteile. """ def __init__(self, trait, parent=None): super(CheckTrait, self).__init__(parent) self.__trait = trait #character = StorageCharacter::getInstance(); self.__layout = QHBoxLayout() self.setLayout(self.__layout) self.__checkBox = QCheckBox() self.__checkBox.setText(trait.name) self.__checkBox.setMaximumHeight(Config.WIDGET_INLINE_HEIGHT_MAX) self.__lineEdit = QLineEdit() #self.__lineEdit.setMinimumWidth( Config.TRAIT_CUSTOMTEXT_WIDTH_MIN ) self.__lineEdit.setMaximumHeight(Config.WIDGET_INLINE_HEIGHT_MAX) self.__layout.addWidget(self.__checkBox) self.__layout.addStretch() self.__layout.addWidget(self.__lineEdit) self.__checkBox.stateChanged.connect(self.setTraitValue) self.__lineEdit.textChanged.connect(self.setTraitCustomText) self.__trait.valueChanged.connect(self.setValue) if type(self.__trait) == StandardTrait: self.__trait.customTextChanged.connect(self.setText) self.__trait.availableChanged.connect(self.setEnabled) def __getValue(self): return self.__checkBox.checkState() def setValue(self, value): if value == 0: checkState = Qt.Unchecked elif value == 1: checkState = Qt.PartiallyChecked else: checkState = Qt.Checked self.__checkBox.setCheckState(checkState) value = property(__getValue, setValue) def setTraitValue(self, value): """ Legt den Wert der Eigenschaft im Speicher fest. """ if (self.__trait.value != value): self.__trait.value = value def setText(self, text): """ Legt den Zusatztext in diesem Widget fest. """ self.__lineEdit.setText(text) def setTraitCustomText(self, text): """ Legt den Zusatztext der Eigenschaft im Speicher fest. """ if (self.__trait.customText != text): self.__trait.customText = text def setDescriptionHidden(self, sw): """ Mit dieser Methode verstecke ich die Textzeile, in welcher zusätzlicher Beschreibungstext eingegeben werden kann. """ if (sw): self.__lineEdit.hide() else: self.__lineEdit.show() def hideOrShowTrait(self, species=None, age=None, era=None, breed=None, faction=None): """ Versteckt oder zeigt diese Eigenschaft. \note age und era gibt es zwar nicht bei SubPowerTrait, aber damit diese Funktion mit StorageCharacter.traitVisibleReasonChanged kompatible bleibt, werden sie als Argument übergeben. """ visible = True # Es können nur Eigenschaften versteckt werden, die einen age- bzw. era-Eintrag besitzen. if ((species and self.__trait.species and self.__trait.species != species) or #(age and self.__trait.age and self.__trait.age != age) or #(era and self.__trait.era and era not in self.__trait.era) or ((breed or faction) and self.__trait.only and breed not in self.__trait.only and faction not in self.__trait.only)): visible = False self.setVisible(visible)
class TabGeneral(QWidget): def __init__(self): QWidget.__init__(self) v_box = QVBoxLayout(self) self.setFixedWidth(500) self.settings = QSettings('NINJA-IDE','Kunai') #Groups self.gbox_Home = QGroupBox('On Start:') self.gbox_Close = QGroupBox("On Close:") self.gbox_Routes = QGroupBox('Routes:') v_box.addWidget(self.gbox_Home) v_box.addWidget(self.gbox_Close) v_box.addWidget(self.gbox_Routes) self.settings.beginGroup('Preferences') self.settings.beginGroup('General') #Home #Layout v_home = QVBoxLayout() ##CheckBox self.ch_lastSesionFiles = QCheckBox('Load files from last session.') self.ch_lastSesionFiles.setCheckState(self.settings.value('load_files', 2).toInt()[0]) self.ch_activatePlugins = QCheckBox('Activate Plugins.') self.ch_activatePlugins.setCheckState(self.settings.value('activate_plugins', 2).toInt()[0]) self.ch_notifyUpdates = QCheckBox('Nofity me for new available updates.') self.ch_notifyUpdates.setCheckState(self.settings.value('notify_updates', 0).toInt()[0]) v_home.addWidget(self.ch_lastSesionFiles) v_home.addWidget(self.ch_activatePlugins) v_home.addWidget(self.ch_notifyUpdates) self.gbox_Home.setLayout(v_home) #Close #Layout v_close = QVBoxLayout() ##CheckBox self.ch_saveState = QCheckBox('Save the window position and geometry.') self.ch_saveState.setCheckState(self.settings.value('save_position_geometry', 0).toInt()[0]) self.ch_confirmExit = QCheckBox('Confirm Exit.') self.ch_confirmExit.setCheckState(self.settings.value('confirm_exit', 2).toInt()[0]) v_close.addWidget(self.ch_saveState) v_close.addWidget(self.ch_confirmExit) self.gbox_Close.setLayout(v_close) #Routes #Layout g_routes = QGridLayout() ##TextBox self.txt_startRoute = QLineEdit() self.txt_startRoute.setText(self.settings.value('start_route','').toString()) self.txt_projectRoute = QLineEdit() self.txt_projectRoute.setText(self.settings.value('project_route','').toString()) self.txt_xtraPlugins = QLineEdit() self.txt_xtraPlugins.setText(self.settings.value('extra_plugins_route','').toString()) ##Button self.btn_startRoute = QPushButton(QIcon(resources.images['openFolder']),'') self.btn_projectRoute = QPushButton(QIcon(resources.images['openFolder']),'') self.btn_xtraPlugins = QPushButton(QIcon(resources.images['openFolder']),'') def load_start_route(): self.txt_startRoute.setText(load_directory(self, 'Start Route')) def load_project_route(): self.txt_projectRoute.setText(load_directory(self, 'Project Route')) def load_xtra_plugins_route(): self.txt_xtraPlugins.setText(load_directory(self, 'Extra Plugins Route')) self.settings.endGroup()#End General Preferences self.settings.endGroup() #Signal self.connect(self.btn_startRoute, SIGNAL('clicked()'), load_start_route) self.connect(self.btn_projectRoute, SIGNAL('clicked()'), load_project_route) self.connect(self.btn_xtraPlugins, SIGNAL('clicked()'), load_xtra_plugins_route) g_routes.addWidget(QLabel('Start Route:'), 0, 0, Qt.AlignRight) g_routes.addWidget(QLabel('Project Files:'), 1, 0, Qt.AlignRight) #g_routes.addWidget(QLabel('Extra Plugins Route:'), 2, 0, Qt.AlignRight) g_routes.addWidget(self.txt_startRoute, 0, 1) g_routes.addWidget(self.txt_projectRoute, 1, 1) #g_routes.addWidget(self.txt_xtraPlugins, 2 ,1) g_routes.addWidget(self.btn_startRoute, 0,2) g_routes.addWidget(self.btn_projectRoute, 1,2) #g_routes.addWidget(self.btn_xtraPlugins, 2, 2) self.gbox_Routes.setLayout(g_routes) def save_state(self): self.settings.beginGroup('Preferences') self.settings.beginGroup('General') #CheckBox self.settings.setValue('load_files', self.ch_lastSesionFiles.checkState()) self.settings.setValue('activate_plugins', self.ch_activatePlugins.checkState()) self.settings.setValue('save_position_geometry', self.ch_saveState.checkState()) self.settings.setValue('confirm_exit', self.ch_confirmExit.checkState()) self.settings.setValue('notify_updates', self.ch_notifyUpdates.checkState()) #TextBox self.settings.setValue('start_route', self.txt_startRoute.text()) self.settings.setValue('project_route', self.txt_projectRoute.text()) self.settings.setValue('extra_plugins_route', self.txt_xtraPlugins.text()) self.settings.endGroup()#End General Preferences self.settings.endGroup()
class QgsAnnotationWidget(QWidget): def __init__(self, parent, item): QWidget.__init__(self, parent) self.gridLayout_2 = QGridLayout(self) self.gridLayout_2.setObjectName(("gridLayout_2")) self.mMapPositionFixedCheckBox = QCheckBox(self) self.mMapPositionFixedCheckBox.setObjectName( ("mMapPositionFixedCheckBox")) self.gridLayout_2.addWidget(self.mMapPositionFixedCheckBox, 0, 0, 1, 1) self.gridLayout = QGridLayout() self.gridLayout.setObjectName(("gridLayout")) self.mFrameColorButton = QgsColorButton(self) self.mFrameColorButton.setText(("")) self.mFrameColorButton.setObjectName(("mFrameColorButton")) self.gridLayout.addWidget(self.mFrameColorButton, 3, 1, 1, 1) self.mFrameColorButton.colorChanged.connect( self.on_mFrameColorButton_colorChanged) self.mBackgroundColorLabel = QLabel(self) self.mBackgroundColorLabel.setObjectName(("mBackgroundColorLabel")) self.gridLayout.addWidget(self.mBackgroundColorLabel, 2, 0, 1, 1) self.mMapMarkerLabel = QLabel(self) self.mMapMarkerLabel.setObjectName(("mMapMarkerLabel")) self.gridLayout.addWidget(self.mMapMarkerLabel, 0, 0, 1, 1) self.mBackgroundColorButton = QgsColorButton(self) self.mBackgroundColorButton.setText(("")) self.mBackgroundColorButton.setObjectName(("mBackgroundColorButton")) self.gridLayout.addWidget(self.mBackgroundColorButton, 2, 1, 1, 1) self.mBackgroundColorButton.colorChanged.connect( self.on_mBackgroundColorButton_colorChanged) self.mMapMarkerButton = QPushButton(self) self.mMapMarkerButton.setText(("")) self.mMapMarkerButton.setObjectName(("mMapMarkerButton")) self.gridLayout.addWidget(self.mMapMarkerButton, 0, 1, 1, 1) self.mMapMarkerButton.clicked.connect(self.on_mMapMarkerButton_clicked) self.mFrameWidthLabel = QLabel(self) self.mFrameWidthLabel.setObjectName(("mFrameWidthLabel")) self.gridLayout.addWidget(self.mFrameWidthLabel, 1, 0, 1, 1) self.mFrameWidthSpinBox = QDoubleSpinBox(self) self.mFrameWidthSpinBox.setObjectName(("mFrameWidthSpinBox")) self.gridLayout.addWidget(self.mFrameWidthSpinBox, 1, 1, 1, 1) self.mFrameColorLabel = QLabel(self) self.mFrameColorLabel.setObjectName(("mFrameColorLabel")) self.gridLayout.addWidget(self.mFrameColorLabel, 3, 0, 1, 1) self.gridLayout_2.addLayout(self.gridLayout, 1, 0, 1, 1) self.mMapMarkerLabel.setBuddy(self.mMapMarkerButton) self.mFrameWidthLabel.setBuddy(self.mFrameWidthSpinBox) self.setWindowTitle("QgsAnnotationWidgetBase") self.mMapPositionFixedCheckBox.setText("Fixed map position") self.mBackgroundColorLabel.setText("Background color") self.mMapMarkerLabel.setText("Map marker") self.mFrameWidthLabel.setText("Frame width") self.mFrameColorLabel.setText("Frame color") self.setLayout(self.gridLayout_2) self.mItem = item if (self.mItem != None): self.blockAllSignals(True) if (self.mItem.mapPositionFixed()): self.mMapPositionFixedCheckBox.setCheckState(Qt.Checked) else: self.mMapPositionFixedCheckBox.setCheckState(Qt.Unchecked) self.mFrameWidthSpinBox.setValue(self.mItem.frameBorderWidth()) self.mFrameColorButton.setColor(self.mItem.frameColor()) self.mFrameColorButton.setColorDialogTitle("Select frame color") self.mFrameColorButton.setColorDialogOptions( QColorDialog.ShowAlphaChannel) self.mBackgroundColorButton.setColor( self.mItem.frameBackgroundColor()) self.mBackgroundColorButton.setColorDialogTitle( "Select background color") self.mBackgroundColorButton.setColorDialogOptions( QColorDialog.ShowAlphaChannel) self.symbol = self.mItem.markerSymbol() if (self.symbol != None): self.mMarkerSymbol = self.symbol.clone() self.updateCenterIcon() self.blockAllSignals(False) def apply(self): if (self.mItem != None): self.mItem.setMapPositionFixed( self.mMapPositionFixedCheckBox.checkState() == Qt.Checked) self.mItem.setFrameBorderWidth(self.mFrameWidthSpinBox.value()) self.mItem.setFrameColor(self.mFrameColorButton.color()) self.mItem.setFrameBackgroundColor( self.mBackgroundColorButton.color()) self.mItem.setMarkerSymbol(self.mMarkerSymbol) self.mMarkerSymbol = None #//item takes ownership self.mItem.update() def blockAllSignals(self, block): self.mMapPositionFixedCheckBox.blockSignals(block) self.mMapMarkerButton.blockSignals(block) self.mFrameWidthSpinBox.blockSignals(block) self.mFrameColorButton.blockSignals(block) def on_mMapMarkerButton_clicked(self): if (self.mMarkerSymbol == None): return markerSymbol = self.mMarkerSymbol.clone() dlg = QgsSymbolV2SelectorDialog(markerSymbol, QgsStyleV2.defaultStyle(), None, self) if (dlg.exec_() != QDialog.Rejected): self.mMarkerSymbol = markerSymbol self.updateCenterIcon() def on_mFrameColorButton_colorChanged(self, color): if (self.mItem == None): return self.mItem.setFrameColor(color) def updateCenterIcon(self): if (self.mMarkerSymbol == None): return icon = QgsSymbolLayerV2Utils.symbolPreviewIcon( self.mMarkerSymbol, self.mMapMarkerButton.iconSize()) self.mMapMarkerButton.setIcon(icon) def on_mBackgroundColorButton_colorChanged(self, color): if (self.mItem == None): return self.mItem.setFrameBackgroundColor(color)
class CheckTrait(QWidget): """ \brief An- bzw. Abwählbare Eigenschaft. Diese Eigensachft ist ähnlich wie CharaTrait mit den Eigenschaften im Speicher verknpüft, allerdings besitzen sie keine Werte, sondern sind nur an- oder Abwählbar. Beispiel für eine solche Eigenscahft sind die Nachteile. """ def __init__(self, trait, parent=None): super(CheckTrait, self).__init__(parent) self.__trait = trait #character = StorageCharacter::getInstance(); self.__layout = QHBoxLayout() self.setLayout( self.__layout ) self.__checkBox = QCheckBox() self.__checkBox.setText( trait.name ) self.__checkBox.setMaximumHeight( Config.WIDGET_INLINE_HEIGHT_MAX ) self.__lineEdit = QLineEdit() #self.__lineEdit.setMinimumWidth( Config.TRAIT_CUSTOMTEXT_WIDTH_MIN ) self.__lineEdit.setMaximumHeight(Config.WIDGET_INLINE_HEIGHT_MAX) self.__layout.addWidget( self.__checkBox ) self.__layout.addStretch() self.__layout.addWidget( self.__lineEdit ) self.__checkBox.stateChanged.connect(self.setTraitValue) self.__lineEdit.textChanged.connect(self.setTraitCustomText) self.__trait.valueChanged.connect(self.setValue) if type(self.__trait) == StandardTrait: self.__trait.customTextChanged.connect(self.setText) self.__trait.availableChanged.connect(self.setEnabled) def __getValue(self): return self.__checkBox.checkState() def setValue(self, value): if value == 0: checkState = Qt.Unchecked elif value == 1: checkState = Qt.PartiallyChecked else: checkState = Qt.Checked self.__checkBox.setCheckState(checkState) value = property(__getValue, setValue) def setTraitValue( self, value ): """ Legt den Wert der Eigenschaft im Speicher fest. """ if ( self.__trait.value != value ): self.__trait.value = value def setText(self, text): """ Legt den Zusatztext in diesem Widget fest. """ self.__lineEdit.setText(text) def setTraitCustomText( self, text ): """ Legt den Zusatztext der Eigenschaft im Speicher fest. """ if ( self.__trait.customText != text ): self.__trait.customText = text def setDescriptionHidden( self, sw ): """ Mit dieser Methode verstecke ich die Textzeile, in welcher zusätzlicher Beschreibungstext eingegeben werden kann. """ if ( sw ): self.__lineEdit.hide() else: self.__lineEdit.show() def hideOrShowTrait(self, species=None, age=None, era=None, breed=None, faction=None): """ Versteckt oder zeigt diese Eigenschaft. \note age und era gibt es zwar nicht bei SubPowerTrait, aber damit diese Funktion mit StorageCharacter.traitVisibleReasonChanged kompatible bleibt, werden sie als Argument übergeben. """ visible = True # Es können nur Eigenschaften versteckt werden, die einen age- bzw. era-Eintrag besitzen. if ( (species and self.__trait.species and self.__trait.species != species) or #(age and self.__trait.age and self.__trait.age != age) or #(era and self.__trait.era and era not in self.__trait.era) or ((breed or faction) and self.__trait.only and breed not in self.__trait.only and faction not in self.__trait.only) ): visible = False self.setVisible(visible)
class FindDialog(QDialog): def __init__(self, parent=None): logging.debug(__name__ + ": __init__") QDialog.__init__(self, parent) self.setWindowFlags(Qt.Window) self.setWindowTitle("Find...") self._findAlgorithm = None self._properties = [] self._scripts = [] self._find = True self._filter = False self.fill() def fill(self): logging.debug(__name__ + ": fill") self._findLabelLabel = QLabel("Label: ") self._findLabelLineEdit = QLineEdit() self._findLabelLineEdit.setToolTip("Example: Particle1") self._caseSensitiveCheckBox = QCheckBox("Case sensitive") self._exactMatchCheckBox = QCheckBox("Exact match") self._helpButton = QPushButton("&Help") self._findPreviousButton = QPushButton("&Previous") self._findPreviousButton.hide() self._findNumberLabel = QLabel("?/?") self._findNumberLabel.hide() self._findNextButton = QPushButton("&Find") self._filterButton = QPushButton("&Filter") self._resetButton = QPushButton("&Reset") self._closeButton = QPushButton("&Close") self.setLayout(QVBoxLayout()) self.layout().setSizeConstraint(QLayout.SetFixedSize) self._layout1 = QHBoxLayout() self._layout3 = QHBoxLayout() self._layout4 = QHBoxLayout() self._layout1.setSizeConstraint(QLayout.SetDefaultConstraint) self._layout3.setSizeConstraint(QLayout.SetDefaultConstraint) self._layout4.setSizeConstraint(QLayout.SetDefaultConstraint) self.layout().addLayout(self._layout1) self.layout().addLayout(self._layout3) self.layout().addStretch() self.layout().addLayout(self._layout4) self._layout1.addWidget(self._findLabelLabel) self._layout1.addWidget(self._findLabelLineEdit) self._layout3.addWidget(self._helpButton) self._layout3.addStretch() self._layout3.addWidget(self._caseSensitiveCheckBox) self._layout3.addWidget(self._exactMatchCheckBox) self._layout4.addWidget(self._findPreviousButton) self._layout4.addWidget(self._findNumberLabel) self._layout4.addWidget(self._findNextButton) self._layout4.addWidget(self._filterButton) self._layout4.addWidget(self._resetButton) self._layout4.addStretch() self._layout4.addWidget(self._closeButton) self.connect(self._findLabelLineEdit, SIGNAL("textChanged(QString)"), self.edited) self.connect(self._caseSensitiveCheckBox, SIGNAL("stateChanged(int)"), self.edited) self.connect(self._exactMatchCheckBox, SIGNAL("stateChanged(int)"), self.edited) self.connect(self._findPreviousButton, SIGNAL("clicked(bool)"), self.findPrevious) self.connect(self._findNextButton, SIGNAL("clicked(bool)"), self.findNext) self.connect(self._filterButton, SIGNAL("clicked(bool)"), self.filter) self.connect(self._resetButton, SIGNAL("clicked(bool)"), self.reset) self.connect(self._helpButton, SIGNAL("clicked(bool)"), self.help) self.connect(self._closeButton, SIGNAL("clicked(bool)"), self.reject) self._addStringProperty(False, False) self._addScript(False, False) def _removeProperty(self): for property in self._properties: if self.sender() in property: self._remove(property) return def _remove(self, object): for o in object: if isinstance(o, QWidget): o.close() self.layout().removeItem(object[0]) if object in self._properties: self._properties.remove(object) elif object in self._scripts: self._scripts.remove(object) def _addStringProperty(self, bool, deletable=True): layout2 = QHBoxLayout() findPropertyNameLabel = QLabel("Property: ") findPropertyNameLineEdit = QLineEdit() findPropertyNameLineEdit.setToolTip("Example: Label = Particle1 ") findPropertyValueLabel = QLabel(" = ") findPropertyValueLineEdit = QLineEdit() findPropertyValueLineEdit.setToolTip("Example: Label = Particle1 ") propertyAdd = QToolButton() propertyAdd.setText("+") propertyDelete = QToolButton() propertyDelete.setText("-") if deletable: propertyAdd.hide() else: propertyDelete.hide() layout2.addWidget(propertyAdd) layout2.addWidget(propertyDelete) layout2.addWidget(findPropertyNameLabel) layout2.addWidget(findPropertyNameLineEdit) layout2.addWidget(findPropertyValueLabel) layout2.addWidget(findPropertyValueLineEdit) self.connect(findPropertyNameLineEdit, SIGNAL("textChanged(QString)"), self.edited) self.connect(findPropertyValueLineEdit, SIGNAL("textChanged(QString)"), self.edited) self.connect(propertyAdd, SIGNAL("clicked(bool)"), self._addStringProperty) self.connect(propertyDelete, SIGNAL("clicked(bool)"), self._removeProperty) self.layout().insertLayout(len(self._properties) + len(self._scripts) + 1, layout2) self._properties += [ ( layout2, findPropertyNameLineEdit, findPropertyValueLineEdit, findPropertyNameLabel, findPropertyValueLabel, propertyAdd, propertyDelete, ) ] def _removeScript(self): for script in self._scripts: if self.sender() in script: self._remove(script) return def _addScript(self, bool, deletable=True): layout2 = QHBoxLayout() findScriptLabel = QLabel("Filter = ") findScriptLineEdit = QLineEdit("") findScriptLineEdit.setToolTip("Example: object.Label == 'Particle1' ") scriptAdd = QToolButton() scriptAdd.setText("+") scriptDelete = QToolButton() scriptDelete.setText("-") if deletable: scriptAdd.hide() else: scriptDelete.hide() layout2.addWidget(scriptAdd) layout2.addWidget(scriptDelete) layout2.addWidget(findScriptLabel) layout2.addWidget(findScriptLineEdit) self.connect(findScriptLineEdit, SIGNAL("textChanged(QString)"), self.edited) self.connect(scriptAdd, SIGNAL("clicked(bool)"), self._addScript) self.connect(scriptDelete, SIGNAL("clicked(bool)"), self._removeScript) self.layout().insertLayout(len(self._properties) + len(self._scripts) + 1, layout2) self._scripts += [(layout2, findScriptLineEdit, findScriptLabel, scriptAdd, scriptDelete)] def onScreen(self, filter=False, find=True): logging.debug(__name__ + ": onScreen") self._find = find self._filter = filter if self._find and self._filter: self._findNextButton.setDefault(True) self.setWindowTitle("Find/Filter...") elif self._find: self._findNextButton.setDefault(True) self.setWindowTitle("Find...") elif self._filter: self._filterButton.setDefault(True) self.setWindowTitle("Filter...") self._findNextButton.setVisible(find) if not find: self._findPreviousButton.setVisible(find) self._filterButton.setVisible(filter) self.show() self.raise_() self.activateWindow() self._findLabelLineEdit.setFocus() def keyPressEvent(self, event): """ """ if event.modifiers() == Qt.ControlModifier and event.key() == Qt.Key_W: self.close() QDialog.keyPressEvent(self, event) def setFindAlgorithm(self, findAlgorithm): logging.debug(__name__ + ": setFindAlgorithm") self._findAlgorithm = findAlgorithm def findAlgorithm(self): return self._findAlgorithm def label(self): return str(self._findLabelLineEdit.text().toAscii()) def setLabel(self, label): logging.debug(__name__ + ": setLabel " + label) self._findLabelLineEdit.setText(label) def properties(self): return [(str(property[1].text().toAscii()), str(property[2].text().toAscii())) for property in self._properties] def scripts(self): return [str(script[1].text().toAscii()) for script in self._scripts] def caseSensitive(self): return self._caseSensitiveCheckBox.checkState() == Qt.Checked def exactMatch(self): return self._exactMatchCheckBox.checkState() == Qt.Checked def edited(self): self._findPreviousButton.hide() if self._findNextButton.isVisible(): self._findNumberLabel.hide() self._findNextButton.setText("&Find") def _updateNumberLabel(self): current = self._findAlgorithm.currentNumber() total = self._findAlgorithm.numberOfResults() message = self._findAlgorithm.message() text = "" if self._filter: text = str(total) + " found" else: if total > 0: text = str(current) + "/" + str(total) else: text = "not found" if message: text += " (" + message + ")" self._findNumberLabel.setText(text) def findPrevious(self): logging.debug(__name__ + ": findPrevious") object = self._findAlgorithm.previous() self._updateNumberLabel() self.emit(SIGNAL("found"), object) def findNext(self): logging.debug(__name__ + ": findNext") if not self._findPreviousButton.isVisible(): self._findNextButton.setVisible(False) self._filterButton.setVisible(False) self._resetButton.setVisible(False) self._findNumberLabel.setText("Searching...") self._findNumberLabel.show() thread = ThreadChain(self._findAlgorithm.findUsingFindDialog, self) while thread.isRunning(): if not Application.NO_PROCESS_EVENTS: QCoreApplication.instance().processEvents() object = thread.returnValue() self._findNextButton.setVisible(True) if self._filter: self._filterButton.setVisible(True) self._resetButton.setVisible(True) self._findPreviousButton.show() self._findNextButton.setText("&Next") else: object = self._findAlgorithm.next() self._updateNumberLabel() self.emit(SIGNAL("found"), object) def filter(self): logging.debug(__name__ + ": filter") self._findNextButton.setVisible(False) self._filterButton.setVisible(False) self._resetButton.setVisible(False) self._findNumberLabel.setText("Searching...") self._findNumberLabel.show() thread = ThreadChain(self._findAlgorithm.findUsingFindDialog, self) while thread.isRunning(): if not Application.NO_PROCESS_EVENTS: QCoreApplication.instance().processEvents() if self._find: self._findNextButton.setVisible(True) self._filterButton.setVisible(True) self._resetButton.setVisible(True) self._updateNumberLabel() self.emit(SIGNAL("filtered"), self._findAlgorithm.results()) def reset(self): self.setLabel("") for o in self._scripts + self._properties: self._remove(o) self._addStringProperty(False, False) self._addScript(False, False) self._findAlgorithm.clear() self._updateNumberLabel() if self._filter: self.emit(SIGNAL("filtered"), None) self.update() def help(self): QMessageBox.about( self, "Info", "You can find objects \n1. using their label shown in the center view, \n2. their properties shown in the property view, or \n3. using a Python script returning a boolean. Empty fields are ignored. Examples are shown as tool tips.", )
class StatusBar(QStatusBar): def __init__(self): QStatusBar.__init__(self) self.editor = None self.widgetStatus = QWidget() vbox = QVBoxLayout(self.widgetStatus) vbox.setContentsMargins(0, 0, 0, 0) #Search Layout hSearch = QHBoxLayout() self.line = TextLine(self) self.line.setMinimumWidth(250) self.checkBackward = QCheckBox('Find Backward') self.checkSensitive = QCheckBox('Respect Case Sensitive') self.checkWholeWord = QCheckBox('Find Whole Words') self.btnClose = QPushButton(self.style().standardIcon(QStyle.SP_DialogCloseButton), '') self.btnFind = QPushButton(QIcon(resources.images['find']), '') self.btnPrevious = QPushButton(self.style().standardIcon(QStyle.SP_ArrowLeft), '') self.btnNext = QPushButton(self.style().standardIcon(QStyle.SP_ArrowRight), '') hSearch.addWidget(self.btnClose) hSearch.addWidget(self.line) hSearch.addWidget(self.btnFind) hSearch.addWidget(self.btnPrevious) hSearch.addWidget(self.btnNext) hSearch.addWidget(self.checkBackward) hSearch.addWidget(self.checkSensitive) hSearch.addWidget(self.checkWholeWord) vbox.addLayout(hSearch) #Replace Layout hReplace = QHBoxLayout() self.lineReplace = TextLine(self) self.lineReplace.setMinimumWidth(250) self.btnCloseReplace = QPushButton(self.style().standardIcon(QStyle.SP_DialogCloseButton), '') self.btnReplace = QPushButton('Replace') self.btnReplaceAll = QPushButton('Replace All') hReplace.addWidget(self.btnCloseReplace) hReplace.addWidget(self.lineReplace) hReplace.addWidget(self.btnReplace) hReplace.addWidget(self.btnReplaceAll) vbox.addLayout(hReplace) self.replace_visibility(False) self.addWidget(self.widgetStatus) self.shortEsc = QShortcut(QKeySequence(Qt.Key_Escape), self) self.connect(self.btnClose, SIGNAL("clicked()"), self.hide_status) self.connect(self.btnFind, SIGNAL("clicked()"), self.find) self.connect(self.btnNext, SIGNAL("clicked()"), self.find_next) self.connect(self.btnPrevious, SIGNAL("clicked()"), self.find_previous) self.connect(self, SIGNAL("messageChanged(QString)"), self.message_end) self.connect(self.btnCloseReplace, SIGNAL("clicked()"), lambda: self.replace_visibility(False)) self.connect(self.btnReplace, SIGNAL("clicked()"), self.replace) self.connect(self.btnReplaceAll, SIGNAL("clicked()"), self.replace_all) self.connect(self.shortEsc, SIGNAL("activated()"), self.hide_status) def focus_find(self, editor): self.line.setFocus() self.editor = editor self.line.selectAll() def replace_visibility(self, val): self.lineReplace.setVisible(val) self.btnCloseReplace.setVisible(val) self.btnReplace.setVisible(val) self.btnReplaceAll.setVisible(val) def hide_status(self): self.checkSensitive.setCheckState(Qt.Unchecked) self.checkWholeWord.setCheckState(Qt.Unchecked) self.checkBackward.setCheckState(Qt.Unchecked) self.hide() self.replace_visibility(False) self.editor.setFocus() def replace(self): s = False if self.checkSensitive.checkState() == Qt.Unchecked else True w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True self.editor.replace_match(str(self.line.text()), str(self.lineReplace.text()), s, w) def replace_all(self): s = False if self.checkSensitive.checkState() == Qt.Unchecked else True w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True self.editor.replace_match(str(self.line.text()), str(self.lineReplace.text()), s, w, True) def find(self): b = False if self.checkBackward.checkState() == Qt.Unchecked else True s = False if self.checkSensitive.checkState() == Qt.Unchecked else True w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True self.editor.find_match(str(self.line.text()), b, s, w) def find_next(self): s = False if self.checkSensitive.checkState() == Qt.Unchecked else True w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True self.editor.find_match(str(self.line.text()), False, s, w) def find_previous(self): s = False if self.checkSensitive.checkState() == Qt.Unchecked else True w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True self.editor.find_match(str(self.line.text()), True, s, w) def showMessage(self, message, timeout): self.show() super(StatusBar, self).showMessage(message, timeout) def message_end(self, message): if message == '': self.hide() super(StatusBar, self).clearMessage()
def initUI(self): self.setMinimumSize(QSize(150, 450)) self.setMaximumSize(QSize(150, 450)) layout = QVBoxLayout(self) self.setLayout(layout) #Create widgets l_sprite = QLabel(self) i_sprite = QSpinBox(self) i_trainerclass = QComboBox(self) i_name = QLineEdit(self) i_gender = QComboBox(self) l_songid = QLabel("Song:", self) i_songid = QSpinBox(self) i_doublebattle = QCheckBox("Double battle", self) i_choosemoves = QCheckBox("Explicit movesets", self) l_items = QLabel("Items:") i_item1 = QComboBox(self) i_item2 = QComboBox(self) i_item3 = QComboBox(self) i_item4 = QComboBox(self) #fill lists, set ranges values i_sprite.setRange(0, 255) i_songid.setRange(0, 0b01111111) i_trainerclass.addItems(self.trainerclasses) l_sprite.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) l_sprite.setMinimumSize(120, 64); l_sprite.setAlignment(Qt.AlignCenter) i_gender.addItems(['Male', 'Female']) i_item1.addItems(self.itemslist) i_item2.addItems(self.itemslist) i_item3.addItems(self.itemslist) i_item4.addItems(self.itemslist) #Set fields according to the trainer object i_sprite.setValue(self.trainer.trainerspriteid) i_name.setText(self.trainer.getName().getText()) i_songid.setValue(self.trainer.getSong()) i_trainerclass.setCurrentIndex(self.trainer.trainerclass) i_doublebattle.setChecked(self.trainer.doublebattle) i_choosemoves.setChecked(self.trainer.customMoves()) i_gender.setCurrentIndex(not self.trainer.isMale()) i_item1.setCurrentIndex(self.trainer.item1) i_item2.setCurrentIndex(self.trainer.item2) i_item3.setCurrentIndex(self.trainer.item3) i_item4.setCurrentIndex(self.trainer.item4) #Add all to layout layout.addWidget(l_sprite) layout.addWidget(i_sprite) layout.addWidget(i_gender) layout.addWidget(i_trainerclass) layout.addWidget(i_name) layout.addWidget(i_name) layout.addWidget(l_songid) layout.addWidget(i_songid) layout.addWidget(i_doublebattle) layout.addWidget(i_choosemoves) layout.addWidget(l_items) layout.addWidget(i_item1) layout.addWidget(i_item2) layout.addWidget(i_item3) layout.addWidget(i_item4) #Connect to signals i_sprite.valueChanged.connect(self.updateSprite) i_choosemoves.stateChanged.connect(self.chooseMovesChanged) #Keep values for future refs self.l_sprite = l_sprite self.i_sprite = i_sprite self.i_trainerclass = i_trainerclass self.i_gender = i_gender self.i_name = i_name self.i_songid = i_songid self.i_item1 = i_item1 self.i_item2 = i_item2 self.i_item3 = i_item3 self.i_item4 = i_item4 self.i_doublebattle = i_doublebattle self.i_choosemoves = i_choosemoves self.updateSprite() self.chooseMovesChanged(i_choosemoves.checkState())
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()
class FindDialog(QDialog): def __init__(self,parent=None): logging.debug(__name__ +': __init__') QDialog.__init__(self,parent) self.setWindowFlags(Qt.Window) self.setWindowTitle("Find...") self._findAlgorithm=None self._properties=[] self._scripts=[] self._find=True self._filter=False self.fill() def fill(self): logging.debug(__name__ +': fill') self._findLabelLabel = QLabel("Label: ") self._findLabelLineEdit = QLineEdit() self._findLabelLineEdit.setToolTip("Example: Particle1") self._caseSensitiveCheckBox=QCheckBox("Case sensitive") self._exactMatchCheckBox=QCheckBox("Exact match") self._helpButton = QPushButton("&Help") self._findPreviousButton = QPushButton("&Previous") self._findPreviousButton.hide() self._findNumberLabel = QLabel("?/?") self._findNumberLabel.hide() self._findNextButton = QPushButton("&Find") self._filterButton = QPushButton("&Filter") self._resetButton = QPushButton("&Reset") self._closeButton = QPushButton("&Close") self.setLayout(QVBoxLayout()) self.layout().setSizeConstraint(QLayout.SetFixedSize) self._layout1=QHBoxLayout() self._layout3=QHBoxLayout() self._layout4=QHBoxLayout() self._layout1.setSizeConstraint(QLayout.SetDefaultConstraint) self._layout3.setSizeConstraint(QLayout.SetDefaultConstraint) self._layout4.setSizeConstraint(QLayout.SetDefaultConstraint) self.layout().addLayout(self._layout1) self.layout().addLayout(self._layout3) self.layout().addStretch() self.layout().addLayout(self._layout4) self._layout1.addWidget(self._findLabelLabel) self._layout1.addWidget(self._findLabelLineEdit) self._layout3.addWidget(self._helpButton) self._layout3.addStretch() self._layout3.addWidget(self._caseSensitiveCheckBox) self._layout3.addWidget(self._exactMatchCheckBox) self._layout4.addWidget(self._findPreviousButton) self._layout4.addWidget(self._findNumberLabel) self._layout4.addWidget(self._findNextButton) self._layout4.addWidget(self._filterButton) self._layout4.addWidget(self._resetButton) self._layout4.addStretch() self._layout4.addWidget(self._closeButton) self.connect(self._findLabelLineEdit, SIGNAL('textChanged(QString)'), self.edited) self.connect(self._caseSensitiveCheckBox, SIGNAL('stateChanged(int)'), self.edited) self.connect(self._exactMatchCheckBox, SIGNAL('stateChanged(int)'), self.edited) self.connect(self._findPreviousButton, SIGNAL('clicked(bool)'), self.findPrevious) self.connect(self._findNextButton, SIGNAL('clicked(bool)'), self.findNext) self.connect(self._filterButton, SIGNAL('clicked(bool)'), self.filter) self.connect(self._resetButton, SIGNAL('clicked(bool)'), self.reset) self.connect(self._helpButton, SIGNAL('clicked(bool)'), self.help) self.connect(self._closeButton, SIGNAL('clicked(bool)'), self.reject) self._addStringProperty(False,False) self._addScript(False,False) def _removeProperty(self): for property in self._properties: if self.sender() in property: self._remove(property) return def _remove(self,object): for o in object: if isinstance(o,QWidget): o.close() self.layout().removeItem(object[0]) if object in self._properties: self._properties.remove(object) elif object in self._scripts: self._scripts.remove(object) def _addStringProperty(self,bool,deletable=True): layout2=QHBoxLayout() findPropertyNameLabel = QLabel("Property: ") findPropertyNameLineEdit = QLineEdit() findPropertyNameLineEdit.setToolTip("Example: Label = Particle1 ") findPropertyValueLabel = QLabel(" = ") findPropertyValueLineEdit = QLineEdit() findPropertyValueLineEdit.setToolTip("Example: Label = Particle1 ") propertyAdd = QToolButton() propertyAdd.setText("+") propertyDelete = QToolButton() propertyDelete.setText("-") if deletable: propertyAdd.hide() else: propertyDelete.hide() layout2.addWidget(propertyAdd) layout2.addWidget(propertyDelete) layout2.addWidget(findPropertyNameLabel) layout2.addWidget(findPropertyNameLineEdit) layout2.addWidget(findPropertyValueLabel) layout2.addWidget(findPropertyValueLineEdit) self.connect(findPropertyNameLineEdit, SIGNAL('textChanged(QString)'), self.edited) self.connect(findPropertyValueLineEdit, SIGNAL('textChanged(QString)'), self.edited) self.connect(propertyAdd, SIGNAL('clicked(bool)'), self._addStringProperty) self.connect(propertyDelete, SIGNAL('clicked(bool)'), self._removeProperty) self.layout().insertLayout(len(self._properties)+len(self._scripts)+1,layout2) self._properties+=[(layout2,findPropertyNameLineEdit,findPropertyValueLineEdit,findPropertyNameLabel,findPropertyValueLabel,propertyAdd,propertyDelete)] def _removeScript(self): for script in self._scripts: if self.sender() in script: self._remove(script) return def _addScript(self,bool,deletable=True): layout2=QHBoxLayout() findScriptLabel = QLabel("Filter = ") findScriptLineEdit = QLineEdit("") findScriptLineEdit.setToolTip("Example: object.Label == 'Particle1' ") scriptAdd = QToolButton() scriptAdd.setText("+") scriptDelete = QToolButton() scriptDelete.setText("-") if deletable: scriptAdd.hide() else: scriptDelete.hide() layout2.addWidget(scriptAdd) layout2.addWidget(scriptDelete) layout2.addWidget(findScriptLabel) layout2.addWidget(findScriptLineEdit) self.connect(findScriptLineEdit, SIGNAL('textChanged(QString)'), self.edited) self.connect(scriptAdd, SIGNAL('clicked(bool)'), self._addScript) self.connect(scriptDelete, SIGNAL('clicked(bool)'), self._removeScript) self.layout().insertLayout(len(self._properties)+len(self._scripts)+1,layout2) self._scripts+=[(layout2,findScriptLineEdit,findScriptLabel,scriptAdd,scriptDelete)] def onScreen(self, filter=False, find=True): logging.debug(__name__ +': onScreen') self._find=find self._filter=filter if self._find and self._filter: self._findNextButton.setDefault(True) self.setWindowTitle("Find/Filter...") elif self._find: self._findNextButton.setDefault(True) self.setWindowTitle("Find...") elif self._filter: self._filterButton.setDefault(True) self.setWindowTitle("Filter...") self._findNextButton.setVisible(find) if not find: self._findPreviousButton.setVisible(find) self._filterButton.setVisible(filter) self.show() self.raise_() self.activateWindow() self._findLabelLineEdit.setFocus() def keyPressEvent(self, event): """ """ if event.modifiers() == Qt.ControlModifier and event.key() == Qt.Key_W: self.close() QDialog.keyPressEvent(self, event) def setFindAlgorithm(self,findAlgorithm): logging.debug(__name__ +': setFindAlgorithm') self._findAlgorithm=findAlgorithm def findAlgorithm(self): return self._findAlgorithm def label(self): return str(self._findLabelLineEdit.text().toAscii()) def setLabel(self,label): logging.debug(__name__ +': setLabel '+label) self._findLabelLineEdit.setText(label) def properties(self): return [(str(property[1].text().toAscii()),str(property[2].text().toAscii())) for property in self._properties] def scripts(self): return [str(script[1].text().toAscii()) for script in self._scripts] def caseSensitive(self): return self._caseSensitiveCheckBox.checkState()==Qt.Checked def exactMatch(self): return self._exactMatchCheckBox.checkState()==Qt.Checked def edited(self): self._findPreviousButton.hide() if self._findNextButton.isVisible(): self._findNumberLabel.hide() self._findNextButton.setText("&Find") def _updateNumberLabel(self): current=self._findAlgorithm.currentNumber() total=self._findAlgorithm.numberOfResults() message=self._findAlgorithm.message() text="" if self._filter: text=str(total)+" found" else: if total>0: text=str(current)+"/"+str(total) else: text="not found" if message: text+=" ("+message+")" self._findNumberLabel.setText(text) def findPrevious(self): logging.debug(__name__ +': findPrevious') object=self._findAlgorithm.previous() self._updateNumberLabel() self.emit(SIGNAL("found"),object) def findNext(self): logging.debug(__name__ +': findNext') if not self._findPreviousButton.isVisible(): self._findNextButton.setVisible(False) self._filterButton.setVisible(False) self._resetButton.setVisible(False) self._findNumberLabel.setText("Searching...") self._findNumberLabel.show() thread = ThreadChain(self._findAlgorithm.findUsingFindDialog, self) while thread.isRunning(): if not Application.NO_PROCESS_EVENTS: QCoreApplication.instance().processEvents() object=thread.returnValue() self._findNextButton.setVisible(True) if self._filter: self._filterButton.setVisible(True) self._resetButton.setVisible(True) self._findPreviousButton.show() self._findNextButton.setText("&Next") else: object=next(self._findAlgorithm) self._updateNumberLabel() self.emit(SIGNAL("found"),object) def filter(self): logging.debug(__name__ +': filter') self._findNextButton.setVisible(False) self._filterButton.setVisible(False) self._resetButton.setVisible(False) self._findNumberLabel.setText("Searching...") self._findNumberLabel.show() thread = ThreadChain(self._findAlgorithm.findUsingFindDialog, self) while thread.isRunning(): if not Application.NO_PROCESS_EVENTS: QCoreApplication.instance().processEvents() if self._find: self._findNextButton.setVisible(True) self._filterButton.setVisible(True) self._resetButton.setVisible(True) self._updateNumberLabel() self.emit(SIGNAL("filtered"),self._findAlgorithm.results()) def reset(self): self.setLabel("") for o in self._scripts+self._properties: self._remove(o) self._addStringProperty(False,False) self._addScript(False,False) self._findAlgorithm.clear() self._updateNumberLabel() if self._filter: self.emit(SIGNAL("filtered"),None) self.update() def help(self): QMessageBox.about(self, 'Info', "You can find objects \n1. using their label shown in the center view, \n2. their properties shown in the property view, or \n3. using a Python script returning a boolean. Empty fields are ignored. Examples are shown as tool tips.")
class dlg_main(QDialog): def __init__(self): QDialog.__init__(self) self.dlg_csv_error = dlg_csv_error(self) self.dlg_csv_error.initGui() self.kukaku_dict = OrderedDict() self.kukaku_dict[u"第1次地域区画"] = 4 self.kukaku_dict[u"第2次地域区画"] = 6 self.kukaku_dict[u"第3次地域区画"] = 8 self.kukaku_dict[u"5倍地域メッシュ"] = 7 self.kukaku_dict[u"2倍地域メッシュ"] = 9 self.kukaku_dict[u"2分の1地域メッシュ"] = 9 self.kukaku_dict[u"4分の1地域メッシュ"] = 10 self.kukaku_dict[u"8分の1地域メッシュ"] = 11 self.kukaku_dict[u"10分の1細分地域メッシュ"] = 10 self.dat_str = np.array([]) self.table_header = np.array([]) self.csv_dat_str = np.array([]) self.EF_dia = myFileDialog(self) self.f_len = np.vectorize(lambda x: len(x)) def initGui(self): self.VBL_main = QVBoxLayout() self.HBL_selectfile = QHBoxLayout() self.Lab_selectfile = QLabel(u"ファイル名") self.LiE_selectfile = QLineEdit() self.PuB_selectfile = QPushButton() self.PuB_selectfile.setText(u"参照") self.HBL_selectfile.addWidget(self.Lab_selectfile) self.HBL_selectfile.addWidget(self.LiE_selectfile) self.HBL_selectfile.addWidget(self.PuB_selectfile) self.VBL_main.addLayout(self.HBL_selectfile) self.HBL_layername = QHBoxLayout() self.Lab_layername = QLabel(u"レイヤ名") self.LiE_layername = QLineEdit() self.HBL_layername.addWidget(self.Lab_layername) self.HBL_layername.addWidget(self.LiE_layername) self.VBL_main.addLayout(self.HBL_layername) self.GrL_config = QGridLayout() self.Lab_recopt_title = QLabel(u"レコードオプション") self.GrL_config.addWidget(self.Lab_recopt_title, 0, 0) self.HBL_recopt = QHBoxLayout() self.Lab_recopt = QLabel(u"無視するヘッダー行") self.SpB_recopt = QSpinBox() self.ChB_recopt = QCheckBox() self.ChB_recopt.setText(u"最初のレコードはフィールド名を保持している") self.HBL_recopt.addWidget(self.Lab_recopt) self.HBL_recopt.addWidget(self.SpB_recopt) self.HBL_recopt.addWidget(self.ChB_recopt) self.GrL_config.addLayout(self.HBL_recopt,0,1) self.Lab_mesh_titile = QLabel(u"メッシュ定義") self.GrL_config.addWidget(self.Lab_mesh_titile,1,0) self.HBL_mesh = QHBoxLayout() self.Lab_mesh_field = QLabel(u"メッシュコード列") self.CoB_mesh_field = QComboBox() self.Lab_mesh_category = QLabel(u"地域メッシュ区画") self.CoB_mesh_category = QComboBox() self.CoB_mesh_category.addItems(self.kukaku_dict.keys()) self.HBL_mesh.addWidget(self.Lab_mesh_field) self.HBL_mesh.addWidget(self.CoB_mesh_field) self.HBL_mesh.addWidget(self.Lab_mesh_category) self.HBL_mesh.addWidget(self.CoB_mesh_category) self.GrL_config.addLayout(self.HBL_mesh,1,1) self.Lab_crs_title = QLabel(u"測地系") self.GrL_config.addWidget(self.Lab_crs_title,2,0) self.CoB_crs = QComboBox() self.CoB_crs.addItems([u"世界測地系(EPSG:4612)",u"日本測地系(EPSG:4301)"]) self.GrL_config.addWidget(self.CoB_crs,2,1) self.VBL_main.addLayout(self.GrL_config) self.model_content = QStandardItemModel() self.TB_content = QTableView() self.TB_content.setModel(self.model_content) self.VBL_main.addWidget(self.TB_content) self.DBB_main = QDialogButtonBox() self.DBB_main.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) self.VBL_main.addWidget(self.DBB_main) self.setLayout(self.VBL_main) self.ChB_recopt.setChecked(True) self.ChB_recopt.stateChanged.connect(self.update_csv_str) self.SpB_recopt.valueChanged.connect(self.update_csv_str) self.PuB_selectfile.clicked.connect(self.EF_dia.open) self.DBB_main.accepted.connect(self.accept) self.DBB_main.rejected.connect(self.reject) def update_csv_str(self): if len(self.dat_str) == 0: pass else: if self.ChB_recopt.checkState() == 0: csv_header = np.array(["field_{0}".format(x) for x in np.arange(0,self.dat_str.shape[1])]) self.csv_dat_str = self.dat_str[(self.SpB_recopt.value()):,] else: csv_header = self.dat_str[self.SpB_recopt.value(),] self.csv_dat_str =self.dat_str[(self.SpB_recopt.value()+1):,] self.clear() self.table_header = np.array([hstr if hstr != u"" else 'field_{0}'.format(i) for i,hstr in enumerate(csv_header)]) load_table(self.model_content, self.table_header, np.arange(0,11), self.csv_dat_str) self.CoB_mesh_field.addItems(self.table_header) def clear(self): self.model_content.clear() self.CoB_mesh_field.clear() def accept(self): if len(self.LiE_selectfile.text()) == 0: QMessageBox.warning(self,u"警告",u"ファイルを選択してください") elif len(self.LiE_layername.text()) == 0: QMessageBox.warning(self,u"警告",u"レイヤ名を入力してください") else: self.csv_meshid_str = self.csv_dat_str[:,self.CoB_mesh_field.currentIndex()] if self.check_decimal(): self.dlg_csv_error.LB_caution.setText(u"以下のデータのメッシュコードに空白\nまたは数値以外の文字が含まれています") load_table(self.dlg_csv_error.model_content,self.table_header, self.e_ind, self.csv_dat_str) self.dlg_csv_error.show() elif self.check_digit(): str = u"以下のデータのメッシュコードの桁数が不正です\n" str += u'{0}コードは{1}桁の整数です。'.format(self.CoB_mesh_category.currentText(), self.kukaku_dict[self.CoB_mesh_category.currentText()]) self.dlg_csv_error.LB_caution.setText(str) load_table(self.dlg_csv_error.model_content,self.table_header, self.e_ind, self.csv_dat_str) self.dlg_csv_error.show() elif self.check_unique(): str = u'以下のデータのメッシュコードが重複しています' self.dlg_csv_error.LB_caution.setText(str) load_table(self.dlg_csv_error.model_content,self.table_header, self.e_ind, self.csv_dat_str) self.dlg_csv_error.show() else: self.create_tmp_csv() self.load_wkt_csv() return QDialog.accept(self) def check_decimal(self): e_ind = np.where(~def_c.isdecimal(self.csv_meshid_str))[0] if len(e_ind) > 0: self.e_ind = e_ind return True else: return False def check_digit(self): digit_arr = self.f_len(self.csv_meshid_str) e_ind = np.where( digit_arr != self.kukaku_dict[self.CoB_mesh_category.currentText()])[0] if len(e_ind) > 0: self.e_ind = e_ind return True else: return False def check_unique(self): u,c = np.unique(self.csv_meshid_str,return_counts=True) tf = c > 1 if tf.any(): self.e_ind = np.where(np.in1d(self.csv_meshid_str, u[tf]))[0] return True else: return False def create_tmp_csv(self): m_wkt = mesh_wkt(self.CoB_mesh_category.currentText()) infile_qstr = self.LiE_selectfile.text() self.outfile_qstr = self.LiE_selectfile.text().replace(".","_wkt.") in_fp = open(infile_qstr,"r") out_fp = open(self.outfile_qstr,"wb") reader = csv.reader(in_fp) writer = csv.writer(out_fp) n_skip = self.SpB_recopt.value() if n_skip > 0: for i in range(0,n_skip): next(reader,None) if self.ChB_recopt.checkState() == 2: header = next(reader,None) header.insert(0,"wkt") writer.writerow(header) for hrow in csv.reader(in_fp): hrow.insert(0,m_wkt.res_wkt(hrow[self.CoB_mesh_field.currentIndex()])) writer.writerow(hrow) in_fp.close() out_fp.close() def load_wkt_csv(self): uri = QUrl.fromLocalFile(self.outfile_qstr) uri.addQueryItem("type","csv") uri.addQueryItem("delimiter",",") uri.addQueryItem("wktField","1") uri.addQueryItem("encoding",self.EF_dia.encoding()) if self.ChB_recopt.checkState() == 2: uri.addQueryItem("useHeader","yes") else: uri.addQueryItem("useHeader","no") if self.CoB_crs.currentIndex() == 0: uri.addQueryItem("crs","EPSG:4612") elif self.CoB_crs.currentIndex() == 0: uri.addQueryItem("crs","EPSG:4301") self.vlayer = QgsVectorLayer(uri.toString(),self.LiE_layername.text(),"delimitedtext") if self.vlayer.isValid(): QgsMapLayerRegistry.instance().addMapLayer( self.vlayer )
class StatusBar(QStatusBar): def __init__(self): QStatusBar.__init__(self) self.editor = None self.widgetStatus = QWidget() vbox = QVBoxLayout(self.widgetStatus) vbox.setContentsMargins(0, 0, 0, 0) #Search Layout hSearch = QHBoxLayout() self.line = TextLine(self) self.line.setMinimumWidth(250) self.checkBackward = QCheckBox('Find Backward') self.checkSensitive = QCheckBox('Respect Case Sensitive') self.checkWholeWord = QCheckBox('Find Whole Words') self.btnClose = QPushButton( self.style().standardIcon(QStyle.SP_DialogCloseButton), '') self.btnFind = QPushButton(QIcon(resources.images['find']), '') self.btnPrevious = QPushButton( self.style().standardIcon(QStyle.SP_ArrowLeft), '') self.btnNext = QPushButton( self.style().standardIcon(QStyle.SP_ArrowRight), '') hSearch.addWidget(self.btnClose) hSearch.addWidget(self.line) hSearch.addWidget(self.btnFind) hSearch.addWidget(self.btnPrevious) hSearch.addWidget(self.btnNext) hSearch.addWidget(self.checkBackward) hSearch.addWidget(self.checkSensitive) hSearch.addWidget(self.checkWholeWord) vbox.addLayout(hSearch) #Replace Layout hReplace = QHBoxLayout() self.lineReplace = TextLine(self) self.lineReplace.setMinimumWidth(250) self.btnCloseReplace = QPushButton( self.style().standardIcon(QStyle.SP_DialogCloseButton), '') self.btnReplace = QPushButton('Replace') self.btnReplaceAll = QPushButton('Replace All') hReplace.addWidget(self.btnCloseReplace) hReplace.addWidget(self.lineReplace) hReplace.addWidget(self.btnReplace) hReplace.addWidget(self.btnReplaceAll) vbox.addLayout(hReplace) self.replace_visibility(False) self.addWidget(self.widgetStatus) self.shortEsc = QShortcut(QKeySequence(Qt.Key_Escape), self) self.connect(self.btnClose, SIGNAL("clicked()"), self.hide_status) self.connect(self.btnFind, SIGNAL("clicked()"), self.find) self.connect(self.btnNext, SIGNAL("clicked()"), self.find_next) self.connect(self.btnPrevious, SIGNAL("clicked()"), self.find_previous) self.connect(self, SIGNAL("messageChanged(QString)"), self.message_end) self.connect(self.btnCloseReplace, SIGNAL("clicked()"), lambda: self.replace_visibility(False)) self.connect(self.btnReplace, SIGNAL("clicked()"), self.replace) self.connect(self.btnReplaceAll, SIGNAL("clicked()"), self.replace_all) self.connect(self.shortEsc, SIGNAL("activated()"), self.hide_status) def focus_find(self, editor): self.line.setFocus() self.editor = editor self.line.selectAll() def replace_visibility(self, val): self.lineReplace.setVisible(val) self.btnCloseReplace.setVisible(val) self.btnReplace.setVisible(val) self.btnReplaceAll.setVisible(val) def hide_status(self): self.checkSensitive.setCheckState(Qt.Unchecked) self.checkWholeWord.setCheckState(Qt.Unchecked) self.checkBackward.setCheckState(Qt.Unchecked) self.hide() self.replace_visibility(False) if self.editor is not None: self.editor.setFocus() def replace(self): s = False if self.checkSensitive.checkState() == Qt.Unchecked else True w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True self.editor.replace_match(str(self.line.text()), str(self.lineReplace.text()), s, w) def replace_all(self): s = False if self.checkSensitive.checkState() == Qt.Unchecked else True w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True self.editor.replace_match(str(self.line.text()), str(self.lineReplace.text()), s, w, True) def find(self): b = False if self.checkBackward.checkState() == Qt.Unchecked else True s = False if self.checkSensitive.checkState() == Qt.Unchecked else True w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True self.editor.find_match(str(self.line.text()), b, s, w) def find_next(self): s = False if self.checkSensitive.checkState() == Qt.Unchecked else True w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True self.editor.find_match(str(self.line.text()), False, s, w) def find_previous(self): s = False if self.checkSensitive.checkState() == Qt.Unchecked else True w = False if self.checkWholeWord.checkState() == Qt.Unchecked else True self.editor.find_match(str(self.line.text()), True, s, w) def showMessage(self, message, timeout): self.widgetStatus.hide() self.replace_visibility(False) self.show() super(StatusBar, self).showMessage(message, timeout) def message_end(self, message): if message == '': self.hide() super(StatusBar, self).clearMessage() self.widgetStatus.show()
class GeneralTab(QWidget): def __init__(self): QWidget.__init__(self) vbox = QVBoxLayout(self) groupBoxStart = QGroupBox('On Start:') groupBoxClose = QGroupBox('On Close:') groupBoxWorkspace = QGroupBox('Workspace and Project:') #Start vboxStart = QVBoxLayout(groupBoxStart) self.checkLastSession = QCheckBox('Load files from last session') self.checkActivatePlugins = QCheckBox('Activate Plugins') self.checkNotifyUpdates = QCheckBox('Nofity me for new available updates.') vboxStart.addWidget(self.checkLastSession) vboxStart.addWidget(self.checkActivatePlugins) vboxStart.addWidget(self.checkNotifyUpdates) #Close vboxClose = QVBoxLayout(groupBoxClose) self.checkConfirmExit = QCheckBox('Confirm Exit.') vboxClose.addWidget(self.checkConfirmExit) #Workspace and Project gridWorkspace = QGridLayout(groupBoxWorkspace) self.txtWorkspace = QLineEdit() self.txtWorkspace.setReadOnly(True) self.btnWorkspace = QPushButton(QIcon(resources.images['openFolder']), '') gridWorkspace.addWidget(QLabel('Workspace'), 0, 0, Qt.AlignRight) gridWorkspace.addWidget(self.txtWorkspace, 0, 1) gridWorkspace.addWidget(self.btnWorkspace, 0, 2) self.txtExtensions = QLineEdit() gridWorkspace.addWidget(QLabel('Supported Extensions:'), 1, 0, Qt.AlignRight) gridWorkspace.addWidget(self.txtExtensions, 1, 1) self.txtPythonPath = QLineEdit() self.btnPythonPath = QPushButton(QIcon(resources.images['open']), '') gridWorkspace.addWidget(QLabel('Python Path:'), 2, 0, Qt.AlignRight) gridWorkspace.addWidget(self.txtPythonPath, 2, 1) gridWorkspace.addWidget(self.btnPythonPath, 2, 2) gridWorkspace.addWidget(QLabel('(This property need to be configured for Windows)'), 3, 1, Qt.AlignRight) #Settings settings = QSettings() settings.beginGroup('preferences') settings.beginGroup('general') self.checkLastSession.setCheckState(settings.value('loadFiles', Qt.Checked).toInt()[0]) self.checkActivatePlugins.setCheckState(settings.value('activatePlugins', Qt.Checked).toInt()[0]) self.checkNotifyUpdates.setCheckState(settings.value('notifyUpdates', Qt.Checked).toInt()[0]) self.checkConfirmExit.setCheckState(settings.value('confirmExit', Qt.Checked).toInt()[0]) self.txtWorkspace.setText(settings.value('workspace', '').toString()) self.txtPythonPath.setText(settings.value('pythonPath', resources.python_path).toString()) extensions = tuple(settings.value('extensions', list(manage_files.supported_extensions)).toList()) extensions = ', '.join([str(e.toString()) for e in extensions]) self.txtExtensions.setText(extensions) settings.endGroup() settings.endGroup() vbox.addWidget(groupBoxStart) vbox.addWidget(groupBoxClose) vbox.addWidget(groupBoxWorkspace) #Signals self.connect(self.btnWorkspace, SIGNAL("clicked()"), self._load_workspace) self.connect(self.btnPythonPath, SIGNAL("clicked()"), self._load_python_path) def _load_workspace(self): path = str(QFileDialog.getExistingDirectory(self, 'Select Workspace')) self.txtWorkspace.setText(path) def _load_python_path(self): path = str(QFileDialog.getOpenFileName(self, 'Select Python Path')) self.txtPythonPath.setText(path) def save(self): settings = QSettings() settings.beginGroup('preferences') settings.beginGroup('general') settings.setValue('loadFiles', self.checkLastSession.checkState()) settings.setValue('activatePlugins', self.checkActivatePlugins.checkState()) settings.setValue('notifyUpdates', self.checkNotifyUpdates.checkState()) settings.setValue('confirmExit', self.checkConfirmExit.checkState()) settings.setValue('workspace', self.txtWorkspace.text()) settings.setValue('pythonPath', self.txtPythonPath.text()) resources.python_path = str(self.txtPythonPath.text()) resources.workspace = str(self.txtWorkspace.text()) extensions = str(self.txtExtensions.text()).split(',') extensions = [e.strip() for e in extensions] settings.setValue('extensions', extensions) manage_files.supported_extensions = tuple(extensions) settings.endGroup() settings.endGroup()
class MainUI(remembering.RememberingMainWindow): """Main UI.""" _programs_file = os.path.join(multiplatform.data_dir, 'encuentro.data') def __init__(self, version, app_quit): super(MainUI, self).__init__() self.app_quit = app_quit self.finished = False self.version = version self.setWindowTitle('Encuentro') self.programs_data = data.ProgramsData(self, self._programs_file) self._touch_config() self.downloaders = {} for downtype, dloader_class in all_downloaders.iteritems(): self.downloaders[downtype] = dloader_class() # finish all gui stuff self.big_panel = central_panel.BigPanel(self) self.episodes_list = self.big_panel.episodes self.episodes_download = self.big_panel.downloads_widget self.setCentralWidget(self.big_panel) # the setting of menubar should be almost in the end, because it may # trigger the wizard, which needs big_panel and etc. self.action_play = self.action_download = None self.filter_line = self.filter_cbox = self.needsomething_alert = None self._menubar() systray.show(self) if config.get('autorefresh'): ue = update.UpdateEpisodes(self) ue.background() else: # refresh data if never done before or if last # update was 7 days ago last_refresh = config.get('autorefresh_last_time') if last_refresh is None or ( dt.datetime.now() - last_refresh > dt.timedelta(7)): ue = update.UpdateEpisodes(self) ue.background() self.show() self.episodes_download.load_pending() logger.debug("Main UI started ok") def _touch_config(self): """Do some config processing.""" # log the config, but without user and pass safecfg = config.sanitized_config() logger.debug("Configuration loaded: %s", safecfg) # we have a default for download dir if not config.get('downloaddir'): config['downloaddir'] = multiplatform.get_download_dir() # maybe clean some config if self.programs_data.reset_config_from_migration: config['user'] = '' config['password'] = '' config.pop('cols_width', None) config.pop('cols_order', None) config.pop('selected_row', None) def have_config(self): """Return if some config is needed.""" return config.get('user') and config.get('password') def have_metadata(self): """Return if metadata is needed.""" return bool(self.programs_data) def _menubar(self): """Set up the menu bar.""" menubar = self.menuBar() # applications menu menu_appl = menubar.addMenu(u'&Aplicación') icon = self.style().standardIcon(QStyle.SP_BrowserReload) action_reload = QAction(icon, '&Refrescar', self) action_reload.setShortcut('Ctrl+R') action_reload.setToolTip(u'Recarga la lista de programas') action_reload.triggered.connect(self.refresh_episodes) menu_appl.addAction(action_reload) icon = self.style().standardIcon(QStyle.SP_FileDialogDetailedView) action_preferences = QAction(icon, u'&Preferencias', self) action_preferences.triggered.connect(self.open_preferences) action_preferences.setToolTip( u'Configurar distintos parámetros del programa') menu_appl.addAction(action_preferences) menu_appl.addSeparator() icon = self.style().standardIcon(QStyle.SP_MessageBoxInformation) _act = QAction(icon, '&Acerca de', self) _act.triggered.connect(self.open_about_dialog) _act.setToolTip(u'Muestra información de la aplicación') menu_appl.addAction(_act) icon = self.style().standardIcon(QStyle.SP_DialogCloseButton) _act = QAction(icon, '&Salir', self) _act.setShortcut('Ctrl+Q') _act.setToolTip(u'Sale de la aplicación') _act.triggered.connect(self.on_close) menu_appl.addAction(_act) # program menu menu_prog = menubar.addMenu(u'&Programa') icon = self.style().standardIcon(QStyle.SP_ArrowDown) self.action_download = QAction(icon, '&Descargar', self) self.action_download.setShortcut('Ctrl+D') self.action_download.setEnabled(False) self.action_download.setToolTip(TTIP_DOWNLOAD_D) self.action_download.triggered.connect(self.download_episode) menu_prog.addAction(self.action_download) icon = self.style().standardIcon(QStyle.SP_MediaPlay) self.action_play = QAction(icon, '&Reproducir', self) self.action_play.setEnabled(False) self.action_play.setToolTip(TTIP_PLAY_D) self.action_play.triggered.connect(self.on_play_action) menu_prog.addAction(self.action_play) # toolbar for buttons toolbar = self.addToolBar('main') toolbar.addAction(self.action_download) toolbar.addAction(self.action_play) toolbar.addSeparator() toolbar.addAction(action_reload) toolbar.addAction(action_preferences) # filter text and button, to the right spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) toolbar.addWidget(spacer) toolbar.addWidget(QLabel(u"Filtro: ")) self.filter_line = QLineEdit() self.filter_line.setMaximumWidth(150) self.filter_line.textChanged.connect(self.on_filter_changed) toolbar.addWidget(self.filter_line) self.filter_cbox = QCheckBox(u"Sólo descargados") self.filter_cbox.stateChanged.connect(self.on_filter_changed) toolbar.addWidget(self.filter_cbox) # if needed, a warning that stuff needs to be configured icon = self.style().standardIcon(QStyle.SP_MessageBoxWarning) m = u"Necesita configurar algo; haga click aquí para abrir el wizard" self.needsomething_alert = QAction(icon, m, self) self.needsomething_alert.triggered.connect(self._start_wizard) toolbar.addAction(self.needsomething_alert) if not config.get('nowizard'): self._start_wizard() self._review_need_something_indicator() def _start_wizard(self, _=None): """Start the wizard if needed.""" if not self.have_config() or not self.have_metadata(): dlg = wizard.WizardDialog(self) dlg.exec_() self._review_need_something_indicator() def on_filter_changed(self, _): """The filter text has changed, apply it in the episodes list.""" text = self.filter_line.text() cbox = self.filter_cbox.checkState() self.episodes_list.set_filter(text, cbox) # after applying filter, nothing is selected, so check buttons # (easiest way to clean them all) self.check_download_play_buttons() def _review_need_something_indicator(self): """Hide/show/enable/disable different indicators if need sth.""" needsomething = bool(not self.have_config() or not self.have_metadata()) self.needsomething_alert.setVisible(needsomething) def shutdown(self): """Stop everything and quit. This shutdown con be called at any time, even on init, so we have extra precautions about which attributes we have. """ signal.emit('save_state') config.save() self.finished = True programs_data = getattr(self, 'programs_data', None) if programs_data is not None: programs_data.save() downloaders = getattr(self, 'downloaders', {}) for downloader in downloaders.itervalues(): downloader.shutdown() # bye bye self.app_quit() def on_close(self, _): """Close signal.""" if self._should_close(): self.shutdown() def closeEvent(self, event): """All is being closed.""" if self._should_close(): self.shutdown() else: event.ignore() def _should_close(self): """Still time to decide if want to close or not.""" logger.info("Attempt to close the program") pending = self.episodes_download.pending() if not pending: # all fine, save all and quit logger.info("Saving states and quitting") return True logger.debug("Still %d active downloads when trying to quit", pending) # stuff pending m = (u"Hay programas todavía en proceso de descarga!\n" u"¿Seguro quiere salir del programa?") QMB = QMessageBox dlg = QMB(u"Guarda!", m, QMB.Question, QMB.Yes, QMB.No, QMB.NoButton) opt = dlg.exec_() if opt != QMB.Yes: logger.info("Quit cancelled") return False # quit anyway, put all downloading and pending episodes to none logger.info("Fixing episodes, saving state and exiting") for program in self.programs_data.values(): state = program.state if state == Status.waiting or state == Status.downloading: program.state = Status.none return True def show_message(self, err_type, text): """Show different messages to the user.""" if self.finished: logger.debug("Ignoring message: %r", text) return logger.debug("Showing a message: %r", text) # error text can be produced by windows, try to to sanitize it if isinstance(text, str): try: text = text.decode("utf8") except UnicodeDecodeError: try: text = text.decode("latin1") except UnicodeDecodeError: text = repr(text) QMB = QMessageBox dlg = QMB(u"Atención: " + err_type, text, QMB.Warning, QMB.Ok, QMB.NoButton, QMB.NoButton) dlg.exec_() def refresh_episodes(self, _=None): """Update and refresh episodes.""" ue = update.UpdateEpisodes(self) ue.interactive() def download_episode(self, _=None): """Download the episode(s).""" episode_ids = self.episodes_list.selected_items() for episode_id in episode_ids: episode = self.programs_data[episode_id] self.queue_download(episode) @defer.inline_callbacks def queue_download(self, episode): """User indicated to download something.""" logger.debug("Download requested of %s", episode) if episode.state != Status.none: logger.debug("Download denied, episode %s is not in downloadeable " "state.", episode.episode_id) return # queue self.episodes_download.append(episode) self.episodes_list.episode_info.update(episode) self.check_download_play_buttons() if self.episodes_download.downloading: return logger.debug("Downloads: starting") while self.episodes_download.pending(): episode = self.episodes_download.prepare() try: filename, episode = yield self._episode_download(episode) except CancelledError: logger.debug("Got a CancelledError!") self.episodes_download.end(error=u"Cancelado") except BadCredentialsError: logger.debug("Bad credentials error!") msg = (u"Error con las credenciales: hay que configurar " u"usuario y clave correctos") self.show_message('BadCredentialsError', msg) self.episodes_download.end(error=msg) except EncuentroError, e: orig_exc = e.orig_exc msg = "%s(%s)" % (orig_exc, e) err_type = e.__class__.__name__ logger.exception("Custom Encuentro error: %s (%r)", e, orig_exc) notify(err_type, msg) self.episodes_download.end(error=u"Error: " + msg) except Exception, e: logger.exception("Unknown download error: %s (%r)", e, e) err_type = e.__class__.__name__ notify(err_type, str(e)) self.episodes_download.end(error=u"Error: " + str(e)) else:
class TabInterface(QWidget): def __init__(self, parent): QWidget.__init__(self) v_box = QVBoxLayout(self) self.setFixedWidth(500) self.settings = QSettings('NINJA-IDE','Kunai') #groups self.gbox_bars = QGroupBox('Lateral Bars:') self.gbox_fonts = QGroupBox('Fonts:') self.gbox_tabs = QGroupBox('Editor Tabs:') self.gbox_tabsPosition = QGroupBox('Tabs Position:') v_box.addWidget(self.gbox_bars) v_box.addWidget(self.gbox_fonts) v_box.addWidget(self.gbox_tabs) v_box.addWidget(self.gbox_tabsPosition) self.settings.beginGroup('Preferences') self.settings.beginGroup('Interface') #Lateral Bars ##Checks self.ch_simbols = QCheckBox('Show Simbols List.') self.ch_simbols.setCheckState(self.settings.value('show_simbol_list', 2).toInt()[0]) self.ch_files = QCheckBox('Show Files List.') self.ch_files.setCheckState(self.settings.value('show_files_list', 2).toInt()[0]) v_bars = QVBoxLayout() v_bars.addWidget(self.ch_simbols) v_bars.addWidget(self.ch_files) self.gbox_bars.setLayout(v_bars) #Buttons self.btn_editor_font = QPushButton(self.settings.value('editor_font','Monospace, 10').toString()) #self.btn_simbol_font = QPushButton(self.settings.value('simbol_list_font','Monospace, 10').toString()) #self.btn_message_font = QPushButton(self.settings.value('window_message_font','Monospace, 10').toString()) def load_editor_font(): self.btn_editor_font.setText(load_font(self, self.get_font_from_string(self.btn_editor_font.text()))) def load_simbol_font(): self.btn_simbol_font.setText(load_font()) def load_message_font(): self.btn_message_font.setText(load_font()) #SIGNALS self.connect(self.btn_editor_font, SIGNAL("clicked()"), load_editor_font) #self.connect(self.btn_simbol_font, SIGNAL ("clicked()"), load_simbol_font) #self.connect(self.btn_message_font, SIGNAL("clicked()"), load_message_font) g_font = QGridLayout() g_font.addWidget(QLabel('Editor Font:'), 0,0,Qt.AlignRight) #g_font.addWidget(QLabel('Simbol List:'),1, 0, Qt.AlignRight) #g_font.addWidget(QLabel('Messages Window:'),2,0,Qt.AlignRight) g_font.addWidget(self.btn_editor_font, 0,1) #g_font.addWidget(self.btn_simbol_font, 1, 1) #g_font.addWidget(self.btn_message_font, 2, 1) self.gbox_fonts.setLayout(g_font) #Edition Tabs #Checks self.ch_showEditTabs = QCheckBox('Show Editor Tabs') self.ch_showEditTabs.setCheckState(self.settings.value('show_editor_tabs', 2).toInt()[0]) self.ch_showClose = QCheckBox('Show Close Button on Tabs') self.ch_showClose.setCheckState(self.settings.value('show_close_tabs', 2).toInt()[0]) self.ch_hidePanel = QCheckBox('F11 hide/show side Panels') self.ch_hidePanel.setCheckState(self.settings.value('hide_show_panels', 2).toInt()[0]) #Option self.opt_left = QRadioButton('Left') self.opt_right =QRadioButton('Right') if (self.settings.value('next_tabs_location', 1).toInt()[0] == 1): self.opt_right.setChecked(True) else: self.opt_left.setChecked(True) h_optionNewFiles = QHBoxLayout() h_optionNewFiles.addWidget(QLabel('Location for New Files Tabs')) h_optionNewFiles.addWidget(self.opt_left) h_optionNewFiles.addWidget(self.opt_right) v_tabs = QVBoxLayout() v_tabs.addWidget(self.ch_showEditTabs) v_tabs.addWidget(self.ch_showClose) v_tabs.addLayout(h_optionNewFiles) #v_tabs.addWidget(self.ch_hidePanel) self.gbox_tabs.setLayout(v_tabs) #Tabs Position #Buttons #self.btn_orientation_change = QPushButton self.btn_hchange = QPushButton(QIcon(resources.images['splitCRotate']),'') self.btn_hchange.setIconSize(QSize(64,64)) self.btn_right_vchange = QPushButton(QIcon(resources.images['splitMRotate']),'') self.btn_right_vchange.setIconSize(QSize(64,64)) #SIGNAL self.connect(self.btn_hchange, SIGNAL('clicked()'), parent._splitter_central_rotate) self.connect(self.btn_right_vchange, SIGNAL('clicked()'), parent._splitter_main_rotate) self.settings.endGroup()#End General Preferences self.settings.endGroup() g_tabPosition = QGridLayout() g_tabPosition.addWidget(self.btn_hchange, 0,0) g_tabPosition.addWidget(self.btn_right_vchange, 0, 1) g_tabPosition.addWidget(QLabel('Vertical Change'),1,0, Qt.AlignCenter) g_tabPosition.addWidget(QLabel('Horizontal Change'),1,1, Qt.AlignCenter) self.gbox_tabsPosition.setLayout(g_tabPosition) #Fonts def get_font_from_string(self, font): if (font.isEmpty()): return QFont("Monospace", 10) listFont = font.remove(' ').split(',') ret = QFont(listFont[0], listFont[1].toInt()[0]) return ret def save_state(self, parent): self.settings.beginGroup('Preferences') self.settings.beginGroup('Interface') #CheckBox self.settings.setValue('show_simbol_list', self.ch_simbols.checkState()) self.settings.setValue('show_files_list', self.ch_files.checkState()) self.settings.setValue('show_editor_tabs', self.ch_showEditTabs.checkState()) self.settings.setValue('show_close_tabs', self.ch_showClose.checkState()) self.settings.setValue('hide_show_panels', self.ch_hidePanel.checkState()) #OptionButton if (self.opt_right.isChecked()): self.settings.setValue('next_tabs_location', 1) else: self.settings.setValue('next_tabs_location', 0) #Fonts self.settings.setValue('editor_font', self.btn_editor_font.text()) #self.settings.setValue('simbol_list_font', self.btn_simbol_font.text()) #self.settings.setValue('window_message_font', self.btn_message_font.text()) #Panels Positions if (parent.get_splitter_position_0() == CentralWidget): self.settings.setValue('central_tab_position', 0) self.settings.setValue('container_tab_position', 1) else: self.settings.setValue('central_tab_position', 1) self.settings.setValue('container_tab_position', 0) if (parent.get_splitter_main_position_0() == QSplitter): self.settings.setValue('main_tab_position', 0) self.settings.setValue('properties_tab_position', 1) else: self.settings.setValue('main_tab_position', 1) self.settings.setValue('properties_tab_position', 0) self.settings.endGroup()#End Interface Preferences self.settings.endGroup()
class ImportParameters(QWidget): def __init__(self): QWidget.__init__(self) self.filename = '' self.import_phases = [] self.import_values = [] grid = QGridLayout() grid.setAlignment(Qt.AlignTop) grid.setColumnStretch(1,1) self.setLayout(grid) self.filename_label = QLabel('No file selected') self.file_browse = QPushButton('Browse...') self.file_browse.setFixedWidth(85) self.file_browse.clicked.connect(self._on_file_browse) self.file_clear = QPushButton('Clear') self.file_clear.setFixedWidth(85) self.file_clear.clicked.connect(self._on_file_clear) self.file_clear.setHidden(True) grid.addWidget(self.filename_label, 1, 0, 1, 0) grid.addWidget(self.file_browse, 1, 3) grid.addWidget(self.file_clear, 1, 3) self.hjd_to_phases = QCheckBox('Convert HJD to phases') self.hjd_to_phases.stateChanged.connect(self._on_hjd_state_changed) grid.addWidget(self.hjd_to_phases, 2, 0, 1, 0) self.time_zero_label = QLabel('T<sub>0</sub>') self.time_zero_label.setFixedWidth(20) self.time_zero = CustomDoubleSpinBox() self.time_zero.setSingleStep(0.01) self.time_zero.setDecimals(10) self.time_zero.setAccelerated(True) self.time_zero.setDisabled(True) self.time_zero.setMinimum(0) self.time_zero.setFixedWidth(200) self.time_zero.setRange(0, sys.float_info.max) grid.addWidget(self.time_zero_label, 3, 0) grid.addWidget(self.time_zero, 3, 1) self.period_label = QLabel('P') self.period_label.setFixedWidth(20) self.period = CustomDoubleSpinBox() self.period.setFixedWidth(200) self.period.setDisabled(True) self.period.setRange(0, sys.float_info.max) self.period.setDecimals(10) grid.addWidget(self.period_label, 4, 0) grid.addWidget(self.period, 4, 1) self.magnitude_to_flux = QCheckBox('Convert magnitude to flux') self.magnitude_to_flux.stateChanged.connect(self._on_magnitude_state_changed) grid.addWidget(self.magnitude_to_flux, 5, 0, 1, 0) self.magnitude_max_label = QLabel('Mag') self.magnitude_max = CustomDoubleSpinBox() self.magnitude_max.setSingleStep(0.01) self.magnitude_max.setDecimals(10) self.magnitude_max.setAccelerated(True) self.magnitude_max.setDisabled(True) self.magnitude_max.setMinimum(0) self.magnitude_max.setFixedWidth(105) grid.addWidget(self.magnitude_max_label, 6, 0) grid.addWidget(self.magnitude_max, 6, 1) self.redraw = QPushButton("Redraw") self.redraw.clicked.connect(self._on_redraw) grid.addWidget(self.redraw, 6,3) def _on_file_browse(self): directory = "" if self.filename is None else QString(str("/").join(str(self.filename).split("/")[:-1])) types = TaskImporter.get_formats() filters = [] for value in types : filters.append(value.upper() + " (*." + value + ")") filters.append("All files (*.*)") self.filename = QFileDialog.getOpenFileName(self, 'Open file', directory=directory, filter=";;".join(filters)) self.update_file_label() def _on_file_clear(self): self.filename = '' self.update_file_label() def update_file_label(self): if self.filename : self.filename_label.setText(self.filename.split("/")[-1]) self.file_clear.setHidden(False) self.redraw.setDisabled(False) else: self.filename_label.setText('No file selected') self.file_clear.setHidden(True) self.redraw.setDisabled(True) pass def import_observation(self): if not self.filename : return try: phases, values = TaskImporter.load_file(self.filename) # convert JD time to phases if self.hjd_to_phases.checkState() == Qt.Checked: if self.time_zero.value() <= 0 : QMessageBox.warning(self, "Error", 'Invalid parameter "T<sub>0</sub>"!') return if self.period.value() <= 0 : QMessageBox.warning(self, "Error", 'Invalid parameter "P"!') return for (index, phase) in enumerate(phases): phases[index] = (phase - self.time_zero.value()) / self.period.value() % 1 # convert magnitude to flux if self.magnitude_to_flux.checkState() == Qt.Checked: for (index, value) in enumerate(values): values[index] = 10**(-(value - self.magnitude_max.value())/2.5) phases = flip_phase_list(phases) # TODO Detrending #slope = (values[8] - values[-8])/(phases[8] - phases[-8]) #angle = atan(slope) # #for index, value in enumerate(values): # hyp = sqrt(abs((phases[-8] - phases[index])**2 - (values[-8] - values[index])**2)) # print hyp # values[index] += hyp * sin(angle) self.import_phases = phases self.import_values = values Global.event.data_imported.emit(self.import_phases, self.import_values) except: QMessageBox.critical(self, "Import error", "Error importing data!\nError: " + str(sys.exc_info()[1])) raise def _on_redraw(self): if not self.filename : QMessageBox.warning(self, "Import file", "Please import file first") return self.import_observation() Global.event.interface_redraw_clicked.emit() pass def _on_hjd_state_changed(self, state): if state == Qt.Checked: self.time_zero.setDisabled(False) self.period.setDisabled(False) else: self.time_zero.setDisabled(True) self.period.setDisabled(True) pass def _on_magnitude_state_changed(self, state): if state == Qt.Checked: self.magnitude_max.setDisabled(False) else: self.magnitude_max.setDisabled(True) pass
class LDSConfigPage(QWizardPage): def __init__(self, parent=None,key=None): super(LDSConfigPage, self).__init__(parent) self.parent = parent self.key = key#'lds' try: (ldsurl,ldskey,ldssvc,ldsver,ldsfmt,ldscql) = self.parent.mfr.readLDSConfig() except: (ldsurl,ldskey,ldssvc,ldsver,ldsfmt,ldscql) = (None,)*6 self.setTitle(self.parent.plist.get(self.key)[1]+' Configuration Options') self.setSubTitle('Here you can enter a name for your custom configuration file, your LDS API key and required output. Also select whether you want to configure a proxy or enable password encryption') QToolTip.setFont(QFont('SansSerif', 10)) #labels fileLabel = QLabel('User Config File') keyLabel = QLabel('LDS API Key') destLabel = QLabel('Output Type') internalLabel = QLabel('Save Layer-Config in DB') self.warnLabel = QLabel('!!!') encryptionLabel = QLabel('Enable Password Protection') serviceLabel = QLabel('Service Type') versionLabel = QLabel('Service Version') infoLinkLabel = QLabel('<a href="http://www.linz.govt.nz/about-linz/linz-data-service/features/how-to-use-web-services">LDS API Information Page</a>') infoLinkLabel.setOpenExternalLinks(True); keyLinkLabel = QLabel('<a href="http://data.linz.govt.nz/my/api/">LDS API Key</a>') keyLinkLabel.setOpenExternalLinks(True); #edit boxes self.fileEdit = QLineEdit(self.parent.uchint) self.fileEdit.setToolTip('Name of user config file (without .conf suffix)') self.keyEdit = QLineEdit(ldskey) self.keyEdit.setToolTip('This is your LDS API key. If you have an account you can copy your key from here <a href="http://data.linz.govt.nz/my/api/">http://data.linz.govt.nz/my/api/</a>') #dropdown self.destSelect = QComboBox() self.destSelect.setToolTip('Choose from one of four possible output destinations') self.destSelect.addItem('') for itemkey in ('pg','ms','fg','sl'): itemindex = self.parent.plist.get(itemkey)[0] itemdata = self.parent.plist.get(itemkey)[1] self.destSelect.addItem(itemdata, itemindex) if itemdata == self.parent.sechint: self.destSelect.setCurrentIndex(itemindex) self.serviceSelect = QComboBox() self.serviceSelect.setToolTip('Choose from WFS (or one day, WMS)') for itemkey in ('','WFS','WMS','WMTS'): self.serviceSelect.addItem(itemkey) self.serviceSelect.setCurrentIndex(0) self.versionSelect = QComboBox() self.versionSelect.setToolTip('Choose service Version') for itemkey in ('','1.0.0','1.1.0','2.0.0'): self.versionSelect.addItem(itemkey) self.versionSelect.setCurrentIndex(0) self.keyEdit.setValidator(QRegExpValidator(QRegExp("[a-fA-F0-9]{32}", re.IGNORECASE), self)) #checkbox self.internalEnable = QCheckBox() self.internalEnable.setToolTip('Enable saving layer-config (per layer config and progress settings) internally') self.internalEnable.toggle() self.internalEnable.setChecked(True) self.internalEnable.stateChanged.connect(self.setWarn) self.encryptionEnable = QCheckBox() self.encryptionEnable.setToolTip('Encrypt any passwords saved to user config file') self.registerField(self.key+"file",self.fileEdit) self.registerField(self.key+"apikey",self.keyEdit) self.registerField(self.key+"dest",self.destSelect,"currentIndex") self.registerField(self.key+"internal",self.internalEnable) self.registerField(self.key+"encryption",self.encryptionEnable) #grid grid = QGridLayout() grid.setSpacing(10) grid.addWidget(fileLabel, 1, 0) grid.addWidget(self.fileEdit, 1, 2) #grid.addWidget(cfileButton, 1, 3) grid.addWidget(keyLabel, 2, 0) grid.addWidget(self.keyEdit, 2, 2) grid.addWidget(destLabel, 3, 0) grid.addWidget(self.destSelect, 3, 2) grid.addWidget(internalLabel, 4, 0) grid.addWidget(self.internalEnable, 4, 2) #if self.internalEnable.checkState(): grid.addWidget(intwarnLabel, 4, 4) grid.addWidget(encryptionLabel, 5, 0) grid.addWidget(self.encryptionEnable, 5, 2) svgrid = QGridLayout() svgrid.addWidget(serviceLabel, 0, 0) svgrid.addWidget(self.serviceSelect, 0, 2) svgrid.addWidget(versionLabel, 1, 0) svgrid.addWidget(self.versionSelect, 1, 2) hbox = QHBoxLayout() hbox.addStretch(1) hbox.addLayout(svgrid) #layout vbox = QVBoxLayout() vbox.addLayout(grid) #vbox.addLayout(hbox) vbox.addStretch(1) vbox.addWidget(self.warnLabel) vbox.addWidget(keyLinkLabel) vbox.addWidget(infoLinkLabel) self.setLayout(vbox) #def selectConfFile(self): # self.fileEdit.setText(QFileDialog.getOpenFileName()) def nextId(self): #if self.field(self.key+"proxy").toBool(): return self.parent.plist.get('proxy')[0] #return int(self.field(self.key+"dest").toString()) def setWarn(self): if self.internalEnable.checkState(): ldslog.warn('Warning, Internal config selected') self.warnLabel.setText('!!!') QApplication.processEvents() else: ldslog.warn('External config selected') self.warnLabel.setText('^_^') QApplication.processEvents()
class LoginView(QDialog,View): _mainLayout_ = None #We put all widgets in container widgets, #If we add all of them to layouts by themselves we get Bus error #when doing mainLayout.addLayout() _usernameWidget_ = None _passWidget_ = None _rememberWidget_ = None _buttonsWidget_ = None _logoLabel_ = None _usernameLabel_ = None _passwordLabel_ = None _usernameLineEdit_ = None _passwordLineEdit_ = None _rememberCheckbox_ = None _registerButton_ = None _loginButton_ = None _myBloopSiteLink_ = None #QLabel _movieWaiting_ = None #Gotta keep a refernce to the .GIF, otherwise it won't send signals to the QLabel _controller_ = None _menuBar_ = None def __init__(self, parent=None): ''' Initializes all components in the dialog. Whoever uses this view, and its controller, must letter bind the controller and the view using view.setController(c) The controller then will be able to access all the view elements with the getters defined in this dummy view class. The controller can also connect to events triggered by this dialog. ''' QDialog.__init__(self) View.__init__(self) #self.createMenubar() #set up the fields self.setWindowTitle(i18n.LABEL_WINDOW_LOGIN_TITLE) imagePath = os.path.join("i18n","images","us_en") self.setWindowIcon(QIcon(os.path.join(imagePath,"bloop.png"))) #Blooploader Logo pixmap = QPixmap(os.path.join('i18n','images','us_en','login_logo.png')) assert(not pixmap.isNull()) self._logoLabel_ = QLabel() self._logoLabel_.setPixmap(pixmap) #login row self._usernameLabel_ = QLabel(i18n.LABEL_USERNAME) self._usernameLineEdit_ = QLineEdit() self._usernameWidget_ = PairedWidget(self._usernameLabel_, self._usernameLineEdit_) #password row self._passwordLabel_ = QLabel(i18n.LABEL_PASSWORD) self._passwordLineEdit_ = QLineEdit() self._passwordLineEdit_.setEchoMode(QLineEdit.Password) self._passWidget_ = PairedWidget(self._passwordLabel_, self._passwordLineEdit_) #remember me row self._rememberCheckbox_ = QCheckBox(i18n.LABEL_REMEMBER_ME) self._rememberWidget_= QWidget() rememberLayout = QHBoxLayout() rememberLayout.addStretch() rememberLayout.addWidget(self._rememberCheckbox_) self._rememberWidget_.setLayout(rememberLayout) #buttons self._loginButton_ = QPushButton(i18n.LABEL_LOGIN) self._buttonsWidget_ = QHBoxLayout() self._buttonsWidget_.addStretch() self._buttonsWidget_.addWidget(self._loginButton_) #MyBloop.com Link at the end self._myBloopSiteLink_ = QLabel('<a href="http://www.mybloop.com">www.mybloop.com</a>') myBloopSiteLinkLayout = QHBoxLayout() myBloopSiteLinkLayout.addStretch() myBloopSiteLinkLayout.addWidget(self._myBloopSiteLink_) myBloopSiteLinkLayout.addStretch() #Stack em up vertically self._mainLayout_ = QVBoxLayout() self._mainLayout_.addStretch() self._mainLayout_.addWidget(self._logoLabel_,0,Qt.AlignCenter) self._mainLayout_.addWidget(self._usernameWidget_) self._mainLayout_.addWidget(self._passWidget_) self._mainLayout_.addWidget(self._rememberWidget_) self._mainLayout_.addLayout(self._buttonsWidget_) self._mainLayout_.addLayout(myBloopSiteLinkLayout) self._mainLayout_.addStretch() #Add another layout to show while we wait #put all this on a QStackedLayout self._passwordLineEdit_.setStyleSheet("border-style: outset; border-width: 1px; border-radius: 3px; border-color: gray; padding: 3px;") self._usernameLineEdit_.setStyleSheet("border-style: outset; border-width: 1px; border-radius: 3px; border-color: gray; padding: 3px;") self._waitLayout_ = QVBoxLayout() self._waitLayout_.setAlignment(Qt.AlignHCenter) self._waitLabel_ = QLabel() pixmap = QPixmap(os.path.join('i18n','images','us_en','loading.png')) self._waitLabel_.setPixmap(pixmap) self._waitLayout_.addWidget(self._waitLabel_) self._waitLayout_.addStretch() self._stackedLayout_ = QStackedLayout() waitWidget = QWidget() waitWidget.setLayout(self._waitLayout_) mainWidget = QWidget() mainWidget.setLayout(self._mainLayout_) self._stackedLayout_.addWidget(mainWidget) self._stackedLayout_.addWidget(waitWidget) self._stackedLayout_.setCurrentIndex(0) #main layout self.fillBackground() loginLayout = QVBoxLayout() loginLayout.addLayout(self._stackedLayout_) self.setLayout(loginLayout) def getLineEditUsername(self): return self._usernameLineEdit_ def getLineEditPassword(self): return self._passwordLineEdit_ def getUsernameLabel(self): return self._usernameLabel_ def getPasswordLabel(self): return self._passwordLabel_ def getButtonLogin(self): return self._loginButton_ def getButtonRegister(self): return self._registerButton_ def getLabelMyBloopSiteLink(self): '''Returns a QLabel object. This QLabel contains one or more links to MyBloop.com pages. It's the responsability of the controller to catch the linkActivated(QString) signal to open a browser for the user. The String passed contains the URL''' return self._myBloopSiteLink_ def getRememberCheckbox(self): return self._rememberCheckbox_ def wantsToBeRemembered(self): return self._rememberCheckbox_.checkState() == Qt.Checked def fillBackground(self): """Fills the background with a solid white""" self.palette().setColor(QPalette.Background, QColor(255,255,255)) self.setAutoFillBackground(True) def showForm(self): self._stackedLayout_.setCurrentIndex(0) def showWaiting(self): self._stackedLayout_.setCurrentIndex(1) def createMenubar(self): self._menuBar_ = QMenuBar(None) #Create File Menu self._fileMenu_ = QMenu(self) am = ActionManager.getInstance() #todo add actions from ActionManager for action in am.getBloopFileMenuActions(): print "MainView.createMenuBar() adding action to file menu", action print self._fileMenu_.addAction(action) #Create Help Menu self._menuBar_.addMenu(self._fileMenu_) #self.setMenuWidget(self._menuBar_) #self._menuBar_.setVisible(True)
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()
class NewOrEditOrganizationViewWidget(QDialog, FWidget): def __init__(self, pp=None, owner=None, parent=None, *args, **kwargs): QDialog.__init__(self, parent, *args, **kwargs) self.setWindowTitle(u"Nouvel Organisation") self.parent = parent self.pp = pp self.owner = owner vbox = QVBoxLayout() self.organization_group_box() vbox.addWidget(self.organGroupBoxBtt) self.setLayout(vbox) def organization_group_box(self): self.organGroupBoxBtt = QGroupBox(self.tr("Nouvelle Organisation")) self.liste_devise = Organization.DEVISE # Combobox widget self.box_devise = QComboBox() for index in self.liste_devise: self.box_devise.addItem("{} {}".format( self.liste_devise[index], index)) self.checked = QCheckBox("Active") self.checked.setChecked(True) self.checked.setToolTip(u"""Cocher si vous voulez pour deactive le login continue à utiliser le systeme""") self.name_orga = LineEdit() self.phone = IntLineEdit() self.bp = LineEdit() self.adress_org = QTextEdit() self.email_org = LineEdit() formbox = QFormLayout() formbox.addRow(FormLabel(u"Nom de l'organisation *"), self.name_orga) formbox.addRow(FormLabel(u"Tel *"), self.phone) formbox.addRow( FormLabel(u"Activer la saisie de mot de passe"), self.checked) formbox.addRow(FormLabel(u"Devise"), self.box_devise) formbox.addRow(FormLabel(u"B.P"), self.bp) formbox.addRow(FormLabel(u"E-mail:"), self.email_org) formbox.addRow(FormLabel(u"Adresse complete:"), self.adress_org) butt = Button_save(u"Enregistrer") butt.clicked.connect(self.save_edit) formbox.addRow("", butt) self.organGroupBoxBtt.setLayout(formbox) def save_edit(self): ''' add operation ''' if check_is_empty(self.name_orga): return if check_is_empty(self.phone): return name_orga = str(self.name_orga.text()) device = str(self.box_devise.currentText().split()[1]) bp = str(self.bp.text()) email_org = str(self.email_org.text()) phone = str(self.phone.text()) adress_org = str(self.adress_org.toPlainText()) org = Organization() org.phone = phone org.device = device org.name_orga = name_orga org.email_org = email_org org.bp = bp org.adress_org = adress_org org.is_login = True if self.checked.checkState( ) == Qt.Checked else False org.save() self.accept()
class Widget(QWidget): def __init__(self, parent=None): super(Widget, self).__init__(parent) buttonHelp1 = QPushButton('help') buttonHelp1.setEnabled(False) buttonHelp1.setToolTip('The table below, with the exception of the last row and column, describe the network\n' + 'in terms of the weight coefficient values. The value of a cell in the n-th row and m-th\n' + 'column is the weight of the n-th feature for the m-th animal class.\n\n' + 'As you can see, each animal class has its own neuron that recognizes it, and each of\n' + 'these neurons has inputs that receive individual feature values.\n\n' + 'The last column represents the input vector, and the last row contains the network\n' + 'output values.') buttonHelp2 = QPushButton('help') buttonHelp2.setEnabled(False) buttonHelp2.setToolTip('If you show the winner, you will see the neuron whose response was the strongest.\n' + 'This neuron indicates the animal class the examined object will most probably fall into.\n' + 'The table below, with the exception of the last row and column, describe the network\n' + 'in terms of the weight coefficient values. The value of a cell in the n-th row and m-th\n' + 'column is the weight of the n-th feature for the m-th animal class.\n\n' + 'As you can see, each animal class has its own neuron that recognizes it, and each of\n' + 'these neurons has inputs that receive individual feature values.\n\n' + 'The last column represents the input vector, and the last row contains the network\n' + 'output values.') hBoxLayout1 = QHBoxLayout() hBoxLayout1.addWidget(QLabel('The neural network in this example uses five features to recognize\n' + 'three classes of animals. Its weight coefficients are predefined and shown in the table below.\n\n' + 'To test the network behavior, enter the input signals in the rightmost column and read the output\n' + 'values from the bottom row.')) hBoxLayout1.addWidget(buttonHelp1) self.checkBoxWinner = QCheckBox() self.checkBoxWinner.setText('Show the winner') hBoxLayout2 = QHBoxLayout() hBoxLayout2.addWidget(self.checkBoxWinner) hBoxLayout2.addWidget(buttonHelp2) self.tableWidget = QTableWidget() self.labelNeuron = QLabel('(There is no winner.)') self.labelType = QLabel('This is something strange!') self.spinBoxThreshold = QDoubleSpinBox() self.spinBoxThreshold.setValue(5.0) self.groupBox = QGroupBox('Show the winner') gridLayout = QGridLayout() gridLayout.addWidget(QLabel('And the winner is...'), 0, 0) gridLayout.addWidget(self.labelNeuron, 0, 1) gridLayout.addWidget(QLabel('Because of this, the network claims:'), 1, 0) gridLayout.addWidget(self.labelType, 1, 1) gridLayout.addWidget(QLabel('Threshold:'), 2, 0) gridLayout.addWidget(self.spinBoxThreshold, 2, 1) self.groupBox.setLayout(gridLayout) self.groupBox.setVisible(False) vBoxLayout = QVBoxLayout() vBoxLayout.addLayout(hBoxLayout1) vBoxLayout.addWidget(self.tableWidget) vBoxLayout.addLayout(hBoxLayout2) vBoxLayout.addWidget(self.groupBox) self.setLayout(vBoxLayout) self.setWindowTitle('Simple linear neural network (example2)') self.classNames = ['mammal', 'bird', 'fish'] self.tableWidget.setColumnCount(5) self.tableWidget.setRowCount(6) self.tableWidget.verticalHeader().hide() self.tableWidget.setHorizontalHeaderLabels(['Feature'] + self.classNames + ['Input vector']) self.tableWidget.setCellWidget(0, 0, QLabel('number of legs')) self.tableWidget.setCellWidget(1, 0, QLabel('lives in water')) self.tableWidget.setCellWidget(2, 0, QLabel('can fly')) self.tableWidget.setCellWidget(3, 0, QLabel('has feathers')) self.tableWidget.setCellWidget(4, 0, QLabel('egg-laying')) self.tableWidget.setCellWidget(5, 0, QLabel('Output')) weights = [ [ 4, 0.01, 0.01, -1, -1.5 ], [ 2, -1, 2, 2.5, 2 ], [ -1, 3.5, 0.01, -2, 1.5 ] ] for i in xrange(len(weights)): for j in xrange(len(weights[i])): self.tableWidget.setCellWidget(j, i + 1, QLabel(' ' + str(weights[i][j]))) for i in xrange(len(weights)): self.tableWidget.setCellWidget(5, i + 1, QLabel('')) for i in xrange(len(weights[0])): doubleSpinBox = QDoubleSpinBox() doubleSpinBox.setValue(0.0) doubleSpinBox.setRange(-15.0, 15.0) self.tableWidget.setCellWidget(i, 4, doubleSpinBox) self.tableWidget.setCellWidget(5, 4, QPushButton('Calculate')) self.linearNetwork = LinearNetwork(initialWeights=weights) self.connect(self.checkBoxWinner, SIGNAL('stateChanged(int)'), self.visibleGrid) self.connect(self.tableWidget.cellWidget(5, 4), SIGNAL('clicked()'), self.updateResult) self.resize(600, 400) def visibleGrid(self, state): if state == 0: self.groupBox.setVisible(False) else: self.groupBox.setVisible(True) self.updateResult() def updateResult(self): inputColumn0 = self.tableWidget.cellWidget(0, 4).value() # number of legs inputColumn1 = self.tableWidget.cellWidget(1, 4).value() # lives in water inputColumn2 = self.tableWidget.cellWidget(2, 4).value() # can fly inputColumn3 = self.tableWidget.cellWidget(3, 4).value() # has feathers inputColumn4 = self.tableWidget.cellWidget(4, 4).value() # egg-laying outputVector = self.linearNetwork.response([inputColumn0, inputColumn1, inputColumn2, inputColumn3, inputColumn4]) if self.checkBoxWinner.checkState() == Qt.Checked: winner = LinearNetwork.winner(outputVector, self.spinBoxThreshold.value()) for i in xrange(len(outputVector)): self.tableWidget.setCellWidget(5, i + 1, QLabel()) if winner != -1: cellWinner = self.tableWidget.cellWidget(5, winner + 1) cellWinner.setStyleSheet('background-color: red;') self.labelNeuron.setText('Neuron ' + str(winner + 1)) self.labelType.setText('This is a ' + self.classNames[winner]) else: self.labelNeuron.setText('(There is no winner.)') self.labelType.setText('Thiss is something strange!') for i in xrange(len(outputVector)): self.tableWidget.cellWidget(5, i + 1).setText(str(outputVector[i]))
class Main(plugin.Plugin): " Main Class " def initialize(self, *args, **kwargs): " Init Main Class " super(Main, self).initialize(*args, **kwargs) self.locator.get_service("menuApp").add_action(QAction(QIcon.fromTheme( "edit-select-all"), __doc__, self, triggered=lambda: self.get_dialog())) self.dialog, self.group0 = QDialog(), QGroupBox() self.group0.setTitle('Coviolations') self.pep8 = QCheckBox('PEP-8 Style Guide for Python Code') self.sloc = QCheckBox('Sloccount Source Code Lines counter') self.unit = QCheckBox('UnitTest Python Unit Tests') self.pipr = QCheckBox('PIP-Review PIP Packages Review') self.tstm = QCheckBox('Testem JavaScript Tests') self.cove = QCheckBox('Coverage Code Tests Coverage report') self.jsli = QCheckBox('JSLint JavaScript Linter') self.metada = QCheckBox('Add Date and Time on a Comment') self.button = QPushButton('Generate YML Files !') self.button.setMinimumSize(400, 50) self.button.clicked.connect(self.make_yml) glow = QGraphicsDropShadowEffect(self) glow.setOffset(0) glow.setBlurRadius(99) glow.setColor(QColor(99, 255, 255)) self.button.setGraphicsEffect(glow) help1 = QLabel('''<a href="https://coviolations.io"><center> GitHub Login to Coviolations Libre C.I.</a>''') help1.setTextInteractionFlags(Qt.LinksAccessibleByMouse) help1.setOpenExternalLinks(True) help1.setMaximumSize(400, 50) vboxg0 = QVBoxLayout(self.group0) for each_widget in (self.pep8, self.sloc, self.unit, self.pipr, self.tstm, self.cove, self.jsli, help1): vboxg0.addWidget(each_widget) each_widget.setToolTip(each_widget.text()) self.group1, self.group2 = QGroupBox(), QGroupBox() self.group1.setTitle('Travis') self.group2.setTitle('Travis') self.py25 = QCheckBox('Python 2.5 (Deprecated)') self.py26 = QCheckBox('Python 2.6 (Deprecated)') self.py27 = QCheckBox('Python 2.7 (Default)') self.py32, self.py33 = QCheckBox('Python 3.2'), QCheckBox('Python 3.3') self.pypy = QCheckBox('Python PyPy (Experimental)') self.cach = QCheckBox('Use Network-Local APT Cache for faster apt-get') self.mong, self.couc = QCheckBox('Mongo DB'), QCheckBox('Couch DB') self.elas, self.kres = QCheckBox('ElasticSearch'), QCheckBox('Kestrel') self.memc, self.rabb = QCheckBox('MemCacheD'), QCheckBox('RabbitMQ') self.redi, self.cass = QCheckBox('Redis'), QCheckBox('Cassandra') self.riak, self.neo4 = QCheckBox('Riak'), QCheckBox('Neo4J') [a.setChecked(True) for a in(self.pep8, self.sloc, self.unit, self.pipr, self.tstm, self.cove, self.jsli, self.metada, self.py27, self.cach)] self.b4in, self.container = QLineEdit(B4INSTL), QWidget() self.inst = QLineEdit('pip install -r requirements.txt --use-mirrors') self.b4sc = QLineEdit('rm --recursive --force --verbose *.pyc') self.scrp = QLineEdit('nosetests --verbose --detailed-errors') self.sucs, self.when = QLineEdit('covio'), QComboBox() self.when.addItems(['change', 'always', 'never']) self.mail = QLineEdit(getuser() + '@gmail.com') self.ircc = QLineEdit(getuser() + 's_channel') self.host = QLineEdit(getuser() + '-dev-server.com') help2 = QLabel('''<a href="https://travis-ci.org"><center> GitHub Login to Travis Libre C.I.</a>''') help2.setTextInteractionFlags(Qt.LinksAccessibleByMouse) help2.setOpenExternalLinks(True) help3 = QLabel('''<a href="http://lint.travis-ci.org/"><center> Travis Lint .travis.yml Config Validator</a>''') help3.setTextInteractionFlags(Qt.LinksAccessibleByMouse) help3.setOpenExternalLinks(True) vboxg1 = QVBoxLayout(self.group1) for each_widget in (QLabel('<b>Try to Build / Run / Test my App on'), self.py25, self.py26, self.py27, self.py32, self.py33, self.pypy, QLabel('<b>Bash command to run Before install your App'), self.b4in, QLabel('<b>Bash command to Install your App'), self.inst, QLabel('<b>Bash command to run Before C.I. process'), self.b4sc, QLabel('<b>Bash command to Build / Run / Test your App'), self.scrp, QLabel('<b>Bash command to run on Sucess of your App'), self.sucs, help2): vboxg1.addWidget(each_widget) vboxg2 = QVBoxLayout(self.group2) for each_widget in (QLabel('<b>Servers to Start on Boot'), self.mong, self.couc, self.elas, self.kres, self.memc, self.rabb, self.redi, self.cass, self.riak, self.neo4, QLabel('<b>Mail to send C.I. Notifications of your App'), self.mail, QLabel('<b>IRC to send C.I. Notifications of your App'), self.ircc, QLabel('<b>When to Send Notifications'), self.when, QLabel('<b>Custom Hostname DNS /etc/hosts for IPv4/6'), self.host, QLabel('<b>Cache'), self.cach, help3): vboxg2.addWidget(each_widget) hboxg, vboxg = QHBoxLayout(self.container), QVBoxLayout(self.dialog) [hboxg.addWidget(a) for a in (self.group1, self.group2, self.group0)] for each_widget in (QLabel('<center><h3>' + __doc__), self.container, self.metada, self.button): vboxg.addWidget(each_widget) QPushButton(QIcon.fromTheme("help-about"), 'About', self.dialog ).clicked.connect(lambda: QMessageBox.information(self.dialog, __doc__, HELPMSG)) def get_dialog(self): ' show dialog auto fill data ' self.dialog.show() def make_yml(self): ' create setup.py file ' cov = str('\n'.join(( '# {} by {} .covio.yml Continuous Integration by Ninja-IDE'.format(datetime.now().isoformat().split('.')[0], getuser()) if self.metada.isChecked() is True else '', 'violations:', ' pep8: pep8 . --exclude="*migrations*,*settings*,*components*,*docs*"' if self.pep8.isChecked() is True else '', ' sloccount: sloccount .' if self.sloc.isChecked() is True else '', ' py_unittest: cat test_result' if self.unit.isChecked() is True else '', ' coverage: coverage report' if self.cove.isChecked() is True else '', ' pip_review:' if self.pipr.isChecked() is True else '', ' command: pip-review' if self.pipr.isChecked() is True else '', ' nofail: true' if self.pipr.isChecked() is True else '', ' testem: cat test_result' if self.tstm.isChecked() is True else '', ' jslint: jslint *.js' if self.jsli.isChecked() is True else '', ))).strip() tra = str('\n'.join(( '# {} by {} .travis.yml Continuous Integration by Ninja-IDE'.format(datetime.now().isoformat().split('.')[0], getuser()) if self.metada.isChecked() is True else '', 'language: python', 'python:', ' - 2.5' if self.py25.isChecked() is True else '', ' - 2.6' if self.py26.isChecked() is True else '', ' - 2.7' if self.py27.isChecked() is True else '', ' - 3.2' if self.py32.isChecked() is True else '', ' - 3.3' if self.py33.isChecked() is True else '', ' - pypy' if self.pypy.isChecked() is True else '', 'before_install: {}'.format(self.b4in.text()), 'install: {}'.format(self.inst.text()), 'before_script: {}'.format(self.b4sc.text()), 'script: {}'.format(self.scrp.text()), 'after_script: coverage report' if self.cove.isChecked() is True else '', 'after_success: {}'.format(self.sucs.text()), '# after_failure: {} # runs when failed'.format(self.sucs.text()), 'notifications:', ' irc:', ' channels: "irc.freenode.org#{}"'.format(self.ircc.text()), ' template:', ' - "%{repository}@%{branch}: %{message}(%{build_url})"', ' - "GitHub Repo URL: %{repository}"', ' - "Build Number: %{build_number}"', ' - "Branch Name: %{branch}"', ' - "Shortened SHA: %{commit}"', ' - "Commit Author: %{author}"', ' - "Diff View URL: %{compare_url}"', ' - "Build Detail: %{build_url}"', ' - "Travis Message: %{message}"', ' - "Travis Job Number: ${TRAVIS_JOB_NUMBER}"', ' - "Travis Build Dir: ${TRAVIS_BUILD_DIR}"', ' - "Travis Build Number: ${TRAVIS_BUILD_NUMBER}"', ' - "Travis Python Version: ${TRAVIS_PYTHON_VERSION}"', ' on_success: {}'.format(self.when.currentText()), ' on_failure: {}'.format(self.when.currentText()), ' use_notice: true # false to disable', ' email:', ' recipients: {}'.format(self.mail.text()), ' template:', ' - "%{repository}@%{branch}: %{message}(%{build_url})"', ' - "GitHub Repo URL: %{repository}"', ' - "Build Number: %{build_number}"', ' - "Branch Name: %{branch}"', ' - "Shortened SHA: %{commit}"', ' - "Commit Author: %{author}"', ' - "Diff View URL: %{compare_url}"', ' - "Build Detail: %{build_url}"', ' - "Travis Message: %{message}"', ' - "Travis Job Number: ${TRAVIS_JOB_NUMBER}"', ' - "Travis Build Dir: ${TRAVIS_BUILD_DIR}"', ' - "Travis Build Number: ${TRAVIS_BUILD_NUMBER}"', ' - "Travis Python Version: ${TRAVIS_PYTHON_VERSION}"', ' on_success: {}'.format(self.when.currentText()), ' on_failure: {}'.format(self.when.currentText()), 'cache: apt' if self.cach.isChecked() is True else '', 'addons:', ' hosts: {}'.format(self.host.text()), 'services:' if any((self.mong.checkState(), self.couc.checkState(), self.elas.checkState(), self.kres.checkState(), self.memc.checkState(), self.rabb.checkState(), self.redi.checkState(), self.cass.checkState(), self.riak.checkState(), self.neo4.checkState())) else '', ' - mongodb' if self.mong.isChecked() is True else '', ' - couchdb' if self.couc.isChecked() is True else '', ' - elasticsearch' if self.elas.isChecked() is True else '', ' - memcached' if self.memc.isChecked() is True else '', ' - rabbitmq' if self.rabb.isChecked() is True else '', ' - redis-server' if self.redi.isChecked() is True else '', ' - cassandra' if self.cass.isChecked() is True else '', ' - riak' if self.riak.isChecked() is True else '', ' - neo4j' if self.neo4.isChecked() is True else '', ' - kestrel' if self.kres.isChecked() is True else '', ))).strip() self.locator.get_service("editor").add_editor(content=cov, syntax='yml') self.locator.get_service("editor").add_editor(content=tra, syntax='yml') self.dialog.hide()