def read(self, fileName): self.state = PluginState.Invalid self.hasError = False self.dependencies = [] specFile = QFile(fileName) if not specFile.exists(): msg = QCoreApplication.translate(None, "File does not exist: {name}") return self.__reportError(msg.format(name=specFile.fileName())) if not specFile.open(QIODevice.ReadOnly): msg = QCoreApplication.translate(None, "Could not open file for read: {name}") return self.__reportError(msg.format(name=specFile.fileName())) fileInfo = QFileInfo(specFile) self.location = fileInfo.absolutePath() self.filePath = fileInfo.absoluteFilePath() reader = QXmlStreamReader(specFile) while not reader.atEnd(): reader.readNext() tokenType = reader.tokenType() if tokenType is QXmlStreamReader.StartElement: self.__readPluginSpec(reader) else: pass if reader.hasError(): msg = QCoreApplication.translate(None, "Error parsing file {0}: {1}, at line {2}, column {3}") return self.__reportError(msg.format(specFile.fileName(), reader.errorString(), reader.lineNumber(), reader.columnNumber())) self.state = PluginState.Read return True
def add(self): """ Agrega un nuevo animal """ common = self.ui.common_name.toPlainText() if common == "": self.ui.msgBox = QtGui.QMessageBox.information(self, u'Error', u"Debe ingresar al menos el nombre común") else: cientific = self.ui.cientific_name.toPlainText() other = self.ui.data.toPlainText() tipo = self.ui.typeBox.currentText() id_type = controller_form.get_id_type(tipo) result = controller_form.add_animal(common, cientific, other, id_type) path = self.ui.image.toPlainText() if path != "": id_animal = controller_form.get_id_animal(common) shutil.copy(path,(self.directory.currentPath()+"/images/")) Ifile = QFileInfo(path) controller_form.add_image_dir(id_animal,Ifile.fileName()) else: noimage = controller_form.no_image() item = QGraphicsPixmapItem(noimage.scaled(100,100)) self.scene = QGraphicsScene() self.ui.graphicsView.setSceneRect(0,0,100,100) self.ui.graphicsView.setScene(self.scene) self.scene.addItem(item) if result: self.reject() else: self.ui.msgBox = QtGui.QMessageBox.information(self, u'Error', u"Hubo un problema al intentar agregar el animal")
def updateFileMenu(self): """ Updates the file menu dynamically, so that recent files can be shown. """ self.menuFile.clear() # self.menuFile.addAction(self.actionNew) # disable for now self.menuFile.addAction(self.actionOpen) self.menuFile.addAction(self.actionSave) self.menuFile.addAction(self.actionSave_as) self.menuFile.addAction(self.actionClose_Model) recentFiles = [] for filename in self.recentFiles: if QFile.exists(filename): recentFiles.append(filename) if len(self.recentFiles) > 0: self.menuFile.addSeparator() for i, filename in enumerate(recentFiles): action = QAction("&%d %s" % (i + 1, QFileInfo(filename).fileName()), self) action.setData(filename) action.setStatusTip("Opens recent file %s" % QFileInfo(filename).fileName()) action.setShortcut(QKeySequence(Qt.CTRL | (Qt.Key_1+i))) action.triggered.connect(self.load_model) #self.connect(action, SIGNAL("triggered()"), self.load_model) self.menuFile.addAction(action) self.menuFile.addSeparator() self.menuFile.addAction(self.actionQuit)
def render(self, fileName, width, height): self.setViewportSize(QSize(width, height)) fileInfo = QFileInfo(fileName) dir = QDir() dir.mkpath(fileInfo.absolutePath()) viewportSize = self.viewportSize() pageSize = self.mainFrame().contentsSize() if pageSize.isEmpty(): return False buffer = QImage(pageSize, QImage.Format_ARGB32) buffer.fill(qRgba(255, 255, 255, 0)) p = QPainter(buffer) p.setRenderHint( QPainter.Antialiasing, True) p.setRenderHint( QPainter.TextAntialiasing, True) p.setRenderHint( QPainter.SmoothPixmapTransform, True) self.setViewportSize(pageSize) self.mainFrame().render(p) p.end() self.setViewportSize(viewportSize) return buffer.save(fileName)
def serializedArguments(self): seperator = "|" rc = "" for spec in self.plugins(): if spec.arguments(): if rc: rc += seperator rc += ":" rc += spec.name() rc += seperator rc += spec.arguments() + seperator if self.private.arguments: if rc: rc += seperator rc += ARGUMENT_KEYWORD # If the argument appears to be a file, make it absolute # when sending to another instance for argument in self.private.arguments: rc += seperator fi = QFileInfo(argument) if fi.exists() and fi.isRelative(): rc += fi.absoluteFilePath() else: rc += argument return rc
def setTitle(self,fullPath): traceLogger.debug("fullPath=%s" % fullPath) if fullPath is '': self.setWindowTitle("[*]" + self.tr("Untitled")) else: info = QFileInfo(fullPath) self.setWindowFilePath(info.absolutePath()) self.setWindowTitle("[*]" + info.fileName())
def grabFileName(self): result = QFileDialog.getOpenFileName( self, "Open file", FileBrowseWidget.lastDirectory, self.fileTypeName) fname = result[0] if fname != '': fileInfo = QFileInfo(fname) try: FileBrowseWidget.lastDir = fileInfo.baseName() except: pass self.lineEdit.setText(fname)
def toQFileInfo(p): if not p or isinstance(p, QFileInfo): fileInfo = p else: fileInfo = QFileInfo(p) if fileInfo and fileInfo.isRelative(): raise ValueError("Given path is relative: '{}'".format(fileInfo.filePath())) return fileInfo
def toQFileInfo(p): if (not p) or isinstance(p, QFileInfo): fileInfo = p else: fileInfo = QFileInfo(p) if fileInfo and fileInfo.isRelative(): raise ValueError("Given path is relative: '{}'".format( fileInfo.filePath())) return fileInfo
def delete(self): """ Borra la imagen del animal cuando se preciona quitar """ path = self.ui.image.toPlainText() Ifile = QFileInfo(path) success = controller_form.del_image(Ifile.fileName()) if not success: self.ui.errorMessageDialog = QtGui.QMessageBox.information(self, 'Error', u"Dirección incorrecta", QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok) self.ui.image.setPlainText("")
def get_file_name(self, url): path = url.path() basename = QFileInfo(path).fileName() if not basename: basename = "download" if QFile.exists(basename): print "aaaaaaaaaaaaaaaah" return return basename
def edit(self): """ Modifica un animal que se encuentre en la base de datos """ id_animal = controller_form.get_id_animal(self.common) common = self.ui.common_name.toPlainText() if common == "": self.ui.msgBox = QtGui.QMessageBox.information(self, u'Error', u"El nombre común no puede estar en blanco") else: cientific = self.ui.cientific_name.toPlainText() other = self.ui.data.toPlainText() tipo = self.ui.typeBox.currentText() id_type = controller_form.get_id_type(tipo) path = self.ui.image.toPlainText() result = controller_form.edit_animal(id_animal,common,cientific,other,id_type) if path != "": pixImage = controller_form.get_root_image(path) item = QGraphicsPixmapItem(pixImage.scaled(100,100)) scene = QGraphicsScene() scene.addItem(item) self.display.setScene(scene) self.ui.image.setPlainText(path) Ifile = QFileInfo(path) if controller_form.search_image(id_animal,Ifile.fileName()): controller_form.add_image_dir(id_animal,Ifile.fileName()) result = True else: result = False else: noimage = controller_form.no_image() item = QGraphicsPixmapItem(noimage.scaled(100,100)) scene = QGraphicsScene() scene.addItem(item) self.display.setScene(scene) self.ui.image.setPlainText(path) if result: self.reject() else: self.ui.msgBox = QtGui.QMessageBox.information(self, u'Error', u"Hubo un problema al intentar editar el animal, intentelo de nuevo")
def generateRFSettings(self): result = QFileDialog.getSaveFileName(self, "Save file", FileBrowseWidget.lastDirectory, "RF settings .yaml (*.yaml)") fname = result[0] if fname != '': fileInfo = QFileInfo(fname) try: FileBrowseWidget.lastDir = fileInfo.baseName() except: pass try: rf_settings = layout.parser.RFSettings.from_rand() timeNow = datetime.datetime.now().strftime("%Y-%M-%d at %H:%M") with open(fname, 'w') as outFile: outFile.write("# Generated on {}\n".format(timeNow) + rf_settings.to_yaml()) self.rfSettingsFile.lineEdit.setText(fname) except IOError as e: # TODO: proper error message print("error writing file: " + str(e))
def on_modelClosed(self, modelController): if not modelController: return filename = QFileInfo(modelController.filename).fileName() if self._modelIndexes.has_key(filename): index = self._modelIndexes[filename] item = self._modelListWidget.takeItem(index) del item self._models.pop(filename) # remove the model self._modelIndexes.pop(filename) if self._modelListWidget.count() > 0: self._modelListWidget.item(0).setSelected(True)
def on_activeModelChanged(self, modelController): if not modelController: self._modelListWidget.setCurrentIndex(None) # deselect all return filename = QFileInfo(modelController.filename).fileName() if self._modelIndexes.has_key(filename): # known model, just select it self._modelListWidget.item(self._modelIndexes[filename]).setSelected(True) else: # new model, add it to the list # truncatedFilename = QFileInfo(filename).fileName() self._modelListWidget.addItem(filename) self._models[filename] = modelController index = self._modelListWidget.count() - 1 self._modelIndexes[filename] = index self._modelListWidget.item(index).setSelected(True)
def data(self, index, role): '''Return data for *index* according to *role*.''' if not index.isValid(): return None column = index.column() item = index.internalPointer() if role == self.ITEM_ROLE: return item elif role == Qt.DisplayRole: if column == 0: return item.name elif column == 1: if item.size: return item.size elif column == 2: return item.type elif column == 3: if item.modified is not None: return item.modified.strftime('%c') elif role == Qt.DecorationRole: if column == 0: icon = self.iconFactory.icon(QFileInfo(item.path)) if icon is None or icon.isNull(): if isinstance(item, Directory): icon = QIcon(':icon_folder') elif isinstance(item, Mount): icon = QIcon(':icon_drive') elif isinstance(item, Collection): icon = QIcon(':icon_collection') else: icon = QIcon(':icon_file') return icon elif role == Qt.TextAlignmentRole: if column == 1: return Qt.AlignRight else: return Qt.AlignLeft return None
def downloadFile(self, path, setting): self.progress_text = 'Downloading {}'.format(path.replace(self.base_url.format(self.selected_version()),'')) url = QUrl(path) fileInfo = QFileInfo(url.path()) fileName = setting.save_file_path(self.selected_version()) archive_exists = QFile.exists(fileName) dest_files_exist = True for dest_file in setting.dest_files: dest_file_path = os.path.join('files', setting.name, dest_file) dest_files_exist &= QFile.exists(dest_file_path) forced = self.getSetting('force_download').value if (archive_exists or dest_files_exist) and not forced: self.continueDownloadingOrExtract() return #QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): self.show_error('Unable to save the file {}: {}.'.format(fileName, self.outFile.errorString())) self.outFile = None self.enableUI() 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)
def __init__(self, res): QWidget.__init__(self) self.res = res layout = QVBoxLayout() self.setLayout(layout) preview = QLabel() if 'image' in res.mime: pixmap = QPixmap(res.file_path).scaledToWidth(32) else: info = QFileInfo(res.file_path) pixmap = QFileIconProvider().icon(info).pixmap(32, 32) preview.setPixmap(pixmap) preview.setMask(pixmap.mask()) preview.setMaximumHeight(32) label = QLabel() label.setText(res.file_name) layout.addWidget(preview) layout.addWidget(label) layout.setAlignment(Qt.AlignHCenter) self.setFixedWidth(64) self.setFixedHeight(64)
def __fileNameWoExt(self): image = QFileInfo(self.directory + QDir.separator() + self.filename) return image.absoluteDir().absolutePath() + QDir.separator() + image.baseName()
def testBasic(self): '''QFileInfo(QFile)''' obj = QFileInfo(QFile())
def abspath(path): """As a replacement of os.path.abspath, which has encoding issue for unicode path @param path unicode or str @return unicode """ return QFileInfo(path).absoluteFilePath() if path else u""
def initialize(self): locale = QLocale() model = self.state.model if not bool(model): self.browser.setHtml("<font color=red>Information can only " "be shown if an index is open</font>") return top, total, _ = self.state.indicatorCounts() fullname = QDir.toNativeSeparators(os.path.abspath(model.filename)) creator = model.config(Gconf.Key.Creator) created = model.config("Created") created = locale.toString( QDateTime.fromString(created, "yyyy-MM-dd HH:mm:ss")) updated = locale.toString(QFileInfo(model.filename).lastModified()) size = os.path.getsize(model.filename) KB = 1024 MB = KB * KB if size < MB: size = "~{:,} KB ({:,} bytes)".format(round(size / KB), size) else: size = "~{:,} MB ({:,} bytes)".format(round(size / MB), size) filename = re.sub(r"\.xix$", "", os.path.basename(fullname), re.IGNORECASE) version = str(model.version()) secs = self.state.workTime + int(time.monotonic() - self.state.startTime) hours, secs = divmod(secs, 3600) if hours: worktime = "{:,}h{}'".format(hours, secs // 60) else: worktime = "{}'".format(secs // 60) uuid = model.config(UUID) LEFT_STYLE = """ style=" margin-right: 0; padding-right: 0; spacing-right: 0; border-right: 0; " """ RIGHT_STYLE = """ style=" margin-left: 0; padding-left: 0; spacing-left: 0; border-left: 0; " """ color1 = "#DDDDFF" color2 = "#EEEEFF" STYLE = ' style="background-color: {};"' texts = [ """<html><table border=0 style=" background-color: {}; ">""".format(color1) ] for i, (name, value, right, debug) in enumerate(( ("Index", filename, False, False), ("Creator", creator, False, False), ("Filename", fullname, False, False), ("Size", size, False, False), ("Created", created, False, False), ("Updated", updated, False, False), ("Total Entries", "{:,}".format(total), True, False), ("Main Entries", "{:,}".format(top), True, False), ("Subentries", "{:,}".format(total - top), True, False), ("Worktime", worktime, True, False), (None, None, False, False), ("Index Format", version, True, False), ("Index UUID", uuid, True, True), )): if debug and not self.state.window.debug: continue if name is None: color1 = "#EEEEEE" color2 = "#DDDDDD" continue style = STYLE.format(color1 if i % 2 == 0 else color2) align = " align=right" if right else "" texts.append("""<tr{}><td{}>{} </td> <td{}{}>{}</td></tr>""".format(style, LEFT_STYLE, html.escape(name), align, RIGHT_STYLE, html.escape(value))) texts.append("</table></html>") self.browser.setHtml("".join(texts))