class AdvancedVisualizationForm(QWidget):
    def __init__(self, mainwindow, result_manager):
        QWidget.__init__(self, mainwindow)
        #mainwindow is an OpusGui
        self.mainwindow = mainwindow
        self.result_manager = result_manager
        self.toolboxBase = self.result_manager.mainwindow.toolboxBase

        self.inGui = False
        self.logFileKey = 0

        self.xml_helper = ResultsManagerXMLHelper(toolboxBase=self.toolboxBase)
        self.result_generator = OpusResultGenerator(
            toolboxBase=self.toolboxBase)

        self.result_generator.guiElement = self

        self.tabIcon = QIcon(':/Images/Images/cog.png')
        self.tabLabel = 'Advanced Visualization'

        self.widgetLayout = QVBoxLayout(self)
        self.widgetLayout.setAlignment(Qt.AlignTop)

        self.resultsGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.resultsGroupBox)

        self.dataGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.dataGroupBox)

        self.optionsGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.optionsGroupBox)

        self._setup_definition_widget()

        self._setup_buttons()
        self._setup_tabs()

    def _setup_buttons(self):
        # Add Generate button...
        self.pbn_go = QPushButton(self.resultsGroupBox)
        self.pbn_go.setObjectName('pbn_go')
        self.pbn_go.setText(QString('Go!'))

        QObject.connect(self.pbn_go, SIGNAL('released()'),
                        self.on_pbn_go_released)
        self.widgetLayout.addWidget(self.pbn_go)

        self.pbn_set_esri_storage_location = QPushButton(self.optionsGroupBox)
        self.pbn_set_esri_storage_location.setObjectName(
            'pbn_set_esri_storage_location')
        self.pbn_set_esri_storage_location.setText(QString('...'))
        self.pbn_set_esri_storage_location.hide()

        QObject.connect(self.pbn_set_esri_storage_location,
                        SIGNAL('released()'),
                        self.on_pbn_set_esri_storage_location_released)

    def _setup_tabs(self):
        # Add a tab widget and layer in a tree view and log panel
        self.tabWidget = QTabWidget(self.resultsGroupBox)

        # Log panel
        self.logText = QTextEdit(self.resultsGroupBox)
        self.logText.setReadOnly(True)
        self.logText.setLineWidth(0)
        self.tabWidget.addTab(self.logText, 'Log')

        # Finally add the tab to the model page
        self.widgetLayout.addWidget(self.tabWidget)

#

    def _setup_definition_widget(self):

        #### setup results group box ####

        self.gridlayout = QGridLayout(self.resultsGroupBox)
        self.gridlayout.setObjectName('gridlayout')

        self.lbl_results = QLabel(self.resultsGroupBox)
        self.lbl_results.setObjectName('lbl_results')
        self.lbl_results.setText(QString('Results'))
        self.gridlayout.addWidget(self.lbl_results, 0, 0, 1, 3)

        self._setup_co_results()
        self.gridlayout.addWidget(self.co_results, 0, 3, 1, 10)

        self.pbn_add = QPushButton(self.resultsGroupBox)
        self.pbn_add.setObjectName('pbn_add')
        self.pbn_add.setText(QString('+'))

        QObject.connect(self.pbn_add, SIGNAL('released()'),
                        self.on_pbn_add_released)
        self.gridlayout.addWidget(self.pbn_add, 0, 14, 1, 1)

        self.lw_indicators = QListWidget(self.resultsGroupBox)
        self.lw_indicators.setObjectName('lw_indicators')
        self.gridlayout.addWidget(self.lw_indicators, 1, 1, 1, 13)

        self.pbn_remove = QPushButton(self.resultsGroupBox)
        self.pbn_remove.setObjectName('pbn_remove')
        self.pbn_remove.setText(QString('-'))

        QObject.connect(self.pbn_remove, SIGNAL('released()'),
                        self.on_pbn_remove_released)
        self.gridlayout.addWidget(self.pbn_remove, 1, 14, 1, 1)

        #### setup data group box ####

        self.gridlayout2 = QGridLayout(self.dataGroupBox)
        self.gridlayout2.setObjectName('gridlayout2')

        self._setup_co_result_style()
        self.gridlayout2.addWidget(self.co_result_style, 1, 0, 1, 2)

        self.lbl_result_style_sep = QLabel(self.resultsGroupBox)
        self.lbl_result_style_sep.setObjectName('lbl_result_style_sep')
        self.lbl_result_style_sep.setText(QString('<center>as</center>'))
        self.gridlayout2.addWidget(self.lbl_result_style_sep, 1, 2, 1, 1)

        self._setup_co_result_type()
        self.gridlayout2.addWidget(self.co_result_type, 1, 3, 1, 2)

        ##### setup options group box ####

        self.gridlayout3 = QGridLayout(self.optionsGroupBox)
        self.gridlayout3.setObjectName('gridlayout3')

        self.le_esri_storage_location = QLineEdit(self.optionsGroupBox)
        self.le_esri_storage_location.setObjectName('le_esri_storage_location')
        self.le_esri_storage_location.setText('[set path]')
        self.le_esri_storage_location.hide()
        self.optionsGroupBox.hide()

        QObject.connect(self.co_result_style,
                        SIGNAL('currentIndexChanged(int)'),
                        self.on_co_result_style_changed)
        QObject.connect(self.co_result_type,
                        SIGNAL('currentIndexChanged(int)'),
                        self.on_co_result_type_changed)

    def _setup_co_results(self):

        self.co_results = QComboBox(self.resultsGroupBox)
        self.co_results.setObjectName('co_results')
        self.co_results.addItem(QString('[select]'))

        results = self.xml_helper.get_available_results()

        for result in results:
            name = '%i.%s' % (result['run_id'], result['indicator_name'])
            self.co_results.addItem(QString(name))

    def _setup_co_result_style(self):
        available_styles = [
            'visualize',
            'export',
        ]
        self.co_result_style = QComboBox(self.dataGroupBox)
        self.co_result_style.setObjectName('co_result_style')

        for dataset in available_styles:
            self.co_result_style.addItem(QString(dataset))

    def _setup_co_result_type(self):
        available_types = [
            'Table (per year, spans indicators)',
            'Chart (per indicator, spans years)',
            'Map (per indicator per year)',
            'Chart (per indicator, spans years)',
        ]

        self.co_result_type = QComboBox(self.dataGroupBox)
        self.co_result_type.setObjectName('co_result_type')

        for dataset in available_types:
            self.co_result_type.addItem(QString(dataset))

    def on_pbnRemoveModel_released(self):
        self.result_manager.removeTab(self)
        self.result_manager.updateGuiElements()

    def on_pbn_add_released(self):
        cur_selected = self.co_results.currentText()
        for i in range(self.lw_indicators.count()):
            if self.lw_indicators.item(i).text() == cur_selected:
                return

        self.lw_indicators.addItem(cur_selected)

    def on_pbn_remove_released(self):
        selected_idxs = self.lw_indicators.selectedIndexes()
        for idx in selected_idxs:
            self.lw_indicators.takeItem(idx.row())

    def on_co_result_style_changed(self, ind):
        available_viz_types = [
            'Table (per year, spans indicators)',
            'Chart (per indicator, spans years)',
            'Map (per indicator per year)',
            'Chart (per indicator, spans years)',
        ]

        available_export_types = ['ESRI table (for loading in ArcGIS)']

        txt = self.co_result_style.currentText()
        if txt == 'visualize':
            available_types = available_viz_types
        else:
            available_types = available_export_types

        self.co_result_type.clear()
        for result_type in available_types:
            r_type = QString(result_type)
            self.co_result_type.addItem(r_type)

    def on_co_result_type_changed(self, ind):
        self.gridlayout3.removeWidget(self.le_esri_storage_location)
        self.gridlayout3.removeWidget(self.pbn_set_esri_storage_location)
        self.optionsGroupBox.hide()

        self.pbn_set_esri_storage_location.hide()
        self.le_esri_storage_location.hide()

        txt = self.co_result_type.currentText()

        print txt
        if txt == 'ESRI table (for loading in ArcGIS)':
            self.pbn_set_esri_storage_location.show()
            self.le_esri_storage_location.show()
            self.gridlayout3.addWidget(self.le_esri_storage_location, 0, 1, 1,
                                       6)
            self.gridlayout3.addWidget(self.pbn_set_esri_storage_location, 0,
                                       7, 1, 1)
            self.optionsGroupBox.show()

    def on_pbn_set_esri_storage_location_released(self):
        print 'pbn_set_esri_storage_location released'
        from opus_core.misc import directory_path_from_opus_path
        start_dir = directory_path_from_opus_path('opus_gui.projects')

        configDialog = QFileDialog()
        filter_str = QString("*.gdb")
        fd = configDialog.getExistingDirectory(
            self,
            QString("Please select an ESRI geodatabase (*.gdb)..."
                    ),  #, *.sde, *.mdb)..."),
            QString(start_dir),
            QFileDialog.ShowDirsOnly)
        if len(fd) != 0:
            fileName = QString(fd)
            fileNameInfo = QFileInfo(QString(fd))
            fileNameBaseName = fileNameInfo.completeBaseName()
            self.le_esri_storage_location.setText(fileName)

    def on_pbn_go_released(self):
        # Fire up a new thread and run the model
        print 'Go button pressed'

        # References to the GUI elements for status for this run...
        #self.statusLabel = self.runStatusLabel
        #self.statusLabel.setText(QString('Model initializing...'))

        indicator_names = []
        for i in range(self.lw_indicators.count()):
            indicator_names.append(str(self.lw_indicators.item(i).text()))

        if indicator_names == []:
            print 'no indicators selected'
            return

        indicator_type = str(self.co_result_type.currentText())
        indicator_type = {
            #'Map (per indicator per year)':'matplotlib_map',
            'Map (per indicator per year)': 'mapnik_map',
            'Chart (per indicator, spans years)': 'matplotlib_chart',
            'Table (per indicator, spans years)': 'table_per_attribute',
            'Table (per year, spans indicators)': 'table_per_year',
            'ESRI table (for loading in ArcGIS)': 'table_esri'
        }[indicator_type]

        kwargs = {}
        if indicator_type == 'table_esri':
            storage_location = str(self.le_esri_storage_location.text())
            if not os.path.exists(storage_location):
                print 'Warning: %s does not exist!!' % storage_location
            kwargs['storage_location'] = storage_location

        self.result_manager.addIndicatorForm(indicator_type=indicator_type,
                                             indicator_names=indicator_names,
                                             kwargs=kwargs)

    def runUpdateLog(self):
        self.logFileKey = self.result_generator._get_current_log(
            self.logFileKey)

    def runErrorFromThread(self, errorMessage):
        QMessageBox.warning(self.mainwindow, 'Warning', errorMessage)
示例#2
0
文件: mplayer.py 项目: Ptaah/Ekd
class Mplayer(QDialog):

	REVENIR, PAS_PRECEDENT_SUIVANT, PRECEDENT_SUIVANT, CURSEUR_SUR_UNE_LIGNE,\
		CURSEUR_A_PART, PARCOURIR, PAS_PARCOURIR, LIST, RATIO = range(9)

	HAUTEUR, LARGEUR = range(2)

	def __init__(self, cheminVideo=[], taille=(250,225),
			choixWidget=(RATIO, REVENIR, PAS_PRECEDENT_SUIVANT,CURSEUR_SUR_UNE_LIGNE,PAS_PARCOURIR,LIST),
			debutFin=(0,0), cheminMPlayer=None, barreTaches=None, facteurLimitant=HAUTEUR,
			cheminParcourir=None, parent=None):

		"""widget mplayer"""
		QDialog.__init__(self, parent)

		#=== Paramètres généraux ===#
		self.setAttribute(Qt.WA_DeleteOnClose)
		self.setWindowTitle(_(u"Player vidéo"))
                #On réduit la marge pour gagner de l'espace
                self.setContentsMargins(0,0,0,0)

		self.systeme = os.name
                ### Quand EKD windows est installé, le chemin des dépendances sont ###########
                ### positionnées dans les variables d'environnement donc pas besoin de #######
                ### collecter le chemin des ces dépendances ##################################
                self.cheminMPlayer = "mplayer"

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

		# liste de chemins vidéos
		if type(cheminVideo) != list :
			self.listeVideos=[cheminVideo]
		else :
			self.listeVideos = cheminVideo

		# est-ce que la vidéo est lue?
		self.estLue=False

		# est-ce que la vidéo est en pause?
		self.estEnPause=False

		self.debutFin = debutFin

		# Nom du fichier courant (le self n'est pas encore utile)
		txtParDefaut = u"Pas de fichier lu"
		if self.listeVideos.__len__()!=0:
			self.fichierCourant =  [txtParDefaut, self.listeVideos[0]]
		else: self.fichierCourant = [txtParDefaut, ""]

		# Barre des tâches de la fenêtre
		self.barreTaches = barreTaches

		# Taille de la vidéo
		self.tailleLargeur=taille[0]
		self.tailleHauteur=taille[1]

		# paramètres des boutons-icones
		iconTaille=22
		flat=1

		# Pour récupérer le temps courant depuis certains cadre
		self.temps = 0

		self.dureeTimer = 10 # temps en ms
		###############################################################################################################################

		#Pour être plus précis lors de la lecture, on prend comme unité la miliseconde. ######################
		## Il faut donc utiliser une echelle 1000 fois plus grande pour les unités du slider
		self.echelle=1000
		###############################################################################################################################

		# Permet de récupérer la durée de la vidéo depuis une instance de la classe
		# Sert dans certains cadres
		self.dureeVideo = 0

		# Chemin sur lequel peut s'ouvrir la boite de dialogue de fichier
		# associée au bouton parcourir
		self.cheminPourBoutonParcourir = cheminParcourir

		self.taille = taille

		debug("self.taille avant lecture : %s %s" % (self.taille, type(self.taille)))

		#=== Widgets ===#

		self.icone_lire=QIcon("Icones" + os.sep + "player_play.png")
		self.icone_pause=QIcon("Icones" + os.sep + "player_pause.png")
		self.icone_arret=QIcon("Icones" + os.sep + "player_stop.png")

		if Mplayer.REVENIR in choixWidget:
			self.bout_revenir = QPushButton(u"Revenir")
			self.bout_revenir.setIcon(QIcon("Icones" + os.sep + "revenir.png"))

		if Mplayer.PARCOURIR in choixWidget:
			self.bout_ouvVideo = QPushButton(u"Parcourir...")

		if Mplayer.PRECEDENT_SUIVANT in choixWidget:
			self.bout_prec = QPushButton(QIcon("Icones" + os.sep + "player_rew.png"),"")
			self.bout_prec.setIconSize(QSize(iconTaille, iconTaille))
			self.bout_prec.setFlat(flat)
			self.bout_suivant = QPushButton(QIcon("Icones" + os.sep + "player_fwd.png"),"")
			self.bout_suivant.setIconSize(QSize(iconTaille, iconTaille))
			self.bout_suivant.setFlat(flat)

		self.LISTW=False
		if Mplayer.LIST in choixWidget :
			self.LISTW = True
			self.listFichiers = QComboBox()
			self.listFichiers.hide()
			self.setListeVideo()


		self.bout_LectPause = QPushButton(self.icone_lire,"")
		self.bout_LectPause.setIconSize(QSize(iconTaille, iconTaille))
		self.bout_LectPause.setFlat(flat)

		self.bout_Arret = QPushButton(self.icone_arret,"")
		self.bout_Arret.setIconSize(QSize(iconTaille, iconTaille))
		self.bout_Arret.setFlat(flat)

		# widget qui contiendra la vidéo
		self.cibleVideo = DisplayVid(self)
		# par défaut le widget-cible est noir
		color = QColor(0, 0, 0)
		self.cibleVideo.setAutoFillBackground(True)
		self.cibleVideo.setPalette(QPalette(color))
		self.cibleVideo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
		self.cibleVideo.setFixedHeight(self.taille[1])
		self.cibleVideo.setToolTip(self.fichierCourant[0])

		#Choix de l'aspect ratio de la vidéo
                if Mplayer.RATIO in choixWidget :
                    self.conf = QGroupBox()
                    self.conf.setContentsMargins(0,0,0,0)
                    self.conf.setMinimumSize(QSize(self.tailleLargeur, 0))
                    self.conf.setObjectName("conf")
                    self.verticalLayout = QHBoxLayout(self.conf)
                    self.verticalLayout.setObjectName("verticalLayout")
                    self.choicenorm = QRadioButton(self.conf)
                    self.choicenorm.setObjectName("choicenorm")
                    self.verticalLayout.addWidget(self.choicenorm)
                    self.choicewide = QRadioButton(self.conf)
                    self.choicewide.setObjectName("choicewide")
                    self.verticalLayout.addWidget(self.choicewide)
                    self.choiceone = QRadioButton(self.conf)
                    self.choiceone.setObjectName("choiceone")
                    self.verticalLayout.addWidget(self.choiceone)
                    self.choicenorm.setText("4:3")
                    self.choicewide.setText("16:9")
                    self.choiceone.setText("w:h")
                # Checked le ratio de la vidéo
                if self.listeVideos.__len__()!=0:
                        self.changeRatio(self.listeVideos[0])
                else :
                        self.setRatio(4.0/3.0)
                        if Mplayer.RATIO in choixWidget :
                            self.choicenorm.setChecked(True)

		self.slider = QSlider(Qt.Horizontal)
		self.slider.setEnabled(True)

		self.mplayerProcess = QProcess(self)

		self.timer = QTimer(self)

		self.tempsChrono = TracerChrono()

		#=== mise-en-page/plan ===#
		mhbox = QHBoxLayout()
		vbox = QVBoxLayout()
		vbox.addWidget(self.cibleVideo)
                if Mplayer.RATIO in choixWidget :
                    vbox.addWidget(self.conf)
		hbox = QHBoxLayout()
		if Mplayer.REVENIR in choixWidget:
			hbox.addWidget(self.bout_revenir)
		if Mplayer.PARCOURIR in choixWidget:
			hbox.addWidget(self.bout_ouvVideo)
		hbox.addWidget(self.bout_LectPause)
		hbox.addWidget(self.bout_Arret)
		if Mplayer.PRECEDENT_SUIVANT in choixWidget:
			hbox.addWidget(self.bout_prec)
			hbox.addWidget(self.bout_suivant)
		hbox.addWidget(self.tempsChrono)
		if Mplayer.CURSEUR_A_PART not in choixWidget:
			hbox.addWidget(self.slider)
		vbox.addLayout(hbox)
		if Mplayer.CURSEUR_A_PART in choixWidget:
			hbox.setAlignment(Qt.AlignLeft)
			hbox = QHBoxLayout()
			hbox.addWidget(self.slider)
			vbox.addLayout(hbox)
		# Liste fichier dans combobox
		if self.LISTW :
			hbox = QHBoxLayout()
			hbox.addWidget(self.listFichiers)
			vbox.addLayout(hbox)

		mhbox.addLayout(vbox)
		self.setLayout(mhbox)

		#=== connexion des widgets à des fonctions ===#

		if Mplayer.REVENIR in choixWidget:
			self.connect(self.bout_revenir, SIGNAL('clicked()'), SLOT('close()'))
		if Mplayer.PARCOURIR in choixWidget:
			self.connect(self.bout_ouvVideo, SIGNAL('clicked()'), self.ouvrirVideo)
		if Mplayer.PRECEDENT_SUIVANT in choixWidget:
			self.connect(self.bout_prec, SIGNAL('clicked()'), self.precedent)
			self.connect(self.bout_suivant, SIGNAL('clicked()'), self.suivant)
		#Ajouté le 08/11/2009 - Liste des fichiers dans une combobox
		if self.LISTW :
			self.connect(self.listFichiers, SIGNAL('currentIndexChanged(int)'), self.changeVideo)
		self.connect(self.bout_LectPause, SIGNAL('clicked()'), self.lectPause)
		self.connect(self.bout_Arret, SIGNAL('clicked()'), self.arretMPlayer)
		self.connect(self.mplayerProcess, SIGNAL('readyReadStandardOutput()'), self.recupSortie)
		self.connect(self.mplayerProcess, SIGNAL('finished(int,QProcess::ExitStatus)'), self.finVideo)
		self.connect(self.timer, SIGNAL('timeout()'), self.sonderTempsActuel)
		self.connect(self.slider, SIGNAL('sliderMoved(int)'), self.changerTempsCurseur)
		self.connect(self.cibleVideo, SIGNAL('changeSize'), self.sizeMplayer)
                if Mplayer.RATIO in choixWidget :
                    self.connect(self.choicenorm, SIGNAL("clicked(bool)"), self.defRatio)
                    self.connect(self.choicewide, SIGNAL("clicked(bool)"), self.defRatio)
                    self.connect(self.choiceone, SIGNAL("clicked(bool)"), self.defRatio)

	def setListeVideo(self) :
		self.referenceVideo = []
		self.listFichiers.clear()
		for vid in self.listeVideos :
			self.referenceVideo.append(vid)
			self.listFichiers.addItem(os.path.basename(vid))
		if self.listeVideos.__len__() > 1 :
			self.listFichiers.show()

	def setAudio(self,au) :
		if au :
			self.cibleVideo.hide()
                        if "conf" in self.__dict__ :
			    self.conf.hide()
		else :
			self.cibleVideo.show()
                        if "conf" in self.__dict__ :
                            self.conf.show()
	def changeVideo(self, index) :
		self.arretMPlayer()
		if index >= 0 : # Condition ajoutée pour éviter une erreure de dépassement de range dans la liste.
			self.listeVideos = self.referenceVideo[index]
			self.listFichiers.setCurrentIndex(index)

	def defRatio(self, state=0) :
		if state :
			if self.choicenorm.isChecked() :
				self.setRatio(4.0/3.0)
			if self.choicewide.isChecked() :
				self.setRatio(16.0/9.0)
			if self.choiceone.isChecked() :
				try :
					dim=getVideoSize(unicode(self.listeVideos[0]))
					self.setRatio(dim[0]/dim[1])
				except :
					None
			self.defRatio()
		else :
			self.adjustSize()

	def setRatio(self,ratio) :
		self.ratio = ratio
		self.sizeMplayer()

	def changeRatio(self,video) :
		rv = getVideoRatio(video)
		if rv[0]==0.0 and type(rv[1])==float :
			rat = rv[1]
		else :
			rat = rv[0]

		if rat > 1.7 :
                        if "choicewide" in self.__dict__ :
                            self.choicewide.setChecked(True)
			self.setRatio(16.0/9.0)
		elif rat > 1.3 and rat <= 1.7 :
                        if "choicenorm" in self.__dict__ :
                            self.choicenorm.setChecked(True)
			self.setRatio(4.0/3.0)
		elif rat < 1.3 and rat != 0.0 :
                        if "choiceone" in self.__dict__ :
                            self.choiceone.setChecked(True)
			dim=getVideoSize(video)
			self.setRatio(dim[0]/dim[1])
		else :
                        if "choicenorm" in self.__dict__ :
                            self.choicenorm.setChecked(True)
			self.setRatio(4.0/3.0)

	def sizeMplayer(self) :
		self.cibleVideo.setFixedHeight(int(self.cibleVideo.width()/self.ratio))

	def ouvrirVideo(self):
		"""Ouverture de la boîte de dialogue de fichiers"""
		txt = u"Fichiers vidéo"
		if self.cheminPourBoutonParcourir:
			chemin = self.cheminPourBoutonParcourir

		else:
			try:
				chemin = EkdConfig.get('general','video_input_path').decode("UTF8")
			except:
				chemin = os.path.expanduser('~')

		liste=QFileDialog.getOpenFileNames(None, u"Ouvrir", chemin, "%s (*.avi *.mpg *.mpeg *.mjpeg *.flv *.mp4 *.ogg *.vob *.mov *.wmv *.3gp *.h264)\n*" %txt)
		if not liste: return
		self.listeVideos = liste
		self.changeRatio(unicode(self.listeVideos[0]))

		chemin = unicode(self.listeVideos[0])
		EkdConfig.set('general','video_input_path',os.path.dirname(chemin).encode("UTF8"))

	def setVideos(self, videos) :
		'''Définie proprement la liste des vidéos à jouer'''
		if type(videos) != list :
			self.listeVideos = [videos]
		else :
			self.listeVideos = videos
		if self.LISTW and videos.__len__() > 1 :
			self.setListeVideo()
		elif self.LISTW :
			self.listFichiers.hide()

	def demarrerMPlayer(self):
		"""démarrage de mplayer avec les arguments choisis"""
		if self.estLue:
			return True

		args = QStringList()	# Liste Qt qui contiendra les options de mplayer
					# Ajout d'options à liste: args << "-option"

		# mplayer fonctionnera comme un terminal dans ce script
		args << "-slave"
		# on ne veut pas avoir des commentaires sans grand intérêt
		args << "-quiet"

		# Sous linux, aucun driver n'a été nécessaire et pas de manip pour Wid :)
		if self.systeme=='posix':
			# try - except?
			# la fenêtre de mplayer restera attaché à la fenêtre
			# wid prend en valeur le nombre identifiant le widget (celui qui contiendra la vidéo)
			args << "-wid" << QString.number(self.cibleVideo.winId()) # Objet QString car args est une liste de ch de caractères
			settings = QSettings()
			videoOutput = settings.value("vo", QVariant('')).toString()
			if videoOutput:
				args << '-vo' << videoOutput

		# Sous windows
		else:
			# reinterpret_cast<qlonglong> obligatoire, winId() ne se laissant pas convertir gentiment ;)
			args << "-wid" << self.cibleVideo.winId().__hex__()
			args << "-vo" << "directx:noaccel"
			#args << "-vo" << "gl" # alternative

		# chemin de la vidéo
		args << self.listeVideos

		if PYQT_VERSION_STR >= "4.1.0":
			# mode de canal: on fusionne le canal de sortie normal (stdout) et celui des erreurs (stderr)
			self.mplayerProcess.setProcessChannelMode(QProcess.MergedChannels)
		# démarrage de mplayer (en tenant compte des arguments définis ci-dessus)
		# comme un nouveau processus
		self.mplayerProcess.start(self.cheminMPlayer, args)
		# au cas où mplayer ne démarrerait pas au bout de 3 sec (ex. problème de codec)
		if not self.mplayerProcess.waitForStarted(3000):
			QMessageBox.critical(self, u"Avertissement", u"Bogue au lancement de la vidéo avec mplayer")
			return False

		# donne le temps toutes les x secondes
		self.timer.start(self.dureeTimer)

		self.estLue = True

		return True

	def recupSortie(self):
		"""récupère les lignes d'information émises par QProcess (mplayerProcess) et en tire les conséquences"""
		while self.mplayerProcess.canReadLine(): # renvoie True si une ligne complète peut être lue à partir du système
			# stocker l'ensemble des bits d'une ligne
			tampon=QByteArray(self.mplayerProcess.readLine()) # readline: lit une ligne ascii à partir du système

			# On vérifie si on a eu des réponses
			if tampon.startsWith("Playing"):
				# On récupère les infos de base ('$ mplayer -input cmdlist' pour avoir la liste complète - file:///usr/share/doc/mplayer-doc/tech/slave.txt.gz pour plus de détails)
				self.mplayerProcess.write("get_video_resolution\n") # récupère la résolution de la vidéo
				self.mplayerProcess.write("get_time_length\n")
				# Nouveau fichier chargé -> on récupère son nom
				ind = tampon.length() - 2 # suppression du '.' à la fin
				tampon.remove(ind,ind)
				tampon.remove(0, 8) # vire Playing
				tampon.replace(QByteArray("\n"), QByteArray(""))
				tampon.replace(QByteArray("\r"), QByteArray(""))
				try:
					# Tour de passe-passe pour ne pas avoir de problème d'accents

					# Condition pour détection windows
					if os.name == 'nt':
						self.fichierCourant[1]=unicode(QString(tampon))
					# Condition pour détection Linux ou MacOSX
					elif os.name in ['posix', 'mac']:
						self.fichierCourant[1]=unicode(QString(tampon)).encode("Latin1").decode("UTF8")
				except UnicodeEncodeError, e:
					debug(e)
					self.fichierCourant[1]="?"
				self.cibleVideo.setToolTip(self.fichierCourant[1])
				if self.barreTaches is not None:
					self.barreTaches.showMessage(self.fichierCourant[1])

			# réponse à get_video_resolution : ANS_VIDEO_RESOLUTION='<width> x <height>'
			if tampon.startsWith("ANS_VIDEO_RESOLUTION"): # retourne True si l'ensemble de bits démarre avec "..."
				debug("tampon : %s" % tampon) # ex. -> ANS_VIDEO_RESOLUTION='352 x 288'
				tampon.remove(0, 21) # suppression des 21 1er caract -> '352 x 288'
				tampon.replace(QByteArray("'"), QByteArray("")) # -> 352 x 288
				tampon.replace(QByteArray(" "), QByteArray("")) # -> 352x288
				tampon.replace(QByteArray("\n"), QByteArray("")) # -> 352x288 # retour chariot unix
				tampon.replace(QByteArray("\r"), QByteArray("")) # -> 352x288 # retour chariot windows
				#print "-----tampon.indexOf('x') :", tampon.indexOf('x'), type(tampon.indexOf('x'))
				sepIndex = tampon.indexOf('x') # récupère la position de 'x' # 3 <type 'int'>
				#print "-----tampon.left(sepIndex).toInt():", tampon.left(sepIndex).toInt(), type(tampon.left(sepIndex).toInt())
				resX = tampon.left(sepIndex).toInt()[0] # -> 352 # (352, True) <type 'tuple'>
				#print "-----tampon.mid(sepIndex+1).toInt() :", tampon.mid(sepIndex+1).toInt(), type(tampon.mid(sepIndex+1).toInt())
				resY = tampon.mid(sepIndex+1).toInt()[0] # -> 288 # (288, True) <type 'tuple'>

				# on définit les nouvelles dimensions de l'image du widget-mplayer.
				# try pour éviter les bogues sur les fichiers audio (sans dimension d'image)!!!
				#try:
				if resX!=0 or resY!=0:
					debug( "ratio : %s - %s" % (self.ratio, type(self.ratio)))
				else:
					debug("fichier audio")

			# réponse à get_time_length : ANS_LENGTH=xx.yy
			elif tampon.startsWith("ANS_LENGTH"):
				debug("tampon : %s" % tampon) # -> ANS_LENGTH=279.38
				tampon.remove(0, 11) # vire ANS_LENGTH=
				tampon.replace(QByteArray("'"), QByteArray(""))
				tampon.replace(QByteArray(" "), QByteArray(""))
				tampon.replace(QByteArray("\n"), QByteArray(""))
				tampon.replace(QByteArray("\r"), QByteArray("")) # -> 279.38
				#print "-----tampon.toFloat() :", tampon.toFloat(), type(tampon.toFloat())
				tempsMax = tampon.toFloat()[0] # (279.3800048828125, True) <type 'tuple'>
				self.dureeVideo = tempsMax
				## Modifié le 28/05/2009 : On augmente la précision du slider
				#self.slider.setMaximum(tempsMax) # déf du domaine de valeur du curseur
				self.slider.setMaximum(tempsMax*self.echelle)

				# ATTENTION J'AI COMMENTE CETTE LIGNE !!!
				#self.slider.setMaximum(tempsMax)

			# réponse à get_time_pos : ANS_TIME_POSITION=xx.y
			elif tampon.startsWith("ANS_TIME_POSITION"):
				#print "tampon :",tampon # -> ANS_TIME_POSITION=1.4 (temps courant)
				tampon.remove(0, 18) # vire ANS_TIME_POSITION=
				tampon.replace(QByteArray("'"), QByteArray(""))
				tampon.replace(QByteArray(" "), QByteArray(""))
				tampon.replace(QByteArray("\n"), QByteArray(""))
				tampon.replace(QByteArray("\r"), QByteArray(""))
				#print "-----tampon.toFloat() :", tampon.toFloat(), type(tampon.toFloat())
				tempsCourant = tampon.toFloat()[0] # (1.3999999761581421, True) <type 'tuple'>
				# récupération du temps courant: utile dans certains cadres
				self.temps = tempsCourant
				# Programmer un arrêt. Utile pour les aperçus
				temps = float("%.1f" %self.temps)
				if self.debutFin!=(0,0) and self.debutFin[1]==temps:
					self.arretMPlayer()
					return
				self.slider.setValue(tempsCourant*self.echelle)
				#############################################################################
				self.changerTempsChrono(tempsCourant) # modifier le chrono du bouton
示例#3
0
class WFramework(QWidget, Logger.ClassLogger):
    """
    Framework widget
    """
    # action, description, misc, parameters
    AddStep = pyqtSignal(str, str, str, dict)  
    UpdateStep = pyqtSignal(str, str, str, dict)  
    CancelEdit = pyqtSignal()
    def __init__(self, parent):
        """
        Constructor
        """
        QWidget.__init__(self)

        self.createActions()
        self.createWidgets()
        self.createToolbar()
        self.createConnections()
    
    def createActions(self):
        """
        Create qt actions
        """
        self.addAction = QPushButton(QIcon(":/add_black.png"), '&Add Action', self)
        self.addAction.setMinimumHeight(40)
        self.addAction.setMaximumWidth(200)
        
        self.cancelAction = QtHelper.createAction(self, "&Cancel", self.cancelStep, 
                                            icon=QIcon(":/undo.png"), tip = 'Cancel update')
        self.cancelAction.setEnabled(False)
        
        self.optionsAction = QtHelper.createAction(self, "&", self.openOptions, 
                                            icon=QIcon(":/recorder-basic-small.png"), tip = 'Framework options')
        
    def openOptions(self):
        """
        Open options dialog
        """
        if self.optionsDialog.exec_() == QDialog.Accepted:
            pass
              
    def createWidgets(self):
        """
        Create all qt widgets
        """
        self.optionsDialog  = OptionsDialog(self)
        
        self.validatorUpper = ValidatorUpper(self)
        self.validatorAll = ValidatorAll(self)
        self.validatorInt = QIntValidator(self)

        font = QFont()
        font.setBold(True)

        self.actionsComboBox = QComboBox(self)
        self.actionsComboBox.setMinimumHeight(40)
        for i in xrange(len(GuiSteps.ACTION_FRAMEWORK_DESCR)):
            if not len( GuiSteps.ACTION_FRAMEWORK_DESCR[i] ):
                self.actionsComboBox.insertSeparator(i+1)
            else:
                el = GuiSteps.ACTION_FRAMEWORK_DESCR[i].keys()
                self.actionsComboBox.addItem( list(el)[0] )
            
        self.labelActionDescr = QLabel(self)
        self.labelActionDescr.setText( "%s\n" % GuiSteps.ACTION_FRAMEWORK_DESCR[0][GuiSteps.FRAMEWORK_INFO])
        self.labelActionDescr.setWordWrap(True)
        self.labelActionDescr.hide()
        
        self.descriptionLine = QLineEdit(self)
        self.descriptionLine.hide()

        actionLayout2 = QGridLayout()

        self.createWidgetGetText()        
        self.createWidgetGetWait()
        self.createWidgetCacheSet()
        self.createWidgetCheckString()
        self.createWidgetGetAsk()

        actionLayout2.addWidget( self.setCacheGroup , 0, 0)
        actionLayout2.addWidget( self.getCheckGroup , 1, 0)
        actionLayout2.addWidget( self.getTextGroup , 2, 0)
        actionLayout2.addWidget( self.getWaitGroup , 3, 0)
        actionLayout2.addWidget( self.getAskGroup , 4, 0)

        labelAct = QLabel( self.tr("Action: ") )
        labelAct.setFont( font) 
        
        self.arrowLabel = QLabel("")
        self.arrowLabel.setPixmap(QPixmap(":/arrow-right.png").scaledToWidth(32))

        self.arrowLabel2 = QLabel("")
        self.arrowLabel2.setPixmap(QPixmap(":/arrow-right.png").scaledToWidth(32))

        layoutFinal = QHBoxLayout()
        layoutFinal.addWidget( labelAct )
        layoutFinal.addWidget(self.actionsComboBox)
        layoutFinal.addWidget( self.arrowLabel )
        layoutFinal.addLayout( actionLayout2 )
        layoutFinal.addWidget( self.arrowLabel2 )
        layoutFinal.addWidget(self.addAction)

        layoutFinal.addStretch(1)
        self.setLayout(layoutFinal)
        
    def createToolbar(self):
        """
        Create toolbar
        """
        pass

    def createWidgetCheckString(self):
        """
        Create widget to check string
        """
        self.getCheckGroup = QGroupBox(self.tr(""))

        # check in ?
        self.checkInTextLine = QLineEdit(self)
        self.checkInTextLine.setMinimumWidth(300)
        self.checkInTextCombo = QComboBox(self)
        self.checkInTextCombo.addItems( [ "CACHE" ] )

        # operator   
        self.checkComboBox = QComboBox(self)
        self.checkComboBox.addItems( [ GuiSteps.OP_CONTAINS, GuiSteps.OP_NOTCONTAINS, GuiSteps.OP_REGEXP, GuiSteps.OP_NOTREGEXP,
                                       GuiSteps.OP_STARTSWITH, GuiSteps.OP_NOTSTARTSWITH, GuiSteps.OP_ENDSWITH, 
                                       GuiSteps.OP_NOTENDSWITH ] )
        
        # check what ?
        self.checkOutTextLine = QLineEdit(self)
        self.checkOutTextLine.setMinimumWidth(300)
        self.checkOutTextCombo = QComboBox(self)
        self.checkOutTextCombo.addItems( LIST_TYPES )

        # final layout
        mainChecklayout = QGridLayout()
        mainChecklayout.addWidget(  QLabel( self.tr("Checking from:") ), 0, 0 )
        mainChecklayout.addWidget(  self.checkInTextCombo, 0, 1 )
        mainChecklayout.addWidget(  self.checkInTextLine, 0, 2 )
        mainChecklayout.addWidget(  QLabel( self.tr("If:") ), 1, 0 )
        mainChecklayout.addWidget(  self.checkComboBox, 1, 1 )
        mainChecklayout.addWidget(  QLabel( self.tr("The Value:") ), 2, 0  )
        mainChecklayout.addWidget(  self.checkOutTextCombo, 2, 1 )
        mainChecklayout.addWidget(  self.checkOutTextLine, 2, 2 )

        self.getCheckGroup.setLayout(mainChecklayout)
        self.getCheckGroup.hide()
        
    def createWidgetGetText(self):
        """
        Create text widget 
        """
        self.getTextGroup = QGroupBox(self.tr(""))

        self.basicTextLine = QLineEdit(self)
        self.basicTextLine.setMinimumWidth(300)
        self.basicTextCombo = QComboBox(self)
        self.basicTextCombo.addItems( LIST_TYPES )

        mainTextlayout = QGridLayout()
        mainTextlayout.addWidget(  QLabel( self.tr("Value:") ), 0, 0 )
        mainTextlayout.addWidget(  self.basicTextCombo, 0, 1 )
        mainTextlayout.addWidget(  self.basicTextLine, 0, 2 )

        self.getTextGroup.setLayout(mainTextlayout)
    
    def createWidgetGetAsk(self):
        """
        Create ask widget
        """
        # ask
        self.getAskGroup = QGroupBox(self.tr(""))

        self.askTextLine = QLineEdit(self)
        self.askTextLine.setMinimumWidth(300)
        self.askTextCombo = QComboBox(self)
        self.askTextCombo.addItems( LIST_TYPES )

        self.askTextCacheLine = QLineEdit(self)
        self.askTextCacheLine.setMinimumWidth(300)
        self.askTextCacheCombo = QComboBox(self)
        self.askTextCacheCombo.addItems( [ "CACHE" ] )
        
        mainAsklayout = QGridLayout()
        mainAsklayout.addWidget(  QLabel( self.tr("User input prompt:") ), 0, 0 )
        mainAsklayout.addWidget(  self.askTextCombo, 0, 1 )
        mainAsklayout.addWidget(  self.askTextLine, 0, 2 )
        mainAsklayout.addWidget(  QLabel( self.tr("And save response in:") ), 1, 0 )
        mainAsklayout.addWidget(  self.askTextCacheCombo, 1, 1 )
        mainAsklayout.addWidget(  self.askTextCacheLine, 1, 2 )
        
        self.getAskGroup.setLayout(mainAsklayout)
        self.getAskGroup.hide()
        
    def createWidgetGetWait(self):
        """
        Create wait text widget
        """
        self.getWaitGroup = QGroupBox(self.tr(""))

        self.valueWaitLine = QLineEdit(self)
        self.valueWaitLine.setMinimumWidth(300)
        self.valueWaitLine.setValidator(self.validatorInt)
        self.valueWaitCombo = QComboBox(self)
        self.valueWaitCombo.addItems( LIST_TYPES )

        mainTextlayout = QGridLayout()
        mainTextlayout.addWidget(  QLabel( self.tr("Value (in seconds):") ), 0, 0 )
        mainTextlayout.addWidget(  self.valueWaitCombo, 0, 1 )
        mainTextlayout.addWidget(  self.valueWaitLine, 0, 2 )

        self.getWaitGroup.setLayout(mainTextlayout)
        self.getWaitGroup.hide()
        
    def createWidgetCacheSet(self):
        """
        Create cache widget
        """
        self.setCacheGroup = QGroupBox(self.tr(""))
        
        setCacheLayout = QGridLayout()
        
        self.cacheKeyName = QLineEdit(self)
        self.cacheKeyName.setMinimumWidth(300)
        
        setCacheLayout.addWidget( QLabel( self.tr("Key name:") ) , 0, 1)
        setCacheLayout.addWidget( self.cacheKeyName , 0, 2)

        self.setCacheGroup.setLayout(setCacheLayout)
        self.setCacheGroup.hide()
        
    def createConnections(self):
        """
        Createa qt connections
        """
        self.actionsComboBox.currentIndexChanged.connect(self.onActionChanged)
        self.addAction.clicked.connect(self.addStep)
        
        self.basicTextCombo.currentIndexChanged.connect(self.onBasicTextTypeChanged)
        self.valueWaitCombo.currentIndexChanged.connect(self.onValueWaitTypeChanged)
        self.checkOutTextCombo.currentIndexChanged.connect(self.onCheckOutTextTypeChanged)
        self.askTextCombo.currentIndexChanged.connect(self.onAskTextTypeChanged)
        
    def onAskTextTypeChanged(self):
        """
        On ask type changed
        """
        if self.askTextCombo.currentText() in [ "TEXT", "CACHE" ]:
            self.askTextLine.setValidator(self.validatorAll)
            
        if self.askTextCombo.currentText() == "ALIAS":
            self.askTextLine.setText( self.askTextLine.text().upper() )
            self.askTextLine.setValidator(self.validatorUpper)
            
    def onCheckOutTextTypeChanged(self):
        """
        On check out type changed
        """
        if self.checkOutTextCombo.currentText() in [ "TEXT", "CACHE" ]:
            self.checkOutTextLine.setValidator(self.validatorAll)
            
        if self.checkOutTextCombo.currentText() == "ALIAS":
            self.checkOutTextLine.setText( self.checkOutTextLine.text().upper() )
            self.checkOutTextLine.setValidator(self.validatorUpper)
            
    def onValueWaitTypeChanged(self):
        """
        On value wait changed
        """
        if self.valueWaitCombo.currentText() in [ "TEXT" ]:
            self.valueWaitLine.setText( "0" )
            self.valueWaitLine.setValidator(self.validatorInt)
            
        if self.valueWaitCombo.currentText() in [ "CACHE" ]:
            self.valueWaitLine.setValidator(self.validatorAll)
            
        if self.valueWaitCombo.currentText() == "ALIAS":
            self.valueWaitLine.setText( self.valueWaitLine.text().upper() )
            self.valueWaitLine.setValidator(self.validatorUpper)
            
    def onBasicTextTypeChanged(self):
        """
        On basic text changed
        """
        if self.basicTextCombo.currentText() in [ "TEXT", "CACHE" ]:
            self.basicTextLine.setValidator(self.validatorAll)

        if self.basicTextCombo.currentText() == "ALIAS":
            self.basicTextLine.setText( self.basicTextLine.text().upper() )
            self.basicTextLine.setValidator(self.validatorUpper)
            
    def pluginDataAccessor(self):
        """
        Return data for plugins
        """
        return { "data": "" } 
        
    def onPluginImport(self, dataJson):
        """
        On call from plugin
        """
        pass 
    
    def onRadioAskChanged(self, button):
        """
        On radio ask changed
        """
        if button.text() == 'From alias parameter':
            self.askTextLine.setText( self.askTextLine.text().upper() )
            self.askTextLine.setValidator(self.validAskUpper)
        else:
            self.askTextLine.setValidator(self.validAskAll)

    def onActionChanged(self):
        """
        On action changed
        """
        descr = 'No description available!'
        i = 0
        for el in GuiSteps.ACTION_FRAMEWORK_DESCR:
            if isinstance(el, dict):
                if self.actionsComboBox.currentText() in el:
                    descr = GuiSteps.ACTION_FRAMEWORK_DESCR[i][self.actionsComboBox.currentText()]
                    break
            i += 1
        self.labelActionDescr.setText( "%s\n" % descr )
        
        if self.actionsComboBox.currentText() in [ GuiSteps.FRAMEWORK_INFO, GuiSteps.FRAMEWORK_WARNING ]:
            self.getTextGroup.show()
            self.getWaitGroup.hide()
            self.setCacheGroup.hide()
            self.getCheckGroup.hide()
            self.getAskGroup.hide()
            
            self.arrowLabel.show()
            self.arrowLabel2.show()
            
        elif self.actionsComboBox.currentText() in [ GuiSteps.FRAMEWORK_WAIT ]:
            self.getWaitGroup.show()
            self.getTextGroup.hide()
            self.setCacheGroup.hide()
            self.getCheckGroup.hide()
            self.getAskGroup.hide()
            
            self.arrowLabel.show()
            self.arrowLabel2.show()
            
        elif self.actionsComboBox.currentText() in [ GuiSteps.FRAMEWORK_CACHE_SET ]:
            self.getTextGroup.show()
            self.getWaitGroup.hide()
            self.setCacheGroup.show()
            self.getCheckGroup.hide()
            self.getAskGroup.hide()
            
            self.arrowLabel.show()
            self.arrowLabel2.show()
            
        elif self.actionsComboBox.currentText() in [ GuiSteps.FRAMEWORK_CHECK_STRING ]:
            self.getCheckGroup.show()
            self.getTextGroup.hide()
            self.getWaitGroup.hide()
            self.setCacheGroup.hide()
            self.getAskGroup.hide()
            
            self.arrowLabel.show()
            self.arrowLabel2.show()
            
        elif self.actionsComboBox.currentText() in [ GuiSteps.FRAMEWORK_INTERACT ]:
            self.getCheckGroup.hide()
            self.getTextGroup.hide()
            self.getWaitGroup.hide()
            self.setCacheGroup.hide()
            self.getAskGroup.show()
            
            self.arrowLabel.show()
            self.arrowLabel2.show()
            
        elif self.actionsComboBox.currentText() in [ GuiSteps.FRAMEWORK_USERCODE, GuiSteps.FRAMEWORK_CACHE_RESET ]:
            self.getCheckGroup.hide()
            self.getTextGroup.hide()
            self.getWaitGroup.hide()
            self.setCacheGroup.hide()
            self.getAskGroup.hide()
            
            self.arrowLabel.hide()
            self.arrowLabel2.show()
            
        else:
            self.getTextGroup.hide()
            self.getWaitGroup.hide()
            self.setCacheGroup.hide()
            self.getCheckGroup.hide()
            self.getAskGroup.hide()
            
            self.arrowLabel.hide()
            self.arrowLabel2.hide()

    def addStep(self):
        """
        Add step
        """
        action = self.actionsComboBox.currentText()
        descr = self.descriptionLine.text()
        descr = unicode(descr).replace('"', '')
        
        signal = self.AddStep
        if self.cancelAction.isEnabled():
            signal = self.UpdateStep

        if action in [ GuiSteps.FRAMEWORK_INFO, GuiSteps.FRAMEWORK_WARNING ]:
            fromCache = False
            if self.basicTextCombo.currentText() == "CACHE": fromCache = True
            fromAlias = False
            if self.basicTextCombo.currentText() == "ALIAS": fromAlias = True
            
            newText = self.basicTextLine.text()
            if not len(newText):
                QMessageBox.warning(self, "Assistant" , "Please to set a value!")
            else:
                parameters = { 'text': newText, 'from-cache': fromCache, 'from-alias': fromAlias }
                signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters )
        
        elif action in [ GuiSteps.FRAMEWORK_INTERACT ]:
            # read text from cache, alias or not ?
            fromCache = False
            if self.askTextCombo.currentText() == "CACHE": fromCache = True
            fromAlias = False
            if self.askTextCombo.currentText() == "ALIAS": fromAlias = True
            
            askText = self.askTextLine.text()
            if not len(askText):
                QMessageBox.warning(self, "Assistant" , "Please to set question to ask!")
            else:
                saveAskText = self.askTextCacheLine.text()
                if not len(saveAskText):
                    QMessageBox.warning(self, "Assistant" , "Please to set key destination cache!")
                else:
                    parameters = { 'key': saveAskText, 'value': askText, 'from-cache': fromCache, 'from-alias': fromAlias }
                    signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters )
                        
        elif action in [ GuiSteps.FRAMEWORK_CHECK_STRING ]:
            fromCache = False
            if self.checkOutTextCombo.currentText() == "CACHE": fromCache = True
            fromAlias = False
            if self.checkOutTextCombo.currentText() == "ALIAS": fromAlias = True
            
            inText = self.checkInTextLine.text()
            if not len(inText):
                QMessageBox.warning(self, "Assistant" , "Please to set a cache key value!")
            else:
                outText = self.checkOutTextLine.text()
                if not len(outText):
                    QMessageBox.warning(self, "Assistant" , "Please to set a value!")
                else:
                    op = self.checkComboBox.currentText()
                    parameters = { 'key': inText, 'value': outText, 'from-cache': fromCache,
                                    'from-alias': fromAlias, "operator": op }
                    signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters )
                    
        elif action in [ GuiSteps.FRAMEWORK_WAIT ]:
            fromCache = False
            if self.valueWaitCombo.currentText() == "CACHE": fromCache = True
            fromAlias = False
            if self.valueWaitCombo.currentText() == "ALIAS": fromAlias = True
            
            miscStr = self.valueWaitLine.text()
            if not len(miscStr):
                QMessageBox.warning(self, "Assistant" , "Please to set a value!")
            else:
                parameters = {'from-cache': fromCache, 'from-alias': fromAlias}
                signal.emit( str(action), unicode(descr), miscStr, parameters )
                
        elif action in [ GuiSteps.FRAMEWORK_CACHE_SET ]:
            fromCache = False
            if self.basicTextCombo.currentText() == "CACHE": fromCache = True
            fromAlias = False
            if self.basicTextCombo.currentText() == "ALIAS": fromAlias = True
            
            newText = self.basicTextLine.text()
            if not len(newText):
                QMessageBox.warning(self, "Assistant" , "Please to set a text value!")
            else:
                miscStr = self.cacheKeyName.text()
                if not len(miscStr):
                    QMessageBox.warning(self, "Assistant" , "Please to set a key name!")
                else:
                    parameters = { 'key': miscStr, 'value': newText, 'from-cache': fromCache, 'from-alias': fromAlias }
                    signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters )

        else:
            signal.emit( str(action), unicode(descr), EMPTY_VALUE, {} )
            
    def cancelStep(self):
        """
        Cancel step
        """
        self.addAction.setText( "&Add" )
        
        buttonFont = QFont()
        buttonFont.setBold(False)
        self.addAction.setFont(buttonFont)
        self.cancelAction.setEnabled(False)
        
        self.CancelEdit.emit()
    
    def finalizeUpdate(self):
        """
        Finalize update 
        """
        self.addAction.setText( "&Add Action" )
        
        buttonFont = QFont()
        buttonFont.setBold(False)
        self.addAction.setFont(buttonFont)
        self.cancelAction.setEnabled(False)

    def editStep(self, stepData):
        """
        Edit step
        """
        self.addAction.setText( "&Update" )
        buttonFont = QFont()
        buttonFont.setBold(True)
        self.addAction.setFont(buttonFont)
        
        self.cancelAction.setEnabled(True)
        
            
        # set the current value for actions combo
        for i in xrange(self.actionsComboBox.count()):
            item_text = self.actionsComboBox.itemText(i)
            if unicode(stepData["action"]) == unicode(item_text):
                self.actionsComboBox.setCurrentIndex(i)
                break
        # and then refresh options
        self.onActionChanged()
        
        # finally fill all fields
        self.descriptionLine.setText( stepData["description"] )
                
        if self.actionsComboBox.currentText() in [ GuiSteps.FRAMEWORK_INFO, GuiSteps.FRAMEWORK_WARNING ] :
            self.basicTextLine.setText ( stepData["parameters"]["text"] )
            if stepData["parameters"]["from-cache"]:
                self.basicTextLine.setValidator(self.validatorAll)
                self.basicTextCombo.setCurrentIndex(INDEX_CACHE)
            elif stepData["parameters"]["from-alias"]:
                self.basicTextLine.setValidator(self.validatorUpper)
                self.basicTextCombo.setCurrentIndex(INDEX_ALIAS)
            else:
                self.basicTextLine.setValidator(self.validatorAll)
                self.basicTextCombo.setCurrentIndex(INDEX_TEXT)

        if self.actionsComboBox.currentText() in [ GuiSteps.FRAMEWORK_WAIT ]:
            self.valueWaitLine.setText ( stepData["misc"] )
            if stepData["parameters"]["from-cache"]:
                self.valueWaitLine.setValidator(self.validatorAll)
                self.valueWaitCombo.setCurrentIndex(INDEX_CACHE)
            elif stepData["parameters"]["from-alias"]:
                self.valueWaitLine.setValidator(self.validatorUpper)
                self.valueWaitCombo.setCurrentIndex(INDEX_ALIAS)
            else:
                self.valueWaitLine.setValidator(self.validatorInt)
                self.valueWaitCombo.setCurrentIndex(INDEX_TEXT)
 
        if self.actionsComboBox.currentText() in [ GuiSteps.FRAMEWORK_CACHE_SET ]:
            self.basicTextLine.setText ( stepData["parameters"]["value"] )
            if stepData["parameters"]["from-cache"]:
                self.basicTextLine.setValidator(self.validatorAll)
                self.basicTextCombo.setCurrentIndex(INDEX_CACHE)
                
            elif stepData["parameters"]["from-alias"]:
                self.basicTextLine.setValidator(self.validatorUpper)
                self.basicTextCombo.setCurrentIndex(INDEX_ALIAS)
            else:
                self.basicTextLine.setValidator(self.validatorAll)
                self.basicTextCombo.setCurrentIndex(INDEX_TEXT)
                
            self.cacheKeyName.setText( stepData["parameters"]["key"] ) 
            
        if self.actionsComboBox.currentText() in [ GuiSteps.FRAMEWORK_CHECK_STRING ]:

            self.checkOutTextLine.setText ( stepData["parameters"]["value"] )
                        
            if stepData["parameters"]["from-cache"]:
                self.checkOutTextLine.setValidator(self.validatorAll)
                self.checkOutTextCombo.setCurrentIndex(INDEX_CACHE)
            elif stepData["parameters"]["from-alias"]:
                self.checkOutTextLine.setValidator(self.validatorUpper)
                self.checkOutTextCombo.setCurrentIndex(INDEX_ALIAS)
            else:
                self.checkOutTextLine.setValidator(self.validatorAll)
                self.checkOutTextCombo.setCurrentIndex(INDEX_TEXT)

            self.checkInTextLine.setText ( stepData["parameters"]["key"] )
            
            for i in xrange(self.checkComboBox.count()):
                item_text = self.checkComboBox.itemText(i)
                if unicode(stepData["parameters"]["operator"]) == unicode(item_text):
                    self.checkComboBox.setCurrentIndex(i)
                    break

        if self.actionsComboBox.currentText() in [ GuiSteps.FRAMEWORK_INTERACT ]:
            self.askTextLine.setText ( stepData["parameters"]["value"] )
            if stepData["parameters"]["from-cache"]:
                self.askTextLine.setValidator(self.validatorAll)
                self.askTextCombo.setCurrentIndex(INDEX_CACHE)
            elif stepData["parameters"]["from-alias"]:
                self.askTextLine.setValidator(self.validatorUpper)
                self.askTextCombo.setCurrentIndex(INDEX_ALIAS)
            else:
                self.askTextLine.setValidator(self.validatorAll)
                self.askTextCombo.setCurrentIndex(INDEX_TEXT)

            self.askTextCacheLine.setText ( stepData["parameters"]["key"] )
            
    def getTimeout(self):
        """
        Return timeout
        """
        return self.optionsDialog.timeoutLine.text() 
        
    def setTimeout(self, timeout):
        """
        Set the timeout
        """
        return self.optionsDialog.timeoutLine.setText(timeout) 
示例#4
0
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 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.toXml = toXml
        self.toCsv = toCsv
        self.toHtml = toHtml
        self.toPrinter = toPrinter
        self.toTxt = toTxt
        self.toPdf = toPdf

        self.fileName = None

        self.createWidgets()
        self.createActions()
        self.createToolbars()

    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)
        self.exportBox.setMaximumHeight(70)

        layout = QVBoxLayout()

        if self.toXml:
            self.txtEdit = QtHelper.RawXmlEditor(parent=self)
            self.txtEdit.setText(self.__data)
            # self.txtEdit.setUtf8(False)
            self.txtEdit.setFont(QFont("Courier", 9))
        else:
            self.txtEdit = QWebView(parent=self)
            # convert to qbyte array to support qt5
            tmp_ = QByteArray()
            tmp_.append(self.__data)

            self.txtEdit.setContent(tmp_, "text/html; charset=utf-8")

        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.txtEdit)

        self.setLayout(layout)

    def createToolbars(self):
        """
        Toolbar creation
        """
        self.toolbar.setObjectName("Export toolbar")
        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 in toolbar
        """
        self.toolbarPlugins.addAction(pluginAction)
        self.toolbarPlugins.setIconSize(QSize(16, 16))
        self.pluginsBox.show()

    def createActions(self):
        """
        Qt Actions
        """
        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 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:
            self.txtEdit.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 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:
            if QtHelper.IS_QT5:  # new in v18
                self.fileName = _filename
                self.txtEdit.page().toPlainText(self.__toPlainText)
            else:
                frame = self.txtEdit.page().mainFrame()
                try:
                    with codecs.open(_filename, "w", "utf-8") as f:
                        f.write(frame.toPlainText())
                except Exception as e:
                    self.error('unable to save report file as txt: %s' %
                               str(e))

    def __toPlainText(self, text):
        """
        New in v18
        Callback from QWebpage
        """
        if self.fileName is None:
            return

        try:
            with codecs.open(self.fileName, "w", "utf-8") as f:
                f.write(text)
        except Exception as e:
            self.error('unable to save report file as txt: %s' % str(e))

        self.fileName = None

    def saveXml(self):
        """
        Save 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 report 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:
            if QtHelper.IS_QT5:  # new in v18
                self.fileName = _filename
                self.txtEdit.page().toHtml(self.__toHtml)
            else:
                frame = self.txtEdit.page().mainFrame()
                try:
                    with codecs.open(_filename, "w", "utf-8") as f:
                        f.write(frame.toHtml())
                except Exception as e:
                    self.error('unable to save report file as html: %s' %
                               str(e))

    def __toHtml(self, html):
        """
        New in v18
        Callback from QWebpage
        """
        if self.fileName is None:
            return

        try:
            with codecs.open(self.fileName, "w", "utf-8") as f:
                f.write(html)
        except Exception as e:
            self.error('unable to save report file as html: %s' % str(e))

        self.fileName = None

    def savePdf(self):
        """
        Save to 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:
            if QtHelper.IS_QT5:  # new in v18
                self.fileName = _filename
                self.txtEdit.page().printToPdf(self.__toPdf)
            else:
                printer = QPrinter(QPrinter.HighResolution)
                printer.setPageSize(QPrinter.A4)
                printer.setColorMode(QPrinter.Color)
                printer.setOutputFormat(QPrinter.PdfFormat)
                printer.setOutputFileName(_filename)

                if isinstance(self.txtEdit, QWebView):
                    self.txtEdit.print_(printer)
                else:
                    doc = QTextDocument()
                    if self.toXml:
                        doc.setPlainText(self.txtEdit.text())
                    else:
                        doc.setHtml(self.txtEdit.toHtml())
                    doc.print_(printer)

    def __toPdf(self, pdf):
        """
        New in v18
        Callback from QWebpage
        """
        if self.fileName is None:
            return

        try:
            with codecs.open(self.fileName, "wb") as f:
                f.write(pdf)
        except Exception as e:
            self.error('unable to save report file as pdf: %s' % str(e))

        self.fileName = None
class AdvancedVisualizationForm(QWidget):
    def __init__(self, mainwindow, result_manager):
        QWidget.__init__(self, mainwindow)
        #mainwindow is an OpusGui
        self.mainwindow = mainwindow
        self.result_manager = result_manager
        self.toolboxBase = self.result_manager.mainwindow.toolboxBase

        self.inGui = False
        self.logFileKey = 0
        
        self.xml_helper = ResultsManagerXMLHelper(toolboxBase = self.toolboxBase)
        self.result_generator = OpusResultGenerator(
                                    toolboxBase = self.toolboxBase)
            
        self.result_generator.guiElement = self
        
        self.tabIcon = QIcon(':/Images/Images/cog.png')
        self.tabLabel = 'Advanced Visualization'

        self.widgetLayout = QVBoxLayout(self)
        self.widgetLayout.setAlignment(Qt.AlignTop)

        self.resultsGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.resultsGroupBox)
        
        self.dataGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.dataGroupBox)
        
        self.optionsGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.optionsGroupBox)
                
        self._setup_definition_widget()

        self._setup_buttons()
        self._setup_tabs()
        
    def _setup_buttons(self):
        # Add Generate button...
        self.pbn_go = QPushButton(self.resultsGroupBox)
        self.pbn_go.setObjectName('pbn_go')
        self.pbn_go.setText(QString('Go!'))
        
        QObject.connect(self.pbn_go, SIGNAL('released()'),
                        self.on_pbn_go_released)
        self.widgetLayout.addWidget(self.pbn_go)
        
        self.pbn_set_esri_storage_location = QPushButton(self.optionsGroupBox)
        self.pbn_set_esri_storage_location.setObjectName('pbn_set_esri_storage_location')
        self.pbn_set_esri_storage_location.setText(QString('...'))
        self.pbn_set_esri_storage_location.hide()
        
        QObject.connect(self.pbn_set_esri_storage_location, SIGNAL('released()'),
                        self.on_pbn_set_esri_storage_location_released)
        
    def _setup_tabs(self):
        # Add a tab widget and layer in a tree view and log panel
        self.tabWidget = QTabWidget(self.resultsGroupBox)
    
        # Log panel
        self.logText = QTextEdit(self.resultsGroupBox)
        self.logText.setReadOnly(True)
        self.logText.setLineWidth(0)
        self.tabWidget.addTab(self.logText,'Log')

        # Finally add the tab to the model page
        self.widgetLayout.addWidget(self.tabWidget)
        
#
    def _setup_definition_widget(self):
        
        #### setup results group box ####
        
        self.gridlayout = QGridLayout(self.resultsGroupBox)
        self.gridlayout.setObjectName('gridlayout')

        self.lbl_results = QLabel(self.resultsGroupBox)
        self.lbl_results.setObjectName('lbl_results')
        self.lbl_results.setText(QString('Results'))
        self.gridlayout.addWidget(self.lbl_results,0,0,1,3)

        self._setup_co_results()
        self.gridlayout.addWidget(self.co_results,0,3,1,10)

        self.pbn_add = QPushButton(self.resultsGroupBox)
        self.pbn_add.setObjectName('pbn_add')
        self.pbn_add.setText(QString('+'))
        
        QObject.connect(self.pbn_add, SIGNAL('released()'),
                        self.on_pbn_add_released)
        self.gridlayout.addWidget(self.pbn_add, 0, 14, 1, 1)

        self.lw_indicators = QListWidget(self.resultsGroupBox)
        self.lw_indicators.setObjectName('lw_indicators')
        self.gridlayout.addWidget(self.lw_indicators,1,1,1,13)

        self.pbn_remove = QPushButton(self.resultsGroupBox)
        self.pbn_remove.setObjectName('pbn_remove')
        self.pbn_remove.setText(QString('-'))
        
        QObject.connect(self.pbn_remove, SIGNAL('released()'),
                        self.on_pbn_remove_released)
        self.gridlayout.addWidget(self.pbn_remove, 1, 14, 1, 1)


        #### setup data group box ####

        self.gridlayout2 = QGridLayout(self.dataGroupBox)
        self.gridlayout2.setObjectName('gridlayout2')

        self._setup_co_result_style()
        self.gridlayout2.addWidget(self.co_result_style,1,0,1,2)
                
        self.lbl_result_style_sep = QLabel(self.resultsGroupBox)
        self.lbl_result_style_sep.setObjectName('lbl_result_style_sep')
        self.lbl_result_style_sep.setText(QString('<center>as</center>'))
        self.gridlayout2.addWidget(self.lbl_result_style_sep,1,2,1,1)

        self._setup_co_result_type()
        self.gridlayout2.addWidget(self.co_result_type,1,3,1,2)

        ##### setup options group box ####
        
        self.gridlayout3 = QGridLayout(self.optionsGroupBox)
        self.gridlayout3.setObjectName('gridlayout3')
        
        self.le_esri_storage_location = QLineEdit(self.optionsGroupBox)
        self.le_esri_storage_location.setObjectName('le_esri_storage_location')
        self.le_esri_storage_location.setText('[set path]')
        self.le_esri_storage_location.hide()
        self.optionsGroupBox.hide()

        
        QObject.connect(self.co_result_style, SIGNAL('currentIndexChanged(int)'),
                self.on_co_result_style_changed)
        QObject.connect(self.co_result_type, SIGNAL('currentIndexChanged(int)'),
                self.on_co_result_type_changed)

    def _setup_co_results(self):
        
        self.co_results = QComboBox(self.resultsGroupBox)
        self.co_results.setObjectName('co_results')
        self.co_results.addItem(QString('[select]'))
        
        results = self.xml_helper.get_available_results()
            
        for result in results:
            name = '%i.%s'%(result['run_id'],result['indicator_name'])
            self.co_results.addItem(QString(name))

    def _setup_co_result_style(self):
        available_styles = [
            'visualize',
            'export',
        ]
        self.co_result_style = QComboBox(self.dataGroupBox)
        self.co_result_style.setObjectName('co_result_style')
        
        for dataset in available_styles:
            self.co_result_style.addItem(QString(dataset))

    def _setup_co_result_type(self):
        available_types = [
            'Table (per year, spans indicators)',
            'Chart (per indicator, spans years)',
            'Map (per indicator per year)',
            'Chart (per indicator, spans years)',
        ]
                
        self.co_result_type = QComboBox(self.dataGroupBox)
        self.co_result_type.setObjectName('co_result_type')
        
        for dataset in available_types:
            self.co_result_type.addItem(QString(dataset))
                    
    def on_pbnRemoveModel_released(self):
        self.result_manager.removeTab(self)
        self.result_manager.updateGuiElements()
        
    def on_pbn_add_released(self):
        cur_selected = self.co_results.currentText()        
        for i in range(self.lw_indicators.count()):
            if self.lw_indicators.item(i).text() == cur_selected:
                return
        
        self.lw_indicators.addItem(cur_selected)
        
    def on_pbn_remove_released(self):
        selected_idxs = self.lw_indicators.selectedIndexes()
        for idx in selected_idxs:
            self.lw_indicators.takeItem(idx.row())
        
    def on_co_result_style_changed(self, ind):
        available_viz_types = [
            'Table (per year, spans indicators)',
            'Chart (per indicator, spans years)',
            'Map (per indicator per year)',
            'Chart (per indicator, spans years)',
        ]
        
        available_export_types = [
            'ESRI table (for loading in ArcGIS)'
        ]
                
        txt = self.co_result_style.currentText()
        if txt == 'visualize':
            available_types = available_viz_types
        else:
            available_types = available_export_types
            
        self.co_result_type.clear()
        for result_type in available_types:
            r_type = QString(result_type)
            self.co_result_type.addItem(r_type)
    
    def on_co_result_type_changed(self, ind):
        self.gridlayout3.removeWidget(self.le_esri_storage_location)
        self.gridlayout3.removeWidget(self.pbn_set_esri_storage_location)
        self.optionsGroupBox.hide()
        
        self.pbn_set_esri_storage_location.hide()
        self.le_esri_storage_location.hide()
        
        txt = self.co_result_type.currentText()

        print txt
        if txt == 'ESRI table (for loading in ArcGIS)':
            self.pbn_set_esri_storage_location.show()   
            self.le_esri_storage_location.show()   
            self.gridlayout3.addWidget(self.le_esri_storage_location,0,1,1,6)
            self.gridlayout3.addWidget(self.pbn_set_esri_storage_location,0,7,1,1)   
            self.optionsGroupBox.show()   
            
    def on_pbn_set_esri_storage_location_released(self):
        print 'pbn_set_esri_storage_location released'
        from opus_core.misc import directory_path_from_opus_path
        start_dir = directory_path_from_opus_path('opus_gui.projects')

        configDialog = QFileDialog()
        filter_str = QString("*.gdb")
        fd = configDialog.getExistingDirectory(self,QString("Please select an ESRI geodatabase (*.gdb)..."), #, *.sde, *.mdb)..."),
                                          QString(start_dir), QFileDialog.ShowDirsOnly)
        if len(fd) != 0:
            fileName = QString(fd)
            fileNameInfo = QFileInfo(QString(fd))
            fileNameBaseName = fileNameInfo.completeBaseName()
            self.le_esri_storage_location.setText(fileName)
            
                
    def on_pbn_go_released(self):
        # Fire up a new thread and run the model
        print 'Go button pressed'

        # References to the GUI elements for status for this run...
        #self.statusLabel = self.runStatusLabel
        #self.statusLabel.setText(QString('Model initializing...'))
        
        indicator_names = []
        for i in range(self.lw_indicators.count()):
            indicator_names.append(str(self.lw_indicators.item(i).text()))
                
        if indicator_names == []:
            print 'no indicators selected'
            return
                
        indicator_type = str(self.co_result_type.currentText())
        indicator_type = {
            #'Map (per indicator per year)':'matplotlib_map',
            'Map (per indicator per year)':'mapnik_map',
            'Chart (per indicator, spans years)':'matplotlib_chart',
            'Table (per indicator, spans years)':'table_per_attribute',
            'Table (per year, spans indicators)':'table_per_year',
            'ESRI table (for loading in ArcGIS)':'table_esri'
        }[indicator_type]
        
        kwargs = {}
        if indicator_type == 'table_esri':
            storage_location = str(self.le_esri_storage_location.text())
            if not os.path.exists(storage_location):
                print 'Warning: %s does not exist!!'%storage_location
            kwargs['storage_location'] = storage_location
        
        self.result_manager.addIndicatorForm(indicator_type = indicator_type,
                                             indicator_names = indicator_names,
                                             kwargs = kwargs)

    def runUpdateLog(self):
        self.logFileKey = self.result_generator._get_current_log(self.logFileKey)


    def runErrorFromThread(self,errorMessage):
        QMessageBox.warning(self.mainwindow, 'Warning', errorMessage)
示例#7
0
class WAndroid(QWidget, Logger.ClassLogger):
    """
    Android widget
    """
    # action, description, misc, parameters
    AddStep = pyqtSignal(str, str, str, dict)
    UpdateStep = pyqtSignal(str, str, str, dict)    
    CancelEdit = pyqtSignal()
    def __init__(self, parent):
        """
        Constructor
        """
        QWidget.__init__(self)

        self.createActions()
        self.createWidgets()
        self.createToolbar()
        self.createConnections()
    
    def createActions(self):
        """
        Create qt actions
        """
        self.addAndroidAction = QPushButton(QIcon(":/add_black.png"), '&Add Action', self)
        self.addAndroidAction.setMinimumHeight(40)         
        self.addAndroidAction.setMaximumWidth(150)
        
        self.cancelAndroidAction = QtHelper.createAction(self, "&Cancel", self.cancelStep, 
                                            icon=None, tip = 'Cancel update')
        self.cancelAndroidAction.setEnabled(False)
        
        self.optionsAction = QtHelper.createAction(self, "&", self.openOptions, 
                                            icon=QIcon(":/recorder-mobile-small.png"), tip = 'Android options')
                                            
    def createWidgets(self):
        """
        Create qt widgets
        """
        self.optionsDialog  = OptionsDialog(self)
        
        self.validatorUpper = ValidatorUpper(self)
        self.validatorAll = ValidatorAll(self)
        self.validatorInt = QIntValidator(self)

        ###################### android action #########################

        self.actionsAndroidComboBox = QComboBox(self)
        self.actionsAndroidComboBox.setMinimumHeight(40)
        for i in xrange(len(GuiSteps.ACTION_ANDROID_DESCR)):
            if not len( GuiSteps.ACTION_ANDROID_DESCR[i] ):
                self.actionsAndroidComboBox.insertSeparator(i+1)
            else:
                el = GuiSteps.ACTION_ANDROID_DESCR[i].keys()
                self.actionsAndroidComboBox.addItem( list(el)[0] )
            
        self.descriptionAndroidLine = QLineEdit(self)
        self.descriptionAndroidLine.setPlaceholderText("Step purpose description")
        self.descriptionAndroidLine.hide()

        self.labelActionAndroidDescr = QLabel( )
        self.labelActionAndroidDescr.hide()
        self.labelActionAndroidDescr.setText( "%s\n" % GuiSteps.ACTION_ANDROID_DESCR[0][GuiSteps.ANDROID_WAKEUP_UNLOCK])
        self.labelActionAndroidDescr.setWordWrap(True)
        
        actionsLayout = QHBoxLayout()
        actionsLayout.addWidget(self.actionsAndroidComboBox)
        
        actionLayoutAndroid = QGridLayout()
        actionLayoutAndroid.addLayout(actionsLayout, 0, 1)

        self.createWidgetShortcut()
        self.createWidgetCode()
        self.createWidgetStart()
        self.createWidgetXY()
        self.createWidgetEndXY()
        self.createWidgetElement()
        self.createWidgetTextTo()
        self.createWidgetLine()
        self.createWidgetLine2()
        
        actionLayoutAndroid2 = QGridLayout()
        actionLayoutAndroid2.addWidget( self.shortcutAndroidGroup , 0, 0)
        actionLayoutAndroid2.addWidget( self.codeAndroidGroup , 0, 0)
        actionLayoutAndroid2.addWidget( self.elemenAndroidGroup , 0, 0)
        actionLayoutAndroid2.addWidget( self.xyAndroidGroup , 0, 0)
        actionLayoutAndroid2.addWidget( self.startAndroidGroup , 0, 0)
        actionLayoutAndroid2.addWidget( self.lineAndroidGroup , 1, 0)
        actionLayoutAndroid2.addWidget( self.line2AndroidGroup , 0, 1)
        actionLayoutAndroid2.addWidget( self.textToGlobalGroup , 0, 1)
        actionLayoutAndroid2.addWidget( self.endXyAndroidGroup, 0, 1)
        
        font = QFont()
        font.setBold(True)
        
        labelAct = QLabel( self.tr("Action: ") )
        labelAct.setFont( font) 
        
        self.arrowLabel = QLabel("")
        self.arrowLabel.setPixmap(QPixmap(":/arrow-right.png").scaledToWidth(32))
        self.arrowLabel.hide()
        
        self.arrowLabel2 = QLabel("")
        self.arrowLabel2.setPixmap(QPixmap(":/arrow-right.png").scaledToWidth(32))

        layoutAndroid = QHBoxLayout()
        layoutAndroid.addWidget( labelAct )
        layoutAndroid.addLayout( actionLayoutAndroid )
        layoutAndroid.addWidget( self.arrowLabel )
        layoutAndroid.addLayout( actionLayoutAndroid2 )
        layoutAndroid.addWidget( self.arrowLabel2 )
        layoutAndroid.addWidget(self.addAndroidAction)

        layoutAndroid.addStretch(1)
        self.setLayout(layoutAndroid)
        
    def createToolbar(self):
        """
        Create qt toolbar
        """
        pass
        
    def openOptions(self):
        """
        Open options
        """
        if self.optionsDialog.exec_() == QDialog.Accepted:
            pass
            
    def createWidgetLine2(self):
        """
        Create line widget
        """
        self.valueAndroidLine2 = QLineEdit(self)
        self.valueAndroidLine2.setMinimumWidth(150)
        self.valueAndroidCombo2 = QComboBox(self)
        self.valueAndroidCombo2.addItems( LIST_TYPES )

        self.line2AndroidGroup = QGroupBox(self.tr(""))
        
        line2Androidlayout = QGridLayout()
        line2Androidlayout.addWidget( QLabel( self.tr("Text to type:") ), 0, 0  ) 
        line2Androidlayout.addWidget( self.valueAndroidCombo2, 0, 1 )
        line2Androidlayout.addWidget( self.valueAndroidLine2, 0, 2 )

        self.line2AndroidGroup.setLayout(line2Androidlayout)
        self.line2AndroidGroup.hide()
        
    def createWidgetLine(self):
        """
        Create line widget
        """
        self.lineAndroidGroup = QGroupBox(self.tr(""))
        lineAndroidlayout = QGridLayout()
        self.valueAndroidLine = QLineEdit(self)
        self.valueAndroidLine.setMinimumWidth(300)
        lineAndroidlayout.addWidget( QLabel( self.tr("Value:") ) , 0,1)
        lineAndroidlayout.addWidget( self.valueAndroidLine , 0, 2)
        self.lineAndroidGroup.setLayout(lineAndroidlayout)
        self.lineAndroidGroup.hide()
        
    def createWidgetTextTo(self):
        """
        Create text widget
        """
        self.valueTextCacheGlobalLine = QLineEdit(self)
        self.valueTextCacheGlobalLine.setMinimumWidth(150)
        self.valueTextCacheGlobalCombo = QComboBox(self)
        self.valueTextCacheGlobalCombo.addItems( ["CACHE"] )
        
        self.textToGlobalGroup = QGroupBox(self.tr(""))
        textToGloballayout = QGridLayout()
        textToGloballayout.addWidget( QLabel( self.tr("Save text in:") ) , 0, 0)
        textToGloballayout.addWidget( self.valueTextCacheGlobalCombo , 0, 1)
        textToGloballayout.addWidget( self.valueTextCacheGlobalLine , 0, 2)
        self.textToGlobalGroup.setLayout(textToGloballayout)
        self.textToGlobalGroup.hide()
        
    def createWidgetElement(self):
        """
        Create text widget
        """
        self.elemenAndroidGroup = QGroupBox(self.tr(""))
        
        self.elementTextAndroidLine = QLineEdit(self)
        self.elementTextAndroidLine.setMinimumWidth(300)
        self.elementTextCombo = QComboBox(self)
        self.elementTextCombo.addItems( LIST_TYPES )
        
        self.elementDescriptionAndroidLine = QLineEdit(self)
        self.elementDescriptionAndroidLine.setMinimumWidth(300)
        self.elementClassAndroidLine = QLineEdit(self)
        self.elementClassAndroidLine.setMinimumWidth(300)
        self.elementRessourceIdAndroidLine = QLineEdit(self)
        self.elementRessourceIdAndroidLine.setMinimumWidth(300)
        self.elementPackageAndroidLine = QLineEdit(self)
        self.elementPackageAndroidLine.setMinimumWidth(300)

        # get  text end
        elementAndroidlayout = QGridLayout()
        elementAndroidlayout.addWidget( QLabel( self.tr("Text Element:") ) , 0,1)
        elementAndroidlayout.addWidget( self.elementTextCombo , 0, 2)
        elementAndroidlayout.addWidget( self.elementTextAndroidLine , 0, 3)
        elementAndroidlayout.addWidget( QLabel( self.tr("Description Element:") ) , 1,1)
        elementAndroidlayout.addWidget( self.elementDescriptionAndroidLine , 1, 3)
        elementAndroidlayout.addWidget( QLabel( self.tr("Class Name:") ) , 2,1)
        elementAndroidlayout.addWidget( self.elementClassAndroidLine , 2, 3)
        elementAndroidlayout.addWidget( QLabel( self.tr("Resource ID:") ) , 3,1)
        elementAndroidlayout.addWidget( self.elementRessourceIdAndroidLine , 3, 3)
        elementAndroidlayout.addWidget( QLabel( self.tr("Package Name:") ) , 4,1)
        elementAndroidlayout.addWidget( self.elementPackageAndroidLine , 4, 3)
        self.elemenAndroidGroup.setLayout(elementAndroidlayout)
        self.elemenAndroidGroup.hide()
        
    def createWidgetEndXY(self):
        """
        Create widget 
        """
        self.endXyAndroidGroup = QGroupBox(self.tr(""))
        endXyAndroidlayout = QGridLayout()
        
        self.endxAndroidLine = QLineEdit(self)
        validatorEndXAndroid = QIntValidator (self)
        self.endxAndroidLine.setValidator(validatorEndXAndroid)
        self.endxAndroidLine.installEventFilter(self)
        
        self.endyAndroidLine = QLineEdit(self)
        validatorEndYAndroid = QIntValidator (self)
        self.endyAndroidLine.setValidator(validatorEndYAndroid)
        self.endyAndroidLine.installEventFilter(self)
        
        endXyAndroidlayout.addWidget( QLabel( self.tr("Destination Coordinate X:") ) , 0, 0)
        endXyAndroidlayout.addWidget( self.endxAndroidLine , 0, 1)
        endXyAndroidlayout.addWidget( QLabel( self.tr("Destination Coordinate Y:") ) , 1,0)
        endXyAndroidlayout.addWidget( self.endyAndroidLine , 1, 1)
        
        self.endXyAndroidGroup.setLayout(endXyAndroidlayout)
        self.endXyAndroidGroup.hide()
        
    def createWidgetXY(self):
        """
        Create text widget
        """
        self.xyAndroidGroup = QGroupBox(self.tr(""))
        xyAndroidlayout = QGridLayout()
        
        self.xAndroidLine = QLineEdit(self)
        validatorXAndroid = QIntValidator (self)
        self.xAndroidLine.setValidator(validatorXAndroid)
        self.xAndroidLine.installEventFilter(self)
        
        self.yAndroidLine = QLineEdit(self)
        validatorYAndroid = QIntValidator (self)
        self.yAndroidLine.setValidator(validatorYAndroid)
        self.yAndroidLine.installEventFilter(self)
        
        xyAndroidlayout.addWidget( QLabel( self.tr("Coordinate X:") ) , 0,0)
        xyAndroidlayout.addWidget( self.xAndroidLine , 0, 1)
        xyAndroidlayout.addWidget( QLabel( self.tr("Coordinate Y:") ) , 1,0)
        xyAndroidlayout.addWidget( self.yAndroidLine , 1, 1)
        
        self.xyAndroidGroup.setLayout(xyAndroidlayout)
        self.xyAndroidGroup.hide()
        
    def createWidgetStart(self):
        """
        Create text widget
        """
        self.startAndroidGroup = QGroupBox(self.tr(""))
        startAndroidlayout = QGridLayout()
        
        self.startXAndroidLine = QLineEdit(self)
        validatorStartXAndroid = QIntValidator (self)
        self.startXAndroidLine.setValidator(validatorStartXAndroid)
        self.startXAndroidLine.installEventFilter(self)
        
        self.startYAndroidLine = QLineEdit(self)
        validatorStartYAndroid = QIntValidator (self)
        self.startYAndroidLine.setValidator(validatorStartYAndroid)
        self.startYAndroidLine.installEventFilter(self)
        
        self.stopXAndroidLine = QLineEdit(self)
        validatorStopXAndroid = QIntValidator (self)
        self.stopXAndroidLine.setValidator(validatorStopXAndroid)
        self.stopXAndroidLine.installEventFilter(self)
        
        self.stopYAndroidLine = QLineEdit(self)
        validatorStopYAndroid = QIntValidator (self)
        self.stopYAndroidLine.setValidator(validatorStopYAndroid)
        self.stopYAndroidLine.installEventFilter(self)
        
        startAndroidlayout.addWidget( QLabel( self.tr("From X:") ) , 0,1)
        startAndroidlayout.addWidget( self.startXAndroidLine , 0, 2)
        startAndroidlayout.addWidget( QLabel( self.tr("From Y:") ) , 0,3)
        startAndroidlayout.addWidget( self.startYAndroidLine , 0, 4)
        startAndroidlayout.addWidget( QLabel( self.tr("To X:") ) ,1,1)
        startAndroidlayout.addWidget( self.stopXAndroidLine , 1, 2)
        startAndroidlayout.addWidget( QLabel( self.tr("To Y:") ) , 1,3)
        startAndroidlayout.addWidget( self.stopYAndroidLine , 1 , 4)
        self.startAndroidGroup.setLayout(startAndroidlayout)
        self.startAndroidGroup.hide()
        
    def createWidgetShortcut(self):
        """
        Create shortcut widget
        """
        self.shortcutAndroidGroup = QGroupBox(self.tr(""))
        shortcutAndroidlayout = QGridLayout()

        self.shortcutAndroidComboBox = QComboBox(self)
        for i in xrange(len(KEYS_SHORTCUT_ANDROID)):
            if len(KEYS_SHORTCUT_ANDROID[i]) == 0:
                self.shortcutAndroidComboBox.insertSeparator(i + 2)
            else:
                self.shortcutAndroidComboBox.addItem (KEYS_SHORTCUT_ANDROID[i])

        shortcutAndroidlayout.addWidget( QLabel( self.tr("Button:") ) , 0,1)
        shortcutAndroidlayout.addWidget(self.shortcutAndroidComboBox, 0, 2)
        
        self.shortcutAndroidGroup.setLayout(shortcutAndroidlayout)
        self.shortcutAndroidGroup.hide()

    def createWidgetCode(self):
        """
        Create code widget
        """
        self.codeAndroidGroup = QGroupBox(self.tr(""))
        self.codeAndroidLine = QLineEdit(self)
        validatorCodeAndroid = QIntValidator (self)
        self.codeAndroidLine.setValidator(validatorCodeAndroid)
        self.codeAndroidLine.installEventFilter(self)
        
        codeAndroidlayout = QGridLayout()
        codeAndroidlayout.addWidget( QLabel( self.tr("Code:") ) , 0,1)
        codeAndroidlayout.addWidget( self.codeAndroidLine , 0, 2)
        self.codeAndroidGroup.setLayout(codeAndroidlayout)
        self.codeAndroidGroup.hide()
        
    def pluginDataAccessor(self):
        """
        Return data for plugin
        """
        return { "data": "" } 
        
    def onPluginImport(self, dataJson):
        """
        Received data from plugin
        """
        pass

    def createConnections(self):
        """
        Create qt connections
        """
        self.actionsAndroidComboBox.currentIndexChanged.connect(self.onActionAndroidChanged)
        self.addAndroidAction.clicked.connect(self.addStep)
        self.valueAndroidCombo2.currentIndexChanged.connect(self.onValueAndroid2TypeChanged)
        self.elementTextCombo.currentIndexChanged.connect(self.onElementTextTypeChanged)
        
    def onElementTextTypeChanged(self):
        """
        On element text changed
        """
        if self.elementTextCombo.currentText() in [ "TEXT", "CACHE" ]:
            self.elementTextAndroidLine.setValidator(self.validatorAll)
            
        if self.elementTextCombo.currentText() == "ALIAS":
            self.elementTextAndroidLine.setText( self.elementTextAndroidLine.text().upper() )
            self.elementTextAndroidLine.setValidator(self.validatorUpper)
            
    def onValueAndroid2TypeChanged(self):
        """
        On value changed
        """
        if self.valueAndroidCombo2.currentText() in [ "TEXT", "CACHE" ]:
            self.valueAndroidLine2.setValidator(self.validatorAll)
            
        if self.valueAndroidCombo2.currentText() == "ALIAS":
            self.valueAndroidLine2.setText( self.valueAndroidLine2.text().upper() )
            self.valueAndroidLine2.setValidator(self.validatorUpper)

    def addStep(self):
        """
        Add step
        """
        action = self.actionsAndroidComboBox.currentText()
        descr = self.descriptionAndroidLine.text()
        descr = unicode(descr).replace('"', '')
        
        signal = self.AddStep
        if self.cancelAndroidAction.isEnabled():
            signal = self.UpdateStep
            
        if self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_WAKUP, GuiSteps.ANDROID_UNLOCK, GuiSteps.ANDROID_REBOOT, 
                                                        GuiSteps.ANDROID_SLEEP, GuiSteps.ANDROID_FREEZE_ROTATION, GuiSteps.ANDROID_UNFREEZE_ROTATION, 
                                                        GuiSteps.ANDROID_BOOTLOADER, GuiSteps.ANDROID_RECOVERY, GuiSteps.ANDROID_NOTIFICATION, 
                                                        GuiSteps.ANDROID_SETTINGS, GuiSteps.ANDROID_DEVICEINFO, GuiSteps.ANDROID_GET_LOGS, 
                                                        GuiSteps.ANDROID_CLEAR_LOGS , GuiSteps.ANDROID_WAKEUP_UNLOCK, GuiSteps.ANDROID_LOCK,
                                                        GuiSteps.ANDROID_SLEEP_LOCK ]:
            signal.emit( str(action), unicode(descr), EMPTY_VALUE, {} )
            
        elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_TYPE_SHORTCUT]:
            shorcut = self.shortcutAndroidComboBox.currentText()
            signal.emit( str(action), unicode(descr), shorcut, {} )
            
        elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_TYPE_KEYCODE ]:
            code = self.codeAndroidLine.text()
            if not len(code):
                QMessageBox.warning(self, "Recording for Gui" , "Please to set a value!")
            else:
                signal.emit( str(action), unicode(descr), code, {} )
                
        elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_CLEAR_ELEMENT, GuiSteps.ANDROID_CLICK_ELEMENT, GuiSteps.ANDROID_LONG_CLICK_ELEMENT,
                                                            GuiSteps.ANDROID_EXIST_ELEMENT, GuiSteps.ANDROID_WAIT_ELEMENT, GuiSteps.ANDROID_TYPE_TEXT_ELEMENT,
                                                            GuiSteps.ANDROID_GET_TEXT_ELEMENT, GuiSteps.ANDROID_DRAG_ELEMENT, GuiSteps.ANDROID_WAIT_CLICK_ELEMENT ]:
            textAndroid = self.elementTextAndroidLine.text()
            descrAndroid = self.elementDescriptionAndroidLine.text()
            classAndroid = self.elementClassAndroidLine.text()
            ressourceAndroid = self.elementRessourceIdAndroidLine.text()
            packageAndroid = self.elementPackageAndroidLine.text()
            if not len(textAndroid) and not len(classAndroid) and not len(ressourceAndroid) and not len(packageAndroid) and not len(descrAndroid):
                QMessageBox.warning(self, "Recording for Gui" , "Please to set one value!")
            else:
                # read text from cache or not ?
                fromElCache = False
                if self.elementTextCombo.currentText() == "CACHE": fromElCache = True
                fromElAlias = False
                if self.elementTextCombo.currentText() == "ALIAS": fromElAlias = True
                        
                if self.actionsAndroidComboBox.currentText() == GuiSteps.ANDROID_TYPE_TEXT_ELEMENT:
                    newTextAndroid = self.valueAndroidLine2.text()
                    if not len(newTextAndroid):
                        QMessageBox.warning(self, "Recording for Gui" , "Please to set a text value!")
                    else:
                        # read text from cache or not ?
                        fromCache = False
                        if self.valueAndroidCombo2.currentText() == "CACHE": fromCache = True
                        fromAlias = False
                        if self.valueAndroidCombo2.currentText() == "ALIAS": fromAlias = True
                        
                        parameters = {'text': textAndroid, 'class': classAndroid, 'ressource': ressourceAndroid, 
                                        'package': packageAndroid, 'description': descrAndroid, 'new-text': newTextAndroid,
                                        'from-cache': fromCache, 'from-alias': fromAlias,
                                        'from-el-cache': fromElCache, 'from-el-alias': fromElAlias }
                        signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters )
                
                elif self.actionsAndroidComboBox.currentText() == GuiSteps.ANDROID_GET_TEXT_ELEMENT:       
                    # read text from cache or not ?
                    cacheKey = ''
                    toCache = True
                    cacheKey = self.valueTextCacheGlobalLine.text()
                        
                    parameters = {'text': textAndroid, 'class': classAndroid, 'ressource': ressourceAndroid, 
                                    'package': packageAndroid, 'description': descrAndroid, 'cache-key': cacheKey,
                                    'to-cache': toCache, 'from-el-cache': fromElCache, 'from-el-alias': fromElAlias }
                    signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters )
                    
                elif self.actionsAndroidComboBox.currentText() == GuiSteps.ANDROID_DRAG_ELEMENT:       
                    xAndroid = self.endxAndroidLine.text()
                    yAndroid = self.endyAndroidLine.text()
                    if not len(xAndroid) and not len(yAndroid):
                        QMessageBox.warning(self, "Recording for Gui" , "Please to set values!")
                    else:
                        parameters = {'text': textAndroid, 'class': classAndroid, 'ressource': ressourceAndroid, 
                                    'package': packageAndroid, 'description': descrAndroid,
                                    'from-el-cache': fromElCache, 'from-el-alias': fromElAlias,
                                    'x': xAndroid, 'y': yAndroid }
                        signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters )
                    
                else:

                    parameters = {'text': textAndroid, 'class': classAndroid, 'ressource': ressourceAndroid, 
                                    'package': packageAndroid, 'description': descrAndroid,
                                    'from-el-cache': fromElCache, 'from-el-alias': fromElAlias }
                    signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters )
                    
        elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_CLICK_POSITION ]:
            xAndroid = self.xAndroidLine.text()
            yAndroid = self.yAndroidLine.text()
            if not len(xAndroid) and not len(yAndroid):
                QMessageBox.warning(self, "Recording for Gui" , "Please to set values!")
            else:
                parameters = { 'x': xAndroid, 'y': yAndroid }
                signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters )
                
        elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_DRAG_ELEMENT, GuiSteps.ANDROID_DRAG_POSITION, 
                                                            GuiSteps.ANDROID_SWIPE_POSITION]:
            startXAndroid = self.startXAndroidLine.text()
            startYAndroid = self.startYAndroidLine.text()
            stopXAndroid = self.stopXAndroidLine.text()
            stopYAndroid = self.stopYAndroidLine.text()
            if not len(startXAndroid) and not len(startYAndroid) and not len(stopXAndroid) and not len(stopYAndroid):
                QMessageBox.warning(self, "Recording for Gui" , "Please to set values!")
            else:
                parameters = { 'start-x': startXAndroid, 'start-y': startYAndroid, 'stop-x': stopXAndroid, 'stop-y': stopYAndroid }
                signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters )

        elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_COMMAND, GuiSteps.ANDROID_SHELL, GuiSteps.ANDROID_RESET_APP,
                                                            GuiSteps.ANDROID_STOP_APP]:
            miscStr = self.valueAndroidLine.text()
            if not len(miscStr):
                QMessageBox.warning(self, "Recording for Gui" , "Please to set a value!")
            else:
                if self.actionsAndroidComboBox.currentText() == GuiSteps.ANDROID_COMMAND:
                    parameters = { 'cmd': miscStr }
                elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_RESET_APP, GuiSteps.ANDROID_STOP_APP ]:
                    parameters = { 'pkg': miscStr }
                else:
                    parameters = { 'sh': miscStr }
                signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters )
                
        else:
            signal.emit( str(action), unicode(descr), EMPTY_VALUE, {} )
        
    def cancelStep(self):
        """
        Cancel step
        """
        self.addAndroidAction.setText( "&Add" )
        buttonFont = QFont()
        buttonFont.setBold(False)
        self.addAndroidAction.setFont(buttonFont)
        
        self.cancelAndroidAction.setEnabled(False)
        
        self.CancelEdit.emit()
    
    def finalizeUpdate(self):
        """
        Finalize the update of a step
        """
        self.addAndroidAction.setText( "&Add Action" )
        
        buttonFont = QFont()
        buttonFont.setBold(False)
        self.addAndroidAction.setFont(buttonFont)
        self.cancelAndroidAction.setEnabled(False)
        
    def onActionAndroidChanged(self):
        """
        On action changed
        """
        descr = 'No description available!'
        i = 0
        for el in GuiSteps.ACTION_ANDROID_DESCR:
            if isinstance(el, dict):
                if self.actionsAndroidComboBox.currentText() in el:
                    descr = GuiSteps.ACTION_ANDROID_DESCR[i][self.actionsAndroidComboBox.currentText()]
                    break
            i += 1
        self.labelActionAndroidDescr.setText( "%s\n" % descr )

            
        if self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_TYPE_SHORTCUT ]:
            self.shortcutAndroidGroup.show()   
            self.codeAndroidGroup.hide()  
            self.elemenAndroidGroup.hide()
            self.startAndroidGroup.hide()
            self.xyAndroidGroup.hide()
            self.lineAndroidGroup.hide()
            self.line2AndroidGroup.hide()
            self.textToGlobalGroup.hide()
            self.endXyAndroidGroup.hide()
            
            self.arrowLabel.show()
            self.arrowLabel2.show()
            
        elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_TYPE_KEYCODE ]:
            self.codeAndroidGroup.show()   
            self.shortcutAndroidGroup.hide()    
            self.elemenAndroidGroup.hide()
            self.startAndroidGroup.hide()
            self.xyAndroidGroup.hide()
            self.lineAndroidGroup.hide()
            self.line2AndroidGroup.hide()
            self.textToGlobalGroup.hide()
            self.endXyAndroidGroup.hide()
            
            self.arrowLabel.show()
            self.arrowLabel2.show()
            
        elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_CLEAR_ELEMENT, GuiSteps.ANDROID_CLICK_ELEMENT, GuiSteps.ANDROID_LONG_CLICK_ELEMENT,
                                                            GuiSteps.ANDROID_EXIST_ELEMENT, GuiSteps.ANDROID_WAIT_ELEMENT, GuiSteps.ANDROID_WAIT_CLICK_ELEMENT ]:
            self.shortcutAndroidGroup.hide()   
            self.codeAndroidGroup.hide()       
            self.elemenAndroidGroup.show()
            self.startAndroidGroup.hide()
            self.xyAndroidGroup.hide()
            self.lineAndroidGroup.hide()
            self.line2AndroidGroup.hide()
            self.textToGlobalGroup.hide()
            self.endXyAndroidGroup.hide()
            
            self.arrowLabel.show()
            self.arrowLabel2.show()
            
        elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_DRAG_ELEMENT ]:
            self.shortcutAndroidGroup.hide()   
            self.codeAndroidGroup.hide()       
            self.elemenAndroidGroup.show()
            self.startAndroidGroup.hide()
            self.xyAndroidGroup.hide()
            self.lineAndroidGroup.hide()
            self.line2AndroidGroup.hide()
            self.textToGlobalGroup.hide()
            self.endXyAndroidGroup.show()
            
            self.arrowLabel.show()
            self.arrowLabel2.show()
            
        elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_GET_TEXT_ELEMENT ]:
            self.shortcutAndroidGroup.hide()   
            self.codeAndroidGroup.hide()       
            self.elemenAndroidGroup.show()
            self.startAndroidGroup.hide()
            self.xyAndroidGroup.hide()
            self.lineAndroidGroup.hide()
            self.line2AndroidGroup.hide()
            self.textToGlobalGroup.show()
            self.endXyAndroidGroup.hide()
            
            self.arrowLabel.show()
            self.arrowLabel2.show()
            
        elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_CLICK_POSITION ]:
            self.shortcutAndroidGroup.hide()   
            self.codeAndroidGroup.hide()       
            self.elemenAndroidGroup.hide()
            self.startAndroidGroup.hide()
            self.xyAndroidGroup.show()
            self.lineAndroidGroup.hide()
            self.line2AndroidGroup.hide()
            self.textToGlobalGroup.hide()
            self.endXyAndroidGroup.hide()
            
            self.arrowLabel.show()
            self.arrowLabel2.show()
            
        elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_DRAG_POSITION, GuiSteps.ANDROID_SWIPE_POSITION ]:
            self.shortcutAndroidGroup.hide()   
            self.codeAndroidGroup.hide()       
            self.elemenAndroidGroup.hide()
            self.startAndroidGroup.show()
            self.xyAndroidGroup.hide()
            self.lineAndroidGroup.hide()
            self.line2AndroidGroup.hide()
            self.textToGlobalGroup.hide()
            self.endXyAndroidGroup.hide()
            
            self.arrowLabel.show()
            self.arrowLabel2.show()
            
        elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_COMMAND, GuiSteps.ANDROID_SHELL, GuiSteps.ANDROID_RESET_APP, 
                                                            GuiSteps.ANDROID_STOP_APP  ]:
            self.shortcutAndroidGroup.hide()   
            self.codeAndroidGroup.hide()       
            self.elemenAndroidGroup.hide()
            self.startAndroidGroup.hide()
            self.xyAndroidGroup.hide()
            self.lineAndroidGroup.show()
            self.line2AndroidGroup.hide()
            self.textToGlobalGroup.hide()
            self.endXyAndroidGroup.hide()
             
            self.arrowLabel.show()
            self.arrowLabel2.show()
            
        elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_TYPE_TEXT_ELEMENT ]:
            self.shortcutAndroidGroup.hide()   
            self.codeAndroidGroup.hide()       
            self.elemenAndroidGroup.show()
            self.startAndroidGroup.hide()
            self.xyAndroidGroup.hide()
            self.lineAndroidGroup.hide()
            self.line2AndroidGroup.show()
            self.textToGlobalGroup.hide()
            self.endXyAndroidGroup.hide()
            
            self.arrowLabel.show()
            self.arrowLabel2.show()
            
        else:
            self.shortcutAndroidGroup.hide()   
            self.codeAndroidGroup.hide()       
            self.elemenAndroidGroup.hide()
            self.startAndroidGroup.hide()
            self.xyAndroidGroup.hide()
            self.lineAndroidGroup.hide()
            self.line2AndroidGroup.hide()
            self.textToGlobalGroup.hide()
            self.endXyAndroidGroup.hide()
            
            self.arrowLabel.hide()
            self.arrowLabel2.show()
            
    def setTimeout(self, timeout):
        """
        Set the timeout
        """
        self.optionsDialog.timeoutAndroidLine.setText(timeout)
        
    def getTimeout(self):
        """
        Return the timeout
        """
        return self.optionsDialog.timeoutAndroidLine.text()
        
    def getAgentName(self):
        """
        Get the agent name
        """
        return self.optionsDialog.agentNameLineAndroid.text()
        
    def getAgentList(self):
        """
        Return the agent list
        """
        return self.optionsDialog.agentsAndroidList
     
    def editStep(self, stepData):
        """
        Edit a step
        """
        self.addAndroidAction.setText( "&Update" )
        buttonFont = QFont()
        buttonFont.setBold(True)
        self.addAndroidAction.setFont(buttonFont)
        
        self.cancelAndroidAction.setEnabled(True)
            
        # set the current value for actions combo
        for i in xrange(self.actionsAndroidComboBox.count()):
            item_text = self.actionsAndroidComboBox.itemText(i)
            if unicode(stepData["action"]) == unicode(item_text):
                self.actionsAndroidComboBox.setCurrentIndex(i)
                break
        # and then refresh options
        self.onActionAndroidChanged()
        
        # finally fill all fields
        self.descriptionAndroidLine.setText( stepData["description"] )

        if self.actionsAndroidComboBox.currentText() == GuiSteps.ANDROID_COMMAND:
            self.valueAndroidLine.setText( stepData["parameters"]["cmd"] )
            
        if self.actionsAndroidComboBox.currentText() == GuiSteps.ANDROID_SHELL:
            self.valueAndroidLine.setText( stepData["parameters"]["sh"] )
            
        if self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_RESET_APP, GuiSteps.ANDROID_STOP_APP ]:
            self.valueAndroidLine.setText( stepData["parameters"]["pkg"] )
            
        if self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_CLEAR_ELEMENT, GuiSteps.ANDROID_TYPE_TEXT_ELEMENT, 
                                                          GuiSteps.ANDROID_CLICK_ELEMENT, GuiSteps.ANDROID_LONG_CLICK_ELEMENT,
                                                          GuiSteps.ANDROID_EXIST_ELEMENT, GuiSteps.ANDROID_WAIT_ELEMENT,
                                                          GuiSteps.ANDROID_GET_TEXT_ELEMENT, GuiSteps.ANDROID_DRAG_ELEMENT,
                                                          GuiSteps.ANDROID_WAIT_CLICK_ELEMENT ]:
                                                          
            self.elementTextAndroidLine.setText( "" )
            self.elementDescriptionAndroidLine.setText( "" )
            self.elementClassAndroidLine.setText( "" )
            self.elementRessourceIdAndroidLine.setText( "" )
            self.elementPackageAndroidLine.setText( "" )
            self.valueAndroidLine2.setText( "" )
            
            if "text" in stepData["parameters"]:
                if stepData["parameters"]["from-el-cache"]:
                    self.elementTextCombo.setCurrentIndex(INDEX_CACHE)
                    self.elementTextAndroidLine.setValidator(self.validatorAll)
                elif stepData["parameters"]["from-el-alias"]:
                    self.elementTextCombo.setCurrentIndex(INDEX_ALIAS)
                    self.elementTextAndroidLine.setValidator(self.validatorUpper) 
                else:
                    self.elementTextCombo.setCurrentIndex(INDEX_TEXT)
                    self.elementTextAndroidLine.setValidator(self.validatorAll)
                
                self.elementTextAndroidLine.setText ( stepData["parameters"]["text"] )

            if "description" in stepData["parameters"]:
                self.elementDescriptionAndroidLine.setText( stepData["parameters"]["description"] )
            if "class" in stepData["parameters"]:
                self.elementClassAndroidLine.setText( stepData["parameters"]["class"] )
            if "ressource" in stepData["parameters"]:
                self.elementRessourceIdAndroidLine.setText( stepData["parameters"]["ressource"] )
            if "package" in stepData["parameters"]:
                self.elementPackageAndroidLine.setText( stepData["parameters"]["package"] )
            if "new-text" in stepData["parameters"]:
                self.valueAndroidLine2.setText( stepData["parameters"]["new-text"] )

            if self.actionsAndroidComboBox.currentText() == GuiSteps.ANDROID_DRAG_ELEMENT:
                if "x" in stepData["parameters"]:
                    self.endxAndroidLine.setText( stepData["parameters"]["x"] )
                if "y" in stepData["parameters"]:
                    self.endyAndroidLine.setText( stepData["parameters"]["y"] )
                
            if self.actionsAndroidComboBox.currentText() == GuiSteps.ANDROID_TYPE_TEXT_ELEMENT:
                if stepData["parameters"]["from-cache"]:
                    self.valueAndroidCombo2.setCurrentIndex(INDEX_CACHE)
                    self.valueAndroidLine2.setValidator(self.validatorAll)
                elif stepData["parameters"]["from-alias"]:
                    self.valueAndroidCombo2.setCurrentIndex(INDEX_ALIAS)
                    self.valueAndroidLine2.setValidator(self.validatorUpper) 
                else:
                    self.valueAndroidCombo2.setCurrentIndex(INDEX_TEXT)
                    self.valueAndroidLine2.setValidator(self.validatorAll)
                
            if self.actionsAndroidComboBox.currentText() == GuiSteps.ANDROID_GET_TEXT_ELEMENT:
                self.valueTextCacheGlobalLine.setText ( stepData["parameters"]["cache-key"] )

        if self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_CLICK_POSITION]:
            if "x" in stepData["parameters"]:
                self.xAndroidLine.setText( stepData["parameters"]["x"] )
            if "y" in stepData["parameters"]:
                self.yAndroidLine.setText( stepData["parameters"]["y"] )
                
        if self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_DRAG_POSITION, GuiSteps.ANDROID_SWIPE_POSITION]:
            if "start-x" in stepData["parameters"]:
                self.startXAndroidLine.setText( stepData["parameters"]["start-x"] )
            if "start-y" in stepData["parameters"]:
                self.startYAndroidLine.setText( stepData["parameters"]["start-y"] )
            if "stop-x" in stepData["parameters"]:
                self.stopXAndroidLine.setText( stepData["parameters"]["stop-x"] )
            if "stop-y" in stepData["parameters"]:
                self.stopYAndroidLine.setText( stepData["parameters"]["stop-y"] )

        if self.actionsAndroidComboBox.currentText() == GuiSteps.ANDROID_TYPE_KEYCODE:
            self.codeAndroidLine.setText( stepData["misc"] )
            
        if self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_TYPE_SHORTCUT ]:
            # set default
            for i in xrange(self.shortcutAndroidComboBox.count()):
                item_text = self.shortcutAndroidComboBox.itemText(i)
                if unicode(stepData["misc"]) == unicode(item_text):
                    self.shortcutAndroidComboBox.setCurrentIndex(i)
                    break
示例#8
0
class WSystem(QWidget, Logger.ClassLogger):
    """
    System widget
    """
    # action, description, misc, parameters
    AddStep = pyqtSignal(str, str, str, dict)
    UpdateStep = pyqtSignal(str, str, str, dict)
    CancelEdit = pyqtSignal()

    def __init__(self, parent):
        """
        Constructor
        """
        QWidget.__init__(self)

        self.createActions()
        self.createWidgets()
        self.createToolbar()
        self.createConnections()

    def createActions(self):
        """
        Create qt actions
        """
        self.addAction = QPushButton(QIcon(":/add_black.png"), '&Add Action',
                                     self)
        self.addAction.setMinimumHeight(40)
        self.addAction.setMaximumWidth(150)
        self.cancelAction = QtHelper.createAction(self,
                                                  "&Cancel",
                                                  self.cancelStep,
                                                  icon=QIcon(":/undo.png"),
                                                  tip='Cancel update')
        self.cancelAction.setEnabled(False)

        self.optionsAction = QtHelper.createAction(
            self,
            "&",
            self.openOptions,
            icon=QIcon(":/system-small.png"),
            tip='System options')

    def openOptions(self):
        """
        Open options dialog
        """
        if self.optionsDialog.exec_() == QDialog.Accepted:
            pass

    def createWidgets(self):
        """
        Create qt widgets
        """
        self.optionsDialog = OptionsDialog(self)

        self.validatorUpper = ValidatorUpper(self)
        self.validatorAll = ValidatorAll(self)
        self.validatorInt = QIntValidator(self)

        self.actionsComboBox = QComboBox(self)
        self.actionsComboBox.setMinimumHeight(40)
        for i in xrange(len(GuiSteps.ACTION_SYSTEM_DESCR)):
            if not len(GuiSteps.ACTION_SYSTEM_DESCR[i]):
                self.actionsComboBox.insertSeparator(i + 1)
            else:
                el = GuiSteps.ACTION_SYSTEM_DESCR[i].keys()
                self.actionsComboBox.addItem(list(el)[0])

        self.labelActionDescr = QLabel(self)
        self.labelActionDescr.hide()
        self.descriptionLine = QLineEdit(self)
        self.descriptionLine.setPlaceholderText("Step purpose description")
        self.descriptionLine.hide()

        actionsLayout = QHBoxLayout()
        actionsLayout.addWidget(self.actionsComboBox)

        actionLayout1 = QGridLayout()
        actionLayout1.addLayout(actionsLayout, 0, 1)

        self.createWidgetSession()
        self.createWidgetText()
        self.createWidgetShortcut()
        self.createWidgetScreen()

        actionLayout2 = QGridLayout()
        actionLayout2.addWidget(self.sessionGroup, 1, 0)
        actionLayout2.addWidget(self.textGroup, 1, 0)
        actionLayout2.addWidget(self.shortcutGroup, 1, 0)
        actionLayout2.addWidget(self.screenGroup, 1, 0)

        font = QFont()
        font.setBold(True)

        labelAct = QLabel(self.tr("Action: "))
        labelAct.setFont(font)

        self.arrowLabel = QLabel("")
        self.arrowLabel.setPixmap(
            QPixmap(":/arrow-right.png").scaledToWidth(32))

        self.arrowLabel2 = QLabel("")
        self.arrowLabel2.setPixmap(
            QPixmap(":/arrow-right.png").scaledToWidth(32))

        layoutFinal = QHBoxLayout()
        layoutFinal.addWidget(labelAct)
        layoutFinal.addLayout(actionLayout1)
        layoutFinal.addWidget(self.arrowLabel)
        layoutFinal.addLayout(actionLayout2)
        layoutFinal.addWidget(self.arrowLabel2)
        layoutFinal.addWidget(self.addAction)

        layoutFinal.addStretch(1)
        self.setLayout(layoutFinal)

    def createToolbar(self):
        """
        Create toolbar
        """
        pass

    def createWidgetScreen(self):
        """
        Create screen widget
        """
        self.screenGroup = QGroupBox(self.tr(""))

        # text
        self.checkComboBox = QComboBox(self)
        self.checkComboBox.addItems([
            GuiSteps.OP_ANY, GuiSteps.OP_CONTAINS, GuiSteps.OP_NOTCONTAINS,
            GuiSteps.OP_REGEXP, GuiSteps.OP_NOTREGEXP, GuiSteps.OP_STARTSWITH,
            GuiSteps.OP_NOTSTARTSWITH, GuiSteps.OP_ENDSWITH,
            GuiSteps.OP_NOTENDSWITH
        ])

        self.screenLine = QLineEdit(self)
        self.screenLine.setMinimumWidth(300)
        self.screenLine.setEnabled(False)
        self.screenLine.hide()
        self.screenArea = QTextEdit(self)
        self.screenArea.setMinimumWidth(300)
        self.screenArea.setEnabled(False)

        self.screenCombo = QComboBox(self)
        self.screenCombo.addItems(LIST_TYPES)
        self.screenCombo.setEnabled(False)

        self.screenSaveCombo = QComboBox(self)
        self.screenSaveCombo.addItems(["VARIABLE", "CACHE"])
        self.screenSaveLine = QLineEdit(self)
        self.screenSaveLine.setMinimumWidth(300)
        self.screenSaveLine.setEnabled(False)

        mainTextlayout = QGridLayout()
        mainTextlayout.addWidget(QLabel(self.tr("Checking if the screen: ")),
                                 0, 0)
        mainTextlayout.addWidget(self.checkComboBox, 0, 1)
        mainTextlayout.addWidget(QLabel(self.tr("The value:")), 1, 0)
        mainTextlayout.addWidget(self.screenCombo, 1, 1)
        mainTextlayout.addWidget(self.screenLine, 2, 1)
        mainTextlayout.addWidget(self.screenArea, 2, 1)
        mainTextlayout.addWidget(QLabel(self.tr("And save the screen in:")), 0,
                                 2)
        mainTextlayout.addWidget(self.screenSaveCombo, 1, 2)
        mainTextlayout.addWidget(self.screenSaveLine, 2, 2)

        self.screenGroup.setLayout(mainTextlayout)
        self.screenGroup.hide()

    def createWidgetText(self):
        """
        Create text widget
        """
        self.textGroup = QGroupBox(self.tr(""))

        # text
        self.textLine = QLineEdit(self)
        self.textLine.setMinimumWidth(300)
        self.textCombo = QComboBox(self)
        self.textCombo.addItems(LIST_TYPES)

        mainTextlayout = QGridLayout()
        mainTextlayout.addWidget(QLabel(self.tr("Send the value:")), 0, 0)
        mainTextlayout.addWidget(self.textCombo, 0, 1)
        mainTextlayout.addWidget(self.textLine, 0, 2)

        self.textGroup.setLayout(mainTextlayout)
        self.textGroup.hide()

    def createWidgetShortcut(self):
        """
        Create shortcut widget
        """
        self.shortcutGroup = QGroupBox(self.tr(""))

        # text
        self.shortcutComboBox = QComboBox()
        self.shortcutComboBox.addItems([KEY_CTRLC, KEY_ENTER])
        self.shortcutComboBox.setMinimumWidth(300)

        mainTextlayout = QGridLayout()
        mainTextlayout.addWidget(QLabel(self.tr("Shortcut:")), 0, 0)
        mainTextlayout.addWidget(self.shortcutComboBox, 0, 1)

        self.shortcutGroup.setLayout(mainTextlayout)
        self.shortcutGroup.hide()

    def createWidgetSession(self):
        """
        Create session widget
        """
        self.sessionGroup = QGroupBox(self.tr(""))

        # login
        self.loginLine = QLineEdit(self)
        self.loginLine.setMinimumWidth(300)
        self.loginCombo = QComboBox(self)
        self.loginCombo.addItems(LIST_TYPES)

        # password
        self.pwdLine = QLineEdit(self)
        self.pwdLine.setMinimumWidth(300)
        self.pwdCombo = QComboBox(self)
        self.pwdCombo.addItems(LIST_TYPES)

        # ip
        self.ipLine = QLineEdit(self)
        self.ipLine.setMinimumWidth(300)
        self.ipCombo = QComboBox(self)
        self.ipCombo.addItems(LIST_TYPES)

        # port
        self.portLine = QLineEdit(self)
        self.portLine.setMinimumWidth(300)
        self.portLine.setText("22")
        self.portLine.setValidator(self.validatorInt)
        self.portCombo = QComboBox(self)
        self.portCombo.addItems(LIST_TYPES)

        # agent support
        self.useAgent = QCheckBox("Use with agent mode")

        mainTextlayout = QGridLayout()
        mainTextlayout.addWidget(QLabel(self.tr("Host:")), 0, 0)
        mainTextlayout.addWidget(self.ipCombo, 0, 1)
        mainTextlayout.addWidget(self.ipLine, 0, 2)
        mainTextlayout.addWidget(QLabel(self.tr("Port (optional):")), 1, 0)
        mainTextlayout.addWidget(self.portCombo, 1, 1)
        mainTextlayout.addWidget(self.portLine, 1, 2)
        mainTextlayout.addWidget(QLabel(self.tr("Login:"******"Password:"******"""
        Create qt connections
        """
        self.actionsComboBox.currentIndexChanged.connect(self.onActionChanged)
        self.addAction.clicked.connect(self.addStep)

        self.ipCombo.currentIndexChanged.connect(self.onIpTypeChanged)
        self.portCombo.currentIndexChanged.connect(self.onPortTypeChanged)
        self.loginCombo.currentIndexChanged.connect(self.onLoginTypeChanged)
        self.pwdCombo.currentIndexChanged.connect(self.onPwdTypeChanged)

        self.textCombo.currentIndexChanged.connect(self.onTextTypeChanged)
        self.screenCombo.currentIndexChanged.connect(self.onScreenTypeChanged)
        self.checkComboBox.currentIndexChanged.connect(
            self.onScreenOperatorChanged)
        self.screenSaveCombo.currentIndexChanged.connect(
            self.onScreenSaveChanged)

    def pluginDataAccessor(self):
        """
        Return data to plugin
        """
        return {"data": ""}

    def onPluginImport(self, dataJson):
        """
        Received data from plugins
        """
        if "steps" not in dataJson:
            QMessageBox.warning(self, "Assistant Automation", "bad import")
            return

        if not isinstance(dataJson['steps'], list):
            QMessageBox.warning(self, "Assistant Automation", "bad import")
            return

        if not ('ip' in dataJson and 'login' in dataJson
                and 'password' in dataJson):
            QMessageBox.warning(self, "Assistant Automation", "bad import")
            return

        # emit open session
        parameters = {
            'dest-ip': dataJson['ip'],
            'dest-port': 22,
            'login': dataJson['login'],
            'password': dataJson['password'],
            'from-cache-ip': False,
            'from-alias-ip': False,
            'from-cache-port': False,
            'from-alias-port': False,
            'from-cache-login': False,
            'from-alias-login': False,
            'from-cache-pwd': False,
            'from-alias-pwd': False,
            'agent-support': False
        }
        self.AddStep.emit(GuiSteps.SYSTEM_SESSION, EMPTY_VALUE, EMPTY_VALUE,
                          parameters)

        for stp in dataJson['steps']:
            if isinstance(stp, dict):

                # new in v16
                fromCache = False
                fromAlias = False
                if "type-value" in stp:
                    if stp["type-value"].lower() == "cache": fromCache = True
                    if stp["type-value"].lower() == "alias": fromAlias = True
                # end of new

                if stp["action-name"] == "SEND":
                    parameters = {
                        'text': stp["action-value"],
                        'from-cache': fromCache,
                        'from-alias': fromAlias
                    }
                    self.AddStep.emit(GuiSteps.SYSTEM_TEXT, EMPTY_VALUE,
                                      EMPTY_VALUE, parameters)
                elif stp["action-name"] == "EXPECT":
                    op = "Contains"
                    if stp["action-type"] == "REGEX":
                        op = "RegEx"
                    parameters = {
                        'value': stp["action-value"],
                        'from-cache': fromCache,
                        'from-alias': fromAlias,
                        'operator': op,
                        'to-cache': False,
                        'cache-key': ''
                    }
                    self.AddStep.emit(GuiSteps.SYSTEM_CHECK_SCREEN,
                                      EMPTY_VALUE, EMPTY_VALUE, parameters)
                else:
                    QMessageBox.warning(
                        self, "Assistant Automation",
                        "action not yet supported: %s" % stp["action-name"])

        # close
        self.AddStep.emit(GuiSteps.SYSTEM_CLOSE, EMPTY_VALUE, EMPTY_VALUE, {})

    def onScreenOperatorChanged(self):
        """
        On screen operator changed
        """
        if self.checkComboBox.currentText() == GuiSteps.OP_ANY:
            self.screenLine.setEnabled(False)
            self.screenArea.setEnabled(False)
            self.screenCombo.setEnabled(False)
        else:
            self.screenLine.setEnabled(True)
            self.screenArea.setEnabled(True)
            self.screenCombo.setEnabled(True)

    def onScreenSaveChanged(self):
        """
        On screen save changed
        """
        if self.screenSaveCombo.currentText() == "VARIABLE":
            self.screenSaveLine.setEnabled(False)
        else:
            self.screenSaveLine.setEnabled(True)

    def onScreenTypeChanged(self):
        """
        On screen type changed
        """
        if self.screenCombo.currentText() in ["TEXT"]:
            self.screenArea.show()
            self.screenLine.hide()
        else:
            self.screenLine.show()
            self.screenArea.hide()
            if self.screenCombo.currentText() in ["CACHE"]:
                self.screenLine.setValidator(self.validatorAll)

            if self.screenCombo.currentText() == "ALIAS":
                self.screenLine.setText(self.screenLine.text().upper())
                self.screenLine.setValidator(self.validatorUpper)

    def onTextTypeChanged(self):
        """
        On text type changed
        """
        if self.textCombo.currentText() in ["TEXT", "CACHE"]:
            self.textLine.setValidator(self.validatorAll)

        if self.textCombo.currentText() == "ALIAS":
            self.textLine.setText(self.textLine.text().upper())
            self.textLine.setValidator(self.validatorUpper)

    def onLoginTypeChanged(self):
        """
        On login type changed
        """
        if self.loginCombo.currentText() in ["TEXT", "CACHE"]:
            self.loginLine.setValidator(self.validatorAll)

        if self.loginCombo.currentText() == "ALIAS":
            self.loginLine.setText(self.loginLine.text().upper())
            self.loginLine.setValidator(self.validatorUpper)

    def onPwdTypeChanged(self):
        """
        On password type changed
        """
        if self.pwdCombo.currentText() in ["TEXT", "CACHE"]:
            self.pwdLine.setValidator(self.validatorAll)

        if self.pwdCombo.currentText() == "ALIAS":
            self.pwdLine.setText(self.pwdLine.text().upper())
            self.pwdLine.setValidator(self.validatorUpper)

    def onIpTypeChanged(self):
        """
        On ip type changed
        """
        if self.ipCombo.currentText() in ["TEXT", "CACHE"]:
            self.ipLine.setValidator(self.validatorAll)

        if self.ipCombo.currentText() == "ALIAS":
            self.ipLine.setText(self.ipLine.text().upper())
            self.ipLine.setValidator(self.validatorUpper)

    def onPortTypeChanged(self):
        """
        On port type changed
        """
        if self.portCombo.currentText() in ["TEXT"]:
            self.portLine.setText("22")
            self.portLine.setValidator(self.validatorInt)

        if self.portCombo.currentText() in ["CACHE"]:
            self.portLine.setValidator(self.validatorAll)

        if self.portCombo.currentText() == "ALIAS":
            self.portLine.setText(self.portLine.text().upper())
            self.portLine.setValidator(self.validatorUpper)

    def onActionChanged(self):
        """
        On action changed
        """
        descr = 'No description available!'
        i = 0
        for el in GuiSteps.ACTION_SYSTEM_DESCR:
            if isinstance(el, dict):
                if self.actionsComboBox.currentText() in el:
                    descr = GuiSteps.ACTION_SYSTEM_DESCR[i][
                        self.actionsComboBox.currentText()]
                    break
            i += 1
        self.labelActionDescr.setText("%s\n" % descr)

        if self.actionsComboBox.currentText() in [GuiSteps.SYSTEM_SESSION]:
            self.sessionGroup.show()
            self.textGroup.hide()
            self.shortcutGroup.hide()
            self.screenGroup.hide()

            self.arrowLabel.show()
            self.arrowLabel2.show()

        elif self.actionsComboBox.currentText() in [GuiSteps.SYSTEM_CLOSE]:
            self.sessionGroup.hide()
            self.textGroup.hide()
            self.shortcutGroup.hide()
            self.screenGroup.hide()

            self.arrowLabel.hide()
            self.arrowLabel2.show()

        elif self.actionsComboBox.currentText() in [
                GuiSteps.SYSTEM_CLEAR_SCREEN
        ]:
            self.sessionGroup.hide()
            self.textGroup.hide()
            self.shortcutGroup.hide()
            self.screenGroup.hide()

            self.arrowLabel.hide()
            self.arrowLabel2.show()

        elif self.actionsComboBox.currentText() in [GuiSteps.SYSTEM_TEXT]:
            self.sessionGroup.hide()
            self.textGroup.show()
            self.shortcutGroup.hide()
            self.screenGroup.hide()

            self.arrowLabel.show()
            self.arrowLabel2.show()

        elif self.actionsComboBox.currentText() in [GuiSteps.SYSTEM_SHORTCUT]:
            self.sessionGroup.hide()
            self.textGroup.hide()
            self.shortcutGroup.show()
            self.screenGroup.hide()

            self.arrowLabel.show()
            self.arrowLabel2.show()

        elif self.actionsComboBox.currentText() in [
                GuiSteps.SYSTEM_CHECK_SCREEN
        ]:
            self.sessionGroup.hide()
            self.textGroup.hide()
            self.shortcutGroup.hide()
            self.screenGroup.show()

            self.arrowLabel.show()
            self.arrowLabel2.show()

        else:
            self.sessionGroup.hide()
            self.textGroup.hide()
            self.shortcutGroup.hide()
            self.screenGroup.hide()

            self.arrowLabel.hide()
            self.arrowLabel2.hide()

    def addStep(self):
        """
        Add step
        """
        action = self.actionsComboBox.currentText()
        descr = self.descriptionLine.text()
        descr = unicode(descr).replace('"', '')

        signal = self.AddStep
        if self.cancelAction.isEnabled():
            signal = self.UpdateStep

        if action in [GuiSteps.SYSTEM_SESSION]:
            fromCacheIp = False
            if self.ipCombo.currentText() == "CACHE": fromCacheIp = True
            fromAliasIp = False
            if self.ipCombo.currentText() == "ALIAS": fromAliasIp = True

            fromCachePort = False
            if self.portCombo.currentText() == "CACHE": fromCachePort = True
            fromAliasPort = False
            if self.portCombo.currentText() == "ALIAS": fromAliasPort = True

            fromCacheLogin = False
            if self.loginCombo.currentText() == "CACHE": fromCacheLogin = True
            fromAliasLogin = False
            if self.loginCombo.currentText() == "ALIAS": fromAliasLogin = True

            fromCachePwd = False
            if self.pwdCombo.currentText() == "CACHE": fromCachePwd = True
            fromAliasPwd = False
            if self.pwdCombo.currentText() == "ALIAS": fromAliasPwd = True

            newIp = self.ipLine.text()
            if not len(newIp):
                QMessageBox.warning(self, "Assistant",
                                    "Please to provide a ip!")
                return

            newPort = self.portLine.text()
            if not len(newPort):
                QMessageBox.warning(self, "Assistant",
                                    "Please to provide a port!")
                return

            newLogin = self.loginLine.text()
            if not len(newLogin):
                QMessageBox.warning(self, "Assistant",
                                    "Please to provide a login!")
                return

            newPwd = self.pwdLine.text()
            agentSupport = "False"
            if self.useAgent.isChecked(): agentSupport = "True"

            parameters = {
                'dest-ip': newIp,
                'dest-port': newPort,
                'login': newLogin,
                'password': newPwd,
                'from-cache-ip': fromCacheIp,
                'from-alias-ip': fromAliasIp,
                'from-cache-port': fromCachePort,
                'from-alias-port': fromAliasPort,
                'from-cache-login': fromCacheLogin,
                'from-alias-login': fromAliasLogin,
                'from-cache-pwd': fromCachePwd,
                'from-alias-pwd': fromAliasPwd,
                'agent-support': agentSupport
            }
            signal.emit(str(action), unicode(descr), EMPTY_VALUE, parameters)

        elif action in [GuiSteps.SYSTEM_CLOSE]:
            signal.emit(str(action), unicode(descr), EMPTY_VALUE, {})

        elif action in [GuiSteps.SYSTEM_CLEAR_SCREEN]:
            signal.emit(str(action), unicode(descr), EMPTY_VALUE, {})

        elif action in [GuiSteps.SYSTEM_TEXT]:
            fromCache = False
            if self.textCombo.currentText() == "CACHE": fromCache = True
            fromAlias = False
            if self.textCombo.currentText() == "ALIAS": fromAlias = True

            newText = self.textLine.text()
            if not len(newText):
                QMessageBox.warning(self, "Assistant",
                                    "Please to provide text!")
                return
            parameters = {
                'text': newText,
                'from-cache': fromCache,
                'from-alias': fromAlias
            }
            signal.emit(str(action), unicode(descr), EMPTY_VALUE, parameters)

        elif action in [GuiSteps.SYSTEM_SHORTCUT]:

            newShortcut = self.shortcutComboBox.currentText()
            parameters = {'shortcut': newShortcut}
            signal.emit(str(action), unicode(descr), EMPTY_VALUE, parameters)

        elif action in [GuiSteps.SYSTEM_CHECK_SCREEN]:
            op = self.checkComboBox.currentText()
            fromCache = False
            if self.screenCombo.currentText() == "CACHE": fromCache = True
            fromAlias = False
            if self.screenCombo.currentText() == "ALIAS": fromAlias = True

            toCache = False
            if self.screenSaveCombo.currentText() == "CACHE": toCache = True
            keyCache = self.screenSaveLine.text()

            newText = ""
            if op != GuiSteps.OP_ANY:
                if fromCache or fromAlias:
                    newText = self.screenLine.text()
                else:
                    newText = self.screenArea.toPlainText()
                if not len(newText):
                    QMessageBox.warning(self, "Assistant",
                                        "Please to provide value to search!")
                    return

            parameters = {
                'value': newText,
                'from-cache': fromCache,
                'from-alias': fromAlias,
                'operator': op,
                'to-cache': toCache,
                'cache-key': keyCache
            }
            signal.emit(str(action), unicode(descr), EMPTY_VALUE, parameters)

        else:
            signal.emit(str(action), unicode(descr), EMPTY_VALUE, {})

    def cancelStep(self):
        """
        Cancel step
        """
        self.addAction.setText("&Add")

        buttonFont = QFont()
        buttonFont.setBold(False)
        self.addAction.setFont(buttonFont)
        self.cancelAction.setEnabled(False)

        self.CancelEdit.emit()

    def finalizeUpdate(self):
        """
        Finalize the update of the step
        """
        self.addAction.setText("&Add Action")

        buttonFont = QFont()
        buttonFont.setBold(False)
        self.addAction.setFont(buttonFont)
        self.cancelAction.setEnabled(False)

    def editStep(self, stepData):
        """
        Edit step
        """
        self.addAction.setText("&Update")
        buttonFont = QFont()
        buttonFont.setBold(True)
        self.addAction.setFont(buttonFont)

        self.cancelAction.setEnabled(True)

        # set the current value for actions combo
        for i in xrange(self.actionsComboBox.count()):
            item_text = self.actionsComboBox.itemText(i)
            if unicode(stepData["action"]) == unicode(item_text):
                self.actionsComboBox.setCurrentIndex(i)
                break

        # and then refresh options
        self.onActionChanged()

        # finally fill all fields
        self.descriptionLine.setText(stepData["description"])

        if self.actionsComboBox.currentText() in [GuiSteps.SYSTEM_SESSION]:
            self.ipLine.setText(stepData["parameters"]["dest-ip"])
            self.portLine.setText("%s" % stepData["parameters"]["dest-port"])
            self.loginLine.setText(stepData["parameters"]["login"])
            self.pwdLine.setText(stepData["parameters"]["password"])

            if stepData["parameters"]["from-cache-ip"]:
                self.ipLine.setValidator(self.validatorAll)
                self.ipCombo.setCurrentIndex(INDEX_CACHE)
            elif stepData["parameters"]["from-alias-ip"]:
                self.ipLine.setValidator(self.validatorUpper)
                self.ipCombo.setCurrentIndex(INDEX_ALIAS)
            else:
                self.ipLine.setValidator(self.validatorAll)
                self.ipCombo.setCurrentIndex(INDEX_TEXT)

            if stepData["parameters"]["from-cache-port"]:
                self.portLine.setValidator(self.validatorAll)
                self.portCombo.setCurrentIndex(INDEX_CACHE)
            elif stepData["parameters"]["from-alias-port"]:
                self.portLine.setValidator(self.validatorUpper)
                self.portCombo.setCurrentIndex(INDEX_ALIAS)
            else:
                self.portLine.setValidator(self.validatorInt)
                self.portCombo.setCurrentIndex(INDEX_TEXT)

            if stepData["parameters"]["from-cache-login"]:
                self.loginLine.setValidator(self.validatorAll)
                self.loginCombo.setCurrentIndex(INDEX_CACHE)
            elif stepData["parameters"]["from-alias-login"]:
                self.loginLine.setValidator(self.validatorUpper)
                self.loginCombo.setCurrentIndex(INDEX_ALIAS)
            else:
                self.loginLine.setValidator(self.validatorAll)
                self.loginCombo.setCurrentIndex(INDEX_TEXT)

            if stepData["parameters"]["from-cache-pwd"]:
                self.pwdLine.setValidator(self.validatorAll)
                self.pwdCombo.setCurrentIndex(INDEX_CACHE)
            elif stepData["parameters"]["from-alias-pwd"]:
                self.pwdLine.setValidator(self.validatorUpper)
                self.pwdCombo.setCurrentIndex(INDEX_ALIAS)
            else:
                self.pwdLine.setValidator(self.validatorAll)
                self.pwdCombo.setCurrentIndex(INDEX_TEXT)

        if self.actionsComboBox.currentText() in [GuiSteps.SYSTEM_CLOSE]:
            pass

        if self.actionsComboBox.currentText() in [
                GuiSteps.SYSTEM_CLEAR_SCREEN
        ]:
            pass

        if self.actionsComboBox.currentText() in [GuiSteps.SYSTEM_TEXT]:

            if stepData["parameters"]["from-cache"]:
                self.textLine.setValidator(self.validatorAll)
                self.textCombo.setCurrentIndex(INDEX_CACHE)
            elif stepData["parameters"]["from-alias"]:
                self.textLine.setValidator(self.validatorUpper)
                self.textCombo.setCurrentIndex(INDEX_ALIAS)
            else:
                self.textLine.setValidator(self.validatorAll)
                self.textCombo.setCurrentIndex(INDEX_TEXT)

            self.textLine.setText(stepData["parameters"]["text"])

        if self.actionsComboBox.currentText() in [GuiSteps.SYSTEM_SHORTCUT]:

            for i in xrange(self.shortcutComboBox.count()):
                item_text = self.shortcutComboBox.itemText(i)
                if unicode(stepData["parameters"]["shortcut"]) == unicode(
                        item_text):
                    self.shortcutComboBox.setCurrentIndex(i)
                    break

        if self.actionsComboBox.currentText() in [
                GuiSteps.SYSTEM_CHECK_SCREEN
        ]:

            if stepData["parameters"]["from-cache"]:
                self.screenLine.setValidator(self.validatorAll)
                self.screenCombo.setCurrentIndex(INDEX_CACHE)
                self.screenLine.setText(stepData["parameters"]["value"])
            elif stepData["parameters"]["from-alias"]:
                self.screenLine.setValidator(self.validatorUpper)
                self.screenCombo.setCurrentIndex(INDEX_ALIAS)
                self.screenLine.setText(stepData["parameters"]["value"])
            else:
                self.screenCombo.setCurrentIndex(INDEX_TEXT)
                self.screenArea.setPlainText(stepData["parameters"]["value"])

            for i in xrange(self.checkComboBox.count()):
                item_text = self.checkComboBox.itemText(i)
                if unicode(stepData["parameters"]["operator"]) == unicode(
                        item_text):
                    self.checkComboBox.setCurrentIndex(i)
                    break

            if stepData["parameters"]["to-cache"]:
                self.screenSaveCombo.setCurrentIndex(1)
                self.screenSaveLine.setText(
                    stepData["parameters"]["cache-key"])
            else:
                self.screenSaveCombo.setCurrentIndex(0)

    def getTimeout(self):
        """
        Return timeout value
        """
        return self.optionsDialog.timeoutLine.text()

    def setTimeout(self, timeout):
        """
        Set the timeout
        """
        return self.optionsDialog.timeoutLine.setText(timeout)

    def getAgentName(self):
        """
        Return the agent name
        """
        return self.optionsDialog.agentNameLine.text()

    def getAgentList(self):
        """
        Return the agent list
        """
        return self.optionsDialog.agentsList
示例#9
0
class PluginWidget(QWidget):

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.pluginMetadata = {}

        # Main layout
        self.mainLayout = QVBoxLayout()
        self.setLayout(self.mainLayout)

        # Define size used for the underlines
        self.underlineSize = QSize()
        self.underlineSize.setHeight(1)

        # Define font used for headers
        self.font = QFont()
        self.font.setPointSize(11)
        self.font.setBold(True)
        self.font.setUnderline(True)

        # Plugins Description
        self.pluginDescription = QLabel()
        self.pluginDescription.setText("Click a plugin to see more information." +
            " Plugins can be configured from the Recording tab. \n")
        self.pluginDescription.setWordWrap(True)

        # Plugins GroupBox
        self.pluginLayout = QVBoxLayout()
        self.pluginGroupBox = QGroupBox("Plugins extend the functionality of Freeseer")
        self.pluginGroupBox.setLayout(self.pluginLayout)
        self.pluginLayout.insertWidget(0, self.pluginDescription)
        self.mainLayout.insertWidget(0, self.pluginGroupBox)

        # Plugins list
        self.list = QTreeWidget()
        self.list.setHeaderHidden(True)
        self.list.headerItem().setText(0, "1")
        self.pluginLayout.insertWidget(1, self.list)

        # Details
        self.detailPane = QGroupBox()
        self.detailLayout = QVBoxLayout()
        self.detailPane.setLayout(self.detailLayout)
        self.detailPaneDesc = QLabel()
        self.detailPaneDesc.setWordWrap(True)
        self.detailLayout.addWidget(self.detailPaneDesc)
        self.pluginLayout.insertWidget(2, self.detailPane)

        self.list.itemSelectionChanged.connect(self.treeViewSelect)

    def treeViewSelect(self):
        item = self.list.currentItem()
        key = str(item.text(0))
        if key in self.pluginMetadata.keys():
            self.showDetails(key)
        else:
            self.hideDetails()

    def showDetails(self, key):
        self.detailPane.setTitle(key)
        self.detailPaneDesc.setText(self.pluginMetadata[key])
        self.detailPane.show()

    def hideDetails(self):
        self.detailPane.hide()

    def getWidgetPlugin(self, plugin, plugin_category, plugman):
        plugin_name = plugin.plugin_object.get_name()
        item = QTreeWidgetItem()

        # Display Plugin's meta data in a tooltip
        pluginDetails = """
        <table>
        <tr>
            <td>Name: </td>
            <td><b>%(name)s</b></td>
        </tr>
        <tr>
            <td>Version: </td>
            <td><b>%(version)s</b></td>
        <tr>
            <td>Author: </td>
            <td><b>%(author)s</b></td>
        </tr>
        <tr>
            <td>Website: </td>
            <td><b>%(website)s</b></td>
        </tr>
        <tr>
            <td>Description: </td>
            <td><b>%(description)s</b></td>
        </tr>
        </table>
        """ % {"name": plugin.name,
               "version": plugin.version,
               "author": plugin.author,
               "website": plugin.website,
               "description": plugin.description}

        # put the details in the hash table
        self.pluginMetadata[plugin_name] = pluginDetails

        item.setText(0, plugin_name)
        return item
示例#10
0
文件: gui.py 项目: skudervatchi/Dzik
class urlgroup(QGroupBox):
    def __init__(self, parent=None):
        super(urlgroup, self).__init__(parent)
        self.setGeometry(10,30,500,80)
        self.setObjectName('urlgroup')
        self.urlbar = QLineEdit()
        self.urlbar.setObjectName('urlbar')
        self.urlbar.setText('Collez votre URL içi')
        self.urlbar.setStyleSheet('font-weight:lighter;color:gray;')
        self.urlbar.show()
        self.parsebutton = QPushButton('Go !!')
        self.parsebutton.setObjectName('parsebutton')
        self.parsebutton.show()
        layout = QBoxLayout(QBoxLayout.LeftToRight, self)
        layout.addWidget(self.urlbar)
        layout.addWidget(self.parsebutton)
        self.show()
        self.group2 = QGroupBox(parent)
        self.group2.setObjectName('core')
        self.group2.setGeometry(10,120,500,280)
        self.group2.show()
        self.group3 = QGroupBox(self.group2)
        self.group3.setObjectName('albuminfos')
        self.group3.setGeometry(10,15,200,245)
        self.group3.show()
        self.itemlist = QListWidget(self.group2)
        self.itemlist.setGeometry(250,15,230,245)
        self.itemlist.show()
        self.dlgroup = QGroupBox(parent)
        self.dlgroup.setObjectName('dlgroup')
        self.dlgroup.setGeometry(10,420,500,100)
        self.dlgroup.show()
        self.dlgroup.dlbutton = QPushButton('Download', self.dlgroup)
        self.dlgroup.dlbutton.setObjectName('dlbutton')
        self.dlgroup.dlbutton.move(10,20)
        self.dlgroup.dlbutton.show()
        self.dlgroup.progressbar = QProgressBar(self.dlgroup)
        self.dlgroup.progressbar.setObjectName('progressbar')
        self.dlgroup.progressbar.setGeometry(100,21,380,21)
        self.dlgroup.progressbar.show()
        self.dlgroup.dlinfos = QLabel(self.dlgroup)
        self.dlgroup.dlinfos.setGeometry(100,70,200,21)
        self.dlgroup.dlinfos.show()
        self.dlgroup.dledfile = QLabel(self.dlgroup)
        self.dlgroup.dledfile.setGeometry(300,70,200,21)
        self.dlgroup.dledfile.show()
        self.dlgroup.dlto = QLineEdit('C:\\', self.dlgroup)
        self.dlgroup.dlto.setGeometry(100,50,350,21)
        self.dlgroup.dlto.show()
        self.dlgroup.dlto.changebt = QToolButton(self.dlgroup)
        self.dlgroup.dlto.changebt.setObjectName('dltobt')
        self.dlgroup.dlto.changebt.setGeometry(10,50,75,21)
        self.dlgroup.dlto.changebt.setText('To')
        self.dlgroup.dlto.changebt.show()
        self.dlgroup.dlto.openf = QPushButton('Open', self.dlgroup)
        self.dlgroup.dlto.openf.setGeometry(455,50,35,21)
        self.dlgroup.dlto.openf.setObjectName('openfolder')
        self.dlgroup.dlto.openf.show()  
        self.album = QLabel(self.group3)
        self.artist = QLabel(self.group3)
        self.year = QLabel(self.group3)
        self.tracks = QLabel(self.group3)
        self.coverart = QLabel(self.group3)
        self.urlbar.setFocus(True)
        self.connect(self.parsebutton, SIGNAL('clicked()'), self.parseclicked )
        self.connect(self.dlgroup.dlbutton, SIGNAL('clicked()'), self.launchdl)
        self.connect(self.dlgroup.dlto.changebt, SIGNAL('clicked()'), self.changedir)
        self.connect(self.dlgroup.dlto.openf, SIGNAL('clicked()'), self.openfolder)
        
    def parseclicked(self):
        self.itemlist.clear()
        url = str(self.urlbar.text())
        self.infos = getsonglist(url)
        if (self.infos == 'connexion impossible') or (self.infos == 'unsupported'):
            self.error = QMessageBox()
            if self.infos == 'connexion impossible':
                self.error.setText('Connexion Impossible !')
            elif self.infos == 'unsupported':
                self.error.setText('Site Unsupported !!')
            self.error.setWindowTitle('Erreur!')
            self.error.setIcon(QMessageBox.Warning)
            self.icon = QIcon('images/mainwindowicon.png')
            self.error.setWindowIcon(self.icon)
            self.error.exec_()
        else:
            self.artist.setText('Artiste : ' + self.infos['artist'])
            self.artist.move(40,175)
            self.artist.show()
            self.album.setText('Album : ' + self.infos['albumname'])
            self.album.move(40,190)
            self.album.show()
            try:
                self.year.setText('Annee : ' + self.infos['year'])
                
            except KeyError:
                self.year.setText('Annee : ' + 'N/A')
            self.year.move(40,205)
            self.year.show()
            self.tracks.setText('Tracks : ' + str(self.infos['tracks']))
            self.tracks.move(40,220)
            self.tracks.show()
            coverartpix = QPixmap(self.infos['coverart'])
            coverartpix = coverartpix.scaled(178,135,)
            self.coverart.setPixmap(coverartpix) 
            self.coverart.move(10,10)
            self.coverart.show()
            self.list2 = []
            for item in self.infos['titles']:
                item = tracklistitems(item)
                self.list2.append(item)
            for item in self.list2:
                self.itemlist.addItem(item)
                
            
            
            

    def launchdl(self):
        if self.dlgroup.dlbutton.text() == 'Download':
            try:
                self.itemlist.item(self.currentitem).setText(self.text)
            except:
                pass
            self.dlgroup.dlbutton.setText('Stop')
            rmtree('tmpimg', True)
            i= 0
            dllist = []
            for item in self.list2:
                if item.eligible() =='Checked':
                    dllist.append(i)
                i= i+1
            self.stritemlist = []
            for i in range(0,self.infos['tracks']):
                #print i
                #print self.itemlist.item(i).text()
                #TODO: hamida album breaks, recheck regexes
                self.stritemlist.append(str(self.itemlist.item(i).text()))
            dlto =  self.dlgroup.dlto.text()
            self.thread = dlThread(dllist, self.infos, dlto, self.stritemlist) 
            self.connect(self.thread, SIGNAL('progress(PyQt_PyObject)'), self.updateProgress)
            self.connect(self.thread, SIGNAL('dledfile(PyQt_PyObject)'), self.updateDlednow)
            self.thread.start()
        else:
            self.dlgroup.dlbutton.setText('Download')
            self.thread.terminate()
      
    def updateProgress(self, progress):
        self.dlgroup.progressbar.setValue(progress['bar'])
        self.dlgroup.dlinfos.setText(progress['info'])
        self.text = self.stritemlist[progress['item']]
        self.currentitem = progress['item']
        self.percent = str(progress['bar']) + ' % - '
        self.percent = QString(self.percent)
        self.dlingicon = QIcon('images/dling.png')
        self.doneicon = QIcon('images/done.png')
        self.itemlist.item(progress['item']).setIcon(self.dlingicon)
        self.itemlist.item(progress['item']).setText(self.percent + self.text)
        if progress['bar'] >= 98:
            self.itemlist.item(progress['item']).setIcon(self.doneicon)
            self.itemlist.item(progress['item']).setText(self.text)
            self.itemlist.item(progress['item']).setCheckState(Qt.Unchecked)
            self.itemlist.item(progress['item']).setFlags(Qt.ItemIsEnabled | Qt.ItemIsEditable | Qt.ItemIsSelectable)
            
    def updateDlednow(self, dledfile):
        self.dlgroup.dledfile.setText(dledfile)

    
    def changedir(self):
        self.dir = QFileDialog.getExistingDirectory()
        self.dlgroup.dlto.setText(self.dir + '/')
    def openfolder(self):
        startfile(self.dlgroup.dlto.text())
        
    def stopdl(self):
        pass
示例#11
0
class SessionsManager(QDialog):
    def __init__(self, n, parent=None):
        super(SessionsManager, self).__init__(parent)
        self.par = n
        #main
        title = Settingz().positions(30)
        self.titleID = title['id']
        self.titlePage = title['page']
        self.titleName = title['name']
        self.titleSub = title['subID']
        self.titleIcon = title['icon']
        self.pagetitle = self.titlePage
        #stylesheet
        stylesheet = Valid().background() + Valid().font()
        treeStyleSheet = Valid().treez()

        self.groupBox1 = QGroupBox(self.titleName)
        self.groupBox2 = QGroupBox('Add')

        #items
        self.tree = QTreeWidget()
        self.tree.setHeaderLabel("Choose " + self.titleName)
        #tree.setItemDelegate(Delegate())
        self.tree.setItemDelegate(Delegates())
        self.tree.headerItem().setText(0, 'Name')
        self.tree.setStyleSheet(treeStyleSheet)
        self.makeTree()
        self.tree.setMinimumHeight(250)
        self.tree.clicked.connect(lambda: self.getSelection())
        self.tree.itemClicked.connect(lambda state: self.getChecked(state))
        #buttons
        #add
        nImg = Buttons().addButton()
        self.pb = QPushButton()
        self.pb.setFlat(True)
        self.pb.setIcon(QIcon(nImg))
        self.pb.setMaximumHeight(30)
        self.pb.setMaximumWidth(30)

        nImg1 = Buttons().closeButton()
        self.pb1 = QPushButton()
        self.pb1.setFlat(True)
        self.pb1.setIcon(QIcon(nImg1))
        self.pb1.setMaximumHeight(30)
        self.pb1.setMaximumWidth(30)

        nImg2 = Buttons().editButton()
        self.pb2 = QPushButton()
        self.pb2.setFlat(True)
        self.pb2.setIcon(QIcon(nImg2))
        self.pb2.setMaximumHeight(30)
        self.pb2.setMaximumWidth(30)

        nImg3 = Buttons().deleteButton()
        self.pb3 = QPushButton()
        self.pb3.setFlat(True)
        self.pb3.setIcon(QIcon(nImg3))
        self.pb3.setMaximumHeight(30)
        self.pb3.setMaximumWidth(30)

        nImg4 = Buttons().saveButton()
        self.pb4 = QPushButton()
        self.pb4.setFlat(True)
        self.pb4.setIcon(QIcon(nImg4))
        self.pb4.setMaximumHeight(30)
        self.pb4.setMaximumWidth(30)

        nImg5 = Buttons().resetButton()
        self.pb5 = QPushButton()
        self.pb5.setFlat(True)
        self.pb5.setIcon(QIcon(nImg5))
        self.pb5.setMaximumHeight(30)
        self.pb5.setMaximumWidth(30)

        nImg6 = Buttons().closeButton()
        self.pb6 = QPushButton()
        self.pb6.setFlat(True)
        self.pb6.setIcon(QIcon(nImg6))
        self.pb6.setMaximumHeight(30)
        self.pb6.setMaximumWidth(30)

        nImg7 = Buttons().addButton()
        self.pb7 = QPushButton()
        self.pb7.setFlat(True)
        self.pb7.setIcon(QIcon(nImg7))
        self.pb7.setMaximumHeight(30)
        self.pb7.setMaximumWidth(30)

        hbo = QHBoxLayout()
        hbo.addStretch()
        hbo.addWidget(self.pb1)
        hbo.addWidget(self.pb3)
        hbo.addWidget(self.pb2)
        hbo.addWidget(self.pb7)

        vbo = QVBoxLayout()
        vbo.addWidget(self.tree)
        vbo.addLayout(hbo)

        self.l1 = QLabel("Name")
        self.le1 = QLineEdit()
        self.le1.setObjectName("name")
        vals1 = Valid().fullNum()
        self.le1.setValidator(vals1)
        self.le1.setPlaceholderText("Lowercase max 25 letters")

        self.fromLbl = QLabel("Starts")
        self.toLbl = QLabel("Ends")
        self.fromData = QDateEdit()
        self.toData = QDateEdit()
        currentDate = QDate()
        self.fromData.setDate(currentDate.currentDate())
        self.fromData.setCalendarPopup(True)
        self.toData.setDate(currentDate.currentDate())
        self.toData.setCalendarPopup(True)

        FormLayout = QFormLayout()
        FormLayout.addRow(self.l1, self.le1)
        FormLayout.addRow(self.fromLbl, self.fromData)
        FormLayout.addRow(self.toLbl, self.toData)

        Hlayout1 = QHBoxLayout()
        Hlayout1.addStretch()
        Hlayout1.addWidget(self.pb6)
        Hlayout1.addWidget(self.pb5)
        Hlayout1.addWidget(self.pb4)
        Hlayout1.addWidget(self.pb)

        Vlayout1 = QVBoxLayout()
        Vlayout1.addLayout(FormLayout)
        Vlayout1.addLayout(Hlayout1)

        self.groupBox1.setLayout(vbo)
        self.groupBox2.setLayout(Vlayout1)
        self.groupBox2.hide()

        self.connect(self.pb, SIGNAL("clicked()"),
                     lambda: self.button_add())  #add
        self.connect(self.pb1, SIGNAL("clicked()"),
                     lambda: self.button_close())  #close
        self.connect(self.pb2, SIGNAL("clicked()"),
                     lambda: self.button_edit())  #edit
        self.connect(self.pb3, SIGNAL("clicked()"),
                     lambda: self.button_delete())  #delete
        self.connect(self.pb4, SIGNAL("clicked()"),
                     lambda: self.button_save())  #save
        self.connect(self.pb5, SIGNAL("clicked()"),
                     lambda: self.button_reset())  #reset

        self.pb4.hide()
        self.pb7.hide()

        grid = QGridLayout()
        grid.addWidget(self.groupBox1, 0, 0)
        grid.addWidget(self.groupBox2, 1, 0)

        self.setLayout(grid)
        self.setStyleSheet(stylesheet)
        self.setWindowIcon(QIcon(self.titleIcon))
        self.setWindowTitle(self.pagetitle)

    def makeTree(self):
        self.tree.clear()
        arr = Db().selectn('session', '', 5)
        self.hold_data = {}
        self.hold_mdata = {}
        self.hold_data_add = {}
        self.hold_data_add_item = {}
        current = time.time()

        if self.titleSub and self.titleSub > 0:
            if arr and len(arr) > 0:
                for val in arr:
                    ch = Valid().pullData('terms', '',
                                          {'sessionID': val['id']})
                    child = QTreeWidgetItem(self.tree)
                    child.setIcon(0, QIcon('icons.cfolder.png'))
                    try:
                        ts = int(float(val['start_date']))
                    except:
                        ts = int(current)
                    ts = datetime.utcfromtimestamp(ts).strftime('%d-%m-%Y')

                    try:
                        ts1 = int(float(val['end_date']))
                    except:
                        ts1 = int(current)
                    ts1 = datetime.utcfromtimestamp(ts1).strftime('%d-%m-%Y')

                    child.setText(
                        0,
                        str(val['name']).upper() + " - " + ts + " " + ts1)
                    self.hold_mdata[val['id']] = child

                    for va in ch:
                        child1 = QTreeWidgetItem(child)
                        child1.setFlags(child1.flags()
                                        | Qt.ItemIsUserCheckable)

                        try:
                            ts2 = int(float(va['start_date']))
                        except:
                            ts2 = int(current)
                        ts2 = datetime.utcfromtimestamp(ts2).strftime(
                            '%d-%m-%Y')
                        try:
                            ts3 = int(float(va['end_date']))
                        except:
                            ts3 = int(current)
                        ts3 = datetime.utcfromtimestamp(ts3).strftime(
                            '%d-%m-%Y')

                        child1.setText(
                            0,
                            str(va['name']).upper() + " " + ts2 + " " + ts3)
                        self.hold_data[va['id']] = child1
                        if (va['active'] == 1):
                            child1.setCheckState(0, Qt.Checked)
                        else:
                            child1.setCheckState(0, Qt.Unchecked)

                    child1 = QTreeWidgetItem(child)
                    child1.setFlags(child1.flags() | Qt.ItemIsUserCheckable)
                    child1.setText(0, 'Add New Term')
                    self.hold_data_add_item[val['id']] = child1
        else:
            if arr and len(arr) > 0:
                for val in arr:
                    child = QTreeWidgetItem(self.tree)
                    child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
                    child.setText(0, str(val['name']).upper())
                    child.setText(1, str(val['abbrv']).upper())
                    self.hold_data[val['id']] = child
                    if (val['active'] == 0):
                        child.setCheckState(0, Qt.Checked)
                    else:
                        child.setCheckState(0, Qt.Unchecked)

        child = QTreeWidgetItem(self.tree)
        child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
        child.setText(0, 'Add New Session')
        self.hold_data_add['addnew'] = child

    def getChecked(self, a):
        arr_hold = []
        g = Db()
        for i in self.hold_data:
            if self.hold_data[i].checkState(0) == Qt.Checked:
                arr_hold.append(i)
                self.hold_data[i].setCheckState(0, Qt.Checked)
                g.update('terms', {'active': 0}, {'active': 1})
                g.update('terms', {'active': 1}, {'id': i})
                tt = g.selectn('terms', '', 1, {'id': i})
                g.update('session', {'active': 0}, {'active': 1})
                g.update('session', {'active': 1}, {'id': tt['sessionID']})
                g.selectn('session', '', 1, {'id': tt['sessionID']})
            else:
                self.hold_data[i].setCheckState(0, Qt.Unchecked)

        self.reloadTerm()

    def reloadTerm(self):
        session = self.par.activeTerm()
        activeTerm = str(session[1]) + ' SESSION ' + str(session[3]) + ' TERM'
        self.par.majorSession = session[2]
        self.par.lbl.setText(activeTerm)

    def getSelected(self):
        r = False
        self.sessionMain = False
        for i in self.hold_mdata:
            if self.hold_mdata[i].isSelected():
                r = i

        if r and r > 0:
            self.groupBox2.show()
            self.sessionMain = True
            return r
        else:
            for i in self.hold_data:
                if self.hold_data[i].isSelected():
                    r = i
            if r and r > 0:
                self.sessionMain = False
                self.groupBox2.show()
                return r
            else:
                self.groupBox2.hide()

    def getSession(self):
        self.sessionID = None
        for i in self.hold_data_session:
            if self.hold_data_session[i].isSelected():
                r = i
        if r and r > 0:
            self.sessionID = r

    def getSelection(self):
        self.le1.clear()
        currentDate = QDate()
        self.fromData.setDate(currentDate.currentDate())
        self.toData.setDate(currentDate.currentDate())
        self.sessionMain = False

        if self.hold_data_add['addnew'].isSelected():
            self.groupBox2.setTitle('Add New')
            self.groupBox2.show()
            self.sessionMain = True
            self.sessionID = False
        else:
            self.sessionMain = False
            r = None
            for i in self.hold_data_add_item:
                if self.hold_data_add_item[i].isSelected():
                    r = i
            if r:
                g = Db()
                v = g.selectn('session', '', 1, {'id': r})
                vname = str(v['name']).upper() + ' Session'
                self.groupBox2.setTitle('ADD ' + str(vname) + ' Term')
                self.sessionID = r
                self.groupBox2.show()
            else:
                self.groupBox2.setTitle('Add')
                self.sessionID = False
                self.groupBox2.hide()

    def setActive(self):
        g = Db()
        for i in self.hold_data:
            if self.hold_data[i].checkState(0) == Qt.Checked:
                g.update('datas', {'active': 0}, {'id': i})
            else:
                g.update('datas', {'active': 1}, {'id': i})

    def button_add(self):
        s1 = self.le1.text()
        _datef = self.fromData.date().toPyDate()
        _datef = time.mktime(_datef.timetuple())
        _datee = self.toData.date().toPyDate()
        _datee = time.mktime(_datee.timetuple())
        g = Db()

        if self.sessionID and self.sessionID > 0:
            try:
                if (len(s1) > 0):
                    y = {
                        'name': s1.lower(),
                        'start_date': _datef,
                        'sessionID': self.sessionID,
                        'end_date': _datee,
                        'active': 0
                    }
                    z = g.insert('terms', y)
                    if z and z > 0:
                        g.createClass(z)
                        g.createSubject(z)
                        g.createFee(z)
                        g.createPay(z)
                        g.createResult(z)
                        g.createAffective(z)
                        g.createPsychomoto(z)
                    self.makeTree()
                    self.button_reset()
                    self.par.menuSession()
                    self.par.dropdownSession()
                else:
                    pass
            except:
                pass
        else:
            try:
                if (len(s1) > 0):
                    y = {
                        'name': s1.lower(),
                        'start_date': _datef,
                        'end_date': _datee,
                        'active': 0
                    }
                    z = g.insert('session', y)
                    if z and z > 0:
                        g.createExpenses(z)
                        g.createStores(z)
                        g.createAwards(z)
                        g.createConducts(z)
                        g.createMails(z)
                        g.createMedicals(z)
                    self.makeTree()
                    self.button_reset()
                    self.par.menuSession()
                    self.par.dropdownSession()
                else:
                    pass
            except:
                pass

    def button_save(self):
        row = self.editrow
        s1 = self.le1.text()
        _datef = self.fromData.date().toPyDate()
        _datef = time.mktime(_datef.timetuple())
        _datee = self.toData.date().toPyDate()
        _datee = time.mktime(_datee.timetuple())

        g = Db()

        if (len(s1) > 0) and row and row > 0:
            if self.sessionID and self.sessionID > 0:
                try:
                    if (len(s1) > 0):
                        y = {
                            'name': s1.lower(),
                            'start_date': _datef,
                            'sessionID': self.sessionID,
                            'end_date': _datee,
                            'active': 0
                        }
                        k = {'id': row}
                        g.update('terms', y, k)
                        z = row
                        if z and z > 0:
                            g.createClass(z)
                            g.createSubject(z)
                            g.createFee(z)
                            g.createPay(z)
                            g.createResult(z)
                            g.createAffective(z)
                            g.createPsychomoto(z)
                        self.makeTree()
                        self.button_reset()
                        self.par.menuSession()
                        self.par.dropdownSession()
                    else:
                        pass
                except:
                    pass
            else:
                try:
                    if (len(s1) > 0):
                        y = {
                            'name': s1.lower(),
                            'start_date': _datef,
                            'end_date': _datee,
                            'active': 0
                        }
                        k = {'id': row}
                        g.update('session', y, k)
                        z = row
                        if z and z > 0:
                            g.createExpenses(z)
                            g.createStores(z)
                            g.createAwards(z)
                            g.createConducts(z)
                            g.createMails(z)
                            g.createMedicals(z)
                        self.makeTree()
                        self.button_reset()
                        self.par.menuSession()
                        self.par.dropdownSession()
                    else:
                        pass
                except:
                    pass

    def button_delete(self):
        row = self.getSelected()
        g = Db()
        try:
            if row and row > 0:
                y = {'abbrv': '', 'active': 2}
                z = {'id': row}
                g.update('datas', y, z)
                self.makeTree()
            else:
                pass
        except:
            pass

    def button_reset(self):
        self.le1.clear()
        currentDate = QDate()
        self.fromData.setDate(currentDate.currentDate())
        self.toData.setDate(currentDate.currentDate())
        self.groupBox2.setTitle('Add')
        self.groupBox2.hide()
        self.pb.show()
        self.pb4.hide()

    def button_edit(self):
        row = self.getSelected()
        currentDate = QDate()
        if row:
            self.editrow = row
            g = Db()
            if self.sessionMain:
                data = g.selectn('session', '', 1, {'id': row})
                data_name = str(data['name'])
                self.groupBox2.setTitle('Edit')
                self.sessionID = False
            else:
                data = g.selectn('terms', '', 1, {'id': row})
                data_sess = g.selectn('session', '', 1,
                                      {'id': data['sessionID']})
                data_name = str(data['name'])
                self.sessionID = data['sessionID']
                self.groupBox2.setTitle('Edit ' + str(data_sess['name']))
            try:
                self.le1.setText(data_name)
            except:
                self.le1.setText('')
            try:
                self.fromData.setDate(data['start_date'])
            except:
                self.fromData.setDate(currentDate.currentDate())
            try:
                self.toData.setDate(data['end_date'])
            except:
                self.toData.setDate(currentDate.currentDate())
            self.pb.hide()
            self.pb4.show()

    def button_close(self):
        self.close()
示例#12
0
class SettingsManager(QDialog):
    def __init__(self, num, n, parent=None):
        super(SettingsManager, self).__init__(parent)

        #main
        self.par = n
        title = Settingz().positions(num)
        self.titleID = title['id']
        self.titleIDx = str(title['id']) + 'x'
        self.titlePage = title['page']
        self.titleName = title['name']
        self.titleSub = title['subID']
        self.titleIcon = title['icon']
        self.pagetitle = self.titlePage
        self.sessionMain = 0
        #stylesheet
        stylesheet = Valid().background() + Valid().font()
        treeStyleSheet = Valid().treez()

        self.groupBox1 = QGroupBox(self.titleName)
        self.groupBox2 = QGroupBox('Add')

        #items
        self.tree = QTreeWidget()
        self.tree.setHeaderLabel("Choose " + self.titleName)
        self.tree.headerItem().setText(0, 'Name')
        self.tree.headerItem().setText(1, 'Abbrv.')
        self.tree.setStyleSheet(treeStyleSheet)
        self.makeTree()
        self.tree.setMinimumHeight(250)
        self.tree.clicked.connect(lambda: self.getSelection())
        self.tree.itemClicked.connect(lambda state: self.getChecked(state))
        #buttons
        #add
        nImg = Buttons().addButton()
        self.pb = QPushButton()
        self.pb.setFlat(True)
        self.pb.setIcon(QIcon(nImg))
        self.pb.setMaximumHeight(30)
        self.pb.setMaximumWidth(30)

        nImg1 = Buttons().closeButton()
        self.pb1 = QPushButton()
        self.pb1.setFlat(True)
        self.pb1.setIcon(QIcon(nImg1))
        self.pb1.setMaximumHeight(30)
        self.pb1.setMaximumWidth(30)

        nImg2 = Buttons().editButton()
        self.pb2 = QPushButton()
        self.pb2.setFlat(True)
        self.pb2.setIcon(QIcon(nImg2))
        self.pb2.setMaximumHeight(30)
        self.pb2.setMaximumWidth(30)

        nImg3 = Buttons().deleteButton()
        self.pb3 = QPushButton()
        self.pb3.setFlat(True)
        self.pb3.setIcon(QIcon(nImg3))
        self.pb3.setMaximumHeight(30)
        self.pb3.setMaximumWidth(30)

        nImg4 = Buttons().saveButton()
        self.pb4 = QPushButton()
        self.pb4.setFlat(True)
        self.pb4.setIcon(QIcon(nImg4))
        self.pb4.setMaximumHeight(30)
        self.pb4.setMaximumWidth(30)

        nImg5 = Buttons().resetButton()
        self.pb5 = QPushButton()
        self.pb5.setFlat(True)
        self.pb5.setIcon(QIcon(nImg5))
        self.pb5.setMaximumHeight(30)
        self.pb5.setMaximumWidth(30)

        nImg6 = Buttons().closeButton()
        self.pb6 = QPushButton()
        self.pb6.setFlat(True)
        self.pb6.setIcon(QIcon(nImg6))
        self.pb6.setMaximumHeight(30)
        self.pb6.setMaximumWidth(30)

        nImg7 = Buttons().addButton()
        self.pb7 = QPushButton()
        self.pb7.setFlat(True)
        self.pb7.setIcon(QIcon(nImg7))
        self.pb7.setMaximumHeight(30)
        self.pb7.setMaximumWidth(30)

        hbo = QHBoxLayout()
        hbo.addStretch()
        hbo.addWidget(self.pb1)
        hbo.addWidget(self.pb3)
        hbo.addWidget(self.pb2)
        hbo.addWidget(self.pb7)

        vbo = QVBoxLayout()
        vbo.addWidget(self.tree)
        vbo.addLayout(hbo)

        self.l1 = QLabel("Name")
        self.le1 = QLineEdit()
        self.le1.setObjectName("name")
        vals1 = Valid().fullText()
        self.le1.setValidator(vals1)
        self.le1.setPlaceholderText("Lowercase max 25 letters")

        self.l2 = QLabel("Abbrv")
        self.le2 = QLineEdit()
        self.le2.setObjectName("abbrv")
        vals2 = Valid().limitText()
        self.le2.setValidator(vals2)
        self.le2.setPlaceholderText("Lowercase max 5 letters")

        FormLayout = QFormLayout()
        FormLayout.addRow(self.l1, self.le1)
        FormLayout.addRow(self.l2, self.le2)

        Hlayout1 = QHBoxLayout()
        Hlayout1.addStretch()
        Hlayout1.addWidget(self.pb6)
        Hlayout1.addWidget(self.pb5)
        Hlayout1.addWidget(self.pb4)
        Hlayout1.addWidget(self.pb)

        Vlayout1 = QVBoxLayout()
        Vlayout1.addLayout(FormLayout)
        Vlayout1.addLayout(Hlayout1)

        self.groupBox1.setLayout(vbo)
        self.groupBox2.setLayout(Vlayout1)
        self.groupBox2.hide()

        self.connect(self.pb, SIGNAL("clicked()"),
                     lambda: self.button_add())  #add
        self.connect(self.pb1, SIGNAL("clicked()"),
                     lambda: self.button_close())  #close
        self.connect(self.pb2, SIGNAL("clicked()"),
                     lambda: self.button_edit())  #edit
        self.connect(self.pb3, SIGNAL("clicked()"),
                     lambda: self.button_delete())  #delete
        self.connect(self.pb4, SIGNAL("clicked()"),
                     lambda: self.button_save())  #save
        self.connect(self.pb5, SIGNAL("clicked()"),
                     lambda: self.button_reset())  #reset

        self.pb4.hide()
        self.pb7.hide()

        grid = QGridLayout()
        grid.addWidget(self.groupBox1, 0, 0)
        grid.addWidget(self.groupBox2, 1, 0)

        self.setLayout(grid)
        self.setStyleSheet(stylesheet)
        self.setWindowIcon(QIcon(self.titleIcon))
        self.setWindowTitle(self.pagetitle)

    def makeTree(self):
        self.tree.clear()
        arr = Valid().pullData('datas', '', {'pubID': self.titleID})
        self.hold_data = {}
        self.hold_mdata = {}
        self.hold_data_add = {}
        self.hold_data_add_item = {}

        if self.titleSub and self.titleSub > 0:
            if arr and len(arr) > 0:
                for val in arr:
                    ch = Valid().pullData('datas', '', {'subID': val['id']})
                    child = QTreeWidgetItem(self.tree)
                    child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
                    child.setText(0, str(val['name']).upper())
                    child.setText(1, str(val['abbrv']).upper())
                    self.hold_data[val['id']] = child
                    self.hold_mdata[val['id']] = child
                    if (val['active'] == 0):
                        child.setCheckState(0, Qt.Checked)
                    else:
                        child.setCheckState(0, Qt.Unchecked)

                    for va in ch:
                        child1 = QTreeWidgetItem(child)
                        child1.setFlags(child1.flags()
                                        | Qt.ItemIsUserCheckable)
                        child1.setText(0, str(va['name']).upper())
                        child1.setText(1, str(va['abbrv']).upper())
                        self.hold_data[va['id']] = child1
                        if (va['active'] == 0):
                            child1.setCheckState(0, Qt.Checked)
                        else:
                            child1.setCheckState(0, Qt.Unchecked)

                    child1 = QTreeWidgetItem(child)
                    child1.setFlags(child1.flags() | Qt.ItemIsUserCheckable)
                    child1.setText(0, 'Add New Item')
                    self.hold_data_add_item[val['id']] = child1
        else:
            if arr and len(arr) > 0:
                for val in arr:
                    child = QTreeWidgetItem(self.tree)
                    child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
                    child.setText(0, str(val['name']).upper())
                    child.setText(1, str(val['abbrv']).upper())
                    self.hold_data[val['id']] = child
                    if (val['active'] == 0):
                        child.setCheckState(0, Qt.Checked)
                    else:
                        child.setCheckState(0, Qt.Unchecked)

        child = QTreeWidgetItem(self.tree)
        child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
        child.setText(0, 'Add New')
        self.hold_data_add['addnew'] = child

    def getChecked(self, a):
        g = Db()
        for i in self.hold_data:
            if self.hold_data[i].checkState(0) == Qt.Checked:
                g.update('datas', {'active': 0}, {'id': i})
            else:
                g.update('datas', {'active': 1}, {'id': i})

        if self.titleID == 1:
            #if class was changed only reload class menu on main window
            self.par.menuStudent()
            self.par.dropdownStudent()

    def getSelected(self):
        r = None
        k = None
        for i in self.hold_data:
            if self.hold_data[i].isSelected():
                r = i
        for j in self.hold_mdata:
            if self.hold_mdata[j].isSelected():
                k = j

        if r and r > 0:
            if r == k:
                self.sessionMain = r
            else:
                self.sessionMain = 0
            self.groupBox2.show()
            return r
        else:
            self.groupBox2.hide()

    def getSelection(self):

        self.le1.clear()
        self.le2.clear()

        if self.hold_data_add['addnew'].isSelected():
            self.sessionMain = 0
            self.groupBox2.setTitle('Add New')
            self.groupBox2.show()
        else:
            r = None
            for i in self.hold_data_add_item:
                if self.hold_data_add_item[i].isSelected():
                    r = i
            if r:
                self.sessionMain = r
                g = Db()
                v = g.selectn('datas', '', 1, {'id': r})
                vname = str(v['name']).upper()
                self.groupBox2.setTitle('ADD ' + str(vname) + ' ITEM')
                self.groupBox2.show()
            else:
                self.groupBox2.setTitle('Add')
                self.groupBox2.hide()

    def setActive(self):
        g = Db()
        for i in self.hold_data:
            if self.hold_data[i].checkState(0) == Qt.Checked:
                g.update('datas', {'active': 0}, {'id': i})
            else:
                g.update('datas', {'active': 1}, {'id': i})

    def button_add(self):
        s1 = self.le1.text()
        s2 = self.le2.text()
        g = Db()
        try:
            if (len(s1) > 0) and (len(s2) > 0):
                if self.sessionMain == 0:
                    y = {
                        'name': s1.lower(),
                        'abbrv': s2.lower(),
                        'pubID': self.titleID,
                        'active': 0
                    }
                else:
                    y = {
                        'name': s1.lower(),
                        'abbrv': s2.lower(),
                        'subID': self.sessionMain,
                        'pubID': self.titleIDx,
                        'active': 0
                    }
                g.insert('datas', y)

                self.makeTree()
                self.button_reset()
                if self.titleID == 1:
                    #if class was changed only relod class menu on main window
                    self.par.menuStudent()
                    self.par.dropdownStudent()
            else:
                pass
        except:
            pass

    def button_save(self):
        row = self.editrow

        s1 = self.le1.text()
        s2 = self.le2.text()
        g = Db()
        try:
            if (len(s1) > 0) and (len(s2) > 0) and row and row > 0:
                y = {'name': s1.lower(), 'abbrv': s2.lower(), 'active': 0}
                z = {'id': row}
                g.update('datas', y, z)
                self.makeTree()
                self.button_reset()
                if self.titleID == 1:
                    #if class was changed only relod class menu on main window
                    self.par.menuStudent()
                    self.par.dropdownStudent()
            else:
                pass
        except:
            pass

    def button_delete(self):
        row = self.getSelected()
        g = Db()
        try:
            if row and row > 0:
                y = {'abbrv': '', 'active': 2}
                z = {'id': row}
                g.update('datas', y, z)
                self.makeTree()
            else:
                pass
        except:
            pass

    def button_reset(self):
        self.le1.clear()
        self.le2.clear()
        self.groupBox2.setTitle('Add')
        self.groupBox2.hide()
        self.pb.show()
        self.pb4.hide()
        self.sessionMain = 0

    def button_edit(self):
        row = self.getSelected()
        self.sessionMain = 0
        if row:
            self.groupBox2.setTitle('Edit')
            self.editrow = row
            g = Db()
            data = g.selectn('datas', '', 1, {'id': row})
            if self.titleID == data['pubID']:
                self.sessionMain = 1
            else:
                self.sessionMain = 0

            try:
                self.le1.setText(data['name'])
            except:
                self.le1.setText('')
            try:
                self.le2.setText(data['abbrv'])
            except:
                self.le2.setText('')
            self.pb.hide()
            self.pb4.show()

    def button_close(self):
        self.close()
示例#13
0
class urlgroup(QGroupBox):
    def __init__(self, parent=None):
        super(urlgroup, self).__init__(parent)
        self.setGeometry(10, 30, 500, 80)
        self.setObjectName('urlgroup')
        self.urlbar = QLineEdit()
        self.urlbar.setObjectName('urlbar')
        self.urlbar.setText('Collez votre URL i�i')
        self.urlbar.setStyleSheet('font-weight:lighter;color:gray;')
        self.urlbar.show()
        self.parsebutton = QPushButton('Go !!')
        self.parsebutton.setObjectName('parsebutton')
        self.parsebutton.show()
        layout = QBoxLayout(QBoxLayout.LeftToRight, self)
        layout.addWidget(self.urlbar)
        layout.addWidget(self.parsebutton)
        self.show()
        self.group2 = QGroupBox(parent)
        self.group2.setObjectName('core')
        self.group2.setGeometry(10, 120, 500, 280)
        self.group2.show()
        self.group3 = QGroupBox(self.group2)
        self.group3.setObjectName('albuminfos')
        self.group3.setGeometry(10, 15, 200, 245)
        self.group3.show()
        self.itemlist = QListWidget(self.group2)
        self.itemlist.setGeometry(250, 15, 230, 245)
        self.itemlist.show()
        self.dlgroup = QGroupBox(parent)
        self.dlgroup.setObjectName('dlgroup')
        self.dlgroup.setGeometry(10, 420, 500, 100)
        self.dlgroup.show()
        self.dlgroup.dlbutton = QPushButton('Download', self.dlgroup)
        self.dlgroup.dlbutton.setObjectName('dlbutton')
        self.dlgroup.dlbutton.move(10, 20)
        self.dlgroup.dlbutton.show()
        self.dlgroup.progressbar = QProgressBar(self.dlgroup)
        self.dlgroup.progressbar.setObjectName('progressbar')
        self.dlgroup.progressbar.setGeometry(100, 21, 380, 21)
        self.dlgroup.progressbar.show()
        self.dlgroup.dlinfos = QLabel(self.dlgroup)
        self.dlgroup.dlinfos.setGeometry(100, 70, 200, 21)
        self.dlgroup.dlinfos.show()
        self.dlgroup.dledfile = QLabel(self.dlgroup)
        self.dlgroup.dledfile.setGeometry(300, 70, 200, 21)
        self.dlgroup.dledfile.show()
        self.dlgroup.dlto = QLineEdit('C:\\', self.dlgroup)
        self.dlgroup.dlto.setGeometry(100, 50, 350, 21)
        self.dlgroup.dlto.show()
        self.dlgroup.dlto.changebt = QToolButton(self.dlgroup)
        self.dlgroup.dlto.changebt.setObjectName('dltobt')
        self.dlgroup.dlto.changebt.setGeometry(10, 50, 75, 21)
        self.dlgroup.dlto.changebt.setText('To')
        self.dlgroup.dlto.changebt.show()
        self.dlgroup.dlto.openf = QPushButton('Open', self.dlgroup)
        self.dlgroup.dlto.openf.setGeometry(455, 50, 35, 21)
        self.dlgroup.dlto.openf.setObjectName('openfolder')
        self.dlgroup.dlto.openf.show()
        self.album = QLabel(self.group3)
        self.artist = QLabel(self.group3)
        self.year = QLabel(self.group3)
        self.tracks = QLabel(self.group3)
        self.coverart = QLabel(self.group3)
        self.urlbar.setFocus(True)
        self.connect(self.parsebutton, SIGNAL('clicked()'), self.parseclicked)
        self.connect(self.dlgroup.dlbutton, SIGNAL('clicked()'), self.launchdl)
        self.connect(self.dlgroup.dlto.changebt, SIGNAL('clicked()'),
                     self.changedir)
        self.connect(self.dlgroup.dlto.openf, SIGNAL('clicked()'),
                     self.openfolder)

    def parseclicked(self):
        self.itemlist.clear()
        url = str(self.urlbar.text())
        self.infos = getsonglist(url)
        if (self.infos == 'connexion impossible') or (self.infos
                                                      == 'unsupported'):
            self.error = QMessageBox()
            if self.infos == 'connexion impossible':
                self.error.setText('Connexion Impossible !')
            elif self.infos == 'unsupported':
                self.error.setText('Site Unsupported !!')
            self.error.setWindowTitle('Erreur!')
            self.error.setIcon(QMessageBox.Warning)
            self.icon = QIcon('images/mainwindowicon.png')
            self.error.setWindowIcon(self.icon)
            self.error.exec_()
        else:
            self.artist.setText('Artiste : ' + self.infos['artist'])
            self.artist.move(40, 175)
            self.artist.show()
            self.album.setText('Album : ' + self.infos['albumname'])
            self.album.move(40, 190)
            self.album.show()
            try:
                self.year.setText('Annee : ' + self.infos['year'])

            except KeyError:
                self.year.setText('Annee : ' + 'N/A')
            self.year.move(40, 205)
            self.year.show()
            self.tracks.setText('Tracks : ' + str(self.infos['tracks']))
            self.tracks.move(40, 220)
            self.tracks.show()
            coverartpix = QPixmap(self.infos['coverart'])
            coverartpix = coverartpix.scaled(
                178,
                135,
            )
            self.coverart.setPixmap(coverartpix)
            self.coverart.move(10, 10)
            self.coverart.show()
            self.list2 = []
            for item in self.infos['titles']:
                item = tracklistitems(item)
                self.list2.append(item)
            for item in self.list2:
                self.itemlist.addItem(item)

    def launchdl(self):
        if self.dlgroup.dlbutton.text() == 'Download':
            try:
                self.itemlist.item(self.currentitem).setText(self.text)
            except:
                pass
            self.dlgroup.dlbutton.setText('Stop')
            rmtree('tmpimg', True)
            i = 0
            dllist = []
            for item in self.list2:
                if item.eligible() == 'Checked':
                    dllist.append(i)
                i = i + 1
            self.stritemlist = []
            for i in range(0, self.infos['tracks']):
                #print i
                #print self.itemlist.item(i).text()
                #TODO: hamida album breaks, recheck regexes
                self.stritemlist.append(str(self.itemlist.item(i).text()))
            dlto = self.dlgroup.dlto.text()
            self.thread = dlThread(dllist, self.infos, dlto, self.stritemlist)
            self.connect(self.thread, SIGNAL('progress(PyQt_PyObject)'),
                         self.updateProgress)
            self.connect(self.thread, SIGNAL('dledfile(PyQt_PyObject)'),
                         self.updateDlednow)
            self.thread.start()
        else:
            self.dlgroup.dlbutton.setText('Download')
            self.thread.terminate()

    def updateProgress(self, progress):
        self.dlgroup.progressbar.setValue(progress['bar'])
        self.dlgroup.dlinfos.setText(progress['info'])
        self.text = self.stritemlist[progress['item']]
        self.currentitem = progress['item']
        self.percent = str(progress['bar']) + ' % - '
        self.percent = QString(self.percent)
        self.dlingicon = QIcon('images/dling.png')
        self.doneicon = QIcon('images/done.png')
        self.itemlist.item(progress['item']).setIcon(self.dlingicon)
        self.itemlist.item(progress['item']).setText(self.percent + self.text)
        if progress['bar'] >= 98:
            self.itemlist.item(progress['item']).setIcon(self.doneicon)
            self.itemlist.item(progress['item']).setText(self.text)
            self.itemlist.item(progress['item']).setCheckState(Qt.Unchecked)
            self.itemlist.item(
                progress['item']).setFlags(Qt.ItemIsEnabled | Qt.ItemIsEditable
                                           | Qt.ItemIsSelectable)

    def updateDlednow(self, dledfile):
        self.dlgroup.dledfile.setText(dledfile)

    def changedir(self):
        self.dir = QFileDialog.getExistingDirectory()
        self.dlgroup.dlto.setText(self.dir + '/')

    def openfolder(self):
        startfile(self.dlgroup.dlto.text())

    def stopdl(self):
        pass
示例#14
0
class PluginWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.pluginMetadata = {}

        # Main layout
        self.mainLayout = QVBoxLayout()
        self.setLayout(self.mainLayout)

        # Define size used for the underlines
        self.underlineSize = QSize()
        self.underlineSize.setHeight(1)

        # Define font used for headers
        self.font = QFont()
        self.font.setPointSize(11)
        self.font.setBold(True)
        self.font.setUnderline(True)

        # Plugins Description
        self.pluginDescription = QLabel()
        self.pluginDescription.setText(
            "Click a plugin to see more information." +
            " Plugins can be configured from the Recording tab. \n")
        self.pluginDescription.setWordWrap(True)

        # Plugins GroupBox
        self.pluginLayout = QVBoxLayout()
        self.pluginGroupBox = QGroupBox(
            "Plugins extend the functionality of Freeseer")
        self.pluginGroupBox.setLayout(self.pluginLayout)
        self.pluginLayout.insertWidget(0, self.pluginDescription)
        self.mainLayout.insertWidget(0, self.pluginGroupBox)

        # Plugins list
        self.list = QTreeWidget()
        self.list.setHeaderHidden(True)
        self.list.headerItem().setText(0, "1")
        self.pluginLayout.insertWidget(1, self.list)

        # Details
        self.detailPane = QGroupBox()
        self.detailLayout = QVBoxLayout()
        self.detailPane.setLayout(self.detailLayout)
        self.detailPaneDesc = QLabel()
        self.detailPaneDesc.setWordWrap(True)
        self.detailLayout.addWidget(self.detailPaneDesc)
        self.pluginLayout.insertWidget(2, self.detailPane)

        self.list.itemSelectionChanged.connect(self.treeViewSelect)

    def treeViewSelect(self):
        item = self.list.currentItem()
        key = str(item.text(0))
        if key in self.pluginMetadata.keys():
            self.showDetails(key)
        else:
            self.hideDetails()

    def showDetails(self, key):
        self.detailPane.setTitle(key)
        self.detailPaneDesc.setText(self.pluginMetadata[key])
        self.detailPane.show()

    def hideDetails(self):
        self.detailPane.hide()

    def getWidgetPlugin(self, plugin, plugin_category, plugman):
        plugin_name = plugin.plugin_object.get_name()
        item = QTreeWidgetItem()

        # Display Plugin's meta data in a tooltip
        pluginDetails = """
        <table>
        <tr>
            <td>Name: </td>
            <td><b>%(name)s</b></td>
        </tr>
        <tr>
            <td>Version: </td>
            <td><b>%(version)s</b></td>
        <tr>
            <td>Author: </td>
            <td><b>%(author)s</b></td>
        </tr>
        <tr>
            <td>Website: </td>
            <td><b>%(website)s</b></td>
        </tr>
        <tr>
            <td>Description: </td>
            <td><b>%(description)s</b></td>
        </tr>
        </table>
        """ % {
            "name": plugin.name,
            "version": plugin.version,
            "author": plugin.author,
            "website": plugin.website,
            "description": plugin.description
        }

        # put the details in the hash table
        self.pluginMetadata[plugin_name] = pluginDetails

        item.setText(0, plugin_name)
        return item