def setText(self, txt): if not self.labelFunction_: if QtWidgets.QApplication.multiLangEnabled() and txt: self.text_ = txt.decode("utf8") if self.text_ == txt: self.text_ = FLUtil.translate(self, "app", txt) else: self.text_ = txt else: dni = 0 argList = QtCore.QSArgumentList() argList << txt if self.domNodeData_ and not self.domNodeData_.isNull(): dni = FLDomDocument(self.domNodeData_) argList << dni v = self.labelFunction_(*argList) if v: txtFun = str(v) if QtWidgets.QApplication.multiLangEnabled() and txtFun: self.text_ = txtFun.decode("utf8") if self.text_ == txtFun: self.text_ = FLUtil.translate(self, "app", txtFun) else: self.text_ = txtFun if dni: del dni
def loadSVGStyle(self): fileName = QtCore.QFileDialog.getOpenFileName( "", FLUtil.translate(self, "app", "Fichero SVG (*.svg)"), self, FLUtil.translate(self, "app", "Cargar estilo SVG"), FLUtil.translate(self, "app", "Cargar estilo SVG")) if not fileName or fileName == "": return self.ui_.ledStyle.setText("file:" + fileName) self.updateReport()
def saveSVGStyle(self): util = FLUtil() if self.report_: fileName = QtCore.QFileDialog.getSaveFileName( "", util.translate(self, "app", "Fichero SVG (*.svg)"), self, util.translate(self, "app", "Guardar en SVG"), util.translate(self, "app", "Guardar en SVG") ) if not fileName or fileName == "": return if not fileName.upper().contains(".SVG"): fileName = fileName + ".svg" q = QtCore.QMessageBox.question( self, util.translate( self, "app", "Sobreescribir {}").format(fileName), util.translate( self, "app", "Ya existe un fichero llamado {}. ¿Desea sobreescribirlo?" ).format(fileName), util.translate(self, "app", "&Sí"), util.translate(self, "app", "&No"), "", 0, 1 ) if QtCore.QFile.exists(fileName) and q: return FLStylePainter.setSVGMode(True) self.updateReport() FLStylePainter.setSVGMode(False) fileNames = [] for i in range(self.report_.pageCount()): fname = fileName + str(i) fileNames.append(fname) page = self.report_.getPageAt(i) psize = self.report_.pageDimensions() page.setBoundingRect(QtCore.QRect(QtCore.QPoint(0, 0), psize)) page.save(fname, "svg") FLStylePainter.normalizeSVGFile(fileName, fileNames) self.updateReport()
def loadSVGStyle(self): util = FLUtil() fileName = QtCore.QFileDialog.getOpenFileName( "", util.translate(self, "app", "Fichero SVG (*.svg)"), self, util.translate(self, "app", "Cargar estilo SVG"), util.translate(self, "app", "Cargar estilo SVG") ) if not fileName or fileName == "": return self.ui_["ledStyle"].setText("file:" + fileName) self.updateReport()
def database(self, connectionName="default"): if not self.d: self.d = FLSqlConnectionsPrivate() if connectionName == "default": if not self.d.defaultDB: self.addDatabase(FLSqlDatabase()) return self.d.defaultDB if not self.d.dictDB: self.addDatabase(FLSqlDatabase()) return self.d.defaultDB ret = self.d.dictDB.get(connectionName) if not ret: print( FLUtil.translate( "FLSqlConnections::database : No existe la conexión '%s', se devuelve la conexión por defecto 'default'" % connectionName)) if not self.d.defaultDB: self.addDatabase(FLSqlDatabase()) ret = self.defaultDB return ret
def init1(self, actionName, parent = None): self.setFocusPolicy(QtGui.QWidget.NoFocus) if actionName.isEmpty(): self.action_ = False print(FLUtil.translate("app","FLFormSearchDB : Nombre de acción vacío")) return else: self.action_ = FLSqlConnections.database().manager().action(actionName) if not self.action_: print(FLUtil.translate("app","FLFormSearchDB : No existe la acción %s" % actionName)) return self.cursor_ = FLSqlCursor(self.action_.table(), True,"default", 0, 0, self) self.name_ = self.action_.name() self.initForm()
def saveSnapShot(self, pathFile): fi = QtCore.QFile(pathFile) if not fi.open(QtCore.QFile.WriteOnly): print("FLFormDB : " + FLUtil.translate( "sys", "Error I/O al intentar escribir el fichero %s" % pathFile)) return self.snapShot().save(fi, "PNG")
def exportToPdf(self): if self.slotsExportedDisabled_: return fileName = QtCore.QFileDialog.getSaveFileName( "", FLUtil.translate(self, "app", "Fichero PDF (*.pdf)"), self, FLUtil.translate(self, "app", "Exportar a PDF"), FLUtil.translate(self, "app", "Exportar a PDF")) if not fileName or fileName == "": return if not fileName.upper().contains(".PDF"): fileName = fileName + ".pdf" q = QtCore.QMessageBox.question( self, FLUtil.translate(self, "app", "Sobreescribir {}").format(fileName), FLUtil.translate( self, "app", "Ya existe un fichero llamado {}. ¿Desea sobreescribirlo?"). format(fileName), FLUtil.translate(self, "app", "&Sí"), FLUtil.translate(self, "app", "&No"), "", 0, 1) if QtCore.QFile.exists(fileName) and q: return self.slotPrintReportToPDF(fileName)
def inicialize2(self, *args, **kwargs): actionName = str(args[0][0]) parent = args[0][1] f = args[1] if parent: self.parent_ = parent else: self.parent_ = QtGui.QWidget(pineboolib.project.mainWidget(), actionName, f) self.layout = None self.mainWidget_ = None self.layoutButtons = None self.pushButtonCancel = None self.showed = False self.iface = None self.oldCursorCtxt = None self.isClosing_ = False self.initFocusWidget_ = None self.oldFormObj = None self.accepted_ = False self.setFocusPolicy(QtGui.QWidget.NoFocus) if actionName.isEmpty(): self.action_ = None print(FLUtil.translate("sys", "FLFormDB : Nombre de acción vacío")) return else: self.action_ = FLSqlConnections.database().manager().action( actionName) if not self.action_: print( FLUtil.translate( "sys", "FLFormDB : No existe la acción %s" % actionName)) return self.cursor_ = FLSqlCursor(self.action_.table(), True, "default", 0, 0, self) self.name_ = self.action_.name() self.initForm()
def exportFileCSVData(self): if self.slotsExportedDisabled_: return util = FLUtil() fileName = QFileDialog.getSaveFileName( self, util.translate("app", "Exportar a CSV"), "", util.translate("app", "Fichero CSV (*.csv *.txt)") ) if not fileName or fileName == "": return if not fileName.upper().contains(".CSV"): fileName = fileName + ".csv" q = QtCore.QMessageBox.question( self, util.translate("app", "Sobreescribir {}").format(fileName), util.translate( self, "app", "Ya existe un fichero llamado {}. ¿Desea sobreescribirlo?" ).format(fileName), util.translate("app", "&Sí"), util.translate("app", "&No"), "", 0, 1 ) if QtCore.QFile.exists(fileName) and q: return file = QtCore.QFile(fileName) if file.open(Qt.IO_WriteOnly): stream = QtCore.QTextStream(file) stream << self.csvData() << "\n" file.close() else: QtCore.QMessageBox.critical( self, util.translate("app", "Error abriendo fichero"), util.translate( "app", "No se pudo abrir el fichero {} para escribir: {}" ).format( fileName, QtWidgets.QApplication.translate( "QFile", file.errorString() ) ) )
def exportToPDF(self): if self.slotsExportedDisabled_: return util = FLUtil() fileName = QFileDialog.getSaveFileName( self, util.translate("app", "Exportar a PDF"), "", util.translate("app", "Fichero PDF (*.pdf)")) if fileName[0] == '': return if fileName[0].upper().find(".PDF") == -1: fileName = fileName[0] + ".pdf" if QtCore.QFile.exists(fileName): q = QMessageBox.question( self, util.translate("app", "Sobreescribir {}").format(fileName), util.translate( "app", "Ya existe un fichero llamado {}. ¿Desea sobreescribirlo?" ).format(fileName), util.translate("app", "&Sí"), util.translate("app", "&No"), "", 0, 1) if q: return self.slotPrintReportToPdf(fileName)
def inicialize2(self,*args, **kwargs): actionName = str(args[0][0]) parent = args[0][1] f = args[1] if parent: self.parent_ = parent else: self.parent_ = QtGui.QWidget(pineboolib.project.mainWidget(), actionName, f) self.layout = None self.mainWidget_ = None self.layoutButtons = None self.pushButtonCancel = None self.showed = False self.iface = None self.oldCursorCtxt = None self.isClosing_ = False self.initFocusWidget_ = None self.oldFormObj = None self.accepted_ = False self.setFocusPolicy(QtGui.QWidget.NoFocus) if actionName.isEmpty(): self.action_ = None print(FLUtil.translate("sys","FLFormDB : Nombre de acción vacío")) return else: self.action_ = FLSqlConnections.database().manager().action(actionName) if not self.action_: print(FLUtil.translate("sys","FLFormDB : No existe la acción %s" % actionName)) return self.cursor_ = FLSqlCursor(self.action_.table(), True, "default", 0, 0, self) self.name_ = self.action_.name() self.initForm()
def init1(self, actionName, parent=None): self.setFocusPolicy(QtGui.QWidget.NoFocus) if actionName.isEmpty(): self.action_ = False print( FLUtil.translate("app", "FLFormSearchDB : Nombre de acción vacío")) return else: self.action_ = FLSqlConnections.database().manager().action( actionName) if not self.action_: print( FLUtil.translate( "app", "FLFormSearchDB : No existe la acción %s" % actionName)) return self.cursor_ = FLSqlCursor(self.action_.table(), True, "default", 0, 0, self) self.name_ = self.action_.name() self.initForm()
def exportToPDF(self): if self.slotsExportedDisabled_: return util = FLUtil() fileName = QFileDialog.getSaveFileName( self, util.translate("app", "Exportar a PDF"), "", util.translate("app", "Fichero PDF (*.pdf)") ) if fileName[0] == '': return if fileName[0].upper().find(".PDF") == -1: fileName = fileName[0] + ".pdf" if QtCore.QFile.exists(fileName): q = QMessageBox.question( self, util.translate("app", "Sobreescribir {}").format(fileName), util.translate( "app", "Ya existe un fichero llamado {}. ¿Desea sobreescribirlo?" ).format(fileName), util.translate("app", "&Sí"), util.translate("app", "&No"), "", 0, 1 ) if q: return self.slotPrintReportToPdf(fileName)
def exportFileCSVData(self): if self.slotsExportedDisabled_: return fileName = QtCore.QFileDialog.getSaveFileName( "", FLUtil.translate(self, "app", "Fichero CSV (*.csv *.txt)"), self, FLUtil.translate(self, "app", "Exportar a CSV"), FLUtil.translate(self, "app", "Exportar a CSV")) if not fileName or fileName == "": return if not fileName.upper().contains(".CSV"): fileName = fileName + ".csv" q = QtCore.QMessageBox.question( self, FLUtil.translate(self, "app", "Sobreescribir {}").format(fileName), FLUtil.translate( self, "app", "Ya existe un fichero llamado {}. ¿Desea sobreescribirlo?"). format(fileName), FLUtil.translate(self, "app", "&Sí"), FLUtil.translate(self, "app", "&No"), "", 0, 1) if QtCore.QFile.exists(fileName) and q: return file = QtCore.QFile(fileName) if file.open(Qt.IO_WriteOnly): stream = QtCore.QTextStream(file) stream << self.csvData() << "\n" file.close() else: QtCore.QMessageBox.critical( self, FLUtil.translate(self, "app", "Error abriendo fichero"), FLUtil.translate( self, "app", "No se pudo abrir el fichero {} para escribir: {}").format( fileName, QtWidgets.QApplication.translate( "QFile", file.errorString())))
def sendEMailPdf(self): t = self.ui_.leDocumento.text() name = "informe.pdf" if not t or t == "" else t fileName = QtCore.QFileDialog.getSaveFileName( AQ_USRHOME + "/" + name + ".pdf", FLUtil.translate(self, "app", "Fichero PDF a enviar (*.pdf)"), self, FLUtil.translate(self, "app", "Exportar a PDF para enviar"), FLUtil.translate(self, "app", "Exportar a PDF para enviar")) if not fileName or fileName == "": return if not fileName.upper().contains(".PDF"): fileName = fileName + ".pdf" q = QtCore.QMessageBox.question( self, FLUtil.translate(self, "app", "Sobreescribir {}").format(fileName), FLUtil.translate( self, "app", "Ya existe un fichero llamado {}. ¿Desea sobreescribirlo?"). format(fileName), FLUtil.translate(self, "app", "&Sí"), FLUtil.translate(self, "app", "&No"), "", 0, 1) if QtCore.QFile.exists(fileName) and q: return autoCloseSave = self.autoClose_ self.slotPrintReportToPDF(fileName) self.autoClose_ = autoCloseSave FLUtil.writeSettingEntry("email/to", self.ui_.lePara.text()) FLUtil.writeSettingEntry("email/from", self.ui_.leDe.text()) FLUtil.writeSettingEntry("email/mailserver", self.ui_.leMailServer.text()) fi = QtCore.QFileInfo(fileName) name = fi.fileName() self.smtpClient_.setMailServer(self.ui_.leMailServer.text()) self.smtpClient_.setTo(self.ui_.lePara.text()) self.smtpClient_.setFrom(self.ui_.leDe.text()) asutxt = self.ui_.leAsunto.text() self.smtpClient_.setSubject(name if asutxt == "" else asutxt) self.smtpClient_.setBody(self.ui_.leCuerpo.text() + "\n\n") html = "<html><body><a href=\"http://abanq.org/\">" html += "<img src=\"cid:logo.png@3d8b627b6292\"/>" html += "</a><br/><br/></body></html>" self.smtpClient_.addTextPart(html, "text/html") self.smtpClient_.addAttachment(fileName) self.smtpClient_.startSend()
def slotRenderProgress(self, p): util = FLUtil() if not self.rptEngine_: return if not self.progress_: self.totalSteps_ = self.rptEngine_.getRenderSteps() if self.totalSteps_ <= 0: self.totalSteps_ = 1 self.progress_ = util.createProgressDialog( util.translate("app", "Creando informe..."), self.totalSteps_) # self.progress_.setMinimunDuration(self.M_PROGRESS_DELAY) self.progress_.canceled.connect(self.slotCancelPrinting) util.setProgress(p) QtWidgets.QApplication.processEvents()
def initForm(self): if self.cursor_ and self.cursor_.metadata(): caption = None if self.action_: self.cursor_.setAction(self.action_) caption = self.action_.caption() if not self.action_.description().isEmpty(): self.QtGui.QWhatsThis.add(self, self.action_.description()) self.idMDI_ = self.action_.name() if caption.isEmpty(): caption = self.cursor_.metadata().alias() self.setCaption(caption) self.bindIface() self.setCursor(self.cursor_) else: self.setCaption(FLUtil.translate("sys", "No hay metadatos"))
def exec(self, n=QString.null): if not self.cursor_: return QVariant() if self.loop and self.inExec_: print( FLUtil.translate( "app", "FLFormSearchDB::exec(): Se ha detectado una llamada recursiva" )) self.QWidget.show() if self.initFocusWidget_: self.initFocusWidget_.setFocus() return QVariant() self.inExec_ = True self.acceptingRejecting_ = False self.QWidget.show() if self.initFocusWidget_: self.initFocusWidget_.setFocus() if self.iface: aqApp.call("init", self.QSArgumentList(), self.iface) #if (!isClosing_ && !aqApp->project()->interpreter()->hadError()) #FIXME # QTimer::singleShot(0, this, SLOT(emitFormReady())); #FIXME self.accepted_ = False self.loop = True if not self.isClosing_ and not self.acceptingRejecting_: QtGui.QApplication.eventLoop().enterLoop() self.loop = False self.clearWFlags(Qt.WShowModal) v = None if self.accepted_ and not n.isEmpty(): v = self.cursor_.valueBuffer(n) else: v = QVariant() self.inExec_ = False return v
def initForm(self): if self.cursor_ and self.cursor_.metadata(): caption = None if self.action_: self.cursor_.setAction(self.action_) caption = self.action_.caption() if not self.action_.description().isEmpty(): self.QtGui.QWhatsThis.add(self, self.action_.description()) self.idMDI_ = self.action_.name() if caption.isEmpty(): caption = self.cursor_.metadata().alias() self.setCaption(caption) self.bindIface() self.setCursor(self.cursor_) else: self.setCaption(FLUtil.translate("sys" ,"No hay metadatos"))
def saveSVGStyle(self): if self.report_: fileName = QtCore.QFileDialog.getSaveFileName( "", FLUtil.translate(self, "app", "Fichero SVG (*.svg)"), self, FLUtil.translate(self, "app", "Guardar en SVG"), FLUtil.translate(self, "app", "Guardar en SVG")) if not fileName or fileName == "": return if not fileName.upper().contains(".SVG"): fileName = fileName + ".svg" q = QtCore.QMessageBox.question( self, FLUtil.translate(self, "app", "Sobreescribir {}").format(fileName), FLUtil.translate( self, "app", "Ya existe un fichero llamado {}. ¿Desea sobreescribirlo?" ).format(fileName), FLUtil.translate(self, "app", "&Sí"), FLUtil.translate(self, "app", "&No"), "", 0, 1) if QtCore.QFile.exists(fileName) and q: return FLStylePainter.setSVGMode(True) self.updateReport() FLStylePainter.setSVGMode(False) fileNames = [] for i in range(self.report_.pageCount()): fname = fileName + str(i) fileNames.append(fname) page = self.report_.getPageAt(i) psize = self.report_.pageDimensions() page.setBoundingRect(QtCore.QRect(QtCore.QPoint(0, 0), psize)) page.save(fname, "svg") FLStylePainter.normalizeSVGFile(fileName, fileNames) self.updateReport()
def exec(self, n = QString.null): if not self.cursor_: return QVariant() if self.loop and self.inExec_: print(FLUtil.translate("app","FLFormSearchDB::exec(): Se ha detectado una llamada recursiva")) self.QWidget.show() if self.initFocusWidget_: self.initFocusWidget_.setFocus() return QVariant() self.inExec_ = True self.acceptingRejecting_ = False self.QWidget.show() if self.initFocusWidget_: self.initFocusWidget_.setFocus() if self.iface: aqApp.call("init", self.QSArgumentList(), self.iface) #if (!isClosing_ && !aqApp->project()->interpreter()->hadError()) #FIXME # QTimer::singleShot(0, this, SLOT(emitFormReady())); #FIXME self.accepted_ = False self.loop = True if not self.isClosing_ and not self.acceptingRejecting_: QtGui.QApplication.eventLoop().enterLoop() self.loop = False self.clearWFlags(Qt.WShowModal) v = None if self.accepted_ and not n.isEmpty(): v = self.cursor_.valueBuffer(n) else: v = QVariant() self.inExec_ = False return v
def database(self, connectionName="default"): if not self.d: self.d = FLSqlConnectionsPrivate() if connectionName == "default": if not self.d.defaultDB: self.addDatabase(FLSqlDatabase()) return self.d.defaultDB if not self.d.dictDB: self.addDatabase(FLSqlDatabase()) return self.d.defaultDB ret = self.d.dictDB.get(connectionName) if not ret: print(FLUtil.translate("FLSqlConnections::database : No existe la conexión '%s', se devuelve la conexión por defecto 'default'" % connectionName)) if not self.d.defaultDB: self.addDatabase(FLSqlDatabase()) ret = self.defaultDB return ret
def metadata(self, n, quick=False): util = FLUtil() if not n: return None if isinstance(n, str): if not n or not self.db_.dbAux(): return None ret = False acl = False key = n stream = None isSysTable = (n[0:3] == "sys" or self.isSystemTable(n)) if not isSysTable: stream = self.db_.managerModules().contentCached("%s.mtd" % key) if not stream: qWarning( "FLManager : Error al cargar los metadatos para la tabla %s" % n) return None # if not key: # key = n if not isSysTable: for fi in self.cacheMetaData_: if fi.name() == key: ret = fi break else: for fi in self.cacheMetaDataSys_: if fi.name() == key: ret = fi break if not ret: if isSysTable: stream = self.db_.managerModules().contentCached("%s.mtd" % n) if not stream: qWarning("FLManager : " + util.tr( "Error al cargar los metadatos para la tabla %s" % n)) return None doc = QDomDocument(n) if not util.domDocumentSetContent(doc, stream): qWarning("FLManager : " + util.tr( "Error al cargar los metadatos para la tabla %s" % n)) return None docElem = doc.documentElement() ret = self.metadata(docElem, quick) if not ret: return None if not isSysTable and not ret.isQuery(): self.cacheMetaData_.append(ret) elif isSysTable: self.cacheMetaDataSys_.append(ret) else: acl = self._prj.acl() if ret.fieldsNamesUnlock(): ret = FLTableMetaData(ret) if acl: acl.process(ret) if not quick and not isSysTable and self._prj.consoleShown( ) and not ret.isQuery() and self.db_.mismatchedTable(n, ret): msg = util.tr( "La estructura de los metadatos de la tabla '%1' y su " "estructura interna en la base de datos no coinciden. " "Debe regenerar la base de datos.").arg(n) throwMsgWarning(self.db_, msg) return ret else: #QDomDoc name = None q = None a = None ftsfun = None v = True ed = True cw = False dl = False no = n.firstChild() while not no.isNull(): e = no.toElement() if not e.isNull(): if e.tagName() == "field": no = no.nextSibling() continue if e.tagName() == "name": name = e.text() no = no.nextSibling() continue if e.tagName() == "query": q = e.text() no = no.nextSibling() continue if e.tagName() == "alias": a = auto_qt_translate_text(e.text()) a = util.translate("Metadata", a) no = no.nextSibling() continue if e.tagName() == "visible": v = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "editable": ed = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "concurWarn": cw = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "detectLocks": dl = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "FTSFunction": ftsfun = (e.text() == "true") no = no.nextSibling() continue no = no.nextSibling() tmd = FLTableMetaData(name, a, q) cK = None assocs = [] tmd.setFTSFunction(ftsfun) tmd.setConcurWarn(cw) tmd.setDetectLocks(dl) no = n.firstChild() while not no.isNull(): e = no.toElement() if not e.isNull(): if e.tagName() == "field": f = self.metadataField(e, v, ed) if not tmd: tmd = FLTableMetaData(name, a, q) tmd.addFieldMD(f) if f.isCompoundKey(): if not cK: cK = FLCompoundKey() cK.addFieldMD(f) if f.associatedFieldName(): assocs.append(f.associatedFieldName()) assocs.append(f.associatedFieldFilterTo()) assocs.append(f.name()) no = no.nextSibling() continue no = no.nextSibling() tmd.setCompoundKey(cK) aWith = None aBy = None for it in assocs: if not aWith: aWith = it continue if not aBy: aBy = it continue tmd.field(it).setAssociatedField(tmd.field(aWith), aBy) if q and not quick: qry = self.query(q, tmd) if qry: fL = qry.fieldList() table = None field = None fields = tmd.fieldsNames().split(",") fieldsEmpty = (not fields) for it in fL: pos = it.find(".") if pos > -1: table = it[:pos] field = it[:pos] else: field = it if not (not fieldsEmpty and table == name and fields.find(field.lower())) == fields.end(): continue mtdAux = self.metadata(table, True) if mtdAux: fmtdAux = mtdAux.field(field) if mtdAux: isForeignKey = False if fmtdAux.isPrimaryKey( ) and not table == name: fmtdAux = FLFieldMetaData(fmtdAux) fmtdAux.setIsprimaryKey(False) fmtdAux.setEditable(False) newRef = (not isForeignKey) fmtdAuxName = fmtdAux.name().lower() if fmtdAuxName.find(".") == -1: fieldsAux = tmd.fieldsNames().split(",") if not fieldsAux.find( fmtdAuxName) == fieldsAux.end(): if not isForeignKey: fmdtAux = FLFieldMetaData(fmtdAux) fmtdAux.setName("%s.%s" % (tambe, field)) newRef = False if newRef: fmtdAux.ref() tmd.addFieldMD(fmtdAux) qry.deleteLater() acl = self._prj.acl() if acl: acl.process(tmd) return tmd
def doCommit(self, cur, notify=True): #if not cur or not aqApp or not qApp: #FIXMME if not cur: return False if not notify: self.emit(cur.autocommit()) if self.transaction_ > 0: if not cur.d.transactionsOpened_ == []: trans = cur.d.transactionsOpened_.pop() if not trans == self.transaction_: print( FLUtil.translate( "app", "FLSqlDatabase : El cursor va a terminar la transacción %s pero la última que inició es la %s" % (self.transaction_, trans))) else: print( FLUtil.translate( "app", "FLSqlDatabase : El cursor va a terminar la transacción %s pero no ha iniciado ninguna" % self.transaction_)) self.transaction_ = self.transaction_ - 1 else: return True if self.transaction_ == 0 and self.canTransaction(): #aqApp->statusHelpMsg(qApp->tr("Terminando transacción...")); #FIXME if self.db_.commit(): self.lastActiveCursor_ = None if not self.canSavePoint(): if self.currentSavePoint_: del self.currentSavePoint_ self.currentSavePoint_ = None self.stackSavePoints_.clear() self.queueSavePoints_.clear() if notify: cur.d.modeAccess_ = FLSqlCursor.BROWSE #aqApp.emitTransactionEnd(cur) cur.d.md5Tuples_ = self.db_.md5TuplesStateTable(cur.d.curName_) return True else: print( FLUtil.translate( "app", "FLSqlDatabase::doCommit : Fallo al intentar terminar transacción" )) return False else: #aqApp->statusHelpMsg(qApp->tr("Liberando punto de salvaguarda %1...").arg(transaction_)); if (self.transaction_ == 1 and self.canTransaction()) or ( self.transaction_ == 0 and not self.canTransaction()): if not self.canSavePoint(): if self.currentSavePoint_: del self.currentSavePoint_ self.currentSavePoint_ = None self.stackSavePoints_.clear() self.queueSavePoints_.clear() else: self.releaseSavePoint(self.transaction_) if notify: cur.d.modeAccess_ = FLSqlCursor.BROWSE return True if not self.canSavePoint(): for tempSavePoint in self.queueSavePoints_: tempSavePoint.setId(self.transaction_ - 1) if self.currentSavePoint_: self.queueSavePoints_.append(self.currentSavePoint_) self.currentSavePoint_ = None if not self.stackSavePoints_ == []: self.currentSavePoint_ = self.stackSavePoints_.pop() else: self.releaseSavePoint(self.transaction_) if notify: cur.d.modeAccess_ = FLSqlCursor.BROWSE return True
def doRollback(self, cur): #if not cur or not self.db_ or not aqApp or not qApp: #FIXME if not cur: return False cancel = False if self.interactiveGUI() and ( cur.d.modeAccess() == FLSqlCursor.INSERT or cur.d.modeAccess_ == FLSqlCursor.EDIT ) and cur.isModifiedBuffer() and cur.d.askForCancelChanges_: res = QtWidgets.QMessageBox.information( self, FLUtil.translate("app", "Cancelar cambios"), FLUtil.translate( "app", "Todos los cambios efectuados se cancelarán.¿Está seguro?" ), QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No | QtWidgets.QMessageBox.Default | QtWidgets.QMessageBox.Escape) if res == QtWidgets.QMessageBox.No: return False cancel = True if self.transaction_ > 0: if not cur.d.transactionsOpened_ == []: trans = cur.d.transactionsOpened_.pop() if not trans == self.transaction_: print( FLUtil.translate( "app", "FLSqlDatabase : El cursor va a deshacer la transacción %s pero la última que inició es la %s" % (self.transaction_, trans))) else: print( FLUtil.translate( "app", "FLSqlDatabase : El cursor va a deshacer la transacción %1 pero no ha iniciado ninguna" % self.transaction_)) self.transaction_ = self.transaction_ - 1 else: return True if self.transaction_ == 0 and self.canTransaction(): #aqApp->statusHelpMsg(qApp->tr("Deshaciendo transacción...")); #FIXME if self.db_.rollback(): self.lastActiveCursor_ = None if not self.canSavePoint(): if self.currentSavePoint_: del self.currentSavePoint_ self.currentSavePoint_ = None self.stackSavePoints_.clear() self.queueSavePoints_.clear() cur.d.modeAccess_ = FLSqlCursor.BROWSE if cancel: cur.select() #aqApp->emitTransactionRollback(cur); return True else: print( FLUtil.translate( "app", "FLSqlDatabase::doRollback : Fallo al intentar deshacer transacción" )) return False else: #aqApp->statusHelpMsg(qApp->tr("Restaurando punto de salvaguarda %1...").arg(transaction_)); if not self.canSavePoint(): for tempSavePoint in self.queueSavePoints_: tempId = tempSavePoint.id() if tempId > self.transaction_ or self.transaction_ == 0: tempSavePoint.undo() del tempSavePoint else: self.queueSavePoints_ if self.currentSavePoint_: self.currentSavePoint_.undo() del self.currentSavePoint_ self.currentSavePoint_ = None if not self.stackSavePoints_ == []: self.currentSavePoint_ = self.stackSavePoints_.pop() if self.transaction_ == 0: if self.currentSavePoint_: del self.currentSavePoint_ self.currentSavePoint_ = None self.stackSavePoints_.clear() self.queueSavePoints_.clear() else: self.rollbackSavePoint(self.transaction_) cur.d.modeAccess_ = FLSqlCursor.BROWSE return True
def metadataField(self, field, v=True, ed=True): if not field: return None util = FLUtil() ck = False n = None a = None ol = False rX = None assocBy = None assocWith = None so = None aN = True iPK = True c = False iNX = False uNI = False coun = False oT = False vG = True fullCalc = False trimm = False t = -1 l = 0 pI = 4 pD = 0 dV = None no = field.firstChild() while not no.isNull(): e = no.toElement() if not e.isNull(): if e.tagName() in ("relation", "associated"): no = no.nextSibling() continue if e.tagName() == "name": n = e.text() no = no.nextSibling() continue if e.tagName() == "alias": a = auto_qt_translate_text(e.text()) no = no.nextSibling() continue if e.tagName() == "null": aN = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "pk": iPK = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "type": if e.text() == "int": t = "int" elif e.text() == "uint": t = "uint" elif e.text() == "bool": t = "bool" elif e.text() == "double": t = "double" elif e.text() == "time": t = "time" elif e.text() == "date": t = "date" elif e.text() == "pixmap": t = "pixmap" elif e.text() == "bytearray": t = "bytearray" elif e.text() == "string": t = "string" elif e.text() == "stringlist": t = "stringlist" elif e.text() == "unlock": t = "unlock" elif e.text() == "serial": t = "serial" no = no.nextSibling() continue if e.tagName() == "length": l = int(e.text()) no = no.nextSibling() continue if e.tagName() == "regexp": rX = e.text() no = no.nextSibling() continue if e.tagName() == "default": if e.text().find("QT_TRANSLATE_NOOP") > -1: dV = auto_qt_translate_text(e.text()) else: dV = e.text() no = no.nextSibling() continue if e.tagName() == "outtransaction": oT = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "counter": coun = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "calculated": c = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "fullycalculated": fullCalc = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "trimmed": trimm = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "visible": v = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "visiblegrid": vG = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "editable": ed = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "partI": pI = int(e.text()) no = no.nextSibling() continue if e.tagName() == "partD": pD = int(e.text()) no = no.nextSibling() continue if e.tagName() == "index": iNX = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "unique": uNI = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "ck": ck = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "optionslist": ol = e.text() no = no.nextSibling() continue if e.tagName() == "searchoptions": so = e.text() no = no.nextSibling() continue no = no.nextSibling() f = FLFieldMetaData(n, util.translate("Metadata", a), aN, iPK, t, l, c, v, ed, pI, pD, iNX, uNI, coun, dV, oT, rX, vG, True, ck) f.setFullyCalculated(fullCalc) f.setTrimed(trimm) if ol: f.setOptionsList(ol) if not so == None: f.setSearchOptions(so) no = field.firstChild() while not no.isNull(): e = no.toElement() if not e.isNull(): if e.tagName() == "relation": f.addRelationMD(self.metadataRelation(e)) no = no.nextSibling() continue if e.tagName() == "associated": noas = e.firstChild() while not noas.isNull(): eas = noas.toElement() if not eas.isNull(): if eas.tagName() == "with": assocWith = eas.text() noas = noas.nextSibling() continue if eas.tagName() == "by": assocBy = eas.text() noas = noas.nextSibling() continue noas = noas.nextSibling() no = no.nextSibling() continue no = no.nextSibling() if assocWith and assocBy: f.setAssociatedField(assocWith, assocBy) return f
def doRollback(self, cur): #if not cur or not self.db_ or not aqApp or not qApp: #FIXME if not cur: return False cancel = False if self.interactiveGUI() and (cur.d.modeAccess() == FLSqlCursor.INSERT or cur.d.modeAccess_ == FLSqlCursor.EDIT) and cur.isModifiedBuffer() and cur.d.askForCancelChanges_: res = QtGui.QMessageBox.information(self,FLUtil.translate("app","Cancelar cambios"),FLUtil.translate("app","Todos los cambios efectuados se cancelarán.¿Está seguro?"), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No | QtGui.QMessageBox.Default | QtGui.QMessageBox.Escape) if res == QtGui.QMessageBox.No: return False cancel = True if self.transaction_ > 0: if not cur.d.transactionsOpened_ == []: trans = cur.d.transactionsOpened_.pop() if not trans == self.transaction_: print(FLUtil.translate("app","FLSqlDatabase : El cursor va a deshacer la transacción %s pero la última que inició es la %s" % (self.transaction_, trans))) else: print(FLUtil.translate("app","FLSqlDatabase : El cursor va a deshacer la transacción %1 pero no ha iniciado ninguna" % self.transaction_)) self.transaction_ = self.transaction_ -1 else: return True if self.transaction_ == 0 and self.canTransaction(): #aqApp->statusHelpMsg(qApp->tr("Deshaciendo transacción...")); #FIXME if self.db_.rollback(): self.lastActiveCursor_ = None if not self.canSavePoint(): if self.currentSavePoint_: del self.currentSavePoint_ self.currentSavePoint_ = None self.stackSavePoints_.clear() self.queueSavePoints_.clear() cur.d.modeAccess_ = FLSqlCursor.BROWSE if cancel: cur.select() #aqApp->emitTransactionRollback(cur); return True else: print(FLUtil.translate("app","FLSqlDatabase::doRollback : Fallo al intentar deshacer transacción")) return False else: #aqApp->statusHelpMsg(qApp->tr("Restaurando punto de salvaguarda %1...").arg(transaction_)); if not self.canSavePoint(): for tempSavePoint in self.queueSavePoints_: tempId = tempSavePoint.id() if tempId > self.transaction_ or self.transaction_ == 0: tempSavePoint.undo() del tempSavePoint else: self.queueSavePoints_ if self.currentSavePoint_: self.currentSavePoint_.undo() del self.currentSavePoint_ self.currentSavePoint_ = None if not self.stackSavePoints_ == []: self.currentSavePoint_ = self.stackSavePoints_.pop() if self.transaction_ == 0: if self.currentSavePoint_: del self.currentSavePoint_ self.currentSavePoint_ = None self.stackSavePoints_.clear() self.queueSavePoints_.clear() else: self.rollbackSavePoint(self.transaction_) cur.d.modeAccess_ = FLSqlCursor.BROWSE return True
def setFromObject(self, object): print("FLAccessControlMainWindow::setFromObject %s" % FLUtil.translate(self,"app","No implementado todavía."))
def metadata(self, n, quick): if quick is None: quick = False ret = self.metadataDev(n, quick) if not quick and ret and not ret.isQuery() and self.db_.mismatchedTable(n, ret): msg = FLUtil.translate("sys","La estructura de los metadatos de la tabla '%s' y su estructura interna en la base de datos no coinciden. Debe regenerar la base de datos." % n) print(msg) if n.isEmpty() or not self.db_.dbAux(): return False ret = False acl = False key = n stream = QString isSysTable = False if n[0:2] is "sys" or self.isSystemTable(n): isSysTable = True if not isSysTable: stream = self.db_.managerModules().contentCached(n + ".mtd", key) if stream.isEmpty(): print("FLManager : " + FLUtil.translate("sys","Error al cargar los metadatos para la tabla %s" % n)) return False if key.isEmpty(): key = n if self.cacheMetaData_ and not isSysTable: ret = self.cacheMetaData_.find(key) else if self.cacheMetaDataSys_ and isSysTable: ret = self.cacheMetaDataSys_.find(key) if not ret: if isSysTable: stream = self.db_.managerModules().contentCached(n + ".mtd") if stream.isEmpty(): print("FLManager : " + FLUtil.translate("sys","Error al cargar los metadatos para la tabla %s" % n)) return False ret = metadata(stream) if not ret: return False if self.cacheMetaData_ and not isSysTable and not ret.isQuery(): ret.setInCache() self.cacheMetaData_.insert(key, ret) else if self.cacheMetaDataSys_ and isSysTable: ret.setInCache() self.cacheMetaDataSys_.insert(key.ret) else: acl = aqApp.acl() if not ret.fieldsNamesUnlock().isEmpty(): ret = FLTableMetaData(ret) if acl: acl.process(ret) if not quick and not isSysTable and aqApp.consoleShow() and not ret.isQuery() and self.db_.mismatchedTable(n, ret): msg = FLUtil.translate("sys","La estructura de los metadatos de la tabla '%s' y su estructura interna en la base de datos no coinciden. Debe regenerar la base de datos." % n) print(msg) return ret
def printReportToPdf(self, outPdfFile): if self.report_ == 0: return False gs = QtWidgets.QApplication.gsExecutable() gsOk = False procTemp = QtCore.QProcess() procTemp.addArgument(gs) procTemp.addArgument("--version") gsOk = procTemp.start() del procTemp if not gsOk: m = QtCore.QMessageBox( FLUtil.translate(self, "app", "Falta Ghostscript"), FLUtil.translate( self, "app", "Para poder exportar a PDF debe instalar Ghostscript" "(http://www.ghostscript.com) y añadir\n" "el directorio de instalación a la ruta de" "búsqueda de programas\ndel sistema (PATH).\n\n"), Qt.QMessageBox.Critical, Qt.QMessageBox.Ok, Qt.QMessageBox.NoButton, Qt.QMessageBox.NoButton, self, 0, False) m.show() return False outPsFile = FLDiskCache.AQ_DISKCACHE_DIRPATH + "/outprintpdf.ps" outPsPdfFile = FLDiskCache.AQ_DISKCACHE_DIRPATH + "/outprintps.pdf" QtCore.QFile.remove(outPsFile) QtCore.QFile.remove(outPsPdfFile) if not self.printReportToPs(outPsFile): return False proc = QtCore.QProcess() proc.addArgument(gs) proc.addArgument("-q") proc.addArgument("-dBATCH") proc.addArgument("-dNOPAUSE") proc.addArgument("-dSAFER") proc.addArgument("-dCompatibilityLevel=1.4") proc.addArgument("-dPDFSETTINGS=/printer") proc.addArgument("-dAutoFilterColorImages=false") proc.addArgument("-sColorImageFilter=FlateEncode") proc.addArgument("-dAutoFilterGrayImages=false") proc.addArgument("-sGrayImageFilter=FlateEncode") proc.addArgument("-r{}".format(self.dpi_)) ps = self.report_.pageSize() if ps == QtPrintSupport.QPrinter.PageSize.A0: proc.addArgument("-sPAPERSIZE=a0") elif ps == QtPrintSupport.QPrinter.PageSize.A1: proc.addArgument("-sPAPERSIZE=a1") elif ps == QtPrintSupport.QPrinter.PageSize.A2: proc.addArgument("-sPAPERSIZE=a2") elif ps == QtPrintSupport.QPrinter.PageSize.A3: proc.addArgument("-sPAPERSIZE=a3") elif ps == QtPrintSupport.QPrinter.PageSize.A4: proc.addArgument("-sPAPERSIZE=a4") elif ps == QtPrintSupport.QPrinter.PageSize.A5: proc.addArgument("-sPAPERSIZE=a5") elif ps == QtPrintSupport.QPrinter.PageSize.B0: proc.addArgument("-sPAPERSIZE=b0") elif ps == QtPrintSupport.QPrinter.PageSize.B1: proc.addArgument("-sPAPERSIZE=b1") elif ps == QtPrintSupport.QPrinter.PageSize.B2: proc.addArgument("-sPAPERSIZE=b2") elif ps == QtPrintSupport.QPrinter.PageSize.B3: proc.addArgument("-sPAPERSIZE=b3") elif ps == QtPrintSupport.QPrinter.PageSize.B4: proc.addArgument("-sPAPERSIZE=b4") elif ps == QtPrintSupport.QPrinter.PageSize.B5: proc.addArgument("-sPAPERSIZE=b5") elif ps == QtPrintSupport.QPrinter.PageSize.Legal: proc.addArgument("-sPAPERSIZE=legal") elif ps == QtPrintSupport.QPrinter.PageSize.Letter: proc.addArgument("-sPAPERSIZE=letter") elif ps == QtPrintSupport.QPrinter.PageSize.Executive: proc.addArgument("-sPAPERSIZE=executive") else: sz = self.report_.pageDimensions() proc.addArgument("-dDEVICEWIDTHPOINTS={}".format(sz.width())) proc.addArgument("-dDEVICEHEIGHTPOINTS={}".format(sz.height())) proc.addArgument("-dAutoRotatePages=/PageByPage") proc.addArgument("-sOutputFile=" + outPsPdfFile) proc.addArgument("-sDEVICE=pdfwrite") proc.addArgument(outPsFile) if not proc.start(): del proc return False while proc.isRunning(): QtWidgets.QApplication.processEvents() del proc QtWidgets.QApplication.processEvents() proc = QtCore.QProcess() proc.addArgument(gs) proc.addArgument("-q") proc.addArgument("-dBATCH") proc.addArgument("-dNOPAUSE") proc.addArgument("-dSAFER") proc.addArgument("-dNODISPLAY") proc.addArgument("-dDELAYSAFER") proc.addArgument("--") proc.addArgument("pdfopt.ps") proc.addArgument(outPsPdfFile) proc.addArgument(outPdfFile) if not proc.start(): del proc return False while proc.isRunning(): QtWidgets.QApplication.processEvents() del proc QtWidgets.QApplication.processEvents() return True
def setText(self, txt): d = Qt.QDate() ret = None month = None day = None year = None val = None regexp = Qt.QRegExp( "[0-9][0-9](-|//)[0-9][0-9](-|//)[0-9][0-9][0-9][0-9]") if self.dataType_ == self.DataType.String: # if aqApp.multiLangEnabled() and txt: #FIXME if txt: self.text_ = txt.decode("utf8") if self.text_ == txt: self.text_ = FLUtil.translate(self, "app", txt) else: self.text_ = txt elif self.dataType_ == self.DataType.Integer: val = float(txt) if val < 0.5 and val > -0.5 and self.blankZero_: self.text_ = Qt.QString("") else: self.text_ = round(val, 0) self.formatNegValue() if (self.comma_): self.formatCommas() elif self.dataType_ == self.DataType.Float: val = float(txt) if val < 0.0000001 and val > -0.0000001 and self.blankZero_: self.text_ = Qt.QString("") else: self.text_ = round(val, self.precision_) self.formatNegValue() if (self.comma_): self.formatCommas() elif self.dataType_ == self.DataType.Date: if not txt: self.text_ = Qt.QString("") else: regexp.search(txt[0:]) ret = regexp.matchedLength() if ret == -1: year = txt[:4] day = txt[2:] month = txt[5:7] if int(year) != 0 and int(month) != 0 and int(day) != 0: d.setYMD(int(year), int(month), int(day)) self.text_ = MUtil.formatDate(d, self.format_) else: self.text_ = Qt.QString("") else: self.text_ = txt elif self.dataType_ == self.DataType.Currency: val = float(txt) if val < 0.01 and val > -0.01 and self.blankZero_: self.text_ = Qt.QString("") else: self.text_ = round(val, 2) self.formatNegValue() if self.comma_: self.formatCommas() self.text_ = self.text_ + str(self.currency_) elif self.dataType_ == self.DataType.Pixmap: if txt and not self.paintFunction_: if not self.pixmap_: self.pixmap_ = Qt.QPixmap() if Qt.QPixmapCache.find(txt[:100], self.pixmap_): if Qt.QFile.exists(txt): self.pixmap_.load(txt) else: self.pixmap_.loadFromData(txt) if not self.pixmap_.isNull(): Qt.QPixmapCache.insert(txt[:100], self.pixmap_) if self.pixmap_.isNull(): self.pixmap_ = False else: if self.pixmap_: self.pixmap_ = False elif self.dataType_ == self.DataType.Codbar: if txt and not self.paintFunction_: cb = FLCodBar(txt, self.codbarType_, 10, 1, 0, 0, True, Qt.black, Qt.white, self.codbarRes_) if not self.pixmap_: self.pixmap_ = Qt.QPixmap() if not cb.pixmap().isNull(): self.pixmap_ = cb.pixmap() else: self.pixmap_ = False else: if self.pixmap_: self.pixmap_ = False elif self.dataType_ == self.DataType.Bool: if txt.toUpper() == "FALSE" or txt.toUpper() == "F": self.text_ = FLUtil.translate(self, "app", "No") else: self.text_ = FLUtil.translate(self, "app", "Sí")
def printReportToPS(self, outPsFile): if self.report_ == 0: return False if False: # WIN32/MAC #FIXME return self.printGhostReportToPS(outPsFile) cnt = self.report_.pageCount() if cnt == 0: QtCore.QMessageBox.critical( self, "Kugar", FLUtil.translate(self, "app", "No hay páginas en el\ninforme para."), QtCore.QMessageBox.Ok, QtCore.QMessageBox.NoButton, QtCore.QMessageBox.NoButton) return False self.printer_ = QtPrintSupport.QPrinter( QtPrintSupport.QPrinter.HighResolution) self.printer_.setPageSize(self.report_.pageSize()) if self.printer_.pageSize() == QtPrintSupport.QPrinter.PageSize.Custom: self.printer_.setCustomPaperSize(self.report_.pageDimensions()) self.printer_.setOrientation(self.report_.pageOrientation()) self.printer_.setMinMax(1, cnt) self.printer_.setFromTo(1, cnt) self.printer_.setFullPage(True) self.printer_.setColorMode(self.colorMode_) self.printer_.setNumCopies(self.numCopies_) self.printer_.setOutputToFile(True) self.printer_.setOutputFileName(outPsFile) painter = QtGui.QPainter() printRev = False viewIdx = self.report_.getCurrentIndex() lpf = QtPrintSupport.QPrinter.PageOrder.LastPageFirst if self.printer_.pageOrder() == lpf: printRev = True printFrom = self.printer_.fromPage() - 1 printTo = self.printer_.toPage() printCnt = (printTo - printFrom) printCopies = self.printer_.numCopies() self.totalSteps_ = printCnt * printCopies currentStep = 1 self.printer_.setNumCopies(self.numCopies_) self.printer_.setResolution(self.dpi_) util = FLUtil() self.progress_ = util.createProgressDialog( FLUtil.translate(self, "app", "Imprimiendo Informe..."), self.totalSteps_) # self.progress_.setMinimunDuration(self.M_PROGRESS_DELAY) self.progress_.canceled.connect(self.slotCancelPrinting) util.setProgress(0) QtWidgets.QApplication.processEvents() painter.begin(self.printer_) pdm = self.printer_.device() dim = self.report_.pageDimensions() painter.setWindow(0, 0, dim.width(), dim.height()) painter.setViewport(0, 0, pdm.width(), pdm.height()) for j in range(printCopies): i = printFrom while i < printTo: if not self.printer_.aborted(): util.setProgress(currentStep) QtWidgets.QApplication.processEvents() if printRev: self.report_.setCurrentPage(i if printCnt == 1 else (printCnt - 1) - i) else: self.report_.setCurrentPage(i) page = self.report_.getCurrentPage() page.play(painter) if (i - printFrom) < (printCnt - 1): self.printer_.newPage() else: j = printCopies break i += 1 currentStep += 1 if j < (printCopies - 1): self.printer_.newPage() painter.end() self.report_.setCurrentPage(viewIdx) del self.printer_ return True
def printReport(self): if self.report_ == 0: return False self.report_.setPrintToPos(self.printToPos_) if self.report_.printToPos(): return self.printToPosReport() if False: # WIN32 #FIXME pass cnt = self.report_.pageCount() if cnt == 0: QtCore.QMessageBox.critical( self, "Kugar", FLUtil.translate(self, "app", "No hay páginas en el\ninforme para."), QtCore.QMessageBox.Ok, QtCore.QMessageBox.NoButton, QtCore.QMessageBox.NoButton) return False self.printer_ = QtPrintSupport.QPrinter( QtPrintSupport.QPrinter.HighResolution) self.printer_.setPageSize(self.report_.pageSize()) if self.printer_.pageSize() == self.printer_.Custom: self.printer_.setCustomPaperSize(self.report_.pageDimensions()) self.printer_.setOrientation(self.report_.pageOrientation()) self.printer_.setPrintRange(self.printer_.AllPages) self.printer_.setFromTo(1, cnt) self.printer_.setFullPage(True) self.printer_.setColorMode(self.colorMode_) self.printer_.setCopyCount(self.numCopies_) if self.printerName_ and self.printerName_ != "": self.printer_.setPrinterName(self.printerName_) printProg = self.printer_.printProgram() if printProg and printProg != "": self.printer_.setPrintProgram(printProg) printNow = True if not self.printerName_ or self.printerName_ == "": dialog = QtPrintSupport.QPrintDialog() if dialog.exec_() != dialog.Accepted: printNow = False # printNow = self.printer_.setup( # QtWidgets.QApplication.focusWidget()) if printNow: painter = QtGui.QPainter() printRev = False viewIdx = self.report_.getCurrentIndex() lpf = QtPrintSupport.QPrinter.LastPageFirst if self.printer_.pageOrder() == lpf: printRev = True printFrom = self.printer_.fromPage() - 1 printTo = self.printer_.toPage() printCnt = (printTo - printFrom) printCopies = self.printer_.copyCount() self.totalSteps_ = printCnt * printCopies currentStep = 1 self.printer_.setCopyCount(1) util = FLUtil() self.progress_ = util.createProgressDialog( util.translate("app", "Imprimiendo Informe..."), self.totalSteps_) # self.progress_.setMinimunDuration(self.M_PROGRESS_DELAY) self.progress_.canceled.connect(self.slotCancelPrinting) util.setProgress(0) QtWidgets.QApplication.processEvents() painter.begin(self.printer_) pdm = self.printer_.device() dim = self.report_.pageDimensions() painter.setWindow(0, 0, dim.width(), dim.height()) painter.setViewport(0, 0, pdm.width(), pdm.height()) for j in range(printCopies): i = printFrom while i < printTo: if not self.printer_.aborted(): util.setProgress(currentStep) QtWidgets.QApplication.processEvents() if printRev: self.report_.setCurrentPage(i if printCnt == 1 else (printCnt - 1) - i) else: self.report_.setCurrentPage(i) page = self.report_.getCurrentPage() page.play(painter) if (i - printFrom) < (printCnt - 1): self.printer_.newPage() else: j = printCopies break i += 1 currentStep += 1 if j < (printCopies - 1): self.printer_.newPage() painter.end() self.report_.setCurrentPage(viewIdx) del self.printer_ return True del self.printer_ return False
def metadata(self, n, quick=False): """ Para obtener definicion de una tabla de la base de datos, a partir de un fichero XML. El nombre de la tabla corresponde con el nombre del fichero mas la extensión ".mtd" que contiene en XML la descripción de la tablas. Este método escanea el fichero y construye/devuelve el objeto FLTableMetaData correspondiente, además realiza una copia de estos metadatos en una tabla de la misma base de datos para poder determinar cuando ha sido modificados y así, si es necesario, reconstruir la tabla para que se adapte a la nuevos metadatos. NO SE HACEN CHEQUEOS DE ERRORES SINTÁCTICOS EN EL XML. IMPORTANTE :Para que estos métodos funcionen correctamente, es estrictamente necesario haber creado la base de datos en PostgreSQL con codificación UNICODE; "createdb -E UNICODE abanq". @param n Nombre de la tabla de la base de datos de la que obtener los metadatos @param quick Si TRUE no realiza chequeos, usar con cuidado @return Un objeto FLTableMetaData con los metadatos de la tabla solicitada """ util = FLUtil() if not n: return None if isinstance(n, str): if not n or not self.db_.dbAux(): return None ret = False acl = False key = n stream = None isSysTable = (n[0:3] == "sys" or self.isSystemTable(n)) if not isSysTable: stream = self.db_.managerModules().contentCached("%s.mtd" % key) if not stream: qWarning( "FLManager : Error al cargar los metadatos para la tabla %s" % n) return None # if not key: # key = n if not isSysTable: for fi in self.cacheMetaData_: if fi.name() == key: ret = fi break else: for fi in self.cacheMetaDataSys_: if fi.name() == key: ret = fi break if not ret: if isSysTable: stream = self.db_.managerModules().contentCached("%s.mtd" % n) if not stream: qWarning("FLManager : " + util.tr( "Error al cargar los metadatos para la tabla %s" % n)) return None doc = QDomDocument(n) if not util.domDocumentSetContent(doc, stream): qWarning("FLManager : " + util.tr( "Error al cargar los metadatos para la tabla %s" % n)) return None docElem = doc.documentElement() ret = self.metadata(docElem, quick) if not ret: return None if not isSysTable and not ret.isQuery(): self.cacheMetaData_.append(ret) elif isSysTable: self.cacheMetaDataSys_.append(ret) else: acl = self._prj.acl() if ret.fieldsNamesUnlock(): ret = FLTableMetaData(ret) if acl: acl.process(ret) if not quick and not isSysTable and self._prj.consoleShown( ) and not ret.isQuery() and self.db_.mismatchedTable(n, ret): msg = util.translate( "application", "La estructura de los metadatos de la tabla '%1' y su estructura interna en la base de datos no coinciden.\n" "Debe regenerar la base de datos.").replace("%1", n) logger.warn(msg) # throwMsgWarning(self.db_, msg) return ret else: # QDomDoc name = None q = None a = None ftsfun = None v = True ed = True cw = False dl = False no = n.firstChild() while not no.isNull(): e = no.toElement() if not e.isNull(): if e.tagName() == "field": no = no.nextSibling() continue if e.tagName() == "name": name = e.text() no = no.nextSibling() continue if e.tagName() == "query": q = e.text() no = no.nextSibling() continue if e.tagName() == "alias": a = auto_qt_translate_text(e.text()) a = util.translate("Metadata", a) no = no.nextSibling() continue if e.tagName() == "visible": v = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "editable": ed = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "concurWarn": cw = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "detectLocks": dl = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "FTSFunction": ftsfun = (e.text() == "true") no = no.nextSibling() continue no = no.nextSibling() tmd = FLTableMetaData(name, a, q) cK = None assocs = [] tmd.setFTSFunction(ftsfun) tmd.setConcurWarn(cw) tmd.setDetectLocks(dl) no = n.firstChild() while not no.isNull(): e = no.toElement() if not e.isNull(): if e.tagName() == "field": f = self.metadataField(e, v, ed) if not tmd: tmd = FLTableMetaData(name, a, q) tmd.addFieldMD(f) if f.isCompoundKey(): if not cK: cK = FLCompoundKey() cK.addFieldMD(f) if f.associatedFieldName(): assocs.append(f.associatedFieldName()) assocs.append(f.associatedFieldFilterTo()) assocs.append(f.name()) no = no.nextSibling() continue no = no.nextSibling() tmd.setCompoundKey(cK) aWith = None aBy = None for it in assocs: if not aWith: aWith = it continue if not aBy: aBy = it continue if not tmd.field(it): continue tmd.field(it).setAssociatedField(tmd.field(aWith), aBy) if q and not quick: qry = self.query(q, tmd) if qry: fL = qry.fieldList() table = None field = None fields = tmd.fieldsNames() # .split(",") fieldsEmpty = (not fields) for it in fL: pos = it.find(".") if pos > -1: table = it[:pos] field = it[pos + 1:] else: field = it # if not (not fieldsEmpty and table == name and fields.find(field.lower())) != fields.end(): # print("Tabla %s nombre %s campo %s buscando en %s" % (table, name, field, fields)) # if not fieldsEmpty and table == name and (field.lower() in fields): Asi esta en Eneboo, pero incluye campos repetidos if not fieldsEmpty and (field.lower() in fields): continue mtdAux = self.metadata(table, True) if mtdAux: fmtdAux = mtdAux.field(field) if mtdAux: isForeignKey = False if fmtdAux.isPrimaryKey( ) and not table == name: fmtdAux = FLFieldMetaData(fmtdAux) fmtdAux.setIsPrimaryKey(False) fmtdAux.setEditable(False) # newRef = (not isForeignKey) fmtdAuxName = fmtdAux.name().lower() if fmtdAuxName.find(".") == -1: # fieldsAux = tmd.fieldsNames().split(",") fieldsAux = tmd.fieldsNames() # if not fieldsAux.find(fmtdAuxName) == fieldsAux.end(): if fmtdAuxName not in fieldsAux: if not isForeignKey: FLFieldMetaData(fmtdAux) # fmtdAux.setName("%s.%s" % (table, field)) # if newRef: # fmtdAux.ref() tmd.addFieldMD(fmtdAux) del qry acl = self._prj.acl() if acl: acl.process(tmd) return tmd
def sendEMailPDF(self): t = self.ui_.leDocumento.text() util = FLUtil() name = "informe.pdf" if not t or t == "" else t fileName = QtCore.QFileDialog.getSaveFileName( AQ_USRHOME + "/" + name + ".pdf", util.translate("app", "Fichero PDF a enviar (*.pdf)"), self, util.translate("app", "Exportar a PDF para enviar"), util.translate("app", "Exportar a PDF para enviar") ) if not fileName or fileName == "": return if not fileName.upper().contains(".PDF"): fileName = fileName + ".pdf" q = QtCore.QMessageBox.question( self, util.translate("app", "Sobreescribir {}").format(fileName), util.translate( self, "app", "Ya existe un fichero llamado {}. ¿Desea sobreescribirlo?" ).format(fileName), util.translate("app", "&Sí"), util.translate("app", "&No"), "", 0, 1 ) if QtCore.QFile.exists(fileName) and q: return autoCloseSave = self.autoClose_ self.slotPrintReportToPdf(fileName) self.autoClose_ = autoCloseSave util.writeSettingEntry("email/to", self.ui_["lePara"].text()) util.writeSettingEntry("email/from", self.ui_["leDe"].text()) util.writeSettingEntry( "email/mailserver", self.ui_["leMailServer"].text() ) fi = QtCore.QFileInfo(fileName) name = fi.fileName() self.smtpClient_.setMailServer(self.ui_["leMailServer"].text()) self.smtpClient_.setTo(self.ui_["lePara"].text()) self.smtpClient_.setFrom(self.ui_["leDe"].text()) asutxt = self.ui_["leAsunto"].text() self.smtpClient_.setSubject(name if asutxt == "" else asutxt) self.smtpClient_.setBody(self.ui_["leCuerpo"].text() + "\n\n") html = "<html><body><a href=\"http://abanq.org/\">" html += "<img src=\"cid:logo.png@3d8b627b6292\"/>" html += "</a><br/><br/></body></html>" self.smtpClient_.addTextPart(html, "text/html") self.smtpClient_.addAttachment(fileName) self.smtpClient_.startSend()
def doCommit(self, cur,notify = True): #if not cur or not aqApp or not qApp: #FIXMME if not cur: return False if not notify: self.emit(cur.autocommit()) if self.transaction_ > 0: if not cur.d.transactionsOpened_ == []: trans = cur.d.transactionsOpened_.pop() if not trans == self.transaction_: print(FLUtil.translate("app","FLSqlDatabase : El cursor va a terminar la transacción %s pero la última que inició es la %s" % (self.transaction_, trans))) else: print(FLUtil.translate("app","FLSqlDatabase : El cursor va a terminar la transacción %s pero no ha iniciado ninguna" % self.transaction_)) self.transaction_ = self.transaction_ -1 else: return True if self.transaction_ == 0 and self.canTransaction(): #aqApp->statusHelpMsg(qApp->tr("Terminando transacción...")); #FIXME if self.db_.commit(): self.lastActiveCursor_ = None if not self.canSavePoint(): if self.currentSavePoint_: del self.currentSavePoint_ self.currentSavePoint_ = None self.stackSavePoints_.clear() self.queueSavePoints_.clear() if notify: cur.d.modeAccess_ = FLSqlCursor.BROWSE #aqApp.emitTransactionEnd(cur) cur.d.md5Tuples_ = self.db_.md5TuplesStateTable(cur.d.curName_) return True else: print(FLUtil.translate("app","FLSqlDatabase::doCommit : Fallo al intentar terminar transacción")) return False else: #aqApp->statusHelpMsg(qApp->tr("Liberando punto de salvaguarda %1...").arg(transaction_)); if (self.transaction_ == 1 and self.canTransaction()) or (self.transaction_ == 0 and not self.canTransaction()): if not self.canSavePoint(): if self.currentSavePoint_: del self.currentSavePoint_ self.currentSavePoint_ = None self.stackSavePoints_.clear() self.queueSavePoints_.clear() else: self.releaseSavePoint(self.transaction_) if notify: cur.d.modeAccess_ = FLSqlCursor.BROWSE return True if not self.canSavePoint(): for tempSavePoint in self.queueSavePoints_: tempSavePoint.setId(self.transaction_ - 1) if self.currentSavePoint_: self.queueSavePoints_.append(self.currentSavePoint_) self.currentSavePoint_ = None if not self.stackSavePoints_ == []: self.currentSavePoint_ = self.stackSavePoints_.pop() else: self.releaseSavePoint(self.transaction_) if notify: cur.d.modeAccess_ = FLSqlCursor.BROWSE return True
def metadataField(self, field, v=True, ed=True): """ Crea un objeto FLFieldMetaData a partir de un elemento XML. Dado un elemento XML, que contiene la descripción de un campo de una tabla construye y agrega a una lista de descripciones de campos el objeto FLFieldMetaData correspondiente, que contiene dicha definición del campo. Tambien lo agrega a una lista de claves compuesta, si el campo construido pertenece a una clave compuesta. NO SE HACEN CHEQUEOS DE ERRORES SINTÁCTICOS EN EL XML. @param field Elemento XML con la descripción del campo @param v Valor utilizado por defecto para la propiedad visible @param ed Valor utilizado por defecto para la propiedad editable @return Objeto FLFieldMetaData que contiene la descripción del campo """ if not field: return None util = FLUtil() ck = False n = None a = None ol = False rX = None assocBy = None assocWith = None so = None aN = True iPK = True c = False iNX = False uNI = False coun = False oT = False vG = True fullCalc = False trimm = False t = -1 length = 0 pI = 4 pD = 0 dV = None no = field.firstChild() while not no.isNull(): e = no.toElement() if not e.isNull(): if e.tagName() in ("relation", "associated"): no = no.nextSibling() continue if e.tagName() == "name": n = e.text() no = no.nextSibling() continue if e.tagName() == "alias": a = auto_qt_translate_text(e.text()) no = no.nextSibling() continue if e.tagName() == "null": aN = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "pk": iPK = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "type": if e.text() == "int": t = "int" elif e.text() == "uint": t = "uint" elif e.text() == "bool": t = "bool" elif e.text() == "double": t = "double" elif e.text() == "time": t = "time" elif e.text() == "date": t = "date" elif e.text() == "pixmap": t = "pixmap" elif e.text() == "bytearray": t = "bytearray" elif e.text() == "string": t = "string" elif e.text() == "stringlist": t = "stringlist" elif e.text() == "unlock": t = "unlock" elif e.text() == "serial": t = "serial" no = no.nextSibling() continue if e.tagName() == "length": length = int(e.text()) no = no.nextSibling() continue if e.tagName() == "regexp": rX = e.text() no = no.nextSibling() continue if e.tagName() == "default": if e.text().find("QT_TRANSLATE_NOOP") > -1: dV = auto_qt_translate_text(e.text()) else: dV = e.text() no = no.nextSibling() continue if e.tagName() == "outtransaction": oT = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "counter": coun = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "calculated": c = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "fullycalculated": fullCalc = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "trimmed": trimm = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "visible": v = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "visiblegrid": vG = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "editable": ed = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "partI": pI = int(e.text()) no = no.nextSibling() continue if e.tagName() == "partD": pD = int(e.text()) no = no.nextSibling() continue if e.tagName() == "index": iNX = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "unique": uNI = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "ck": ck = (e.text() == "true") no = no.nextSibling() continue if e.tagName() == "optionslist": ol = e.text() no = no.nextSibling() continue if e.tagName() == "searchoptions": so = e.text() no = no.nextSibling() continue no = no.nextSibling() f = FLFieldMetaData(n, util.translate("Metadata", a), aN, iPK, t, length, c, v, ed, pI, pD, iNX, uNI, coun, dV, oT, rX, vG, True, ck) f.setFullyCalculated(fullCalc) f.setTrimed(trimm) if ol: f.setOptionsList(ol) if so is not None: f.setSearchOptions(so) no = field.firstChild() while not no.isNull(): e = no.toElement() if not e.isNull(): if e.tagName() == "relation": f.addRelationMD(self.metadataRelation(e)) no = no.nextSibling() continue if e.tagName() == "associated": noas = e.firstChild() while not noas.isNull(): eas = noas.toElement() if not eas.isNull(): if eas.tagName() == "with": assocWith = eas.text() noas = noas.nextSibling() continue if eas.tagName() == "by": assocBy = eas.text() noas = noas.nextSibling() continue noas = noas.nextSibling() no = no.nextSibling() continue no = no.nextSibling() if assocWith and assocBy: f.setAssociatedField(assocWith, assocBy) return f
def saveSnapShot(self, pathFile): fi = QtCore.QFile(pathFile) if not fi.open(QtCore.QFile.WriteOnly): print("FLFormDB : " + FLUtil.translate("sys", "Error I/O al intentar escribir el fichero %s" % pathFile)) return self.snapShot().save(fi, "PNG")