def handler(self, title): """Maneja el evento de click sobre cualquiera de los botones de cargar archivo, con el fin de abrir un diálogo que le permita al usuario seleccionar el archivo de su sistema de archivos.""" layerPath = QFileDialog.getSaveFileName(self, u'Crear archivo xls', '.', 'Archivo Excel (*.xls)') layerInfo = QFileInfo(layerPath) if layerPath == "" : return if len(layerInfo.fileName()) < 5: layerPath += ".xls" elif layerInfo.fileName()[-4: ] != ".xls": layerPath += ".xls" self.lineEditPath.setText(layerPath)
def downloadFile(self, url_to_download, fout): " get the file from remote url to local folder " url = QUrl(url_to_download) fileInfo = QFileInfo(url.path()) fileName = path.join(fout, str(fileInfo.fileName())) if QFile.exists(fileName): QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): QMessageBox.information( self, "ERROR", "Cant save the file %s: %s." % (fileName, self.outFile.errorString()) ) self.outFile = None return mode = QHttp.ConnectionModeHttp port = url.port() if port == -1: port = 0 self.http.setHost(url.host(), mode, port) self.httpRequestAborted = False tpath = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if tpath: tpath = str(tpath) else: tpath = sep # Download the file. print(" INFO: Blender Download Started ! ") self.httpGetId = self.http.get(tpath, self.outFile)
def redo(self): if self._ds is None: self._ds = self.receiver.sourceList.currentListElement() if self._ds is None: QMessageBox.warning(self.receiver, "DataSource not selected", "Please select one of the datasources") else: if self._ds.instance is None: dsEdit = DataSource.DataSource(self.receiver.sourceList) dsEdit.id = self._ds.id dsEdit.directory = self.receiver.sourceList.directory dsEdit.name = self.receiver.sourceList.elements[ self._ds.id].name self._ds.instance = dsEdit if self._ds.instance is not None: self._pathFile = self._ds.instance.getNewName() fi = QFileInfo(self._pathFile) self.name = unicode(fi.fileName()) if self.name[-4:] == '.xml': self.name = self.name[:-4] if self.name[-3:] == '.ds': self.name = self.name[:-3] self.directory = unicode(fi.dir().path()) logger.debug("EXEC dsourceSaveAs")
def exportXMLToFile(self): ''' NO DOCUMENTATION ''' assert self.has_selected_item() # Ask the users where they want to save the file start_dir = '' opus_home = os.environ.get('OPUS_HOME') if opus_home: start_dir_test = os.path.join(opus_home, 'project_configs') if start_dir_test: start_dir = start_dir_test configDialog = QFileDialog() filter_str = QString("*.xml") fd = configDialog.getSaveFileName(self.manager.base_widget, QString("Save As..."), QString(start_dir), filter_str) # Check for cancel if len(fd) == 0: return fileNameInfo = QFileInfo(QString(fd)) fileName = fileNameInfo.fileName().trimmed() fileNamePath = fileNameInfo.absolutePath().trimmed() saveName = os.path.join(str(fileNamePath), str(fileName)) # proper root node for XmlConfiguration root_node = Element('opus_project') import copy root_node.append(copy.deepcopy(self.selected_item().node)) # Write out the file ElementTree(root_node).write(saveName)
def verify(self): if self.ui.txtPath.text() == "": return filePathDirInfo = QFileInfo(self.ui.txtPath.text()) sName = filePathDirInfo.fileName() vectorName = sName[:len(sName) - 4] uri1 = "" if self.ui.cmbCurrentCrs.currentText( ) == self.ui.cmbDisplayCrs.currentText(): if self.ui.cmbCurrentCrs.currentText() == "DecimalDegree": uri1 = "file:" + self.ui.txtPath.text( ) + "?delimiter=%s&xField=%s&yField=%s&crs=epsg:4326" % ( "\t", "Long", "Lat") self.AddMapLayer(uri1, vectorName) else: uri1 = "file:" + self.ui.txtPath.text( ) + "?delimiter=%s&xField=%s&yField=%s&crs=epsg:32633" % ( "\t", "Long", "Lat") self.AddMapLayer(uri1, vectorName) else: if self.ui.cmbCurrentCrs.currentText() == "DecimalDegree": uri1 = "file:" + self.ui.txtPath.text( ) + "?delimiter=%s&xField=%s&yField=%s&crs=epsg:4326" % ( "\t", "Long", "Lat") self.AddMapLayer(uri1, vectorName) else: uri1 = "file:" + self.ui.txtPath.text( ) + "?delimiter=%s&xField=%s&yField=%s&crs=epsg:32633" % ( "\t", "Long", "Lat") self.AddMapLayer(uri1, vectorName)
def downloadFile(self): url = QUrl(self.downloadUrl) fileInfo = QFileInfo(url.path()) #fileName = fileInfo.fileName() fileName = self.targetDirectory + fileInfo.fileName() if QFile.exists(fileName): QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): QMessageBox.information(self, 'Error', 'Unable to save the file %s: %s.' % (fileName, self.outFile.errorString())) self.outFile = None return mode = QHttp.ConnectionModeHttp port = url.port() if port == -1: port = 0 self.http.setHost(url.host(), mode, port) self.httpRequestAborted = False print url path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if path: path = str(path) else: path = '/' # Right at the end we append the query string that is lost, the original author did not include this unfortunately. parsedUrl = urlparse(self.downloadUrl) if not parsedUrl.query == '': # fix this mess, otherwise leave it alone path = path + "?" + parsedUrl.query print path # Download the file. self.httpGetId = self.http.get(path, self.outFile)
def export(self): if self.__path is not None: default_export_path = self.__path else: default_export_path = PlotSettingsModel().getDefaultPlotPath() dialog = QFileDialog(self.__active_plot_panel) dialog.setFileMode(QFileDialog.AnyFile) # dialog.setNameFilter("Image (*.png);; PDF (*.pdf)") dialog.setNameFilter("Image (*.png)") dialog.setWindowTitle("Export plot") dialog.setDirectory(default_export_path) dialog.setOption(QFileDialog.DontUseNativeDialog, True) dialog.setLabelText(QFileDialog.FileType, "Select file type: ") dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.selectFile(self.getDefaultFileName()) if dialog.exec_(): result = dialog.selectedFiles() assert isinstance(result, QStringList) if len(result) == 1: file_info = QFileInfo(result[0]) self.__file_name = file_info.fileName() self.__path = file_info.path() self.__selected_file_type = dialog.selectedNameFilter() name = self.__active_plot_panel.getName() url = self.__active_plot_panel.getUrl() web_page = PlotWebPage("export - %s" % name) web_page.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) web_page.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff) web_page.setViewportSize(QSize(self.__width, self.__height)) self.__bridge = PlotBridge(web_page, url) self.__bridge.plotReady.connect(self.plotReady) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
def downloadFile(self, url_to_download, download_location): url = QUrl(url_to_download) fileInfo = QFileInfo(url.path()) #fileName = fileInfo.fileName() fileName = download_location + fileInfo.fileName() self.file_name = fileName print("Filename = " + fileName) if QFile.exists(fileName): QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): QMessageBox.information(self, 'Error', 'Unable to save the file %s: %s.' % (fileName, self.outFile.errorString())) self.outFile = None return mode = QHttp.ConnectionModeHttp port = url.port() if port == -1: port = 0 self.http.setHost(url.host(), mode, port) self.httpRequestAborted = False path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if path: path = str(path) else: path = '/' # Download the file. self.httpGetId = self.http.get(path, self.outFile) return fileName
def exportXMLToFile(self): """ NO DOCUMENTATION """ assert self.has_selected_item() # Ask the users where they want to save the file start_dir = "" opus_home = os.environ.get("OPUS_HOME") if opus_home: start_dir_test = os.path.join(opus_home, "project_configs") if start_dir_test: start_dir = start_dir_test configDialog = QFileDialog() filter_str = QString("*.xml") fd = configDialog.getSaveFileName( self.manager.base_widget, QString("Save As..."), QString(start_dir), filter_str ) # Check for cancel if len(fd) == 0: return fileNameInfo = QFileInfo(QString(fd)) fileName = fileNameInfo.fileName().trimmed() fileNamePath = fileNameInfo.absolutePath().trimmed() saveName = os.path.join(str(fileNamePath), str(fileName)) # proper root node for XmlConfiguration root_node = Element("opus_project") import copy root_node.append(copy.deepcopy(self.selected_item().node)) # Write out the file ElementTree(root_node).write(saveName)
def verify(self): if self.ui.txtPath.text() == "": return filePathDirInfo = QFileInfo(self.ui.txtPath.text()) sName = filePathDirInfo.fileName() vectorName = sName[:len(sName) - 4] uri1 = "" latCrs = define._latLonCrs #QgsCoordinateReferenceSystem(4326, QgsCoordinateReferenceSystem.EpsgCrsId) meterCrs = define._xyCrs # QgsCoordinateReferenceSystem(32633, QgsCoordinateReferenceSystem.EpsgCrsId) if self.ui.cmbCurrentCrs.currentText( ) == self.ui.cmbDisplayCrs.currentText(): if self.ui.cmbCurrentCrs.currentText() == "DecimalDegree": uri1 = "file:" + self.ui.txtPath.text( ) + "?delimiter=%s&xField=%s&yField=%s&crs=epsg:4326" % ( "\t", "Long", "Lat") self.AddMapLayer(uri1, vectorName, latCrs) else: uri1 = "file:" + self.ui.txtPath.text( ) + "?delimiter=%s&xField=%s&yField=%s&crs=epsg:32633" % ( "\t", "Long", "Lat") self.AddMapLayer(uri1, vectorName, meterCrs) else: if self.ui.cmbCurrentCrs.currentText() == "DecimalDegree": uri1 = "file:" + self.ui.txtPath.text( ) + "?delimiter=%s&xField=%s&yField=%s&crs=epsg:4326" % ( "\t", "Long", "Lat") self.AddMapLayer(uri1, vectorName, meterCrs) else: uri1 = "file:" + self.ui.txtPath.text( ) + "?delimiter=%s&xField=%s&yField=%s&crs=epsg:32633" % ( "\t", "Long", "Lat") self.AddMapLayer(uri1, vectorName, latCrs)
def dropEvent(self, event): for file in event.mimeData().urls(): fi = QFileInfo(QFile(file.toLocalFile())) if fi.suffix() in self.acceptedFormats: self.addImageToTable(fi.filePath(), self.table.rowCount()) else: self.statusBar.showMessage('File format of {} not supported'.format(fi.fileName()), 5000) event.accept()
def on_actionOpen_file_triggered(self): file_dialog = QFileDialog(self, self.tr("Open file(s)..."), filter=self.tr("FITS files (*.fit *.dst *.fits *.fts *.lilo *.lihi *.silo *.sihi *.mxlo *.mxhi *.rilo *.rihi *.vdlo *.vdhi)")) file_dialog.setFileMode(QFileDialog.ExistingFile) files = file_dialog.getOpenFileNames() if files: for file_ in files: file_info = QFileInfo(file_) file_path = str(file_info.filePath()) self.add_tab(file_path, file_info.fileName())
def dropEvent(self, event): for file in event.mimeData().urls(): fi = QFileInfo(QFile(file.toLocalFile())) if fi.suffix() in self.acceptedFormats: self.addImageToTable(fi.filePath(), self.table.rowCount()) else: self.statusBar.showMessage( 'File format of {} not supported'.format(fi.fileName()), 5000) event.accept()
def open_file(self, filePath): """ Try to read the currently selected file and print it out to the stdout. """ fileInfo = QFileInfo(filePath) fname = unicode(fileInfo.fileName()) name, ext = path.splitext(fname) if ext.lower() in u'.bmp .gif .ico .jpg .png .tif .xbm'.split(): # apertura come immagine message = u'Opening image {}...'.format(filePath) logging.info(message) self.status_bar.showMessage(message) pixmap = QPixmap(filePath) self.image_window = QScrollArea() self.image_label = QLabel() self.image_label.setPixmap(pixmap) self.image_window.setWidget(self.image_label) self.image_window.show() self.image_label.show() message = u'Image size: {}x{}'.format(pixmap.width(), pixmap.height()) self.status_bar.showMessage(message) else: message = u'Opening file {}...'.format(filePath) logging.info(message) self.status_bar.showMessage(message) nchars = 1000000 # number of first characters showed (temp) try: fobj = open(unicode(filePath), 'rb') except Exception as err: # [Errno 22] invalid mode ('r') or filename: PyQt4.QtCore.QString(u'F:/\u65e5\u672c.txt') print('open error: {}'.format(err)) logging.error(err) self.status_bar.showMessage(str(err)) else: try: data = fobj.read(nchars) except Exception as err: print('read error: {}'.format(err)) logging.error(err) self.status_bar.showMessage(str(err)) else: #sts, old_output = getstatusoutput('chardetect.py "{}"'.format(filePath)) dec = data.decode('utf-8') # override existing text window self.text_window.setPlainText(dec) if not self.text_window.isVisible(): self.text_window.show() status_msg = u"'{}' file read.".format(fname) if len(data) == nchars: status_msg += u' (NB: showed {:,} first bytes only!)'.format(nchars) self.status_bar.showMessage(status_msg) finally: fobj.close()
def funcionAgregar(self): homeUsuario = QDir.homePath() rutaPdf = QFileDialog.getOpenFileName( self, directory=homeUsuario) #indico que me abra en el home del usuario objetoPDF = QFileInfo(rutaPdf) #self.listWidget.addItem(QFileDialog.getOpenFileName()) self.listWidget.addItem(objetoPDF.fileName()) self.a.append(unicode(rutaPdf)) print(self.a) print("contenido de arreglo a")
def copyFiles(filesToCopy, out_dir): plugin_dir = pluginDir() for item in filesToCopy: dest_dir = os.path.join(out_dir, item.get("dest", "")) subdirs = item.get("subdirs", False) overwrite = item.get("overwrite", False) if debug_mode: qDebug(str(item)) qDebug("dest dir: %s" % dest_dir) # make destination directory QDir().mkpath(dest_dir) # copy files for f in item.get("files", []): fi = QFileInfo(f) dest = os.path.join(dest_dir, fi.fileName()) if fi.isRelative(): copyFile(os.path.join(plugin_dir, f), dest, overwrite) else: copyFile(f, dest, overwrite) # copy directories for d in item.get("dirs", []): fi = QFileInfo(d) source = os.path.join(plugin_dir, d) if fi.isRelative() else d dest = os.path.join(dest_dir, fi.fileName()) if subdirs: copyDir(source, dest, overwrite) else: # make destination directory QDir().mkpath(dest) # copy files in the source directory filenames = QDir(source).entryList(QDir.Files) for filename in filenames: copyFile(os.path.join(source, filename), os.path.join(dest, filename), overwrite)
def load(self): settings = QSettings() workpath = settings.value("workPath").toString() + "/" datapath = settings.value("dataPath").toString() + "/" if (platform.system() != "Linux"): workpath = workpath.replace("/","\\") datapath = datapath.replace("/","\\") filename = QtGui.QFileDialog.getOpenFileName(self, "Open MUSIC Output File", datapath,self.tr("Text Files (*.txt)")) if(filename != ""): finfo = QFileInfo(filename) self.ui.le_r.setText(QFileInfo(filename).fileName()) settings.setValue("dataPath",finfo.absolutePath()) if(os.path.exists(workpath + finfo.fileName())): selectedpath = str(finfo.absolutePath() + "/") if(platform.system() != "Linux"): selectedpath = selectedpath.replace("/","\\") if(selectedpath != str(workpath)): os.remove(str(workpath) + str(finfo.fileName())) copyfile(filename, str(workpath) + str(finfo.fileName())) else: copyfile(filename,str(workpath) + str(finfo.fileName())) self.loadTable(str(workpath) + str(finfo.fileName()))
def on_actionOpen_file_triggered(self): file_dialog = QFileDialog( self, self.tr("Open file(s)..."), filter=self. tr("FITS files (*.fit *.dst *.fits *.fts *.lilo *.lihi *.silo *.sihi *.mxlo *.mxhi *.rilo *.rihi *.vdlo *.vdhi)" )) file_dialog.setFileMode(QFileDialog.ExistingFile) files = file_dialog.getOpenFileNames() if files: for file_ in files: file_info = QFileInfo(file_) file_path = str(file_info.filePath()) self.add_tab(file_path, file_info.fileName())
def do_ftp_put(self): num = len(self.files) for i in range(num): file = self.files[i] fhandle = QFile(file) fhandle.open(QIODevice.ReadOnly) byte_array = QByteArray() byte_array.append(fhandle.readData(fhandle.size())) fileinfo = QFileInfo(file) filename = fileinfo.fileName() self.ftp.put(byte_array, filename) self.ftp.close()
def generate_recovery_filepath(filePath): """ Based on a filePath generate the name for the recovery File. """ # check if sconcho directory in user's home directory exists sconchoDirName = QDir.homePath() + "/.sconcho" sconchoDir = QDir(sconchoDirName) if not sconchoDir.exists(): status = sconchoDir.mkdir(sconchoDirName) recoveryFileInfo = QFileInfo(filePath) recoveryFilePath = sconchoDirName + "/" + \ recoveryFileInfo.fileName() + ".recovery" return recoveryFilePath
def createDb(self, fileName): '''Create a new spatialite database file :param fileName: the filename of the database file :returns: True if the file could be created :rtype: bool ''' try: db = sqlite.connect(fileName) cur = db.cursor() except OperationalError: self.bar.pushMessage(self.tr("SpatiaLite Database"), self.tr("Unable to create database file!"), level=QgsMessageBar.CRITICAL) return False try: db.enable_load_extension(True) except OperationalError: self.bar.pushMessage(self.tr("SpatiaLite Database"), self.tr("SQLITE Load_extension off!"), level=QgsMessageBar.INFO) cur.execute("Select initspatialmetadata(1)") db.commit() db.close fi = QFileInfo(fileName) if not fi.exists(): return False key = u'/SpatiaLite/connections/' + fi.fileName() + u'/sqlitepath' settings = QSettings() if not settings.contains(key): settings.setValue('/SpatiaLite/connections/selected', fi.fileName() + self.tr('@') + fi.canonicalFilePath()) settings.setValue(key, fi.canonicalFilePath()) self.bar.pushMessage(self.tr("SpatiaLite Database"), self.tr("Registered new database!"), level=QgsMessageBar.SUCCESS) return True
def load(self): settings = QSettings() workpath = settings.value("workPath").toString() + "/" datapath = settings.value("dataPath").toString() + "/" if (platform.system() != "Linux"): workpath = workpath.replace("/", "\\") datapath = datapath.replace("/", "\\") filename = QtGui.QFileDialog.getOpenFileName( self, "Open MUSIC Output File", datapath, self.tr("Text Files (*.txt)")) if (filename != ""): finfo = QFileInfo(filename) self.ui.le_r.setText(QFileInfo(filename).fileName()) settings.setValue("dataPath", finfo.absolutePath()) if (os.path.exists(workpath + finfo.fileName())): selectedpath = str(finfo.absolutePath() + "/") if (platform.system() != "Linux"): selectedpath = selectedpath.replace("/", "\\") if (selectedpath != str(workpath)): os.remove(str(workpath) + str(finfo.fileName())) copyfile(filename, str(workpath) + str(finfo.fileName())) else: copyfile(filename, str(workpath) + str(finfo.fileName())) self.loadTable(str(workpath) + str(finfo.fileName()))
def exportXMLToFile(self, inherited=True): ''' NO DOCUMENTATION ''' # Ask the users where they want to save the file start_dir = paths.get_project_configs_path() configDialog = QFileDialog() filter_str = QString("*.xml") fd = configDialog.getSaveFileName(self.manager.base_widget, QString("Save As..."), QString(start_dir), filter_str) # Check for cancel if len(fd) == 0: return fileNameInfo = QFileInfo(QString(fd)) fileName = fileNameInfo.fileName().trimmed() fileNamePath = fileNameInfo.absolutePath().trimmed() saveName = os.path.join(str(fileNamePath), str(fileName)) root_node = self.get_clean_copy_of_selected_node(inherited) ElementTree(root_node).write(saveName)
def pnlFileEvent_1(self): inputFilePath = QFileDialog.getOpenFileName( self, "Open Xml File", QCoreApplication.applicationDirPath(), "Xml Files (*.xml)") if inputFilePath == "": return fileInfo = QFileInfo(inputFilePath) self.pnlFile.Value = fileInfo.fileName() contents = None with open(inputFilePath, 'rb', 0) as tempFile: contents = tempFile.read() tempFile.close() bytes = FasDataBlockFile.CRC_Calculation(contents) string_0 = QString(inputFilePath) crcFileDir = string_0.left(string_0.length() - 3) + "crc" fileInfo = QFileInfo(crcFileDir) if self.rwFlag == "r": if not fileInfo.exists(): QMessageBox.warning(self, "Warning", "CRC file is not existing.") return crcFileContents = None with open(crcFileDir, 'rb', 0) as tempFileCrc: crcFileContents = tempFileCrc.read() tempFileCrc.close() if bytes != crcFileContents: self.pnlCalculatedCrcValue.textBox.setStyleSheet( "color: rgb(255, 0, 0);") else: self.pnlCalculatedCrcValue.textBox.setStyleSheet( "color: rgb(0, 0, 0);") self.pnlSuppliedCrcValue.Value = crcFileContents self.pnlCalculatedCrcValue.Value = bytes else: fileStream = open(crcFileDir, 'wb') fileStream.write(bytes) fileStream.close() self.pnlCalculatedCrcValue.Value = bytes
def redo(self): if self._cp is None: self._cp = self.receiver.componentList.currentListElement() if self._cp is None: QMessageBox.warning(self.receiver, "Component not selected", "Please select one of the components") else: if self._cp.instance is not None: self._pathFile = self._cp.instance.getNewName() fi = QFileInfo(self._pathFile) self.name = unicode(fi.fileName()) if self.name[-4:] == '.xml': self.name = self.name[:-4] self.directory = unicode(fi.dir().path()) self._cp.instance.name = self.name self._cp.instance.directory = self.directory if hasattr(self._cp, "id"): self.receiver.componentList.populateElements(self._cp.id) else: self.receiver.componentList.populateElements() logger.debug("EXEC componentSaveAs")
def downloadFile(self): url = QUrl(self.url_text.text()) if self.txt_location.text() == "": QDir.setCurrent("$HOME/Downloads") else: QDir.setCurrent(self.loc) self.statusbar.showMessage("Downloading") fileInfo = QFileInfo(url.path()) fileName = fileInfo.fileName() if QFile.exists(fileName): QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): QMessageBox.information( self, 'Error', 'Unable to save the file %s: %s.' % (fileName, self.outFile.errorString())) self.outFile = None return mode = QHttp.ConnectionModeHttp port = url.port() if port == -1: port = 0 self.http.setHost(url.host(), mode, port) self.httpRequestAborted = False path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if path: path = str(path) else: path = '$HOME/Downloads' # Download the file. self.httpGetId = self.http.get(path, self.outFile)
def downloadFile(self): url = QUrl(self.url_text.text()) if self.txt_location.text()=="": QDir.setCurrent("$HOME/Downloads") else: QDir.setCurrent(self.loc) self.statusbar.showMessage("Downloading") fileInfo = QFileInfo(url.path()) fileName = fileInfo.fileName() if QFile.exists(fileName): QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): QMessageBox.information(self, 'Error', 'Unable to save the file %s: %s.' % (fileName, self.outFile.errorString())) self.outFile = None return mode = QHttp.ConnectionModeHttp port = url.port() if port == -1: port = 0 self.http.setHost(url.host(), mode, port) self.httpRequestAborted = False path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if path: path = str(path) else: path = '$HOME/Downloads' # Download the file. self.httpGetId = self.http.get(path, self.outFile)
def download_finished(self): """ """ reply = self.sender() if reply.error(): print("Download failed. Error string:\n", reply.errorString()) print("Download finished! Reply:", reply) file_info = QFileInfo(reply.url().path()) file_name = file_info.fileName() file_path = self.current_path + '/' + file_name out_file = QFile(file_path) print("Path:", file_path) if QFile.exists(file_name): print("File exists") # TODO: Add better notification if not out_file.open(QIODevice.WriteOnly): out_file = None print("Failed to open file") # TODO: Add better notification out_file.write(reply.readAll()) out_file.close() reply.deleteLater()
def _update_path(self): if not self._use_suffix: self._viewer.set_path(self._current_path) return self._viewer.reset_path() if not self._current_path: return selected_file = QFileInfo(self._current_path) if not selected_file.exists(): return selected_dir = selected_file.absoluteDir() file_name = selected_file.fileName() if not selected_dir.exists(): return if not selected_dir.cd('converted'): return suffixed_path = selected_dir.absoluteFilePath(file_name) self._viewer.set_path(suffixed_path)
def addLayer(self): layerPath = QFileDialog.getOpenFileName(self, u'Abrir shapefile', '.', 'Shapefiles (*.shp)') layerInfo = QFileInfo(layerPath) layerProvider = 'ogr' # name = '/home/cbdavide/Documentos/Projects/shape-viewer/Colombia/Colombia.shp' # layer = QgsVectorLayer(name, 'ejje', layerProvider) layer = QgsVectorLayer(layerPath, layerInfo.fileName(), layerProvider) if not layer.isValid(): return # Cambiar el color del layer symbol_layer = layer.rendererV2().symbols()[0].symbolLayer(0) symbol_layer.setColor(QColor(176, 251, 163)) QgsMapLayerRegistry.instance().addMapLayer(layer) if self.canvas.layerCount() == 0: self.canvas.setExtent(layer.extent()) self.layers.insert(0, QgsMapCanvasLayer(layer)) self.canvas.setLayerSet(self.layers)
def export(self): if self.__path is not None: default_export_path = self.__path else: default_export_path = PlotSettingsModel().getDefaultPlotPath() dialog = QFileDialog(self.__active_plot_panel) dialog.setFileMode(QFileDialog.AnyFile) #dialog.setNameFilter("Image (*.png);; PDF (*.pdf)") dialog.setNameFilter("Image (*.png)") dialog.setWindowTitle("Export plot") dialog.setDirectory(default_export_path) dialog.setOption(QFileDialog.DontUseNativeDialog, True) dialog.setLabelText(QFileDialog.FileType, "Select file type: ") dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.selectFile(self.getDefaultFileName()) if dialog.exec_(): result = dialog.selectedFiles() assert isinstance(result, QStringList) if len(result) == 1: file_info = QFileInfo(result[0]) self.__file_name = file_info.fileName() self.__path = file_info.path() self.__selected_file_type = dialog.selectedNameFilter() name = self.__active_plot_panel.getName() url = self.__active_plot_panel.getUrl() web_page = PlotWebPage("export - %s" % name) web_page.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) web_page.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff) web_page.setViewportSize(QSize(self.__width, self.__height)) self.__bridge = PlotBridge(web_page, url) self.__bridge.plotReady.connect(self.plotReady) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
def __init__(self, IMC, parent=None): super(QDialog, self).__init__(parent) self.IMC = IMC self.setModal(True) self.setSizeGripEnabled(True) bookinfo = QFileInfo(IMC.bookPath) self.setWindowTitle("Properties of {0}".format(bookinfo.fileName())) # Our layout is a vertical stack of widgets and hboxes vlayout = QVBoxLayout() # Add the path information field fplb = QLabel("Path: {0}".format(unicode(bookinfo.path()))) fplb.setFrameStyle(QFrame.Sunken) fplb.setToolTip(QString("Full path to document")) vlayout.addWidget(fplb) # Add the write-encoding choice, setting the buttons to reflect # the current value. We build this up from the inside out. # Two radio buttons. As they will be exclusive we need connect # the toggled() signal from only one of them. self.saveEncoding = self.IMC.bookSaveEncoding rb_enc_utf = QRadioButton(QString("UTF-8")) rb_enc_utf.setChecked(self.saveEncoding == rb_enc_utf.text()) rb_enc_utf.toggled.connect(self.encodingChange) rb_enc_ltn = QRadioButton(QString("Latin-1")) rb_enc_ltn.setChecked(self.saveEncoding != rb_enc_utf.text()) # put the buttons in a layout because groupbox doesn't act as one hb_enc_btns = QHBoxLayout() hb_enc_btns.addWidget(rb_enc_utf) hb_enc_btns.addWidget(rb_enc_ltn) # add to groupbox to get exclusivity on the buttons gb_enc = QGroupBox() gb_enc.setLayout(hb_enc_btns) # put in horizontal box with descriptive label, and add to the dialog hb_enc = QHBoxLayout() lb_enc = QLabel("Write Encoding") lb_enc.setToolTip("Character encoding when writing the document") hb_enc.addWidget(lb_enc) hb_enc.addWidget(gb_enc) vlayout.addLayout(hb_enc) # Next get a QStringList of available dicts from pqSpell # and create a combobox with that content. dictlist = IMC.spellCheck.dictList() dictlist.sort() self.maintag = self.IMC.bookMainDict if self.maintag.isEmpty(): self.maintag = self.IMC.spellCheck.mainTag current = dictlist.indexOf(QString(self.maintag)) # index of current dict or -1 self.cb_dic = QComboBox() self.cb_dic.addItems(dictlist) if current >= 0: self.cb_dic.setCurrentIndex(current) self.cb_dic.activated.connect(self.dictChange) hb_dic = QHBoxLayout() hb_dic.addWidget(QLabel("Main Dictionary")) hb_dic.addStretch() hb_dic.addWidget(self.cb_dic) vlayout.addLayout(hb_dic) # create the [ apply cancel ] buttons, but apply == accept apply_button = QPushButton("Apply") cancel_button = QPushButton("Cancel") cancel_button.setDefault(True) bbox = QDialogButtonBox() bbox.addButton(cancel_button, QDialogButtonBox.RejectRole) bbox.addButton(apply_button, QDialogButtonBox.AcceptRole) bbox.accepted.connect(self.applyButtonHit) bbox.rejected.connect(self.cancelButtonHit) vlayout.addWidget(bbox) self.setLayout(vlayout)
class DocumentWidget(QWidget, Ui_frmDocumentItem): """ Widget for displaying source document details """ # Reference removed signal is raised prior # to destroying the widget. referencesRemoved = pyqtSignal(int) fileUploadComplete = pyqtSignal() def __init__( self, document_model=None, fileManager=None, mode=UPLOAD_MODE, parent=None, canRemove=True, view_manager=None ): QWidget.__init__(self, parent) self.setupUi(self) self.initGui() self.fileInfo = None self.fileUUID = None self.document_model = document_model self.fileManager = fileManager self._mode = mode self._displayName = "" self._docSize = 0 self._srcDoc = None self._fileName = "" self._canRemove = canRemove self._view_manager = view_manager self.curr_profile = current_profile() self.removed_doc = [] self.lblClose.installEventFilter(self) self.lblName.installEventFilter(self) self._source_entity = "" self._doc_type = "" self._doc_type_id = None #Set defaults self.fileNameColor = "#5555ff" self.fileMetaColor = "#8f8f8f" def eventFilter(self,watched,e): """ Capture label mouse release events for deleting and opening a source document respectively. """ if QEvent is None: return False if watched == self.lblClose and e.type() == QEvent.MouseButtonRelease: self.removeDocument() return True elif watched == self.lblName and e.type() == QEvent.MouseButtonRelease: self.openDocument() return True else: return QWidget.eventFilter(self,watched,e) def initGui(self): """ Initialize GUI """ self.lblName.clear() self.pgBar.setVisible(False) self.pgBar.setValue(0) def mode(self): """ Returns the mode that the widget is configured to run. Returns either UPLOAD_MODE or DOWNLOAD_MODE. """ return self._mode def view_manager(self): """ Manager for viewing the document contents. """ return self._view_manager def removeDocument(self): """ Destroy the document widget and removes file references in the network drive and corresponding database record. """ msgConfirm = QApplication.translate("DocumentWidget", """Are you sure you want to delete this document? This action cannot be undone. \nClick Yes to proceed or No to cancel.""") response = QMessageBox.warning(self.parent(), QApplication.translate("DocumentWidget", "Delete Source Document"), msgConfirm, QMessageBox.Yes | QMessageBox.No) if response == QMessageBox.No: return self._remove_doc() def clean_up(self): """ Remove the referenced uploaded file which has not yet been saved. :return: True to indicate that the document was successfully removed or False if an error was encountered. :rtype: bool """ if self._mode == UPLOAD_MODE: return self._remove_doc(True) return True def _remove_doc(self, suppress_messages=False): """ :param suppress_messages: Set whether user messages should be displayed or the system should continue with execution. :type suppress_messages: bool :return: True to indicate that the document was successfully removed or False if an error was encountered. :rtype: bool """ status = True if self._mode == UPLOAD_MODE: status = self.fileManager.deleteDocument() else: doc_type = self.doc_type_value() self.removed_doc.append(self._srcDoc) # Before anything, we check if file exist! if self.fileManager.file_exist(self._srcDoc, doc_type): status = self.fileManager.deleteDocument(self._srcDoc, doc_type) if not status: if not suppress_messages: msg = QApplication.translate("DocumentWidget", "The system could not delete the document. Please " "check your document repository settings.") QMessageBox.critical(self.parent(), QApplication.translate("DocumentWidget", "Delete Source Document"), msg) return False if self._mode == DOWNLOAD_MODE: #Try to delete document and suppress error if it does not exist try: self._srcDoc.delete() # Remove the same document from supporting # doc table linked to other str record as the file doesn't exist. doc_obj = self.document_model() other_party_doc = doc_obj.queryObject().filter( self.document_model.document_identifier == self._srcDoc.document_identifier ).all() for docs in other_party_doc: self.removed_doc.append(docs) docs.delete() except sqlalchemy.exc.SQLAlchemyError as exc: LOGGER.debug(str(exc)) #Emit signal to indicate the widget is ready to be removed self.referencesRemoved.emit(self._doc_type_id) self.deleteLater() return True def openDocument(self): """ Open the document referenced by this widget. """ if not self._view_manager is None: self._view_manager.load_viewer(self) def setCanRemoveDocument(self,state): """ Disable the close button so that users are not able to remove the document from the list. """ self.lblClose.setVisible(state) def setFile(self, dfile, source_entity, doc_type, doc_type_id): """ Set the absolute file path including the name, that is to be associated with the document widget. """ if self._mode == UPLOAD_MODE: self.fileInfo = QFileInfo(dfile) self._displayName = unicode(self.fileInfo.fileName()) self._docSize = self.fileInfo.size() self._source_entity = source_entity self._doc_type = doc_type self._doc_type_id = doc_type_id self.uploadDoc() self.buildDisplay() def setModel(self, sourcedoc): """ Set the SourceDocument model that is to be associated with the widget. Only valid if the widget mode is in DOWNLOAD_MODE. """ self.pgBar.setVisible(False) if self._mode == DOWNLOAD_MODE: self._displayName = sourcedoc.filename self._docSize = sourcedoc.document_size self.fileUUID = sourcedoc.document_identifier self._srcDoc = sourcedoc self._source_entity = sourcedoc.source_entity self._doc_type_id = sourcedoc.document_type self.buildDisplay() def doc_type_value(self): """ Returns the document type value. :return: the document type value in which a document is uploaded. :type: String :rtype: String """ entity = self.curr_profile.entity_by_name(self._source_entity) doc_type_entity = entity.supporting_doc.document_type_entity self._doc_type = entity_id_to_attr( doc_type_entity, 'value', self._doc_type_id ) return self._doc_type def doc_source_entity(self): """ Returns the document type (enumeration) that the widget currently references. """ return self._source_entity def set_source_entity(self, source_entity): """ Set the document type using its code. See enumeration options. """ self._source_entity = source_entity def displayName(self): """ Returns the original file name of the supporting document. """ return self._displayName def file_identifier(self): """ Returns the unique identifier of the file generated by the system upon uploading. """ return self.fileUUID def sourceDocument(self, doc_type_id): """ Builds the database model for the source document file reference. """ if self._mode == UPLOAD_MODE: entity_doc_obj = self.document_model() entity_doc_obj.document_identifier = self.fileUUID entity_doc_obj.filename = self.fileInfo.fileName() entity_doc_obj.document_size = self._docSize entity_doc_obj.creation_date = datetime.now() entity_doc_obj.source_entity = self._source_entity entity_doc_obj.document_type = doc_type_id self._srcDoc = entity_doc_obj return self._srcDoc def set_thumbnail(self): """ Sets thumbnail to the document widget by cropping if necessary. :return: None :rtype: NoneType """ extension = self._displayName[self._displayName.rfind('.'):] QApplication.processEvents() doc_path = u'{}/{}/{}/{}/{}{}'.format( source_document_location(), unicode(self.curr_profile.name), unicode(self._source_entity), unicode(self.doc_type_value()).replace(' ', '_'), unicode(self.fileUUID), unicode(extension) ).lower() ph_image = QImage(doc_path) ph_pixmap = QPixmap.fromImage(ph_image) # If width is larger than height, use height as width and height if ph_pixmap.width() > ph_pixmap.height(): rectangle = QRect(0, 0, ph_pixmap.height(), ph_pixmap.height()) ph_pixmap = ph_pixmap.copy(rectangle) # If height is larger than width, use width as width and height elif ph_pixmap.height() > ph_pixmap.width(): rectangle = QRect(0, 0, ph_pixmap.width(), ph_pixmap.width()) ph_pixmap = ph_pixmap.copy(rectangle) self.lblThumbnail.setPixmap(ph_pixmap) self.lblThumbnail.setScaledContents(True) def buildDisplay(self): """ Build html text for displaying file information. """ if not self._docSize is None: display_doc_size = unicode(size(self._docSize)) else: display_doc_size = '0' html = u'<html>' \ '<head/>' \ '<body>' \ '<p>' \ '<span ' \ 'style="font-weight:600;' \ 'text-decoration: underline;' \ 'color:#5555ff;"' \ '>' \ '{}</span>' \ '<span ' \ 'style="font-weight:600;' \ 'color:#8f8f8f;"' \ '> ({})' \ '</span>' \ '</p>' \ '</body>' \ '</html>'.format( unicode(self._displayName), display_doc_size ) self.lblName.setText(html) #Enable/disable close self.setCanRemoveDocument(self._canRemove) #Disable link if no view manager has been configured if self._view_manager is None: self.lblName.setEnabled(False) self.set_thumbnail() def uploadDoc(self): """ Upload the file to the central repository in a separate thread using the specified file manager """ if isinstance(self.fileManager, NetworkFileManager): self.pgBar.setVisible(True) self._docSize = self.fileInfo.size() ''' Create document transfer helper for multi-threading capabilities. Use of queued connections will guarantee that signals and slots are captured in any thread. ''' workerThread = QThread(self) docWorker = DocumentTransferWorker( self.fileManager, self.fileInfo, "%s"%(self._source_entity), "%s"%(self._doc_type), self ) docWorker.moveToThread(workerThread) workerThread.started.connect(docWorker.transfer) docWorker.blockWrite.connect(self.onBlockWritten) docWorker.complete.connect(self.onCompleteTransfer) workerThread.finished.connect(docWorker.deleteLater) workerThread.finished.connect(workerThread.deleteLater) workerThread.start() # Call transfer() to get fileUUID early #docWorker.transfer() self.fileUUID = docWorker.file_uuid def onBlockWritten(self,size): """ Raised when a block of data is written to the central repository. Updates the progress bar with the bytes transferred as a percentage. """ progress = (size * 100)/self._docSize self.pgBar.setValue(progress) QApplication.processEvents() def onCompleteTransfer(self, fileid): """ Slot raised when file has been successfully transferred. """ self.pgBar.setVisible(False) self.fileUUID = str(fileid) self.fileUploadComplete.emit()
''' QGIS Processing script (c) 2017 Andreas Plesch serve html file and show in browser ''' ##X3D=group ##serve_and_open_html=name ##input_html=file ##server_port=number 8000 ##open_in_browser=boolean False ##html_file_name=output string import shutil import webbrowser from PyQt4.QtCore import QUrl, QFileInfo port = int(server_port) html = QFileInfo(input_html) html_file_name = html.fileName() if open_in_browser: root_folder = html.canonicalPath() # kills running web server if necessary processing.runalg('script:launchwebserver', root_folder, port) #url = QUrl.fromLocalFile(output_file).toString() #deal with spaces and such url = QUrl(u'http://localhost:%s/%s' % (port, html_file_name)) #perhaps warn if not ending in html webbrowser.open_new(url.toString())
def importXMLFromFile(self): ''' NO DOCUMENTATION ''' assert self.has_selected_item() # print "importXMLFromFile" # First, prompt the user for the filename to read in start_dir = '' opus_home = os.environ.get('OPUS_HOME') if opus_home: start_dir_test = os.path.join(opus_home, 'project_configs') if start_dir_test: start_dir = start_dir_test configDialog = QFileDialog() filter_str = QString("*.xml") fd = configDialog.getOpenFileName( self.manager.base_widget, "Please select an xml file to import...", start_dir, filter_str) # Check for cancel if len(fd) == 0: return fileName = QString(fd) fileNameInfo = QFileInfo(QString(fd)) fileNameInfoBaseName = fileNameInfo.completeBaseName() fileNameInfoName = fileNameInfo.fileName().trimmed() fileNameInfoPath = fileNameInfo.absolutePath().trimmed() # Pass that in to create a new XMLConfiguration xml_config = XMLConfiguration(str(fileNameInfoName), str(fileNameInfoPath)) xml_node = xml_config.full_tree.getroot() if len(xml_node) == 0: raise ValueError('Loading node from XML file failed. ' 'No node definition found') xml_node = xml_node[0] parent_node = self.selected_item().node allowed_parent_tags = {"tool": ["tool_group"], \ "class_module": ["tool"], \ "path_to_tool_modules": ["tool_library"], \ "tool_library": ["data_manager"], \ "tool_group": ["tool_library"], \ "params": ["tool"], \ "param": ["params"], \ "tool_config": ["tool_set"], \ "tool_set": ["tool_sets"], \ "tool_sets": ["data_manager"]} if parent_node.tag not in allowed_parent_tags[xml_node.tag]: MessageBox.error( mainwindow=self.view, text='Invalid Xml insert', detailed_text= ('Xml insert of node of type "%s" failed. ' 'Invalid type of parent node is "%s" - needs to be one of %s' % (xml_node.tag, parent_node.tag, str(allowed_parent_tags[xml_node.tag])))) return # Insert it into the parent node from where the user clicked name = xml_node.get('name') if xml_node.get('name') is not None else '' if self.model.insertRow(0, self.selected_index(), xml_node) is False: MessageBox.error( mainwindow=self.view, text='Xml Insert Failed', detailed_text= ('Xml insert of node with name "%s" failed - ' 'most likely because there is already a node with that name.' % name)) return
def importXMLFromFile(self): """ NO DOCUMENTATION """ assert self.has_selected_item() # print "importXMLFromFile" # First, prompt the user for the filename to read in start_dir = "" opus_home = os.environ.get("OPUS_HOME") if opus_home: start_dir_test = os.path.join(opus_home, "project_configs") if start_dir_test: start_dir = start_dir_test configDialog = QFileDialog() filter_str = QString("*.xml") fd = configDialog.getOpenFileName( self.manager.base_widget, "Please select an xml file to import...", start_dir, filter_str ) # Check for cancel if len(fd) == 0: return fileName = QString(fd) fileNameInfo = QFileInfo(QString(fd)) fileNameInfoBaseName = fileNameInfo.completeBaseName() fileNameInfoName = fileNameInfo.fileName().trimmed() fileNameInfoPath = fileNameInfo.absolutePath().trimmed() # Pass that in to create a new XMLConfiguration xml_config = XMLConfiguration(str(fileNameInfoName), str(fileNameInfoPath)) xml_node = xml_config.full_tree.getroot() if len(xml_node) == 0: raise ValueError("Loading node from XML file failed. " "No node definition found") xml_node = xml_node[0] parent_node = self.selected_item().node allowed_parent_tags = { "tool": ["tool_group"], "class_module": ["tool"], "path_to_tool_modules": ["tool_library"], "tool_library": ["data_manager"], "tool_group": ["tool_library"], "params": ["tool"], "param": ["params"], "tool_config": ["tool_set"], "tool_set": ["tool_sets"], "tool_sets": ["data_manager"], } if parent_node.tag not in allowed_parent_tags[xml_node.tag]: MessageBox.error( mainwindow=self.view, text="Invalid Xml insert", detailed_text=( 'Xml insert of node of type "%s" failed. ' 'Invalid type of parent node is "%s" - needs to be one of %s' % (xml_node.tag, parent_node.tag, str(allowed_parent_tags[xml_node.tag])) ), ) return # Insert it into the parent node from where the user clicked name = xml_node.get("name") if xml_node.get("name") is not None else "" if self.model.insertRow(0, self.selected_index(), xml_node) is False: MessageBox.error( mainwindow=self.view, text="Xml Insert Failed", detailed_text=( 'Xml insert of node with name "%s" failed - ' "most likely because there is already a node with that name." % name ), ) return
class FileSystemItem(QObject): """ An element in the FileSystemModel. """ iconProvider = QFileIconProvider() fileExtensions = ['*.qlr'] xmlSearchableTags = ['title', 'abstract','layername', 'attribution'] def __init__(self, file, recurse = True, recursion_counter = None, namingregex = None): super(FileSystemItem, self).__init__() # Raise exception if root path has too many child elements if recursion_counter: recursion_counter.increment() if isinstance(file, QFileInfo): self.fileinfo = file else: self.fileinfo = QFileInfo(file) self.fullpath = self.fileinfo.absoluteFilePath() self.basename = self.fileinfo.completeBaseName() self.displayname = self.fileinfo.fileName() if self.fileinfo.isDir() else self.fileinfo.completeBaseName() if namingregex: self.displayname = namingregex.match(self.displayname).group(1) self.icon = FileSystemItem.iconProvider.icon(self.fileinfo) self.isdir = self.fileinfo.isDir() self.children = [] if self.isdir else None if self.isdir and recurse: qdir = QDir(self.fullpath) for finfo in qdir.entryInfoList( FileSystemItem.fileExtensions , QDir.Files | QDir.AllDirs | QDir.NoDotAndDotDot,QDir.Name): self.children.append(FileSystemItem(finfo, recurse, recursion_counter, namingregex)) else: # file # Populate this if and when needed self.searchablecontent = None def filtered(self, filter): """ Filters the root path. :filter is a string. Is it contained in the basename or displayname then this item will be rendered. :return: the directory item. If nothing is found returns None. """ if not filter: return self filterlower = filter.lower() namematch = self.name_matches(filter) if self.isdir: if namematch: # Stop searching. Return this dir and all sub items return FileSystemItem(self.fullpath, True) else: # Only return dir if at least one sub item is a filter match diritem = FileSystemItem(self.fullpath, False) for child in self.children: childmatch = child.filtered(filter) if childmatch is not None: diritem.children.append((childmatch)) if len(diritem.children) > 0: return diritem else: if self.searchablecontent is None: self.searchablecontent = self.get_searchable_content().lower() if namematch or self.content_matches(filter): return FileSystemItem(self.fullpath, False) return None def matches(self, searchterm): """Returns true if this item mathces the searchterm""" return self.name_matches(searchterm) or self.content_matches(searchterm) def name_matches(self, searchterm): """Returns true if the searchterm matches the name of this item""" lowered = searchterm.lower() return lowered in self.basename.lower() or lowered in self.displayname.lower() def content_matches(self, searchterm): """Returns True if the searchterm matches content of this item""" if self.isdir: return False lowered = searchterm.lower() if self.searchablecontent is None: self.searchablecontent = self.get_searchable_content().lower() return lowered in self.searchablecontent def get_searchable_content(self): """ Pulls out tags from the object and returns them in order to be used by the filtered() method. """ f = QFile(self.fileinfo.absoluteFilePath()) f.open(QIODevice.ReadOnly) #stream = QTextStream(f) #stream.setCodec("UTF-8") try: doc = QDomDocument() doc.setContent( f.readAll() ) docelt = doc.documentElement() texts = [] for tagName in FileSystemItem.xmlSearchableTags: nodes = docelt.elementsByTagName(tagName) for i in range(nodes.count()): node = nodes.at(i) value = node.firstChild().toText().data() #print value texts.append( value ) # Add keywords nodes = docelt.elementsByTagName("keywordList") for i in range(nodes.count()): kwnode = nodes.at(i) valnodes = kwnode.toElement().elementsByTagName("value") for j in range(valnodes.count()): value = valnodes.at(j).firstChild().toText().data() texts.append(value) return u' '.join(texts) finally: f.close()
def get_Title(self): fileInfo = QFileInfo(self.fileName) return String.QString2Str(fileInfo.fileName())
class Downloader(QDialog): " MultiThreaded GUI Downloader Dialog " def __init__(self, parent=None, url_to_download=None, fout=None): " init class " super(Downloader, self).__init__(parent) self.timer = time() self.httpGetId = 0 self.httpRequestAborted = False self.url = QUrl(url_to_download) self.fileInfo = QFileInfo(self.url.path()) self.fout = fout self.fileName = path.join(fout, str(self.fileInfo.fileName())) self.statusLabel = QLabel( "<center><h3>Downloading from:</h3>%s<h3>Saving to:</h3>%s</center>" % (url_to_download, fout) ) self.bytes = QLabel(" ??? ") self.closeButton = QPushButton(" Cancel ") self.closeButton.setAutoDefault(False) self.progressBar = QProgressBar() buttonBox = QDialogButtonBox() buttonBox.addButton(self.closeButton, QDialogButtonBox.RejectRole) self.http = QHttp(self) self.http.requestFinished.connect(self.httpRequestFinished) self.http.dataReadProgress.connect(self.updateDataReadProgress) self.http.responseHeaderReceived.connect(self.readResponseHeader) self.closeButton.clicked.connect(self.cancelDownload) mainLayout = QVBoxLayout() mainLayout.addWidget(self.statusLabel) mainLayout.addWidget(self.progressBar) mainLayout.addWidget(self.bytes) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.setWindowTitle(__doc__ + " - MultiThreaded Downloader ") self.resize(parent.size().width(), self.size().height()) self.downloadFile(url_to_download, fout) def downloadFile(self, url_to_download, fout): " get the file from remote url to local folder " url = QUrl(url_to_download) fileInfo = QFileInfo(url.path()) fileName = path.join(fout, str(fileInfo.fileName())) if QFile.exists(fileName): QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): QMessageBox.information( self, "ERROR", "Cant save the file %s: %s." % (fileName, self.outFile.errorString()) ) self.outFile = None return mode = QHttp.ConnectionModeHttp port = url.port() if port == -1: port = 0 self.http.setHost(url.host(), mode, port) self.httpRequestAborted = False tpath = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if tpath: tpath = str(tpath) else: tpath = sep # Download the file. print(" INFO: Blender Download Started ! ") self.httpGetId = self.http.get(tpath, self.outFile) def cancelDownload(self): " abort the download " self.statusLabel.setText(" INFO: Download Canceled ! ") self.httpRequestAborted = True self.http.abort() self.close() def httpRequestFinished(self, requestId, error): " what to do when download is finised " if requestId != self.httpGetId: return if self.httpRequestAborted: if self.outFile is not None: self.outFile.close() self.outFile.remove() self.outFile = None return self.outFile.close() if error: self.outFile.remove() QMessageBox.information(self, "ERROR", "Download Failed: %s." % self.http.errorString()) self.statusLabel.setText(" <center> <h1> ✔ OK! ʘ‿ʘ </h1> <center> ") print(" INFO: Blender Download Finished ! ") if self.fileName.lower().endswith((".tar.gz", ".tgz", ".tar.bz2", ".tbz")): self.extract_file(self.fileName) def readResponseHeader(self, responseHeader): " Check for genuine error conditions " print(" INFO: HTTP Response is " + responseHeader.reasonPhrase()) print(" INFO: HTTP Status Code is " + responseHeader.statusCode()) if responseHeader.statusCode() not in (200, 300, 301, 302, 303, 307): QMessageBox.information(self, "ERROR", "Download Failed: %s." % responseHeader.reasonPhrase()) self.httpRequestAborted = True self.http.abort() def updateDataReadProgress(self, bytesRead, totalBytes): " update the GUI Dialog " if self.httpRequestAborted: return self.progressBar.setMaximum(totalBytes) self.progressBar.setValue(bytesRead) self.bytes.setText(" %s of %s Bytes on %s Minutes " % (bytesRead, totalBytes, int(time() - self.timer) / 60)) def extract_file(self, filepath): " extract the file " tarfile.debug = 3 zipfile.debug = 3 if filepath is None: return elif filepath.endswith(".zip"): opener, mode = zipfile.ZipFile, "r" print((" INFO: Extraction Mode is zipfile.ZipFile " + mode)) elif filepath.endswith(".tar.gz") or filepath.endswith(".tgz"): opener, mode = tarfile.open, "r:gz" print((" INFO: Extraction Mode is tarfile.open " + mode)) elif filepath.endswith(".tar.bz2") or filepath.endswith(".tbz"): opener, mode = tarfile.open, "r:bz2" print((" INFO: Extraction Mode is tarfile.open " + mode)) else: raise ValueError("Could not extract %s " % filepath) cwd = getcwd() chdir(self.fout) try: print((" INFO: Extracting Compressed file " + filepath)) filez = opener(filepath, mode) filez.extractall() filez.close() except: print((" ERROR: Could not extract %s " + filepath)) raise ValueError("Could not extract %s " % filepath) finally: print((" INFO: Finished Extraction of Compressed file " + filepath)) chdir(cwd) print(" INFO: Done. ")
class DocumentWidget(QWidget, Ui_frmDocumentItem): """ Widget for displaying source document details """ # Reference removed signal is raised prior # to destroying the widget. referencesRemoved = pyqtSignal(int) fileUploadComplete = pyqtSignal() def __init__( self, document_model=None, fileManager=None, mode=UPLOAD_MODE, parent=None, canRemove=True, view_manager=None ): QWidget.__init__(self, parent) self.setupUi(self) self.initGui() self.fileInfo = None self.fileUUID = None self.document_model = document_model self.fileManager = fileManager self._mode = mode self._displayName = "" self._docSize = 0 self._srcDoc = None self._fileName = "" self._canRemove = canRemove self._view_manager = view_manager self.curr_profile = current_profile() self.removed_doc = [] self.lblClose.installEventFilter(self) self.lblName.installEventFilter(self) self._source_entity = "" self._doc_type = "" self._doc_type_id = None #Set defaults self.fileNameColor = "#5555ff" self.fileMetaColor = "#8f8f8f" def eventFilter(self,watched,e): """ Capture label mouse release events for deleting and opening a source document respectively. """ if QEvent is None: return False if watched == self.lblClose and e.type() == QEvent.MouseButtonRelease: self.removeDocument() return True elif watched == self.lblName and e.type() == QEvent.MouseButtonRelease: self.openDocument() return True else: return QWidget.eventFilter(self,watched,e) def initGui(self): """ Initialize GUI """ self.lblName.clear() self.pgBar.setVisible(False) self.pgBar.setValue(0) def mode(self): """ Returns the mode that the widget is configured to run. Returns either UPLOAD_MODE or DOWNLOAD_MODE. """ return self._mode def view_manager(self): """ Manager for viewing the document contents. """ return self._view_manager def removeDocument(self): """ Destroy the document widget and removes file references in the network drive and corresponding database record. """ msgConfirm = QApplication.translate("DocumentWidget", """Are you sure you want to delete this document? This action cannot be undone. \nClick Yes to proceed or No to cancel.""") response = QMessageBox.warning(self.parent(), QApplication.translate("DocumentWidget", "Delete Source Document"), msgConfirm, QMessageBox.Yes | QMessageBox.No) if response == QMessageBox.No: return self._remove_doc() def clean_up(self): """ Remove the referenced uploaded file which has not yet been saved. :return: True to indicate that the document was successfully removed or False if an error was encountered. :rtype: bool """ if self._mode == UPLOAD_MODE: return self._remove_doc(True) return True def _remove_doc(self, suppress_messages=False): """ :param suppress_messages: Set whether user messages should be displayed or the system should continue with execution. :type suppress_messages: bool :return: True to indicate that the document was successfully removed or False if an error was encountered. :rtype: bool """ if self._mode == UPLOAD_MODE: status = self.fileManager.deleteDocument() else: doc_type = self.doc_type_value() self.removed_doc.append(self._srcDoc) status = self.fileManager.deleteDocument(self._srcDoc, doc_type) if not status: if not suppress_messages: msg = QApplication.translate("DocumentWidget", "The system could not delete the document. Please " "check your document repository settings.") QMessageBox.critical(self.parent(), QApplication.translate("DocumentWidget", "Delete Source Document"), msg) return False if self._mode == DOWNLOAD_MODE: #Try to delete document and suppress error if it does not exist try: self._srcDoc.delete() # Remove the same document from supporting # doc table linked to other str record as the file doesn't exist. doc_obj = self.document_model() other_party_doc = doc_obj.queryObject().filter( self.document_model.document_identifier == self._srcDoc.document_identifier ).all() for docs in other_party_doc: self.removed_doc.append(docs) docs.delete() except sqlalchemy.exc.SQLAlchemyError as exc: LOGGER.debug(str(exc)) #Emit signal to indicate the widget is ready to be removed self.referencesRemoved.emit(self._doc_type_id) self.deleteLater() return True def openDocument(self): """ Open the document referenced by this widget. """ if not self._view_manager is None: self._view_manager.load_viewer(self) def setCanRemoveDocument(self,state): """ Disable the close button so that users are not able to remove the document from the list. """ self.lblClose.setVisible(state) def setFile(self, dfile, source_entity, doc_type, doc_type_id): """ Set the absolute file path including the name, that is to be associated with the document widget. """ if self._mode == UPLOAD_MODE: self.fileInfo = QFileInfo(dfile) self._displayName = unicode(self.fileInfo.fileName()) self._docSize = self.fileInfo.size() self._source_entity = source_entity self._doc_type = doc_type self._doc_type_id = doc_type_id self.uploadDoc() self.buildDisplay() def setModel(self, sourcedoc): """ Set the SourceDocument model that is to be associated with the widget. Only valid if the widget mode is in DOWNLOAD_MODE. """ self.pgBar.setVisible(False) if self._mode == DOWNLOAD_MODE: self._displayName = sourcedoc.filename self._docSize = sourcedoc.document_size self.fileUUID = sourcedoc.document_identifier self._srcDoc = sourcedoc self._source_entity = sourcedoc.source_entity self._doc_type_id = sourcedoc.document_type self.buildDisplay() def doc_type_value(self): """ Returns the document type value. :return: the document type value in which a document is uploaded. :type: String :rtype: String """ entity = self.curr_profile.entity_by_name(self._source_entity) doc_type_entity = entity.supporting_doc.document_type_entity self._doc_type = entity_id_to_attr( doc_type_entity, 'value', self._doc_type_id ) return self._doc_type def doc_source_entity(self): """ Returns the document type (enumeration) that the widget currently references. """ return self._source_entity def set_source_entity(self, source_entity): """ Set the document type using its code. See enumeration options. """ self._source_entity = source_entity def displayName(self): """ Returns the original file name of the supporting document. """ return self._displayName def file_identifier(self): """ Returns the unique identifier of the file generated by the system upon uploading. """ return self.fileUUID def sourceDocument(self, doc_type_id): """ Builds the database model for the source document file reference. """ if self._mode == UPLOAD_MODE: entity_doc_obj = self.document_model() entity_doc_obj.document_identifier = self.fileUUID entity_doc_obj.filename = self.fileInfo.fileName() entity_doc_obj.document_size = self._docSize entity_doc_obj.creation_date = datetime.now() entity_doc_obj.source_entity = self._source_entity entity_doc_obj.document_type = doc_type_id self._srcDoc = entity_doc_obj return self._srcDoc def set_thumbnail(self): """ Sets thumbnail to the document widget by cropping if necessary. :return: None :rtype: NoneType """ extension = self._displayName[self._displayName.rfind('.'):] QApplication.processEvents() doc_path = u'{}/{}/{}/{}/{}{}'.format( source_document_location(), unicode(self.curr_profile.name), unicode(self._source_entity), unicode(self.doc_type_value()).replace(' ', '_'), unicode(self.fileUUID), unicode(extension) ).lower() ph_image = QImage(doc_path) ph_pixmap = QPixmap.fromImage(ph_image) # If width is larger than height, use height as width and height if ph_pixmap.width() > ph_pixmap.height(): rectangle = QRect(0, 0, ph_pixmap.height(), ph_pixmap.height()) ph_pixmap = ph_pixmap.copy(rectangle) # If height is larger than width, use width as width and height elif ph_pixmap.height() > ph_pixmap.width(): rectangle = QRect(0, 0, ph_pixmap.width(), ph_pixmap.width()) ph_pixmap = ph_pixmap.copy(rectangle) self.lblThumbnail.setPixmap(ph_pixmap) self.lblThumbnail.setScaledContents(True) def buildDisplay(self): """ Build html text for displaying file information. """ if not self._docSize is None: display_doc_size = unicode(size(self._docSize)) else: display_doc_size = '0' html = u'<html>' \ '<head/>' \ '<body>' \ '<p>' \ '<span ' \ 'style="font-weight:600;' \ 'text-decoration: underline;' \ 'color:#5555ff;"' \ '>' \ '{}</span>' \ '<span ' \ 'style="font-weight:600;' \ 'color:#8f8f8f;"' \ '> ({})' \ '</span>' \ '</p>' \ '</body>' \ '</html>'.format( unicode(self._displayName), display_doc_size ) self.lblName.setText(html) #Enable/disable close self.setCanRemoveDocument(self._canRemove) #Disable link if no view manager has been configured if self._view_manager is None: self.lblName.setEnabled(False) self.set_thumbnail() def uploadDoc(self): """ Upload the file to the central repository in a separate thread using the specified file manager """ if isinstance(self.fileManager, NetworkFileManager): self.pgBar.setVisible(True) self._docSize = self.fileInfo.size() ''' Create document transfer helper for multi-threading capabilities. Use of queued connections will guarantee that signals and slots are captured in any thread. ''' workerThread = QThread(self) docWorker = DocumentTransferWorker( self.fileManager, self.fileInfo, "%s"%(self._source_entity), "%s"%(self._doc_type), self ) docWorker.moveToThread(workerThread) workerThread.started.connect(docWorker.transfer) docWorker.blockWrite.connect(self.onBlockWritten) docWorker.complete.connect(self.onCompleteTransfer) workerThread.finished.connect(docWorker.deleteLater) workerThread.finished.connect(workerThread.deleteLater) workerThread.start() # Call transfer() to get fileUUID early #docWorker.transfer() self.fileUUID = docWorker.file_uuid def onBlockWritten(self,size): """ Raised when a block of data is written to the central repository. Updates the progress bar with the bytes transferred as a percentage. """ progress = (size * 100)/self._docSize self.pgBar.setValue(progress) QApplication.processEvents() def onCompleteTransfer(self, fileid): """ Slot raised when file has been successfully transferred. """ self.pgBar.setVisible(False) self.fileUUID = str(fileid) self.fileUploadComplete.emit()
def __init__(self, IMC, parent=None): super(QDialog, self).__init__(parent) self.IMC = IMC self.setModal(True) self.setSizeGripEnabled(True) bookinfo = QFileInfo(IMC.bookPath) self.setWindowTitle(u"Properties of {0}".format(bookinfo.fileName())) # Our layout is a vertical stack of widgets and hboxes vlayout = QVBoxLayout() # Add the path information field fplb = QLabel(u"Path: {0}".format(unicode(bookinfo.path()))) fplb.setFrameStyle(QFrame.Sunken) fplb.setToolTip(QString(u'Full path to document')) vlayout.addWidget(fplb) # Add the write-encoding choice, setting the buttons to reflect # the current value. We build this up from the inside out. # Two radio buttons. As they will be exclusive we need connect # the toggled() signal from only one of them. self.saveEncoding = self.IMC.bookSaveEncoding rb_enc_utf = QRadioButton(QString(u'UTF-8')) rb_enc_utf.setChecked(self.saveEncoding == rb_enc_utf.text()) rb_enc_utf.toggled.connect(self.encodingChange) rb_enc_ltn = QRadioButton(QString(u'Latin-1')) rb_enc_ltn.setChecked(self.saveEncoding != rb_enc_utf.text()) # put the buttons in a layout because groupbox doesn't act as one hb_enc_btns = QHBoxLayout() hb_enc_btns.addWidget(rb_enc_utf) hb_enc_btns.addWidget(rb_enc_ltn) # add to groupbox to get exclusivity on the buttons gb_enc = QGroupBox() gb_enc.setLayout(hb_enc_btns) # put in horizontal box with descriptive label, and add to the dialog hb_enc = QHBoxLayout() lb_enc = QLabel(u'Write Encoding') lb_enc.setToolTip('Character encoding when writing the document') hb_enc.addWidget(lb_enc) hb_enc.addWidget(gb_enc) vlayout.addLayout(hb_enc) # Next get a QStringList of available dicts from pqSpell # and create a combobox with that content. dictlist = IMC.spellCheck.dictList() dictlist.sort() self.maintag = self.IMC.bookMainDict if self.maintag.isEmpty(): self.maintag = self.IMC.spellCheck.mainTag current = dictlist.indexOf(QString( self.maintag)) # index of current dict or -1 self.cb_dic = QComboBox() self.cb_dic.addItems(dictlist) if current >= 0: self.cb_dic.setCurrentIndex(current) self.cb_dic.activated.connect(self.dictChange) hb_dic = QHBoxLayout() hb_dic.addWidget(QLabel(u'Main Dictionary')) hb_dic.addStretch() hb_dic.addWidget(self.cb_dic) vlayout.addLayout(hb_dic) # create the [ apply cancel ] buttons, but apply == accept apply_button = QPushButton("Apply") cancel_button = QPushButton("Cancel") cancel_button.setDefault(True) bbox = QDialogButtonBox() bbox.addButton(cancel_button, QDialogButtonBox.RejectRole) bbox.addButton(apply_button, QDialogButtonBox.AcceptRole) bbox.accepted.connect(self.applyButtonHit) bbox.rejected.connect(self.cancelButtonHit) vlayout.addWidget(bbox) self.setLayout(vlayout)