예제 #1
0
 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
예제 #2
0
 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")
예제 #3
0
    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)
예제 #4
0
    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)
예제 #5
0
 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
예제 #6
0
 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())
예제 #7
0
파일: loader.py 프로젝트: jschloer/keyplus
 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)
예제 #8
0
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
예제 #9
0
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
예제 #10
0
 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("")
예제 #11
0
 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
예제 #12
0
    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")
예제 #13
0
파일: loader.py 프로젝트: hineybush/keyplus
    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))
예제 #14
0
    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)
예제 #15
0
    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)
예제 #16
0
    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
예제 #17
0
    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)
예제 #18
0
    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)
예제 #19
0
 def __fileNameWoExt(self):
     image = QFileInfo(self.directory + QDir.separator() + self.filename)
     return image.absoluteDir().absolutePath() + QDir.separator() + image.baseName()
예제 #20
0
 def testBasic(self):
     '''QFileInfo(QFile)'''
     obj = QFileInfo(QFile())
예제 #21
0
파일: skpaths.py 프로젝트: Rougnt/VNR-Core
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""
예제 #22
0
파일: Info.py 프로젝트: ra2003/xindex
    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{}>{}&nbsp;&nbsp;</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))