Beispiel #1
0
	def data(self, index, role=Qt.DisplayRole):
		"""
		Reimplements the :meth:`QSortFilterProxyModel.data` method.
		
		:param index: Index.
		:type index: QModelIndex
		:param role: Role.
		:type role: int
		:return: Data.
		:rtype: QVariant
		"""

		if role == Qt.DisplayRole:
			node = self.getNode(index)
			if node.family == "Editor":
				data = self.__editorNodeFormat.format(node.name)
			elif node.family == "File":
				data = self.__fileNodeFormat.format(node.name)
			elif node.family == "Directory":
				data = self.__directoryNodeFormat.format(node.name)
			elif node.family == "Project":
				if node is self.sourceModel().defaultProjectNode:
					data = self.__defaultProjectNodeFormat.format(node.name)
				else:
					data = self.__projectNodeFormat.format(node.name)
			else:
				data = QVariant()
			return data
		else:
			return QSortFilterProxyModel.data(self, index, role)
Beispiel #2
0
 def data( self, index, role = Qt.DisplayRole ):
     """
     Esta funcion redefine data en la clase base, es el metodo que se utiliza para mostrar los datos del modelo
     """
     value = QSortFilterProxyModel.data( self, index, role )
     if value.isValid() and role == Qt.DisplayRole:
         if index.column() == SALDO:
             return moneyfmt( Decimal( value.toString() ), 4, "US$ " )
     return value
Beispiel #3
0
    def data( self, index, role ):
        if not index.isValid():
            return None

        if index.column() == ACTIVO and role in ( Qt.CheckStateRole,
                                                  Qt.DisplayRole ):
            if role == Qt.CheckStateRole:
                value = QVariant( Qt.Checked ) if index.data( Qt.EditRole ).toBool() else QVariant( Qt.Unchecked )
                return value
        else:
            return QSortFilterProxyModel.data( self, index, role )
Beispiel #4
0
 def data( self, index, role = Qt.DisplayRole ):
     """
     Esta funcion redefine data en la clase base, es el metodo 
     que se utiliza para mostrar los datos del modelo
     """
     value = QSortFilterProxyModel.data( self, index, role )
     if value.isValid() and role in ( Qt.EditRole, Qt.DisplayRole ):
         if index.column() in ( SUBTOTALC, IVAC, TOTALC ):
             return moneyfmt( Decimal( value.toString() ), 4, "C$" )
         elif index.column() == TOTALD:
             return moneyfmt( Decimal( value.toString() ), 4, "US$" )
     return value
Beispiel #5
0
    def data( self, index, role = Qt.DisplayRole ):
        """
        Esta funcion redefine data en la clase base, es el metodo que 
        se utiliza para mostrar los datos del modelo
        """
        if not index.isValid():
            return None

        if index.column() == DEBE:
            _row = self.mapToSource( index ).row()
#            value = self.sourceModel().sourceModel().lines[row].monto
#            try:
            value = QSortFilterProxyModel.data( self, index, Qt.EditRole ).toString()
            value = Decimal( value if value != "" else 0 )

            if role == Qt.EditRole:
                return QSortFilterProxyModel.data( self, index, Qt.EditRole )
            elif role == Qt.DisplayRole:
                self.dataChanged.emit( index, index )
                return moneyfmt( value, 4, '' )
        else:
            return QSortFilterProxyModel.data( self, index, role )
Beispiel #6
0
    def data( self, index, role = Qt.DisplayRole ):
        """
        Esta funcion redefine data en la clase base, es el metodo que se utiliza para mostrar los datos del modelo
        """
        value = QSortFilterProxyModel.data( self, index, role )
        if value.isValid() and role in ( Qt.EditRole, Qt.DisplayRole , Qt.TextAlignmentRole ):
            if index.column() in ( TOTAL, TOTALPAGADO, TOTALRETENCION ) :
                if role in ( Qt.EditRole, Qt.DisplayRole ):
                    value = value.toString()
                    return moneyfmt( Decimal( value if value != "-" else 0 ), 4, "US$" )
                elif role == Qt.TextAlignmentRole:
                    return Qt.AlignHCenter | Qt.AlignVCenter

        return value
class ConfigurationDialog(QDialog, Ui_Configuration, SettingDialog):
    def __init__(self):
        QDialog.__init__(self)
        self.setupUi(self)
        self.settings = MySettings()
        SettingDialog.__init__(self, self.settings)

        # new declaration of ProjectFinder since changes can be cancelled
        self.projectFinder = ProjectFinder(self)

        # table model
        self.projectSearchModel = ProjectSearchModel(self.projectFinder)

        self.proxyModel = QSortFilterProxyModel(self)
        self.proxyModel.setSourceModel(self.projectSearchModel)
        self.projectSearchTable.setModel(self.proxyModel)

        header = self.projectSearchTable.horizontalHeader()
        header.setResizeMode(QHeaderView.ResizeToContents)

        # open/create QuickFinder file
        self.createFileButton.clicked.connect(self.createQFTSfile)
        self.openFileButton.clicked.connect(self.openQFTSfile)
        self.readQFTSfile()

        # project search
        self.addSearchButton.clicked.connect(self.addProjectSearch)
        self.removeSearchButton.clicked.connect(self.removeProjectSearch)
        self.editSearchButton.clicked.connect(self.editProjectSearch)
        self.refreshButton.clicked.connect(self.refreshProjectSearch)
        self.projectSearchTable.selectionModel().selectionChanged.connect(self.enableButtons)
        self.enableButtons()

        # geomapfish
        self.geomapfishCrsButton.clicked.connect(self.geomapfishCrsButtonClicked)

    def reject(self):
        if self.closeAndControl():
            QDialog.reject(self)

    def accept(self):
        if self.closeAndControl():
            QDialog.accept(self)

    def closeAndControl(self):
        self.projectFinder.close()
        for search in self.projectFinder.searches.values():
            if search.dateEvaluated is None:
                box = QMessageBox(QMessageBox.Warning,
                                  "Quick Finder",
                                  QCoreApplication.translate("Configuration dialog", "Some searches are still not recorded to the file. Do you want to record them now ? "),
                                  QMessageBox.Cancel | QMessageBox.Yes | QMessageBox.Close,
                                  self)
                ret = box.exec_()
                if ret == QMessageBox.Cancel:
                    return False
                elif ret == QMessageBox.Yes:
                    self.refreshProjectSearch()
                    return False
        return True

    def readQFTSfile(self):
        filepath = self.qftsfilepath.text()
        self.projectFinder.setFile(filepath)
        self.projectSearchTable.setEnabled(self.projectFinder.isValid)
        self.projectSearchButtonsWidget.setEnabled(self.projectFinder.isValid)

    def createQFTSfile(self):
        prjPath = QgsProject.instance().homePath()
        filepath = QFileDialog.getSaveFileName(self, "Create Quickfinder index file", prjPath,
                                               "Quickfinder file (*.qfts)")
        if filepath:
            if filepath[-5:] != ".qfts":
                filepath += ".qfts"
            if path.isfile(filepath):
                remove(filepath)
            createFTSfile(filepath)
            self.qftsfilepath.setText(filepath)
            self.readQFTSfile()

    def openQFTSfile(self):
        prjPath = QgsProject.instance().homePath()
        filepath = QFileDialog.getOpenFileName(self, "Open Quickfinder index file",
                                               prjPath, "Quickfinder file (*.qfts)")
        if filepath:
            self.qftsfilepath.setText(filepath)
            self.readQFTSfile()

    def addProjectSearch(self):
        ProjectSearchDialog(self.projectFinder, self.projectSearchModel).exec_()

    def removeProjectSearch(self):
        sel = self.selectedSearchIds()
        if len(sel) == 0:
            return
        box = QMessageBox(QMessageBox.Warning,
                                  "Quick Finder",
                                  QCoreApplication.translate("Configuration dialog", "Are you sure to remove {0} search(es) ? ").format(len(sel)),
                                  QMessageBox.Yes | QMessageBox.Cancel,
                                  self)
        ret = box.exec_()
        if ret == QMessageBox.Cancel:
            return
        self.projectSearchModel.removeSearches(sel)

    def editProjectSearch(self):
        sel = self.selectedSearchIds()
        if len(sel) != 1:
            return
        if not self.projectSearchModel.searches.has_key(sel[0]):
            return
        search = self.projectSearchModel.searches[sel[0]]
        if search:
            ProjectSearchDialog(self.projectFinder, self.projectSearchModel, search).exec_()

    def refreshProjectSearch(self):
        RefreshDialog(self.projectFinder, self.projectSearchModel, self.selectedSearchIds()).exec_()

    def selectedSearchIds(self):
        selectedSearchId = []
        for idx in self.projectSearchTable.selectionModel().selectedRows():
            selectedSearchId.append(self.proxyModel.data(idx, SearchIdRole))
        return selectedSearchId

    def enableButtons(self):
        n = len(self.selectedSearchIds())
        self.removeSearchButton.setEnabled(n > 0)
        self.editSearchButton.setEnabled(n == 1)
        self.projectSearchButtonsWidget.setEnabled(self.projectFinder.isValid)

    def geomapfishCrsButtonClicked(self):
        dlg = QgsGenericProjectionSelector(self)
        dlg.setMessage('Select GeoMapFish CRS')
        dlg.setSelectedAuthId(self.geomapfishCrs.text())
        if dlg.exec_():
            self.geomapfishCrs.setText(dlg.selectedAuthId())
Beispiel #8
0
class FrmOperations(QMainWindow, Ui_frmOperations):
    def __init__(self, parent=None):
        super(FrmOperations, self).__init__(parent)
        self.setupUi(self)
        self.__status = False
        self.database = QSqlDatabase.database()

        self.navmodel = QSqlQueryModel()
        self.navproxymodel = QSortFilterProxyModel()
        self.navproxymodel.setFilterKeyColumn(-1)
        self.navproxymodel.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.navproxymodel.setSourceModel(self.navmodel)

        self.detailsmodel = QSqlQueryModel()
        self.detailsproxymodel = QSortFilterProxyModel()
        self.detailsproxymodel.setSourceModel(self.detailsmodel)

        self.navproxymodel.setDynamicSortFilter(True)
        self.detailsproxymodel.setDynamicSortFilter(True)

        self.mapper = QDataWidgetMapper(self)
        self.mapper.setModel(self.navproxymodel)

        self.user = user.LoggedUser

        self.editModel = None

        self.tableNavigation.setModel(self.navproxymodel)
        self.tableDetails.setModel(self.detailsproxymodel)

        self.tableDetails.setColumnHidden(IDCUENTA, True)
        self.tableDetails.setColumnHidden(IDDOCUMENTOC, True)

        self.actionCancelar.setVisible(False)
        self.actionGuardar.setVisible(False)

        #        self.actionGuardar.activated.connect( self.save )
        self.tableNavigation.selectionModel().selectionChanged[QItemSelection, QItemSelection].connect(
            self.updateDetails
        )

        QTimer.singleShot(0, self.updateModels)

    def updateModels(self):
        try:
            if not self.database.isOpen():
                if not self.database.open():
                    raise UserWarning("No se pudo conectar con la base de datos")
            self.navmodel.setQuery(
                """
            SELECT 
                d.iddocumento, 
                d.ndocimpreso as 'N Doc', 
                d.fechacreacion as 'Fecha', 
                c.descripcion as 'Concepto'
            FROM documentos d
            JOIN conceptos c ON c.idconcepto = d.idconcepto
            WHERE d.idtipodoc = %d
            ORDER BY d.iddocumento DESC
            """
                % constantes.IDAJUSTECONTABLE
            )
            self.detailsmodel.setQuery(
                """
            SELECT 
                cxd.idcuenta,  
                cc.codigo as 'Codigo Cuenta', 
                cc.descripcion as 'Nombre Cuenta',
                CONCAT('C$',FORMAT(cxd.monto,4)) as Monto,
                cxd.iddocumento  
            FROM cuentasxdocumento cxd 
            JOIN cuentascontables cc ON cxd.idcuenta = cc.idcuenta
            JOIN documentos d ON d.iddocumento = cxd.iddocumento 
            WHERE d.idtipodoc = %d
            ORDER BY nlinea 
            """
                % constantes.IDAJUSTECONTABLE
            )

            self.mapper.addMapping(self.dtPicker, FECHACREACION)
            self.mapper.addMapping(self.txtConcept, CONCEPTO)
            self.tableNavigation.selectionModel().setCurrentIndex(
                self.navproxymodel.index(0, 0), QItemSelectionModel.Select
            )

            self.tableNavigation.setColumnHidden(IDDOCUMENTO, True)
            self.tableDetails.setColumnHidden(IDDOCUMENTOC, True)
            self.tableDetails.setColumnHidden(IDCUENTA, True)

            self.tableDetails.setColumnWidth(CODIGO, 240)
            self.tableDetails.setColumnWidth(DESCRIPCION, 250)

            self.tableNavigation.setColumnWidth(FECHACREACION, 200)
            self.tableNavigation.setColumnWidth(CONCEPTO, 250)
        except UserWarning as inst:
            logging.error(inst)
            QMessageBox.critical(self, qApp.organizationName(), unicode(inst))
        except Exception as inst:
            logging.critical(inst)

    def updateDetails(self, selected, _deselected):
        if len(selected.indexes()) > 0:
            self.mapper.setCurrentModelIndex(selected.indexes()[0])
            self.detailsproxymodel.setFilterKeyColumn(IDDOCUMENTOC)
            self.detailsproxymodel.setFilterRegExp(self.navproxymodel.data(selected.indexes()[0]).toString())

    def setStatus(self, status):
        """
        Cambiar el modo del formulario
        
        true = adding
        false = navigating
        
        @param status: El modo del formulario
        @type status:bool
        """

        self.widget.setHidden(status)
        self.txtSearch.setEnabled(not status)
        self.actionNuevo.setVisible(not status)
        self.actionCancelar.setVisible(status)
        self.actionGuardar.setVisible(status)
        self.cbConcepts.setEnabled(status)
        self.tableDetails.setEditTriggers(QTableView.AllEditTriggers if status else QTableView.NoEditTriggers)
        self.tableNavigation.setEnabled(not status)
        self.tableDetails.setEditTriggers(QTableView.AllEditTriggers)
        #        self.stackedWidget.setCurrentIndex( 0 if status else 1 )
        self.stConcepts.setCurrentIndex(1 if status else 0)

    def getStatus(self):
        return self.__status

    status = property(getStatus, setStatus)

    @pyqtSlot()
    def on_actionCancelar_activated(self):
        self.status = False
        self.editModel = None
        self.tableDetails.setModel(self.detailsproxymodel)
        self.tableDetails.setColumnHidden(IDDOCUMENTOC, True)
        self.tableDetails.setColumnHidden(IDCUENTA, True)

    @pyqtSlot()
    def on_actionGuardar_activated(self):
        self.save()

    @pyqtSlot()
    def on_actionNuevo_activated(self):
        try:
            if not self.database.isOpen():
                if not self.database.open():
                    raise UserWarning("No se pudo abrir la base de datos")

            self.editModel = AccountsSelectorModel()
            self.editModel.insertRow(1)

            delegate = AccountsSelectorDelegate(
                QSqlQuery(
                    """
            SELECT 
                c.idcuenta, 
                c.codigo, 
                c.descripcion 
            FROM cuentascontables c 
            JOIN cuentascontables p ON c.padre = p.idcuenta AND p.padre != 1
            """
                )
            )

            self.dtPicker.setDateTime(QDateTime.currentDateTime())
            self.dtPicker.setMaximumDateTime(QDateTime.currentDateTime())

            self.conceptsmodel = QSqlQueryModel()
            q = """
            SELECT
                idconcepto,
                descripcion
            FROM conceptos
            WHERE idtipodoc = %d and idconcepto <>%d
             """ % (
                constantes.IDAJUSTECONTABLE,
                constantes.IDCONCEPTOBALANCEINICIAL,
            )

            self.conceptsmodel.setQuery(q)

            if self.conceptsmodel.rowCount() < 1:
                raise UserWarning(
                    "No existen conceptos para ajustes contables, por favor comuniquese con el administrador del sistema"
                )

            self.cbConcepts.setModel(self.conceptsmodel)
            self.cbConcepts.setModelColumn(1)
            self.tableDetails.setModel(self.editModel)
            self.tableDetails.setColumnHidden(IDCUENTA, True)
            self.tableDetails.setColumnHidden(IDDOCUMENTOC, True)
            self.tableDetails.setItemDelegate(delegate)

            self.status = True

            self.tableDetails.resizeColumnsToContents()
        except UserWarning as inst:
            self.status = False
            QMessageBox.critical(self, qApp.organizationName(), unicode(inst))
            logging.error(unicode(inst))
        except Exception as inst:
            QMessageBox.critical(self, qApp.organizationName(), "Hubo un error al tratar de iniciar un nuevo ajuste")
            logging.critical(unicode(inst))
            self.status = False

    @pyqtSlot("QString")
    def on_txtSearch_textChanged(self, text):

        self.navproxymodel.setFilterRegExp(text)

    def save(self):
        query = QSqlQuery()

        try:
            if not self.editModel.valid:
                raise UserWarning("El documento no es valido, no se puede guardar")

            if not self.database.isOpen():
                if not self.database.open():
                    raise UserWarning("No se pudo conectar con la base de datos")

            if not self.database.transaction():
                raise Exception(u"No se pudo comenzar la transacción")
            #               Cargar el numero del asiento actual
            query.prepare(
                """
            SELECT
                  MAX(CAST(ndocimpreso AS SIGNED))+1
            FROM documentos d
            WHERE idtipodoc=24
            ;
            """
            )

            query.exec_()
            query.first()

            n = query.value(0).toString()
            if n == "0":
                n = "1"

            if not query.prepare(
                """
            INSERT INTO documentos (ndocimpreso, fechacreacion, idconcepto,   idtipodoc)
            VALUES (:ndocimpreso, :fechacreacion, :idconcepto,  %d)
            """
                % constantes.IDAJUSTECONTABLE
            ):
                raise Exception("No se pudo preparar la consulta para guardar el documento")
            query.bindValue(":ndocimpreso", n)
            query.bindValue(":fechacreacion", self.dtPicker.dateTime().toString("yyyyMMddhhmmss"))
            query.bindValue(
                ":idconcepto", self.conceptsmodel.record(self.cbConcepts.currentIndex()).value("idconcepto").toInt()[0]
            )

            if not query.exec_():
                raise Exception("No se pudo ejecutar la consulta para guardar el asiento")

            insertedId = query.lastInsertId().toInt()[0]

            if not query.prepare(
                """
            INSERT INTO personasxdocumento (idpersona, iddocumento, idaccion) 
            VALUES (:usuario, :documento, :idaccion)
            """
            ):
                raise Exception("No se pudo preparar la consulta para insertar el usuario")
            query.bindValue(":usuario", self.user.uid)
            query.bindValue(":documento", insertedId)
            query.bindValue(":idaccion", constantes.ACCCREA)

            if not query.exec_():
                raise Exception(u"No se pudo guardar la relación con el usuario")

            for lineid, line in enumerate(self.editModel.lines):
                if line.valid:
                    line.save(insertedId, lineid + 1)

            if not self.database.commit():
                raise Exception("No se pudo ejecutar la transaccion")
            self.tableDetails.setModel(self.detailsproxymodel)
            self.updateModels()

            self.status = False
        except UserWarning as inst:
            QMessageBox.critical(self, qApp.organizationName(), unicode(inst))
            logging.error(inst)
        except Exception as inst:
            QMessageBox.critical(self, qApp.organizationName(), "Hubo un error al tratar de guardar su ajuste")
            self.database.rollback()
            logging.critical(inst)
            logging.critical(query.lastError().text())
        finally:
            if self.database.isOpen():
                self.database.close()
Beispiel #9
0
class FileDialog(QDialog, Ui_FileDialog):
    """
  FileDialog class
  """

    #############################################################################
    def __init__(self, parent=None):
        """
    initialize the widget
    """
        QDialog.__init__(self, parent)
        Ui_FileDialog.__init__(self)
        self.setupUi(self)
        #flags = 0
        #flags = Qt.Window | Qt.WindowMinimizeButtonHint;
        #self.setWindowFlags( flags )
        self.hideTckFilter()
        self.__controler = ControlerFileDialog(self, parent.getControler())
        self.connect(self.closeButton, SIGNAL("clicked()"),
                     self.__controler.close)
        self.connect(self.saveButton, SIGNAL("clicked()"),
                     self.__controler.save)
        self.connect(self.advancedSave, SIGNAL("clicked()"),
                     self.__controler.advancedSave)
        self.connect(self.nextButton, SIGNAL("clicked()"),
                     self.__controler.next)

        self.__model = {}
        self.__path = None
        self.__fileExtension = None
        self.__popUp = QMenu(self.tableView)

        self.__jobAction = QAction(self.tr("Job Info"), self.tableView)
        self.connect(self.__jobAction, SIGNAL("triggered()"),
                     self.__controler.jobinfo)
        self.__popUp.addAction(self.__jobAction)

        self.__ancesstorsAction = QAction(self.tr("Get Anccestors"),
                                          self.tableView)
        self.connect(self.__ancesstorsAction, SIGNAL("triggered()"),
                     self.__controler.getancesstots)
        self.__popUp.addAction(self.__ancesstorsAction)

        self.__loginfoAction = QAction(self.tr("Logginig informations"),
                                       self.tableView)
        self.connect(self.__loginfoAction, SIGNAL("triggered()"),
                     self.__controler.loggininginfo)
        self.__popUp.addAction(self.__loginfoAction)

        self.__copyAction = QAction(self.tr("Copy data"), self.tableView)
        self.connect(self.__copyAction, SIGNAL("triggered()"),
                     self.__controler.copy)
        self.__popUp.addAction(self.__copyAction)

        self.tableView.setContextMenuPolicy(Qt.CustomContextMenu)
        self.connect(self.tableView,
                     SIGNAL('customContextMenuRequested(QPoint)'),
                     self.popUpMenu)

        self.__advancedSave = AdvancedSave(self)
        self.__advancedSave.setFocus()

        self.__controler.addChild('AdvancedSave',
                                  self.__advancedSave.getControler())

        self.__historyDialog = HistoryDialog(self)
        self.__controler.addChild('HistoryDialog',
                                  self.__historyDialog.getControler())

        self.connect(self.tckcombo, SIGNAL('currentIndexChanged(QString)'),
                     self.getControler().tckChanged)
        self.__proxy = QSortFilterProxyModel()

        self.connect(self.tckButton, SIGNAL("clicked()"),
                     self.__controler.tckButtonPressed)
        self.connect(self.tckcloseButton, SIGNAL("clicked()"),
                     self.__controler.hideFilterWidget)

        self.filterWidget.setupControler(self)
        self.__controler.addChild('TckFilterWidget',
                                  self.filterWidget.getControler())

    #############################################################################
    def closeEvent(self, event):
        """handles the close action"""
        gLogger.debug(event)
        self.getControler().close()

    #############################################################################
    def getControler(self):
        """returns the controller"""
        return self.__controler

    #############################################################################
    def setModel(self, model):
        """sets the model"""
        self.__model = model

    def updateModel(self, model):
        """updates the model in case of change"""
        self.__model.update(model)

    #############################################################################
    def getModel(self):
        """returns the model"""
        return self.__model

    #############################################################################
    def setPath(self, path):
        """sets the path"""
        self.__path = path

    #############################################################################
    def getPath(self):
        """returns the path"""
        return self.__path

    #############################################################################
    def showNumberOfEvents(self, number):
        """shows the number of events"""
        self.lineEdit_2.setText(str(number))

    #############################################################################
    def showNumberOfFiles(self, number):
        """shows the number of files"""
        self.lineEdit.setText(str(number))

    #############################################################################
    def showEventInputStat(self, number):
        """shows the number of processed input events"""
        self.alleventinputstat.setText(str(number))

    #############################################################################
    def showFilesSize(self, number):
        """shows the size of the files"""
        self.lineEdit_5.setText(str(number) + '  GB')

    #############################################################################
    def showSelectedNumberOfEvents(self, number):
        """shows the selected number of events"""
        self.lineEdit_4.setText(str(number))

    #############################################################################
    def showSelectedEventInputStat(self, number):
        """shows the selected processed input events"""
        self.eventInputstat.setText(str(number))

    #############################################################################
    def showSelectedNumberOfFiles(self, number):
        """shoes the selected number of files"""
        self.lineEdit_3.setText(str(number))

    #############################################################################
    def showSelectedFileSize(self, number):
        """shows the selected file size"""
        self.lineEdit_6.setText(str(number) + '  GB')

    #############################################################################
    def showTotalLuminosity(self, number):
        """shows the total luminosity"""
        self.alltotalluminosity.setText(str(number))

    #############################################################################
    def showSelectedTotalLuminosity(self, number):
        """selected total luminosity"""
        self.totalluminosity.setText(str(number))

    #############################################################################
    def showLuminosity(self, number):
        """luminosity"""
        self.allluminosity.setText(str(number))

    #############################################################################
    def showSelectedLuminosity(self, number):
        """selected luminosity"""
        self.luminosity.setText(str(number))

    #############################################################################
    def showError(self, message):
        """shows the message as an ERROR"""
        QMessageBox.critical(self, "ERROR", message, QMessageBox.Ok)

    #############################################################################
    def showData(self, data):
        """shows the files in the table widget"""
        self.waitCursor()

        tabledata = []

        header = [
            'FileName', 'EventStat', 'FileSize', 'CreationDate', 'JobStart',
            'JobEnd', 'WorkerNode', 'RunNumber', 'FillNumber', 'FullStat',
            'DataqualityFlag', 'EventInputStat', 'TotalLuminosity',
            'Luminosity', 'InstLuminosity', 'TCK'
        ]
        data.update(self.__model)
        keys = data.keys()
        keys.sort()
        for item in keys:
            lfn = data[item]
            i = []
            for info in header:
                value = lfn[info]
                if value == None:
                    value = ''
                i += [value]
            tabledata += [i]

        if len(tabledata) > 0:
            self.filltable(header, tabledata)
        self.arrowCursor()
        return True

    #############################################################################
    def filltable(self, header, tabledata):
        """ fill the table widget"""
        # set the table model

        tm = TableModel(tabledata, header, self)

        self.__proxy.setSourceModel(tm)

        self.tableView.setModel(self.__proxy)
        self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.tableView.setSelectionMode(QAbstractItemView.ExtendedSelection)

        self.tableView.setAlternatingRowColors(True)

        sm = self.tableView.selectionModel()
        self.connect(
            sm, SIGNAL("selectionChanged(QItemSelection, QItemSelection)"),
            self.__controler.selection)

        # set the minimum size
        self.setMinimumSize(400, 300)

        # hide grid
        self.tableView.setShowGrid(True)

        # set the font
        #font = QFont("Courier New", 12)
        #self.tableView.setFont(font)

        # hide vertical header
        vh = self.tableView.verticalHeader()
        vh.setVisible(True)

        # set horizontal header properties
        hh = self.tableView.horizontalHeader()
        hh.setStretchLastSection(True)

        # set column width to fit contents
        self.tableView.resizeColumnsToContents()
        self.tableView.setSortingEnabled(True)

        # set row height
        nrows = len(tabledata)
        for row in xrange(nrows):
            self.tableView.setRowHeight(row, 18)

        self.__proxy.sort(0, Qt.AscendingOrder)
        # enable sorting
        # this doesn't work
        #tv.setSortingEnabled(True)

    #############################################################################
    def saveAs(self, filename=''):
        """saves the selected files"""
        saveDialog = QFileDialog(
            self, 'Feicim Save file(s) dialog', QDir.currentPath(),
            'Python option(*.py);;Option file (*.opts);;Text file (*.txt);;CSV (*.csv)'
        )
        saveDialog.setAcceptMode(QFileDialog.AcceptSave)

        saveDialog.selectFile(filename)
        #self.connect(saveDialog, SIGNAL("filterSelected(const QString &)"),self.filter )
        ##saveDialog.setDirectory (QDir.currentPath())
        #filters = ['Option file (*.opts)' ,'Pool xml file (*.xml)','*.txt']
        #filters = ['Option file (*.opts)','*.py','*.txt']
        #saveDialog.setFilter(';;'.join(filters))
        #saveDialog.setFilter('Option file (*.opts);;Text file (*.txt);;Python option')
        #saveDialog.setFileMode(QFileDialog.AnyFile)
        #saveDialog.setViewMode(QFileDialog.Detail)

        ext = ''
        if saveDialog.exec_():
            filename = str(saveDialog.selectedFiles()[0])
            ext = saveDialog.selectedFilter()
            if 'Text file (*.txt)' in ext:
                if not filename.endswith('.txt'):
                    filename += '.txt'
            elif 'Option file (*.opts)' in ext:
                if not filename.endswith('.opts'):
                    filename += '.opts'
            elif 'Python option(*.py)' in ext:
                if not filename.endswith('.py'):
                    filename += '.py'
            elif 'CSV (*.csv)' in ext:
                if not filename.endswith('.csv'):
                    filename += '.csv'
            try:
                open(filename)
            except IOError:
                pass
            else:
                response = QMessageBox.warning(self, "File dialog",
                                               "File exists, overwrite?",
                                               QMessageBox.Ok, QMessageBox.No)
                if response == QMessageBox.No:
                    filename = ''
        if filename == '':
            return '', ''

        return filename, ext

    #############################################################################
    def popUpMenu(self):
        """shows the popup menu"""
        self.__popUp.popup(QCursor.pos())

    #############################################################################
    def showSelection(self, in_dict):
        """ shows the Bookkeeping query, the selected dataset"""

        if in_dict.has_key('ConfigName'):
            self.configname.setText(in_dict["ConfigName"])

        if in_dict.has_key('ConfigVersion'):
            self.configversion.setText(in_dict["ConfigVersion"])

        if in_dict.has_key('ConditionDescription'):
            self.simulation.setText(in_dict["ConditionDescription"])

        if in_dict.has_key('ProcessingPass'):
            self.processing.setText(in_dict["ProcessingPass"])

        if in_dict.has_key('EventTypeId'):
            self.eventtype.setText(in_dict["EventTypeId"])

        if in_dict.has_key('Production'):
            self.production.setText('')

        if in_dict.has_key('FileType'):
            self.filetype.setText(in_dict["FileType"])

        self.progrnameandversion.setText('')

    #############################################################################
    def clearTable(self):
        """clear the elements from the table"""
        #self.tableView().clear()
        self.__model = {}

    #############################################################################
    def fillTckFilter(self, data):
        """fills the tck combo box"""
        tcks = data + ['All']

        self.tckcombo.clear()
        j = 0
        for i in tcks:
            self.tckcombo.addItem(i, QVariant(i))
            if i == 'All':
                self.tckcombo.setCurrentIndex(j)
            j += 1
        #self.tckcombo.view().setSelectionMode(QAbstractItemView.MultiSelection)

    #############################################################################
    def applyFilter(self, data):
        """performs filter over the files"""
        if data == 'All':
            gLogger.debug('applyFilter-ALL')
            self.__proxy.clear()
            self.__proxy.invalidateFilter()
            filterCondition = "^\\S+$"
            gLogger.debug('Filter condition:' + filterCondition)
            self.__proxy.setFilterKeyColumn(15)
            self.__proxy.setFilterRegExp(filterCondition)
            for row in xrange(self.__proxy.rowCount()):
                self.tableView.setRowHeight(row, 18)
        else:
            gLogger.debug('applyFilter-Selected')
            self.__proxy.setFilterKeyColumn(15)
            filterCondition = '%s' % (data)
            gLogger.debug('Filter condition:' + filterCondition)
            self.__proxy.setFilterRegExp(filterCondition)
            for row in xrange(self.__proxy.rowCount()):
                self.tableView.setRowHeight(row, 18)

    def applyListFilter(self, data):
        """specific filter"""
        gLogger.debug('applyListFilter')
        filterCondition = '\\b'
        cond = '('
        for i in data:
            cond += i
            cond += '|'
        cond = cond[:-1]
        filterCondition += cond + ')\\b'
        gLogger.debug('Filter condition:' + filterCondition)
        self.__proxy.setFilterKeyColumn(15)
        self.__proxy.setFilterRegExp(filterCondition)
        for row in xrange(self.__proxy.rowCount()):
            self.tableView.setRowHeight(row, 18)

    #############################################################################
    def showTckFilter(self):
        """shows the tcks"""
        self.tckButton.hide()
        self.tckcloseButton.show()
        self.tckcombo.hide()
        self.filterWidget.show()

    #############################################################################
    def hideTckFilter(self):
        """hides the tcks"""
        self.tckButton.show()
        self.tckcloseButton.hide()
        self.tckcombo.show()
        self.filterWidget.hide()

    #############################################################################
    def getLFNs(self):
        """returns the lfns"""
        lfns = []
        for row in xrange(self.__proxy.rowCount()):
            index = self.__proxy.index(
                row, 0)  # this add the files to my selected list
            lfns += [str(self.__proxy.data(index).toString())]
        return lfns

    #############################################################################
    def waitCursor(self):
        """shows the wait cursor"""
        self.setCursor(Qt.WaitCursor)

    #############################################################################
    def arrowCursor(self):
        """shows the normal cursor"""
        self.setCursor(Qt.ArrowCursor)
class ConfigurationDialog(QDialog, Ui_Configuration, SettingDialog):
    def __init__(self):
        QDialog.__init__(self)
        self.setupUi(self)
        self.settings = MySettings()
        SettingDialog.__init__(self, self.settings)

        # new declaration of ProjectFinder since changes can be cancelled
        self.projectFinder = ProjectFinder(self)

        # table model
        self.projectSearchModel = ProjectSearchModel(self.projectFinder)

        self.proxyModel = QSortFilterProxyModel(self)
        self.proxyModel.setSourceModel(self.projectSearchModel)
        self.projectSearchTable.setModel(self.proxyModel)

        header = self.projectSearchTable.horizontalHeader()
        header.setResizeMode(QHeaderView.ResizeToContents)

        # open/create QuickFinder file
        self.createFileButton.clicked.connect(self.createQFTSfile)
        self.openFileButton.clicked.connect(self.openQFTSfile)
        self.readQFTSfile()

        # project search
        self.addSearchButton.clicked.connect(self.addProjectSearch)
        self.removeSearchButton.clicked.connect(self.removeProjectSearch)
        self.editSearchButton.clicked.connect(self.editProjectSearch)
        self.refreshButton.clicked.connect(self.refreshProjectSearch)
        self.projectSearchTable.selectionModel().selectionChanged.connect(
            self.enableButtons)
        self.enableButtons()

        # geomapfish
        self.geomapfishCrsButton.clicked.connect(
            self.geomapfishCrsButtonClicked)

    def reject(self):
        if self.closeAndControl():
            QDialog.reject(self)

    def accept(self):
        if self.closeAndControl():
            QDialog.accept(self)

    def closeAndControl(self):
        self.projectFinder.close()
        for search in self.projectFinder.searches.values():
            if search.dateEvaluated is None:
                box = QMessageBox(
                    QMessageBox.Warning, "Quick Finder",
                    QCoreApplication.translate(
                        "Configuration dialog",
                        "Some searches are still not recorded to the file. Do you want to record them now ? "
                    ),
                    QMessageBox.Cancel | QMessageBox.Yes | QMessageBox.Close,
                    self)
                ret = box.exec_()
                if ret == QMessageBox.Cancel:
                    return False
                elif ret == QMessageBox.Yes:
                    self.refreshProjectSearch()
                    return False
        return True

    def readQFTSfile(self):
        filepath = self.qftsfilepath.text()
        self.projectFinder.setFile(filepath)
        self.projectSearchTable.setEnabled(self.projectFinder.isValid)
        self.projectSearchButtonsWidget.setEnabled(self.projectFinder.isValid)

    def createQFTSfile(self):
        prjPath = QgsProject.instance().homePath()
        filepath = QFileDialog.getSaveFileName(
            self, "Create Quickfinder index file", prjPath,
            "Quickfinder file (*.qfts)")
        if filepath:
            if filepath[-5:] != ".qfts":
                filepath += ".qfts"
            if path.isfile(filepath):
                remove(filepath)
            createFTSfile(filepath)
            self.qftsfilepath.setText(filepath)
            self.readQFTSfile()

    def openQFTSfile(self):
        prjPath = QgsProject.instance().homePath()
        filepath = QFileDialog.getOpenFileName(self,
                                               "Open Quickfinder index file",
                                               prjPath,
                                               "Quickfinder file (*.qfts)")
        if filepath:
            self.qftsfilepath.setText(filepath)
            self.readQFTSfile()

    def addProjectSearch(self):
        ProjectSearchDialog(self.projectFinder,
                            self.projectSearchModel).exec_()

    def removeProjectSearch(self):
        sel = self.selectedSearchIds()
        if len(sel) == 0:
            return
        box = QMessageBox(
            QMessageBox.Warning, "Quick Finder",
            QCoreApplication.translate(
                "Configuration dialog",
                "Are you sure to remove {0} search(es) ? ").format(len(sel)),
            QMessageBox.Yes | QMessageBox.Cancel, self)
        ret = box.exec_()
        if ret == QMessageBox.Cancel:
            return
        self.projectSearchModel.removeSearches(sel)

    def editProjectSearch(self):
        sel = self.selectedSearchIds()
        if len(sel) != 1:
            return
        if not self.projectSearchModel.searches.has_key(sel[0]):
            return
        search = self.projectSearchModel.searches[sel[0]]
        if search:
            ProjectSearchDialog(self.projectFinder, self.projectSearchModel,
                                search).exec_()

    def refreshProjectSearch(self):
        RefreshDialog(self.projectFinder, self.projectSearchModel,
                      self.selectedSearchIds()).exec_()

    def selectedSearchIds(self):
        selectedSearchId = []
        for idx in self.projectSearchTable.selectionModel().selectedRows():
            selectedSearchId.append(self.proxyModel.data(idx, SearchIdRole))
        return selectedSearchId

    def enableButtons(self):
        n = len(self.selectedSearchIds())
        self.removeSearchButton.setEnabled(n > 0)
        self.editSearchButton.setEnabled(n == 1)
        self.projectSearchButtonsWidget.setEnabled(self.projectFinder.isValid)

    def geomapfishCrsButtonClicked(self):
        dlg = QgsGenericProjectionSelector(self)
        dlg.setMessage('Select GeoMapFish CRS')
        dlg.setSelectedAuthId(self.geomapfishCrs.text())
        if dlg.exec_():
            self.geomapfishCrs.setText(dlg.selectedAuthId())